babylon.max.js 3.1 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560
  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, mimeType) {
  4924. if (mimeType === void 0) { mimeType = "image/png"; }
  4925. // Read the contents of the framebuffer
  4926. var numberOfChannelsByLine = width * 4;
  4927. var halfHeight = height / 2;
  4928. //Reading datas from WebGL
  4929. var data = engine.readPixels(0, 0, width, height);
  4930. //To flip image on Y axis.
  4931. for (var i = 0; i < halfHeight; i++) {
  4932. for (var j = 0; j < numberOfChannelsByLine; j++) {
  4933. var currentCell = j + i * numberOfChannelsByLine;
  4934. var targetLine = height - i - 1;
  4935. var targetCell = j + targetLine * numberOfChannelsByLine;
  4936. var temp = data[currentCell];
  4937. data[currentCell] = data[targetCell];
  4938. data[targetCell] = temp;
  4939. }
  4940. }
  4941. // Create a 2D canvas to store the result
  4942. if (!screenshotCanvas) {
  4943. screenshotCanvas = document.createElement('canvas');
  4944. }
  4945. screenshotCanvas.width = width;
  4946. screenshotCanvas.height = height;
  4947. var context = screenshotCanvas.getContext('2d');
  4948. // Copy the pixels to a 2D canvas
  4949. var imageData = context.createImageData(width, height);
  4950. //cast is due to ts error in lib.d.ts, see here - https://github.com/Microsoft/TypeScript/issues/949
  4951. var castData = imageData.data;
  4952. castData.set(data);
  4953. context.putImageData(imageData, 0, 0);
  4954. var base64Image = screenshotCanvas.toDataURL(mimeType);
  4955. if (successCallback) {
  4956. successCallback(base64Image);
  4957. }
  4958. else {
  4959. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  4960. if (("download" in document.createElement("a"))) {
  4961. var a = window.document.createElement("a");
  4962. a.href = base64Image;
  4963. var date = new Date();
  4964. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  4965. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  4966. window.document.body.appendChild(a);
  4967. a.addEventListener("click", function () {
  4968. a.parentElement.removeChild(a);
  4969. });
  4970. a.click();
  4971. }
  4972. else {
  4973. var newWindow = window.open("");
  4974. var img = newWindow.document.createElement("img");
  4975. img.src = base64Image;
  4976. newWindow.document.body.appendChild(img);
  4977. }
  4978. }
  4979. };
  4980. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  4981. if (mimeType === void 0) { mimeType = "image/png"; }
  4982. var width;
  4983. var height;
  4984. //If a precision value is specified
  4985. if (size.precision) {
  4986. width = Math.round(engine.getRenderWidth() * size.precision);
  4987. height = Math.round(width / engine.getAspectRatio(camera));
  4988. size = { width: width, height: height };
  4989. }
  4990. else if (size.width && size.height) {
  4991. width = size.width;
  4992. height = size.height;
  4993. }
  4994. else if (size.width && !size.height) {
  4995. width = size.width;
  4996. height = Math.round(width / engine.getAspectRatio(camera));
  4997. size = { width: width, height: height };
  4998. }
  4999. else if (size.height && !size.width) {
  5000. height = size.height;
  5001. width = Math.round(height * engine.getAspectRatio(camera));
  5002. size = { width: width, height: height };
  5003. }
  5004. else if (!isNaN(size)) {
  5005. height = size;
  5006. width = size;
  5007. }
  5008. else {
  5009. Tools.Error("Invalid 'size' parameter !");
  5010. return;
  5011. }
  5012. var scene = camera.getScene();
  5013. var previousCamera = null;
  5014. if (scene.activeCamera !== camera) {
  5015. previousCamera = scene.activeCamera;
  5016. scene.activeCamera = camera;
  5017. }
  5018. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  5019. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false);
  5020. texture.renderList = scene.meshes;
  5021. texture.onAfterRenderObservable.add(function () {
  5022. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType);
  5023. });
  5024. scene.incrementRenderId();
  5025. scene.resetCachedMaterial();
  5026. texture.render(true);
  5027. texture.dispose();
  5028. if (previousCamera) {
  5029. scene.activeCamera = previousCamera;
  5030. }
  5031. camera.getProjectionMatrix(true); // Force cache refresh;
  5032. };
  5033. // XHR response validator for local file scenario
  5034. Tools.ValidateXHRData = function (xhr, dataType) {
  5035. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  5036. if (dataType === void 0) { dataType = 7; }
  5037. try {
  5038. if (dataType & 1) {
  5039. if (xhr.responseText && xhr.responseText.length > 0) {
  5040. return true;
  5041. }
  5042. else if (dataType === 1) {
  5043. return false;
  5044. }
  5045. }
  5046. if (dataType & 2) {
  5047. // Check header width and height since there is no "TGA" magic number
  5048. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  5049. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  5050. return true;
  5051. }
  5052. else if (dataType === 2) {
  5053. return false;
  5054. }
  5055. }
  5056. if (dataType & 4) {
  5057. // Check for the "DDS" magic number
  5058. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  5059. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  5060. return true;
  5061. }
  5062. else {
  5063. return false;
  5064. }
  5065. }
  5066. }
  5067. catch (e) {
  5068. }
  5069. return false;
  5070. };
  5071. Object.defineProperty(Tools, "NoneLogLevel", {
  5072. get: function () {
  5073. return Tools._NoneLogLevel;
  5074. },
  5075. enumerable: true,
  5076. configurable: true
  5077. });
  5078. Object.defineProperty(Tools, "MessageLogLevel", {
  5079. get: function () {
  5080. return Tools._MessageLogLevel;
  5081. },
  5082. enumerable: true,
  5083. configurable: true
  5084. });
  5085. Object.defineProperty(Tools, "WarningLogLevel", {
  5086. get: function () {
  5087. return Tools._WarningLogLevel;
  5088. },
  5089. enumerable: true,
  5090. configurable: true
  5091. });
  5092. Object.defineProperty(Tools, "ErrorLogLevel", {
  5093. get: function () {
  5094. return Tools._ErrorLogLevel;
  5095. },
  5096. enumerable: true,
  5097. configurable: true
  5098. });
  5099. Object.defineProperty(Tools, "AllLogLevel", {
  5100. get: function () {
  5101. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  5102. },
  5103. enumerable: true,
  5104. configurable: true
  5105. });
  5106. Tools._AddLogEntry = function (entry) {
  5107. Tools._LogCache = entry + Tools._LogCache;
  5108. if (Tools.OnNewCacheEntry) {
  5109. Tools.OnNewCacheEntry(entry);
  5110. }
  5111. };
  5112. Tools._FormatMessage = function (message) {
  5113. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  5114. var date = new Date();
  5115. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  5116. };
  5117. Tools._LogDisabled = function (message) {
  5118. // nothing to do
  5119. };
  5120. Tools._LogEnabled = function (message) {
  5121. var formattedMessage = Tools._FormatMessage(message);
  5122. console.log("BJS - " + formattedMessage);
  5123. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  5124. Tools._AddLogEntry(entry);
  5125. };
  5126. Tools._WarnDisabled = function (message) {
  5127. // nothing to do
  5128. };
  5129. Tools._WarnEnabled = function (message) {
  5130. var formattedMessage = Tools._FormatMessage(message);
  5131. console.warn("BJS - " + formattedMessage);
  5132. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  5133. Tools._AddLogEntry(entry);
  5134. };
  5135. Tools._ErrorDisabled = function (message) {
  5136. // nothing to do
  5137. };
  5138. Tools._ErrorEnabled = function (message) {
  5139. Tools.errorsCount++;
  5140. var formattedMessage = Tools._FormatMessage(message);
  5141. console.error("BJS - " + formattedMessage);
  5142. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  5143. Tools._AddLogEntry(entry);
  5144. };
  5145. Object.defineProperty(Tools, "LogCache", {
  5146. get: function () {
  5147. return Tools._LogCache;
  5148. },
  5149. enumerable: true,
  5150. configurable: true
  5151. });
  5152. Tools.ClearLogCache = function () {
  5153. Tools._LogCache = "";
  5154. Tools.errorsCount = 0;
  5155. };
  5156. Object.defineProperty(Tools, "LogLevels", {
  5157. set: function (level) {
  5158. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  5159. Tools.Log = Tools._LogEnabled;
  5160. }
  5161. else {
  5162. Tools.Log = Tools._LogDisabled;
  5163. }
  5164. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  5165. Tools.Warn = Tools._WarnEnabled;
  5166. }
  5167. else {
  5168. Tools.Warn = Tools._WarnDisabled;
  5169. }
  5170. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  5171. Tools.Error = Tools._ErrorEnabled;
  5172. }
  5173. else {
  5174. Tools.Error = Tools._ErrorDisabled;
  5175. }
  5176. },
  5177. enumerable: true,
  5178. configurable: true
  5179. });
  5180. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  5181. get: function () {
  5182. return Tools._PerformanceNoneLogLevel;
  5183. },
  5184. enumerable: true,
  5185. configurable: true
  5186. });
  5187. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  5188. get: function () {
  5189. return Tools._PerformanceUserMarkLogLevel;
  5190. },
  5191. enumerable: true,
  5192. configurable: true
  5193. });
  5194. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  5195. get: function () {
  5196. return Tools._PerformanceConsoleLogLevel;
  5197. },
  5198. enumerable: true,
  5199. configurable: true
  5200. });
  5201. Object.defineProperty(Tools, "PerformanceLogLevel", {
  5202. set: function (level) {
  5203. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  5204. Tools.StartPerformanceCounter = Tools._StartUserMark;
  5205. Tools.EndPerformanceCounter = Tools._EndUserMark;
  5206. return;
  5207. }
  5208. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  5209. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  5210. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  5211. return;
  5212. }
  5213. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  5214. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  5215. },
  5216. enumerable: true,
  5217. configurable: true
  5218. });
  5219. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  5220. };
  5221. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  5222. };
  5223. Tools._StartUserMark = function (counterName, condition) {
  5224. if (condition === void 0) { condition = true; }
  5225. if (!condition || !Tools._performance.mark) {
  5226. return;
  5227. }
  5228. Tools._performance.mark(counterName + "-Begin");
  5229. };
  5230. Tools._EndUserMark = function (counterName, condition) {
  5231. if (condition === void 0) { condition = true; }
  5232. if (!condition || !Tools._performance.mark) {
  5233. return;
  5234. }
  5235. Tools._performance.mark(counterName + "-End");
  5236. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  5237. };
  5238. Tools._StartPerformanceConsole = function (counterName, condition) {
  5239. if (condition === void 0) { condition = true; }
  5240. if (!condition) {
  5241. return;
  5242. }
  5243. Tools._StartUserMark(counterName, condition);
  5244. if (console.time) {
  5245. console.time(counterName);
  5246. }
  5247. };
  5248. Tools._EndPerformanceConsole = function (counterName, condition) {
  5249. if (condition === void 0) { condition = true; }
  5250. if (!condition) {
  5251. return;
  5252. }
  5253. Tools._EndUserMark(counterName, condition);
  5254. if (console.time) {
  5255. console.timeEnd(counterName);
  5256. }
  5257. };
  5258. Object.defineProperty(Tools, "Now", {
  5259. get: function () {
  5260. if (window.performance && window.performance.now) {
  5261. return window.performance.now();
  5262. }
  5263. return new Date().getTime();
  5264. },
  5265. enumerable: true,
  5266. configurable: true
  5267. });
  5268. /**
  5269. * This method will return the name of the class used to create the instance of the given object.
  5270. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  5271. * @param object the object to get the class name from
  5272. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  5273. */
  5274. Tools.getClassName = function (object, isType) {
  5275. if (isType === void 0) { isType = false; }
  5276. var name = null;
  5277. if (!isType && object.getClassName) {
  5278. name = object.getClassName();
  5279. }
  5280. else {
  5281. if (object instanceof Object) {
  5282. var classObj = isType ? object : Object.getPrototypeOf(object);
  5283. name = classObj.constructor["__bjsclassName__"];
  5284. }
  5285. if (!name) {
  5286. name = typeof object;
  5287. }
  5288. }
  5289. return name;
  5290. };
  5291. Tools.first = function (array, predicate) {
  5292. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  5293. var el = array_1[_i];
  5294. if (predicate(el)) {
  5295. return el;
  5296. }
  5297. }
  5298. };
  5299. /**
  5300. * 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.
  5301. * @param array
  5302. */
  5303. Tools.arrayOrStringFeeder = function (array) {
  5304. return function (index) {
  5305. if (index >= array.length) {
  5306. return null;
  5307. }
  5308. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  5309. if (val && val.getHashCode) {
  5310. val = val.getHashCode();
  5311. }
  5312. if (typeof val === "string") {
  5313. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  5314. }
  5315. return val;
  5316. };
  5317. };
  5318. /**
  5319. * Compute the hashCode of a stream of number
  5320. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  5321. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  5322. * @return the hash code computed
  5323. */
  5324. Tools.hashCodeFromStream = function (feeder) {
  5325. // Based from here: http://stackoverflow.com/a/7616484/802124
  5326. var hash = 0;
  5327. var index = 0;
  5328. var chr = feeder(index++);
  5329. while (chr != null) {
  5330. hash = ((hash << 5) - hash) + chr;
  5331. hash |= 0; // Convert to 32bit integer
  5332. chr = feeder(index++);
  5333. }
  5334. return hash;
  5335. };
  5336. Tools.BaseUrl = "";
  5337. Tools.CorsBehavior = "anonymous";
  5338. Tools.UseFallbackTexture = true;
  5339. // Logs
  5340. Tools._NoneLogLevel = 0;
  5341. Tools._MessageLogLevel = 1;
  5342. Tools._WarningLogLevel = 2;
  5343. Tools._ErrorLogLevel = 4;
  5344. Tools._LogCache = "";
  5345. Tools.errorsCount = 0;
  5346. Tools.Log = Tools._LogEnabled;
  5347. Tools.Warn = Tools._WarnEnabled;
  5348. Tools.Error = Tools._ErrorEnabled;
  5349. // Performances
  5350. Tools._PerformanceNoneLogLevel = 0;
  5351. Tools._PerformanceUserMarkLogLevel = 1;
  5352. Tools._PerformanceConsoleLogLevel = 2;
  5353. Tools._performance = window.performance;
  5354. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  5355. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  5356. return Tools;
  5357. }());
  5358. BABYLON.Tools = Tools;
  5359. /**
  5360. * This class is used to track a performance counter which is number based.
  5361. * The user has access to many properties which give statistics of different nature
  5362. *
  5363. * The implementer can track two kinds of Performance Counter: time and count
  5364. * 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.
  5365. * 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.
  5366. */
  5367. var PerfCounter = (function () {
  5368. function PerfCounter() {
  5369. this._startMonitoringTime = 0;
  5370. this._min = 0;
  5371. this._max = 0;
  5372. this._average = 0;
  5373. this._lastSecAverage = 0;
  5374. this._current = 0;
  5375. this._totalValueCount = 0;
  5376. this._totalAccumulated = 0;
  5377. this._lastSecAccumulated = 0;
  5378. this._lastSecTime = 0;
  5379. this._lastSecValueCount = 0;
  5380. }
  5381. Object.defineProperty(PerfCounter.prototype, "min", {
  5382. /**
  5383. * Returns the smallest value ever
  5384. */
  5385. get: function () {
  5386. return this._min;
  5387. },
  5388. enumerable: true,
  5389. configurable: true
  5390. });
  5391. Object.defineProperty(PerfCounter.prototype, "max", {
  5392. /**
  5393. * Returns the biggest value ever
  5394. */
  5395. get: function () {
  5396. return this._max;
  5397. },
  5398. enumerable: true,
  5399. configurable: true
  5400. });
  5401. Object.defineProperty(PerfCounter.prototype, "average", {
  5402. /**
  5403. * Returns the average value since the performance counter is running
  5404. */
  5405. get: function () {
  5406. return this._average;
  5407. },
  5408. enumerable: true,
  5409. configurable: true
  5410. });
  5411. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  5412. /**
  5413. * Returns the average value of the last second the counter was monitored
  5414. */
  5415. get: function () {
  5416. return this._lastSecAverage;
  5417. },
  5418. enumerable: true,
  5419. configurable: true
  5420. });
  5421. Object.defineProperty(PerfCounter.prototype, "current", {
  5422. /**
  5423. * Returns the current value
  5424. */
  5425. get: function () {
  5426. return this._current;
  5427. },
  5428. enumerable: true,
  5429. configurable: true
  5430. });
  5431. Object.defineProperty(PerfCounter.prototype, "total", {
  5432. get: function () {
  5433. return this._totalAccumulated;
  5434. },
  5435. enumerable: true,
  5436. configurable: true
  5437. });
  5438. /**
  5439. * Call this method to start monitoring a new frame.
  5440. * 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.
  5441. */
  5442. PerfCounter.prototype.fetchNewFrame = function () {
  5443. this._totalValueCount++;
  5444. this._current = 0;
  5445. this._lastSecValueCount++;
  5446. };
  5447. /**
  5448. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  5449. * @param newCount the count value to add to the monitored count
  5450. * @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.
  5451. */
  5452. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  5453. this._current += newCount;
  5454. if (fetchResult) {
  5455. this._fetchResult();
  5456. }
  5457. };
  5458. /**
  5459. * Start monitoring this performance counter
  5460. */
  5461. PerfCounter.prototype.beginMonitoring = function () {
  5462. this._startMonitoringTime = Tools.Now;
  5463. };
  5464. /**
  5465. * Compute the time lapsed since the previous beginMonitoring() call.
  5466. * @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
  5467. */
  5468. PerfCounter.prototype.endMonitoring = function (newFrame) {
  5469. if (newFrame === void 0) { newFrame = true; }
  5470. if (newFrame) {
  5471. this.fetchNewFrame();
  5472. }
  5473. var currentTime = Tools.Now;
  5474. this._current = currentTime - this._startMonitoringTime;
  5475. if (newFrame) {
  5476. this._fetchResult();
  5477. }
  5478. };
  5479. PerfCounter.prototype._fetchResult = function () {
  5480. this._totalAccumulated += this._current;
  5481. this._lastSecAccumulated += this._current;
  5482. // Min/Max update
  5483. this._min = Math.min(this._min, this._current);
  5484. this._max = Math.max(this._max, this._current);
  5485. this._average = this._totalAccumulated / this._totalValueCount;
  5486. // Reset last sec?
  5487. var now = Tools.Now;
  5488. if ((now - this._lastSecTime) > 1000) {
  5489. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  5490. this._lastSecTime = now;
  5491. this._lastSecAccumulated = 0;
  5492. this._lastSecValueCount = 0;
  5493. }
  5494. };
  5495. return PerfCounter;
  5496. }());
  5497. BABYLON.PerfCounter = PerfCounter;
  5498. /**
  5499. * Use this className as a decorator on a given class definition to add it a name.
  5500. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  5501. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  5502. * @param name
  5503. */
  5504. function className(name) {
  5505. return function (target) {
  5506. target["__bjsclassName__"] = name;
  5507. };
  5508. }
  5509. BABYLON.className = className;
  5510. /**
  5511. * An implementation of a loop for asynchronous functions.
  5512. */
  5513. var AsyncLoop = (function () {
  5514. /**
  5515. * Constroctor.
  5516. * @param iterations the number of iterations.
  5517. * @param _fn the function to run each iteration
  5518. * @param _successCallback the callback that will be called upon succesful execution
  5519. * @param offset starting offset.
  5520. */
  5521. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  5522. if (offset === void 0) { offset = 0; }
  5523. this.iterations = iterations;
  5524. this._fn = _fn;
  5525. this._successCallback = _successCallback;
  5526. this.index = offset - 1;
  5527. this._done = false;
  5528. }
  5529. /**
  5530. * Execute the next iteration. Must be called after the last iteration was finished.
  5531. */
  5532. AsyncLoop.prototype.executeNext = function () {
  5533. if (!this._done) {
  5534. if (this.index + 1 < this.iterations) {
  5535. ++this.index;
  5536. this._fn(this);
  5537. }
  5538. else {
  5539. this.breakLoop();
  5540. }
  5541. }
  5542. };
  5543. /**
  5544. * Break the loop and run the success callback.
  5545. */
  5546. AsyncLoop.prototype.breakLoop = function () {
  5547. this._done = true;
  5548. this._successCallback();
  5549. };
  5550. /**
  5551. * Helper function
  5552. */
  5553. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  5554. if (offset === void 0) { offset = 0; }
  5555. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  5556. loop.executeNext();
  5557. return loop;
  5558. };
  5559. /**
  5560. * A for-loop that will run a given number of iterations synchronous and the rest async.
  5561. * @param iterations total number of iterations
  5562. * @param syncedIterations number of synchronous iterations in each async iteration.
  5563. * @param fn the function to call each iteration.
  5564. * @param callback a success call back that will be called when iterating stops.
  5565. * @param breakFunction a break condition (optional)
  5566. * @param timeout timeout settings for the setTimeout function. default - 0.
  5567. * @constructor
  5568. */
  5569. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  5570. if (timeout === void 0) { timeout = 0; }
  5571. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  5572. if (breakFunction && breakFunction())
  5573. loop.breakLoop();
  5574. else {
  5575. setTimeout(function () {
  5576. for (var i = 0; i < syncedIterations; ++i) {
  5577. var iteration = (loop.index * syncedIterations) + i;
  5578. if (iteration >= iterations)
  5579. break;
  5580. fn(iteration);
  5581. if (breakFunction && breakFunction()) {
  5582. loop.breakLoop();
  5583. break;
  5584. }
  5585. }
  5586. loop.executeNext();
  5587. }, timeout);
  5588. }
  5589. }, callback);
  5590. };
  5591. return AsyncLoop;
  5592. }());
  5593. BABYLON.AsyncLoop = AsyncLoop;
  5594. })(BABYLON || (BABYLON = {}));
  5595. var BABYLON;
  5596. (function (BABYLON) {
  5597. var Internals;
  5598. (function (Internals) {
  5599. var _AlphaState = (function () {
  5600. function _AlphaState() {
  5601. this._isAlphaBlendDirty = false;
  5602. this._isBlendFunctionParametersDirty = false;
  5603. this._alphaBlend = false;
  5604. this._blendFunctionParameters = new Array(4);
  5605. }
  5606. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  5607. get: function () {
  5608. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  5609. },
  5610. enumerable: true,
  5611. configurable: true
  5612. });
  5613. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  5614. get: function () {
  5615. return this._alphaBlend;
  5616. },
  5617. set: function (value) {
  5618. if (this._alphaBlend === value) {
  5619. return;
  5620. }
  5621. this._alphaBlend = value;
  5622. this._isAlphaBlendDirty = true;
  5623. },
  5624. enumerable: true,
  5625. configurable: true
  5626. });
  5627. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  5628. if (this._blendFunctionParameters[0] === value0 &&
  5629. this._blendFunctionParameters[1] === value1 &&
  5630. this._blendFunctionParameters[2] === value2 &&
  5631. this._blendFunctionParameters[3] === value3) {
  5632. return;
  5633. }
  5634. this._blendFunctionParameters[0] = value0;
  5635. this._blendFunctionParameters[1] = value1;
  5636. this._blendFunctionParameters[2] = value2;
  5637. this._blendFunctionParameters[3] = value3;
  5638. this._isBlendFunctionParametersDirty = true;
  5639. };
  5640. _AlphaState.prototype.reset = function () {
  5641. this._alphaBlend = false;
  5642. this._blendFunctionParameters[0] = null;
  5643. this._blendFunctionParameters[1] = null;
  5644. this._blendFunctionParameters[2] = null;
  5645. this._blendFunctionParameters[3] = null;
  5646. this._isAlphaBlendDirty = true;
  5647. this._isBlendFunctionParametersDirty = false;
  5648. };
  5649. _AlphaState.prototype.apply = function (gl) {
  5650. if (!this.isDirty) {
  5651. return;
  5652. }
  5653. // Alpha blend
  5654. if (this._isAlphaBlendDirty) {
  5655. if (this._alphaBlend) {
  5656. gl.enable(gl.BLEND);
  5657. }
  5658. else {
  5659. gl.disable(gl.BLEND);
  5660. }
  5661. this._isAlphaBlendDirty = false;
  5662. }
  5663. // Alpha function
  5664. if (this._isBlendFunctionParametersDirty) {
  5665. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  5666. this._isBlendFunctionParametersDirty = false;
  5667. }
  5668. };
  5669. return _AlphaState;
  5670. }());
  5671. Internals._AlphaState = _AlphaState;
  5672. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  5673. })(BABYLON || (BABYLON = {}));
  5674. var BABYLON;
  5675. (function (BABYLON) {
  5676. var Internals;
  5677. (function (Internals) {
  5678. var _DepthCullingState = (function () {
  5679. function _DepthCullingState() {
  5680. this._isDepthTestDirty = false;
  5681. this._isDepthMaskDirty = false;
  5682. this._isDepthFuncDirty = false;
  5683. this._isCullFaceDirty = false;
  5684. this._isCullDirty = false;
  5685. this._isZOffsetDirty = false;
  5686. }
  5687. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  5688. get: function () {
  5689. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  5690. },
  5691. enumerable: true,
  5692. configurable: true
  5693. });
  5694. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  5695. get: function () {
  5696. return this._zOffset;
  5697. },
  5698. set: function (value) {
  5699. if (this._zOffset === value) {
  5700. return;
  5701. }
  5702. this._zOffset = value;
  5703. this._isZOffsetDirty = true;
  5704. },
  5705. enumerable: true,
  5706. configurable: true
  5707. });
  5708. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  5709. get: function () {
  5710. return this._cullFace;
  5711. },
  5712. set: function (value) {
  5713. if (this._cullFace === value) {
  5714. return;
  5715. }
  5716. this._cullFace = value;
  5717. this._isCullFaceDirty = true;
  5718. },
  5719. enumerable: true,
  5720. configurable: true
  5721. });
  5722. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  5723. get: function () {
  5724. return this._cull;
  5725. },
  5726. set: function (value) {
  5727. if (this._cull === value) {
  5728. return;
  5729. }
  5730. this._cull = value;
  5731. this._isCullDirty = true;
  5732. },
  5733. enumerable: true,
  5734. configurable: true
  5735. });
  5736. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  5737. get: function () {
  5738. return this._depthFunc;
  5739. },
  5740. set: function (value) {
  5741. if (this._depthFunc === value) {
  5742. return;
  5743. }
  5744. this._depthFunc = value;
  5745. this._isDepthFuncDirty = true;
  5746. },
  5747. enumerable: true,
  5748. configurable: true
  5749. });
  5750. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  5751. get: function () {
  5752. return this._depthMask;
  5753. },
  5754. set: function (value) {
  5755. if (this._depthMask === value) {
  5756. return;
  5757. }
  5758. this._depthMask = value;
  5759. this._isDepthMaskDirty = true;
  5760. },
  5761. enumerable: true,
  5762. configurable: true
  5763. });
  5764. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  5765. get: function () {
  5766. return this._depthTest;
  5767. },
  5768. set: function (value) {
  5769. if (this._depthTest === value) {
  5770. return;
  5771. }
  5772. this._depthTest = value;
  5773. this._isDepthTestDirty = true;
  5774. },
  5775. enumerable: true,
  5776. configurable: true
  5777. });
  5778. _DepthCullingState.prototype.reset = function () {
  5779. this._depthMask = true;
  5780. this._depthTest = true;
  5781. this._depthFunc = null;
  5782. this._cullFace = null;
  5783. this._cull = null;
  5784. this._zOffset = 0;
  5785. this._isDepthTestDirty = true;
  5786. this._isDepthMaskDirty = true;
  5787. this._isDepthFuncDirty = false;
  5788. this._isCullFaceDirty = false;
  5789. this._isCullDirty = false;
  5790. this._isZOffsetDirty = false;
  5791. };
  5792. _DepthCullingState.prototype.apply = function (gl) {
  5793. if (!this.isDirty) {
  5794. return;
  5795. }
  5796. // Cull
  5797. if (this._isCullDirty) {
  5798. if (this.cull) {
  5799. gl.enable(gl.CULL_FACE);
  5800. }
  5801. else {
  5802. gl.disable(gl.CULL_FACE);
  5803. }
  5804. this._isCullDirty = false;
  5805. }
  5806. // Cull face
  5807. if (this._isCullFaceDirty) {
  5808. gl.cullFace(this.cullFace);
  5809. this._isCullFaceDirty = false;
  5810. }
  5811. // Depth mask
  5812. if (this._isDepthMaskDirty) {
  5813. gl.depthMask(this.depthMask);
  5814. this._isDepthMaskDirty = false;
  5815. }
  5816. // Depth test
  5817. if (this._isDepthTestDirty) {
  5818. if (this.depthTest) {
  5819. gl.enable(gl.DEPTH_TEST);
  5820. }
  5821. else {
  5822. gl.disable(gl.DEPTH_TEST);
  5823. }
  5824. this._isDepthTestDirty = false;
  5825. }
  5826. // Depth func
  5827. if (this._isDepthFuncDirty) {
  5828. gl.depthFunc(this.depthFunc);
  5829. this._isDepthFuncDirty = false;
  5830. }
  5831. // zOffset
  5832. if (this._isZOffsetDirty) {
  5833. if (this.zOffset) {
  5834. gl.enable(gl.POLYGON_OFFSET_FILL);
  5835. gl.polygonOffset(this.zOffset, 0);
  5836. }
  5837. else {
  5838. gl.disable(gl.POLYGON_OFFSET_FILL);
  5839. }
  5840. this._isZOffsetDirty = false;
  5841. }
  5842. };
  5843. return _DepthCullingState;
  5844. }());
  5845. Internals._DepthCullingState = _DepthCullingState;
  5846. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  5847. })(BABYLON || (BABYLON = {}));
  5848. var BABYLON;
  5849. (function (BABYLON) {
  5850. var compileShader = function (gl, source, type, defines) {
  5851. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  5852. gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
  5853. gl.compileShader(shader);
  5854. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  5855. throw new Error(gl.getShaderInfoLog(shader));
  5856. }
  5857. return shader;
  5858. };
  5859. var HALF_FLOAT_OES = 0x8D61;
  5860. var getWebGLTextureType = function (gl, type) {
  5861. if (type === Engine.TEXTURETYPE_FLOAT) {
  5862. return gl.FLOAT;
  5863. }
  5864. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  5865. // Add Half Float Constant.
  5866. return HALF_FLOAT_OES;
  5867. }
  5868. return gl.UNSIGNED_BYTE;
  5869. };
  5870. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  5871. var magFilter = gl.NEAREST;
  5872. var minFilter = gl.NEAREST;
  5873. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  5874. magFilter = gl.LINEAR;
  5875. if (generateMipMaps) {
  5876. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  5877. }
  5878. else {
  5879. minFilter = gl.LINEAR;
  5880. }
  5881. }
  5882. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  5883. magFilter = gl.LINEAR;
  5884. if (generateMipMaps) {
  5885. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  5886. }
  5887. else {
  5888. minFilter = gl.LINEAR;
  5889. }
  5890. }
  5891. else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  5892. magFilter = gl.NEAREST;
  5893. if (generateMipMaps) {
  5894. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  5895. }
  5896. else {
  5897. minFilter = gl.NEAREST;
  5898. }
  5899. }
  5900. return {
  5901. min: minFilter,
  5902. mag: magFilter
  5903. };
  5904. };
  5905. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, onLoad, samplingMode) {
  5906. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  5907. var engine = scene.getEngine();
  5908. var potWidth = BABYLON.Tools.GetExponentOfTwo(width, engine.getCaps().maxTextureSize);
  5909. var potHeight = BABYLON.Tools.GetExponentOfTwo(height, engine.getCaps().maxTextureSize);
  5910. engine._bindTextureDirectly(gl.TEXTURE_2D, texture);
  5911. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  5912. texture._baseWidth = width;
  5913. texture._baseHeight = height;
  5914. texture._width = potWidth;
  5915. texture._height = potHeight;
  5916. texture.isReady = true;
  5917. processFunction(potWidth, potHeight);
  5918. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  5919. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  5920. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  5921. if (!noMipmap && !isCompressed) {
  5922. gl.generateMipmap(gl.TEXTURE_2D);
  5923. }
  5924. engine._bindTextureDirectly(gl.TEXTURE_2D, null);
  5925. engine.resetTextureCache();
  5926. scene._removePendingData(texture);
  5927. if (onLoad) {
  5928. onLoad();
  5929. }
  5930. };
  5931. var partialLoad = function (url, index, loadedImages, scene, onfinish) {
  5932. var img;
  5933. var onload = function () {
  5934. loadedImages[index] = img;
  5935. loadedImages._internalCount++;
  5936. scene._removePendingData(img);
  5937. if (loadedImages._internalCount === 6) {
  5938. onfinish(loadedImages);
  5939. }
  5940. };
  5941. var onerror = function () {
  5942. scene._removePendingData(img);
  5943. };
  5944. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  5945. scene._addPendingData(img);
  5946. };
  5947. var cascadeLoad = function (rootUrl, scene, onfinish, files) {
  5948. var loadedImages = [];
  5949. loadedImages._internalCount = 0;
  5950. for (var index = 0; index < 6; index++) {
  5951. partialLoad(files[index], index, loadedImages, scene, onfinish);
  5952. }
  5953. };
  5954. var InstancingAttributeInfo = (function () {
  5955. function InstancingAttributeInfo() {
  5956. }
  5957. return InstancingAttributeInfo;
  5958. }());
  5959. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  5960. var EngineCapabilities = (function () {
  5961. function EngineCapabilities() {
  5962. }
  5963. return EngineCapabilities;
  5964. }());
  5965. BABYLON.EngineCapabilities = EngineCapabilities;
  5966. /**
  5967. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  5968. */
  5969. var Engine = (function () {
  5970. /**
  5971. * @constructor
  5972. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  5973. * @param {boolean} [antialias] - enable antialias
  5974. * @param options - further options to be sent to the getContext function
  5975. */
  5976. function Engine(canvas, antialias, options, adaptToDeviceRatio) {
  5977. var _this = this;
  5978. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = true; }
  5979. // Public members
  5980. this.isFullscreen = false;
  5981. this.isPointerLock = false;
  5982. this.cullBackFaces = true;
  5983. this.renderEvenInBackground = true;
  5984. // To enable/disable IDB support and avoid XHR on .manifest
  5985. this.enableOfflineSupport = true;
  5986. this.scenes = new Array();
  5987. this._windowIsBackground = false;
  5988. this._webGLVersion = "1.0";
  5989. this._drawCalls = new BABYLON.PerfCounter();
  5990. this._renderingQueueLaunched = false;
  5991. this._activeRenderLoops = [];
  5992. // FPS
  5993. this.fpsRange = 60;
  5994. this.previousFramesDuration = [];
  5995. this.fps = 60;
  5996. this.deltaTime = 0;
  5997. // States
  5998. this._depthCullingState = new BABYLON.Internals._DepthCullingState();
  5999. this._alphaState = new BABYLON.Internals._AlphaState();
  6000. this._alphaMode = Engine.ALPHA_DISABLE;
  6001. // Cache
  6002. this._loadedTexturesCache = new Array();
  6003. this._maxTextureChannels = 16;
  6004. this._activeTexturesCache = new Array(this._maxTextureChannels);
  6005. this._compiledEffects = {};
  6006. this._uintIndicesCurrentlySet = false;
  6007. this._currentBoundBuffer = new Array();
  6008. this._currentBufferPointers = [];
  6009. this._currentInstanceLocations = new Array();
  6010. this._currentInstanceBuffers = new Array();
  6011. this._renderingCanvas = canvas;
  6012. this._externalData = new BABYLON.StringDictionary();
  6013. options = options || {};
  6014. if (antialias != null) {
  6015. options.antialias = antialias;
  6016. }
  6017. if (options.preserveDrawingBuffer === undefined) {
  6018. options.preserveDrawingBuffer = false;
  6019. }
  6020. // Checks if some of the format renders first to allow the use of webgl inspector.
  6021. var renderToFullFloat = this._canRenderToFloatTexture();
  6022. var renderToHalfFloat = this._canRenderToHalfFloatTexture();
  6023. // GL
  6024. //try {
  6025. // this._gl = <WebGLRenderingContext>(canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  6026. // if (this._gl) {
  6027. // this._webGLVersion = "2.0";
  6028. // }
  6029. //} catch (e) {
  6030. // // Do nothing
  6031. //}
  6032. if (!this._gl) {
  6033. try {
  6034. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  6035. }
  6036. catch (e) {
  6037. throw new Error("WebGL not supported");
  6038. }
  6039. }
  6040. if (!this._gl) {
  6041. throw new Error("WebGL not supported");
  6042. }
  6043. this._onBlur = function () {
  6044. _this._windowIsBackground = true;
  6045. };
  6046. this._onFocus = function () {
  6047. _this._windowIsBackground = false;
  6048. };
  6049. window.addEventListener("blur", this._onBlur);
  6050. window.addEventListener("focus", this._onFocus);
  6051. // Viewport
  6052. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  6053. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  6054. this.resize();
  6055. // Caps
  6056. this._caps = new EngineCapabilities();
  6057. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  6058. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  6059. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  6060. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  6061. // Infos
  6062. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  6063. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  6064. if (rendererInfo != null) {
  6065. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  6066. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  6067. }
  6068. if (!this._glVendor) {
  6069. this._glVendor = "Unknown vendor";
  6070. }
  6071. if (!this._glRenderer) {
  6072. this._glRenderer = "Unknown renderer";
  6073. }
  6074. // Extensions
  6075. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  6076. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  6077. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  6078. 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');
  6079. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  6080. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  6081. this._caps.uintIndices = this._gl.getExtension('OES_element_index_uint') !== null;
  6082. this._caps.fragmentDepthSupported = this._gl.getExtension('EXT_frag_depth') !== null;
  6083. this._caps.highPrecisionShaderSupported = true;
  6084. this._caps.drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  6085. this._caps.textureFloatLinearFiltering = this._gl.getExtension('OES_texture_float_linear');
  6086. this._caps.textureLOD = this._gl.getExtension('EXT_shader_texture_lod');
  6087. this._caps.textureFloatRender = renderToFullFloat;
  6088. this._caps.textureHalfFloat = (this._gl.getExtension('OES_texture_half_float') !== null);
  6089. this._caps.textureHalfFloatLinearFiltering = this._gl.getExtension('OES_texture_half_float_linear');
  6090. this._caps.textureHalfFloatRender = renderToHalfFloat;
  6091. if (this._gl.getShaderPrecisionFormat) {
  6092. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  6093. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  6094. }
  6095. // Depth buffer
  6096. this.setDepthBuffer(true);
  6097. this.setDepthFunctionToLessOrEqual();
  6098. this.setDepthWrite(true);
  6099. // Fullscreen
  6100. this._onFullscreenChange = function () {
  6101. if (document.fullscreen !== undefined) {
  6102. _this.isFullscreen = document.fullscreen;
  6103. }
  6104. else if (document.mozFullScreen !== undefined) {
  6105. _this.isFullscreen = document.mozFullScreen;
  6106. }
  6107. else if (document.webkitIsFullScreen !== undefined) {
  6108. _this.isFullscreen = document.webkitIsFullScreen;
  6109. }
  6110. else if (document.msIsFullScreen !== undefined) {
  6111. _this.isFullscreen = document.msIsFullScreen;
  6112. }
  6113. // Pointer lock
  6114. if (_this.isFullscreen && _this._pointerLockRequested) {
  6115. canvas.requestPointerLock = canvas.requestPointerLock ||
  6116. canvas.msRequestPointerLock ||
  6117. canvas.mozRequestPointerLock ||
  6118. canvas.webkitRequestPointerLock;
  6119. if (canvas.requestPointerLock) {
  6120. canvas.requestPointerLock();
  6121. }
  6122. }
  6123. };
  6124. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  6125. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  6126. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  6127. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  6128. // Pointer lock
  6129. this._onPointerLockChange = function () {
  6130. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  6131. document.webkitPointerLockElement === canvas ||
  6132. document.msPointerLockElement === canvas ||
  6133. document.pointerLockElement === canvas);
  6134. };
  6135. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  6136. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  6137. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  6138. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  6139. if (BABYLON.AudioEngine && !Engine.audioEngine) {
  6140. Engine.audioEngine = new BABYLON.AudioEngine();
  6141. }
  6142. //default loading screen
  6143. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  6144. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  6145. }
  6146. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  6147. get: function () {
  6148. return Engine._ALPHA_DISABLE;
  6149. },
  6150. enumerable: true,
  6151. configurable: true
  6152. });
  6153. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  6154. get: function () {
  6155. return Engine._ALPHA_ONEONE;
  6156. },
  6157. enumerable: true,
  6158. configurable: true
  6159. });
  6160. Object.defineProperty(Engine, "ALPHA_ADD", {
  6161. get: function () {
  6162. return Engine._ALPHA_ADD;
  6163. },
  6164. enumerable: true,
  6165. configurable: true
  6166. });
  6167. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  6168. get: function () {
  6169. return Engine._ALPHA_COMBINE;
  6170. },
  6171. enumerable: true,
  6172. configurable: true
  6173. });
  6174. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  6175. get: function () {
  6176. return Engine._ALPHA_SUBTRACT;
  6177. },
  6178. enumerable: true,
  6179. configurable: true
  6180. });
  6181. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  6182. get: function () {
  6183. return Engine._ALPHA_MULTIPLY;
  6184. },
  6185. enumerable: true,
  6186. configurable: true
  6187. });
  6188. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  6189. get: function () {
  6190. return Engine._ALPHA_MAXIMIZED;
  6191. },
  6192. enumerable: true,
  6193. configurable: true
  6194. });
  6195. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  6196. get: function () {
  6197. return Engine._DELAYLOADSTATE_NONE;
  6198. },
  6199. enumerable: true,
  6200. configurable: true
  6201. });
  6202. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  6203. get: function () {
  6204. return Engine._DELAYLOADSTATE_LOADED;
  6205. },
  6206. enumerable: true,
  6207. configurable: true
  6208. });
  6209. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  6210. get: function () {
  6211. return Engine._DELAYLOADSTATE_LOADING;
  6212. },
  6213. enumerable: true,
  6214. configurable: true
  6215. });
  6216. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  6217. get: function () {
  6218. return Engine._DELAYLOADSTATE_NOTLOADED;
  6219. },
  6220. enumerable: true,
  6221. configurable: true
  6222. });
  6223. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  6224. get: function () {
  6225. return Engine._TEXTUREFORMAT_ALPHA;
  6226. },
  6227. enumerable: true,
  6228. configurable: true
  6229. });
  6230. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  6231. get: function () {
  6232. return Engine._TEXTUREFORMAT_LUMINANCE;
  6233. },
  6234. enumerable: true,
  6235. configurable: true
  6236. });
  6237. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  6238. get: function () {
  6239. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  6240. },
  6241. enumerable: true,
  6242. configurable: true
  6243. });
  6244. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  6245. get: function () {
  6246. return Engine._TEXTUREFORMAT_RGB;
  6247. },
  6248. enumerable: true,
  6249. configurable: true
  6250. });
  6251. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  6252. get: function () {
  6253. return Engine._TEXTUREFORMAT_RGBA;
  6254. },
  6255. enumerable: true,
  6256. configurable: true
  6257. });
  6258. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  6259. get: function () {
  6260. return Engine._TEXTURETYPE_UNSIGNED_INT;
  6261. },
  6262. enumerable: true,
  6263. configurable: true
  6264. });
  6265. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  6266. get: function () {
  6267. return Engine._TEXTURETYPE_FLOAT;
  6268. },
  6269. enumerable: true,
  6270. configurable: true
  6271. });
  6272. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  6273. get: function () {
  6274. return Engine._TEXTURETYPE_HALF_FLOAT;
  6275. },
  6276. enumerable: true,
  6277. configurable: true
  6278. });
  6279. Object.defineProperty(Engine, "Version", {
  6280. get: function () {
  6281. return "2.5-alpha";
  6282. },
  6283. enumerable: true,
  6284. configurable: true
  6285. });
  6286. Object.defineProperty(Engine.prototype, "webGLVersion", {
  6287. get: function () {
  6288. return this._webGLVersion;
  6289. },
  6290. enumerable: true,
  6291. configurable: true
  6292. });
  6293. Engine.prototype._prepareWorkingCanvas = function () {
  6294. if (this._workingCanvas) {
  6295. return;
  6296. }
  6297. this._workingCanvas = document.createElement("canvas");
  6298. this._workingContext = this._workingCanvas.getContext("2d");
  6299. };
  6300. Engine.prototype.resetTextureCache = function () {
  6301. for (var index = 0; index < this._maxTextureChannels; index++) {
  6302. this._activeTexturesCache[index] = null;
  6303. }
  6304. };
  6305. Engine.prototype.getGlInfo = function () {
  6306. return {
  6307. vendor: this._glVendor,
  6308. renderer: this._glRenderer,
  6309. version: this._glVersion
  6310. };
  6311. };
  6312. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  6313. if (useScreen === void 0) { useScreen = false; }
  6314. var viewport = camera.viewport;
  6315. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  6316. };
  6317. Engine.prototype.getRenderWidth = function (useScreen) {
  6318. if (useScreen === void 0) { useScreen = false; }
  6319. if (!useScreen && this._currentRenderTarget) {
  6320. return this._currentRenderTarget._width;
  6321. }
  6322. return this._renderingCanvas.width;
  6323. };
  6324. Engine.prototype.getRenderHeight = function (useScreen) {
  6325. if (useScreen === void 0) { useScreen = false; }
  6326. if (!useScreen && this._currentRenderTarget) {
  6327. return this._currentRenderTarget._height;
  6328. }
  6329. return this._renderingCanvas.height;
  6330. };
  6331. Engine.prototype.getRenderingCanvas = function () {
  6332. return this._renderingCanvas;
  6333. };
  6334. Engine.prototype.getRenderingCanvasClientRect = function () {
  6335. return this._renderingCanvas.getBoundingClientRect();
  6336. };
  6337. Engine.prototype.setHardwareScalingLevel = function (level) {
  6338. this._hardwareScalingLevel = level;
  6339. this.resize();
  6340. };
  6341. Engine.prototype.getHardwareScalingLevel = function () {
  6342. return this._hardwareScalingLevel;
  6343. };
  6344. Engine.prototype.getLoadedTexturesCache = function () {
  6345. return this._loadedTexturesCache;
  6346. };
  6347. Engine.prototype.getCaps = function () {
  6348. return this._caps;
  6349. };
  6350. Object.defineProperty(Engine.prototype, "drawCalls", {
  6351. get: function () {
  6352. return this._drawCalls.current;
  6353. },
  6354. enumerable: true,
  6355. configurable: true
  6356. });
  6357. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  6358. get: function () {
  6359. return this._drawCalls;
  6360. },
  6361. enumerable: true,
  6362. configurable: true
  6363. });
  6364. Engine.prototype.getDepthFunction = function () {
  6365. return this._depthCullingState.depthFunc;
  6366. };
  6367. Engine.prototype.setDepthFunction = function (depthFunc) {
  6368. this._depthCullingState.depthFunc = depthFunc;
  6369. };
  6370. Engine.prototype.setDepthFunctionToGreater = function () {
  6371. this._depthCullingState.depthFunc = this._gl.GREATER;
  6372. };
  6373. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  6374. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  6375. };
  6376. Engine.prototype.setDepthFunctionToLess = function () {
  6377. this._depthCullingState.depthFunc = this._gl.LESS;
  6378. };
  6379. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  6380. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  6381. };
  6382. /**
  6383. * stop executing a render loop function and remove it from the execution array
  6384. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  6385. */
  6386. Engine.prototype.stopRenderLoop = function (renderFunction) {
  6387. if (!renderFunction) {
  6388. this._activeRenderLoops = [];
  6389. return;
  6390. }
  6391. var index = this._activeRenderLoops.indexOf(renderFunction);
  6392. if (index >= 0) {
  6393. this._activeRenderLoops.splice(index, 1);
  6394. }
  6395. };
  6396. Engine.prototype._renderLoop = function () {
  6397. var shouldRender = true;
  6398. if (!this.renderEvenInBackground && this._windowIsBackground) {
  6399. shouldRender = false;
  6400. }
  6401. if (shouldRender) {
  6402. // Start new frame
  6403. this.beginFrame();
  6404. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  6405. var renderFunction = this._activeRenderLoops[index];
  6406. renderFunction();
  6407. }
  6408. // Present
  6409. this.endFrame();
  6410. }
  6411. if (this._activeRenderLoops.length > 0) {
  6412. // Register new frame
  6413. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  6414. }
  6415. else {
  6416. this._renderingQueueLaunched = false;
  6417. }
  6418. };
  6419. /**
  6420. * Register and execute a render loop. The engine can have more than one render function.
  6421. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  6422. * @example
  6423. * engine.runRenderLoop(function () {
  6424. * scene.render()
  6425. * })
  6426. */
  6427. Engine.prototype.runRenderLoop = function (renderFunction) {
  6428. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  6429. return;
  6430. }
  6431. this._activeRenderLoops.push(renderFunction);
  6432. if (!this._renderingQueueLaunched) {
  6433. this._renderingQueueLaunched = true;
  6434. this._bindedRenderFunction = this._renderLoop.bind(this);
  6435. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  6436. }
  6437. };
  6438. /**
  6439. * Toggle full screen mode.
  6440. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  6441. * @param {any} options - an options object to be sent to the requestFullscreen function
  6442. */
  6443. Engine.prototype.switchFullscreen = function (requestPointerLock, options) {
  6444. if (this.isFullscreen) {
  6445. BABYLON.Tools.ExitFullscreen();
  6446. }
  6447. else {
  6448. this._pointerLockRequested = requestPointerLock;
  6449. BABYLON.Tools.RequestFullscreen(this._renderingCanvas, options);
  6450. }
  6451. };
  6452. Engine.prototype.clear = function (color, backBuffer, depthStencil) {
  6453. this.applyStates();
  6454. if (backBuffer) {
  6455. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  6456. }
  6457. if (depthStencil && this._depthCullingState.depthMask) {
  6458. this._gl.clearDepth(1.0);
  6459. }
  6460. var mode = 0;
  6461. if (backBuffer) {
  6462. mode |= this._gl.COLOR_BUFFER_BIT;
  6463. }
  6464. if (depthStencil && this._depthCullingState.depthMask) {
  6465. mode |= this._gl.DEPTH_BUFFER_BIT;
  6466. }
  6467. this._gl.clear(mode);
  6468. };
  6469. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  6470. var gl = this._gl;
  6471. // Save state
  6472. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  6473. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  6474. // Change state
  6475. gl.enable(gl.SCISSOR_TEST);
  6476. gl.scissor(x, y, width, height);
  6477. // Clear
  6478. this.clear(clearColor, true, true);
  6479. // Restore state
  6480. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  6481. if (curScissor === true) {
  6482. gl.enable(gl.SCISSOR_TEST);
  6483. }
  6484. else {
  6485. gl.disable(gl.SCISSOR_TEST);
  6486. }
  6487. };
  6488. /**
  6489. * Set the WebGL's viewport
  6490. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  6491. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  6492. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  6493. */
  6494. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  6495. var width = requiredWidth || (navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.width);
  6496. var height = requiredHeight || (navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.height);
  6497. var x = viewport.x || 0;
  6498. var y = viewport.y || 0;
  6499. this._cachedViewport = viewport;
  6500. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  6501. };
  6502. /**
  6503. * Directly set the WebGL Viewport
  6504. * The x, y, width & height are directly passed to the WebGL call
  6505. * @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.
  6506. */
  6507. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  6508. var currentViewport = this._cachedViewport;
  6509. this._cachedViewport = null;
  6510. this._gl.viewport(x, y, width, height);
  6511. return currentViewport;
  6512. };
  6513. Engine.prototype.beginFrame = function () {
  6514. this._measureFps();
  6515. };
  6516. Engine.prototype.endFrame = function () {
  6517. //this.flushFramebuffer();
  6518. };
  6519. /**
  6520. * resize the view according to the canvas' size.
  6521. * @example
  6522. * window.addEventListener("resize", function () {
  6523. * engine.resize();
  6524. * });
  6525. */
  6526. Engine.prototype.resize = function () {
  6527. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  6528. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  6529. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  6530. for (var index = 0; index < this.scenes.length; index++) {
  6531. var scene = this.scenes[index];
  6532. if (scene.debugLayer.isVisible()) {
  6533. scene.debugLayer._syncPositions();
  6534. }
  6535. }
  6536. };
  6537. /**
  6538. * force a specific size of the canvas
  6539. * @param {number} width - the new canvas' width
  6540. * @param {number} height - the new canvas' height
  6541. */
  6542. Engine.prototype.setSize = function (width, height) {
  6543. this._renderingCanvas.width = width;
  6544. this._renderingCanvas.height = height;
  6545. for (var index = 0; index < this.scenes.length; index++) {
  6546. var scene = this.scenes[index];
  6547. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  6548. var cam = scene.cameras[camIndex];
  6549. cam._currentRenderId = 0;
  6550. }
  6551. }
  6552. };
  6553. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight) {
  6554. this._currentRenderTarget = texture;
  6555. var gl = this._gl;
  6556. this.bindUnboundFramebuffer(texture._framebuffer);
  6557. if (texture.isCube) {
  6558. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture, 0);
  6559. }
  6560. else {
  6561. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  6562. }
  6563. this._gl.viewport(0, 0, requiredWidth || texture._width, requiredHeight || texture._height);
  6564. this.wipeCaches();
  6565. };
  6566. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  6567. if (this._currentFramebuffer !== framebuffer) {
  6568. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  6569. this._currentFramebuffer = framebuffer;
  6570. }
  6571. };
  6572. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps) {
  6573. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  6574. this._currentRenderTarget = null;
  6575. if (texture.generateMipMaps && !disableGenerateMipMaps) {
  6576. var gl = this._gl;
  6577. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  6578. gl.generateMipmap(gl.TEXTURE_2D);
  6579. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  6580. }
  6581. this.bindUnboundFramebuffer(null);
  6582. };
  6583. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  6584. if (texture.generateMipMaps) {
  6585. var gl = this._gl;
  6586. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  6587. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6588. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  6589. }
  6590. };
  6591. Engine.prototype.flushFramebuffer = function () {
  6592. this._gl.flush();
  6593. };
  6594. Engine.prototype.restoreDefaultFramebuffer = function () {
  6595. this._currentRenderTarget = null;
  6596. this.bindUnboundFramebuffer(null);
  6597. this.setViewport(this._cachedViewport);
  6598. this.wipeCaches();
  6599. };
  6600. // VBOs
  6601. Engine.prototype._resetVertexBufferBinding = function () {
  6602. this.bindArrayBuffer(null);
  6603. this._cachedVertexBuffers = null;
  6604. };
  6605. Engine.prototype.createVertexBuffer = function (vertices) {
  6606. var vbo = this._gl.createBuffer();
  6607. this.bindArrayBuffer(vbo);
  6608. if (vertices instanceof Float32Array) {
  6609. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  6610. }
  6611. else {
  6612. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  6613. }
  6614. this._resetVertexBufferBinding();
  6615. vbo.references = 1;
  6616. return vbo;
  6617. };
  6618. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  6619. var vbo = this._gl.createBuffer();
  6620. this.bindArrayBuffer(vbo);
  6621. if (vertices instanceof Float32Array) {
  6622. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  6623. }
  6624. else {
  6625. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  6626. }
  6627. this._resetVertexBufferBinding();
  6628. vbo.references = 1;
  6629. return vbo;
  6630. };
  6631. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  6632. this.bindArrayBuffer(vertexBuffer);
  6633. if (offset === undefined) {
  6634. offset = 0;
  6635. }
  6636. if (count === undefined) {
  6637. if (vertices instanceof Float32Array) {
  6638. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  6639. }
  6640. else {
  6641. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  6642. }
  6643. }
  6644. else {
  6645. if (vertices instanceof Float32Array) {
  6646. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  6647. }
  6648. else {
  6649. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  6650. }
  6651. }
  6652. this._resetVertexBufferBinding();
  6653. };
  6654. Engine.prototype._resetIndexBufferBinding = function () {
  6655. this.bindIndexBuffer(null);
  6656. this._cachedIndexBuffer = null;
  6657. };
  6658. Engine.prototype.createIndexBuffer = function (indices) {
  6659. var vbo = this._gl.createBuffer();
  6660. this.bindIndexBuffer(vbo);
  6661. // Check for 32 bits indices
  6662. var arrayBuffer;
  6663. var need32Bits = false;
  6664. if (this._caps.uintIndices) {
  6665. for (var index = 0; index < indices.length; index++) {
  6666. if (indices[index] > 65535) {
  6667. need32Bits = true;
  6668. break;
  6669. }
  6670. }
  6671. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  6672. }
  6673. else {
  6674. arrayBuffer = new Uint16Array(indices);
  6675. }
  6676. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  6677. this._resetIndexBufferBinding();
  6678. vbo.references = 1;
  6679. vbo.is32Bits = need32Bits;
  6680. return vbo;
  6681. };
  6682. Engine.prototype.bindArrayBuffer = function (buffer) {
  6683. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  6684. };
  6685. Engine.prototype.bindIndexBuffer = function (buffer) {
  6686. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  6687. };
  6688. Engine.prototype.bindBuffer = function (buffer, target) {
  6689. if (this._currentBoundBuffer[target] !== buffer) {
  6690. this._gl.bindBuffer(target, buffer);
  6691. this._currentBoundBuffer[target] = buffer;
  6692. }
  6693. };
  6694. Engine.prototype.updateArrayBuffer = function (data) {
  6695. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  6696. };
  6697. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  6698. var pointer = this._currentBufferPointers[indx];
  6699. var changed = false;
  6700. if (!pointer) {
  6701. changed = true;
  6702. this._currentBufferPointers[indx] = { indx: indx, size: size, type: type, normalized: normalized, stride: stride, offset: offset, buffer: buffer };
  6703. }
  6704. else {
  6705. if (pointer.buffer !== buffer) {
  6706. pointer.buffer = buffer;
  6707. changed = true;
  6708. }
  6709. if (pointer.size !== size) {
  6710. pointer.size = size;
  6711. changed = true;
  6712. }
  6713. if (pointer.type !== type) {
  6714. pointer.type = type;
  6715. changed = true;
  6716. }
  6717. if (pointer.normalized !== normalized) {
  6718. pointer.normalized = normalized;
  6719. changed = true;
  6720. }
  6721. if (pointer.stride !== stride) {
  6722. pointer.stride = stride;
  6723. changed = true;
  6724. }
  6725. if (pointer.offset !== offset) {
  6726. pointer.offset = offset;
  6727. changed = true;
  6728. }
  6729. }
  6730. if (changed) {
  6731. this.bindArrayBuffer(buffer);
  6732. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  6733. }
  6734. };
  6735. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  6736. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  6737. this._cachedVertexBuffers = vertexBuffer;
  6738. this._cachedEffectForVertexBuffers = effect;
  6739. var offset = 0;
  6740. for (var index = 0; index < vertexDeclaration.length; index++) {
  6741. var order = effect.getAttributeLocation(index);
  6742. if (order >= 0) {
  6743. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  6744. }
  6745. offset += vertexDeclaration[index] * 4;
  6746. }
  6747. }
  6748. if (this._cachedIndexBuffer !== indexBuffer) {
  6749. this._cachedIndexBuffer = indexBuffer;
  6750. this.bindIndexBuffer(indexBuffer);
  6751. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  6752. }
  6753. };
  6754. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  6755. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  6756. this._cachedVertexBuffers = vertexBuffers;
  6757. this._cachedEffectForVertexBuffers = effect;
  6758. var attributes = effect.getAttributesNames();
  6759. for (var index = 0; index < attributes.length; index++) {
  6760. var order = effect.getAttributeLocation(index);
  6761. if (order >= 0) {
  6762. var vertexBuffer = vertexBuffers[attributes[index]];
  6763. if (!vertexBuffer) {
  6764. continue;
  6765. }
  6766. var buffer = vertexBuffer.getBuffer();
  6767. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  6768. if (vertexBuffer.getIsInstanced()) {
  6769. this._caps.instancedArrays.vertexAttribDivisorANGLE(order, 1);
  6770. this._currentInstanceLocations.push(order);
  6771. this._currentInstanceBuffers.push(buffer);
  6772. }
  6773. }
  6774. }
  6775. }
  6776. if (indexBuffer != null && this._cachedIndexBuffer !== indexBuffer) {
  6777. this._cachedIndexBuffer = indexBuffer;
  6778. this.bindIndexBuffer(indexBuffer);
  6779. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  6780. }
  6781. };
  6782. Engine.prototype.unbindInstanceAttributes = function () {
  6783. var boundBuffer;
  6784. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  6785. var instancesBuffer = this._currentInstanceBuffers[i];
  6786. if (boundBuffer != instancesBuffer) {
  6787. boundBuffer = instancesBuffer;
  6788. this.bindArrayBuffer(instancesBuffer);
  6789. }
  6790. var offsetLocation = this._currentInstanceLocations[i];
  6791. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  6792. }
  6793. this._currentInstanceBuffers.length = 0;
  6794. this._currentInstanceLocations.length = 0;
  6795. };
  6796. Engine.prototype._releaseBuffer = function (buffer) {
  6797. buffer.references--;
  6798. if (buffer.references === 0) {
  6799. this._gl.deleteBuffer(buffer);
  6800. return true;
  6801. }
  6802. return false;
  6803. };
  6804. Engine.prototype.createInstancesBuffer = function (capacity) {
  6805. var buffer = this._gl.createBuffer();
  6806. buffer.capacity = capacity;
  6807. this.bindArrayBuffer(buffer);
  6808. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  6809. return buffer;
  6810. };
  6811. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  6812. this._gl.deleteBuffer(buffer);
  6813. };
  6814. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  6815. this.bindArrayBuffer(instancesBuffer);
  6816. if (data) {
  6817. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  6818. }
  6819. if (offsetLocations[0].index !== undefined) {
  6820. var stride = 0;
  6821. for (var i = 0; i < offsetLocations.length; i++) {
  6822. var ai = offsetLocations[i];
  6823. stride += ai.attributeSize * 4;
  6824. }
  6825. for (var i = 0; i < offsetLocations.length; i++) {
  6826. var ai = offsetLocations[i];
  6827. this._gl.enableVertexAttribArray(ai.index);
  6828. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  6829. this._caps.instancedArrays.vertexAttribDivisorANGLE(ai.index, 1);
  6830. this._currentInstanceLocations.push(ai.index);
  6831. this._currentInstanceBuffers.push(instancesBuffer);
  6832. }
  6833. }
  6834. else {
  6835. for (var index = 0; index < 4; index++) {
  6836. var offsetLocation = offsetLocations[index];
  6837. this._gl.enableVertexAttribArray(offsetLocation);
  6838. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  6839. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  6840. this._currentInstanceLocations.push(offsetLocation);
  6841. this._currentInstanceBuffers.push(instancesBuffer);
  6842. }
  6843. }
  6844. };
  6845. Engine.prototype.applyStates = function () {
  6846. this._depthCullingState.apply(this._gl);
  6847. this._alphaState.apply(this._gl);
  6848. };
  6849. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  6850. // Apply states
  6851. this.applyStates();
  6852. this._drawCalls.addCount(1, false);
  6853. // Render
  6854. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  6855. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  6856. if (instancesCount) {
  6857. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  6858. return;
  6859. }
  6860. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  6861. };
  6862. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  6863. // Apply states
  6864. this.applyStates();
  6865. this._drawCalls.addCount(1, false);
  6866. if (instancesCount) {
  6867. this._caps.instancedArrays.drawArraysInstancedANGLE(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  6868. return;
  6869. }
  6870. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  6871. };
  6872. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  6873. // Apply states
  6874. this.applyStates();
  6875. this._drawCalls.addCount(1, false);
  6876. if (instancesCount) {
  6877. this._caps.instancedArrays.drawArraysInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount, instancesCount);
  6878. return;
  6879. }
  6880. this._gl.drawArrays(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount);
  6881. };
  6882. // Shaders
  6883. Engine.prototype._releaseEffect = function (effect) {
  6884. if (this._compiledEffects[effect._key]) {
  6885. delete this._compiledEffects[effect._key];
  6886. if (effect.getProgram()) {
  6887. this._gl.deleteProgram(effect.getProgram());
  6888. }
  6889. }
  6890. };
  6891. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  6892. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  6893. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  6894. var name = vertex + "+" + fragment + "@" + defines;
  6895. if (this._compiledEffects[name]) {
  6896. return this._compiledEffects[name];
  6897. }
  6898. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  6899. effect._key = name;
  6900. this._compiledEffects[name] = effect;
  6901. return effect;
  6902. };
  6903. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  6904. if (uniformsNames === void 0) { uniformsNames = []; }
  6905. if (samplers === void 0) { samplers = []; }
  6906. if (defines === void 0) { defines = ""; }
  6907. return this.createEffect({
  6908. vertex: "particles",
  6909. fragmentElement: fragmentName
  6910. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  6911. };
  6912. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  6913. context = context || this._gl;
  6914. var vertexShader = compileShader(context, vertexCode, "vertex", defines);
  6915. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines);
  6916. var shaderProgram = context.createProgram();
  6917. context.attachShader(shaderProgram, vertexShader);
  6918. context.attachShader(shaderProgram, fragmentShader);
  6919. context.linkProgram(shaderProgram);
  6920. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  6921. if (!linked) {
  6922. var error = context.getProgramInfoLog(shaderProgram);
  6923. if (error) {
  6924. throw new Error(error);
  6925. }
  6926. }
  6927. context.deleteShader(vertexShader);
  6928. context.deleteShader(fragmentShader);
  6929. return shaderProgram;
  6930. };
  6931. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  6932. var results = [];
  6933. for (var index = 0; index < uniformsNames.length; index++) {
  6934. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  6935. }
  6936. return results;
  6937. };
  6938. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  6939. var results = [];
  6940. for (var index = 0; index < attributesNames.length; index++) {
  6941. try {
  6942. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  6943. }
  6944. catch (e) {
  6945. results.push(-1);
  6946. }
  6947. }
  6948. return results;
  6949. };
  6950. Engine.prototype.enableEffect = function (effect) {
  6951. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  6952. if (effect && effect.onBind) {
  6953. effect.onBind(effect);
  6954. }
  6955. return;
  6956. }
  6957. this._vertexAttribArraysToUse = this._vertexAttribArraysToUse || [];
  6958. this._vertexAttribArraysEnabled = this._vertexAttribArraysEnabled || [];
  6959. // Use program
  6960. this.setProgram(effect.getProgram());
  6961. var i, ul;
  6962. for (i = 0, ul = this._vertexAttribArraysToUse.length; i < ul; i++) {
  6963. this._vertexAttribArraysToUse[i] = false;
  6964. }
  6965. var attributesCount = effect.getAttributesCount();
  6966. for (i = 0; i < attributesCount; i++) {
  6967. // Attributes
  6968. var order = effect.getAttributeLocation(i);
  6969. if (order >= 0) {
  6970. this._vertexAttribArraysToUse[order] = true;
  6971. }
  6972. }
  6973. for (i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  6974. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArraysEnabled[i] || this._vertexAttribArraysToUse[i]) {
  6975. continue;
  6976. }
  6977. this._vertexAttribArraysEnabled[i] = false;
  6978. this._gl.disableVertexAttribArray(i);
  6979. }
  6980. for (i = 0, ul = this._vertexAttribArraysToUse.length; i < ul; i++) {
  6981. if (this._vertexAttribArraysToUse[i] && !this._vertexAttribArraysEnabled[i]) {
  6982. this._vertexAttribArraysEnabled[i] = true;
  6983. this._gl.enableVertexAttribArray(i);
  6984. }
  6985. }
  6986. this._currentEffect = effect;
  6987. if (effect.onBind) {
  6988. effect.onBind(effect);
  6989. }
  6990. };
  6991. Engine.prototype.setIntArray = function (uniform, array) {
  6992. if (!uniform)
  6993. return;
  6994. this._gl.uniform1iv(uniform, array);
  6995. };
  6996. Engine.prototype.setIntArray2 = function (uniform, array) {
  6997. if (!uniform || array.length % 2 !== 0)
  6998. return;
  6999. this._gl.uniform2iv(uniform, array);
  7000. };
  7001. Engine.prototype.setIntArray3 = function (uniform, array) {
  7002. if (!uniform || array.length % 3 !== 0)
  7003. return;
  7004. this._gl.uniform3iv(uniform, array);
  7005. };
  7006. Engine.prototype.setIntArray4 = function (uniform, array) {
  7007. if (!uniform || array.length % 4 !== 0)
  7008. return;
  7009. this._gl.uniform4iv(uniform, array);
  7010. };
  7011. Engine.prototype.setFloatArray = function (uniform, array) {
  7012. if (!uniform)
  7013. return;
  7014. this._gl.uniform1fv(uniform, array);
  7015. };
  7016. Engine.prototype.setFloatArray2 = function (uniform, array) {
  7017. if (!uniform || array.length % 2 !== 0)
  7018. return;
  7019. this._gl.uniform2fv(uniform, array);
  7020. };
  7021. Engine.prototype.setFloatArray3 = function (uniform, array) {
  7022. if (!uniform || array.length % 3 !== 0)
  7023. return;
  7024. this._gl.uniform3fv(uniform, array);
  7025. };
  7026. Engine.prototype.setFloatArray4 = function (uniform, array) {
  7027. if (!uniform || array.length % 4 !== 0)
  7028. return;
  7029. this._gl.uniform4fv(uniform, array);
  7030. };
  7031. Engine.prototype.setArray = function (uniform, array) {
  7032. if (!uniform)
  7033. return;
  7034. this._gl.uniform1fv(uniform, array);
  7035. };
  7036. Engine.prototype.setArray2 = function (uniform, array) {
  7037. if (!uniform || array.length % 2 !== 0)
  7038. return;
  7039. this._gl.uniform2fv(uniform, array);
  7040. };
  7041. Engine.prototype.setArray3 = function (uniform, array) {
  7042. if (!uniform || array.length % 3 !== 0)
  7043. return;
  7044. this._gl.uniform3fv(uniform, array);
  7045. };
  7046. Engine.prototype.setArray4 = function (uniform, array) {
  7047. if (!uniform || array.length % 4 !== 0)
  7048. return;
  7049. this._gl.uniform4fv(uniform, array);
  7050. };
  7051. Engine.prototype.setMatrices = function (uniform, matrices) {
  7052. if (!uniform)
  7053. return;
  7054. this._gl.uniformMatrix4fv(uniform, false, matrices);
  7055. };
  7056. Engine.prototype.setMatrix = function (uniform, matrix) {
  7057. if (!uniform)
  7058. return;
  7059. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  7060. };
  7061. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  7062. if (!uniform)
  7063. return;
  7064. this._gl.uniformMatrix3fv(uniform, false, matrix);
  7065. };
  7066. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  7067. if (!uniform)
  7068. return;
  7069. this._gl.uniformMatrix2fv(uniform, false, matrix);
  7070. };
  7071. Engine.prototype.setFloat = function (uniform, value) {
  7072. if (!uniform)
  7073. return;
  7074. this._gl.uniform1f(uniform, value);
  7075. };
  7076. Engine.prototype.setFloat2 = function (uniform, x, y) {
  7077. if (!uniform)
  7078. return;
  7079. this._gl.uniform2f(uniform, x, y);
  7080. };
  7081. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  7082. if (!uniform)
  7083. return;
  7084. this._gl.uniform3f(uniform, x, y, z);
  7085. };
  7086. Engine.prototype.setBool = function (uniform, bool) {
  7087. if (!uniform)
  7088. return;
  7089. this._gl.uniform1i(uniform, bool);
  7090. };
  7091. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  7092. if (!uniform)
  7093. return;
  7094. this._gl.uniform4f(uniform, x, y, z, w);
  7095. };
  7096. Engine.prototype.setColor3 = function (uniform, color3) {
  7097. if (!uniform)
  7098. return;
  7099. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  7100. };
  7101. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  7102. if (!uniform)
  7103. return;
  7104. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  7105. };
  7106. // States
  7107. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  7108. if (zOffset === void 0) { zOffset = 0; }
  7109. if (reverseSide === void 0) { reverseSide = false; }
  7110. // Culling
  7111. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  7112. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  7113. var cullFace = this.cullBackFaces ? showSide : hideSide;
  7114. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  7115. if (culling) {
  7116. this._depthCullingState.cullFace = cullFace;
  7117. this._depthCullingState.cull = true;
  7118. }
  7119. else {
  7120. this._depthCullingState.cull = false;
  7121. }
  7122. }
  7123. // Z offset
  7124. this._depthCullingState.zOffset = zOffset;
  7125. };
  7126. Engine.prototype.setDepthBuffer = function (enable) {
  7127. this._depthCullingState.depthTest = enable;
  7128. };
  7129. Engine.prototype.getDepthWrite = function () {
  7130. return this._depthCullingState.depthMask;
  7131. };
  7132. Engine.prototype.setDepthWrite = function (enable) {
  7133. this._depthCullingState.depthMask = enable;
  7134. };
  7135. Engine.prototype.setColorWrite = function (enable) {
  7136. this._gl.colorMask(enable, enable, enable, enable);
  7137. };
  7138. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  7139. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  7140. if (this._alphaMode === mode) {
  7141. return;
  7142. }
  7143. switch (mode) {
  7144. case Engine.ALPHA_DISABLE:
  7145. this._alphaState.alphaBlend = false;
  7146. break;
  7147. case Engine.ALPHA_COMBINE:
  7148. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  7149. this._alphaState.alphaBlend = true;
  7150. break;
  7151. case Engine.ALPHA_ONEONE:
  7152. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  7153. this._alphaState.alphaBlend = true;
  7154. break;
  7155. case Engine.ALPHA_ADD:
  7156. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  7157. this._alphaState.alphaBlend = true;
  7158. break;
  7159. case Engine.ALPHA_SUBTRACT:
  7160. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  7161. this._alphaState.alphaBlend = true;
  7162. break;
  7163. case Engine.ALPHA_MULTIPLY:
  7164. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  7165. this._alphaState.alphaBlend = true;
  7166. break;
  7167. case Engine.ALPHA_MAXIMIZED:
  7168. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  7169. this._alphaState.alphaBlend = true;
  7170. break;
  7171. }
  7172. if (!noDepthWriteChange) {
  7173. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  7174. }
  7175. this._alphaMode = mode;
  7176. };
  7177. Engine.prototype.getAlphaMode = function () {
  7178. return this._alphaMode;
  7179. };
  7180. Engine.prototype.setAlphaTesting = function (enable) {
  7181. this._alphaTest = enable;
  7182. };
  7183. Engine.prototype.getAlphaTesting = function () {
  7184. return this._alphaTest;
  7185. };
  7186. // Textures
  7187. Engine.prototype.wipeCaches = function () {
  7188. this.resetTextureCache();
  7189. this._currentEffect = null;
  7190. this._depthCullingState.reset();
  7191. this.setDepthFunctionToLessOrEqual();
  7192. this._alphaState.reset();
  7193. this._cachedVertexBuffers = null;
  7194. this._cachedIndexBuffer = null;
  7195. this._cachedEffectForVertexBuffers = null;
  7196. };
  7197. Engine.prototype.setSamplingMode = function (texture, samplingMode) {
  7198. var gl = this._gl;
  7199. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  7200. var magFilter = gl.NEAREST;
  7201. var minFilter = gl.NEAREST;
  7202. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  7203. magFilter = gl.LINEAR;
  7204. minFilter = gl.LINEAR;
  7205. }
  7206. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  7207. magFilter = gl.LINEAR;
  7208. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  7209. }
  7210. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  7211. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  7212. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  7213. texture.samplingMode = samplingMode;
  7214. };
  7215. Engine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer) {
  7216. var _this = this;
  7217. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  7218. if (onLoad === void 0) { onLoad = null; }
  7219. if (onError === void 0) { onError = null; }
  7220. if (buffer === void 0) { buffer = null; }
  7221. var texture = this._gl.createTexture();
  7222. var extension;
  7223. var fromData = false;
  7224. if (url.substr(0, 5) === "data:") {
  7225. fromData = true;
  7226. }
  7227. if (!fromData)
  7228. extension = url.substr(url.length - 4, 4).toLowerCase();
  7229. else {
  7230. var oldUrl = url;
  7231. fromData = oldUrl.split(':');
  7232. url = oldUrl;
  7233. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  7234. }
  7235. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  7236. var isTGA = (extension === ".tga");
  7237. scene._addPendingData(texture);
  7238. texture.url = url;
  7239. texture.noMipmap = noMipmap;
  7240. texture.references = 1;
  7241. texture.samplingMode = samplingMode;
  7242. this._loadedTexturesCache.push(texture);
  7243. var onerror = function () {
  7244. scene._removePendingData(texture);
  7245. if (onError) {
  7246. onError();
  7247. }
  7248. };
  7249. var callback;
  7250. if (isTGA) {
  7251. callback = function (arrayBuffer) {
  7252. var data = new Uint8Array(arrayBuffer);
  7253. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  7254. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  7255. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  7256. }, onLoad, samplingMode);
  7257. };
  7258. if (!(fromData instanceof Array))
  7259. BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
  7260. callback(arrayBuffer);
  7261. }, onerror, scene.database, true);
  7262. else
  7263. callback(buffer);
  7264. }
  7265. else if (isDDS) {
  7266. callback = function (data) {
  7267. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  7268. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  7269. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  7270. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  7271. }, onLoad, samplingMode);
  7272. };
  7273. if (!(fromData instanceof Array))
  7274. BABYLON.Tools.LoadFile(url, function (data) {
  7275. callback(data);
  7276. }, onerror, scene.database, true);
  7277. else
  7278. callback(buffer);
  7279. }
  7280. else {
  7281. var onload = function (img) {
  7282. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  7283. var isPot = (img.width === potWidth && img.height === potHeight);
  7284. if (!isPot) {
  7285. _this._prepareWorkingCanvas();
  7286. _this._workingCanvas.width = potWidth;
  7287. _this._workingCanvas.height = potHeight;
  7288. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  7289. _this._workingContext.imageSmoothingEnabled = false;
  7290. _this._workingContext.mozImageSmoothingEnabled = false;
  7291. _this._workingContext.oImageSmoothingEnabled = false;
  7292. _this._workingContext.webkitImageSmoothingEnabled = false;
  7293. _this._workingContext.msImageSmoothingEnabled = false;
  7294. }
  7295. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  7296. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  7297. _this._workingContext.imageSmoothingEnabled = true;
  7298. _this._workingContext.mozImageSmoothingEnabled = true;
  7299. _this._workingContext.oImageSmoothingEnabled = true;
  7300. _this._workingContext.webkitImageSmoothingEnabled = true;
  7301. _this._workingContext.msImageSmoothingEnabled = true;
  7302. }
  7303. }
  7304. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  7305. }, onLoad, samplingMode);
  7306. };
  7307. if (!(fromData instanceof Array))
  7308. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  7309. else
  7310. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  7311. }
  7312. return texture;
  7313. };
  7314. Engine.prototype._getInternalFormat = function (format) {
  7315. var internalFormat = this._gl.RGBA;
  7316. switch (format) {
  7317. case Engine.TEXTUREFORMAT_ALPHA:
  7318. internalFormat = this._gl.ALPHA;
  7319. break;
  7320. case Engine.TEXTUREFORMAT_LUMINANCE:
  7321. internalFormat = this._gl.LUMINANCE;
  7322. break;
  7323. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  7324. internalFormat = this._gl.LUMINANCE_ALPHA;
  7325. break;
  7326. case Engine.TEXTUREFORMAT_RGB:
  7327. internalFormat = this._gl.RGB;
  7328. break;
  7329. case Engine.TEXTUREFORMAT_RGBA:
  7330. internalFormat = this._gl.RGBA;
  7331. break;
  7332. }
  7333. return internalFormat;
  7334. };
  7335. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression) {
  7336. if (compression === void 0) { compression = null; }
  7337. var internalFormat = this._getInternalFormat(format);
  7338. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  7339. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  7340. if (texture._width % 4 !== 0) {
  7341. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  7342. }
  7343. if (compression) {
  7344. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture._width, texture._height, 0, data);
  7345. }
  7346. else {
  7347. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture._width, texture._height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  7348. }
  7349. if (texture.generateMipMaps) {
  7350. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  7351. }
  7352. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  7353. this.resetTextureCache();
  7354. texture.isReady = true;
  7355. };
  7356. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression) {
  7357. if (compression === void 0) { compression = null; }
  7358. var texture = this._gl.createTexture();
  7359. texture._baseWidth = width;
  7360. texture._baseHeight = height;
  7361. texture._width = width;
  7362. texture._height = height;
  7363. texture.references = 1;
  7364. this.updateRawTexture(texture, data, format, invertY, compression);
  7365. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  7366. // Filters
  7367. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  7368. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  7369. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  7370. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  7371. texture.samplingMode = samplingMode;
  7372. this._loadedTexturesCache.push(texture);
  7373. return texture;
  7374. };
  7375. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  7376. var texture = this._gl.createTexture();
  7377. texture._baseWidth = width;
  7378. texture._baseHeight = height;
  7379. if (generateMipMaps) {
  7380. width = BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize);
  7381. height = BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize);
  7382. }
  7383. this.resetTextureCache();
  7384. texture._width = width;
  7385. texture._height = height;
  7386. texture.isReady = false;
  7387. texture.generateMipMaps = generateMipMaps;
  7388. texture.references = 1;
  7389. texture.samplingMode = samplingMode;
  7390. this.updateTextureSamplingMode(samplingMode, texture);
  7391. this._loadedTexturesCache.push(texture);
  7392. return texture;
  7393. };
  7394. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  7395. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  7396. if (texture.isCube) {
  7397. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  7398. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  7399. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  7400. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  7401. }
  7402. else {
  7403. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  7404. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  7405. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  7406. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  7407. }
  7408. };
  7409. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha) {
  7410. if (premulAlpha === void 0) { premulAlpha = false; }
  7411. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  7412. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  7413. if (premulAlpha) {
  7414. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  7415. }
  7416. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  7417. if (texture.generateMipMaps) {
  7418. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  7419. }
  7420. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  7421. this.resetTextureCache();
  7422. texture.isReady = true;
  7423. };
  7424. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  7425. if (texture._isDisabled) {
  7426. return;
  7427. }
  7428. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  7429. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  7430. try {
  7431. // Testing video texture support
  7432. if (this._videoTextureSupported === undefined) {
  7433. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  7434. if (this._gl.getError() !== 0) {
  7435. this._videoTextureSupported = false;
  7436. }
  7437. else {
  7438. this._videoTextureSupported = true;
  7439. }
  7440. }
  7441. // Copy video through the current working canvas if video texture is not supported
  7442. if (!this._videoTextureSupported) {
  7443. if (!texture._workingCanvas) {
  7444. texture._workingCanvas = document.createElement("canvas");
  7445. texture._workingContext = texture._workingCanvas.getContext("2d");
  7446. texture._workingCanvas.width = texture._width;
  7447. texture._workingCanvas.height = texture._height;
  7448. }
  7449. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  7450. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  7451. }
  7452. else {
  7453. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  7454. }
  7455. if (texture.generateMipMaps) {
  7456. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  7457. }
  7458. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  7459. this.resetTextureCache();
  7460. texture.isReady = true;
  7461. }
  7462. catch (ex) {
  7463. // Something unexpected
  7464. // Let's disable the texture
  7465. texture._isDisabled = true;
  7466. }
  7467. };
  7468. Engine.prototype.createRenderTargetTexture = function (size, options) {
  7469. // old version had a "generateMipMaps" arg instead of options.
  7470. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  7471. // in the same way, generateDepthBuffer is defaulted to true
  7472. var generateMipMaps = false;
  7473. var generateDepthBuffer = true;
  7474. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  7475. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  7476. if (options !== undefined) {
  7477. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  7478. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  7479. type = options.type === undefined ? type : options.type;
  7480. if (options.samplingMode !== undefined) {
  7481. samplingMode = options.samplingMode;
  7482. }
  7483. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  7484. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  7485. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  7486. }
  7487. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  7488. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  7489. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  7490. }
  7491. }
  7492. var gl = this._gl;
  7493. var texture = gl.createTexture();
  7494. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  7495. var width = size.width || size;
  7496. var height = size.height || size;
  7497. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  7498. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  7499. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  7500. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  7501. }
  7502. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  7503. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  7504. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  7505. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  7506. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, getWebGLTextureType(gl, type), null);
  7507. var depthBuffer;
  7508. // Create the depth buffer
  7509. if (generateDepthBuffer) {
  7510. depthBuffer = gl.createRenderbuffer();
  7511. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  7512. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  7513. }
  7514. // Create the framebuffer
  7515. var framebuffer = gl.createFramebuffer();
  7516. this.bindUnboundFramebuffer(framebuffer);
  7517. if (generateDepthBuffer) {
  7518. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  7519. }
  7520. if (generateMipMaps) {
  7521. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  7522. }
  7523. // Unbind
  7524. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  7525. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  7526. this.bindUnboundFramebuffer(null);
  7527. texture._framebuffer = framebuffer;
  7528. if (generateDepthBuffer) {
  7529. texture._depthBuffer = depthBuffer;
  7530. }
  7531. texture._baseWidth = width;
  7532. texture._baseHeight = height;
  7533. texture._width = width;
  7534. texture._height = height;
  7535. texture.isReady = true;
  7536. texture.generateMipMaps = generateMipMaps;
  7537. texture.references = 1;
  7538. texture.samplingMode = samplingMode;
  7539. texture.type = type;
  7540. this.resetTextureCache();
  7541. this._loadedTexturesCache.push(texture);
  7542. return texture;
  7543. };
  7544. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  7545. var gl = this._gl;
  7546. var texture = gl.createTexture();
  7547. var generateMipMaps = true;
  7548. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  7549. if (options !== undefined) {
  7550. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  7551. if (options.samplingMode !== undefined) {
  7552. samplingMode = options.samplingMode;
  7553. }
  7554. }
  7555. texture.isCube = true;
  7556. texture.references = 1;
  7557. texture.generateMipMaps = generateMipMaps;
  7558. texture.references = 1;
  7559. texture.samplingMode = samplingMode;
  7560. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  7561. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  7562. for (var face = 0; face < 6; face++) {
  7563. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  7564. }
  7565. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  7566. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  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. // Create the depth buffer
  7570. var depthBuffer = gl.createRenderbuffer();
  7571. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  7572. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, size, size);
  7573. // Create the framebuffer
  7574. var framebuffer = gl.createFramebuffer();
  7575. this.bindUnboundFramebuffer(framebuffer);
  7576. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  7577. // Mipmaps
  7578. if (texture.generateMipMaps) {
  7579. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  7580. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  7581. }
  7582. // Unbind
  7583. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  7584. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  7585. this.bindUnboundFramebuffer(null);
  7586. texture._framebuffer = framebuffer;
  7587. texture._depthBuffer = depthBuffer;
  7588. this.resetTextureCache();
  7589. texture._width = size;
  7590. texture._height = size;
  7591. texture.isReady = true;
  7592. return texture;
  7593. };
  7594. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap) {
  7595. var _this = this;
  7596. var gl = this._gl;
  7597. var texture = gl.createTexture();
  7598. texture.isCube = true;
  7599. texture.url = rootUrl;
  7600. texture.references = 1;
  7601. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  7602. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  7603. if (isDDS) {
  7604. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  7605. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  7606. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  7607. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  7608. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  7609. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  7610. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  7611. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  7612. }
  7613. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  7614. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  7615. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  7616. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  7617. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  7618. _this.resetTextureCache();
  7619. texture._width = info.width;
  7620. texture._height = info.height;
  7621. texture.isReady = true;
  7622. }, null, null, true);
  7623. }
  7624. else {
  7625. cascadeLoad(rootUrl, scene, function (imgs) {
  7626. var width = BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  7627. var height = width;
  7628. _this._prepareWorkingCanvas();
  7629. _this._workingCanvas.width = width;
  7630. _this._workingCanvas.height = height;
  7631. var faces = [
  7632. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  7633. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  7634. ];
  7635. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  7636. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  7637. for (var index = 0; index < faces.length; index++) {
  7638. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  7639. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  7640. }
  7641. if (!noMipmap) {
  7642. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  7643. }
  7644. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  7645. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  7646. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  7647. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  7648. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  7649. _this.resetTextureCache();
  7650. texture._width = width;
  7651. texture._height = height;
  7652. texture.isReady = true;
  7653. }, files);
  7654. }
  7655. return texture;
  7656. };
  7657. Engine.prototype.updateTextureSize = function (texture, width, height) {
  7658. texture._width = width;
  7659. texture._height = height;
  7660. texture._size = width * height;
  7661. texture._baseWidth = width;
  7662. texture._baseHeight = height;
  7663. };
  7664. Engine.prototype.createRawCubeTexture = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator) {
  7665. var _this = this;
  7666. var gl = this._gl;
  7667. var texture = gl.createTexture();
  7668. scene._addPendingData(texture);
  7669. texture.isCube = true;
  7670. texture.references = 1;
  7671. texture.url = url;
  7672. var internalFormat = this._getInternalFormat(format);
  7673. var textureType = gl.UNSIGNED_BYTE;
  7674. if (type === Engine.TEXTURETYPE_FLOAT) {
  7675. textureType = gl.FLOAT;
  7676. }
  7677. var width = size;
  7678. var height = width;
  7679. var isPot = (BABYLON.Tools.IsExponentOfTwo(width) && BABYLON.Tools.IsExponentOfTwo(height));
  7680. texture._width = width;
  7681. texture._height = height;
  7682. var onerror = function () {
  7683. scene._removePendingData(texture);
  7684. };
  7685. var internalCallback = function (data) {
  7686. var rgbeDataArrays = callback(data);
  7687. var facesIndex = [
  7688. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  7689. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  7690. ];
  7691. width = texture._width;
  7692. height = texture._height;
  7693. isPot = (BABYLON.Tools.IsExponentOfTwo(width) && BABYLON.Tools.IsExponentOfTwo(height));
  7694. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  7695. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  7696. if (!noMipmap && isPot) {
  7697. if (mipmmapGenerator) {
  7698. var arrayTemp = [];
  7699. // Data are known to be in +X +Y +Z -X -Y -Z
  7700. // mipmmapGenerator data is expected to be order in +X -X +Y -Y +Z -Z
  7701. arrayTemp.push(rgbeDataArrays[0]); // +X
  7702. arrayTemp.push(rgbeDataArrays[3]); // -X
  7703. arrayTemp.push(rgbeDataArrays[1]); // +Y
  7704. arrayTemp.push(rgbeDataArrays[4]); // -Y
  7705. arrayTemp.push(rgbeDataArrays[2]); // +Z
  7706. arrayTemp.push(rgbeDataArrays[5]); // -Z
  7707. var mipData = mipmmapGenerator(arrayTemp);
  7708. for (var level = 0; level < mipData.length; level++) {
  7709. var mipSize = width >> level;
  7710. // mipData is order in +X -X +Y -Y +Z -Z
  7711. gl.texImage2D(facesIndex[0], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][0]);
  7712. gl.texImage2D(facesIndex[1], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][2]);
  7713. gl.texImage2D(facesIndex[2], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][4]);
  7714. gl.texImage2D(facesIndex[3], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][1]);
  7715. gl.texImage2D(facesIndex[4], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][3]);
  7716. gl.texImage2D(facesIndex[5], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][5]);
  7717. }
  7718. }
  7719. else {
  7720. // Data are known to be in +X +Y +Z -X -Y -Z
  7721. for (var index = 0; index < facesIndex.length; index++) {
  7722. var faceData = rgbeDataArrays[index];
  7723. gl.texImage2D(facesIndex[index], 0, internalFormat, width, height, 0, internalFormat, textureType, faceData);
  7724. }
  7725. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  7726. // Workaround firefox bug fix https://bugzilla.mozilla.org/show_bug.cgi?id=1221822
  7727. // By following the webgl standard changes from Revision 7, 2014/11/24
  7728. // Firefox Removed the support for RGB32F, since it is not natively supported on all platforms where WebGL is implemented.
  7729. if (textureType === gl.FLOAT && internalFormat === gl.RGB && gl.getError() === 1282) {
  7730. BABYLON.Tools.Log("RGB32F not renderable on Firefox, trying fallback to RGBA32F.");
  7731. // Data are known to be in +X +Y +Z -X -Y -Z
  7732. for (var index = 0; index < facesIndex.length; index++) {
  7733. var faceData = rgbeDataArrays[index];
  7734. // Create a new RGBA Face.
  7735. var newFaceData = new Float32Array(width * height * 4);
  7736. for (var x = 0; x < width; x++) {
  7737. for (var y = 0; y < height; y++) {
  7738. var index_1 = (y * width + x) * 3;
  7739. var newIndex = (y * width + x) * 4;
  7740. // Map Old Value to new value.
  7741. newFaceData[newIndex + 0] = faceData[index_1 + 0];
  7742. newFaceData[newIndex + 1] = faceData[index_1 + 1];
  7743. newFaceData[newIndex + 2] = faceData[index_1 + 2];
  7744. // Add fully opaque alpha channel.
  7745. newFaceData[newIndex + 3] = 1;
  7746. }
  7747. }
  7748. // Reupload the face.
  7749. gl.texImage2D(facesIndex[index], 0, gl.RGBA, width, height, 0, gl.RGBA, textureType, newFaceData);
  7750. }
  7751. // Try to generate mipmap again.
  7752. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  7753. }
  7754. }
  7755. }
  7756. else {
  7757. noMipmap = true;
  7758. }
  7759. if (textureType === gl.FLOAT && !_this._caps.textureFloatLinearFiltering) {
  7760. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  7761. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  7762. }
  7763. else if (textureType === HALF_FLOAT_OES && !_this._caps.textureHalfFloatLinearFiltering) {
  7764. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  7765. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  7766. }
  7767. else {
  7768. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  7769. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  7770. }
  7771. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  7772. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  7773. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  7774. texture.isReady = true;
  7775. _this.resetTextureCache();
  7776. scene._removePendingData(texture);
  7777. };
  7778. BABYLON.Tools.LoadFile(url, function (data) {
  7779. internalCallback(data);
  7780. }, onerror, scene.database, true);
  7781. return texture;
  7782. };
  7783. ;
  7784. Engine.prototype._releaseTexture = function (texture) {
  7785. var gl = this._gl;
  7786. if (texture._framebuffer) {
  7787. gl.deleteFramebuffer(texture._framebuffer);
  7788. }
  7789. if (texture._depthBuffer) {
  7790. gl.deleteRenderbuffer(texture._depthBuffer);
  7791. }
  7792. gl.deleteTexture(texture);
  7793. // Unbind channels
  7794. this.unbindAllTextures();
  7795. var index = this._loadedTexturesCache.indexOf(texture);
  7796. if (index !== -1) {
  7797. this._loadedTexturesCache.splice(index, 1);
  7798. }
  7799. };
  7800. Engine.prototype.setProgram = function (program) {
  7801. if (this._currentProgram !== program) {
  7802. this._gl.useProgram(program);
  7803. this._currentProgram = program;
  7804. }
  7805. };
  7806. Engine.prototype.bindSamplers = function (effect) {
  7807. this.setProgram(effect.getProgram());
  7808. var samplers = effect.getSamplers();
  7809. for (var index = 0; index < samplers.length; index++) {
  7810. var uniform = effect.getUniform(samplers[index]);
  7811. this._gl.uniform1i(uniform, index);
  7812. }
  7813. this._currentEffect = null;
  7814. };
  7815. Engine.prototype.activateTexture = function (texture) {
  7816. if (this._activeTexture !== texture) {
  7817. this._gl.activeTexture(texture);
  7818. this._activeTexture = texture;
  7819. }
  7820. };
  7821. Engine.prototype._bindTextureDirectly = function (target, texture) {
  7822. if (this._activeTexturesCache[this._activeTexture] !== texture) {
  7823. this._gl.bindTexture(target, texture);
  7824. this._activeTexturesCache[this._activeTexture] = texture;
  7825. }
  7826. };
  7827. Engine.prototype._bindTexture = function (channel, texture) {
  7828. if (channel < 0) {
  7829. return;
  7830. }
  7831. this.activateTexture(this._gl["TEXTURE" + channel]);
  7832. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  7833. };
  7834. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  7835. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  7836. };
  7837. Engine.prototype.unbindAllTextures = function () {
  7838. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  7839. this.activateTexture(this._gl["TEXTURE" + channel]);
  7840. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  7841. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  7842. }
  7843. };
  7844. Engine.prototype.setTexture = function (channel, uniform, texture) {
  7845. if (channel < 0) {
  7846. return;
  7847. }
  7848. this._gl.uniform1i(uniform, channel);
  7849. this._setTexture(channel, texture);
  7850. };
  7851. Engine.prototype._setTexture = function (channel, texture) {
  7852. // Not ready?
  7853. if (!texture || !texture.isReady()) {
  7854. if (this._activeTexturesCache[channel] != null) {
  7855. this.activateTexture(this._gl["TEXTURE" + channel]);
  7856. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  7857. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  7858. }
  7859. return;
  7860. }
  7861. // Video
  7862. var alreadyActivated = false;
  7863. if (texture instanceof BABYLON.VideoTexture) {
  7864. this.activateTexture(this._gl["TEXTURE" + channel]);
  7865. alreadyActivated = true;
  7866. texture.update();
  7867. }
  7868. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  7869. texture.delayLoad();
  7870. return;
  7871. }
  7872. var internalTexture = texture.getInternalTexture();
  7873. if (this._activeTexturesCache[channel] === internalTexture) {
  7874. return;
  7875. }
  7876. if (!alreadyActivated) {
  7877. this.activateTexture(this._gl["TEXTURE" + channel]);
  7878. }
  7879. if (internalTexture.isCube) {
  7880. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  7881. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  7882. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  7883. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  7884. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  7885. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  7886. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  7887. }
  7888. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  7889. }
  7890. else {
  7891. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture);
  7892. if (internalTexture._cachedWrapU !== texture.wrapU) {
  7893. internalTexture._cachedWrapU = texture.wrapU;
  7894. switch (texture.wrapU) {
  7895. case BABYLON.Texture.WRAP_ADDRESSMODE:
  7896. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  7897. break;
  7898. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  7899. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  7900. break;
  7901. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  7902. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  7903. break;
  7904. }
  7905. }
  7906. if (internalTexture._cachedWrapV !== texture.wrapV) {
  7907. internalTexture._cachedWrapV = texture.wrapV;
  7908. switch (texture.wrapV) {
  7909. case BABYLON.Texture.WRAP_ADDRESSMODE:
  7910. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  7911. break;
  7912. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  7913. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  7914. break;
  7915. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  7916. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  7917. break;
  7918. }
  7919. }
  7920. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  7921. }
  7922. };
  7923. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  7924. if (channel < 0) {
  7925. return;
  7926. }
  7927. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  7928. this._textureUnits = new Int32Array(textures.length);
  7929. }
  7930. for (var i = 0; i < textures.length; i++) {
  7931. this._textureUnits[i] = channel + i;
  7932. }
  7933. this._gl.uniform1iv(uniform, this._textureUnits);
  7934. for (var index = 0; index < textures.length; index++) {
  7935. this._setTexture(channel + index, textures[index]);
  7936. }
  7937. };
  7938. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  7939. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  7940. var value = texture.anisotropicFilteringLevel;
  7941. if (texture.getInternalTexture().samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  7942. value = 1;
  7943. }
  7944. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  7945. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  7946. texture._cachedAnisotropicFilteringLevel = value;
  7947. }
  7948. };
  7949. Engine.prototype.readPixels = function (x, y, width, height) {
  7950. var data = new Uint8Array(height * width * 4);
  7951. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  7952. return data;
  7953. };
  7954. /**
  7955. * Add an externaly attached data from its key.
  7956. * This method call will fail and return false, if such key already exists.
  7957. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  7958. * @param key the unique key that identifies the data
  7959. * @param data the data object to associate to the key for this Engine instance
  7960. * @return true if no such key were already present and the data was added successfully, false otherwise
  7961. */
  7962. Engine.prototype.addExternalData = function (key, data) {
  7963. return this._externalData.add(key, data);
  7964. };
  7965. /**
  7966. * Get an externaly attached data from its key
  7967. * @param key the unique key that identifies the data
  7968. * @return the associated data, if present (can be null), or undefined if not present
  7969. */
  7970. Engine.prototype.getExternalData = function (key) {
  7971. return this._externalData.get(key);
  7972. };
  7973. /**
  7974. * Get an externaly attached data from its key, create it using a factory if it's not already present
  7975. * @param key the unique key that identifies the data
  7976. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  7977. * @return the associated data, can be null if the factory returned null.
  7978. */
  7979. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  7980. return this._externalData.getOrAddWithFactory(key, factory);
  7981. };
  7982. /**
  7983. * Remove an externaly attached data from the Engine instance
  7984. * @param key the unique key that identifies the data
  7985. * @return true if the data was successfully removed, false if it doesn't exist
  7986. */
  7987. Engine.prototype.removeExternalData = function (key) {
  7988. return this._externalData.remove(key);
  7989. };
  7990. Engine.prototype.releaseInternalTexture = function (texture) {
  7991. if (!texture) {
  7992. return;
  7993. }
  7994. texture.references--;
  7995. // Final reference ?
  7996. if (texture.references === 0) {
  7997. var texturesCache = this.getLoadedTexturesCache();
  7998. var index = texturesCache.indexOf(texture);
  7999. if (index > -1) {
  8000. texturesCache.splice(index, 1);
  8001. }
  8002. this._releaseTexture(texture);
  8003. }
  8004. };
  8005. // Dispose
  8006. Engine.prototype.dispose = function () {
  8007. this.hideLoadingUI();
  8008. this.stopRenderLoop();
  8009. // Release scenes
  8010. while (this.scenes.length) {
  8011. this.scenes[0].dispose();
  8012. }
  8013. // Release audio engine
  8014. Engine.audioEngine.dispose();
  8015. // Release effects
  8016. for (var name in this._compiledEffects) {
  8017. this._gl.deleteProgram(this._compiledEffects[name]._program);
  8018. }
  8019. // Unbind
  8020. if (this._vertexAttribArraysEnabled) {
  8021. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  8022. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArraysEnabled[i]) {
  8023. continue;
  8024. }
  8025. this._gl.disableVertexAttribArray(i);
  8026. }
  8027. }
  8028. this._gl = null;
  8029. // Events
  8030. window.removeEventListener("blur", this._onBlur);
  8031. window.removeEventListener("focus", this._onFocus);
  8032. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  8033. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  8034. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  8035. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  8036. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  8037. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  8038. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  8039. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  8040. };
  8041. // Loading screen
  8042. Engine.prototype.displayLoadingUI = function () {
  8043. this._loadingScreen.displayLoadingUI();
  8044. };
  8045. Engine.prototype.hideLoadingUI = function () {
  8046. this._loadingScreen.hideLoadingUI();
  8047. };
  8048. Object.defineProperty(Engine.prototype, "loadingScreen", {
  8049. get: function () {
  8050. return this._loadingScreen;
  8051. },
  8052. set: function (loadingScreen) {
  8053. this._loadingScreen = loadingScreen;
  8054. },
  8055. enumerable: true,
  8056. configurable: true
  8057. });
  8058. Object.defineProperty(Engine.prototype, "loadingUIText", {
  8059. set: function (text) {
  8060. this._loadingScreen.loadingUIText = text;
  8061. },
  8062. enumerable: true,
  8063. configurable: true
  8064. });
  8065. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  8066. set: function (color) {
  8067. this._loadingScreen.loadingUIBackgroundColor = color;
  8068. },
  8069. enumerable: true,
  8070. configurable: true
  8071. });
  8072. Engine.prototype.attachContextLostEvent = function (callback) {
  8073. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  8074. };
  8075. Engine.prototype.attachContextRestoredEvent = function (callback) {
  8076. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  8077. };
  8078. // FPS
  8079. Engine.prototype.getFps = function () {
  8080. return this.fps;
  8081. };
  8082. Engine.prototype.getDeltaTime = function () {
  8083. return this.deltaTime;
  8084. };
  8085. Engine.prototype._measureFps = function () {
  8086. this.previousFramesDuration.push(BABYLON.Tools.Now);
  8087. var length = this.previousFramesDuration.length;
  8088. if (length >= 2) {
  8089. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  8090. }
  8091. if (length >= this.fpsRange) {
  8092. if (length > this.fpsRange) {
  8093. this.previousFramesDuration.splice(0, 1);
  8094. length = this.previousFramesDuration.length;
  8095. }
  8096. var sum = 0;
  8097. for (var id = 0; id < length - 1; id++) {
  8098. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  8099. }
  8100. this.fps = 1000.0 / (sum / (length - 1));
  8101. }
  8102. };
  8103. Engine.prototype._canRenderToFloatTexture = function () {
  8104. return this._canRenderToTextureOfType(BABYLON.Engine.TEXTURETYPE_FLOAT, 'OES_texture_float');
  8105. };
  8106. Engine.prototype._canRenderToHalfFloatTexture = function () {
  8107. return this._canRenderToTextureOfType(BABYLON.Engine.TEXTURETYPE_HALF_FLOAT, 'OES_texture_half_float');
  8108. };
  8109. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  8110. Engine.prototype._canRenderToTextureOfType = function (format, extension) {
  8111. var tempcanvas = document.createElement("canvas");
  8112. tempcanvas.height = 16;
  8113. tempcanvas.width = 16;
  8114. var gl = (tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl"));
  8115. // extension.
  8116. var ext = gl.getExtension(extension);
  8117. if (!ext) {
  8118. return false;
  8119. }
  8120. // setup GLSL program
  8121. var vertexCode = "attribute vec4 a_position;\n void main() {\n gl_Position = a_position;\n }";
  8122. var fragmentCode = "precision mediump float;\n uniform vec4 u_color;\n uniform sampler2D u_texture;\n\n void main() {\n gl_FragColor = texture2D(u_texture, vec2(0.5, 0.5)) * u_color;\n }";
  8123. var program = this.createShaderProgram(vertexCode, fragmentCode, null, gl);
  8124. gl.useProgram(program);
  8125. // look up where the vertex data needs to go.
  8126. var positionLocation = gl.getAttribLocation(program, "a_position");
  8127. var colorLoc = gl.getUniformLocation(program, "u_color");
  8128. // provide texture coordinates for the rectangle.
  8129. var positionBuffer = gl.createBuffer();
  8130. gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);
  8131. gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([
  8132. -1.0, -1.0,
  8133. 1.0, -1.0,
  8134. -1.0, 1.0,
  8135. -1.0, 1.0,
  8136. 1.0, -1.0,
  8137. 1.0, 1.0]), gl.STATIC_DRAW);
  8138. gl.enableVertexAttribArray(positionLocation);
  8139. gl.vertexAttribPointer(positionLocation, 2, gl.FLOAT, false, 0, 0);
  8140. var whiteTex = gl.createTexture();
  8141. gl.bindTexture(gl.TEXTURE_2D, whiteTex);
  8142. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, new Uint8Array([255, 255, 255, 255]));
  8143. var tex = gl.createTexture();
  8144. gl.bindTexture(gl.TEXTURE_2D, tex);
  8145. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 1, 1, 0, gl.RGBA, getWebGLTextureType(gl, format), null);
  8146. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  8147. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  8148. var fb = gl.createFramebuffer();
  8149. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  8150. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, tex, 0);
  8151. var cleanup = function () {
  8152. gl.deleteProgram(program);
  8153. gl.disableVertexAttribArray(positionLocation);
  8154. gl.deleteBuffer(positionBuffer);
  8155. gl.deleteFramebuffer(fb);
  8156. gl.deleteTexture(whiteTex);
  8157. gl.deleteTexture(tex);
  8158. };
  8159. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  8160. if (status !== gl.FRAMEBUFFER_COMPLETE) {
  8161. BABYLON.Tools.Log("GL Support: can **NOT** render to " + format + " texture");
  8162. cleanup();
  8163. return false;
  8164. }
  8165. // Draw the rectangle.
  8166. gl.bindTexture(gl.TEXTURE_2D, whiteTex);
  8167. gl.uniform4fv(colorLoc, [0, 10, 20, 1]);
  8168. gl.drawArrays(gl.TRIANGLES, 0, 6);
  8169. gl.bindTexture(gl.TEXTURE_2D, tex);
  8170. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  8171. gl.clearColor(1, 0, 0, 1);
  8172. gl.clear(gl.COLOR_BUFFER_BIT);
  8173. gl.uniform4fv(colorLoc, [0, 1 / 10, 1 / 20, 1]);
  8174. gl.drawArrays(gl.TRIANGLES, 0, 6);
  8175. var pixel = new Uint8Array(4);
  8176. gl.readPixels(0, 0, 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, pixel);
  8177. if (pixel[0] !== 0 ||
  8178. pixel[1] < 248 ||
  8179. pixel[2] < 248 ||
  8180. pixel[3] < 254) {
  8181. BABYLON.Tools.Log("GL Support: Was not able to actually render to " + format + " texture");
  8182. cleanup();
  8183. return false;
  8184. }
  8185. // Succesfully rendered to "format" texture.
  8186. cleanup();
  8187. return true;
  8188. };
  8189. // Statics
  8190. Engine.isSupported = function () {
  8191. try {
  8192. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  8193. if (navigator.isCocoonJS) {
  8194. return true;
  8195. }
  8196. var tempcanvas = document.createElement("canvas");
  8197. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  8198. return gl != null && !!window.WebGLRenderingContext;
  8199. }
  8200. catch (e) {
  8201. return false;
  8202. }
  8203. };
  8204. // Const statics
  8205. Engine._ALPHA_DISABLE = 0;
  8206. Engine._ALPHA_ADD = 1;
  8207. Engine._ALPHA_COMBINE = 2;
  8208. Engine._ALPHA_SUBTRACT = 3;
  8209. Engine._ALPHA_MULTIPLY = 4;
  8210. Engine._ALPHA_MAXIMIZED = 5;
  8211. Engine._ALPHA_ONEONE = 6;
  8212. Engine._DELAYLOADSTATE_NONE = 0;
  8213. Engine._DELAYLOADSTATE_LOADED = 1;
  8214. Engine._DELAYLOADSTATE_LOADING = 2;
  8215. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  8216. Engine._TEXTUREFORMAT_ALPHA = 0;
  8217. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  8218. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  8219. Engine._TEXTUREFORMAT_RGB = 4;
  8220. Engine._TEXTUREFORMAT_RGBA = 5;
  8221. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  8222. Engine._TEXTURETYPE_FLOAT = 1;
  8223. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  8224. // Updatable statics so stick with vars here
  8225. Engine.CollisionsEpsilon = 0.001;
  8226. Engine.CodeRepository = "src/";
  8227. Engine.ShadersRepository = "src/Shaders/";
  8228. return Engine;
  8229. }());
  8230. BABYLON.Engine = Engine;
  8231. })(BABYLON || (BABYLON = {}));
  8232. var BABYLON;
  8233. (function (BABYLON) {
  8234. /**
  8235. * Node is the basic class for all scene objects (Mesh, Light Camera).
  8236. */
  8237. var Node = (function () {
  8238. /**
  8239. * @constructor
  8240. * @param {string} name - the name and id to be given to this node
  8241. * @param {BABYLON.Scene} the scene this node will be added to
  8242. */
  8243. function Node(name, scene) {
  8244. this.state = "";
  8245. this.animations = new Array();
  8246. this._ranges = {};
  8247. this._childrenFlag = -1;
  8248. this._isEnabled = true;
  8249. this._isReady = true;
  8250. this._currentRenderId = -1;
  8251. this._parentRenderId = -1;
  8252. this.name = name;
  8253. this.id = name;
  8254. this._scene = scene;
  8255. this._initCache();
  8256. }
  8257. Object.defineProperty(Node.prototype, "parent", {
  8258. get: function () {
  8259. return this._parentNode;
  8260. },
  8261. set: function (parent) {
  8262. if (this._parentNode === parent) {
  8263. return;
  8264. }
  8265. if (this._parentNode) {
  8266. var index = this._parentNode._children.indexOf(this);
  8267. if (index !== -1) {
  8268. this._parentNode._children.splice(index, 1);
  8269. }
  8270. }
  8271. this._parentNode = parent;
  8272. if (this._parentNode) {
  8273. if (!this._parentNode._children) {
  8274. this._parentNode._children = new Array();
  8275. }
  8276. this._parentNode._children.push(this);
  8277. }
  8278. },
  8279. enumerable: true,
  8280. configurable: true
  8281. });
  8282. Node.prototype.getScene = function () {
  8283. return this._scene;
  8284. };
  8285. Node.prototype.getEngine = function () {
  8286. return this._scene.getEngine();
  8287. };
  8288. // override it in derived class
  8289. Node.prototype.getWorldMatrix = function () {
  8290. return BABYLON.Matrix.Identity();
  8291. };
  8292. // override it in derived class if you add new variables to the cache
  8293. // and call the parent class method
  8294. Node.prototype._initCache = function () {
  8295. this._cache = {};
  8296. this._cache.parent = undefined;
  8297. };
  8298. Node.prototype.updateCache = function (force) {
  8299. if (!force && this.isSynchronized())
  8300. return;
  8301. this._cache.parent = this.parent;
  8302. this._updateCache();
  8303. };
  8304. // override it in derived class if you add new variables to the cache
  8305. // and call the parent class method if !ignoreParentClass
  8306. Node.prototype._updateCache = function (ignoreParentClass) {
  8307. };
  8308. // override it in derived class if you add new variables to the cache
  8309. Node.prototype._isSynchronized = function () {
  8310. return true;
  8311. };
  8312. Node.prototype._markSyncedWithParent = function () {
  8313. this._parentRenderId = this.parent._currentRenderId;
  8314. };
  8315. Node.prototype.isSynchronizedWithParent = function () {
  8316. if (!this.parent) {
  8317. return true;
  8318. }
  8319. if (this._parentRenderId !== this.parent._currentRenderId) {
  8320. return false;
  8321. }
  8322. return this.parent.isSynchronized();
  8323. };
  8324. Node.prototype.isSynchronized = function (updateCache) {
  8325. var check = this.hasNewParent();
  8326. check = check || !this.isSynchronizedWithParent();
  8327. check = check || !this._isSynchronized();
  8328. if (updateCache)
  8329. this.updateCache(true);
  8330. return !check;
  8331. };
  8332. Node.prototype.hasNewParent = function (update) {
  8333. if (this._cache.parent === this.parent)
  8334. return false;
  8335. if (update)
  8336. this._cache.parent = this.parent;
  8337. return true;
  8338. };
  8339. /**
  8340. * Is this node ready to be used/rendered
  8341. * @return {boolean} is it ready
  8342. */
  8343. Node.prototype.isReady = function () {
  8344. return this._isReady;
  8345. };
  8346. /**
  8347. * Is this node enabled.
  8348. * If the node has a parent and is enabled, the parent will be inspected as well.
  8349. * @return {boolean} whether this node (and its parent) is enabled.
  8350. * @see setEnabled
  8351. */
  8352. Node.prototype.isEnabled = function () {
  8353. if (!this._isEnabled) {
  8354. return false;
  8355. }
  8356. if (this.parent) {
  8357. return this.parent.isEnabled();
  8358. }
  8359. return true;
  8360. };
  8361. /**
  8362. * Set the enabled state of this node.
  8363. * @param {boolean} value - the new enabled state
  8364. * @see isEnabled
  8365. */
  8366. Node.prototype.setEnabled = function (value) {
  8367. this._isEnabled = value;
  8368. };
  8369. /**
  8370. * Is this node a descendant of the given node.
  8371. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  8372. * @param {BABYLON.Node} ancestor - The parent node to inspect
  8373. * @see parent
  8374. */
  8375. Node.prototype.isDescendantOf = function (ancestor) {
  8376. if (this.parent) {
  8377. if (this.parent === ancestor) {
  8378. return true;
  8379. }
  8380. return this.parent.isDescendantOf(ancestor);
  8381. }
  8382. return false;
  8383. };
  8384. /**
  8385. * Evaluate the list of children and determine if they should be considered as descendants considering the given criterias
  8386. * @param {BABYLON.Node[]} results the result array containing the nodes matching the given criterias
  8387. * @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.
  8388. * @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.
  8389. */
  8390. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  8391. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  8392. if (!this._children) {
  8393. return;
  8394. }
  8395. for (var index = 0; index < this._children.length; index++) {
  8396. var item = this._children[index];
  8397. if (!predicate || predicate(item)) {
  8398. results.push(item);
  8399. }
  8400. if (!directDescendantsOnly) {
  8401. item._getDescendants(results, false, predicate);
  8402. }
  8403. }
  8404. };
  8405. /**
  8406. * Will return all nodes that have this node as ascendant.
  8407. * @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.
  8408. * @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.
  8409. * @return {BABYLON.Node[]} all children nodes of all types.
  8410. */
  8411. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  8412. var results = [];
  8413. this._getDescendants(results, directDescendantsOnly, predicate);
  8414. return results;
  8415. };
  8416. /**
  8417. * @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.
  8418. * @Deprecated, legacy support.
  8419. * use getDecendants instead.
  8420. */
  8421. Node.prototype.getChildren = function (predicate) {
  8422. return this.getDescendants(true, predicate);
  8423. };
  8424. /**
  8425. * Get all child-meshes of this node.
  8426. */
  8427. Node.prototype.getChildMeshes = function (directDecendantsOnly, predicate) {
  8428. var results = [];
  8429. this._getDescendants(results, directDecendantsOnly, function (node) {
  8430. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  8431. });
  8432. return results;
  8433. };
  8434. Node.prototype._setReady = function (state) {
  8435. if (state === this._isReady) {
  8436. return;
  8437. }
  8438. if (!state) {
  8439. this._isReady = false;
  8440. return;
  8441. }
  8442. this._isReady = true;
  8443. if (this.onReady) {
  8444. this.onReady(this);
  8445. }
  8446. };
  8447. Node.prototype.getAnimationByName = function (name) {
  8448. for (var i = 0; i < this.animations.length; i++) {
  8449. var animation = this.animations[i];
  8450. if (animation.name === name) {
  8451. return animation;
  8452. }
  8453. }
  8454. return null;
  8455. };
  8456. Node.prototype.createAnimationRange = function (name, from, to) {
  8457. // check name not already in use
  8458. if (!this._ranges[name]) {
  8459. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  8460. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  8461. if (this.animations[i]) {
  8462. this.animations[i].createRange(name, from, to);
  8463. }
  8464. }
  8465. }
  8466. };
  8467. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  8468. if (deleteFrames === void 0) { deleteFrames = true; }
  8469. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  8470. if (this.animations[i]) {
  8471. this.animations[i].deleteRange(name, deleteFrames);
  8472. }
  8473. }
  8474. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  8475. };
  8476. Node.prototype.getAnimationRange = function (name) {
  8477. return this._ranges[name];
  8478. };
  8479. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  8480. var range = this.getAnimationRange(name);
  8481. if (!range) {
  8482. return null;
  8483. }
  8484. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  8485. };
  8486. Node.prototype.serializeAnimationRanges = function () {
  8487. var serializationRanges = [];
  8488. for (var name in this._ranges) {
  8489. var range = {};
  8490. range.name = name;
  8491. range.from = this._ranges[name].from;
  8492. range.to = this._ranges[name].to;
  8493. serializationRanges.push(range);
  8494. }
  8495. return serializationRanges;
  8496. };
  8497. Node.prototype.dispose = function () {
  8498. this.parent = null;
  8499. };
  8500. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  8501. if (parsedNode.ranges) {
  8502. for (var index = 0; index < parsedNode.ranges.length; index++) {
  8503. var data = parsedNode.ranges[index];
  8504. node.createAnimationRange(data.name, data.from, data.to);
  8505. }
  8506. }
  8507. };
  8508. __decorate([
  8509. BABYLON.serialize()
  8510. ], Node.prototype, "name", void 0);
  8511. __decorate([
  8512. BABYLON.serialize()
  8513. ], Node.prototype, "id", void 0);
  8514. __decorate([
  8515. BABYLON.serialize()
  8516. ], Node.prototype, "uniqueId", void 0);
  8517. __decorate([
  8518. BABYLON.serialize()
  8519. ], Node.prototype, "state", void 0);
  8520. return Node;
  8521. }());
  8522. BABYLON.Node = Node;
  8523. })(BABYLON || (BABYLON = {}));
  8524. var BABYLON;
  8525. (function (BABYLON) {
  8526. var FilesInput = (function () {
  8527. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  8528. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  8529. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  8530. this._engine = p_engine;
  8531. this._canvas = p_canvas;
  8532. this._currentScene = p_scene;
  8533. this._sceneLoadedCallback = p_sceneLoadedCallback;
  8534. this._progressCallback = p_progressCallback;
  8535. this._additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  8536. this._textureLoadingCallback = p_textureLoadingCallback;
  8537. this._startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  8538. }
  8539. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  8540. var _this = this;
  8541. if (p_elementToMonitor) {
  8542. this._elementToMonitor = p_elementToMonitor;
  8543. this._elementToMonitor.addEventListener("dragenter", function (e) { _this.drag(e); }, false);
  8544. this._elementToMonitor.addEventListener("dragover", function (e) { _this.drag(e); }, false);
  8545. this._elementToMonitor.addEventListener("drop", function (e) { _this.drop(e); }, false);
  8546. }
  8547. };
  8548. FilesInput.prototype.renderFunction = function () {
  8549. if (this._additionnalRenderLoopLogicCallback) {
  8550. this._additionnalRenderLoopLogicCallback();
  8551. }
  8552. if (this._currentScene) {
  8553. if (this._textureLoadingCallback) {
  8554. var remaining = this._currentScene.getWaitingItemsCount();
  8555. if (remaining > 0) {
  8556. this._textureLoadingCallback(remaining);
  8557. }
  8558. }
  8559. this._currentScene.render();
  8560. }
  8561. };
  8562. FilesInput.prototype.drag = function (e) {
  8563. e.stopPropagation();
  8564. e.preventDefault();
  8565. };
  8566. FilesInput.prototype.drop = function (eventDrop) {
  8567. eventDrop.stopPropagation();
  8568. eventDrop.preventDefault();
  8569. this.loadFiles(eventDrop);
  8570. };
  8571. FilesInput.prototype.loadFiles = function (event) {
  8572. if (this._startingProcessingFilesCallback)
  8573. this._startingProcessingFilesCallback();
  8574. // Handling data transfer via drag'n'drop
  8575. if (event && event.dataTransfer && event.dataTransfer.files) {
  8576. this._filesToLoad = event.dataTransfer.files;
  8577. }
  8578. // Handling files from input files
  8579. if (event && event.target && event.target.files) {
  8580. this._filesToLoad = event.target.files;
  8581. }
  8582. if (this._filesToLoad && this._filesToLoad.length > 0) {
  8583. for (var i = 0; i < this._filesToLoad.length; i++) {
  8584. switch (this._filesToLoad[i].type) {
  8585. case "image/jpeg":
  8586. case "image/png":
  8587. case "image/bmp":
  8588. FilesInput.FilesTextures[this._filesToLoad[i].name.toLowerCase()] = this._filesToLoad[i];
  8589. break;
  8590. case "image/targa":
  8591. case "image/vnd.ms-dds":
  8592. case "audio/wav":
  8593. case "audio/x-wav":
  8594. case "audio/mp3":
  8595. case "audio/mpeg":
  8596. case "audio/mpeg3":
  8597. case "audio/x-mpeg-3":
  8598. case "audio/ogg":
  8599. FilesInput.FilesToLoad[this._filesToLoad[i].name.toLowerCase()] = this._filesToLoad[i];
  8600. break;
  8601. default:
  8602. if (this._filesToLoad[i].name.indexOf(".mtl") !== -1) {
  8603. FilesInput.FilesToLoad[this._filesToLoad[i].name.toLowerCase()] = this._filesToLoad[i];
  8604. }
  8605. else if ((this._filesToLoad[i].name.indexOf(".babylon") !== -1 ||
  8606. this._filesToLoad[i].name.indexOf(".stl") !== -1 ||
  8607. this._filesToLoad[i].name.indexOf(".obj") !== -1)
  8608. && this._filesToLoad[i].name.indexOf(".manifest") === -1
  8609. && this._filesToLoad[i].name.indexOf(".incremental") === -1 && this._filesToLoad[i].name.indexOf(".babylonmeshdata") === -1
  8610. && this._filesToLoad[i].name.indexOf(".babylongeometrydata") === -1 && this._filesToLoad[i].name.indexOf(".babylonbinarymeshdata") === -1 &&
  8611. this._filesToLoad[i].name.indexOf(".binary.babylon") === -1) {
  8612. this._sceneFileToLoad = this._filesToLoad[i];
  8613. }
  8614. break;
  8615. }
  8616. }
  8617. this.reload();
  8618. }
  8619. };
  8620. FilesInput.prototype.reload = function () {
  8621. var _this = this;
  8622. var that = this;
  8623. // If a ".babylon" file has been provided
  8624. if (this._sceneFileToLoad) {
  8625. if (this._currentScene) {
  8626. if (BABYLON.Tools.errorsCount > 0) {
  8627. BABYLON.Tools.ClearLogCache();
  8628. BABYLON.Tools.Log("Babylon.js engine (v" + BABYLON.Engine.Version + ") launched");
  8629. }
  8630. this._engine.stopRenderLoop();
  8631. this._currentScene.dispose();
  8632. }
  8633. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  8634. that._currentScene = newScene;
  8635. // Wait for textures and shaders to be ready
  8636. that._currentScene.executeWhenReady(function () {
  8637. // Attach camera to canvas inputs
  8638. if (!that._currentScene.activeCamera || that._currentScene.lights.length === 0) {
  8639. that._currentScene.createDefaultCameraOrLight();
  8640. }
  8641. that._currentScene.activeCamera.attachControl(that._canvas);
  8642. if (that._sceneLoadedCallback) {
  8643. that._sceneLoadedCallback(_this._sceneFileToLoad, that._currentScene);
  8644. }
  8645. that._engine.runRenderLoop(function () { that.renderFunction(); });
  8646. });
  8647. }, function (progress) {
  8648. if (_this._progressCallback) {
  8649. _this._progressCallback(progress);
  8650. }
  8651. });
  8652. }
  8653. else {
  8654. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  8655. }
  8656. };
  8657. FilesInput.FilesTextures = new Array();
  8658. FilesInput.FilesToLoad = new Array();
  8659. return FilesInput;
  8660. }());
  8661. BABYLON.FilesInput = FilesInput;
  8662. })(BABYLON || (BABYLON = {}));
  8663. var BABYLON;
  8664. (function (BABYLON) {
  8665. var IntersectionInfo = (function () {
  8666. function IntersectionInfo(bu, bv, distance) {
  8667. this.bu = bu;
  8668. this.bv = bv;
  8669. this.distance = distance;
  8670. this.faceId = 0;
  8671. this.subMeshId = 0;
  8672. }
  8673. return IntersectionInfo;
  8674. }());
  8675. BABYLON.IntersectionInfo = IntersectionInfo;
  8676. var PickingInfo = (function () {
  8677. function PickingInfo() {
  8678. this.hit = false;
  8679. this.distance = 0;
  8680. this.pickedPoint = null;
  8681. this.pickedMesh = null;
  8682. this.bu = 0;
  8683. this.bv = 0;
  8684. this.faceId = -1;
  8685. this.subMeshId = 0;
  8686. this.pickedSprite = null;
  8687. }
  8688. // Methods
  8689. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  8690. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  8691. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  8692. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  8693. return null;
  8694. }
  8695. var indices = this.pickedMesh.getIndices();
  8696. var result;
  8697. if (useVerticesNormals) {
  8698. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  8699. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  8700. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  8701. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  8702. normal0 = normal0.scale(this.bu);
  8703. normal1 = normal1.scale(this.bv);
  8704. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  8705. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  8706. }
  8707. else {
  8708. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  8709. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  8710. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  8711. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  8712. var p1p2 = vertex1.subtract(vertex2);
  8713. var p3p2 = vertex3.subtract(vertex2);
  8714. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  8715. }
  8716. if (useWorldCoordinates) {
  8717. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  8718. }
  8719. return BABYLON.Vector3.Normalize(result);
  8720. };
  8721. PickingInfo.prototype.getTextureCoordinates = function () {
  8722. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  8723. return null;
  8724. }
  8725. var indices = this.pickedMesh.getIndices();
  8726. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  8727. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  8728. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  8729. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  8730. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  8731. uv1 = uv1.scale(this.bu);
  8732. uv2 = uv2.scale(this.bv);
  8733. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  8734. };
  8735. return PickingInfo;
  8736. }());
  8737. BABYLON.PickingInfo = PickingInfo;
  8738. })(BABYLON || (BABYLON = {}));
  8739. var BABYLON;
  8740. (function (BABYLON) {
  8741. var BoundingSphere = (function () {
  8742. function BoundingSphere(minimum, maximum) {
  8743. this.minimum = minimum;
  8744. this.maximum = maximum;
  8745. this._tempRadiusVector = BABYLON.Vector3.Zero();
  8746. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  8747. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  8748. this.radius = distance * 0.5;
  8749. this.centerWorld = BABYLON.Vector3.Zero();
  8750. this._update(BABYLON.Matrix.Identity());
  8751. }
  8752. // Methods
  8753. BoundingSphere.prototype._update = function (world) {
  8754. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  8755. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  8756. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  8757. };
  8758. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  8759. for (var i = 0; i < 6; i++) {
  8760. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  8761. return false;
  8762. }
  8763. return true;
  8764. };
  8765. BoundingSphere.prototype.intersectsPoint = function (point) {
  8766. var x = this.centerWorld.x - point.x;
  8767. var y = this.centerWorld.y - point.y;
  8768. var z = this.centerWorld.z - point.z;
  8769. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  8770. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  8771. return false;
  8772. return true;
  8773. };
  8774. // Statics
  8775. BoundingSphere.Intersects = function (sphere0, sphere1) {
  8776. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  8777. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  8778. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  8779. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  8780. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  8781. return false;
  8782. return true;
  8783. };
  8784. return BoundingSphere;
  8785. }());
  8786. BABYLON.BoundingSphere = BoundingSphere;
  8787. })(BABYLON || (BABYLON = {}));
  8788. var BABYLON;
  8789. (function (BABYLON) {
  8790. var BoundingBox = (function () {
  8791. function BoundingBox(minimum, maximum) {
  8792. this.minimum = minimum;
  8793. this.maximum = maximum;
  8794. this.vectors = new Array();
  8795. this.vectorsWorld = new Array();
  8796. // Bounding vectors
  8797. this.vectors.push(this.minimum.clone());
  8798. this.vectors.push(this.maximum.clone());
  8799. this.vectors.push(this.minimum.clone());
  8800. this.vectors[2].x = this.maximum.x;
  8801. this.vectors.push(this.minimum.clone());
  8802. this.vectors[3].y = this.maximum.y;
  8803. this.vectors.push(this.minimum.clone());
  8804. this.vectors[4].z = this.maximum.z;
  8805. this.vectors.push(this.maximum.clone());
  8806. this.vectors[5].z = this.minimum.z;
  8807. this.vectors.push(this.maximum.clone());
  8808. this.vectors[6].x = this.minimum.x;
  8809. this.vectors.push(this.maximum.clone());
  8810. this.vectors[7].y = this.minimum.y;
  8811. // OBB
  8812. this.center = this.maximum.add(this.minimum).scale(0.5);
  8813. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  8814. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  8815. // World
  8816. for (var index = 0; index < this.vectors.length; index++) {
  8817. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  8818. }
  8819. this.minimumWorld = BABYLON.Vector3.Zero();
  8820. this.maximumWorld = BABYLON.Vector3.Zero();
  8821. this._update(BABYLON.Matrix.Identity());
  8822. }
  8823. // Methods
  8824. BoundingBox.prototype.getWorldMatrix = function () {
  8825. return this._worldMatrix;
  8826. };
  8827. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  8828. this._worldMatrix.copyFrom(matrix);
  8829. return this;
  8830. };
  8831. BoundingBox.prototype._update = function (world) {
  8832. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  8833. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  8834. for (var index = 0; index < this.vectors.length; index++) {
  8835. var v = this.vectorsWorld[index];
  8836. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  8837. if (v.x < this.minimumWorld.x)
  8838. this.minimumWorld.x = v.x;
  8839. if (v.y < this.minimumWorld.y)
  8840. this.minimumWorld.y = v.y;
  8841. if (v.z < this.minimumWorld.z)
  8842. this.minimumWorld.z = v.z;
  8843. if (v.x > this.maximumWorld.x)
  8844. this.maximumWorld.x = v.x;
  8845. if (v.y > this.maximumWorld.y)
  8846. this.maximumWorld.y = v.y;
  8847. if (v.z > this.maximumWorld.z)
  8848. this.maximumWorld.z = v.z;
  8849. }
  8850. // OBB
  8851. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  8852. this.center.scaleInPlace(0.5);
  8853. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  8854. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  8855. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  8856. this._worldMatrix = world;
  8857. };
  8858. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  8859. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  8860. };
  8861. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  8862. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  8863. };
  8864. BoundingBox.prototype.intersectsPoint = function (point) {
  8865. var delta = -BABYLON.Epsilon;
  8866. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  8867. return false;
  8868. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  8869. return false;
  8870. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  8871. return false;
  8872. return true;
  8873. };
  8874. BoundingBox.prototype.intersectsSphere = function (sphere) {
  8875. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  8876. };
  8877. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  8878. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  8879. return false;
  8880. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  8881. return false;
  8882. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  8883. return false;
  8884. return true;
  8885. };
  8886. // Statics
  8887. BoundingBox.Intersects = function (box0, box1) {
  8888. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  8889. return false;
  8890. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  8891. return false;
  8892. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  8893. return false;
  8894. return true;
  8895. };
  8896. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  8897. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  8898. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  8899. return (num <= (sphereRadius * sphereRadius));
  8900. };
  8901. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  8902. for (var p = 0; p < 6; p++) {
  8903. for (var i = 0; i < 8; i++) {
  8904. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  8905. return false;
  8906. }
  8907. }
  8908. }
  8909. return true;
  8910. };
  8911. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  8912. for (var p = 0; p < 6; p++) {
  8913. var inCount = 8;
  8914. for (var i = 0; i < 8; i++) {
  8915. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  8916. --inCount;
  8917. }
  8918. else {
  8919. break;
  8920. }
  8921. }
  8922. if (inCount === 0)
  8923. return false;
  8924. }
  8925. return true;
  8926. };
  8927. return BoundingBox;
  8928. }());
  8929. BABYLON.BoundingBox = BoundingBox;
  8930. })(BABYLON || (BABYLON = {}));
  8931. var BABYLON;
  8932. (function (BABYLON) {
  8933. var computeBoxExtents = function (axis, box) {
  8934. var p = BABYLON.Vector3.Dot(box.center, axis);
  8935. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  8936. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  8937. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  8938. var r = r0 + r1 + r2;
  8939. return {
  8940. min: p - r,
  8941. max: p + r
  8942. };
  8943. };
  8944. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  8945. var axisOverlap = function (axis, box0, box1) {
  8946. var result0 = computeBoxExtents(axis, box0);
  8947. var result1 = computeBoxExtents(axis, box1);
  8948. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  8949. };
  8950. var BoundingInfo = (function () {
  8951. function BoundingInfo(minimum, maximum) {
  8952. this.minimum = minimum;
  8953. this.maximum = maximum;
  8954. this._isLocked = false;
  8955. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  8956. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  8957. }
  8958. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  8959. get: function () {
  8960. return this._isLocked;
  8961. },
  8962. set: function (value) {
  8963. this._isLocked = value;
  8964. },
  8965. enumerable: true,
  8966. configurable: true
  8967. });
  8968. // Methods
  8969. BoundingInfo.prototype.update = function (world) {
  8970. if (this._isLocked) {
  8971. return;
  8972. }
  8973. this.boundingBox._update(world);
  8974. this.boundingSphere._update(world);
  8975. };
  8976. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  8977. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  8978. return false;
  8979. return this.boundingBox.isInFrustum(frustumPlanes);
  8980. };
  8981. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  8982. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  8983. };
  8984. BoundingInfo.prototype._checkCollision = function (collider) {
  8985. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  8986. };
  8987. BoundingInfo.prototype.intersectsPoint = function (point) {
  8988. if (!this.boundingSphere.centerWorld) {
  8989. return false;
  8990. }
  8991. if (!this.boundingSphere.intersectsPoint(point)) {
  8992. return false;
  8993. }
  8994. if (!this.boundingBox.intersectsPoint(point)) {
  8995. return false;
  8996. }
  8997. return true;
  8998. };
  8999. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  9000. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  9001. return false;
  9002. }
  9003. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  9004. return false;
  9005. }
  9006. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  9007. return false;
  9008. }
  9009. if (!precise) {
  9010. return true;
  9011. }
  9012. var box0 = this.boundingBox;
  9013. var box1 = boundingInfo.boundingBox;
  9014. if (!axisOverlap(box0.directions[0], box0, box1))
  9015. return false;
  9016. if (!axisOverlap(box0.directions[1], box0, box1))
  9017. return false;
  9018. if (!axisOverlap(box0.directions[2], box0, box1))
  9019. return false;
  9020. if (!axisOverlap(box1.directions[0], box0, box1))
  9021. return false;
  9022. if (!axisOverlap(box1.directions[1], box0, box1))
  9023. return false;
  9024. if (!axisOverlap(box1.directions[2], box0, box1))
  9025. return false;
  9026. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  9027. return false;
  9028. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  9029. return false;
  9030. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  9031. return false;
  9032. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  9033. return false;
  9034. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  9035. return false;
  9036. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  9037. return false;
  9038. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  9039. return false;
  9040. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  9041. return false;
  9042. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  9043. return false;
  9044. return true;
  9045. };
  9046. return BoundingInfo;
  9047. }());
  9048. BABYLON.BoundingInfo = BoundingInfo;
  9049. })(BABYLON || (BABYLON = {}));
  9050. var BABYLON;
  9051. (function (BABYLON) {
  9052. var Ray = (function () {
  9053. function Ray(origin, direction, length) {
  9054. if (length === void 0) { length = Number.MAX_VALUE; }
  9055. this.origin = origin;
  9056. this.direction = direction;
  9057. this.length = length;
  9058. }
  9059. // Methods
  9060. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  9061. var d = 0.0;
  9062. var maxValue = Number.MAX_VALUE;
  9063. var inv;
  9064. var min;
  9065. var max;
  9066. var temp;
  9067. if (Math.abs(this.direction.x) < 0.0000001) {
  9068. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  9069. return false;
  9070. }
  9071. }
  9072. else {
  9073. inv = 1.0 / this.direction.x;
  9074. min = (minimum.x - this.origin.x) * inv;
  9075. max = (maximum.x - this.origin.x) * inv;
  9076. if (max === -Infinity) {
  9077. max = Infinity;
  9078. }
  9079. if (min > max) {
  9080. temp = min;
  9081. min = max;
  9082. max = temp;
  9083. }
  9084. d = Math.max(min, d);
  9085. maxValue = Math.min(max, maxValue);
  9086. if (d > maxValue) {
  9087. return false;
  9088. }
  9089. }
  9090. if (Math.abs(this.direction.y) < 0.0000001) {
  9091. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  9092. return false;
  9093. }
  9094. }
  9095. else {
  9096. inv = 1.0 / this.direction.y;
  9097. min = (minimum.y - this.origin.y) * inv;
  9098. max = (maximum.y - this.origin.y) * inv;
  9099. if (max === -Infinity) {
  9100. max = Infinity;
  9101. }
  9102. if (min > max) {
  9103. temp = min;
  9104. min = max;
  9105. max = temp;
  9106. }
  9107. d = Math.max(min, d);
  9108. maxValue = Math.min(max, maxValue);
  9109. if (d > maxValue) {
  9110. return false;
  9111. }
  9112. }
  9113. if (Math.abs(this.direction.z) < 0.0000001) {
  9114. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  9115. return false;
  9116. }
  9117. }
  9118. else {
  9119. inv = 1.0 / this.direction.z;
  9120. min = (minimum.z - this.origin.z) * inv;
  9121. max = (maximum.z - this.origin.z) * inv;
  9122. if (max === -Infinity) {
  9123. max = Infinity;
  9124. }
  9125. if (min > max) {
  9126. temp = min;
  9127. min = max;
  9128. max = temp;
  9129. }
  9130. d = Math.max(min, d);
  9131. maxValue = Math.min(max, maxValue);
  9132. if (d > maxValue) {
  9133. return false;
  9134. }
  9135. }
  9136. return true;
  9137. };
  9138. Ray.prototype.intersectsBox = function (box) {
  9139. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  9140. };
  9141. Ray.prototype.intersectsSphere = function (sphere) {
  9142. var x = sphere.center.x - this.origin.x;
  9143. var y = sphere.center.y - this.origin.y;
  9144. var z = sphere.center.z - this.origin.z;
  9145. var pyth = (x * x) + (y * y) + (z * z);
  9146. var rr = sphere.radius * sphere.radius;
  9147. if (pyth <= rr) {
  9148. return true;
  9149. }
  9150. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  9151. if (dot < 0.0) {
  9152. return false;
  9153. }
  9154. var temp = pyth - (dot * dot);
  9155. return temp <= rr;
  9156. };
  9157. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  9158. if (!this._edge1) {
  9159. this._edge1 = BABYLON.Vector3.Zero();
  9160. this._edge2 = BABYLON.Vector3.Zero();
  9161. this._pvec = BABYLON.Vector3.Zero();
  9162. this._tvec = BABYLON.Vector3.Zero();
  9163. this._qvec = BABYLON.Vector3.Zero();
  9164. }
  9165. vertex1.subtractToRef(vertex0, this._edge1);
  9166. vertex2.subtractToRef(vertex0, this._edge2);
  9167. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  9168. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  9169. if (det === 0) {
  9170. return null;
  9171. }
  9172. var invdet = 1 / det;
  9173. this.origin.subtractToRef(vertex0, this._tvec);
  9174. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  9175. if (bu < 0 || bu > 1.0) {
  9176. return null;
  9177. }
  9178. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  9179. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  9180. if (bv < 0 || bu + bv > 1.0) {
  9181. return null;
  9182. }
  9183. //check if the distance is longer than the predefined length.
  9184. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  9185. if (distance > this.length) {
  9186. return null;
  9187. }
  9188. return new BABYLON.IntersectionInfo(bu, bv, distance);
  9189. };
  9190. Ray.prototype.intersectsPlane = function (plane) {
  9191. var distance;
  9192. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  9193. if (Math.abs(result1) < 9.99999997475243E-07) {
  9194. return null;
  9195. }
  9196. else {
  9197. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  9198. distance = (-plane.d - result2) / result1;
  9199. if (distance < 0.0) {
  9200. if (distance < -9.99999997475243E-07) {
  9201. return null;
  9202. }
  9203. else {
  9204. return 0;
  9205. }
  9206. }
  9207. return distance;
  9208. }
  9209. };
  9210. /**
  9211. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  9212. * @param sega the first point of the segment to test the intersection against
  9213. * @param segb the second point of the segment to test the intersection against
  9214. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  9215. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  9216. */
  9217. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  9218. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  9219. var u = segb.subtract(sega);
  9220. var v = rsegb.subtract(this.origin);
  9221. var w = sega.subtract(this.origin);
  9222. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  9223. var b = BABYLON.Vector3.Dot(u, v);
  9224. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  9225. var d = BABYLON.Vector3.Dot(u, w);
  9226. var e = BABYLON.Vector3.Dot(v, w);
  9227. var D = a * c - b * b; // always >= 0
  9228. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  9229. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  9230. // compute the line parameters of the two closest points
  9231. if (D < Ray.smallnum) {
  9232. sN = 0.0; // force using point P0 on segment S1
  9233. sD = 1.0; // to prevent possible division by 0.0 later
  9234. tN = e;
  9235. tD = c;
  9236. }
  9237. else {
  9238. sN = (b * e - c * d);
  9239. tN = (a * e - b * d);
  9240. if (sN < 0.0) {
  9241. sN = 0.0;
  9242. tN = e;
  9243. tD = c;
  9244. }
  9245. else if (sN > sD) {
  9246. sN = sD;
  9247. tN = e + b;
  9248. tD = c;
  9249. }
  9250. }
  9251. if (tN < 0.0) {
  9252. tN = 0.0;
  9253. // recompute sc for this edge
  9254. if (-d < 0.0) {
  9255. sN = 0.0;
  9256. }
  9257. else if (-d > a)
  9258. sN = sD;
  9259. else {
  9260. sN = -d;
  9261. sD = a;
  9262. }
  9263. }
  9264. else if (tN > tD) {
  9265. tN = tD;
  9266. // recompute sc for this edge
  9267. if ((-d + b) < 0.0) {
  9268. sN = 0;
  9269. }
  9270. else if ((-d + b) > a) {
  9271. sN = sD;
  9272. }
  9273. else {
  9274. sN = (-d + b);
  9275. sD = a;
  9276. }
  9277. }
  9278. // finally do the division to get sc and tc
  9279. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  9280. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  9281. // get the difference of the two closest points
  9282. var qtc = v.multiplyByFloats(tc, tc, tc);
  9283. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  9284. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  9285. if (isIntersected) {
  9286. return qtc.length();
  9287. }
  9288. return -1;
  9289. };
  9290. // Statics
  9291. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  9292. var start = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  9293. var end = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  9294. var direction = end.subtract(start);
  9295. direction.normalize();
  9296. return new Ray(start, direction);
  9297. };
  9298. /**
  9299. * 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
  9300. * transformed to the given world matrix.
  9301. * @param origin The origin point
  9302. * @param end The end point
  9303. * @param world a matrix to transform the ray to. Default is the identity matrix.
  9304. */
  9305. Ray.CreateNewFromTo = function (origin, end, world) {
  9306. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  9307. var direction = end.subtract(origin);
  9308. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  9309. direction.normalize();
  9310. return Ray.Transform(new Ray(origin, direction, length), world);
  9311. };
  9312. Ray.Transform = function (ray, matrix) {
  9313. var newOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, matrix);
  9314. var newDirection = BABYLON.Vector3.TransformNormal(ray.direction, matrix);
  9315. newDirection.normalize();
  9316. return new Ray(newOrigin, newDirection, ray.length);
  9317. };
  9318. Ray.smallnum = 0.00000001;
  9319. Ray.rayl = 10e8;
  9320. return Ray;
  9321. }());
  9322. BABYLON.Ray = Ray;
  9323. })(BABYLON || (BABYLON = {}));
  9324. var BABYLON;
  9325. (function (BABYLON) {
  9326. var AbstractMesh = (function (_super) {
  9327. __extends(AbstractMesh, _super);
  9328. // Constructor
  9329. function AbstractMesh(name, scene) {
  9330. var _this = this;
  9331. _super.call(this, name, scene);
  9332. // Events
  9333. /**
  9334. * An event triggered when the mesh is disposed.
  9335. * @type {BABYLON.Observable}
  9336. */
  9337. this.onDisposeObservable = new BABYLON.Observable();
  9338. /**
  9339. * An event triggered when this mesh collides with another one
  9340. * @type {BABYLON.Observable}
  9341. */
  9342. this.onCollideObservable = new BABYLON.Observable();
  9343. /**
  9344. * An event triggered when the collision's position changes
  9345. * @type {BABYLON.Observable}
  9346. */
  9347. this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  9348. /**
  9349. * An event triggered after the world matrix is updated
  9350. * @type {BABYLON.Observable}
  9351. */
  9352. this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  9353. // Properties
  9354. this.definedFacingForward = true; // orientation for POV movement & rotation
  9355. this.position = new BABYLON.Vector3(0, 0, 0);
  9356. this._rotation = new BABYLON.Vector3(0, 0, 0);
  9357. this._scaling = new BABYLON.Vector3(1, 1, 1);
  9358. this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  9359. this.visibility = 1.0;
  9360. this.alphaIndex = Number.MAX_VALUE;
  9361. this.infiniteDistance = false;
  9362. this.isVisible = true;
  9363. this.isPickable = true;
  9364. this.showBoundingBox = false;
  9365. this.showSubMeshesBoundingBox = false;
  9366. this.isBlocker = false;
  9367. this.renderingGroupId = 0;
  9368. this.receiveShadows = false;
  9369. this.renderOutline = false;
  9370. this.outlineColor = BABYLON.Color3.Red();
  9371. this.outlineWidth = 0.02;
  9372. this.renderOverlay = false;
  9373. this.overlayColor = BABYLON.Color3.Red();
  9374. this.overlayAlpha = 0.5;
  9375. this.hasVertexAlpha = false;
  9376. this.useVertexColors = true;
  9377. this.applyFog = true;
  9378. this.computeBonesUsingShaders = true;
  9379. this.scalingDeterminant = 1;
  9380. this.numBoneInfluencers = 4;
  9381. this.useOctreeForRenderingSelection = true;
  9382. this.useOctreeForPicking = true;
  9383. this.useOctreeForCollisions = true;
  9384. this.layerMask = 0x0FFFFFFF;
  9385. this.alwaysSelectAsActiveMesh = false;
  9386. // Collisions
  9387. this._checkCollisions = false;
  9388. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  9389. this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  9390. this._collider = new BABYLON.Collider();
  9391. this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  9392. this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  9393. this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  9394. // Edges
  9395. this.edgesWidth = 1;
  9396. this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  9397. // Cache
  9398. this._localWorld = BABYLON.Matrix.Zero();
  9399. this._worldMatrix = BABYLON.Matrix.Zero();
  9400. this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  9401. this._absolutePosition = BABYLON.Vector3.Zero();
  9402. this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  9403. this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  9404. this._isDirty = false;
  9405. this._pivotMatrix = BABYLON.Matrix.Identity();
  9406. this._isDisposed = false;
  9407. this._renderId = 0;
  9408. this._intersectionsInProgress = new Array();
  9409. this._isWorldMatrixFrozen = false;
  9410. this._unIndexed = false;
  9411. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  9412. if (collidedMesh === void 0) { collidedMesh = null; }
  9413. //TODO move this to the collision coordinator!
  9414. if (_this.getScene().workerCollisions)
  9415. newPosition.multiplyInPlace(_this._collider.radius);
  9416. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  9417. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  9418. _this.position.addInPlace(_this._diffPositionForCollisions);
  9419. }
  9420. if (collidedMesh) {
  9421. _this.onCollideObservable.notifyObservers(collidedMesh);
  9422. }
  9423. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  9424. };
  9425. scene.addMesh(this);
  9426. }
  9427. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  9428. get: function () {
  9429. return AbstractMesh._BILLBOARDMODE_NONE;
  9430. },
  9431. enumerable: true,
  9432. configurable: true
  9433. });
  9434. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  9435. get: function () {
  9436. return AbstractMesh._BILLBOARDMODE_X;
  9437. },
  9438. enumerable: true,
  9439. configurable: true
  9440. });
  9441. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  9442. get: function () {
  9443. return AbstractMesh._BILLBOARDMODE_Y;
  9444. },
  9445. enumerable: true,
  9446. configurable: true
  9447. });
  9448. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  9449. get: function () {
  9450. return AbstractMesh._BILLBOARDMODE_Z;
  9451. },
  9452. enumerable: true,
  9453. configurable: true
  9454. });
  9455. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  9456. get: function () {
  9457. return AbstractMesh._BILLBOARDMODE_ALL;
  9458. },
  9459. enumerable: true,
  9460. configurable: true
  9461. });
  9462. Object.defineProperty(AbstractMesh.prototype, "onDispose", {
  9463. set: function (callback) {
  9464. if (this._onDisposeObserver) {
  9465. this.onDisposeObservable.remove(this._onDisposeObserver);
  9466. }
  9467. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  9468. },
  9469. enumerable: true,
  9470. configurable: true
  9471. });
  9472. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  9473. set: function (callback) {
  9474. if (this._onCollideObserver) {
  9475. this.onCollideObservable.remove(this._onCollideObserver);
  9476. }
  9477. this._onCollideObserver = this.onCollideObservable.add(callback);
  9478. },
  9479. enumerable: true,
  9480. configurable: true
  9481. });
  9482. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  9483. set: function (callback) {
  9484. if (this._onCollisionPositionChangeObserver) {
  9485. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  9486. }
  9487. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  9488. },
  9489. enumerable: true,
  9490. configurable: true
  9491. });
  9492. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  9493. get: function () {
  9494. return this._skeleton;
  9495. },
  9496. set: function (value) {
  9497. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  9498. this._skeleton._unregisterMeshWithPoseMatrix(this);
  9499. }
  9500. if (value && value.needInitialSkinMatrix) {
  9501. value._registerMeshWithPoseMatrix(this);
  9502. }
  9503. this._skeleton = value;
  9504. if (!this._skeleton) {
  9505. this._bonesTransformMatrices = null;
  9506. }
  9507. },
  9508. enumerable: true,
  9509. configurable: true
  9510. });
  9511. /**
  9512. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  9513. */
  9514. AbstractMesh.prototype.toString = function (fullDetails) {
  9515. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  9516. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  9517. if (this._skeleton) {
  9518. ret += ", skeleton: " + this._skeleton.name;
  9519. }
  9520. if (fullDetails) {
  9521. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  9522. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  9523. }
  9524. return ret;
  9525. };
  9526. Object.defineProperty(AbstractMesh.prototype, "rotation", {
  9527. /**
  9528. * Getting the rotation object.
  9529. * If rotation quaternion is set, this vector will (almost always) be the Zero vector!
  9530. */
  9531. get: function () {
  9532. return this._rotation;
  9533. },
  9534. set: function (newRotation) {
  9535. this._rotation = newRotation;
  9536. },
  9537. enumerable: true,
  9538. configurable: true
  9539. });
  9540. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  9541. get: function () {
  9542. return this._scaling;
  9543. },
  9544. set: function (newScaling) {
  9545. this._scaling = newScaling;
  9546. if (this.physicsImpostor) {
  9547. this.physicsImpostor.forceUpdate();
  9548. }
  9549. },
  9550. enumerable: true,
  9551. configurable: true
  9552. });
  9553. Object.defineProperty(AbstractMesh.prototype, "rotationQuaternion", {
  9554. get: function () {
  9555. return this._rotationQuaternion;
  9556. },
  9557. set: function (quaternion) {
  9558. this._rotationQuaternion = quaternion;
  9559. //reset the rotation vector.
  9560. if (quaternion && this.rotation.length()) {
  9561. this.rotation.copyFromFloats(0, 0, 0);
  9562. }
  9563. },
  9564. enumerable: true,
  9565. configurable: true
  9566. });
  9567. // Methods
  9568. AbstractMesh.prototype.updatePoseMatrix = function (matrix) {
  9569. this._poseMatrix.copyFrom(matrix);
  9570. };
  9571. AbstractMesh.prototype.getPoseMatrix = function () {
  9572. return this._poseMatrix;
  9573. };
  9574. AbstractMesh.prototype.disableEdgesRendering = function () {
  9575. if (this._edgesRenderer !== undefined) {
  9576. this._edgesRenderer.dispose();
  9577. this._edgesRenderer = undefined;
  9578. }
  9579. };
  9580. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  9581. if (epsilon === void 0) { epsilon = 0.95; }
  9582. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  9583. this.disableEdgesRendering();
  9584. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  9585. };
  9586. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  9587. get: function () {
  9588. return false;
  9589. },
  9590. enumerable: true,
  9591. configurable: true
  9592. });
  9593. AbstractMesh.prototype.getLOD = function (camera) {
  9594. return this;
  9595. };
  9596. AbstractMesh.prototype.getTotalVertices = function () {
  9597. return 0;
  9598. };
  9599. AbstractMesh.prototype.getIndices = function () {
  9600. return null;
  9601. };
  9602. AbstractMesh.prototype.getVerticesData = function (kind) {
  9603. return null;
  9604. };
  9605. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  9606. return false;
  9607. };
  9608. AbstractMesh.prototype.getBoundingInfo = function () {
  9609. if (this._masterMesh) {
  9610. return this._masterMesh.getBoundingInfo();
  9611. }
  9612. if (!this._boundingInfo) {
  9613. this._updateBoundingInfo();
  9614. }
  9615. return this._boundingInfo;
  9616. };
  9617. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  9618. this._boundingInfo = boundingInfo;
  9619. };
  9620. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  9621. get: function () {
  9622. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  9623. },
  9624. enumerable: true,
  9625. configurable: true
  9626. });
  9627. AbstractMesh.prototype._preActivate = function () {
  9628. };
  9629. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  9630. };
  9631. AbstractMesh.prototype._activate = function (renderId) {
  9632. this._renderId = renderId;
  9633. };
  9634. AbstractMesh.prototype.getWorldMatrix = function () {
  9635. if (this._masterMesh) {
  9636. return this._masterMesh.getWorldMatrix();
  9637. }
  9638. if (this._currentRenderId !== this.getScene().getRenderId()) {
  9639. this.computeWorldMatrix();
  9640. }
  9641. return this._worldMatrix;
  9642. };
  9643. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  9644. get: function () {
  9645. return this._worldMatrix;
  9646. },
  9647. enumerable: true,
  9648. configurable: true
  9649. });
  9650. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  9651. get: function () {
  9652. return this._absolutePosition;
  9653. },
  9654. enumerable: true,
  9655. configurable: true
  9656. });
  9657. AbstractMesh.prototype.freezeWorldMatrix = function () {
  9658. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  9659. this.computeWorldMatrix(true);
  9660. this._isWorldMatrixFrozen = true;
  9661. };
  9662. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  9663. this._isWorldMatrixFrozen = false;
  9664. this.computeWorldMatrix(true);
  9665. };
  9666. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  9667. get: function () {
  9668. return this._isWorldMatrixFrozen;
  9669. },
  9670. enumerable: true,
  9671. configurable: true
  9672. });
  9673. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  9674. axis.normalize();
  9675. if (!this.rotationQuaternion) {
  9676. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  9677. this.rotation = BABYLON.Vector3.Zero();
  9678. }
  9679. var rotationQuaternion;
  9680. if (!space || space === BABYLON.Space.LOCAL) {
  9681. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  9682. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  9683. }
  9684. else {
  9685. if (this.parent) {
  9686. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  9687. invertParentWorldMatrix.invert();
  9688. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  9689. }
  9690. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  9691. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  9692. }
  9693. };
  9694. AbstractMesh.prototype.translate = function (axis, distance, space) {
  9695. var displacementVector = axis.scale(distance);
  9696. if (!space || space === BABYLON.Space.LOCAL) {
  9697. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  9698. this.setPositionWithLocalVector(tempV3);
  9699. }
  9700. else {
  9701. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  9702. }
  9703. };
  9704. AbstractMesh.prototype.getAbsolutePosition = function () {
  9705. this.computeWorldMatrix();
  9706. return this._absolutePosition;
  9707. };
  9708. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  9709. if (!absolutePosition) {
  9710. return;
  9711. }
  9712. var absolutePositionX;
  9713. var absolutePositionY;
  9714. var absolutePositionZ;
  9715. if (absolutePosition.x === undefined) {
  9716. if (arguments.length < 3) {
  9717. return;
  9718. }
  9719. absolutePositionX = arguments[0];
  9720. absolutePositionY = arguments[1];
  9721. absolutePositionZ = arguments[2];
  9722. }
  9723. else {
  9724. absolutePositionX = absolutePosition.x;
  9725. absolutePositionY = absolutePosition.y;
  9726. absolutePositionZ = absolutePosition.z;
  9727. }
  9728. if (this.parent) {
  9729. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  9730. invertParentWorldMatrix.invert();
  9731. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  9732. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  9733. }
  9734. else {
  9735. this.position.x = absolutePositionX;
  9736. this.position.y = absolutePositionY;
  9737. this.position.z = absolutePositionZ;
  9738. }
  9739. };
  9740. // ================================== Point of View Movement =================================
  9741. /**
  9742. * Perform relative position change from the point of view of behind the front of the mesh.
  9743. * This is performed taking into account the meshes current rotation, so you do not have to care.
  9744. * Supports definition of mesh facing forward or backward.
  9745. * @param {number} amountRight
  9746. * @param {number} amountUp
  9747. * @param {number} amountForward
  9748. */
  9749. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  9750. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  9751. };
  9752. /**
  9753. * Calculate relative position change from the point of view of behind the front of the mesh.
  9754. * This is performed taking into account the meshes current rotation, so you do not have to care.
  9755. * Supports definition of mesh facing forward or backward.
  9756. * @param {number} amountRight
  9757. * @param {number} amountUp
  9758. * @param {number} amountForward
  9759. */
  9760. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  9761. var rotMatrix = new BABYLON.Matrix();
  9762. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  9763. rotQuaternion.toRotationMatrix(rotMatrix);
  9764. var translationDelta = BABYLON.Vector3.Zero();
  9765. var defForwardMult = this.definedFacingForward ? -1 : 1;
  9766. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  9767. return translationDelta;
  9768. };
  9769. // ================================== Point of View Rotation =================================
  9770. /**
  9771. * Perform relative rotation change from the point of view of behind the front of the mesh.
  9772. * Supports definition of mesh facing forward or backward.
  9773. * @param {number} flipBack
  9774. * @param {number} twirlClockwise
  9775. * @param {number} tiltRight
  9776. */
  9777. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  9778. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  9779. };
  9780. /**
  9781. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  9782. * Supports definition of mesh facing forward or backward.
  9783. * @param {number} flipBack
  9784. * @param {number} twirlClockwise
  9785. * @param {number} tiltRight
  9786. */
  9787. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  9788. var defForwardMult = this.definedFacingForward ? 1 : -1;
  9789. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  9790. };
  9791. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  9792. this._pivotMatrix = matrix;
  9793. this._cache.pivotMatrixUpdated = true;
  9794. };
  9795. AbstractMesh.prototype.getPivotMatrix = function () {
  9796. return this._pivotMatrix;
  9797. };
  9798. AbstractMesh.prototype._isSynchronized = function () {
  9799. if (this._isDirty) {
  9800. return false;
  9801. }
  9802. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  9803. return false;
  9804. if (this._cache.pivotMatrixUpdated) {
  9805. return false;
  9806. }
  9807. if (this.infiniteDistance) {
  9808. return false;
  9809. }
  9810. if (!this._cache.position.equals(this.position))
  9811. return false;
  9812. if (this.rotationQuaternion) {
  9813. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  9814. return false;
  9815. }
  9816. if (!this._cache.rotation.equals(this.rotation))
  9817. return false;
  9818. if (!this._cache.scaling.equals(this.scaling))
  9819. return false;
  9820. return true;
  9821. };
  9822. AbstractMesh.prototype._initCache = function () {
  9823. _super.prototype._initCache.call(this);
  9824. this._cache.localMatrixUpdated = false;
  9825. this._cache.position = BABYLON.Vector3.Zero();
  9826. this._cache.scaling = BABYLON.Vector3.Zero();
  9827. this._cache.rotation = BABYLON.Vector3.Zero();
  9828. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  9829. this._cache.billboardMode = -1;
  9830. };
  9831. AbstractMesh.prototype.markAsDirty = function (property) {
  9832. if (property === "rotation") {
  9833. this.rotationQuaternion = null;
  9834. }
  9835. this._currentRenderId = Number.MAX_VALUE;
  9836. this._isDirty = true;
  9837. };
  9838. AbstractMesh.prototype._updateBoundingInfo = function () {
  9839. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  9840. this._boundingInfo.update(this.worldMatrixFromCache);
  9841. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  9842. };
  9843. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  9844. if (!this.subMeshes) {
  9845. return;
  9846. }
  9847. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  9848. var subMesh = this.subMeshes[subIndex];
  9849. if (!subMesh.IsGlobal) {
  9850. subMesh.updateBoundingInfo(matrix);
  9851. }
  9852. }
  9853. };
  9854. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  9855. if (this._isWorldMatrixFrozen) {
  9856. return this._worldMatrix;
  9857. }
  9858. if (!force && (this._currentRenderId === this.getScene().getRenderId() || this.isSynchronized(true))) {
  9859. this._currentRenderId = this.getScene().getRenderId();
  9860. return this._worldMatrix;
  9861. }
  9862. this._cache.position.copyFrom(this.position);
  9863. this._cache.scaling.copyFrom(this.scaling);
  9864. this._cache.pivotMatrixUpdated = false;
  9865. this._cache.billboardMode = this.billboardMode;
  9866. this._currentRenderId = this.getScene().getRenderId();
  9867. this._isDirty = false;
  9868. // Scaling
  9869. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  9870. // Rotation
  9871. //rotate, if quaternion is set and rotation was used
  9872. if (this.rotationQuaternion) {
  9873. var len = this.rotation.length();
  9874. if (len) {
  9875. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  9876. this.rotation.copyFromFloats(0, 0, 0);
  9877. }
  9878. }
  9879. if (this.rotationQuaternion) {
  9880. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  9881. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  9882. }
  9883. else {
  9884. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  9885. this._cache.rotation.copyFrom(this.rotation);
  9886. }
  9887. // Translation
  9888. if (this.infiniteDistance && !this.parent) {
  9889. var camera = this.getScene().activeCamera;
  9890. if (camera) {
  9891. var cameraWorldMatrix = camera.getWorldMatrix();
  9892. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  9893. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  9894. }
  9895. }
  9896. else {
  9897. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  9898. }
  9899. // Composing transformations
  9900. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  9901. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  9902. // Billboarding
  9903. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  9904. BABYLON.Tmp.Vector3[0].copyFrom(this.position);
  9905. var localPosition = BABYLON.Tmp.Vector3[0];
  9906. if (this.parent && this.parent.getWorldMatrix) {
  9907. this._markSyncedWithParent();
  9908. var parentMatrix;
  9909. if (this._meshToBoneReferal) {
  9910. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  9911. parentMatrix = BABYLON.Tmp.Matrix[6];
  9912. }
  9913. else {
  9914. parentMatrix = this.parent.getWorldMatrix();
  9915. }
  9916. BABYLON.Vector3.TransformNormalToRef(localPosition, parentMatrix, BABYLON.Tmp.Vector3[1]);
  9917. localPosition = BABYLON.Tmp.Vector3[1];
  9918. }
  9919. var zero = this.getScene().activeCamera.globalPosition.clone();
  9920. if (this.parent && this.parent.position) {
  9921. localPosition.addInPlace(this.parent.position);
  9922. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, BABYLON.Tmp.Matrix[2]);
  9923. }
  9924. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) !== AbstractMesh.BILLBOARDMODE_ALL) {
  9925. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_X)
  9926. zero.x = localPosition.x + BABYLON.Epsilon;
  9927. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Y)
  9928. zero.y = localPosition.y + BABYLON.Epsilon;
  9929. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Z)
  9930. zero.z = localPosition.z + BABYLON.Epsilon;
  9931. }
  9932. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), BABYLON.Tmp.Matrix[3]);
  9933. BABYLON.Tmp.Matrix[3].m[12] = BABYLON.Tmp.Matrix[3].m[13] = BABYLON.Tmp.Matrix[3].m[14] = 0;
  9934. BABYLON.Tmp.Matrix[3].invert();
  9935. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[3], this._localWorld);
  9936. this._rotateYByPI.multiplyToRef(this._localWorld, BABYLON.Tmp.Matrix[5]);
  9937. }
  9938. // Local world
  9939. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  9940. // Parent
  9941. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === AbstractMesh.BILLBOARDMODE_NONE) {
  9942. this._markSyncedWithParent();
  9943. if (this._meshToBoneReferal) {
  9944. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  9945. BABYLON.Tmp.Matrix[6].multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), this._worldMatrix);
  9946. }
  9947. else {
  9948. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  9949. }
  9950. }
  9951. else {
  9952. this._worldMatrix.copyFrom(this._localWorld);
  9953. }
  9954. // Bounding info
  9955. this._updateBoundingInfo();
  9956. // Absolute position
  9957. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  9958. // Callbacks
  9959. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  9960. if (!this._poseMatrix) {
  9961. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  9962. }
  9963. return this._worldMatrix;
  9964. };
  9965. /**
  9966. * If you'd like to be callbacked after the mesh position, rotation or scaling has been updated
  9967. * @param func: callback function to add
  9968. */
  9969. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  9970. this.onAfterWorldMatrixUpdateObservable.add(func);
  9971. };
  9972. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  9973. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  9974. };
  9975. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  9976. this.computeWorldMatrix();
  9977. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  9978. };
  9979. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  9980. this.computeWorldMatrix();
  9981. var invLocalWorldMatrix = this._localWorld.clone();
  9982. invLocalWorldMatrix.invert();
  9983. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  9984. };
  9985. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  9986. this.computeWorldMatrix(true);
  9987. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  9988. };
  9989. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  9990. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  9991. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  9992. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  9993. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  9994. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  9995. /// <returns>Mesh oriented towards targetMesh</returns>
  9996. if (yawCor === void 0) { yawCor = 0; }
  9997. if (pitchCor === void 0) { pitchCor = 0; }
  9998. if (rollCor === void 0) { rollCor = 0; }
  9999. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  10000. var dv = AbstractMesh._lookAtVectorCache;
  10001. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  10002. targetPoint.subtractToRef(pos, dv);
  10003. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  10004. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  10005. var pitch = Math.atan2(dv.y, len);
  10006. this.rotationQuaternion = this.rotationQuaternion || new BABYLON.Quaternion();
  10007. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  10008. };
  10009. AbstractMesh.prototype.attachToBone = function (bone, affectedMesh) {
  10010. this._meshToBoneReferal = affectedMesh;
  10011. this.parent = bone;
  10012. if (bone.getWorldMatrix().determinant() < 0) {
  10013. this.scalingDeterminant *= -1;
  10014. }
  10015. };
  10016. AbstractMesh.prototype.detachFromBone = function () {
  10017. if (this.parent.getWorldMatrix().determinant() < 0) {
  10018. this.scalingDeterminant *= -1;
  10019. }
  10020. this._meshToBoneReferal = null;
  10021. this.parent = null;
  10022. };
  10023. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  10024. return this._boundingInfo.isInFrustum(frustumPlanes);
  10025. };
  10026. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  10027. return this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  10028. ;
  10029. };
  10030. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  10031. if (!this._boundingInfo || !mesh._boundingInfo) {
  10032. return false;
  10033. }
  10034. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  10035. };
  10036. AbstractMesh.prototype.intersectsPoint = function (point) {
  10037. if (!this._boundingInfo) {
  10038. return false;
  10039. }
  10040. return this._boundingInfo.intersectsPoint(point);
  10041. };
  10042. // Physics
  10043. /**
  10044. * @Deprecated. Use new PhysicsImpostor instead.
  10045. * */
  10046. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  10047. //legacy support
  10048. if (impostor.impostor) {
  10049. options = impostor;
  10050. impostor = impostor.impostor;
  10051. }
  10052. this.physicsImpostor = new BABYLON.PhysicsImpostor(this, impostor, options, this.getScene());
  10053. return this.physicsImpostor.physicsBody;
  10054. };
  10055. AbstractMesh.prototype.getPhysicsImpostor = function () {
  10056. return this.physicsImpostor;
  10057. };
  10058. /**
  10059. * @Deprecated. Use getPhysicsImpostor().getParam("mass");
  10060. */
  10061. AbstractMesh.prototype.getPhysicsMass = function () {
  10062. return this.physicsImpostor.getParam("mass");
  10063. };
  10064. /**
  10065. * @Deprecated. Use getPhysicsImpostor().getParam("friction");
  10066. */
  10067. AbstractMesh.prototype.getPhysicsFriction = function () {
  10068. return this.physicsImpostor.getParam("friction");
  10069. };
  10070. /**
  10071. * @Deprecated. Use getPhysicsImpostor().getParam("restitution");
  10072. */
  10073. AbstractMesh.prototype.getPhysicsRestitution = function () {
  10074. return this.physicsImpostor.getParam("restitution");
  10075. };
  10076. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  10077. if (!camera) {
  10078. camera = this.getScene().activeCamera;
  10079. }
  10080. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  10081. };
  10082. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  10083. if (!camera) {
  10084. camera = this.getScene().activeCamera;
  10085. }
  10086. return this.absolutePosition.subtract(camera.position).length();
  10087. };
  10088. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  10089. if (!this.physicsImpostor) {
  10090. return;
  10091. }
  10092. this.physicsImpostor.applyImpulse(force, contactPoint);
  10093. };
  10094. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  10095. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  10096. return;
  10097. }
  10098. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  10099. mainPivot: pivot1,
  10100. connectedPivot: pivot2,
  10101. nativeParams: options
  10102. });
  10103. };
  10104. /**
  10105. * @Deprecated
  10106. */
  10107. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  10108. BABYLON.Tools.Warn("updatePhysicsBodyPosition() is deprecated, please use updatePhysicsBody()");
  10109. this.updatePhysicsBody();
  10110. };
  10111. /**
  10112. * @Deprecated
  10113. * Calling this function is not needed anymore.
  10114. * The physics engine takes care of transofmration automatically.
  10115. */
  10116. AbstractMesh.prototype.updatePhysicsBody = function () {
  10117. //Unneeded
  10118. };
  10119. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  10120. // Collisions
  10121. get: function () {
  10122. return this._checkCollisions;
  10123. },
  10124. set: function (collisionEnabled) {
  10125. this._checkCollisions = collisionEnabled;
  10126. if (this.getScene().workerCollisions) {
  10127. this.getScene().collisionCoordinator.onMeshUpdated(this);
  10128. }
  10129. },
  10130. enumerable: true,
  10131. configurable: true
  10132. });
  10133. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  10134. var globalPosition = this.getAbsolutePosition();
  10135. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  10136. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  10137. this._collider.radius = this.ellipsoid;
  10138. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  10139. };
  10140. // Submeshes octree
  10141. /**
  10142. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  10143. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  10144. */
  10145. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  10146. if (maxCapacity === void 0) { maxCapacity = 64; }
  10147. if (maxDepth === void 0) { maxDepth = 2; }
  10148. if (!this._submeshesOctree) {
  10149. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  10150. }
  10151. this.computeWorldMatrix(true);
  10152. // Update octree
  10153. var bbox = this.getBoundingInfo().boundingBox;
  10154. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  10155. return this._submeshesOctree;
  10156. };
  10157. // Collisions
  10158. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  10159. this._generatePointsArray();
  10160. // Transformation
  10161. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  10162. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  10163. subMesh._lastColliderWorldVertices = [];
  10164. subMesh._trianglePlanes = [];
  10165. var start = subMesh.verticesStart;
  10166. var end = (subMesh.verticesStart + subMesh.verticesCount);
  10167. for (var i = start; i < end; i++) {
  10168. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  10169. }
  10170. }
  10171. // Collide
  10172. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  10173. if (collider.collisionFound) {
  10174. collider.collidedMesh = this;
  10175. }
  10176. };
  10177. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  10178. var subMeshes;
  10179. var len;
  10180. // Octrees
  10181. if (this._submeshesOctree && this.useOctreeForCollisions) {
  10182. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  10183. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  10184. len = intersections.length;
  10185. subMeshes = intersections.data;
  10186. }
  10187. else {
  10188. subMeshes = this.subMeshes;
  10189. len = subMeshes.length;
  10190. }
  10191. for (var index = 0; index < len; index++) {
  10192. var subMesh = subMeshes[index];
  10193. // Bounding test
  10194. if (len > 1 && !subMesh._checkCollision(collider))
  10195. continue;
  10196. this._collideForSubMesh(subMesh, transformMatrix, collider);
  10197. }
  10198. };
  10199. AbstractMesh.prototype._checkCollision = function (collider) {
  10200. // Bounding box test
  10201. if (!this._boundingInfo._checkCollision(collider))
  10202. return;
  10203. // Transformation matrix
  10204. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  10205. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  10206. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  10207. };
  10208. // Picking
  10209. AbstractMesh.prototype._generatePointsArray = function () {
  10210. return false;
  10211. };
  10212. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  10213. var pickingInfo = new BABYLON.PickingInfo();
  10214. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  10215. return pickingInfo;
  10216. }
  10217. if (!this._generatePointsArray()) {
  10218. return pickingInfo;
  10219. }
  10220. var intersectInfo = null;
  10221. // Octrees
  10222. var subMeshes;
  10223. var len;
  10224. if (this._submeshesOctree && this.useOctreeForPicking) {
  10225. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  10226. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  10227. len = intersections.length;
  10228. subMeshes = intersections.data;
  10229. }
  10230. else {
  10231. subMeshes = this.subMeshes;
  10232. len = subMeshes.length;
  10233. }
  10234. for (var index = 0; index < len; index++) {
  10235. var subMesh = subMeshes[index];
  10236. // Bounding test
  10237. if (len > 1 && !subMesh.canIntersects(ray))
  10238. continue;
  10239. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  10240. if (currentIntersectInfo) {
  10241. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  10242. intersectInfo = currentIntersectInfo;
  10243. intersectInfo.subMeshId = index;
  10244. if (fastCheck) {
  10245. break;
  10246. }
  10247. }
  10248. }
  10249. }
  10250. if (intersectInfo) {
  10251. // Get picked point
  10252. var world = this.getWorldMatrix();
  10253. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  10254. var direction = ray.direction.clone();
  10255. direction = direction.scale(intersectInfo.distance);
  10256. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  10257. var pickedPoint = worldOrigin.add(worldDirection);
  10258. // Return result
  10259. pickingInfo.hit = true;
  10260. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  10261. pickingInfo.pickedPoint = pickedPoint;
  10262. pickingInfo.pickedMesh = this;
  10263. pickingInfo.bu = intersectInfo.bu;
  10264. pickingInfo.bv = intersectInfo.bv;
  10265. pickingInfo.faceId = intersectInfo.faceId;
  10266. pickingInfo.subMeshId = intersectInfo.subMeshId;
  10267. return pickingInfo;
  10268. }
  10269. return pickingInfo;
  10270. };
  10271. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  10272. return null;
  10273. };
  10274. AbstractMesh.prototype.releaseSubMeshes = function () {
  10275. if (this.subMeshes) {
  10276. while (this.subMeshes.length) {
  10277. this.subMeshes[0].dispose();
  10278. }
  10279. }
  10280. else {
  10281. this.subMeshes = new Array();
  10282. }
  10283. };
  10284. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  10285. var _this = this;
  10286. var index;
  10287. // Action manager
  10288. if (this.actionManager) {
  10289. this.actionManager.dispose();
  10290. this.actionManager = null;
  10291. }
  10292. // Skeleton
  10293. this.skeleton = null;
  10294. // Animations
  10295. this.getScene().stopAnimation(this);
  10296. // Physics
  10297. if (this.physicsImpostor) {
  10298. this.physicsImpostor.dispose();
  10299. }
  10300. // Intersections in progress
  10301. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  10302. var other = this._intersectionsInProgress[index];
  10303. var pos = other._intersectionsInProgress.indexOf(this);
  10304. other._intersectionsInProgress.splice(pos, 1);
  10305. }
  10306. this._intersectionsInProgress = [];
  10307. // Lights
  10308. var lights = this.getScene().lights;
  10309. lights.forEach(function (light) {
  10310. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  10311. if (meshIndex !== -1) {
  10312. light.includedOnlyMeshes.splice(meshIndex, 1);
  10313. }
  10314. meshIndex = light.excludedMeshes.indexOf(_this);
  10315. if (meshIndex !== -1) {
  10316. light.excludedMeshes.splice(meshIndex, 1);
  10317. }
  10318. });
  10319. // Edges
  10320. if (this._edgesRenderer) {
  10321. this._edgesRenderer.dispose();
  10322. this._edgesRenderer = null;
  10323. }
  10324. // SubMeshes
  10325. this.releaseSubMeshes();
  10326. // Remove from scene
  10327. this.getScene().removeMesh(this);
  10328. if (!doNotRecurse) {
  10329. // Particles
  10330. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  10331. if (this.getScene().particleSystems[index].emitter === this) {
  10332. this.getScene().particleSystems[index].dispose();
  10333. index--;
  10334. }
  10335. }
  10336. // Children
  10337. var objects = this.getDescendants(true);
  10338. for (index = 0; index < objects.length; index++) {
  10339. objects[index].dispose();
  10340. }
  10341. }
  10342. else {
  10343. var childMeshes = this.getChildMeshes(true);
  10344. for (index = 0; index < childMeshes.length; index++) {
  10345. var child = childMeshes[index];
  10346. child.parent = null;
  10347. child.computeWorldMatrix(true);
  10348. }
  10349. }
  10350. _super.prototype.dispose.call(this);
  10351. this.onAfterWorldMatrixUpdateObservable.clear();
  10352. this.onCollideObservable.clear();
  10353. this.onCollisionPositionChangeObservable.clear();
  10354. this._isDisposed = true;
  10355. // Callback
  10356. this.onDisposeObservable.notifyObservers(this);
  10357. this.onDisposeObservable.clear();
  10358. };
  10359. // Statics
  10360. AbstractMesh._BILLBOARDMODE_NONE = 0;
  10361. AbstractMesh._BILLBOARDMODE_X = 1;
  10362. AbstractMesh._BILLBOARDMODE_Y = 2;
  10363. AbstractMesh._BILLBOARDMODE_Z = 4;
  10364. AbstractMesh._BILLBOARDMODE_ALL = 7;
  10365. AbstractMesh._rotationAxisCache = new BABYLON.Quaternion();
  10366. AbstractMesh._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  10367. return AbstractMesh;
  10368. }(BABYLON.Node));
  10369. BABYLON.AbstractMesh = AbstractMesh;
  10370. })(BABYLON || (BABYLON = {}));
  10371. var BABYLON;
  10372. (function (BABYLON) {
  10373. var Light = (function (_super) {
  10374. __extends(Light, _super);
  10375. function Light(name, scene) {
  10376. _super.call(this, name, scene);
  10377. this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  10378. this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  10379. this.intensity = 1.0;
  10380. this.range = Number.MAX_VALUE;
  10381. this.includeOnlyWithLayerMask = 0;
  10382. this.includedOnlyMeshes = new Array();
  10383. this.excludedMeshes = new Array();
  10384. this.excludeWithLayerMask = 0;
  10385. // PBR Properties.
  10386. this.radius = 0.00001;
  10387. this._excludedMeshesIds = new Array();
  10388. this._includedOnlyMeshesIds = new Array();
  10389. scene.addLight(this);
  10390. }
  10391. /**
  10392. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  10393. */
  10394. Light.prototype.toString = function (fullDetails) {
  10395. var ret = "Name: " + this.name;
  10396. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  10397. if (this.animations) {
  10398. for (var i = 0; i < this.animations.length; i++) {
  10399. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  10400. }
  10401. }
  10402. if (fullDetails) {
  10403. }
  10404. return ret;
  10405. };
  10406. Light.prototype.getShadowGenerator = function () {
  10407. return this._shadowGenerator;
  10408. };
  10409. Light.prototype.getAbsolutePosition = function () {
  10410. return BABYLON.Vector3.Zero();
  10411. };
  10412. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  10413. };
  10414. Light.prototype._getWorldMatrix = function () {
  10415. return BABYLON.Matrix.Identity();
  10416. };
  10417. Light.prototype.canAffectMesh = function (mesh) {
  10418. if (!mesh) {
  10419. return true;
  10420. }
  10421. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  10422. return false;
  10423. }
  10424. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  10425. return false;
  10426. }
  10427. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  10428. return false;
  10429. }
  10430. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  10431. return false;
  10432. }
  10433. return true;
  10434. };
  10435. Light.prototype.getWorldMatrix = function () {
  10436. this._currentRenderId = this.getScene().getRenderId();
  10437. var worldMatrix = this._getWorldMatrix();
  10438. if (this.parent && this.parent.getWorldMatrix) {
  10439. if (!this._parentedWorldMatrix) {
  10440. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  10441. }
  10442. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  10443. this._markSyncedWithParent();
  10444. return this._parentedWorldMatrix;
  10445. }
  10446. return worldMatrix;
  10447. };
  10448. Light.prototype.dispose = function () {
  10449. if (this._shadowGenerator) {
  10450. this._shadowGenerator.dispose();
  10451. this._shadowGenerator = null;
  10452. }
  10453. // Animations
  10454. this.getScene().stopAnimation(this);
  10455. // Remove from scene
  10456. this.getScene().removeLight(this);
  10457. _super.prototype.dispose.call(this);
  10458. };
  10459. Light.prototype.getTypeID = function () {
  10460. return 0;
  10461. };
  10462. Light.prototype.clone = function (name) {
  10463. return BABYLON.SerializationHelper.Clone(Light.GetConstructorFromName(this.getTypeID(), name, this.getScene()), this);
  10464. };
  10465. Light.prototype.serialize = function () {
  10466. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  10467. // Type
  10468. serializationObject.type = this.getTypeID();
  10469. // Parent
  10470. if (this.parent) {
  10471. serializationObject.parentId = this.parent.id;
  10472. }
  10473. // Inclusion / exclusions
  10474. if (this.excludedMeshes.length > 0) {
  10475. serializationObject.excludedMeshesIds = [];
  10476. this.excludedMeshes.forEach(function (mesh) {
  10477. serializationObject.excludedMeshesIds.push(mesh.id);
  10478. });
  10479. }
  10480. if (this.includedOnlyMeshes.length > 0) {
  10481. serializationObject.includedOnlyMeshesIds = [];
  10482. this.includedOnlyMeshes.forEach(function (mesh) {
  10483. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  10484. });
  10485. }
  10486. // Animations
  10487. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  10488. serializationObject.ranges = this.serializeAnimationRanges();
  10489. return serializationObject;
  10490. };
  10491. Light.GetConstructorFromName = function (type, name, scene) {
  10492. switch (type) {
  10493. case 0:
  10494. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  10495. case 1:
  10496. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  10497. case 2:
  10498. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  10499. case 3:
  10500. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  10501. }
  10502. };
  10503. Light.Parse = function (parsedLight, scene) {
  10504. var light = BABYLON.SerializationHelper.Parse(Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene), parsedLight, scene);
  10505. // Inclusion / exclusions
  10506. if (parsedLight.excludedMeshesIds) {
  10507. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  10508. }
  10509. if (parsedLight.includedOnlyMeshesIds) {
  10510. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  10511. }
  10512. // Parent
  10513. if (parsedLight.parentId) {
  10514. light._waitingParentId = parsedLight.parentId;
  10515. }
  10516. // Animations
  10517. if (parsedLight.animations) {
  10518. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  10519. var parsedAnimation = parsedLight.animations[animationIndex];
  10520. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  10521. }
  10522. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  10523. }
  10524. if (parsedLight.autoAnimate) {
  10525. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  10526. }
  10527. return light;
  10528. };
  10529. __decorate([
  10530. BABYLON.serializeAsColor3()
  10531. ], Light.prototype, "diffuse", void 0);
  10532. __decorate([
  10533. BABYLON.serializeAsColor3()
  10534. ], Light.prototype, "specular", void 0);
  10535. __decorate([
  10536. BABYLON.serialize()
  10537. ], Light.prototype, "intensity", void 0);
  10538. __decorate([
  10539. BABYLON.serialize()
  10540. ], Light.prototype, "range", void 0);
  10541. __decorate([
  10542. BABYLON.serialize()
  10543. ], Light.prototype, "includeOnlyWithLayerMask", void 0);
  10544. __decorate([
  10545. BABYLON.serialize()
  10546. ], Light.prototype, "excludeWithLayerMask", void 0);
  10547. __decorate([
  10548. BABYLON.serialize()
  10549. ], Light.prototype, "radius", void 0);
  10550. return Light;
  10551. }(BABYLON.Node));
  10552. BABYLON.Light = Light;
  10553. })(BABYLON || (BABYLON = {}));
  10554. var BABYLON;
  10555. (function (BABYLON) {
  10556. var PointLight = (function (_super) {
  10557. __extends(PointLight, _super);
  10558. function PointLight(name, position, scene) {
  10559. _super.call(this, name, scene);
  10560. this.position = position;
  10561. }
  10562. PointLight.prototype.getAbsolutePosition = function () {
  10563. return this.transformedPosition ? this.transformedPosition : this.position;
  10564. };
  10565. PointLight.prototype.computeTransformedPosition = function () {
  10566. if (this.parent && this.parent.getWorldMatrix) {
  10567. if (!this.transformedPosition) {
  10568. this.transformedPosition = BABYLON.Vector3.Zero();
  10569. }
  10570. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  10571. return true;
  10572. }
  10573. return false;
  10574. };
  10575. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  10576. if (this.parent && this.parent.getWorldMatrix) {
  10577. this.computeTransformedPosition();
  10578. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0);
  10579. return;
  10580. }
  10581. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  10582. };
  10583. PointLight.prototype.needCube = function () {
  10584. return true;
  10585. };
  10586. PointLight.prototype.supportsVSM = function () {
  10587. return false;
  10588. };
  10589. PointLight.prototype.needRefreshPerFrame = function () {
  10590. return false;
  10591. };
  10592. PointLight.prototype.getShadowDirection = function (faceIndex) {
  10593. switch (faceIndex) {
  10594. case 0:
  10595. return new BABYLON.Vector3(1, 0, 0);
  10596. case 1:
  10597. return new BABYLON.Vector3(-1, 0, 0);
  10598. case 2:
  10599. return new BABYLON.Vector3(0, -1, 0);
  10600. case 3:
  10601. return new BABYLON.Vector3(0, 1, 0);
  10602. case 4:
  10603. return new BABYLON.Vector3(0, 0, 1);
  10604. case 5:
  10605. return new BABYLON.Vector3(0, 0, -1);
  10606. }
  10607. return BABYLON.Vector3.Zero();
  10608. };
  10609. PointLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  10610. var activeCamera = this.getScene().activeCamera;
  10611. BABYLON.Matrix.PerspectiveFovLHToRef(Math.PI / 2, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  10612. };
  10613. PointLight.prototype._getWorldMatrix = function () {
  10614. if (!this._worldMatrix) {
  10615. this._worldMatrix = BABYLON.Matrix.Identity();
  10616. }
  10617. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  10618. return this._worldMatrix;
  10619. };
  10620. PointLight.prototype.getTypeID = function () {
  10621. return 0;
  10622. };
  10623. __decorate([
  10624. BABYLON.serializeAsVector3()
  10625. ], PointLight.prototype, "position", void 0);
  10626. return PointLight;
  10627. }(BABYLON.Light));
  10628. BABYLON.PointLight = PointLight;
  10629. })(BABYLON || (BABYLON = {}));
  10630. var BABYLON;
  10631. (function (BABYLON) {
  10632. var SpotLight = (function (_super) {
  10633. __extends(SpotLight, _super);
  10634. function SpotLight(name, position, direction, angle, exponent, scene) {
  10635. _super.call(this, name, scene);
  10636. this.position = position;
  10637. this.direction = direction;
  10638. this.angle = angle;
  10639. this.exponent = exponent;
  10640. }
  10641. SpotLight.prototype.getAbsolutePosition = function () {
  10642. return this.transformedPosition ? this.transformedPosition : this.position;
  10643. };
  10644. SpotLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  10645. var activeCamera = this.getScene().activeCamera;
  10646. BABYLON.Matrix.PerspectiveFovLHToRef(this.angle, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  10647. };
  10648. SpotLight.prototype.needCube = function () {
  10649. return false;
  10650. };
  10651. SpotLight.prototype.supportsVSM = function () {
  10652. return true;
  10653. };
  10654. SpotLight.prototype.needRefreshPerFrame = function () {
  10655. return false;
  10656. };
  10657. SpotLight.prototype.getShadowDirection = function (faceIndex) {
  10658. return this.direction;
  10659. };
  10660. SpotLight.prototype.setDirectionToTarget = function (target) {
  10661. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  10662. return this.direction;
  10663. };
  10664. SpotLight.prototype.computeTransformedPosition = function () {
  10665. if (this.parent && this.parent.getWorldMatrix) {
  10666. if (!this.transformedPosition) {
  10667. this.transformedPosition = BABYLON.Vector3.Zero();
  10668. }
  10669. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  10670. return true;
  10671. }
  10672. return false;
  10673. };
  10674. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  10675. var normalizeDirection;
  10676. if (this.parent && this.parent.getWorldMatrix) {
  10677. if (!this._transformedDirection) {
  10678. this._transformedDirection = BABYLON.Vector3.Zero();
  10679. }
  10680. this.computeTransformedPosition();
  10681. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  10682. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent);
  10683. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  10684. }
  10685. else {
  10686. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  10687. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  10688. }
  10689. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  10690. };
  10691. SpotLight.prototype._getWorldMatrix = function () {
  10692. if (!this._worldMatrix) {
  10693. this._worldMatrix = BABYLON.Matrix.Identity();
  10694. }
  10695. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  10696. return this._worldMatrix;
  10697. };
  10698. SpotLight.prototype.getTypeID = function () {
  10699. return 2;
  10700. };
  10701. __decorate([
  10702. BABYLON.serializeAsVector3()
  10703. ], SpotLight.prototype, "position", void 0);
  10704. __decorate([
  10705. BABYLON.serializeAsVector3()
  10706. ], SpotLight.prototype, "direction", void 0);
  10707. __decorate([
  10708. BABYLON.serialize()
  10709. ], SpotLight.prototype, "angle", void 0);
  10710. __decorate([
  10711. BABYLON.serialize()
  10712. ], SpotLight.prototype, "exponent", void 0);
  10713. return SpotLight;
  10714. }(BABYLON.Light));
  10715. BABYLON.SpotLight = SpotLight;
  10716. })(BABYLON || (BABYLON = {}));
  10717. var BABYLON;
  10718. (function (BABYLON) {
  10719. var HemisphericLight = (function (_super) {
  10720. __extends(HemisphericLight, _super);
  10721. function HemisphericLight(name, direction, scene) {
  10722. _super.call(this, name, scene);
  10723. this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  10724. this.direction = direction;
  10725. }
  10726. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  10727. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  10728. return this.direction;
  10729. };
  10730. HemisphericLight.prototype.getShadowGenerator = function () {
  10731. return null;
  10732. };
  10733. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  10734. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  10735. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  10736. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  10737. };
  10738. HemisphericLight.prototype._getWorldMatrix = function () {
  10739. if (!this._worldMatrix) {
  10740. this._worldMatrix = BABYLON.Matrix.Identity();
  10741. }
  10742. return this._worldMatrix;
  10743. };
  10744. HemisphericLight.prototype.getTypeID = function () {
  10745. return 3;
  10746. };
  10747. __decorate([
  10748. BABYLON.serializeAsColor3()
  10749. ], HemisphericLight.prototype, "groundColor", void 0);
  10750. __decorate([
  10751. BABYLON.serializeAsVector3()
  10752. ], HemisphericLight.prototype, "direction", void 0);
  10753. return HemisphericLight;
  10754. }(BABYLON.Light));
  10755. BABYLON.HemisphericLight = HemisphericLight;
  10756. })(BABYLON || (BABYLON = {}));
  10757. var BABYLON;
  10758. (function (BABYLON) {
  10759. var DirectionalLight = (function (_super) {
  10760. __extends(DirectionalLight, _super);
  10761. function DirectionalLight(name, direction, scene) {
  10762. _super.call(this, name, scene);
  10763. this.shadowOrthoScale = 0.5;
  10764. this.autoUpdateExtends = true;
  10765. // Cache
  10766. this._orthoLeft = Number.MAX_VALUE;
  10767. this._orthoRight = Number.MIN_VALUE;
  10768. this._orthoTop = Number.MIN_VALUE;
  10769. this._orthoBottom = Number.MAX_VALUE;
  10770. this.position = direction.scale(-1);
  10771. this.direction = direction;
  10772. }
  10773. DirectionalLight.prototype.getAbsolutePosition = function () {
  10774. return this.transformedPosition ? this.transformedPosition : this.position;
  10775. };
  10776. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  10777. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  10778. return this.direction;
  10779. };
  10780. DirectionalLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  10781. var activeCamera = this.getScene().activeCamera;
  10782. // Check extends
  10783. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  10784. var tempVector3 = BABYLON.Vector3.Zero();
  10785. this._orthoLeft = Number.MAX_VALUE;
  10786. this._orthoRight = Number.MIN_VALUE;
  10787. this._orthoTop = Number.MIN_VALUE;
  10788. this._orthoBottom = Number.MAX_VALUE;
  10789. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  10790. var mesh = renderList[meshIndex];
  10791. if (!mesh) {
  10792. continue;
  10793. }
  10794. var boundingInfo = mesh.getBoundingInfo();
  10795. if (!boundingInfo) {
  10796. continue;
  10797. }
  10798. var boundingBox = boundingInfo.boundingBox;
  10799. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  10800. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  10801. if (tempVector3.x < this._orthoLeft)
  10802. this._orthoLeft = tempVector3.x;
  10803. if (tempVector3.y < this._orthoBottom)
  10804. this._orthoBottom = tempVector3.y;
  10805. if (tempVector3.x > this._orthoRight)
  10806. this._orthoRight = tempVector3.x;
  10807. if (tempVector3.y > this._orthoTop)
  10808. this._orthoTop = tempVector3.y;
  10809. }
  10810. }
  10811. }
  10812. var xOffset = this._orthoRight - this._orthoLeft;
  10813. var yOffset = this._orthoTop - this._orthoBottom;
  10814. 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);
  10815. };
  10816. DirectionalLight.prototype.supportsVSM = function () {
  10817. return true;
  10818. };
  10819. DirectionalLight.prototype.needRefreshPerFrame = function () {
  10820. return true;
  10821. };
  10822. DirectionalLight.prototype.needCube = function () {
  10823. return false;
  10824. };
  10825. DirectionalLight.prototype.getShadowDirection = function (faceIndex) {
  10826. return this.direction;
  10827. };
  10828. DirectionalLight.prototype.computeTransformedPosition = function () {
  10829. if (this.parent && this.parent.getWorldMatrix) {
  10830. if (!this.transformedPosition) {
  10831. this.transformedPosition = BABYLON.Vector3.Zero();
  10832. }
  10833. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  10834. return true;
  10835. }
  10836. return false;
  10837. };
  10838. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  10839. if (this.parent && this.parent.getWorldMatrix) {
  10840. if (!this._transformedDirection) {
  10841. this._transformedDirection = BABYLON.Vector3.Zero();
  10842. }
  10843. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  10844. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  10845. return;
  10846. }
  10847. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  10848. };
  10849. DirectionalLight.prototype._getWorldMatrix = function () {
  10850. if (!this._worldMatrix) {
  10851. this._worldMatrix = BABYLON.Matrix.Identity();
  10852. }
  10853. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  10854. return this._worldMatrix;
  10855. };
  10856. DirectionalLight.prototype.getTypeID = function () {
  10857. return 1;
  10858. };
  10859. __decorate([
  10860. BABYLON.serializeAsVector3()
  10861. ], DirectionalLight.prototype, "position", void 0);
  10862. __decorate([
  10863. BABYLON.serializeAsVector3()
  10864. ], DirectionalLight.prototype, "direction", void 0);
  10865. __decorate([
  10866. BABYLON.serialize()
  10867. ], DirectionalLight.prototype, "shadowOrthoScale", void 0);
  10868. __decorate([
  10869. BABYLON.serialize()
  10870. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  10871. return DirectionalLight;
  10872. }(BABYLON.Light));
  10873. BABYLON.DirectionalLight = DirectionalLight;
  10874. })(BABYLON || (BABYLON = {}));
  10875. var BABYLON;
  10876. (function (BABYLON) {
  10877. var ShadowGenerator = (function () {
  10878. function ShadowGenerator(mapSize, light) {
  10879. var _this = this;
  10880. // Members
  10881. this._filter = ShadowGenerator.FILTER_NONE;
  10882. this.blurScale = 2;
  10883. this._blurBoxOffset = 0;
  10884. this._bias = 0.00005;
  10885. this._lightDirection = BABYLON.Vector3.Zero();
  10886. this.forceBackFacesOnly = false;
  10887. this._darkness = 0;
  10888. this._transparencyShadow = false;
  10889. this._viewMatrix = BABYLON.Matrix.Zero();
  10890. this._projectionMatrix = BABYLON.Matrix.Zero();
  10891. this._transformMatrix = BABYLON.Matrix.Zero();
  10892. this._worldViewProjection = BABYLON.Matrix.Zero();
  10893. this._currentFaceIndex = 0;
  10894. this._currentFaceIndexCache = 0;
  10895. this._useFullFloat = true;
  10896. this._light = light;
  10897. this._scene = light.getScene();
  10898. this._mapSize = mapSize;
  10899. light._shadowGenerator = this;
  10900. // Texture type fallback from float to int if not supported.
  10901. var textureType;
  10902. var caps = this._scene.getEngine().getCaps();
  10903. if (caps.textureFloat && caps.textureFloatLinearFiltering && caps.textureFloatRender) {
  10904. this._useFullFloat = true;
  10905. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  10906. }
  10907. else {
  10908. this._useFullFloat = false;
  10909. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  10910. }
  10911. // Render target
  10912. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false, true, textureType, light.needCube());
  10913. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  10914. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  10915. this._shadowMap.anisotropicFilteringLevel = 1;
  10916. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  10917. this._shadowMap.renderParticles = false;
  10918. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  10919. _this._currentFaceIndex = faceIndex;
  10920. });
  10921. this._shadowMap.onAfterUnbindObservable.add(function () {
  10922. if (!_this.useBlurVarianceShadowMap) {
  10923. return;
  10924. }
  10925. if (!_this._shadowMap2) {
  10926. _this._shadowMap2 = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, _this._scene, false, true, textureType);
  10927. _this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  10928. _this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  10929. _this._shadowMap2.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  10930. _this._downSamplePostprocess = new BABYLON.PassPostProcess("downScale", 1.0 / _this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, _this._scene.getEngine());
  10931. _this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  10932. effect.setTexture("textureSampler", _this._shadowMap);
  10933. });
  10934. _this.blurBoxOffset = 1;
  10935. }
  10936. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._boxBlurPostprocess], _this._shadowMap2.getInternalTexture());
  10937. });
  10938. // Custom render function
  10939. var renderSubMesh = function (subMesh) {
  10940. var mesh = subMesh.getRenderingMesh();
  10941. var scene = _this._scene;
  10942. var engine = scene.getEngine();
  10943. // Culling
  10944. engine.setState(subMesh.getMaterial().backFaceCulling);
  10945. // Managing instances
  10946. var batch = mesh._getInstancesRenderList(subMesh._id);
  10947. if (batch.mustReturn) {
  10948. return;
  10949. }
  10950. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  10951. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  10952. engine.enableEffect(_this._effect);
  10953. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  10954. var material = subMesh.getMaterial();
  10955. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  10956. _this._effect.setVector3("lightPosition", _this.getLight().position);
  10957. if (_this.getLight().needCube()) {
  10958. _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  10959. }
  10960. // Alpha test
  10961. if (material && material.needAlphaTesting()) {
  10962. var alphaTexture = material.getAlphaTestTexture();
  10963. _this._effect.setTexture("diffuseSampler", alphaTexture);
  10964. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  10965. }
  10966. // Bones
  10967. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  10968. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  10969. }
  10970. if (_this.forceBackFacesOnly) {
  10971. engine.setState(true, 0, false, true);
  10972. }
  10973. // Draw
  10974. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  10975. if (_this.forceBackFacesOnly) {
  10976. engine.setState(true, 0, false, false);
  10977. }
  10978. }
  10979. else {
  10980. // Need to reset refresh rate of the shadowMap
  10981. _this._shadowMap.resetRefreshCounter();
  10982. }
  10983. };
  10984. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  10985. var index;
  10986. for (index = 0; index < opaqueSubMeshes.length; index++) {
  10987. renderSubMesh(opaqueSubMeshes.data[index]);
  10988. }
  10989. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  10990. renderSubMesh(alphaTestSubMeshes.data[index]);
  10991. }
  10992. if (_this._transparencyShadow) {
  10993. for (index = 0; index < transparentSubMeshes.length; index++) {
  10994. renderSubMesh(transparentSubMeshes.data[index]);
  10995. }
  10996. }
  10997. };
  10998. this._shadowMap.onClearObservable.add(function (engine) {
  10999. if (_this.useBlurVarianceShadowMap || _this.useVarianceShadowMap) {
  11000. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true);
  11001. }
  11002. else {
  11003. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  11004. }
  11005. });
  11006. }
  11007. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  11008. // Static
  11009. get: function () {
  11010. return ShadowGenerator._FILTER_NONE;
  11011. },
  11012. enumerable: true,
  11013. configurable: true
  11014. });
  11015. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  11016. get: function () {
  11017. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  11018. },
  11019. enumerable: true,
  11020. configurable: true
  11021. });
  11022. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  11023. get: function () {
  11024. return ShadowGenerator._FILTER_POISSONSAMPLING;
  11025. },
  11026. enumerable: true,
  11027. configurable: true
  11028. });
  11029. Object.defineProperty(ShadowGenerator, "FILTER_BLURVARIANCESHADOWMAP", {
  11030. get: function () {
  11031. return ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP;
  11032. },
  11033. enumerable: true,
  11034. configurable: true
  11035. });
  11036. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  11037. get: function () {
  11038. return this._bias;
  11039. },
  11040. set: function (bias) {
  11041. this._bias = bias;
  11042. },
  11043. enumerable: true,
  11044. configurable: true
  11045. });
  11046. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  11047. get: function () {
  11048. return this._blurBoxOffset;
  11049. },
  11050. set: function (value) {
  11051. var _this = this;
  11052. if (this._blurBoxOffset === value) {
  11053. return;
  11054. }
  11055. this._blurBoxOffset = value;
  11056. if (this._boxBlurPostprocess) {
  11057. this._boxBlurPostprocess.dispose();
  11058. }
  11059. 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);
  11060. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  11061. effect.setFloat2("screenSize", _this._mapSize / _this.blurScale, _this._mapSize / _this.blurScale);
  11062. });
  11063. },
  11064. enumerable: true,
  11065. configurable: true
  11066. });
  11067. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  11068. get: function () {
  11069. return this._filter;
  11070. },
  11071. set: function (value) {
  11072. if (this._filter === value) {
  11073. return;
  11074. }
  11075. this._filter = value;
  11076. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap || this.usePoissonSampling) {
  11077. this._shadowMap.anisotropicFilteringLevel = 16;
  11078. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  11079. }
  11080. else {
  11081. this._shadowMap.anisotropicFilteringLevel = 1;
  11082. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11083. }
  11084. },
  11085. enumerable: true,
  11086. configurable: true
  11087. });
  11088. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  11089. get: function () {
  11090. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP && this._light.supportsVSM();
  11091. },
  11092. set: function (value) {
  11093. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  11094. },
  11095. enumerable: true,
  11096. configurable: true
  11097. });
  11098. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  11099. get: function () {
  11100. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING ||
  11101. (!this._light.supportsVSM() && (this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP ||
  11102. this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP));
  11103. },
  11104. set: function (value) {
  11105. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  11106. },
  11107. enumerable: true,
  11108. configurable: true
  11109. });
  11110. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  11111. get: function () {
  11112. return this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP && this._light.supportsVSM();
  11113. },
  11114. set: function (value) {
  11115. this.filter = (value ? ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  11116. },
  11117. enumerable: true,
  11118. configurable: true
  11119. });
  11120. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  11121. var defines = [];
  11122. if (this._useFullFloat) {
  11123. defines.push("#define FULLFLOAT");
  11124. }
  11125. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  11126. defines.push("#define VSM");
  11127. }
  11128. if (this.getLight().needCube()) {
  11129. defines.push("#define CUBEMAP");
  11130. }
  11131. var attribs = [BABYLON.VertexBuffer.PositionKind];
  11132. var mesh = subMesh.getMesh();
  11133. var material = subMesh.getMaterial();
  11134. // Alpha test
  11135. if (material && material.needAlphaTesting()) {
  11136. defines.push("#define ALPHATEST");
  11137. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  11138. attribs.push(BABYLON.VertexBuffer.UVKind);
  11139. defines.push("#define UV1");
  11140. }
  11141. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  11142. var alphaTexture = material.getAlphaTestTexture();
  11143. if (alphaTexture.coordinatesIndex === 1) {
  11144. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  11145. defines.push("#define UV2");
  11146. }
  11147. }
  11148. }
  11149. // Bones
  11150. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  11151. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  11152. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  11153. if (mesh.numBoneInfluencers > 4) {
  11154. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  11155. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  11156. }
  11157. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  11158. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  11159. }
  11160. else {
  11161. defines.push("#define NUM_BONE_INFLUENCERS 0");
  11162. }
  11163. // Instances
  11164. if (useInstances) {
  11165. defines.push("#define INSTANCES");
  11166. attribs.push("world0");
  11167. attribs.push("world1");
  11168. attribs.push("world2");
  11169. attribs.push("world3");
  11170. }
  11171. // Get correct effect
  11172. var join = defines.join("\n");
  11173. if (this._cachedDefines !== join) {
  11174. this._cachedDefines = join;
  11175. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues"], ["diffuseSampler"], join);
  11176. }
  11177. return this._effect.isReady();
  11178. };
  11179. ShadowGenerator.prototype.getShadowMap = function () {
  11180. return this._shadowMap;
  11181. };
  11182. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  11183. if (this._shadowMap2) {
  11184. return this._shadowMap2;
  11185. }
  11186. return this._shadowMap;
  11187. };
  11188. ShadowGenerator.prototype.getLight = function () {
  11189. return this._light;
  11190. };
  11191. // Methods
  11192. ShadowGenerator.prototype.getTransformMatrix = function () {
  11193. var scene = this._scene;
  11194. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  11195. return this._transformMatrix;
  11196. }
  11197. this._currentRenderID = scene.getRenderId();
  11198. this._currentFaceIndexCache = this._currentFaceIndex;
  11199. var lightPosition = this._light.position;
  11200. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  11201. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  11202. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  11203. }
  11204. if (this._light.computeTransformedPosition()) {
  11205. lightPosition = this._light.transformedPosition;
  11206. }
  11207. if (this._light.needRefreshPerFrame() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  11208. this._cachedPosition = lightPosition.clone();
  11209. this._cachedDirection = this._lightDirection.clone();
  11210. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  11211. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  11212. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  11213. }
  11214. return this._transformMatrix;
  11215. };
  11216. ShadowGenerator.prototype.getDarkness = function () {
  11217. return this._darkness;
  11218. };
  11219. ShadowGenerator.prototype.setDarkness = function (darkness) {
  11220. if (darkness >= 1.0)
  11221. this._darkness = 1.0;
  11222. else if (darkness <= 0.0)
  11223. this._darkness = 0.0;
  11224. else
  11225. this._darkness = darkness;
  11226. };
  11227. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  11228. this._transparencyShadow = hasShadow;
  11229. };
  11230. ShadowGenerator.prototype._packHalf = function (depth) {
  11231. var scale = depth * 255.0;
  11232. var fract = scale - Math.floor(scale);
  11233. return new BABYLON.Vector2(depth - fract / 255.0, fract);
  11234. };
  11235. ShadowGenerator.prototype.dispose = function () {
  11236. this._shadowMap.dispose();
  11237. if (this._shadowMap2) {
  11238. this._shadowMap2.dispose();
  11239. }
  11240. if (this._downSamplePostprocess) {
  11241. this._downSamplePostprocess.dispose();
  11242. }
  11243. if (this._boxBlurPostprocess) {
  11244. this._boxBlurPostprocess.dispose();
  11245. }
  11246. };
  11247. ShadowGenerator.prototype.serialize = function () {
  11248. var serializationObject = {};
  11249. serializationObject.lightId = this._light.id;
  11250. serializationObject.mapSize = this.getShadowMap().getRenderSize();
  11251. serializationObject.useVarianceShadowMap = this.useVarianceShadowMap;
  11252. serializationObject.usePoissonSampling = this.usePoissonSampling;
  11253. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  11254. serializationObject.renderList = [];
  11255. for (var meshIndex = 0; meshIndex < this.getShadowMap().renderList.length; meshIndex++) {
  11256. var mesh = this.getShadowMap().renderList[meshIndex];
  11257. serializationObject.renderList.push(mesh.id);
  11258. }
  11259. return serializationObject;
  11260. };
  11261. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  11262. //casting to point light, as light is missing the position attr and typescript complains.
  11263. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  11264. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  11265. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  11266. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  11267. meshes.forEach(function (mesh) {
  11268. shadowGenerator.getShadowMap().renderList.push(mesh);
  11269. });
  11270. }
  11271. if (parsedShadowGenerator.usePoissonSampling) {
  11272. shadowGenerator.usePoissonSampling = true;
  11273. }
  11274. else if (parsedShadowGenerator.useVarianceShadowMap) {
  11275. shadowGenerator.useVarianceShadowMap = true;
  11276. }
  11277. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  11278. shadowGenerator.useBlurVarianceShadowMap = true;
  11279. if (parsedShadowGenerator.blurScale) {
  11280. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  11281. }
  11282. if (parsedShadowGenerator.blurBoxOffset) {
  11283. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  11284. }
  11285. }
  11286. if (parsedShadowGenerator.bias !== undefined) {
  11287. shadowGenerator.bias = parsedShadowGenerator.bias;
  11288. }
  11289. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  11290. return shadowGenerator;
  11291. };
  11292. ShadowGenerator._FILTER_NONE = 0;
  11293. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  11294. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  11295. ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP = 3;
  11296. return ShadowGenerator;
  11297. }());
  11298. BABYLON.ShadowGenerator = ShadowGenerator;
  11299. })(BABYLON || (BABYLON = {}));
  11300. var BABYLON;
  11301. (function (BABYLON) {
  11302. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  11303. if (boxMin.x > sphereCenter.x + sphereRadius)
  11304. return false;
  11305. if (sphereCenter.x - sphereRadius > boxMax.x)
  11306. return false;
  11307. if (boxMin.y > sphereCenter.y + sphereRadius)
  11308. return false;
  11309. if (sphereCenter.y - sphereRadius > boxMax.y)
  11310. return false;
  11311. if (boxMin.z > sphereCenter.z + sphereRadius)
  11312. return false;
  11313. if (sphereCenter.z - sphereRadius > boxMax.z)
  11314. return false;
  11315. return true;
  11316. };
  11317. var getLowestRoot = (function () {
  11318. var result = { root: 0, found: false };
  11319. return function (a, b, c, maxR) {
  11320. result.root = 0;
  11321. result.found = false;
  11322. var determinant = b * b - 4.0 * a * c;
  11323. if (determinant < 0)
  11324. return result;
  11325. var sqrtD = Math.sqrt(determinant);
  11326. var r1 = (-b - sqrtD) / (2.0 * a);
  11327. var r2 = (-b + sqrtD) / (2.0 * a);
  11328. if (r1 > r2) {
  11329. var temp = r2;
  11330. r2 = r1;
  11331. r1 = temp;
  11332. }
  11333. if (r1 > 0 && r1 < maxR) {
  11334. result.root = r1;
  11335. result.found = true;
  11336. return result;
  11337. }
  11338. if (r2 > 0 && r2 < maxR) {
  11339. result.root = r2;
  11340. result.found = true;
  11341. return result;
  11342. }
  11343. return result;
  11344. };
  11345. })();
  11346. var Collider = (function () {
  11347. function Collider() {
  11348. this.radius = new BABYLON.Vector3(1, 1, 1);
  11349. this.retry = 0;
  11350. this.basePointWorld = BABYLON.Vector3.Zero();
  11351. this.velocityWorld = BABYLON.Vector3.Zero();
  11352. this.normalizedVelocity = BABYLON.Vector3.Zero();
  11353. this._collisionPoint = BABYLON.Vector3.Zero();
  11354. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  11355. this._tempVector = BABYLON.Vector3.Zero();
  11356. this._tempVector2 = BABYLON.Vector3.Zero();
  11357. this._tempVector3 = BABYLON.Vector3.Zero();
  11358. this._tempVector4 = BABYLON.Vector3.Zero();
  11359. this._edge = BABYLON.Vector3.Zero();
  11360. this._baseToVertex = BABYLON.Vector3.Zero();
  11361. this._destinationPoint = BABYLON.Vector3.Zero();
  11362. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  11363. this._displacementVector = BABYLON.Vector3.Zero();
  11364. }
  11365. // Methods
  11366. Collider.prototype._initialize = function (source, dir, e) {
  11367. this.velocity = dir;
  11368. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  11369. this.basePoint = source;
  11370. source.multiplyToRef(this.radius, this.basePointWorld);
  11371. dir.multiplyToRef(this.radius, this.velocityWorld);
  11372. this.velocityWorldLength = this.velocityWorld.length();
  11373. this.epsilon = e;
  11374. this.collisionFound = false;
  11375. };
  11376. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  11377. pa.subtractToRef(point, this._tempVector);
  11378. pb.subtractToRef(point, this._tempVector2);
  11379. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  11380. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  11381. if (d < 0)
  11382. return false;
  11383. pc.subtractToRef(point, this._tempVector3);
  11384. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  11385. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  11386. if (d < 0)
  11387. return false;
  11388. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  11389. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  11390. return d >= 0;
  11391. };
  11392. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  11393. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  11394. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  11395. if (distance > this.velocityWorldLength + max + sphereRadius) {
  11396. return false;
  11397. }
  11398. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  11399. return false;
  11400. return true;
  11401. };
  11402. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  11403. var t0;
  11404. var embeddedInPlane = false;
  11405. //defensive programming, actually not needed.
  11406. if (!trianglePlaneArray) {
  11407. trianglePlaneArray = [];
  11408. }
  11409. if (!trianglePlaneArray[faceIndex]) {
  11410. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  11411. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  11412. }
  11413. var trianglePlane = trianglePlaneArray[faceIndex];
  11414. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  11415. return;
  11416. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  11417. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  11418. if (normalDotVelocity == 0) {
  11419. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  11420. return;
  11421. embeddedInPlane = true;
  11422. t0 = 0;
  11423. }
  11424. else {
  11425. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  11426. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  11427. if (t0 > t1) {
  11428. var temp = t1;
  11429. t1 = t0;
  11430. t0 = temp;
  11431. }
  11432. if (t0 > 1.0 || t1 < 0.0)
  11433. return;
  11434. if (t0 < 0)
  11435. t0 = 0;
  11436. if (t0 > 1.0)
  11437. t0 = 1.0;
  11438. }
  11439. this._collisionPoint.copyFromFloats(0, 0, 0);
  11440. var found = false;
  11441. var t = 1.0;
  11442. if (!embeddedInPlane) {
  11443. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  11444. this.velocity.scaleToRef(t0, this._tempVector);
  11445. this._planeIntersectionPoint.addInPlace(this._tempVector);
  11446. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  11447. found = true;
  11448. t = t0;
  11449. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  11450. }
  11451. }
  11452. if (!found) {
  11453. var velocitySquaredLength = this.velocity.lengthSquared();
  11454. var a = velocitySquaredLength;
  11455. this.basePoint.subtractToRef(p1, this._tempVector);
  11456. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  11457. var c = this._tempVector.lengthSquared() - 1.0;
  11458. var lowestRoot = getLowestRoot(a, b, c, t);
  11459. if (lowestRoot.found) {
  11460. t = lowestRoot.root;
  11461. found = true;
  11462. this._collisionPoint.copyFrom(p1);
  11463. }
  11464. this.basePoint.subtractToRef(p2, this._tempVector);
  11465. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  11466. c = this._tempVector.lengthSquared() - 1.0;
  11467. lowestRoot = getLowestRoot(a, b, c, t);
  11468. if (lowestRoot.found) {
  11469. t = lowestRoot.root;
  11470. found = true;
  11471. this._collisionPoint.copyFrom(p2);
  11472. }
  11473. this.basePoint.subtractToRef(p3, this._tempVector);
  11474. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  11475. c = this._tempVector.lengthSquared() - 1.0;
  11476. lowestRoot = getLowestRoot(a, b, c, t);
  11477. if (lowestRoot.found) {
  11478. t = lowestRoot.root;
  11479. found = true;
  11480. this._collisionPoint.copyFrom(p3);
  11481. }
  11482. p2.subtractToRef(p1, this._edge);
  11483. p1.subtractToRef(this.basePoint, this._baseToVertex);
  11484. var edgeSquaredLength = this._edge.lengthSquared();
  11485. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  11486. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  11487. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  11488. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  11489. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  11490. lowestRoot = getLowestRoot(a, b, c, t);
  11491. if (lowestRoot.found) {
  11492. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  11493. if (f >= 0.0 && f <= 1.0) {
  11494. t = lowestRoot.root;
  11495. found = true;
  11496. this._edge.scaleInPlace(f);
  11497. p1.addToRef(this._edge, this._collisionPoint);
  11498. }
  11499. }
  11500. p3.subtractToRef(p2, this._edge);
  11501. p2.subtractToRef(this.basePoint, this._baseToVertex);
  11502. edgeSquaredLength = this._edge.lengthSquared();
  11503. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  11504. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  11505. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  11506. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  11507. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  11508. lowestRoot = getLowestRoot(a, b, c, t);
  11509. if (lowestRoot.found) {
  11510. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  11511. if (f >= 0.0 && f <= 1.0) {
  11512. t = lowestRoot.root;
  11513. found = true;
  11514. this._edge.scaleInPlace(f);
  11515. p2.addToRef(this._edge, this._collisionPoint);
  11516. }
  11517. }
  11518. p1.subtractToRef(p3, this._edge);
  11519. p3.subtractToRef(this.basePoint, this._baseToVertex);
  11520. edgeSquaredLength = this._edge.lengthSquared();
  11521. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  11522. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  11523. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  11524. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  11525. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  11526. lowestRoot = getLowestRoot(a, b, c, t);
  11527. if (lowestRoot.found) {
  11528. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  11529. if (f >= 0.0 && f <= 1.0) {
  11530. t = lowestRoot.root;
  11531. found = true;
  11532. this._edge.scaleInPlace(f);
  11533. p3.addToRef(this._edge, this._collisionPoint);
  11534. }
  11535. }
  11536. }
  11537. if (found) {
  11538. var distToCollision = t * this.velocity.length();
  11539. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  11540. if (!this.intersectionPoint) {
  11541. this.intersectionPoint = this._collisionPoint.clone();
  11542. }
  11543. else {
  11544. this.intersectionPoint.copyFrom(this._collisionPoint);
  11545. }
  11546. this.nearestDistance = distToCollision;
  11547. this.collisionFound = true;
  11548. }
  11549. }
  11550. };
  11551. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  11552. for (var i = indexStart; i < indexEnd; i += 3) {
  11553. var p1 = pts[indices[i] - decal];
  11554. var p2 = pts[indices[i + 1] - decal];
  11555. var p3 = pts[indices[i + 2] - decal];
  11556. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  11557. }
  11558. };
  11559. Collider.prototype._getResponse = function (pos, vel) {
  11560. pos.addToRef(vel, this._destinationPoint);
  11561. vel.scaleInPlace((this.nearestDistance / vel.length()));
  11562. this.basePoint.addToRef(vel, pos);
  11563. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  11564. this._slidePlaneNormal.normalize();
  11565. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  11566. pos.addInPlace(this._displacementVector);
  11567. this.intersectionPoint.addInPlace(this._displacementVector);
  11568. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  11569. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  11570. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  11571. };
  11572. return Collider;
  11573. }());
  11574. BABYLON.Collider = Collider;
  11575. })(BABYLON || (BABYLON = {}));
  11576. var BABYLON;
  11577. (function (BABYLON) {
  11578. //WebWorker code will be inserted to this variable.
  11579. BABYLON.CollisionWorker = "";
  11580. (function (WorkerTaskType) {
  11581. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  11582. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  11583. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  11584. })(BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  11585. var WorkerTaskType = BABYLON.WorkerTaskType;
  11586. (function (WorkerReplyType) {
  11587. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  11588. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  11589. })(BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  11590. var WorkerReplyType = BABYLON.WorkerReplyType;
  11591. var CollisionCoordinatorWorker = (function () {
  11592. function CollisionCoordinatorWorker() {
  11593. var _this = this;
  11594. this._scaledPosition = BABYLON.Vector3.Zero();
  11595. this._scaledVelocity = BABYLON.Vector3.Zero();
  11596. this.onMeshUpdated = function (mesh) {
  11597. _this._addUpdateMeshesList[mesh.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(mesh);
  11598. };
  11599. this.onGeometryUpdated = function (geometry) {
  11600. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  11601. };
  11602. this._afterRender = function () {
  11603. if (!_this._init)
  11604. return;
  11605. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  11606. return;
  11607. }
  11608. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  11609. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  11610. if (_this._runningUpdated > 4) {
  11611. return;
  11612. }
  11613. ++_this._runningUpdated;
  11614. var payload = {
  11615. updatedMeshes: _this._addUpdateMeshesList,
  11616. updatedGeometries: _this._addUpdateGeometriesList,
  11617. removedGeometries: _this._toRemoveGeometryArray,
  11618. removedMeshes: _this._toRemoveMeshesArray
  11619. };
  11620. var message = {
  11621. payload: payload,
  11622. taskType: WorkerTaskType.UPDATE
  11623. };
  11624. var serializable = [];
  11625. for (var id in payload.updatedGeometries) {
  11626. if (payload.updatedGeometries.hasOwnProperty(id)) {
  11627. //prepare transferables
  11628. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  11629. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  11630. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  11631. }
  11632. }
  11633. _this._worker.postMessage(message, serializable);
  11634. _this._addUpdateMeshesList = {};
  11635. _this._addUpdateGeometriesList = {};
  11636. _this._toRemoveGeometryArray = [];
  11637. _this._toRemoveMeshesArray = [];
  11638. };
  11639. this._onMessageFromWorker = function (e) {
  11640. var returnData = e.data;
  11641. if (returnData.error != WorkerReplyType.SUCCESS) {
  11642. //TODO what errors can be returned from the worker?
  11643. BABYLON.Tools.Warn("error returned from worker!");
  11644. return;
  11645. }
  11646. switch (returnData.taskType) {
  11647. case WorkerTaskType.INIT:
  11648. _this._init = true;
  11649. //Update the worked with ALL of the scene's current state
  11650. _this._scene.meshes.forEach(function (mesh) {
  11651. _this.onMeshAdded(mesh);
  11652. });
  11653. _this._scene.getGeometries().forEach(function (geometry) {
  11654. _this.onGeometryAdded(geometry);
  11655. });
  11656. break;
  11657. case WorkerTaskType.UPDATE:
  11658. _this._runningUpdated--;
  11659. break;
  11660. case WorkerTaskType.COLLIDE:
  11661. _this._runningCollisionTask = false;
  11662. var returnPayload = returnData.payload;
  11663. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  11664. return;
  11665. _this._collisionsCallbackArray[returnPayload.collisionId](returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId));
  11666. //cleanup
  11667. _this._collisionsCallbackArray[returnPayload.collisionId] = undefined;
  11668. break;
  11669. }
  11670. };
  11671. this._collisionsCallbackArray = [];
  11672. this._init = false;
  11673. this._runningUpdated = 0;
  11674. this._runningCollisionTask = false;
  11675. this._addUpdateMeshesList = {};
  11676. this._addUpdateGeometriesList = {};
  11677. this._toRemoveGeometryArray = [];
  11678. this._toRemoveMeshesArray = [];
  11679. }
  11680. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  11681. if (!this._init)
  11682. return;
  11683. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  11684. return;
  11685. position.divideToRef(collider.radius, this._scaledPosition);
  11686. velocity.divideToRef(collider.radius, this._scaledVelocity);
  11687. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  11688. var payload = {
  11689. collider: {
  11690. position: this._scaledPosition.asArray(),
  11691. velocity: this._scaledVelocity.asArray(),
  11692. radius: collider.radius.asArray()
  11693. },
  11694. collisionId: collisionIndex,
  11695. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  11696. maximumRetry: maximumRetry
  11697. };
  11698. var message = {
  11699. payload: payload,
  11700. taskType: WorkerTaskType.COLLIDE
  11701. };
  11702. this._worker.postMessage(message);
  11703. };
  11704. CollisionCoordinatorWorker.prototype.init = function (scene) {
  11705. this._scene = scene;
  11706. this._scene.registerAfterRender(this._afterRender);
  11707. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  11708. this._worker = new Worker(workerUrl);
  11709. this._worker.onmessage = this._onMessageFromWorker;
  11710. var message = {
  11711. payload: {},
  11712. taskType: WorkerTaskType.INIT
  11713. };
  11714. this._worker.postMessage(message);
  11715. };
  11716. CollisionCoordinatorWorker.prototype.destroy = function () {
  11717. this._scene.unregisterAfterRender(this._afterRender);
  11718. this._worker.terminate();
  11719. };
  11720. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  11721. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  11722. this.onMeshUpdated(mesh);
  11723. };
  11724. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  11725. this._toRemoveMeshesArray.push(mesh.uniqueId);
  11726. };
  11727. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  11728. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  11729. geometry.onGeometryUpdated = this.onGeometryUpdated;
  11730. this.onGeometryUpdated(geometry);
  11731. };
  11732. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  11733. this._toRemoveGeometryArray.push(geometry.id);
  11734. };
  11735. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  11736. var submeshes = [];
  11737. if (mesh.subMeshes) {
  11738. submeshes = mesh.subMeshes.map(function (sm, idx) {
  11739. return {
  11740. position: idx,
  11741. verticesStart: sm.verticesStart,
  11742. verticesCount: sm.verticesCount,
  11743. indexStart: sm.indexStart,
  11744. indexCount: sm.indexCount,
  11745. hasMaterial: !!sm.getMaterial(),
  11746. sphereCenter: sm.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  11747. sphereRadius: sm.getBoundingInfo().boundingSphere.radiusWorld,
  11748. boxMinimum: sm.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  11749. boxMaximum: sm.getBoundingInfo().boundingBox.maximumWorld.asArray()
  11750. };
  11751. });
  11752. }
  11753. var geometryId = null;
  11754. if (mesh instanceof BABYLON.Mesh) {
  11755. geometryId = mesh.geometry ? mesh.geometry.id : null;
  11756. }
  11757. else if (mesh instanceof BABYLON.InstancedMesh) {
  11758. geometryId = (mesh.sourceMesh && mesh.sourceMesh.geometry) ? mesh.sourceMesh.geometry.id : null;
  11759. }
  11760. return {
  11761. uniqueId: mesh.uniqueId,
  11762. id: mesh.id,
  11763. name: mesh.name,
  11764. geometryId: geometryId,
  11765. sphereCenter: mesh.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  11766. sphereRadius: mesh.getBoundingInfo().boundingSphere.radiusWorld,
  11767. boxMinimum: mesh.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  11768. boxMaximum: mesh.getBoundingInfo().boundingBox.maximumWorld.asArray(),
  11769. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  11770. subMeshes: submeshes,
  11771. checkCollisions: mesh.checkCollisions
  11772. };
  11773. };
  11774. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  11775. return {
  11776. id: geometry.id,
  11777. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  11778. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  11779. indices: new Int32Array(geometry.getIndices() || []),
  11780. };
  11781. };
  11782. return CollisionCoordinatorWorker;
  11783. }());
  11784. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  11785. var CollisionCoordinatorLegacy = (function () {
  11786. function CollisionCoordinatorLegacy() {
  11787. this._scaledPosition = BABYLON.Vector3.Zero();
  11788. this._scaledVelocity = BABYLON.Vector3.Zero();
  11789. this._finalPosition = BABYLON.Vector3.Zero();
  11790. }
  11791. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  11792. position.divideToRef(collider.radius, this._scaledPosition);
  11793. velocity.divideToRef(collider.radius, this._scaledVelocity);
  11794. collider.collidedMesh = null;
  11795. collider.retry = 0;
  11796. collider.initialVelocity = this._scaledVelocity;
  11797. collider.initialPosition = this._scaledPosition;
  11798. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  11799. this._finalPosition.multiplyInPlace(collider.radius);
  11800. //run the callback
  11801. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  11802. };
  11803. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  11804. this._scene = scene;
  11805. };
  11806. CollisionCoordinatorLegacy.prototype.destroy = function () {
  11807. //Legacy need no destruction method.
  11808. };
  11809. //No update in legacy mode
  11810. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  11811. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  11812. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  11813. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  11814. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  11815. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  11816. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  11817. if (excludedMesh === void 0) { excludedMesh = null; }
  11818. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  11819. if (collider.retry >= maximumRetry) {
  11820. finalPosition.copyFrom(position);
  11821. return;
  11822. }
  11823. collider._initialize(position, velocity, closeDistance);
  11824. // Check all meshes
  11825. for (var index = 0; index < this._scene.meshes.length; index++) {
  11826. var mesh = this._scene.meshes[index];
  11827. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  11828. mesh._checkCollision(collider);
  11829. }
  11830. }
  11831. if (!collider.collisionFound) {
  11832. position.addToRef(velocity, finalPosition);
  11833. return;
  11834. }
  11835. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  11836. collider._getResponse(position, velocity);
  11837. }
  11838. if (velocity.length() <= closeDistance) {
  11839. finalPosition.copyFrom(position);
  11840. return;
  11841. }
  11842. collider.retry++;
  11843. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  11844. };
  11845. return CollisionCoordinatorLegacy;
  11846. }());
  11847. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  11848. })(BABYLON || (BABYLON = {}));
  11849. var BABYLON;
  11850. (function (BABYLON) {
  11851. var Camera = (function (_super) {
  11852. __extends(Camera, _super);
  11853. function Camera(name, position, scene) {
  11854. _super.call(this, name, scene);
  11855. this.upVector = BABYLON.Vector3.Up();
  11856. this.orthoLeft = null;
  11857. this.orthoRight = null;
  11858. this.orthoBottom = null;
  11859. this.orthoTop = null;
  11860. this.fov = 0.8;
  11861. this.minZ = 1.0;
  11862. this.maxZ = 10000.0;
  11863. this.inertia = 0.9;
  11864. this.mode = Camera.PERSPECTIVE_CAMERA;
  11865. this.isIntermediate = false;
  11866. this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  11867. this.layerMask = 0x0FFFFFFF;
  11868. this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  11869. // Camera rig members
  11870. this.cameraRigMode = Camera.RIG_MODE_NONE;
  11871. this._rigCameras = new Array();
  11872. // Cache
  11873. this._computedViewMatrix = BABYLON.Matrix.Identity();
  11874. this._projectionMatrix = new BABYLON.Matrix();
  11875. this._postProcesses = new Array();
  11876. this._transformMatrix = BABYLON.Matrix.Zero();
  11877. this._activeMeshes = new BABYLON.SmartArray(256);
  11878. this._globalPosition = BABYLON.Vector3.Zero();
  11879. this._refreshFrustumPlanes = true;
  11880. scene.addCamera(this);
  11881. if (!scene.activeCamera) {
  11882. scene.activeCamera = this;
  11883. }
  11884. this.position = position;
  11885. }
  11886. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  11887. get: function () {
  11888. return Camera._PERSPECTIVE_CAMERA;
  11889. },
  11890. enumerable: true,
  11891. configurable: true
  11892. });
  11893. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  11894. get: function () {
  11895. return Camera._ORTHOGRAPHIC_CAMERA;
  11896. },
  11897. enumerable: true,
  11898. configurable: true
  11899. });
  11900. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  11901. get: function () {
  11902. return Camera._FOVMODE_VERTICAL_FIXED;
  11903. },
  11904. enumerable: true,
  11905. configurable: true
  11906. });
  11907. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  11908. get: function () {
  11909. return Camera._FOVMODE_HORIZONTAL_FIXED;
  11910. },
  11911. enumerable: true,
  11912. configurable: true
  11913. });
  11914. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  11915. get: function () {
  11916. return Camera._RIG_MODE_NONE;
  11917. },
  11918. enumerable: true,
  11919. configurable: true
  11920. });
  11921. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  11922. get: function () {
  11923. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  11924. },
  11925. enumerable: true,
  11926. configurable: true
  11927. });
  11928. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  11929. get: function () {
  11930. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  11931. },
  11932. enumerable: true,
  11933. configurable: true
  11934. });
  11935. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  11936. get: function () {
  11937. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  11938. },
  11939. enumerable: true,
  11940. configurable: true
  11941. });
  11942. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  11943. get: function () {
  11944. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  11945. },
  11946. enumerable: true,
  11947. configurable: true
  11948. });
  11949. Object.defineProperty(Camera, "RIG_MODE_VR", {
  11950. get: function () {
  11951. return Camera._RIG_MODE_VR;
  11952. },
  11953. enumerable: true,
  11954. configurable: true
  11955. });
  11956. /**
  11957. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  11958. */
  11959. Camera.prototype.toString = function (fullDetails) {
  11960. var ret = "Name: " + this.name;
  11961. ret += ", type: " + this.getTypeName();
  11962. if (this.animations) {
  11963. for (var i = 0; i < this.animations.length; i++) {
  11964. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  11965. }
  11966. }
  11967. if (fullDetails) {
  11968. }
  11969. return ret;
  11970. };
  11971. Object.defineProperty(Camera.prototype, "globalPosition", {
  11972. get: function () {
  11973. return this._globalPosition;
  11974. },
  11975. enumerable: true,
  11976. configurable: true
  11977. });
  11978. Camera.prototype.getActiveMeshes = function () {
  11979. return this._activeMeshes;
  11980. };
  11981. Camera.prototype.isActiveMesh = function (mesh) {
  11982. return (this._activeMeshes.indexOf(mesh) !== -1);
  11983. };
  11984. //Cache
  11985. Camera.prototype._initCache = function () {
  11986. _super.prototype._initCache.call(this);
  11987. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  11988. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  11989. this._cache.mode = undefined;
  11990. this._cache.minZ = undefined;
  11991. this._cache.maxZ = undefined;
  11992. this._cache.fov = undefined;
  11993. this._cache.aspectRatio = undefined;
  11994. this._cache.orthoLeft = undefined;
  11995. this._cache.orthoRight = undefined;
  11996. this._cache.orthoBottom = undefined;
  11997. this._cache.orthoTop = undefined;
  11998. this._cache.renderWidth = undefined;
  11999. this._cache.renderHeight = undefined;
  12000. };
  12001. Camera.prototype._updateCache = function (ignoreParentClass) {
  12002. if (!ignoreParentClass) {
  12003. _super.prototype._updateCache.call(this);
  12004. }
  12005. var engine = this.getEngine();
  12006. this._cache.position.copyFrom(this.position);
  12007. this._cache.upVector.copyFrom(this.upVector);
  12008. this._cache.mode = this.mode;
  12009. this._cache.minZ = this.minZ;
  12010. this._cache.maxZ = this.maxZ;
  12011. this._cache.fov = this.fov;
  12012. this._cache.aspectRatio = engine.getAspectRatio(this);
  12013. this._cache.orthoLeft = this.orthoLeft;
  12014. this._cache.orthoRight = this.orthoRight;
  12015. this._cache.orthoBottom = this.orthoBottom;
  12016. this._cache.orthoTop = this.orthoTop;
  12017. this._cache.renderWidth = engine.getRenderWidth();
  12018. this._cache.renderHeight = engine.getRenderHeight();
  12019. };
  12020. Camera.prototype._updateFromScene = function () {
  12021. this.updateCache();
  12022. this.update();
  12023. };
  12024. // Synchronized
  12025. Camera.prototype._isSynchronized = function () {
  12026. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  12027. };
  12028. Camera.prototype._isSynchronizedViewMatrix = function () {
  12029. if (!_super.prototype._isSynchronized.call(this))
  12030. return false;
  12031. return this._cache.position.equals(this.position)
  12032. && this._cache.upVector.equals(this.upVector)
  12033. && this.isSynchronizedWithParent();
  12034. };
  12035. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  12036. var check = this._cache.mode === this.mode
  12037. && this._cache.minZ === this.minZ
  12038. && this._cache.maxZ === this.maxZ;
  12039. if (!check) {
  12040. return false;
  12041. }
  12042. var engine = this.getEngine();
  12043. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  12044. check = this._cache.fov === this.fov
  12045. && this._cache.aspectRatio === engine.getAspectRatio(this);
  12046. }
  12047. else {
  12048. check = this._cache.orthoLeft === this.orthoLeft
  12049. && this._cache.orthoRight === this.orthoRight
  12050. && this._cache.orthoBottom === this.orthoBottom
  12051. && this._cache.orthoTop === this.orthoTop
  12052. && this._cache.renderWidth === engine.getRenderWidth()
  12053. && this._cache.renderHeight === engine.getRenderHeight();
  12054. }
  12055. return check;
  12056. };
  12057. // Controls
  12058. Camera.prototype.attachControl = function (element, noPreventDefault) {
  12059. };
  12060. Camera.prototype.detachControl = function (element) {
  12061. };
  12062. Camera.prototype.update = function () {
  12063. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  12064. this._updateRigCameras();
  12065. }
  12066. this._checkInputs();
  12067. };
  12068. Camera.prototype._checkInputs = function () {
  12069. };
  12070. Camera.prototype._cascadePostProcessesToRigCams = function () {
  12071. // invalidate framebuffer
  12072. if (this._postProcesses.length > 0) {
  12073. this._postProcesses[0].markTextureDirty();
  12074. }
  12075. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  12076. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  12077. var cam = this._rigCameras[i];
  12078. var rigPostProcess = cam._rigPostProcess;
  12079. // for VR rig, there does not have to be a post process
  12080. if (rigPostProcess) {
  12081. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  12082. if (isPass) {
  12083. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  12084. cam.isIntermediate = this._postProcesses.length === 0;
  12085. }
  12086. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  12087. rigPostProcess.markTextureDirty();
  12088. }
  12089. else {
  12090. cam._postProcesses = this._postProcesses.slice(0);
  12091. }
  12092. }
  12093. };
  12094. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  12095. if (insertAt === void 0) { insertAt = null; }
  12096. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  12097. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  12098. return 0;
  12099. }
  12100. if (insertAt == null || insertAt < 0) {
  12101. this._postProcesses.push(postProcess);
  12102. }
  12103. else {
  12104. this._postProcesses.splice(insertAt, 0, postProcess);
  12105. }
  12106. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  12107. return this._postProcesses.indexOf(postProcess);
  12108. };
  12109. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  12110. if (atIndices === void 0) { atIndices = null; }
  12111. var result = [];
  12112. var i;
  12113. var index;
  12114. if (!atIndices) {
  12115. var idx = this._postProcesses.indexOf(postProcess);
  12116. if (idx !== -1) {
  12117. this._postProcesses.splice(idx, 1);
  12118. }
  12119. }
  12120. else {
  12121. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  12122. // iterate descending, so can just splice as we go
  12123. for (i = atIndices.length - 1; i >= 0; i--) {
  12124. if (this._postProcesses[atIndices[i]] !== postProcess) {
  12125. result.push(i);
  12126. continue;
  12127. }
  12128. this._postProcesses.splice(index, 1);
  12129. }
  12130. }
  12131. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  12132. return result;
  12133. };
  12134. Camera.prototype.getWorldMatrix = function () {
  12135. if (!this._worldMatrix) {
  12136. this._worldMatrix = BABYLON.Matrix.Identity();
  12137. }
  12138. var viewMatrix = this.getViewMatrix();
  12139. viewMatrix.invertToRef(this._worldMatrix);
  12140. return this._worldMatrix;
  12141. };
  12142. Camera.prototype._getViewMatrix = function () {
  12143. return BABYLON.Matrix.Identity();
  12144. };
  12145. Camera.prototype.getViewMatrix = function (force) {
  12146. this._computedViewMatrix = this._computeViewMatrix(force);
  12147. if (!force && this._isSynchronizedViewMatrix()) {
  12148. return this._computedViewMatrix;
  12149. }
  12150. this._refreshFrustumPlanes = true;
  12151. if (!this.parent || !this.parent.getWorldMatrix) {
  12152. this._globalPosition.copyFrom(this.position);
  12153. }
  12154. else {
  12155. if (!this._worldMatrix) {
  12156. this._worldMatrix = BABYLON.Matrix.Identity();
  12157. }
  12158. this._computedViewMatrix.invertToRef(this._worldMatrix);
  12159. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  12160. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  12161. this._computedViewMatrix.invert();
  12162. this._markSyncedWithParent();
  12163. }
  12164. this._currentRenderId = this.getScene().getRenderId();
  12165. return this._computedViewMatrix;
  12166. };
  12167. Camera.prototype._computeViewMatrix = function (force) {
  12168. if (!force && this._isSynchronizedViewMatrix()) {
  12169. return this._computedViewMatrix;
  12170. }
  12171. this._computedViewMatrix = this._getViewMatrix();
  12172. this._currentRenderId = this.getScene().getRenderId();
  12173. return this._computedViewMatrix;
  12174. };
  12175. Camera.prototype.getProjectionMatrix = function (force) {
  12176. if (!force && this._isSynchronizedProjectionMatrix()) {
  12177. return this._projectionMatrix;
  12178. }
  12179. this._refreshFrustumPlanes = true;
  12180. var engine = this.getEngine();
  12181. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  12182. if (this.minZ <= 0) {
  12183. this.minZ = 0.1;
  12184. }
  12185. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  12186. return this._projectionMatrix;
  12187. }
  12188. var halfWidth = engine.getRenderWidth() / 2.0;
  12189. var halfHeight = engine.getRenderHeight() / 2.0;
  12190. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  12191. return this._projectionMatrix;
  12192. };
  12193. Camera.prototype.getTranformationMatrix = function () {
  12194. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  12195. return this._transformMatrix;
  12196. };
  12197. Camera.prototype.updateFrustumPlanes = function () {
  12198. if (!this._refreshFrustumPlanes) {
  12199. return;
  12200. }
  12201. this.getTranformationMatrix();
  12202. if (!this._frustumPlanes) {
  12203. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  12204. }
  12205. else {
  12206. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  12207. }
  12208. this._refreshFrustumPlanes = false;
  12209. };
  12210. Camera.prototype.isInFrustum = function (target) {
  12211. this.updateFrustumPlanes();
  12212. return target.isInFrustum(this._frustumPlanes);
  12213. };
  12214. Camera.prototype.isCompletelyInFrustum = function (target) {
  12215. this.updateFrustumPlanes();
  12216. return target.isCompletelyInFrustum(this._frustumPlanes);
  12217. };
  12218. Camera.prototype.dispose = function () {
  12219. // Animations
  12220. this.getScene().stopAnimation(this);
  12221. // Remove from scene
  12222. this.getScene().removeCamera(this);
  12223. while (this._rigCameras.length > 0) {
  12224. this._rigCameras.pop().dispose();
  12225. }
  12226. // Postprocesses
  12227. for (var i = 0; i < this._postProcesses.length; ++i) {
  12228. this._postProcesses[i].dispose(this);
  12229. }
  12230. _super.prototype.dispose.call(this);
  12231. };
  12232. // ---- Camera rigs section ----
  12233. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  12234. while (this._rigCameras.length > 0) {
  12235. this._rigCameras.pop().dispose();
  12236. }
  12237. this.cameraRigMode = mode;
  12238. this._cameraRigParams = {};
  12239. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  12240. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  12241. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  12242. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  12243. // create the rig cameras, unless none
  12244. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  12245. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  12246. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  12247. }
  12248. switch (this.cameraRigMode) {
  12249. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  12250. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  12251. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  12252. break;
  12253. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  12254. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  12255. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  12256. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  12257. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  12258. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  12259. break;
  12260. case Camera.RIG_MODE_VR:
  12261. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  12262. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  12263. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  12264. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  12265. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  12266. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  12267. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  12268. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  12269. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  12270. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  12271. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  12272. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  12273. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  12274. if (metrics.compensateDistortion) {
  12275. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  12276. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  12277. }
  12278. break;
  12279. }
  12280. this._cascadePostProcessesToRigCams();
  12281. this.
  12282. update();
  12283. };
  12284. Camera.prototype._getVRProjectionMatrix = function () {
  12285. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  12286. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  12287. return this._projectionMatrix;
  12288. };
  12289. Camera.prototype.setCameraRigParameter = function (name, value) {
  12290. if (!this._cameraRigParams) {
  12291. this._cameraRigParams = {};
  12292. }
  12293. this._cameraRigParams[name] = value;
  12294. //provisionnally:
  12295. if (name === "interaxialDistance") {
  12296. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  12297. }
  12298. };
  12299. /**
  12300. * needs to be overridden by children so sub has required properties to be copied
  12301. */
  12302. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  12303. return null;
  12304. };
  12305. /**
  12306. * May need to be overridden by children
  12307. */
  12308. Camera.prototype._updateRigCameras = function () {
  12309. for (var i = 0; i < this._rigCameras.length; i++) {
  12310. this._rigCameras[i].minZ = this.minZ;
  12311. this._rigCameras[i].maxZ = this.maxZ;
  12312. this._rigCameras[i].fov = this.fov;
  12313. }
  12314. // only update viewport when ANAGLYPH
  12315. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  12316. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  12317. }
  12318. };
  12319. Camera.prototype._setupInputs = function () {
  12320. };
  12321. Camera.prototype.serialize = function () {
  12322. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  12323. // Type
  12324. serializationObject.type = this.getTypeName();
  12325. // Parent
  12326. if (this.parent) {
  12327. serializationObject.parentId = this.parent.id;
  12328. }
  12329. if (this.inputs) {
  12330. this.inputs.serialize(serializationObject);
  12331. }
  12332. // Animations
  12333. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  12334. serializationObject.ranges = this.serializeAnimationRanges();
  12335. return serializationObject;
  12336. };
  12337. Camera.prototype.getTypeName = function () {
  12338. return "Camera";
  12339. };
  12340. Camera.prototype.clone = function (name) {
  12341. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getTypeName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  12342. };
  12343. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  12344. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  12345. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  12346. switch (type) {
  12347. case "ArcRotateCamera":
  12348. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  12349. case "DeviceOrientationCamera":
  12350. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  12351. case "FollowCamera":
  12352. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  12353. case "ArcFollowCamera":
  12354. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  12355. case "GamepadCamera":
  12356. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  12357. case "TouchCamera":
  12358. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  12359. case "VirtualJoysticksCamera":
  12360. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  12361. case "WebVRFreeCamera":
  12362. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  12363. case "VRDeviceOrientationFreeCamera":
  12364. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  12365. case "AnaglyphArcRotateCamera":
  12366. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  12367. case "AnaglyphFreeCamera":
  12368. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  12369. case "AnaglyphGamepadCamera":
  12370. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  12371. case "AnaglyphUniversalCamera":
  12372. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  12373. case "StereoscopicArcRotateCamera":
  12374. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  12375. case "StereoscopicFreeCamera":
  12376. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  12377. case "StereoscopicGamepadCamera":
  12378. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  12379. case "StereoscopicUniversalCamera":
  12380. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  12381. case "FreeCamera":
  12382. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  12383. default:
  12384. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  12385. }
  12386. };
  12387. Camera.Parse = function (parsedCamera, scene) {
  12388. var type = parsedCamera.type;
  12389. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  12390. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  12391. // Parent
  12392. if (parsedCamera.parentId) {
  12393. camera._waitingParentId = parsedCamera.parentId;
  12394. }
  12395. //If camera has an input manager, let it parse inputs settings
  12396. if (camera.inputs) {
  12397. camera.inputs.parse(parsedCamera);
  12398. camera._setupInputs();
  12399. }
  12400. // Target
  12401. if (parsedCamera.target) {
  12402. if (camera.setTarget) {
  12403. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  12404. }
  12405. }
  12406. // Apply 3d rig, when found
  12407. if (parsedCamera.cameraRigMode) {
  12408. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  12409. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  12410. }
  12411. // Animations
  12412. if (parsedCamera.animations) {
  12413. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  12414. var parsedAnimation = parsedCamera.animations[animationIndex];
  12415. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  12416. }
  12417. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  12418. }
  12419. if (parsedCamera.autoAnimate) {
  12420. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  12421. }
  12422. return camera;
  12423. };
  12424. // Statics
  12425. Camera._PERSPECTIVE_CAMERA = 0;
  12426. Camera._ORTHOGRAPHIC_CAMERA = 1;
  12427. Camera._FOVMODE_VERTICAL_FIXED = 0;
  12428. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  12429. Camera._RIG_MODE_NONE = 0;
  12430. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  12431. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  12432. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  12433. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  12434. Camera._RIG_MODE_VR = 20;
  12435. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  12436. __decorate([
  12437. BABYLON.serializeAsVector3()
  12438. ], Camera.prototype, "position", void 0);
  12439. __decorate([
  12440. BABYLON.serializeAsVector3()
  12441. ], Camera.prototype, "upVector", void 0);
  12442. __decorate([
  12443. BABYLON.serialize()
  12444. ], Camera.prototype, "orthoLeft", void 0);
  12445. __decorate([
  12446. BABYLON.serialize()
  12447. ], Camera.prototype, "orthoRight", void 0);
  12448. __decorate([
  12449. BABYLON.serialize()
  12450. ], Camera.prototype, "orthoBottom", void 0);
  12451. __decorate([
  12452. BABYLON.serialize()
  12453. ], Camera.prototype, "orthoTop", void 0);
  12454. __decorate([
  12455. BABYLON.serialize()
  12456. ], Camera.prototype, "fov", void 0);
  12457. __decorate([
  12458. BABYLON.serialize()
  12459. ], Camera.prototype, "minZ", void 0);
  12460. __decorate([
  12461. BABYLON.serialize()
  12462. ], Camera.prototype, "maxZ", void 0);
  12463. __decorate([
  12464. BABYLON.serialize()
  12465. ], Camera.prototype, "inertia", void 0);
  12466. __decorate([
  12467. BABYLON.serialize()
  12468. ], Camera.prototype, "mode", void 0);
  12469. __decorate([
  12470. BABYLON.serialize()
  12471. ], Camera.prototype, "layerMask", void 0);
  12472. __decorate([
  12473. BABYLON.serialize()
  12474. ], Camera.prototype, "fovMode", void 0);
  12475. __decorate([
  12476. BABYLON.serialize()
  12477. ], Camera.prototype, "cameraRigMode", void 0);
  12478. __decorate([
  12479. BABYLON.serialize()
  12480. ], Camera.prototype, "interaxialDistance", void 0);
  12481. __decorate([
  12482. BABYLON.serialize()
  12483. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  12484. return Camera;
  12485. }(BABYLON.Node));
  12486. BABYLON.Camera = Camera;
  12487. })(BABYLON || (BABYLON = {}));
  12488. var BABYLON;
  12489. (function (BABYLON) {
  12490. BABYLON.CameraInputTypes = {};
  12491. var CameraInputsManager = (function () {
  12492. function CameraInputsManager(camera) {
  12493. this.attached = {};
  12494. this.camera = camera;
  12495. this.checkInputs = function () { };
  12496. }
  12497. CameraInputsManager.prototype.add = function (input) {
  12498. var type = input.getSimpleName();
  12499. if (this.attached[type]) {
  12500. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  12501. return;
  12502. }
  12503. this.attached[type] = input;
  12504. input.camera = this.camera;
  12505. //for checkInputs, we are dynamically creating a function
  12506. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  12507. if (input.checkInputs) {
  12508. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  12509. }
  12510. if (this.attachedElement) {
  12511. input.attachControl(this.attachedElement);
  12512. }
  12513. };
  12514. CameraInputsManager.prototype.remove = function (inputToRemove) {
  12515. for (var cam in this.attached) {
  12516. var input = this.attached[cam];
  12517. if (input === inputToRemove) {
  12518. input.detachControl(this.attachedElement);
  12519. delete this.attached[cam];
  12520. this.rebuildInputCheck();
  12521. }
  12522. }
  12523. };
  12524. CameraInputsManager.prototype.removeByType = function (inputType) {
  12525. for (var cam in this.attached) {
  12526. var input = this.attached[cam];
  12527. if (input.getTypeName() === inputType) {
  12528. input.detachControl(this.attachedElement);
  12529. delete this.attached[cam];
  12530. this.rebuildInputCheck();
  12531. }
  12532. }
  12533. };
  12534. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  12535. var current = this.checkInputs;
  12536. return function () {
  12537. current();
  12538. fn();
  12539. };
  12540. };
  12541. CameraInputsManager.prototype.attachInput = function (input) {
  12542. input.attachControl(this.attachedElement, this.noPreventDefault);
  12543. };
  12544. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  12545. if (this.attachedElement) {
  12546. return;
  12547. }
  12548. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  12549. this.attachedElement = element;
  12550. this.noPreventDefault = noPreventDefault;
  12551. for (var cam in this.attached) {
  12552. var input = this.attached[cam];
  12553. this.attached[cam].attachControl(element, noPreventDefault);
  12554. }
  12555. };
  12556. CameraInputsManager.prototype.detachElement = function (element) {
  12557. if (this.attachedElement !== element) {
  12558. return;
  12559. }
  12560. for (var cam in this.attached) {
  12561. var input = this.attached[cam];
  12562. this.attached[cam].detachControl(element);
  12563. }
  12564. this.attachedElement = null;
  12565. };
  12566. CameraInputsManager.prototype.rebuildInputCheck = function () {
  12567. this.checkInputs = function () { };
  12568. for (var cam in this.attached) {
  12569. var input = this.attached[cam];
  12570. if (input.checkInputs) {
  12571. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  12572. }
  12573. }
  12574. };
  12575. CameraInputsManager.prototype.clear = function () {
  12576. if (this.attachedElement) {
  12577. this.detachElement(this.attachedElement);
  12578. }
  12579. this.attached = {};
  12580. this.attachedElement = null;
  12581. this.checkInputs = function () { };
  12582. };
  12583. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  12584. var inputs = {};
  12585. for (var cam in this.attached) {
  12586. var input = this.attached[cam];
  12587. var res = BABYLON.SerializationHelper.Serialize(input);
  12588. inputs[input.getTypeName()] = res;
  12589. }
  12590. serializedCamera.inputsmgr = inputs;
  12591. };
  12592. CameraInputsManager.prototype.parse = function (parsedCamera) {
  12593. var parsedInputs = parsedCamera.inputsmgr;
  12594. if (parsedInputs) {
  12595. this.clear();
  12596. for (var n in parsedInputs) {
  12597. var construct = BABYLON.CameraInputTypes[n];
  12598. if (construct) {
  12599. var parsedinput = parsedInputs[n];
  12600. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  12601. this.add(input);
  12602. }
  12603. }
  12604. }
  12605. else {
  12606. //2016-03-08 this part is for managing backward compatibility
  12607. for (var n in this.attached) {
  12608. var construct = BABYLON.CameraInputTypes[this.attached[n].getTypeName()];
  12609. if (construct) {
  12610. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  12611. this.remove(this.attached[n]);
  12612. this.add(input);
  12613. }
  12614. }
  12615. }
  12616. };
  12617. return CameraInputsManager;
  12618. }());
  12619. BABYLON.CameraInputsManager = CameraInputsManager;
  12620. })(BABYLON || (BABYLON = {}));
  12621. var BABYLON;
  12622. (function (BABYLON) {
  12623. var FreeCameraMouseInput = (function () {
  12624. function FreeCameraMouseInput(touchEnabled) {
  12625. if (touchEnabled === void 0) { touchEnabled = true; }
  12626. this.touchEnabled = touchEnabled;
  12627. this.angularSensibility = 2000.0;
  12628. }
  12629. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  12630. var _this = this;
  12631. if (!this._pointerInput) {
  12632. var camera = this.camera;
  12633. var engine = this.camera.getEngine();
  12634. this._pointerInput = function (p, s) {
  12635. var evt = p.event;
  12636. if (!_this.touchEnabled && evt.pointerType === "touch") {
  12637. return;
  12638. }
  12639. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  12640. try {
  12641. evt.srcElement.setPointerCapture(evt.pointerId);
  12642. }
  12643. catch (e) {
  12644. }
  12645. _this.previousPosition = {
  12646. x: evt.clientX,
  12647. y: evt.clientY
  12648. };
  12649. if (!noPreventDefault) {
  12650. evt.preventDefault();
  12651. element.focus();
  12652. }
  12653. }
  12654. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  12655. try {
  12656. evt.srcElement.releasePointerCapture(evt.pointerId);
  12657. }
  12658. catch (e) {
  12659. }
  12660. _this.previousPosition = null;
  12661. if (!noPreventDefault) {
  12662. evt.preventDefault();
  12663. }
  12664. }
  12665. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  12666. if (!_this.previousPosition && !engine.isPointerLock) {
  12667. return;
  12668. }
  12669. var offsetX;
  12670. var offsetY;
  12671. if (!engine.isPointerLock) {
  12672. offsetX = evt.clientX - _this.previousPosition.x;
  12673. offsetY = evt.clientY - _this.previousPosition.y;
  12674. }
  12675. else {
  12676. offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  12677. offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  12678. }
  12679. camera.cameraRotation.y += offsetX / _this.angularSensibility;
  12680. camera.cameraRotation.x += offsetY / _this.angularSensibility;
  12681. _this.previousPosition = {
  12682. x: evt.clientX,
  12683. y: evt.clientY
  12684. };
  12685. if (!noPreventDefault) {
  12686. evt.preventDefault();
  12687. }
  12688. }
  12689. };
  12690. }
  12691. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  12692. };
  12693. FreeCameraMouseInput.prototype.detachControl = function (element) {
  12694. if (this._observer && element) {
  12695. this.camera.getScene().onPointerObservable.remove(this._observer);
  12696. this._observer = null;
  12697. this.previousPosition = null;
  12698. }
  12699. };
  12700. FreeCameraMouseInput.prototype.getTypeName = function () {
  12701. return "FreeCameraMouseInput";
  12702. };
  12703. FreeCameraMouseInput.prototype.getSimpleName = function () {
  12704. return "mouse";
  12705. };
  12706. __decorate([
  12707. BABYLON.serialize()
  12708. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  12709. return FreeCameraMouseInput;
  12710. }());
  12711. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  12712. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  12713. })(BABYLON || (BABYLON = {}));
  12714. var BABYLON;
  12715. (function (BABYLON) {
  12716. var FreeCameraKeyboardMoveInput = (function () {
  12717. function FreeCameraKeyboardMoveInput() {
  12718. this._keys = [];
  12719. this.keysUp = [38];
  12720. this.keysDown = [40];
  12721. this.keysLeft = [37];
  12722. this.keysRight = [39];
  12723. }
  12724. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  12725. var _this = this;
  12726. if (!this._onKeyDown) {
  12727. element.tabIndex = 1;
  12728. this._onKeyDown = function (evt) {
  12729. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  12730. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  12731. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  12732. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  12733. var index = _this._keys.indexOf(evt.keyCode);
  12734. if (index === -1) {
  12735. _this._keys.push(evt.keyCode);
  12736. }
  12737. if (!noPreventDefault) {
  12738. evt.preventDefault();
  12739. }
  12740. }
  12741. };
  12742. this._onKeyUp = function (evt) {
  12743. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  12744. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  12745. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  12746. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  12747. var index = _this._keys.indexOf(evt.keyCode);
  12748. if (index >= 0) {
  12749. _this._keys.splice(index, 1);
  12750. }
  12751. if (!noPreventDefault) {
  12752. evt.preventDefault();
  12753. }
  12754. }
  12755. };
  12756. element.addEventListener("keydown", this._onKeyDown, false);
  12757. element.addEventListener("keyup", this._onKeyUp, false);
  12758. BABYLON.Tools.RegisterTopRootEvents([
  12759. { name: "blur", handler: this._onLostFocus }
  12760. ]);
  12761. }
  12762. };
  12763. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  12764. if (this._onKeyDown) {
  12765. element.removeEventListener("keydown", this._onKeyDown);
  12766. element.removeEventListener("keyup", this._onKeyUp);
  12767. BABYLON.Tools.UnregisterTopRootEvents([
  12768. { name: "blur", handler: this._onLostFocus }
  12769. ]);
  12770. this._keys = [];
  12771. this._onKeyDown = null;
  12772. this._onKeyUp = null;
  12773. }
  12774. };
  12775. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  12776. if (this._onKeyDown) {
  12777. var camera = this.camera;
  12778. // Keyboard
  12779. for (var index = 0; index < this._keys.length; index++) {
  12780. var keyCode = this._keys[index];
  12781. var speed = camera._computeLocalCameraSpeed();
  12782. if (this.keysLeft.indexOf(keyCode) !== -1) {
  12783. camera._localDirection.copyFromFloats(-speed, 0, 0);
  12784. }
  12785. else if (this.keysUp.indexOf(keyCode) !== -1) {
  12786. camera._localDirection.copyFromFloats(0, 0, speed);
  12787. }
  12788. else if (this.keysRight.indexOf(keyCode) !== -1) {
  12789. camera._localDirection.copyFromFloats(speed, 0, 0);
  12790. }
  12791. else if (this.keysDown.indexOf(keyCode) !== -1) {
  12792. camera._localDirection.copyFromFloats(0, 0, -speed);
  12793. }
  12794. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  12795. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  12796. camera.cameraDirection.addInPlace(camera._transformedDirection);
  12797. }
  12798. }
  12799. };
  12800. FreeCameraKeyboardMoveInput.prototype.getTypeName = function () {
  12801. return "FreeCameraKeyboardMoveInput";
  12802. };
  12803. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  12804. this._keys = [];
  12805. };
  12806. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  12807. return "keyboard";
  12808. };
  12809. __decorate([
  12810. BABYLON.serialize()
  12811. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  12812. __decorate([
  12813. BABYLON.serialize()
  12814. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  12815. __decorate([
  12816. BABYLON.serialize()
  12817. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  12818. __decorate([
  12819. BABYLON.serialize()
  12820. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  12821. return FreeCameraKeyboardMoveInput;
  12822. }());
  12823. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  12824. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  12825. })(BABYLON || (BABYLON = {}));
  12826. var BABYLON;
  12827. (function (BABYLON) {
  12828. var FreeCameraTouchInput = (function () {
  12829. function FreeCameraTouchInput() {
  12830. this._offsetX = null;
  12831. this._offsetY = null;
  12832. this._pointerCount = 0;
  12833. this._pointerPressed = [];
  12834. this.touchAngularSensibility = 200000.0;
  12835. this.touchMoveSensibility = 250.0;
  12836. }
  12837. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  12838. var _this = this;
  12839. var previousPosition;
  12840. if (this._pointerInput === undefined) {
  12841. this._onLostFocus = function (evt) {
  12842. _this._offsetX = null;
  12843. _this._offsetY = null;
  12844. };
  12845. this._pointerInput = function (p, s) {
  12846. var evt = p.event;
  12847. if (evt.pointerType === "mouse") {
  12848. return;
  12849. }
  12850. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  12851. if (!noPreventDefault) {
  12852. evt.preventDefault();
  12853. }
  12854. _this._pointerPressed.push(evt.pointerId);
  12855. if (_this._pointerPressed.length !== 1) {
  12856. return;
  12857. }
  12858. previousPosition = {
  12859. x: evt.clientX,
  12860. y: evt.clientY
  12861. };
  12862. }
  12863. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  12864. if (!noPreventDefault) {
  12865. evt.preventDefault();
  12866. }
  12867. var index = _this._pointerPressed.indexOf(evt.pointerId);
  12868. if (index === -1) {
  12869. return;
  12870. }
  12871. _this._pointerPressed.splice(index, 1);
  12872. if (index != 0) {
  12873. return;
  12874. }
  12875. previousPosition = null;
  12876. _this._offsetX = null;
  12877. _this._offsetY = null;
  12878. }
  12879. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  12880. if (!noPreventDefault) {
  12881. evt.preventDefault();
  12882. }
  12883. if (!previousPosition) {
  12884. return;
  12885. }
  12886. var index = _this._pointerPressed.indexOf(evt.pointerId);
  12887. if (index != 0) {
  12888. return;
  12889. }
  12890. _this._offsetX = evt.clientX - previousPosition.x;
  12891. _this._offsetY = -(evt.clientY - previousPosition.y);
  12892. }
  12893. };
  12894. }
  12895. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  12896. element.addEventListener("blur", this._onLostFocus);
  12897. };
  12898. FreeCameraTouchInput.prototype.detachControl = function (element) {
  12899. if (this._pointerInput && element) {
  12900. this.camera.getScene().onPointerObservable.remove(this._observer);
  12901. this._observer = null;
  12902. element.removeEventListener("blur", this._onLostFocus);
  12903. this._onLostFocus = null;
  12904. this._pointerPressed = [];
  12905. this._offsetX = null;
  12906. this._offsetY = null;
  12907. this._pointerCount = 0;
  12908. }
  12909. };
  12910. FreeCameraTouchInput.prototype.checkInputs = function () {
  12911. if (this._offsetX) {
  12912. var camera = this.camera;
  12913. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  12914. if (this._pointerPressed.length > 1) {
  12915. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  12916. }
  12917. else {
  12918. var speed = camera._computeLocalCameraSpeed();
  12919. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  12920. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  12921. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  12922. }
  12923. }
  12924. };
  12925. FreeCameraTouchInput.prototype.getTypeName = function () {
  12926. return "FreeCameraTouchInput";
  12927. };
  12928. FreeCameraTouchInput.prototype.getSimpleName = function () {
  12929. return "touch";
  12930. };
  12931. __decorate([
  12932. BABYLON.serialize()
  12933. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  12934. __decorate([
  12935. BABYLON.serialize()
  12936. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  12937. return FreeCameraTouchInput;
  12938. }());
  12939. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  12940. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  12941. })(BABYLON || (BABYLON = {}));
  12942. var BABYLON;
  12943. (function (BABYLON) {
  12944. var FreeCameraDeviceOrientationInput = (function () {
  12945. function FreeCameraDeviceOrientationInput() {
  12946. var _this = this;
  12947. this._screenOrientationAngle = 0;
  12948. this._screenQuaternion = new BABYLON.Quaternion();
  12949. this._alpha = 0;
  12950. this._beta = 0;
  12951. this._gamma = 0;
  12952. this._orientationChanged = function () {
  12953. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  12954. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  12955. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  12956. };
  12957. this._deviceOrientation = function (evt) {
  12958. _this._alpha = evt.alpha;
  12959. _this._beta = evt.beta;
  12960. _this._gamma = evt.gamma;
  12961. };
  12962. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  12963. this._orientationChanged();
  12964. }
  12965. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  12966. get: function () {
  12967. return this._camera;
  12968. },
  12969. set: function (camera) {
  12970. this._camera = camera;
  12971. if (!this._camera.rotationQuaternion)
  12972. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  12973. },
  12974. enumerable: true,
  12975. configurable: true
  12976. });
  12977. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  12978. window.addEventListener("orientationchange", this._orientationChanged);
  12979. window.addEventListener("deviceorientation", this._deviceOrientation);
  12980. };
  12981. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  12982. window.removeEventListener("orientationchange", this._orientationChanged);
  12983. window.removeEventListener("deviceorientation", this._deviceOrientation);
  12984. };
  12985. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  12986. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  12987. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  12988. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  12989. //Mirror on XY Plane
  12990. this._camera.rotationQuaternion.z *= -1;
  12991. this._camera.rotationQuaternion.w *= -1;
  12992. };
  12993. FreeCameraDeviceOrientationInput.prototype.getTypeName = function () {
  12994. return "FreeCameraDeviceOrientationInput";
  12995. };
  12996. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  12997. return "deviceOrientation";
  12998. };
  12999. return FreeCameraDeviceOrientationInput;
  13000. }());
  13001. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  13002. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  13003. })(BABYLON || (BABYLON = {}));
  13004. var BABYLON;
  13005. (function (BABYLON) {
  13006. var FreeCameraGamepadInput = (function () {
  13007. function FreeCameraGamepadInput() {
  13008. this.gamepadAngularSensibility = 200;
  13009. this.gamepadMoveSensibility = 40;
  13010. }
  13011. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  13012. var _this = this;
  13013. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  13014. };
  13015. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  13016. if (this._gamepads) {
  13017. this._gamepads.dispose();
  13018. }
  13019. this.gamepad = null;
  13020. };
  13021. FreeCameraGamepadInput.prototype.checkInputs = function () {
  13022. if (this.gamepad) {
  13023. var camera = this.camera;
  13024. var LSValues = this.gamepad.leftStick;
  13025. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  13026. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  13027. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  13028. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  13029. var RSValues = this.gamepad.rightStick;
  13030. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  13031. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  13032. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  13033. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  13034. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  13035. var speed = camera._computeLocalCameraSpeed() * 50.0;
  13036. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x * speed, 0, -LSValues.y * speed), cameraTransform);
  13037. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  13038. camera.cameraRotation = camera.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  13039. }
  13040. };
  13041. FreeCameraGamepadInput.prototype._onNewGameConnected = function (gamepad) {
  13042. // Only the first gamepad can control the camera
  13043. if (gamepad.index === 0) {
  13044. this.gamepad = gamepad;
  13045. }
  13046. };
  13047. FreeCameraGamepadInput.prototype.getTypeName = function () {
  13048. return "FreeCameraGamepadInput";
  13049. };
  13050. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  13051. return "gamepad";
  13052. };
  13053. __decorate([
  13054. BABYLON.serialize()
  13055. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  13056. __decorate([
  13057. BABYLON.serialize()
  13058. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  13059. return FreeCameraGamepadInput;
  13060. }());
  13061. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  13062. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  13063. })(BABYLON || (BABYLON = {}));
  13064. var BABYLON;
  13065. (function (BABYLON) {
  13066. var ArcRotateCameraKeyboardMoveInput = (function () {
  13067. function ArcRotateCameraKeyboardMoveInput() {
  13068. this._keys = [];
  13069. this.keysUp = [38];
  13070. this.keysDown = [40];
  13071. this.keysLeft = [37];
  13072. this.keysRight = [39];
  13073. }
  13074. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  13075. var _this = this;
  13076. element.tabIndex = 1;
  13077. this._onKeyDown = function (evt) {
  13078. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  13079. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  13080. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  13081. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  13082. var index = _this._keys.indexOf(evt.keyCode);
  13083. if (index === -1) {
  13084. _this._keys.push(evt.keyCode);
  13085. }
  13086. if (evt.preventDefault) {
  13087. if (!noPreventDefault) {
  13088. evt.preventDefault();
  13089. }
  13090. }
  13091. }
  13092. };
  13093. this._onKeyUp = function (evt) {
  13094. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  13095. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  13096. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  13097. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  13098. var index = _this._keys.indexOf(evt.keyCode);
  13099. if (index >= 0) {
  13100. _this._keys.splice(index, 1);
  13101. }
  13102. if (evt.preventDefault) {
  13103. if (!noPreventDefault) {
  13104. evt.preventDefault();
  13105. }
  13106. }
  13107. }
  13108. };
  13109. this._onLostFocus = function () {
  13110. _this._keys = [];
  13111. };
  13112. element.addEventListener("keydown", this._onKeyDown, false);
  13113. element.addEventListener("keyup", this._onKeyUp, false);
  13114. BABYLON.Tools.RegisterTopRootEvents([
  13115. { name: "blur", handler: this._onLostFocus }
  13116. ]);
  13117. };
  13118. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  13119. if (element) {
  13120. element.removeEventListener("keydown", this._onKeyDown);
  13121. element.removeEventListener("keyup", this._onKeyUp);
  13122. }
  13123. BABYLON.Tools.UnregisterTopRootEvents([
  13124. { name: "blur", handler: this._onLostFocus }
  13125. ]);
  13126. this._keys = [];
  13127. this._onKeyDown = null;
  13128. this._onKeyUp = null;
  13129. this._onLostFocus = null;
  13130. };
  13131. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  13132. if (this._onKeyDown) {
  13133. var camera = this.camera;
  13134. for (var index = 0; index < this._keys.length; index++) {
  13135. var keyCode = this._keys[index];
  13136. if (this.keysLeft.indexOf(keyCode) !== -1) {
  13137. camera.inertialAlphaOffset -= 0.01;
  13138. }
  13139. else if (this.keysUp.indexOf(keyCode) !== -1) {
  13140. camera.inertialBetaOffset -= 0.01;
  13141. }
  13142. else if (this.keysRight.indexOf(keyCode) !== -1) {
  13143. camera.inertialAlphaOffset += 0.01;
  13144. }
  13145. else if (this.keysDown.indexOf(keyCode) !== -1) {
  13146. camera.inertialBetaOffset += 0.01;
  13147. }
  13148. }
  13149. }
  13150. };
  13151. ArcRotateCameraKeyboardMoveInput.prototype.getTypeName = function () {
  13152. return "ArcRotateCameraKeyboardMoveInput";
  13153. };
  13154. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  13155. return "keyboard";
  13156. };
  13157. __decorate([
  13158. BABYLON.serialize()
  13159. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  13160. __decorate([
  13161. BABYLON.serialize()
  13162. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  13163. __decorate([
  13164. BABYLON.serialize()
  13165. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  13166. __decorate([
  13167. BABYLON.serialize()
  13168. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  13169. return ArcRotateCameraKeyboardMoveInput;
  13170. }());
  13171. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  13172. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  13173. })(BABYLON || (BABYLON = {}));
  13174. var BABYLON;
  13175. (function (BABYLON) {
  13176. var ArcRotateCameraMouseWheelInput = (function () {
  13177. function ArcRotateCameraMouseWheelInput() {
  13178. this.wheelPrecision = 3.0;
  13179. }
  13180. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  13181. var _this = this;
  13182. this._wheel = function (p, s) {
  13183. //sanity check - this should be a PointerWheel event.
  13184. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  13185. return;
  13186. var event = p.event;
  13187. var delta = 0;
  13188. if (event.wheelDelta) {
  13189. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  13190. }
  13191. else if (event.detail) {
  13192. delta = -event.detail / _this.wheelPrecision;
  13193. }
  13194. if (delta)
  13195. _this.camera.inertialRadiusOffset += delta;
  13196. if (event.preventDefault) {
  13197. if (!noPreventDefault) {
  13198. event.preventDefault();
  13199. }
  13200. }
  13201. };
  13202. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  13203. };
  13204. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  13205. if (this._observer && element) {
  13206. this.camera.getScene().onPointerObservable.remove(this._observer);
  13207. this._observer = null;
  13208. this._wheel = null;
  13209. }
  13210. };
  13211. ArcRotateCameraMouseWheelInput.prototype.getTypeName = function () {
  13212. return "ArcRotateCameraMouseWheelInput";
  13213. };
  13214. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  13215. return "mousewheel";
  13216. };
  13217. __decorate([
  13218. BABYLON.serialize()
  13219. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  13220. return ArcRotateCameraMouseWheelInput;
  13221. }());
  13222. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  13223. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  13224. })(BABYLON || (BABYLON = {}));
  13225. var BABYLON;
  13226. (function (BABYLON) {
  13227. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  13228. var ArcRotateCameraPointersInput = (function () {
  13229. function ArcRotateCameraPointersInput() {
  13230. this.angularSensibilityX = 1000.0;
  13231. this.angularSensibilityY = 1000.0;
  13232. this.pinchPrecision = 6.0;
  13233. this.panningSensibility = 50.0;
  13234. this._isPanClick = false;
  13235. this.pinchInwards = true;
  13236. }
  13237. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  13238. var _this = this;
  13239. var engine = this.camera.getEngine();
  13240. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  13241. var pointA, pointB;
  13242. var previousPinchDistance = 0;
  13243. this._pointerInput = function (p, s) {
  13244. var evt = p.event;
  13245. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  13246. try {
  13247. evt.srcElement.setPointerCapture(evt.pointerId);
  13248. }
  13249. catch (e) {
  13250. }
  13251. // Manage panning with pan button click
  13252. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  13253. // manage pointers
  13254. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  13255. if (pointA === undefined) {
  13256. pointA = cacheSoloPointer;
  13257. }
  13258. else if (pointB === undefined) {
  13259. pointB = cacheSoloPointer;
  13260. }
  13261. if (!noPreventDefault) {
  13262. evt.preventDefault();
  13263. element.focus();
  13264. }
  13265. }
  13266. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  13267. try {
  13268. evt.srcElement.releasePointerCapture(evt.pointerId);
  13269. }
  13270. catch (e) {
  13271. }
  13272. cacheSoloPointer = null;
  13273. previousPinchDistance = 0;
  13274. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  13275. //but emptying completly pointers collection is required to fix a bug on iPhone :
  13276. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  13277. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  13278. pointA = pointB = undefined;
  13279. if (!noPreventDefault) {
  13280. evt.preventDefault();
  13281. }
  13282. }
  13283. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  13284. if (!noPreventDefault) {
  13285. evt.preventDefault();
  13286. }
  13287. // One button down
  13288. if (pointA && pointB === undefined) {
  13289. if (_this.panningSensibility !== 0 &&
  13290. ((evt.ctrlKey && _this.camera._useCtrlForPanning) ||
  13291. (!_this.camera._useCtrlForPanning && _this._isPanClick))) {
  13292. _this.camera
  13293. .inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  13294. _this.camera
  13295. .inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  13296. }
  13297. else {
  13298. var offsetX = evt.clientX - cacheSoloPointer.x;
  13299. var offsetY = evt.clientY - cacheSoloPointer.y;
  13300. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  13301. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  13302. }
  13303. cacheSoloPointer.x = evt.clientX;
  13304. cacheSoloPointer.y = evt.clientY;
  13305. }
  13306. else if (pointA && pointB) {
  13307. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  13308. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  13309. ed.x = evt.clientX;
  13310. ed.y = evt.clientY;
  13311. var direction = _this.pinchInwards ? 1 : -1;
  13312. var distX = pointA.x - pointB.x;
  13313. var distY = pointA.y - pointB.y;
  13314. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  13315. if (previousPinchDistance === 0) {
  13316. previousPinchDistance = pinchSquaredDistance;
  13317. return;
  13318. }
  13319. if (pinchSquaredDistance !== previousPinchDistance) {
  13320. _this.camera
  13321. .inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) /
  13322. (_this.pinchPrecision *
  13323. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  13324. direction);
  13325. previousPinchDistance = pinchSquaredDistance;
  13326. }
  13327. }
  13328. }
  13329. };
  13330. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  13331. this._onContextMenu = function (evt) {
  13332. evt.preventDefault();
  13333. };
  13334. if (!this.camera._useCtrlForPanning) {
  13335. element.addEventListener("contextmenu", this._onContextMenu, false);
  13336. }
  13337. this._onLostFocus = function () {
  13338. //this._keys = [];
  13339. pointA = pointB = undefined;
  13340. previousPinchDistance = 0;
  13341. cacheSoloPointer = null;
  13342. };
  13343. this._onMouseMove = function (evt) {
  13344. if (!engine.isPointerLock) {
  13345. return;
  13346. }
  13347. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  13348. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  13349. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  13350. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  13351. if (!noPreventDefault) {
  13352. evt.preventDefault();
  13353. }
  13354. };
  13355. this._onGestureStart = function (e) {
  13356. if (window.MSGesture === undefined) {
  13357. return;
  13358. }
  13359. if (!_this._MSGestureHandler) {
  13360. _this._MSGestureHandler = new MSGesture();
  13361. _this._MSGestureHandler.target = element;
  13362. }
  13363. _this._MSGestureHandler.addPointer(e.pointerId);
  13364. };
  13365. this._onGesture = function (e) {
  13366. _this.camera.radius *= e.scale;
  13367. if (e.preventDefault) {
  13368. if (!noPreventDefault) {
  13369. e.stopPropagation();
  13370. e.preventDefault();
  13371. }
  13372. }
  13373. };
  13374. element.addEventListener("mousemove", this._onMouseMove, false);
  13375. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  13376. element.addEventListener("MSGestureChange", this._onGesture, false);
  13377. element.addEventListener("keydown", this._onKeyDown, false);
  13378. element.addEventListener("keyup", this._onKeyUp, false);
  13379. BABYLON.Tools.RegisterTopRootEvents([
  13380. { name: "blur", handler: this._onLostFocus }
  13381. ]);
  13382. };
  13383. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  13384. if (element && this._observer) {
  13385. this.camera.getScene().onPointerObservable.remove(this._observer);
  13386. this._observer = null;
  13387. element.removeEventListener("contextmenu", this._onContextMenu);
  13388. element.removeEventListener("mousemove", this._onMouseMove);
  13389. element.removeEventListener("MSPointerDown", this._onGestureStart);
  13390. element.removeEventListener("MSGestureChange", this._onGesture);
  13391. element.removeEventListener("keydown", this._onKeyDown);
  13392. element.removeEventListener("keyup", this._onKeyUp);
  13393. this._isPanClick = false;
  13394. this.pinchInwards = true;
  13395. this._onKeyDown = null;
  13396. this._onKeyUp = null;
  13397. this._onMouseMove = null;
  13398. this._onGestureStart = null;
  13399. this._onGesture = null;
  13400. this._MSGestureHandler = null;
  13401. this._onLostFocus = null;
  13402. this._onContextMenu = null;
  13403. }
  13404. BABYLON.Tools.UnregisterTopRootEvents([
  13405. { name: "blur", handler: this._onLostFocus }
  13406. ]);
  13407. };
  13408. ArcRotateCameraPointersInput.prototype.getTypeName = function () {
  13409. return "ArcRotateCameraPointersInput";
  13410. };
  13411. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  13412. return "pointers";
  13413. };
  13414. __decorate([
  13415. BABYLON.serialize()
  13416. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  13417. __decorate([
  13418. BABYLON.serialize()
  13419. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  13420. __decorate([
  13421. BABYLON.serialize()
  13422. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  13423. __decorate([
  13424. BABYLON.serialize()
  13425. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  13426. return ArcRotateCameraPointersInput;
  13427. }());
  13428. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  13429. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  13430. })(BABYLON || (BABYLON = {}));
  13431. var BABYLON;
  13432. (function (BABYLON) {
  13433. var ArcRotateCameraGamepadInput = (function () {
  13434. function ArcRotateCameraGamepadInput() {
  13435. this.gamepadRotationSensibility = 80;
  13436. this.gamepadMoveSensibility = 40;
  13437. }
  13438. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  13439. var _this = this;
  13440. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  13441. };
  13442. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  13443. if (this._gamepads) {
  13444. this._gamepads.dispose();
  13445. }
  13446. this.gamepad = null;
  13447. };
  13448. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  13449. if (this.gamepad) {
  13450. var camera = this.camera;
  13451. var RSValues = this.gamepad.rightStick;
  13452. if (RSValues.x != 0) {
  13453. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  13454. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  13455. camera.inertialAlphaOffset += normalizedRX;
  13456. }
  13457. }
  13458. if (RSValues.y != 0) {
  13459. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  13460. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  13461. camera.inertialBetaOffset += normalizedRY;
  13462. }
  13463. }
  13464. var LSValues = this.gamepad.leftStick;
  13465. if (LSValues.y != 0) {
  13466. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  13467. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  13468. this.camera.inertialRadiusOffset -= normalizedLY;
  13469. }
  13470. }
  13471. }
  13472. };
  13473. ArcRotateCameraGamepadInput.prototype._onNewGameConnected = function (gamepad) {
  13474. // Only the first gamepad can control the camera
  13475. if (gamepad.index === 0) {
  13476. this.gamepad = gamepad;
  13477. }
  13478. };
  13479. ArcRotateCameraGamepadInput.prototype.getTypeName = function () {
  13480. return "ArcRotateCameraGamepadInput";
  13481. };
  13482. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  13483. return "gamepad";
  13484. };
  13485. __decorate([
  13486. BABYLON.serialize()
  13487. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  13488. __decorate([
  13489. BABYLON.serialize()
  13490. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  13491. return ArcRotateCameraGamepadInput;
  13492. }());
  13493. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  13494. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  13495. })(BABYLON || (BABYLON = {}));
  13496. var BABYLON;
  13497. (function (BABYLON) {
  13498. var ArcRotateCameraVRDeviceOrientationInput = (function () {
  13499. function ArcRotateCameraVRDeviceOrientationInput() {
  13500. this.alphaCorrection = 1;
  13501. this.betaCorrection = 1;
  13502. this.gammaCorrection = 1;
  13503. this._alpha = 0;
  13504. this._beta = 0;
  13505. this._gamma = 0;
  13506. this._dirty = false;
  13507. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  13508. }
  13509. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  13510. this.camera.attachControl(element, noPreventDefault);
  13511. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  13512. };
  13513. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  13514. var camera = this.camera;
  13515. this._alpha = +evt.alpha | 0;
  13516. this._beta = +evt.beta | 0;
  13517. this._gamma = +evt.gamma | 0;
  13518. this._dirty = true;
  13519. };
  13520. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  13521. if (this._dirty) {
  13522. this._dirty = false;
  13523. if (this._gamma < 0) {
  13524. this._gamma = 180 + this._gamma;
  13525. }
  13526. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  13527. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  13528. }
  13529. };
  13530. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  13531. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  13532. };
  13533. ArcRotateCameraVRDeviceOrientationInput.prototype.getTypeName = function () {
  13534. return "ArcRotateCameraVRDeviceOrientationInput";
  13535. };
  13536. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  13537. return "VRDeviceOrientation";
  13538. };
  13539. return ArcRotateCameraVRDeviceOrientationInput;
  13540. }());
  13541. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  13542. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  13543. })(BABYLON || (BABYLON = {}));
  13544. var BABYLON;
  13545. (function (BABYLON) {
  13546. var TargetCamera = (function (_super) {
  13547. __extends(TargetCamera, _super);
  13548. function TargetCamera(name, position, scene) {
  13549. _super.call(this, name, position, scene);
  13550. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  13551. this.cameraRotation = new BABYLON.Vector2(0, 0);
  13552. this.rotation = new BABYLON.Vector3(0, 0, 0);
  13553. this.speed = 2.0;
  13554. this.noRotationConstraint = false;
  13555. this.lockedTarget = null;
  13556. this._currentTarget = BABYLON.Vector3.Zero();
  13557. this._viewMatrix = BABYLON.Matrix.Zero();
  13558. this._camMatrix = BABYLON.Matrix.Zero();
  13559. this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  13560. this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  13561. this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  13562. this._defaultUpVector = new BABYLON.Vector3(0, 1, 0);
  13563. this._transformedReferencePoint = BABYLON.Vector3.Zero();
  13564. this._lookAtTemp = BABYLON.Matrix.Zero();
  13565. this._tempMatrix = BABYLON.Matrix.Zero();
  13566. }
  13567. TargetCamera.prototype.getFrontPosition = function (distance) {
  13568. var direction = this.getTarget().subtract(this.position);
  13569. direction.normalize();
  13570. direction.scaleInPlace(distance);
  13571. return this.globalPosition.add(direction);
  13572. };
  13573. TargetCamera.prototype._getLockedTargetPosition = function () {
  13574. if (!this.lockedTarget) {
  13575. return null;
  13576. }
  13577. return this.lockedTarget.position || this.lockedTarget;
  13578. };
  13579. // Cache
  13580. TargetCamera.prototype._initCache = function () {
  13581. _super.prototype._initCache.call(this);
  13582. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  13583. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  13584. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  13585. };
  13586. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  13587. if (!ignoreParentClass) {
  13588. _super.prototype._updateCache.call(this);
  13589. }
  13590. var lockedTargetPosition = this._getLockedTargetPosition();
  13591. if (!lockedTargetPosition) {
  13592. this._cache.lockedTarget = null;
  13593. }
  13594. else {
  13595. if (!this._cache.lockedTarget) {
  13596. this._cache.lockedTarget = lockedTargetPosition.clone();
  13597. }
  13598. else {
  13599. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  13600. }
  13601. }
  13602. this._cache.rotation.copyFrom(this.rotation);
  13603. if (this.rotationQuaternion)
  13604. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  13605. };
  13606. // Synchronized
  13607. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  13608. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  13609. return false;
  13610. }
  13611. var lockedTargetPosition = this._getLockedTargetPosition();
  13612. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  13613. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  13614. };
  13615. // Methods
  13616. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  13617. var engine = this.getEngine();
  13618. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  13619. };
  13620. // Target
  13621. TargetCamera.prototype.setTarget = function (target) {
  13622. this.upVector.normalize();
  13623. BABYLON.Matrix.LookAtLHToRef(this.position, target, this._defaultUpVector, this._camMatrix);
  13624. this._camMatrix.invert();
  13625. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  13626. var vDir = target.subtract(this.position);
  13627. if (vDir.x >= 0.0) {
  13628. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  13629. }
  13630. else {
  13631. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  13632. }
  13633. this.rotation.z = 0;
  13634. if (isNaN(this.rotation.x)) {
  13635. this.rotation.x = 0;
  13636. }
  13637. if (isNaN(this.rotation.y)) {
  13638. this.rotation.y = 0;
  13639. }
  13640. if (isNaN(this.rotation.z)) {
  13641. this.rotation.z = 0;
  13642. }
  13643. if (this.rotationQuaternion) {
  13644. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  13645. }
  13646. };
  13647. TargetCamera.prototype.getTarget = function () {
  13648. return this._currentTarget;
  13649. };
  13650. TargetCamera.prototype._decideIfNeedsToMove = function () {
  13651. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  13652. };
  13653. TargetCamera.prototype._updatePosition = function () {
  13654. this.position.addInPlace(this.cameraDirection);
  13655. };
  13656. TargetCamera.prototype._checkInputs = function () {
  13657. var needToMove = this._decideIfNeedsToMove();
  13658. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  13659. // Move
  13660. if (needToMove) {
  13661. this._updatePosition();
  13662. }
  13663. // Rotate
  13664. if (needToRotate) {
  13665. this.rotation.x += this.cameraRotation.x;
  13666. this.rotation.y += this.cameraRotation.y;
  13667. if (!this.noRotationConstraint) {
  13668. var limit = (Math.PI / 2) * 0.95;
  13669. if (this.rotation.x > limit)
  13670. this.rotation.x = limit;
  13671. if (this.rotation.x < -limit)
  13672. this.rotation.x = -limit;
  13673. }
  13674. }
  13675. // Inertia
  13676. if (needToMove) {
  13677. if (Math.abs(this.cameraDirection.x) < BABYLON.Epsilon) {
  13678. this.cameraDirection.x = 0;
  13679. }
  13680. if (Math.abs(this.cameraDirection.y) < BABYLON.Epsilon) {
  13681. this.cameraDirection.y = 0;
  13682. }
  13683. if (Math.abs(this.cameraDirection.z) < BABYLON.Epsilon) {
  13684. this.cameraDirection.z = 0;
  13685. }
  13686. this.cameraDirection.scaleInPlace(this.inertia);
  13687. }
  13688. if (needToRotate) {
  13689. if (Math.abs(this.cameraRotation.x) < BABYLON.Epsilon) {
  13690. this.cameraRotation.x = 0;
  13691. }
  13692. if (Math.abs(this.cameraRotation.y) < BABYLON.Epsilon) {
  13693. this.cameraRotation.y = 0;
  13694. }
  13695. this.cameraRotation.scaleInPlace(this.inertia);
  13696. }
  13697. _super.prototype._checkInputs.call(this);
  13698. };
  13699. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  13700. if (this.rotationQuaternion) {
  13701. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  13702. //update the up vector!
  13703. BABYLON.Vector3.TransformNormalToRef(this._defaultUpVector, this._cameraRotationMatrix, this.upVector);
  13704. }
  13705. else {
  13706. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  13707. }
  13708. };
  13709. TargetCamera.prototype._getViewMatrix = function () {
  13710. if (!this.lockedTarget) {
  13711. // Compute
  13712. this._updateCameraRotationMatrix();
  13713. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  13714. // Computing target and final matrix
  13715. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  13716. }
  13717. else {
  13718. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  13719. }
  13720. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  13721. return this._viewMatrix;
  13722. };
  13723. /**
  13724. * @override
  13725. * Override Camera.createRigCamera
  13726. */
  13727. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  13728. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  13729. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  13730. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR) {
  13731. if (!this.rotationQuaternion) {
  13732. this.rotationQuaternion = new BABYLON.Quaternion();
  13733. }
  13734. rigCamera._cameraRigParams = {};
  13735. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  13736. }
  13737. return rigCamera;
  13738. }
  13739. return null;
  13740. };
  13741. /**
  13742. * @override
  13743. * Override Camera._updateRigCameras
  13744. */
  13745. TargetCamera.prototype._updateRigCameras = function () {
  13746. var camLeft = this._rigCameras[0];
  13747. var camRight = this._rigCameras[1];
  13748. switch (this.cameraRigMode) {
  13749. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  13750. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  13751. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  13752. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  13753. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  13754. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  13755. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  13756. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  13757. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  13758. camLeft.setTarget(this.getTarget());
  13759. camRight.setTarget(this.getTarget());
  13760. break;
  13761. case BABYLON.Camera.RIG_MODE_VR:
  13762. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  13763. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  13764. camLeft.position.copyFrom(this.position);
  13765. camRight.position.copyFrom(this.position);
  13766. break;
  13767. }
  13768. _super.prototype._updateRigCameras.call(this);
  13769. };
  13770. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  13771. if (!this._rigCamTransformMatrix) {
  13772. this._rigCamTransformMatrix = new BABYLON.Matrix();
  13773. }
  13774. var target = this.getTarget();
  13775. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  13776. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  13777. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  13778. };
  13779. TargetCamera.prototype.getTypeName = function () {
  13780. return "TargetCamera";
  13781. };
  13782. __decorate([
  13783. BABYLON.serializeAsVector3()
  13784. ], TargetCamera.prototype, "rotation", void 0);
  13785. __decorate([
  13786. BABYLON.serialize()
  13787. ], TargetCamera.prototype, "speed", void 0);
  13788. __decorate([
  13789. BABYLON.serializeAsMeshReference("lockedTargetId")
  13790. ], TargetCamera.prototype, "lockedTarget", void 0);
  13791. return TargetCamera;
  13792. }(BABYLON.Camera));
  13793. BABYLON.TargetCamera = TargetCamera;
  13794. })(BABYLON || (BABYLON = {}));
  13795. var BABYLON;
  13796. (function (BABYLON) {
  13797. var FreeCamera = (function (_super) {
  13798. __extends(FreeCamera, _super);
  13799. function FreeCamera(name, position, scene) {
  13800. var _this = this;
  13801. _super.call(this, name, position, scene);
  13802. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  13803. this.checkCollisions = false;
  13804. this.applyGravity = false;
  13805. this._collider = new BABYLON.Collider();
  13806. this._needMoveForGravity = false;
  13807. this._oldPosition = BABYLON.Vector3.Zero();
  13808. this._diffPosition = BABYLON.Vector3.Zero();
  13809. this._newPosition = BABYLON.Vector3.Zero();
  13810. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  13811. if (collidedMesh === void 0) { collidedMesh = null; }
  13812. //TODO move this to the collision coordinator!
  13813. if (_this.getScene().workerCollisions)
  13814. newPosition.multiplyInPlace(_this._collider.radius);
  13815. var updatePosition = function (newPos) {
  13816. _this._newPosition.copyFrom(newPos);
  13817. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  13818. var oldPosition = _this.position.clone();
  13819. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  13820. _this.position.addInPlace(_this._diffPosition);
  13821. if (_this.onCollide && collidedMesh) {
  13822. _this.onCollide(collidedMesh);
  13823. }
  13824. }
  13825. };
  13826. updatePosition(newPosition);
  13827. };
  13828. this.inputs = new BABYLON.FreeCameraInputsManager(this);
  13829. this.inputs.addKeyboard().addMouse();
  13830. }
  13831. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  13832. //-- begin properties for backward compatibility for inputs
  13833. get: function () {
  13834. var mouse = this.inputs.attached["mouse"];
  13835. if (mouse)
  13836. return mouse.angularSensibility;
  13837. },
  13838. set: function (value) {
  13839. var mouse = this.inputs.attached["mouse"];
  13840. if (mouse)
  13841. mouse.angularSensibility = value;
  13842. },
  13843. enumerable: true,
  13844. configurable: true
  13845. });
  13846. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  13847. get: function () {
  13848. var keyboard = this.inputs.attached["keyboard"];
  13849. if (keyboard)
  13850. return keyboard.keysUp;
  13851. },
  13852. set: function (value) {
  13853. var keyboard = this.inputs.attached["keyboard"];
  13854. if (keyboard)
  13855. keyboard.keysUp = value;
  13856. },
  13857. enumerable: true,
  13858. configurable: true
  13859. });
  13860. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  13861. get: function () {
  13862. var keyboard = this.inputs.attached["keyboard"];
  13863. if (keyboard)
  13864. return keyboard.keysDown;
  13865. },
  13866. set: function (value) {
  13867. var keyboard = this.inputs.attached["keyboard"];
  13868. if (keyboard)
  13869. keyboard.keysDown = value;
  13870. },
  13871. enumerable: true,
  13872. configurable: true
  13873. });
  13874. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  13875. get: function () {
  13876. var keyboard = this.inputs.attached["keyboard"];
  13877. if (keyboard)
  13878. return keyboard.keysLeft;
  13879. },
  13880. set: function (value) {
  13881. var keyboard = this.inputs.attached["keyboard"];
  13882. if (keyboard)
  13883. keyboard.keysLeft = value;
  13884. },
  13885. enumerable: true,
  13886. configurable: true
  13887. });
  13888. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  13889. get: function () {
  13890. var keyboard = this.inputs.attached["keyboard"];
  13891. if (keyboard)
  13892. return keyboard.keysRight;
  13893. },
  13894. set: function (value) {
  13895. var keyboard = this.inputs.attached["keyboard"];
  13896. if (keyboard)
  13897. keyboard.keysRight = value;
  13898. },
  13899. enumerable: true,
  13900. configurable: true
  13901. });
  13902. // Controls
  13903. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  13904. this.inputs.attachElement(element, noPreventDefault);
  13905. };
  13906. FreeCamera.prototype.detachControl = function (element) {
  13907. this.inputs.detachElement(element);
  13908. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  13909. this.cameraRotation = new BABYLON.Vector2(0, 0);
  13910. };
  13911. FreeCamera.prototype._collideWithWorld = function (velocity) {
  13912. var globalPosition;
  13913. if (this.parent) {
  13914. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  13915. }
  13916. else {
  13917. globalPosition = this.position;
  13918. }
  13919. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  13920. this._collider.radius = this.ellipsoid;
  13921. //no need for clone, as long as gravity is not on.
  13922. var actualVelocity = velocity;
  13923. //add gravity to the velocity to prevent the dual-collision checking
  13924. if (this.applyGravity) {
  13925. //this prevents mending with cameraDirection, a global variable of the free camera class.
  13926. actualVelocity = velocity.add(this.getScene().gravity);
  13927. }
  13928. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  13929. };
  13930. FreeCamera.prototype._checkInputs = function () {
  13931. if (!this._localDirection) {
  13932. this._localDirection = BABYLON.Vector3.Zero();
  13933. this._transformedDirection = BABYLON.Vector3.Zero();
  13934. }
  13935. this.inputs.checkInputs();
  13936. _super.prototype._checkInputs.call(this);
  13937. };
  13938. FreeCamera.prototype._decideIfNeedsToMove = function () {
  13939. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  13940. };
  13941. FreeCamera.prototype._updatePosition = function () {
  13942. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  13943. this._collideWithWorld(this.cameraDirection);
  13944. }
  13945. else {
  13946. this.position.addInPlace(this.cameraDirection);
  13947. }
  13948. };
  13949. FreeCamera.prototype.dispose = function () {
  13950. this.inputs.clear();
  13951. _super.prototype.dispose.call(this);
  13952. };
  13953. FreeCamera.prototype.getTypeName = function () {
  13954. return "FreeCamera";
  13955. };
  13956. __decorate([
  13957. BABYLON.serializeAsVector3()
  13958. ], FreeCamera.prototype, "ellipsoid", void 0);
  13959. __decorate([
  13960. BABYLON.serialize()
  13961. ], FreeCamera.prototype, "checkCollisions", void 0);
  13962. __decorate([
  13963. BABYLON.serialize()
  13964. ], FreeCamera.prototype, "applyGravity", void 0);
  13965. return FreeCamera;
  13966. }(BABYLON.TargetCamera));
  13967. BABYLON.FreeCamera = FreeCamera;
  13968. })(BABYLON || (BABYLON = {}));
  13969. var BABYLON;
  13970. (function (BABYLON) {
  13971. var FreeCameraInputsManager = (function (_super) {
  13972. __extends(FreeCameraInputsManager, _super);
  13973. function FreeCameraInputsManager(camera) {
  13974. _super.call(this, camera);
  13975. }
  13976. FreeCameraInputsManager.prototype.addKeyboard = function () {
  13977. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  13978. return this;
  13979. };
  13980. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  13981. if (touchEnabled === void 0) { touchEnabled = true; }
  13982. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  13983. return this;
  13984. };
  13985. FreeCameraInputsManager.prototype.addGamepad = function () {
  13986. this.add(new BABYLON.FreeCameraGamepadInput());
  13987. return this;
  13988. };
  13989. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  13990. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  13991. return this;
  13992. };
  13993. FreeCameraInputsManager.prototype.addTouch = function () {
  13994. this.add(new BABYLON.FreeCameraTouchInput());
  13995. return this;
  13996. };
  13997. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  13998. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  13999. return this;
  14000. };
  14001. return FreeCameraInputsManager;
  14002. }(BABYLON.CameraInputsManager));
  14003. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  14004. })(BABYLON || (BABYLON = {}));
  14005. var BABYLON;
  14006. (function (BABYLON) {
  14007. var FollowCamera = (function (_super) {
  14008. __extends(FollowCamera, _super);
  14009. function FollowCamera(name, position, scene, target) {
  14010. _super.call(this, name, position, scene);
  14011. this.radius = 12;
  14012. this.rotationOffset = 0;
  14013. this.heightOffset = 4;
  14014. this.cameraAcceleration = 0.05;
  14015. this.maxCameraSpeed = 20;
  14016. this.target = target;
  14017. }
  14018. FollowCamera.prototype.getRadians = function (degrees) {
  14019. return degrees * Math.PI / 180;
  14020. };
  14021. FollowCamera.prototype.follow = function (cameraTarget) {
  14022. if (!cameraTarget)
  14023. return;
  14024. var yRotation;
  14025. if (cameraTarget.rotationQuaternion) {
  14026. var rotMatrix = new BABYLON.Matrix();
  14027. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  14028. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  14029. }
  14030. else {
  14031. yRotation = cameraTarget.rotation.y;
  14032. }
  14033. var radians = this.getRadians(this.rotationOffset) + yRotation;
  14034. var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
  14035. var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
  14036. var dx = targetX - this.position.x;
  14037. var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
  14038. var dz = (targetZ) - this.position.z;
  14039. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  14040. var vy = dy * this.cameraAcceleration;
  14041. var vz = dz * this.cameraAcceleration * 2;
  14042. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  14043. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  14044. }
  14045. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  14046. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  14047. }
  14048. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  14049. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  14050. }
  14051. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  14052. this.setTarget(cameraTarget.position);
  14053. };
  14054. FollowCamera.prototype._checkInputs = function () {
  14055. _super.prototype._checkInputs.call(this);
  14056. this.follow(this.target);
  14057. };
  14058. FollowCamera.prototype.getTypeName = function () {
  14059. return "FollowCamera";
  14060. };
  14061. __decorate([
  14062. BABYLON.serialize()
  14063. ], FollowCamera.prototype, "radius", void 0);
  14064. __decorate([
  14065. BABYLON.serialize()
  14066. ], FollowCamera.prototype, "rotationOffset", void 0);
  14067. __decorate([
  14068. BABYLON.serialize()
  14069. ], FollowCamera.prototype, "heightOffset", void 0);
  14070. __decorate([
  14071. BABYLON.serialize()
  14072. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  14073. __decorate([
  14074. BABYLON.serialize()
  14075. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  14076. __decorate([
  14077. BABYLON.serializeAsMeshReference("lockedTargetId")
  14078. ], FollowCamera.prototype, "target", void 0);
  14079. return FollowCamera;
  14080. }(BABYLON.TargetCamera));
  14081. BABYLON.FollowCamera = FollowCamera;
  14082. var ArcFollowCamera = (function (_super) {
  14083. __extends(ArcFollowCamera, _super);
  14084. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  14085. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  14086. this.alpha = alpha;
  14087. this.beta = beta;
  14088. this.radius = radius;
  14089. this.target = target;
  14090. this._cartesianCoordinates = BABYLON.Vector3.Zero();
  14091. this.follow();
  14092. }
  14093. ArcFollowCamera.prototype.follow = function () {
  14094. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  14095. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  14096. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  14097. this.position = this.target.position.add(this._cartesianCoordinates);
  14098. this.setTarget(this.target.position);
  14099. };
  14100. ArcFollowCamera.prototype._checkInputs = function () {
  14101. _super.prototype._checkInputs.call(this);
  14102. this.follow();
  14103. };
  14104. ArcFollowCamera.prototype.getTypeName = function () {
  14105. return "ArcFollowCamera";
  14106. };
  14107. return ArcFollowCamera;
  14108. }(BABYLON.TargetCamera));
  14109. BABYLON.ArcFollowCamera = ArcFollowCamera;
  14110. })(BABYLON || (BABYLON = {}));
  14111. var BABYLON;
  14112. (function (BABYLON) {
  14113. // We're mainly based on the logic defined into the FreeCamera code
  14114. var TouchCamera = (function (_super) {
  14115. __extends(TouchCamera, _super);
  14116. //-- end properties for backward compatibility for inputs
  14117. function TouchCamera(name, position, scene) {
  14118. _super.call(this, name, position, scene);
  14119. this.inputs.addTouch();
  14120. this._setupInputs();
  14121. }
  14122. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  14123. //-- Begin properties for backward compatibility for inputs
  14124. get: function () {
  14125. var touch = this.inputs.attached["touch"];
  14126. if (touch)
  14127. return touch.touchAngularSensibility;
  14128. },
  14129. set: function (value) {
  14130. var touch = this.inputs.attached["touch"];
  14131. if (touch)
  14132. touch.touchAngularSensibility = value;
  14133. },
  14134. enumerable: true,
  14135. configurable: true
  14136. });
  14137. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  14138. get: function () {
  14139. var touch = this.inputs.attached["touch"];
  14140. if (touch)
  14141. return touch.touchMoveSensibility;
  14142. },
  14143. set: function (value) {
  14144. var touch = this.inputs.attached["touch"];
  14145. if (touch)
  14146. touch.touchMoveSensibility = value;
  14147. },
  14148. enumerable: true,
  14149. configurable: true
  14150. });
  14151. TouchCamera.prototype.getTypeName = function () {
  14152. return "TouchCamera";
  14153. };
  14154. TouchCamera.prototype._setupInputs = function () {
  14155. var mouse = this.inputs.attached["mouse"];
  14156. if (mouse) {
  14157. mouse.touchEnabled = false;
  14158. }
  14159. };
  14160. return TouchCamera;
  14161. }(BABYLON.FreeCamera));
  14162. BABYLON.TouchCamera = TouchCamera;
  14163. })(BABYLON || (BABYLON = {}));
  14164. var BABYLON;
  14165. (function (BABYLON) {
  14166. var ArcRotateCamera = (function (_super) {
  14167. __extends(ArcRotateCamera, _super);
  14168. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  14169. var _this = this;
  14170. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  14171. this.inertialAlphaOffset = 0;
  14172. this.inertialBetaOffset = 0;
  14173. this.inertialRadiusOffset = 0;
  14174. this.lowerAlphaLimit = null;
  14175. this.upperAlphaLimit = null;
  14176. this.lowerBetaLimit = 0.01;
  14177. this.upperBetaLimit = Math.PI;
  14178. this.lowerRadiusLimit = null;
  14179. this.upperRadiusLimit = null;
  14180. this.inertialPanningX = 0;
  14181. this.inertialPanningY = 0;
  14182. //-- end properties for backward compatibility for inputs
  14183. this.zoomOnFactor = 1;
  14184. this.targetScreenOffset = BABYLON.Vector2.Zero();
  14185. this.allowUpsideDown = true;
  14186. this._viewMatrix = new BABYLON.Matrix();
  14187. // Panning
  14188. this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  14189. this.checkCollisions = false;
  14190. this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  14191. this._collider = new BABYLON.Collider();
  14192. this._previousPosition = BABYLON.Vector3.Zero();
  14193. this._collisionVelocity = BABYLON.Vector3.Zero();
  14194. this._newPosition = BABYLON.Vector3.Zero();
  14195. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  14196. if (collidedMesh === void 0) { collidedMesh = null; }
  14197. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  14198. newPosition.multiplyInPlace(_this._collider.radius);
  14199. }
  14200. if (!collidedMesh) {
  14201. _this._previousPosition.copyFrom(_this.position);
  14202. }
  14203. else {
  14204. _this.setPosition(newPosition);
  14205. if (_this.onCollide) {
  14206. _this.onCollide(collidedMesh);
  14207. }
  14208. }
  14209. // Recompute because of constraints
  14210. var cosa = Math.cos(_this.alpha);
  14211. var sina = Math.sin(_this.alpha);
  14212. var cosb = Math.cos(_this.beta);
  14213. var sinb = Math.sin(_this.beta);
  14214. if (sinb === 0) {
  14215. sinb = 0.0001;
  14216. }
  14217. var target = _this._getTargetPosition();
  14218. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  14219. _this.position.copyFrom(_this._newPosition);
  14220. var up = _this.upVector;
  14221. if (_this.allowUpsideDown && _this.beta < 0) {
  14222. up = up.clone();
  14223. up = up.negate();
  14224. }
  14225. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  14226. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  14227. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  14228. _this._collisionTriggered = false;
  14229. };
  14230. if (!target) {
  14231. this.target = BABYLON.Vector3.Zero();
  14232. }
  14233. else {
  14234. this.target = target;
  14235. }
  14236. this.alpha = alpha;
  14237. this.beta = beta;
  14238. this.radius = radius;
  14239. this.getViewMatrix();
  14240. this.inputs = new BABYLON.ArcRotateCameraInputsManager(this);
  14241. this.inputs.addKeyboard().addMouseWheel().addPointers().addGamepad();
  14242. }
  14243. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  14244. //-- begin properties for backward compatibility for inputs
  14245. get: function () {
  14246. var pointers = this.inputs.attached["pointers"];
  14247. if (pointers)
  14248. return pointers.angularSensibilityX;
  14249. },
  14250. set: function (value) {
  14251. var pointers = this.inputs.attached["pointers"];
  14252. if (pointers) {
  14253. pointers.angularSensibilityX = value;
  14254. }
  14255. },
  14256. enumerable: true,
  14257. configurable: true
  14258. });
  14259. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  14260. get: function () {
  14261. var pointers = this.inputs.attached["pointers"];
  14262. if (pointers)
  14263. return pointers.angularSensibilityY;
  14264. },
  14265. set: function (value) {
  14266. var pointers = this.inputs.attached["pointers"];
  14267. if (pointers) {
  14268. pointers.angularSensibilityY = value;
  14269. }
  14270. },
  14271. enumerable: true,
  14272. configurable: true
  14273. });
  14274. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  14275. get: function () {
  14276. var pointers = this.inputs.attached["pointers"];
  14277. if (pointers)
  14278. return pointers.pinchPrecision;
  14279. },
  14280. set: function (value) {
  14281. var pointers = this.inputs.attached["pointers"];
  14282. if (pointers) {
  14283. pointers.pinchPrecision = value;
  14284. }
  14285. },
  14286. enumerable: true,
  14287. configurable: true
  14288. });
  14289. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  14290. get: function () {
  14291. var pointers = this.inputs.attached["pointers"];
  14292. if (pointers)
  14293. return pointers.panningSensibility;
  14294. },
  14295. set: function (value) {
  14296. var pointers = this.inputs.attached["pointers"];
  14297. if (pointers) {
  14298. pointers.panningSensibility = value;
  14299. }
  14300. },
  14301. enumerable: true,
  14302. configurable: true
  14303. });
  14304. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  14305. get: function () {
  14306. var keyboard = this.inputs.attached["keyboard"];
  14307. if (keyboard)
  14308. return keyboard.keysUp;
  14309. },
  14310. set: function (value) {
  14311. var keyboard = this.inputs.attached["keyboard"];
  14312. if (keyboard)
  14313. keyboard.keysUp = value;
  14314. },
  14315. enumerable: true,
  14316. configurable: true
  14317. });
  14318. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  14319. get: function () {
  14320. var keyboard = this.inputs.attached["keyboard"];
  14321. if (keyboard)
  14322. return keyboard.keysDown;
  14323. },
  14324. set: function (value) {
  14325. var keyboard = this.inputs.attached["keyboard"];
  14326. if (keyboard)
  14327. keyboard.keysDown = value;
  14328. },
  14329. enumerable: true,
  14330. configurable: true
  14331. });
  14332. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  14333. get: function () {
  14334. var keyboard = this.inputs.attached["keyboard"];
  14335. if (keyboard)
  14336. return keyboard.keysLeft;
  14337. },
  14338. set: function (value) {
  14339. var keyboard = this.inputs.attached["keyboard"];
  14340. if (keyboard)
  14341. keyboard.keysLeft = value;
  14342. },
  14343. enumerable: true,
  14344. configurable: true
  14345. });
  14346. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  14347. get: function () {
  14348. var keyboard = this.inputs.attached["keyboard"];
  14349. if (keyboard)
  14350. return keyboard.keysRight;
  14351. },
  14352. set: function (value) {
  14353. var keyboard = this.inputs.attached["keyboard"];
  14354. if (keyboard)
  14355. keyboard.keysRight = value;
  14356. },
  14357. enumerable: true,
  14358. configurable: true
  14359. });
  14360. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  14361. get: function () {
  14362. var mousewheel = this.inputs.attached["mousewheel"];
  14363. if (mousewheel)
  14364. return mousewheel.wheelPrecision;
  14365. },
  14366. set: function (value) {
  14367. var mousewheel = this.inputs.attached["mousewheel"];
  14368. if (mousewheel)
  14369. mousewheel.wheelPrecision = value;
  14370. },
  14371. enumerable: true,
  14372. configurable: true
  14373. });
  14374. // Cache
  14375. ArcRotateCamera.prototype._initCache = function () {
  14376. _super.prototype._initCache.call(this);
  14377. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  14378. this._cache.alpha = undefined;
  14379. this._cache.beta = undefined;
  14380. this._cache.radius = undefined;
  14381. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  14382. };
  14383. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  14384. if (!ignoreParentClass) {
  14385. _super.prototype._updateCache.call(this);
  14386. }
  14387. this._cache.target.copyFrom(this._getTargetPosition());
  14388. this._cache.alpha = this.alpha;
  14389. this._cache.beta = this.beta;
  14390. this._cache.radius = this.radius;
  14391. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  14392. };
  14393. ArcRotateCamera.prototype._getTargetPosition = function () {
  14394. if (this.target.getAbsolutePosition) {
  14395. return this.target.getAbsolutePosition();
  14396. }
  14397. return this.target;
  14398. };
  14399. // Synchronized
  14400. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  14401. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  14402. return false;
  14403. return this._cache.target.equals(this.target)
  14404. && this._cache.alpha === this.alpha
  14405. && this._cache.beta === this.beta
  14406. && this._cache.radius === this.radius
  14407. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  14408. };
  14409. // Methods
  14410. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  14411. var _this = this;
  14412. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  14413. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  14414. this._useCtrlForPanning = useCtrlForPanning;
  14415. this._panningMouseButton = panningMouseButton;
  14416. this.inputs.attachElement(element, noPreventDefault);
  14417. this._reset = function () {
  14418. _this.inertialAlphaOffset = 0;
  14419. _this.inertialBetaOffset = 0;
  14420. _this.inertialRadiusOffset = 0;
  14421. };
  14422. };
  14423. ArcRotateCamera.prototype.detachControl = function (element) {
  14424. this.inputs.detachElement(element);
  14425. if (this._reset) {
  14426. this._reset();
  14427. }
  14428. };
  14429. ArcRotateCamera.prototype._checkInputs = function () {
  14430. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  14431. if (this._collisionTriggered) {
  14432. return;
  14433. }
  14434. this.inputs.checkInputs();
  14435. // Inertia
  14436. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  14437. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  14438. this.beta += this.inertialBetaOffset;
  14439. this.radius -= this.inertialRadiusOffset;
  14440. this.inertialAlphaOffset *= this.inertia;
  14441. this.inertialBetaOffset *= this.inertia;
  14442. this.inertialRadiusOffset *= this.inertia;
  14443. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  14444. this.inertialAlphaOffset = 0;
  14445. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  14446. this.inertialBetaOffset = 0;
  14447. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Epsilon)
  14448. this.inertialRadiusOffset = 0;
  14449. }
  14450. // Panning inertia
  14451. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  14452. if (!this._localDirection) {
  14453. this._localDirection = BABYLON.Vector3.Zero();
  14454. this._transformedDirection = BABYLON.Vector3.Zero();
  14455. }
  14456. this.inertialPanningX *= this.inertia;
  14457. this.inertialPanningY *= this.inertia;
  14458. if (Math.abs(this.inertialPanningX) < BABYLON.Epsilon)
  14459. this.inertialPanningX = 0;
  14460. if (Math.abs(this.inertialPanningY) < BABYLON.Epsilon)
  14461. this.inertialPanningY = 0;
  14462. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  14463. this._localDirection.multiplyInPlace(this.panningAxis);
  14464. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  14465. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  14466. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  14467. if (!this.panningAxis.y) {
  14468. this._transformedDirection.y = 0;
  14469. }
  14470. if (!this.target.getAbsolutePosition) {
  14471. this.target.addInPlace(this._transformedDirection);
  14472. }
  14473. }
  14474. // Limits
  14475. this._checkLimits();
  14476. _super.prototype._checkInputs.call(this);
  14477. };
  14478. ArcRotateCamera.prototype._checkLimits = function () {
  14479. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  14480. if (this.allowUpsideDown && this.beta > Math.PI) {
  14481. this.beta = this.beta - (2 * Math.PI);
  14482. }
  14483. }
  14484. else {
  14485. if (this.beta < this.lowerBetaLimit) {
  14486. this.beta = this.lowerBetaLimit;
  14487. }
  14488. }
  14489. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  14490. if (this.allowUpsideDown && this.beta < -Math.PI) {
  14491. this.beta = this.beta + (2 * Math.PI);
  14492. }
  14493. }
  14494. else {
  14495. if (this.beta > this.upperBetaLimit) {
  14496. this.beta = this.upperBetaLimit;
  14497. }
  14498. }
  14499. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  14500. this.alpha = this.lowerAlphaLimit;
  14501. }
  14502. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  14503. this.alpha = this.upperAlphaLimit;
  14504. }
  14505. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  14506. this.radius = this.lowerRadiusLimit;
  14507. }
  14508. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  14509. this.radius = this.upperRadiusLimit;
  14510. }
  14511. };
  14512. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  14513. var radiusv3 = this.position.subtract(this._getTargetPosition());
  14514. this.radius = radiusv3.length();
  14515. // Alpha
  14516. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  14517. if (radiusv3.z < 0) {
  14518. this.alpha = 2 * Math.PI - this.alpha;
  14519. }
  14520. // Beta
  14521. this.beta = Math.acos(radiusv3.y / this.radius);
  14522. this._checkLimits();
  14523. };
  14524. ArcRotateCamera.prototype.setPosition = function (position) {
  14525. if (this.position.equals(position)) {
  14526. return;
  14527. }
  14528. this.position.copyFrom(position);
  14529. this.rebuildAnglesAndRadius();
  14530. };
  14531. ArcRotateCamera.prototype.setTarget = function (target) {
  14532. if (this._getTargetPosition().equals(target)) {
  14533. return;
  14534. }
  14535. this.target = target;
  14536. this.rebuildAnglesAndRadius();
  14537. };
  14538. ArcRotateCamera.prototype._getViewMatrix = function () {
  14539. // Compute
  14540. var cosa = Math.cos(this.alpha);
  14541. var sina = Math.sin(this.alpha);
  14542. var cosb = Math.cos(this.beta);
  14543. var sinb = Math.sin(this.beta);
  14544. if (sinb === 0) {
  14545. sinb = 0.0001;
  14546. }
  14547. var target = this._getTargetPosition();
  14548. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  14549. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  14550. this._collider.radius = this.collisionRadius;
  14551. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  14552. this._collisionTriggered = true;
  14553. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  14554. }
  14555. else {
  14556. this.position.copyFrom(this._newPosition);
  14557. var up = this.upVector;
  14558. if (this.allowUpsideDown && this.beta < 0) {
  14559. up = up.clone();
  14560. up = up.negate();
  14561. }
  14562. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  14563. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  14564. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  14565. }
  14566. return this._viewMatrix;
  14567. };
  14568. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  14569. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  14570. meshes = meshes || this.getScene().meshes;
  14571. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  14572. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  14573. this.radius = distance * this.zoomOnFactor;
  14574. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  14575. };
  14576. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  14577. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  14578. var meshesOrMinMaxVector;
  14579. var distance;
  14580. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  14581. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  14582. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  14583. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  14584. }
  14585. else {
  14586. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  14587. distance = meshesOrMinMaxVectorAndDistance.distance;
  14588. }
  14589. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  14590. if (!doNotUpdateMaxZ) {
  14591. this.maxZ = distance * 2;
  14592. }
  14593. };
  14594. /**
  14595. * @override
  14596. * Override Camera.createRigCamera
  14597. */
  14598. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  14599. var alphaShift;
  14600. switch (this.cameraRigMode) {
  14601. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  14602. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  14603. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  14604. case BABYLON.Camera.RIG_MODE_VR:
  14605. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  14606. break;
  14607. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  14608. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  14609. break;
  14610. }
  14611. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this.target, this.getScene());
  14612. rigCam._cameraRigParams = {};
  14613. return rigCam;
  14614. };
  14615. /**
  14616. * @override
  14617. * Override Camera._updateRigCameras
  14618. */
  14619. ArcRotateCamera.prototype._updateRigCameras = function () {
  14620. var camLeft = this._rigCameras[0];
  14621. var camRight = this._rigCameras[1];
  14622. camLeft.beta = camRight.beta = this.beta;
  14623. camLeft.radius = camRight.radius = this.radius;
  14624. switch (this.cameraRigMode) {
  14625. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  14626. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  14627. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  14628. case BABYLON.Camera.RIG_MODE_VR:
  14629. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  14630. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  14631. break;
  14632. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  14633. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  14634. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  14635. break;
  14636. }
  14637. _super.prototype._updateRigCameras.call(this);
  14638. };
  14639. ArcRotateCamera.prototype.dispose = function () {
  14640. this.inputs.clear();
  14641. _super.prototype.dispose.call(this);
  14642. };
  14643. ArcRotateCamera.prototype.getTypeName = function () {
  14644. return "ArcRotateCamera";
  14645. };
  14646. __decorate([
  14647. BABYLON.serialize()
  14648. ], ArcRotateCamera.prototype, "alpha", void 0);
  14649. __decorate([
  14650. BABYLON.serialize()
  14651. ], ArcRotateCamera.prototype, "beta", void 0);
  14652. __decorate([
  14653. BABYLON.serialize()
  14654. ], ArcRotateCamera.prototype, "radius", void 0);
  14655. __decorate([
  14656. BABYLON.serializeAsVector3()
  14657. ], ArcRotateCamera.prototype, "target", void 0);
  14658. __decorate([
  14659. BABYLON.serialize()
  14660. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  14661. __decorate([
  14662. BABYLON.serialize()
  14663. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  14664. __decorate([
  14665. BABYLON.serialize()
  14666. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  14667. __decorate([
  14668. BABYLON.serialize()
  14669. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  14670. __decorate([
  14671. BABYLON.serialize()
  14672. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  14673. __decorate([
  14674. BABYLON.serialize()
  14675. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  14676. __decorate([
  14677. BABYLON.serialize()
  14678. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  14679. __decorate([
  14680. BABYLON.serialize()
  14681. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  14682. __decorate([
  14683. BABYLON.serialize()
  14684. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  14685. __decorate([
  14686. BABYLON.serialize()
  14687. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  14688. __decorate([
  14689. BABYLON.serialize()
  14690. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  14691. __decorate([
  14692. BABYLON.serialize()
  14693. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  14694. __decorate([
  14695. BABYLON.serialize()
  14696. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  14697. return ArcRotateCamera;
  14698. }(BABYLON.TargetCamera));
  14699. BABYLON.ArcRotateCamera = ArcRotateCamera;
  14700. })(BABYLON || (BABYLON = {}));
  14701. var BABYLON;
  14702. (function (BABYLON) {
  14703. var ArcRotateCameraInputsManager = (function (_super) {
  14704. __extends(ArcRotateCameraInputsManager, _super);
  14705. function ArcRotateCameraInputsManager(camera) {
  14706. _super.call(this, camera);
  14707. }
  14708. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  14709. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  14710. return this;
  14711. };
  14712. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  14713. this.add(new BABYLON.ArcRotateCameraPointersInput());
  14714. return this;
  14715. };
  14716. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  14717. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  14718. return this;
  14719. };
  14720. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  14721. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  14722. return this;
  14723. };
  14724. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  14725. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  14726. return this;
  14727. };
  14728. return ArcRotateCameraInputsManager;
  14729. }(BABYLON.CameraInputsManager));
  14730. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  14731. })(BABYLON || (BABYLON = {}));
  14732. var BABYLON;
  14733. (function (BABYLON) {
  14734. var RenderingManager = (function () {
  14735. function RenderingManager(scene) {
  14736. this._renderingGroups = new Array();
  14737. this._scene = scene;
  14738. }
  14739. RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
  14740. if (this._scene._activeParticleSystems.length === 0) {
  14741. return;
  14742. }
  14743. // Particles
  14744. var activeCamera = this._scene.activeCamera;
  14745. this._scene._particlesDuration.beginMonitoring();
  14746. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  14747. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  14748. if (particleSystem.renderingGroupId !== index) {
  14749. continue;
  14750. }
  14751. if ((activeCamera.layerMask & particleSystem.layerMask) === 0) {
  14752. continue;
  14753. }
  14754. this._clearDepthBuffer();
  14755. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  14756. this._scene._activeParticles.addCount(particleSystem.render(), false);
  14757. }
  14758. }
  14759. this._scene._particlesDuration.endMonitoring(false);
  14760. };
  14761. RenderingManager.prototype._renderSprites = function (index) {
  14762. if (!this._scene.spritesEnabled || this._scene.spriteManagers.length === 0) {
  14763. return;
  14764. }
  14765. // Sprites
  14766. var activeCamera = this._scene.activeCamera;
  14767. this._scene._spritesDuration.beginMonitoring();
  14768. for (var id = 0; id < this._scene.spriteManagers.length; id++) {
  14769. var spriteManager = this._scene.spriteManagers[id];
  14770. if (spriteManager.renderingGroupId === index && ((activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  14771. this._clearDepthBuffer();
  14772. spriteManager.render();
  14773. }
  14774. }
  14775. this._scene._spritesDuration.endMonitoring(false);
  14776. };
  14777. RenderingManager.prototype._clearDepthBuffer = function () {
  14778. if (this._depthBufferAlreadyCleaned) {
  14779. return;
  14780. }
  14781. this._scene.getEngine().clear(0, false, true);
  14782. this._depthBufferAlreadyCleaned = true;
  14783. };
  14784. RenderingManager.prototype._renderSpritesAndParticles = function () {
  14785. if (this._currentRenderSprites) {
  14786. this._renderSprites(this._currentIndex);
  14787. }
  14788. if (this._currentRenderParticles) {
  14789. this._renderParticles(this._currentIndex, this._currentActiveMeshes);
  14790. }
  14791. };
  14792. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  14793. this._currentActiveMeshes = activeMeshes;
  14794. this._currentRenderParticles = renderParticles;
  14795. this._currentRenderSprites = renderSprites;
  14796. for (var index = 0; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  14797. this._depthBufferAlreadyCleaned = index === 0;
  14798. var renderingGroup = this._renderingGroups[index];
  14799. var needToStepBack = false;
  14800. this._currentIndex = index;
  14801. if (renderingGroup) {
  14802. this._clearDepthBuffer();
  14803. if (!renderingGroup.onBeforeTransparentRendering) {
  14804. renderingGroup.onBeforeTransparentRendering = this._renderSpritesAndParticles.bind(this);
  14805. }
  14806. if (!renderingGroup.render(customRenderFunction)) {
  14807. this._renderingGroups.splice(index, 1);
  14808. needToStepBack = true;
  14809. this._renderSpritesAndParticles();
  14810. }
  14811. }
  14812. else {
  14813. this._renderSpritesAndParticles();
  14814. }
  14815. if (needToStepBack) {
  14816. index--;
  14817. }
  14818. }
  14819. };
  14820. RenderingManager.prototype.reset = function () {
  14821. this._renderingGroups.forEach(function (renderingGroup, index, array) {
  14822. if (renderingGroup) {
  14823. renderingGroup.prepare();
  14824. }
  14825. });
  14826. };
  14827. RenderingManager.prototype.dispatch = function (subMesh) {
  14828. var mesh = subMesh.getMesh();
  14829. var renderingGroupId = mesh.renderingGroupId || 0;
  14830. if (!this._renderingGroups[renderingGroupId]) {
  14831. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene);
  14832. }
  14833. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  14834. };
  14835. RenderingManager.MAX_RENDERINGGROUPS = 4;
  14836. return RenderingManager;
  14837. }());
  14838. BABYLON.RenderingManager = RenderingManager;
  14839. })(BABYLON || (BABYLON = {}));
  14840. var BABYLON;
  14841. (function (BABYLON) {
  14842. var RenderingGroup = (function () {
  14843. function RenderingGroup(index, scene) {
  14844. this.index = index;
  14845. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  14846. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  14847. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  14848. this._scene = scene;
  14849. }
  14850. RenderingGroup.prototype.render = function (customRenderFunction) {
  14851. if (customRenderFunction) {
  14852. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  14853. return true;
  14854. }
  14855. if (this._opaqueSubMeshes.length === 0 && this._alphaTestSubMeshes.length === 0 && this._transparentSubMeshes.length === 0) {
  14856. if (this.onBeforeTransparentRendering) {
  14857. this.onBeforeTransparentRendering();
  14858. }
  14859. return false;
  14860. }
  14861. var engine = this._scene.getEngine();
  14862. // Opaque
  14863. var subIndex;
  14864. var submesh;
  14865. for (subIndex = 0; subIndex < this._opaqueSubMeshes.length; subIndex++) {
  14866. submesh = this._opaqueSubMeshes.data[subIndex];
  14867. submesh.render(false);
  14868. }
  14869. // Alpha test
  14870. engine.setAlphaTesting(true);
  14871. for (subIndex = 0; subIndex < this._alphaTestSubMeshes.length; subIndex++) {
  14872. submesh = this._alphaTestSubMeshes.data[subIndex];
  14873. submesh.render(false);
  14874. }
  14875. engine.setAlphaTesting(false);
  14876. if (this.onBeforeTransparentRendering) {
  14877. this.onBeforeTransparentRendering();
  14878. }
  14879. // Transparent
  14880. if (this._transparentSubMeshes.length) {
  14881. // Sorting
  14882. for (subIndex = 0; subIndex < this._transparentSubMeshes.length; subIndex++) {
  14883. submesh = this._transparentSubMeshes.data[subIndex];
  14884. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  14885. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(this._scene.activeCamera.globalPosition).length();
  14886. }
  14887. var sortedArray = this._transparentSubMeshes.data.slice(0, this._transparentSubMeshes.length);
  14888. sortedArray.sort(function (a, b) {
  14889. // Alpha index first
  14890. if (a._alphaIndex > b._alphaIndex) {
  14891. return 1;
  14892. }
  14893. if (a._alphaIndex < b._alphaIndex) {
  14894. return -1;
  14895. }
  14896. // Then distance to camera
  14897. if (a._distanceToCamera < b._distanceToCamera) {
  14898. return 1;
  14899. }
  14900. if (a._distanceToCamera > b._distanceToCamera) {
  14901. return -1;
  14902. }
  14903. return 0;
  14904. });
  14905. // Rendering
  14906. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  14907. submesh = sortedArray[subIndex];
  14908. submesh.render(true);
  14909. }
  14910. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  14911. }
  14912. return true;
  14913. };
  14914. RenderingGroup.prototype.prepare = function () {
  14915. this._opaqueSubMeshes.reset();
  14916. this._transparentSubMeshes.reset();
  14917. this._alphaTestSubMeshes.reset();
  14918. };
  14919. RenderingGroup.prototype.dispatch = function (subMesh) {
  14920. var material = subMesh.getMaterial();
  14921. var mesh = subMesh.getMesh();
  14922. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  14923. this._transparentSubMeshes.push(subMesh);
  14924. }
  14925. else if (material.needAlphaTesting()) {
  14926. this._alphaTestSubMeshes.push(subMesh);
  14927. }
  14928. else {
  14929. this._opaqueSubMeshes.push(subMesh); // Opaque
  14930. }
  14931. };
  14932. return RenderingGroup;
  14933. }());
  14934. BABYLON.RenderingGroup = RenderingGroup;
  14935. })(BABYLON || (BABYLON = {}));
  14936. var BABYLON;
  14937. (function (BABYLON) {
  14938. var PointerEventTypes = (function () {
  14939. function PointerEventTypes() {
  14940. }
  14941. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  14942. get: function () {
  14943. return PointerEventTypes._POINTERDOWN;
  14944. },
  14945. enumerable: true,
  14946. configurable: true
  14947. });
  14948. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  14949. get: function () {
  14950. return PointerEventTypes._POINTERUP;
  14951. },
  14952. enumerable: true,
  14953. configurable: true
  14954. });
  14955. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  14956. get: function () {
  14957. return PointerEventTypes._POINTERMOVE;
  14958. },
  14959. enumerable: true,
  14960. configurable: true
  14961. });
  14962. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  14963. get: function () {
  14964. return PointerEventTypes._POINTERWHEEL;
  14965. },
  14966. enumerable: true,
  14967. configurable: true
  14968. });
  14969. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  14970. get: function () {
  14971. return PointerEventTypes._POINTERPICK;
  14972. },
  14973. enumerable: true,
  14974. configurable: true
  14975. });
  14976. PointerEventTypes._POINTERDOWN = 0x01;
  14977. PointerEventTypes._POINTERUP = 0x02;
  14978. PointerEventTypes._POINTERMOVE = 0x04;
  14979. PointerEventTypes._POINTERWHEEL = 0x08;
  14980. PointerEventTypes._POINTERPICK = 0x10;
  14981. return PointerEventTypes;
  14982. }());
  14983. BABYLON.PointerEventTypes = PointerEventTypes;
  14984. var PointerInfoBase = (function () {
  14985. function PointerInfoBase(type, event) {
  14986. this.type = type;
  14987. this.event = event;
  14988. }
  14989. return PointerInfoBase;
  14990. }());
  14991. BABYLON.PointerInfoBase = PointerInfoBase;
  14992. /**
  14993. * This class is used to store pointer related info for the onPrePointerObservable event.
  14994. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  14995. */
  14996. var PointerInfoPre = (function (_super) {
  14997. __extends(PointerInfoPre, _super);
  14998. function PointerInfoPre(type, event, localX, localY) {
  14999. _super.call(this, type, event);
  15000. this.skipOnPointerObservable = false;
  15001. this.localPosition = new BABYLON.Vector2(localX, localY);
  15002. }
  15003. return PointerInfoPre;
  15004. }(PointerInfoBase));
  15005. BABYLON.PointerInfoPre = PointerInfoPre;
  15006. /**
  15007. * This type contains all the data related to a pointer event in Babylon.js.
  15008. * 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.
  15009. */
  15010. var PointerInfo = (function (_super) {
  15011. __extends(PointerInfo, _super);
  15012. function PointerInfo(type, event, pickInfo) {
  15013. _super.call(this, type, event);
  15014. this.pickInfo = pickInfo;
  15015. }
  15016. return PointerInfo;
  15017. }(PointerInfoBase));
  15018. BABYLON.PointerInfo = PointerInfo;
  15019. /**
  15020. * Represents a scene to be rendered by the engine.
  15021. * @see http://doc.babylonjs.com/page.php?p=21911
  15022. */
  15023. var Scene = (function () {
  15024. /**
  15025. * @constructor
  15026. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  15027. */
  15028. function Scene(engine) {
  15029. // Members
  15030. this.autoClear = true;
  15031. this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  15032. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  15033. this.forceWireframe = false;
  15034. this.forcePointsCloud = false;
  15035. this.forceShowBoundingBoxes = false;
  15036. this.animationsEnabled = true;
  15037. this.constantlyUpdateMeshUnderPointer = false;
  15038. this.hoverCursor = "pointer";
  15039. // Events
  15040. /**
  15041. * An event triggered when the scene is disposed.
  15042. * @type {BABYLON.Observable}
  15043. */
  15044. this.onDisposeObservable = new BABYLON.Observable();
  15045. /**
  15046. * An event triggered before rendering the scene
  15047. * @type {BABYLON.Observable}
  15048. */
  15049. this.onBeforeRenderObservable = new BABYLON.Observable();
  15050. /**
  15051. * An event triggered after rendering the scene
  15052. * @type {BABYLON.Observable}
  15053. */
  15054. this.onAfterRenderObservable = new BABYLON.Observable();
  15055. /**
  15056. * An event triggered when the scene is ready
  15057. * @type {BABYLON.Observable}
  15058. */
  15059. this.onReadyObservable = new BABYLON.Observable();
  15060. /**
  15061. * An event triggered before rendering a camera
  15062. * @type {BABYLON.Observable}
  15063. */
  15064. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  15065. /**
  15066. * An event triggered after rendering a camera
  15067. * @type {BABYLON.Observable}
  15068. */
  15069. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  15070. /**
  15071. * An event triggered when a camera is created
  15072. * @type {BABYLON.Observable}
  15073. */
  15074. this.onNewCameraAddedObservable = new BABYLON.Observable();
  15075. /**
  15076. * An event triggered when a camera is removed
  15077. * @type {BABYLON.Observable}
  15078. */
  15079. this.onCameraRemovedObservable = new BABYLON.Observable();
  15080. /**
  15081. * An event triggered when a light is created
  15082. * @type {BABYLON.Observable}
  15083. */
  15084. this.onNewLightAddedObservable = new BABYLON.Observable();
  15085. /**
  15086. * An event triggered when a light is removed
  15087. * @type {BABYLON.Observable}
  15088. */
  15089. this.onLightRemovedObservable = new BABYLON.Observable();
  15090. /**
  15091. * An event triggered when a geometry is created
  15092. * @type {BABYLON.Observable}
  15093. */
  15094. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  15095. /**
  15096. * An event triggered when a geometry is removed
  15097. * @type {BABYLON.Observable}
  15098. */
  15099. this.onGeometryRemovedObservable = new BABYLON.Observable();
  15100. /**
  15101. * An event triggered when a mesh is created
  15102. * @type {BABYLON.Observable}
  15103. */
  15104. this.onNewMeshAddedObservable = new BABYLON.Observable();
  15105. /**
  15106. * An event triggered when a mesh is removed
  15107. * @type {BABYLON.Observable}
  15108. */
  15109. this.onMeshRemovedObservable = new BABYLON.Observable();
  15110. // Animations
  15111. this.animations = [];
  15112. /**
  15113. * 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).
  15114. * You have the possibility to skip the 3D Engine process and the call to onPointerObservable by setting PointerInfoBase.skipOnPointerObservable to true
  15115. */
  15116. this.onPrePointerObservable = new BABYLON.Observable();
  15117. /**
  15118. * Observable event triggered each time an input event is received from the rendering canvas
  15119. */
  15120. this.onPointerObservable = new BABYLON.Observable();
  15121. 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
  15122. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  15123. this._startingPointerTime = 0;
  15124. // Fog
  15125. /**
  15126. * is fog enabled on this scene.
  15127. * @type {boolean}
  15128. */
  15129. this.fogEnabled = true;
  15130. this.fogMode = Scene.FOGMODE_NONE;
  15131. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  15132. this.fogDensity = 0.1;
  15133. this.fogStart = 0;
  15134. this.fogEnd = 1000.0;
  15135. // Lights
  15136. /**
  15137. * is shadow enabled on this scene.
  15138. * @type {boolean}
  15139. */
  15140. this.shadowsEnabled = true;
  15141. /**
  15142. * is light enabled on this scene.
  15143. * @type {boolean}
  15144. */
  15145. this.lightsEnabled = true;
  15146. /**
  15147. * All of the lights added to this scene.
  15148. * @see BABYLON.Light
  15149. * @type {BABYLON.Light[]}
  15150. */
  15151. this.lights = new Array();
  15152. // Cameras
  15153. /**
  15154. * All of the cameras added to this scene.
  15155. * @see BABYLON.Camera
  15156. * @type {BABYLON.Camera[]}
  15157. */
  15158. this.cameras = new Array();
  15159. this.activeCameras = new Array();
  15160. // Meshes
  15161. /**
  15162. * All of the (abstract) meshes added to this scene.
  15163. * @see BABYLON.AbstractMesh
  15164. * @type {BABYLON.AbstractMesh[]}
  15165. */
  15166. this.meshes = new Array();
  15167. // Geometries
  15168. this._geometries = new Array();
  15169. this.materials = new Array();
  15170. this.multiMaterials = new Array();
  15171. this.defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  15172. // Textures
  15173. this.texturesEnabled = true;
  15174. this.textures = new Array();
  15175. // Particles
  15176. this.particlesEnabled = true;
  15177. this.particleSystems = new Array();
  15178. // Sprites
  15179. this.spritesEnabled = true;
  15180. this.spriteManagers = new Array();
  15181. // Layers
  15182. this.layers = new Array();
  15183. // Skeletons
  15184. this.skeletonsEnabled = true;
  15185. this.skeletons = new Array();
  15186. // Lens flares
  15187. this.lensFlaresEnabled = true;
  15188. this.lensFlareSystems = new Array();
  15189. // Collisions
  15190. this.collisionsEnabled = true;
  15191. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  15192. // Postprocesses
  15193. this.postProcessesEnabled = true;
  15194. // Customs render targets
  15195. this.renderTargetsEnabled = true;
  15196. this.dumpNextRenderTargets = false;
  15197. this.customRenderTargets = new Array();
  15198. // Imported meshes
  15199. this.importedMeshesFiles = new Array();
  15200. // Probes
  15201. this.probesEnabled = true;
  15202. this.reflectionProbes = new Array();
  15203. this._actionManagers = new Array();
  15204. this._meshesForIntersections = new BABYLON.SmartArray(256);
  15205. // Procedural textures
  15206. this.proceduralTexturesEnabled = true;
  15207. this._proceduralTextures = new Array();
  15208. this.soundTracks = new Array();
  15209. this._audioEnabled = true;
  15210. this._headphone = false;
  15211. // Performance counters
  15212. this._totalMeshesCounter = new BABYLON.PerfCounter();
  15213. this._totalLightsCounter = new BABYLON.PerfCounter();
  15214. this._totalMaterialsCounter = new BABYLON.PerfCounter();
  15215. this._totalTexturesCounter = new BABYLON.PerfCounter();
  15216. this._totalVertices = new BABYLON.PerfCounter();
  15217. this._activeIndices = new BABYLON.PerfCounter();
  15218. this._activeParticles = new BABYLON.PerfCounter();
  15219. this._lastFrameDuration = new BABYLON.PerfCounter();
  15220. this._evaluateActiveMeshesDuration = new BABYLON.PerfCounter();
  15221. this._renderTargetsDuration = new BABYLON.PerfCounter();
  15222. this._particlesDuration = new BABYLON.PerfCounter();
  15223. this._renderDuration = new BABYLON.PerfCounter();
  15224. this._spritesDuration = new BABYLON.PerfCounter();
  15225. this._activeBones = new BABYLON.PerfCounter();
  15226. this._renderId = 0;
  15227. this._executeWhenReadyTimeoutId = -1;
  15228. this._intermediateRendering = false;
  15229. this._toBeDisposed = new BABYLON.SmartArray(256);
  15230. this._pendingData = []; //ANY
  15231. this._activeMeshes = new BABYLON.SmartArray(256);
  15232. this._processedMaterials = new BABYLON.SmartArray(256);
  15233. this._renderTargets = new BABYLON.SmartArray(256);
  15234. this._activeParticleSystems = new BABYLON.SmartArray(256);
  15235. this._activeSkeletons = new BABYLON.SmartArray(32);
  15236. this._softwareSkinnedMeshes = new BABYLON.SmartArray(32);
  15237. this._activeAnimatables = new Array();
  15238. this._transformMatrix = BABYLON.Matrix.Zero();
  15239. this._edgesRenderers = new BABYLON.SmartArray(16);
  15240. this._uniqueIdCounter = 0;
  15241. this._engine = engine;
  15242. engine.scenes.push(this);
  15243. this._renderingManager = new BABYLON.RenderingManager(this);
  15244. this.postProcessManager = new BABYLON.PostProcessManager(this);
  15245. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  15246. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  15247. if (BABYLON.OutlineRenderer) {
  15248. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  15249. }
  15250. this.attachControl();
  15251. if (BABYLON.SoundTrack) {
  15252. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  15253. }
  15254. //simplification queue
  15255. if (BABYLON.SimplificationQueue) {
  15256. this.simplificationQueue = new BABYLON.SimplificationQueue();
  15257. }
  15258. //collision coordinator initialization. For now legacy per default.
  15259. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  15260. }
  15261. Object.defineProperty(Scene, "FOGMODE_NONE", {
  15262. get: function () {
  15263. return Scene._FOGMODE_NONE;
  15264. },
  15265. enumerable: true,
  15266. configurable: true
  15267. });
  15268. Object.defineProperty(Scene, "FOGMODE_EXP", {
  15269. get: function () {
  15270. return Scene._FOGMODE_EXP;
  15271. },
  15272. enumerable: true,
  15273. configurable: true
  15274. });
  15275. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  15276. get: function () {
  15277. return Scene._FOGMODE_EXP2;
  15278. },
  15279. enumerable: true,
  15280. configurable: true
  15281. });
  15282. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  15283. get: function () {
  15284. return Scene._FOGMODE_LINEAR;
  15285. },
  15286. enumerable: true,
  15287. configurable: true
  15288. });
  15289. Object.defineProperty(Scene.prototype, "onDispose", {
  15290. set: function (callback) {
  15291. if (this._onDisposeObserver) {
  15292. this.onDisposeObservable.remove(this._onDisposeObserver);
  15293. }
  15294. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  15295. },
  15296. enumerable: true,
  15297. configurable: true
  15298. });
  15299. Object.defineProperty(Scene.prototype, "beforeRender", {
  15300. set: function (callback) {
  15301. if (this._onBeforeRenderObserver) {
  15302. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  15303. }
  15304. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  15305. },
  15306. enumerable: true,
  15307. configurable: true
  15308. });
  15309. Object.defineProperty(Scene.prototype, "afterRender", {
  15310. set: function (callback) {
  15311. if (this._onAfterRenderObserver) {
  15312. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  15313. }
  15314. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  15315. },
  15316. enumerable: true,
  15317. configurable: true
  15318. });
  15319. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  15320. set: function (callback) {
  15321. if (this._onBeforeCameraRenderObserver) {
  15322. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  15323. }
  15324. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  15325. },
  15326. enumerable: true,
  15327. configurable: true
  15328. });
  15329. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  15330. set: function (callback) {
  15331. if (this._onAfterCameraRenderObserver) {
  15332. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  15333. }
  15334. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  15335. },
  15336. enumerable: true,
  15337. configurable: true
  15338. });
  15339. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  15340. get: function () {
  15341. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  15342. },
  15343. enumerable: true,
  15344. configurable: true
  15345. });
  15346. Object.defineProperty(Scene.prototype, "debugLayer", {
  15347. // Properties
  15348. get: function () {
  15349. if (!this._debugLayer) {
  15350. this._debugLayer = new BABYLON.DebugLayer(this);
  15351. }
  15352. return this._debugLayer;
  15353. },
  15354. enumerable: true,
  15355. configurable: true
  15356. });
  15357. Object.defineProperty(Scene.prototype, "workerCollisions", {
  15358. get: function () {
  15359. return this._workerCollisions;
  15360. },
  15361. set: function (enabled) {
  15362. enabled = (enabled && !!Worker);
  15363. this._workerCollisions = enabled;
  15364. if (this.collisionCoordinator) {
  15365. this.collisionCoordinator.destroy();
  15366. }
  15367. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  15368. this.collisionCoordinator.init(this);
  15369. },
  15370. enumerable: true,
  15371. configurable: true
  15372. });
  15373. Object.defineProperty(Scene.prototype, "SelectionOctree", {
  15374. get: function () {
  15375. return this._selectionOctree;
  15376. },
  15377. enumerable: true,
  15378. configurable: true
  15379. });
  15380. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  15381. /**
  15382. * The mesh that is currently under the pointer.
  15383. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  15384. */
  15385. get: function () {
  15386. return this._pointerOverMesh;
  15387. },
  15388. enumerable: true,
  15389. configurable: true
  15390. });
  15391. Object.defineProperty(Scene.prototype, "pointerX", {
  15392. /**
  15393. * Current on-screen X position of the pointer
  15394. * @return {number} X position of the pointer
  15395. */
  15396. get: function () {
  15397. return this._pointerX;
  15398. },
  15399. enumerable: true,
  15400. configurable: true
  15401. });
  15402. Object.defineProperty(Scene.prototype, "pointerY", {
  15403. /**
  15404. * Current on-screen Y position of the pointer
  15405. * @return {number} Y position of the pointer
  15406. */
  15407. get: function () {
  15408. return this._pointerY;
  15409. },
  15410. enumerable: true,
  15411. configurable: true
  15412. });
  15413. Scene.prototype.getCachedMaterial = function () {
  15414. return this._cachedMaterial;
  15415. };
  15416. Scene.prototype.getBoundingBoxRenderer = function () {
  15417. return this._boundingBoxRenderer;
  15418. };
  15419. Scene.prototype.getOutlineRenderer = function () {
  15420. return this._outlineRenderer;
  15421. };
  15422. Scene.prototype.getEngine = function () {
  15423. return this._engine;
  15424. };
  15425. Scene.prototype.getTotalVertices = function () {
  15426. return this._totalVertices.current;
  15427. };
  15428. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  15429. get: function () {
  15430. return this._totalVertices;
  15431. },
  15432. enumerable: true,
  15433. configurable: true
  15434. });
  15435. Scene.prototype.getActiveIndices = function () {
  15436. return this._activeIndices.current;
  15437. };
  15438. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  15439. get: function () {
  15440. return this._activeIndices;
  15441. },
  15442. enumerable: true,
  15443. configurable: true
  15444. });
  15445. Scene.prototype.getActiveParticles = function () {
  15446. return this._activeParticles.current;
  15447. };
  15448. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  15449. get: function () {
  15450. return this._activeParticles;
  15451. },
  15452. enumerable: true,
  15453. configurable: true
  15454. });
  15455. Scene.prototype.getActiveBones = function () {
  15456. return this._activeBones.current;
  15457. };
  15458. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  15459. get: function () {
  15460. return this._activeBones;
  15461. },
  15462. enumerable: true,
  15463. configurable: true
  15464. });
  15465. // Stats
  15466. Scene.prototype.getLastFrameDuration = function () {
  15467. return this._lastFrameDuration.current;
  15468. };
  15469. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  15470. get: function () {
  15471. return this._lastFrameDuration;
  15472. },
  15473. enumerable: true,
  15474. configurable: true
  15475. });
  15476. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  15477. return this._evaluateActiveMeshesDuration.current;
  15478. };
  15479. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  15480. get: function () {
  15481. return this._evaluateActiveMeshesDuration;
  15482. },
  15483. enumerable: true,
  15484. configurable: true
  15485. });
  15486. Scene.prototype.getActiveMeshes = function () {
  15487. return this._activeMeshes;
  15488. };
  15489. Scene.prototype.getRenderTargetsDuration = function () {
  15490. return this._renderTargetsDuration.current;
  15491. };
  15492. Scene.prototype.getRenderDuration = function () {
  15493. return this._renderDuration.current;
  15494. };
  15495. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  15496. get: function () {
  15497. return this._renderDuration;
  15498. },
  15499. enumerable: true,
  15500. configurable: true
  15501. });
  15502. Scene.prototype.getParticlesDuration = function () {
  15503. return this._particlesDuration.current;
  15504. };
  15505. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  15506. get: function () {
  15507. return this._particlesDuration;
  15508. },
  15509. enumerable: true,
  15510. configurable: true
  15511. });
  15512. Scene.prototype.getSpritesDuration = function () {
  15513. return this._spritesDuration.current;
  15514. };
  15515. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  15516. get: function () {
  15517. return this._spritesDuration;
  15518. },
  15519. enumerable: true,
  15520. configurable: true
  15521. });
  15522. Scene.prototype.getAnimationRatio = function () {
  15523. return this._animationRatio;
  15524. };
  15525. Scene.prototype.getRenderId = function () {
  15526. return this._renderId;
  15527. };
  15528. Scene.prototype.incrementRenderId = function () {
  15529. this._renderId++;
  15530. };
  15531. Scene.prototype._updatePointerPosition = function (evt) {
  15532. var canvasRect = this._engine.getRenderingCanvasClientRect();
  15533. this._pointerX = evt.clientX - canvasRect.left;
  15534. this._pointerY = evt.clientY - canvasRect.top;
  15535. this._unTranslatedPointerX = this._pointerX;
  15536. this._unTranslatedPointerY = this._pointerY;
  15537. if (this.cameraToUseForPointers) {
  15538. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  15539. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  15540. }
  15541. };
  15542. // Pointers handling
  15543. /**
  15544. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  15545. * @param attachUp defines if you want to attach events to pointerup
  15546. * @param attachDown defines if you want to attach events to pointerdown
  15547. * @param attachMove defines if you want to attach events to pointermove
  15548. */
  15549. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  15550. var _this = this;
  15551. if (attachUp === void 0) { attachUp = true; }
  15552. if (attachDown === void 0) { attachDown = true; }
  15553. if (attachMove === void 0) { attachMove = true; }
  15554. var spritePredicate = function (sprite) {
  15555. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  15556. };
  15557. this._onPointerMove = function (evt) {
  15558. _this._updatePointerPosition(evt);
  15559. // PreObservable support
  15560. if (_this.onPrePointerObservable.hasObservers()) {
  15561. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  15562. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  15563. _this.onPrePointerObservable.notifyObservers(pi, type);
  15564. if (pi.skipOnPointerObservable) {
  15565. return;
  15566. }
  15567. }
  15568. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  15569. return;
  15570. }
  15571. var canvas = _this._engine.getRenderingCanvas();
  15572. if (!_this.pointerMovePredicate) {
  15573. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && (_this.constantlyUpdateMeshUnderPointer || mesh.actionManager !== null && mesh.actionManager !== undefined); };
  15574. }
  15575. // Meshes
  15576. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  15577. if (pickResult.hit && pickResult.pickedMesh) {
  15578. _this.setPointerOverSprite(null);
  15579. _this.setPointerOverMesh(pickResult.pickedMesh);
  15580. if (_this._pointerOverMesh.actionManager && _this._pointerOverMesh.actionManager.hasPointerTriggers) {
  15581. canvas.style.cursor = _this.hoverCursor;
  15582. }
  15583. else {
  15584. canvas.style.cursor = "";
  15585. }
  15586. }
  15587. else {
  15588. _this.setPointerOverMesh(null);
  15589. // Sprites
  15590. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  15591. if (pickResult.hit && pickResult.pickedSprite) {
  15592. canvas.style.cursor = _this.hoverCursor;
  15593. _this.setPointerOverSprite(pickResult.pickedSprite);
  15594. }
  15595. else {
  15596. _this.setPointerOverSprite(null);
  15597. // Restore pointer
  15598. canvas.style.cursor = "";
  15599. }
  15600. }
  15601. if (_this.onPointerMove) {
  15602. _this.onPointerMove(evt, pickResult);
  15603. }
  15604. if (_this.onPointerObservable.hasObservers()) {
  15605. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  15606. var pi = new PointerInfo(type, evt, pickResult);
  15607. _this.onPointerObservable.notifyObservers(pi, type);
  15608. }
  15609. };
  15610. this._onPointerDown = function (evt) {
  15611. _this._updatePointerPosition(evt);
  15612. // PreObservable support
  15613. if (_this.onPrePointerObservable.hasObservers()) {
  15614. var type = PointerEventTypes.POINTERDOWN;
  15615. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  15616. _this.onPrePointerObservable.notifyObservers(pi, type);
  15617. if (pi.skipOnPointerObservable) {
  15618. return;
  15619. }
  15620. }
  15621. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  15622. return;
  15623. }
  15624. _this._startingPointerPosition.x = _this._pointerX;
  15625. _this._startingPointerPosition.y = _this._pointerY;
  15626. _this._startingPointerTime = new Date().getTime();
  15627. if (!_this.pointerDownPredicate) {
  15628. _this.pointerDownPredicate = function (mesh) {
  15629. return mesh.isPickable && mesh.isVisible && mesh.isReady() && (!mesh.actionManager || mesh.actionManager.hasPointerTriggers);
  15630. };
  15631. }
  15632. // Meshes
  15633. _this._pickedDownMesh = null;
  15634. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  15635. if (pickResult.hit && pickResult.pickedMesh) {
  15636. if (pickResult.pickedMesh.actionManager) {
  15637. _this._pickedDownMesh = pickResult.pickedMesh;
  15638. if (pickResult.pickedMesh.actionManager.hasPickTriggers) {
  15639. switch (evt.button) {
  15640. case 0:
  15641. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  15642. break;
  15643. case 1:
  15644. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  15645. break;
  15646. case 2:
  15647. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  15648. break;
  15649. }
  15650. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  15651. }
  15652. if (pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  15653. var that = _this;
  15654. window.setTimeout(function () {
  15655. 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);
  15656. if (pickResult.hit && pickResult.pickedMesh) {
  15657. if (pickResult.pickedMesh.actionManager) {
  15658. 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)) {
  15659. that._startingPointerTime = 0;
  15660. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  15661. }
  15662. }
  15663. }
  15664. }, BABYLON.ActionManager.LongPressDelay);
  15665. }
  15666. }
  15667. }
  15668. if (_this.onPointerDown) {
  15669. _this.onPointerDown(evt, pickResult);
  15670. }
  15671. if (_this.onPointerObservable.hasObservers()) {
  15672. var type = PointerEventTypes.POINTERDOWN;
  15673. var pi = new PointerInfo(type, evt, pickResult);
  15674. _this.onPointerObservable.notifyObservers(pi, type);
  15675. }
  15676. // Sprites
  15677. _this._pickedDownSprite = null;
  15678. if (_this.spriteManagers.length > 0) {
  15679. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  15680. if (pickResult.hit && pickResult.pickedSprite) {
  15681. if (pickResult.pickedSprite.actionManager) {
  15682. _this._pickedDownSprite = pickResult.pickedSprite;
  15683. switch (evt.button) {
  15684. case 0:
  15685. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  15686. break;
  15687. case 1:
  15688. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  15689. break;
  15690. case 2:
  15691. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  15692. break;
  15693. }
  15694. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  15695. }
  15696. }
  15697. }
  15698. };
  15699. this._onPointerUp = function (evt) {
  15700. _this._updatePointerPosition(evt);
  15701. // PreObservable support
  15702. if (_this.onPrePointerObservable.hasObservers()) {
  15703. var type = PointerEventTypes.POINTERUP;
  15704. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  15705. _this.onPrePointerObservable.notifyObservers(pi, type);
  15706. if (pi.skipOnPointerObservable) {
  15707. return;
  15708. }
  15709. }
  15710. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  15711. return;
  15712. }
  15713. if (!_this.pointerUpPredicate) {
  15714. _this.pointerUpPredicate = function (mesh) {
  15715. return mesh.isPickable && mesh.isVisible && mesh.isReady() && (!mesh.actionManager || (mesh.actionManager.hasPickTriggers || mesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)));
  15716. };
  15717. }
  15718. // Meshes
  15719. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerUpPredicate, false, _this.cameraToUseForPointers);
  15720. if (pickResult.hit && pickResult.pickedMesh) {
  15721. if (_this._pickedDownMesh != null && pickResult.pickedMesh == _this._pickedDownMesh) {
  15722. if (_this.onPointerPick) {
  15723. _this.onPointerPick(evt, pickResult);
  15724. }
  15725. if (_this.onPointerObservable.hasObservers()) {
  15726. var type = PointerEventTypes.POINTERPICK;
  15727. var pi = new PointerInfo(type, evt, pickResult);
  15728. _this.onPointerObservable.notifyObservers(pi, type);
  15729. }
  15730. }
  15731. if (pickResult.pickedMesh.actionManager) {
  15732. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  15733. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < BABYLON.ActionManager.DragMovementThreshold) {
  15734. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  15735. }
  15736. }
  15737. }
  15738. if (_this._pickedDownMesh && _this._pickedDownMesh !== pickResult.pickedMesh) {
  15739. _this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(_this._pickedDownMesh, evt));
  15740. }
  15741. if (_this.onPointerUp) {
  15742. _this.onPointerUp(evt, pickResult);
  15743. }
  15744. if (_this.onPointerObservable.hasObservers()) {
  15745. var type = PointerEventTypes.POINTERUP;
  15746. var pi = new PointerInfo(type, evt, pickResult);
  15747. _this.onPointerObservable.notifyObservers(pi, type);
  15748. }
  15749. _this._startingPointerTime = 0;
  15750. // Sprites
  15751. if (_this.spriteManagers.length > 0) {
  15752. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  15753. if (pickResult.hit && pickResult.pickedSprite) {
  15754. if (pickResult.pickedSprite.actionManager) {
  15755. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  15756. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < BABYLON.ActionManager.DragMovementThreshold) {
  15757. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  15758. }
  15759. }
  15760. }
  15761. if (_this._pickedDownSprite && _this._pickedDownSprite !== pickResult.pickedSprite) {
  15762. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  15763. }
  15764. }
  15765. };
  15766. this._onKeyDown = function (evt) {
  15767. if (_this.actionManager) {
  15768. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  15769. }
  15770. };
  15771. this._onKeyUp = function (evt) {
  15772. if (_this.actionManager) {
  15773. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  15774. }
  15775. };
  15776. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  15777. var canvas = this._engine.getRenderingCanvas();
  15778. if (attachMove) {
  15779. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  15780. // Wheel
  15781. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  15782. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  15783. }
  15784. if (attachDown) {
  15785. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  15786. }
  15787. if (attachUp) {
  15788. canvas.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  15789. }
  15790. canvas.tabIndex = 1;
  15791. canvas.addEventListener("keydown", this._onKeyDown, false);
  15792. canvas.addEventListener("keyup", this._onKeyUp, false);
  15793. };
  15794. Scene.prototype.detachControl = function () {
  15795. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  15796. var canvas = this._engine.getRenderingCanvas();
  15797. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  15798. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  15799. canvas.removeEventListener(eventPrefix + "up", this._onPointerUp);
  15800. // Wheel
  15801. canvas.removeEventListener('mousewheel', this._onPointerMove);
  15802. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  15803. canvas.removeEventListener("keydown", this._onKeyDown);
  15804. canvas.removeEventListener("keyup", this._onKeyUp);
  15805. };
  15806. // Ready
  15807. Scene.prototype.isReady = function () {
  15808. if (this._pendingData.length > 0) {
  15809. return false;
  15810. }
  15811. var index;
  15812. for (index = 0; index < this._geometries.length; index++) {
  15813. var geometry = this._geometries[index];
  15814. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  15815. return false;
  15816. }
  15817. }
  15818. for (index = 0; index < this.meshes.length; index++) {
  15819. var mesh = this.meshes[index];
  15820. if (!mesh.isReady()) {
  15821. return false;
  15822. }
  15823. var mat = mesh.material;
  15824. if (mat) {
  15825. if (!mat.isReady(mesh)) {
  15826. return false;
  15827. }
  15828. }
  15829. }
  15830. return true;
  15831. };
  15832. Scene.prototype.resetCachedMaterial = function () {
  15833. this._cachedMaterial = null;
  15834. };
  15835. Scene.prototype.registerBeforeRender = function (func) {
  15836. this.onBeforeRenderObservable.add(func);
  15837. };
  15838. Scene.prototype.unregisterBeforeRender = function (func) {
  15839. this.onBeforeRenderObservable.removeCallback(func);
  15840. };
  15841. Scene.prototype.registerAfterRender = function (func) {
  15842. this.onAfterRenderObservable.add(func);
  15843. };
  15844. Scene.prototype.unregisterAfterRender = function (func) {
  15845. this.onAfterRenderObservable.removeCallback(func);
  15846. };
  15847. Scene.prototype._addPendingData = function (data) {
  15848. this._pendingData.push(data);
  15849. };
  15850. Scene.prototype._removePendingData = function (data) {
  15851. var index = this._pendingData.indexOf(data);
  15852. if (index !== -1) {
  15853. this._pendingData.splice(index, 1);
  15854. }
  15855. };
  15856. Scene.prototype.getWaitingItemsCount = function () {
  15857. return this._pendingData.length;
  15858. };
  15859. /**
  15860. * Registers a function to be executed when the scene is ready.
  15861. * @param {Function} func - the function to be executed.
  15862. */
  15863. Scene.prototype.executeWhenReady = function (func) {
  15864. var _this = this;
  15865. this.onReadyObservable.add(func);
  15866. if (this._executeWhenReadyTimeoutId !== -1) {
  15867. return;
  15868. }
  15869. this._executeWhenReadyTimeoutId = setTimeout(function () {
  15870. _this._checkIsReady();
  15871. }, 150);
  15872. };
  15873. Scene.prototype._checkIsReady = function () {
  15874. var _this = this;
  15875. if (this.isReady()) {
  15876. this.onReadyObservable.notifyObservers(this);
  15877. this.onReadyObservable.clear();
  15878. this._executeWhenReadyTimeoutId = -1;
  15879. return;
  15880. }
  15881. this._executeWhenReadyTimeoutId = setTimeout(function () {
  15882. _this._checkIsReady();
  15883. }, 150);
  15884. };
  15885. // Animations
  15886. /**
  15887. * Will start the animation sequence of a given target
  15888. * @param target - the target
  15889. * @param {number} from - from which frame should animation start
  15890. * @param {number} to - till which frame should animation run.
  15891. * @param {boolean} [loop] - should the animation loop
  15892. * @param {number} [speedRatio] - the speed in which to run the animation
  15893. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  15894. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  15895. * @return {BABYLON.Animatable} the animatable object created for this animation
  15896. * @see BABYLON.Animatable
  15897. * @see http://doc.babylonjs.com/page.php?p=22081
  15898. */
  15899. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  15900. if (speedRatio === void 0) { speedRatio = 1.0; }
  15901. this.stopAnimation(target);
  15902. if (!animatable) {
  15903. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  15904. }
  15905. // Local animations
  15906. if (target.animations) {
  15907. animatable.appendAnimations(target, target.animations);
  15908. }
  15909. // Children animations
  15910. if (target.getAnimatables) {
  15911. var animatables = target.getAnimatables();
  15912. for (var index = 0; index < animatables.length; index++) {
  15913. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  15914. }
  15915. }
  15916. animatable.reset();
  15917. return animatable;
  15918. };
  15919. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  15920. if (speedRatio === undefined) {
  15921. speedRatio = 1.0;
  15922. }
  15923. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  15924. return animatable;
  15925. };
  15926. Scene.prototype.getAnimatableByTarget = function (target) {
  15927. for (var index = 0; index < this._activeAnimatables.length; index++) {
  15928. if (this._activeAnimatables[index].target === target) {
  15929. return this._activeAnimatables[index];
  15930. }
  15931. }
  15932. return null;
  15933. };
  15934. Object.defineProperty(Scene.prototype, "Animatables", {
  15935. get: function () {
  15936. return this._activeAnimatables;
  15937. },
  15938. enumerable: true,
  15939. configurable: true
  15940. });
  15941. /**
  15942. * Will stop the animation of the given target
  15943. * @param target - the target
  15944. * @see beginAnimation
  15945. */
  15946. Scene.prototype.stopAnimation = function (target) {
  15947. var animatable = this.getAnimatableByTarget(target);
  15948. if (animatable) {
  15949. animatable.stop();
  15950. }
  15951. };
  15952. Scene.prototype._animate = function () {
  15953. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  15954. return;
  15955. }
  15956. if (!this._animationStartDate) {
  15957. if (this._pendingData.length > 0) {
  15958. return;
  15959. }
  15960. this._animationStartDate = BABYLON.Tools.Now;
  15961. }
  15962. // Getting time
  15963. var now = BABYLON.Tools.Now;
  15964. var delay = now - this._animationStartDate;
  15965. for (var index = 0; index < this._activeAnimatables.length; index++) {
  15966. this._activeAnimatables[index]._animate(delay);
  15967. }
  15968. };
  15969. // Matrix
  15970. Scene.prototype.getViewMatrix = function () {
  15971. return this._viewMatrix;
  15972. };
  15973. Scene.prototype.getProjectionMatrix = function () {
  15974. return this._projectionMatrix;
  15975. };
  15976. Scene.prototype.getTransformMatrix = function () {
  15977. return this._transformMatrix;
  15978. };
  15979. Scene.prototype.setTransformMatrix = function (view, projection) {
  15980. this._viewMatrix = view;
  15981. this._projectionMatrix = projection;
  15982. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  15983. // Update frustum
  15984. if (!this._frustumPlanes) {
  15985. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  15986. }
  15987. else {
  15988. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  15989. }
  15990. };
  15991. // Methods
  15992. Scene.prototype.addMesh = function (newMesh) {
  15993. newMesh.uniqueId = this._uniqueIdCounter++;
  15994. var position = this.meshes.push(newMesh);
  15995. //notify the collision coordinator
  15996. this.collisionCoordinator.onMeshAdded(newMesh);
  15997. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  15998. };
  15999. Scene.prototype.removeMesh = function (toRemove) {
  16000. var index = this.meshes.indexOf(toRemove);
  16001. if (index !== -1) {
  16002. // Remove from the scene if mesh found
  16003. this.meshes.splice(index, 1);
  16004. }
  16005. //notify the collision coordinator
  16006. this.collisionCoordinator.onMeshRemoved(toRemove);
  16007. this.onMeshRemovedObservable.notifyObservers(toRemove);
  16008. return index;
  16009. };
  16010. Scene.prototype.removeSkeleton = function (toRemove) {
  16011. var index = this.skeletons.indexOf(toRemove);
  16012. if (index !== -1) {
  16013. // Remove from the scene if mesh found
  16014. this.skeletons.splice(index, 1);
  16015. }
  16016. return index;
  16017. };
  16018. Scene.prototype.removeLight = function (toRemove) {
  16019. var index = this.lights.indexOf(toRemove);
  16020. if (index !== -1) {
  16021. // Remove from the scene if mesh found
  16022. this.lights.splice(index, 1);
  16023. }
  16024. this.onLightRemovedObservable.notifyObservers(toRemove);
  16025. return index;
  16026. };
  16027. Scene.prototype.removeCamera = function (toRemove) {
  16028. var index = this.cameras.indexOf(toRemove);
  16029. if (index !== -1) {
  16030. // Remove from the scene if mesh found
  16031. this.cameras.splice(index, 1);
  16032. }
  16033. // Remove from activeCameras
  16034. var index2 = this.activeCameras.indexOf(toRemove);
  16035. if (index2 !== -1) {
  16036. // Remove from the scene if mesh found
  16037. this.activeCameras.splice(index2, 1);
  16038. }
  16039. // Reset the activeCamera
  16040. if (this.activeCamera === toRemove) {
  16041. if (this.cameras.length > 0) {
  16042. this.activeCamera = this.cameras[0];
  16043. }
  16044. else {
  16045. this.activeCamera = null;
  16046. }
  16047. }
  16048. this.onCameraRemovedObservable.notifyObservers(toRemove);
  16049. return index;
  16050. };
  16051. Scene.prototype.addLight = function (newLight) {
  16052. newLight.uniqueId = this._uniqueIdCounter++;
  16053. var position = this.lights.push(newLight);
  16054. this.onNewLightAddedObservable.notifyObservers(newLight);
  16055. };
  16056. Scene.prototype.addCamera = function (newCamera) {
  16057. newCamera.uniqueId = this._uniqueIdCounter++;
  16058. var position = this.cameras.push(newCamera);
  16059. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  16060. };
  16061. /**
  16062. * Switch active camera
  16063. * @param {Camera} newCamera - new active camera
  16064. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  16065. */
  16066. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  16067. if (attachControl === void 0) { attachControl = true; }
  16068. var canvas = this._engine.getRenderingCanvas();
  16069. this.activeCamera.detachControl(canvas);
  16070. this.activeCamera = newCamera;
  16071. if (attachControl) {
  16072. newCamera.attachControl(canvas);
  16073. }
  16074. };
  16075. /**
  16076. * sets the active camera of the scene using its ID
  16077. * @param {string} id - the camera's ID
  16078. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  16079. * @see activeCamera
  16080. */
  16081. Scene.prototype.setActiveCameraByID = function (id) {
  16082. var camera = this.getCameraByID(id);
  16083. if (camera) {
  16084. this.activeCamera = camera;
  16085. return camera;
  16086. }
  16087. return null;
  16088. };
  16089. /**
  16090. * sets the active camera of the scene using its name
  16091. * @param {string} name - the camera's name
  16092. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  16093. * @see activeCamera
  16094. */
  16095. Scene.prototype.setActiveCameraByName = function (name) {
  16096. var camera = this.getCameraByName(name);
  16097. if (camera) {
  16098. this.activeCamera = camera;
  16099. return camera;
  16100. }
  16101. return null;
  16102. };
  16103. /**
  16104. * get a material using its id
  16105. * @param {string} the material's ID
  16106. * @return {BABYLON.Material|null} the material or null if none found.
  16107. */
  16108. Scene.prototype.getMaterialByID = function (id) {
  16109. for (var index = 0; index < this.materials.length; index++) {
  16110. if (this.materials[index].id === id) {
  16111. return this.materials[index];
  16112. }
  16113. }
  16114. return null;
  16115. };
  16116. /**
  16117. * get a material using its name
  16118. * @param {string} the material's name
  16119. * @return {BABYLON.Material|null} the material or null if none found.
  16120. */
  16121. Scene.prototype.getMaterialByName = function (name) {
  16122. for (var index = 0; index < this.materials.length; index++) {
  16123. if (this.materials[index].name === name) {
  16124. return this.materials[index];
  16125. }
  16126. }
  16127. return null;
  16128. };
  16129. Scene.prototype.getLensFlareSystemByName = function (name) {
  16130. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  16131. if (this.lensFlareSystems[index].name === name) {
  16132. return this.lensFlareSystems[index];
  16133. }
  16134. }
  16135. return null;
  16136. };
  16137. Scene.prototype.getLensFlareSystemByID = function (id) {
  16138. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  16139. if (this.lensFlareSystems[index].id === id) {
  16140. return this.lensFlareSystems[index];
  16141. }
  16142. }
  16143. return null;
  16144. };
  16145. Scene.prototype.getCameraByID = function (id) {
  16146. for (var index = 0; index < this.cameras.length; index++) {
  16147. if (this.cameras[index].id === id) {
  16148. return this.cameras[index];
  16149. }
  16150. }
  16151. return null;
  16152. };
  16153. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  16154. for (var index = 0; index < this.cameras.length; index++) {
  16155. if (this.cameras[index].uniqueId === uniqueId) {
  16156. return this.cameras[index];
  16157. }
  16158. }
  16159. return null;
  16160. };
  16161. /**
  16162. * get a camera using its name
  16163. * @param {string} the camera's name
  16164. * @return {BABYLON.Camera|null} the camera or null if none found.
  16165. */
  16166. Scene.prototype.getCameraByName = function (name) {
  16167. for (var index = 0; index < this.cameras.length; index++) {
  16168. if (this.cameras[index].name === name) {
  16169. return this.cameras[index];
  16170. }
  16171. }
  16172. return null;
  16173. };
  16174. /**
  16175. * get a bone using its id
  16176. * @param {string} the bone's id
  16177. * @return {BABYLON.Bone|null} the bone or null if not found
  16178. */
  16179. Scene.prototype.getBoneByID = function (id) {
  16180. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  16181. var skeleton = this.skeletons[skeletonIndex];
  16182. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  16183. if (skeleton.bones[boneIndex].id === id) {
  16184. return skeleton.bones[boneIndex];
  16185. }
  16186. }
  16187. }
  16188. return null;
  16189. };
  16190. /**
  16191. * get a bone using its id
  16192. * @param {string} the bone's name
  16193. * @return {BABYLON.Bone|null} the bone or null if not found
  16194. */
  16195. Scene.prototype.getBoneByName = function (name) {
  16196. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  16197. var skeleton = this.skeletons[skeletonIndex];
  16198. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  16199. if (skeleton.bones[boneIndex].name === name) {
  16200. return skeleton.bones[boneIndex];
  16201. }
  16202. }
  16203. }
  16204. return null;
  16205. };
  16206. /**
  16207. * get a light node using its name
  16208. * @param {string} the light's name
  16209. * @return {BABYLON.Light|null} the light or null if none found.
  16210. */
  16211. Scene.prototype.getLightByName = function (name) {
  16212. for (var index = 0; index < this.lights.length; index++) {
  16213. if (this.lights[index].name === name) {
  16214. return this.lights[index];
  16215. }
  16216. }
  16217. return null;
  16218. };
  16219. /**
  16220. * get a light node using its ID
  16221. * @param {string} the light's id
  16222. * @return {BABYLON.Light|null} the light or null if none found.
  16223. */
  16224. Scene.prototype.getLightByID = function (id) {
  16225. for (var index = 0; index < this.lights.length; index++) {
  16226. if (this.lights[index].id === id) {
  16227. return this.lights[index];
  16228. }
  16229. }
  16230. return null;
  16231. };
  16232. /**
  16233. * get a light node using its scene-generated unique ID
  16234. * @param {number} the light's unique id
  16235. * @return {BABYLON.Light|null} the light or null if none found.
  16236. */
  16237. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  16238. for (var index = 0; index < this.lights.length; index++) {
  16239. if (this.lights[index].uniqueId === uniqueId) {
  16240. return this.lights[index];
  16241. }
  16242. }
  16243. return null;
  16244. };
  16245. /**
  16246. * get a particle system by id
  16247. * @param id {number} the particle system id
  16248. * @return {BABYLON.ParticleSystem|null} the corresponding system or null if none found.
  16249. */
  16250. Scene.prototype.getParticleSystemByID = function (id) {
  16251. for (var index = 0; index < this.particleSystems.length; index++) {
  16252. if (this.particleSystems[index].id === id) {
  16253. return this.particleSystems[index];
  16254. }
  16255. }
  16256. return null;
  16257. };
  16258. /**
  16259. * get a geometry using its ID
  16260. * @param {string} the geometry's id
  16261. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  16262. */
  16263. Scene.prototype.getGeometryByID = function (id) {
  16264. for (var index = 0; index < this._geometries.length; index++) {
  16265. if (this._geometries[index].id === id) {
  16266. return this._geometries[index];
  16267. }
  16268. }
  16269. return null;
  16270. };
  16271. /**
  16272. * add a new geometry to this scene.
  16273. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  16274. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  16275. * @return {boolean} was the geometry added or not
  16276. */
  16277. Scene.prototype.pushGeometry = function (geometry, force) {
  16278. if (!force && this.getGeometryByID(geometry.id)) {
  16279. return false;
  16280. }
  16281. this._geometries.push(geometry);
  16282. //notify the collision coordinator
  16283. this.collisionCoordinator.onGeometryAdded(geometry);
  16284. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  16285. return true;
  16286. };
  16287. /**
  16288. * Removes an existing geometry
  16289. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  16290. * @return {boolean} was the geometry removed or not
  16291. */
  16292. Scene.prototype.removeGeometry = function (geometry) {
  16293. var index = this._geometries.indexOf(geometry);
  16294. if (index > -1) {
  16295. this._geometries.splice(index, 1);
  16296. //notify the collision coordinator
  16297. this.collisionCoordinator.onGeometryDeleted(geometry);
  16298. this.onGeometryRemovedObservable.notifyObservers(geometry);
  16299. return true;
  16300. }
  16301. return false;
  16302. };
  16303. Scene.prototype.getGeometries = function () {
  16304. return this._geometries;
  16305. };
  16306. /**
  16307. * Get the first added mesh found of a given ID
  16308. * @param {string} id - the id to search for
  16309. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  16310. */
  16311. Scene.prototype.getMeshByID = function (id) {
  16312. for (var index = 0; index < this.meshes.length; index++) {
  16313. if (this.meshes[index].id === id) {
  16314. return this.meshes[index];
  16315. }
  16316. }
  16317. return null;
  16318. };
  16319. Scene.prototype.getMeshesByID = function (id) {
  16320. return this.meshes.filter(function (m) {
  16321. return m.id === id;
  16322. });
  16323. };
  16324. /**
  16325. * Get a mesh with its auto-generated unique id
  16326. * @param {number} uniqueId - the unique id to search for
  16327. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  16328. */
  16329. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  16330. for (var index = 0; index < this.meshes.length; index++) {
  16331. if (this.meshes[index].uniqueId === uniqueId) {
  16332. return this.meshes[index];
  16333. }
  16334. }
  16335. return null;
  16336. };
  16337. /**
  16338. * Get a the last added mesh found of a given ID
  16339. * @param {string} id - the id to search for
  16340. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  16341. */
  16342. Scene.prototype.getLastMeshByID = function (id) {
  16343. for (var index = this.meshes.length - 1; index >= 0; index--) {
  16344. if (this.meshes[index].id === id) {
  16345. return this.meshes[index];
  16346. }
  16347. }
  16348. return null;
  16349. };
  16350. /**
  16351. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  16352. * @param {string} id - the id to search for
  16353. * @return {BABYLON.Node|null} the node found or null if not found at all.
  16354. */
  16355. Scene.prototype.getLastEntryByID = function (id) {
  16356. var index;
  16357. for (index = this.meshes.length - 1; index >= 0; index--) {
  16358. if (this.meshes[index].id === id) {
  16359. return this.meshes[index];
  16360. }
  16361. }
  16362. for (index = this.cameras.length - 1; index >= 0; index--) {
  16363. if (this.cameras[index].id === id) {
  16364. return this.cameras[index];
  16365. }
  16366. }
  16367. for (index = this.lights.length - 1; index >= 0; index--) {
  16368. if (this.lights[index].id === id) {
  16369. return this.lights[index];
  16370. }
  16371. }
  16372. return null;
  16373. };
  16374. Scene.prototype.getNodeByID = function (id) {
  16375. var mesh = this.getMeshByID(id);
  16376. if (mesh) {
  16377. return mesh;
  16378. }
  16379. var light = this.getLightByID(id);
  16380. if (light) {
  16381. return light;
  16382. }
  16383. var camera = this.getCameraByID(id);
  16384. if (camera) {
  16385. return camera;
  16386. }
  16387. var bone = this.getBoneByID(id);
  16388. return bone;
  16389. };
  16390. Scene.prototype.getNodeByName = function (name) {
  16391. var mesh = this.getMeshByName(name);
  16392. if (mesh) {
  16393. return mesh;
  16394. }
  16395. var light = this.getLightByName(name);
  16396. if (light) {
  16397. return light;
  16398. }
  16399. var camera = this.getCameraByName(name);
  16400. if (camera) {
  16401. return camera;
  16402. }
  16403. var bone = this.getBoneByName(name);
  16404. return bone;
  16405. };
  16406. Scene.prototype.getMeshByName = function (name) {
  16407. for (var index = 0; index < this.meshes.length; index++) {
  16408. if (this.meshes[index].name === name) {
  16409. return this.meshes[index];
  16410. }
  16411. }
  16412. return null;
  16413. };
  16414. Scene.prototype.getSoundByName = function (name) {
  16415. var index;
  16416. if (BABYLON.AudioEngine) {
  16417. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  16418. if (this.mainSoundTrack.soundCollection[index].name === name) {
  16419. return this.mainSoundTrack.soundCollection[index];
  16420. }
  16421. }
  16422. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  16423. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  16424. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  16425. return this.soundTracks[sdIndex].soundCollection[index];
  16426. }
  16427. }
  16428. }
  16429. }
  16430. return null;
  16431. };
  16432. Scene.prototype.getLastSkeletonByID = function (id) {
  16433. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  16434. if (this.skeletons[index].id === id) {
  16435. return this.skeletons[index];
  16436. }
  16437. }
  16438. return null;
  16439. };
  16440. Scene.prototype.getSkeletonById = function (id) {
  16441. for (var index = 0; index < this.skeletons.length; index++) {
  16442. if (this.skeletons[index].id === id) {
  16443. return this.skeletons[index];
  16444. }
  16445. }
  16446. return null;
  16447. };
  16448. Scene.prototype.getSkeletonByName = function (name) {
  16449. for (var index = 0; index < this.skeletons.length; index++) {
  16450. if (this.skeletons[index].name === name) {
  16451. return this.skeletons[index];
  16452. }
  16453. }
  16454. return null;
  16455. };
  16456. Scene.prototype.isActiveMesh = function (mesh) {
  16457. return (this._activeMeshes.indexOf(mesh) !== -1);
  16458. };
  16459. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  16460. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  16461. var material = subMesh.getMaterial();
  16462. if (mesh.showSubMeshesBoundingBox) {
  16463. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  16464. }
  16465. if (material) {
  16466. // Render targets
  16467. if (material.getRenderTargetTextures) {
  16468. if (this._processedMaterials.indexOf(material) === -1) {
  16469. this._processedMaterials.push(material);
  16470. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  16471. }
  16472. }
  16473. // Dispatch
  16474. this._activeIndices.addCount(subMesh.indexCount, false);
  16475. this._renderingManager.dispatch(subMesh);
  16476. }
  16477. }
  16478. };
  16479. Scene.prototype._isInIntermediateRendering = function () {
  16480. return this._intermediateRendering;
  16481. };
  16482. Scene.prototype._evaluateActiveMeshes = function () {
  16483. this.activeCamera._activeMeshes.reset();
  16484. this._activeMeshes.reset();
  16485. this._renderingManager.reset();
  16486. this._processedMaterials.reset();
  16487. this._activeParticleSystems.reset();
  16488. this._activeSkeletons.reset();
  16489. this._softwareSkinnedMeshes.reset();
  16490. this._boundingBoxRenderer.reset();
  16491. this._edgesRenderers.reset();
  16492. // Meshes
  16493. var meshes;
  16494. var len;
  16495. if (this._selectionOctree) {
  16496. var selection = this._selectionOctree.select(this._frustumPlanes);
  16497. meshes = selection.data;
  16498. len = selection.length;
  16499. }
  16500. else {
  16501. len = this.meshes.length;
  16502. meshes = this.meshes;
  16503. }
  16504. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  16505. var mesh = meshes[meshIndex];
  16506. if (mesh.isBlocked) {
  16507. continue;
  16508. }
  16509. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  16510. if (!mesh.isReady() || !mesh.isEnabled()) {
  16511. continue;
  16512. }
  16513. mesh.computeWorldMatrix();
  16514. // Intersections
  16515. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  16516. this._meshesForIntersections.pushNoDuplicate(mesh);
  16517. }
  16518. // Switch to current LOD
  16519. var meshLOD = mesh.getLOD(this.activeCamera);
  16520. if (!meshLOD) {
  16521. continue;
  16522. }
  16523. mesh._preActivate();
  16524. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  16525. this._activeMeshes.push(mesh);
  16526. this.activeCamera._activeMeshes.push(mesh);
  16527. mesh._activate(this._renderId);
  16528. this._activeMesh(mesh, meshLOD);
  16529. }
  16530. }
  16531. // Particle systems
  16532. this._particlesDuration.beginMonitoring();
  16533. var beforeParticlesDate = BABYLON.Tools.Now;
  16534. if (this.particlesEnabled) {
  16535. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  16536. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  16537. var particleSystem = this.particleSystems[particleIndex];
  16538. if (!particleSystem.isStarted()) {
  16539. continue;
  16540. }
  16541. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  16542. this._activeParticleSystems.push(particleSystem);
  16543. particleSystem.animate();
  16544. }
  16545. }
  16546. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  16547. }
  16548. this._particlesDuration.endMonitoring(false);
  16549. };
  16550. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  16551. if (mesh.skeleton && this.skeletonsEnabled) {
  16552. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  16553. mesh.skeleton.prepare();
  16554. }
  16555. if (!mesh.computeBonesUsingShaders) {
  16556. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  16557. }
  16558. }
  16559. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  16560. this._boundingBoxRenderer.renderList.push(sourceMesh.getBoundingInfo().boundingBox);
  16561. }
  16562. if (sourceMesh._edgesRenderer) {
  16563. this._edgesRenderers.push(sourceMesh._edgesRenderer);
  16564. }
  16565. if (mesh && mesh.subMeshes) {
  16566. // Submeshes Octrees
  16567. var len;
  16568. var subMeshes;
  16569. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  16570. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  16571. len = intersections.length;
  16572. subMeshes = intersections.data;
  16573. }
  16574. else {
  16575. subMeshes = mesh.subMeshes;
  16576. len = subMeshes.length;
  16577. }
  16578. for (var subIndex = 0; subIndex < len; subIndex++) {
  16579. var subMesh = subMeshes[subIndex];
  16580. this._evaluateSubMesh(subMesh, mesh);
  16581. }
  16582. }
  16583. };
  16584. Scene.prototype.updateTransformMatrix = function (force) {
  16585. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  16586. };
  16587. Scene.prototype._renderForCamera = function (camera) {
  16588. var engine = this._engine;
  16589. var startTime = BABYLON.Tools.Now;
  16590. this.activeCamera = camera;
  16591. if (!this.activeCamera)
  16592. throw new Error("Active camera not set");
  16593. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  16594. // Viewport
  16595. engine.setViewport(this.activeCamera.viewport);
  16596. // Camera
  16597. this.resetCachedMaterial();
  16598. this._renderId++;
  16599. this.updateTransformMatrix();
  16600. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  16601. // Meshes
  16602. this._evaluateActiveMeshesDuration.beginMonitoring();
  16603. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  16604. this._evaluateActiveMeshes();
  16605. this._evaluateActiveMeshesDuration.endMonitoring(false);
  16606. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  16607. // Software skinning
  16608. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  16609. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  16610. mesh.applySkeleton(mesh.skeleton);
  16611. }
  16612. // Render targets
  16613. this._renderTargetsDuration.beginMonitoring();
  16614. var beforeRenderTargetDate = BABYLON.Tools.Now;
  16615. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  16616. this._intermediateRendering = true;
  16617. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  16618. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  16619. var renderTarget = this._renderTargets.data[renderIndex];
  16620. if (renderTarget._shouldRender()) {
  16621. this._renderId++;
  16622. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  16623. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  16624. }
  16625. }
  16626. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  16627. this._intermediateRendering = false;
  16628. this._renderId++;
  16629. engine.restoreDefaultFramebuffer(); // Restore back buffer
  16630. }
  16631. this._renderTargetsDuration.endMonitoring(false);
  16632. // Prepare Frame
  16633. this.postProcessManager._prepareFrame();
  16634. this._renderDuration.beginMonitoring();
  16635. // Backgrounds
  16636. var layerIndex;
  16637. var layer;
  16638. if (this.layers.length) {
  16639. engine.setDepthBuffer(false);
  16640. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  16641. layer = this.layers[layerIndex];
  16642. if (layer.isBackground) {
  16643. layer.render();
  16644. }
  16645. }
  16646. engine.setDepthBuffer(true);
  16647. }
  16648. // Render
  16649. BABYLON.Tools.StartPerformanceCounter("Main render");
  16650. this._renderingManager.render(null, null, true, true);
  16651. BABYLON.Tools.EndPerformanceCounter("Main render");
  16652. // Bounding boxes
  16653. this._boundingBoxRenderer.render();
  16654. // Edges
  16655. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  16656. this._edgesRenderers.data[edgesRendererIndex].render();
  16657. }
  16658. // Lens flares
  16659. if (this.lensFlaresEnabled) {
  16660. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  16661. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  16662. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  16663. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  16664. lensFlareSystem.render();
  16665. }
  16666. }
  16667. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  16668. }
  16669. // Foregrounds
  16670. if (this.layers.length) {
  16671. engine.setDepthBuffer(false);
  16672. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  16673. layer = this.layers[layerIndex];
  16674. if (!layer.isBackground) {
  16675. layer.render();
  16676. }
  16677. }
  16678. engine.setDepthBuffer(true);
  16679. }
  16680. this._renderDuration.endMonitoring(false);
  16681. // Finalize frame
  16682. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  16683. // Update camera
  16684. this.activeCamera._updateFromScene();
  16685. // Reset some special arrays
  16686. this._renderTargets.reset();
  16687. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  16688. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  16689. };
  16690. Scene.prototype._processSubCameras = function (camera) {
  16691. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  16692. this._renderForCamera(camera);
  16693. return;
  16694. }
  16695. // rig cameras
  16696. for (var index = 0; index < camera._rigCameras.length; index++) {
  16697. this._renderForCamera(camera._rigCameras[index]);
  16698. }
  16699. this.activeCamera = camera;
  16700. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  16701. // Update camera
  16702. this.activeCamera._updateFromScene();
  16703. };
  16704. Scene.prototype._checkIntersections = function () {
  16705. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  16706. var sourceMesh = this._meshesForIntersections.data[index];
  16707. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  16708. var action = sourceMesh.actionManager.actions[actionIndex];
  16709. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  16710. var parameters = action.getTriggerParameter();
  16711. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  16712. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  16713. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  16714. if (areIntersecting && currentIntersectionInProgress === -1) {
  16715. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  16716. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  16717. sourceMesh._intersectionsInProgress.push(otherMesh);
  16718. }
  16719. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  16720. sourceMesh._intersectionsInProgress.push(otherMesh);
  16721. }
  16722. }
  16723. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  16724. //They intersected, and now they don't.
  16725. //is this trigger an exit trigger? execute an event.
  16726. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  16727. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  16728. }
  16729. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  16730. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  16731. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  16732. }
  16733. }
  16734. }
  16735. }
  16736. }
  16737. };
  16738. Scene.prototype.render = function () {
  16739. this._lastFrameDuration.beginMonitoring();
  16740. this._particlesDuration.fetchNewFrame();
  16741. this._spritesDuration.fetchNewFrame();
  16742. this._activeParticles.fetchNewFrame();
  16743. this._renderDuration.fetchNewFrame();
  16744. this._renderTargetsDuration.fetchNewFrame();
  16745. this._evaluateActiveMeshesDuration.fetchNewFrame();
  16746. this._totalVertices.fetchNewFrame();
  16747. this._activeIndices.fetchNewFrame();
  16748. this._activeBones.fetchNewFrame();
  16749. this.getEngine().drawCallsPerfCounter.fetchNewFrame();
  16750. this._meshesForIntersections.reset();
  16751. this.resetCachedMaterial();
  16752. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  16753. // Actions
  16754. if (this.actionManager) {
  16755. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  16756. }
  16757. //Simplification Queue
  16758. if (this.simplificationQueue && !this.simplificationQueue.running) {
  16759. this.simplificationQueue.executeNext();
  16760. }
  16761. // Animations
  16762. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  16763. this._animationRatio = deltaTime * (60.0 / 1000.0);
  16764. this._animate();
  16765. // Physics
  16766. if (this._physicsEngine) {
  16767. BABYLON.Tools.StartPerformanceCounter("Physics");
  16768. this._physicsEngine._step(deltaTime / 1000.0);
  16769. BABYLON.Tools.EndPerformanceCounter("Physics");
  16770. }
  16771. // Before render
  16772. this.onBeforeRenderObservable.notifyObservers(this);
  16773. // Customs render targets
  16774. this._renderTargetsDuration.beginMonitoring();
  16775. var beforeRenderTargetDate = BABYLON.Tools.Now;
  16776. var engine = this.getEngine();
  16777. var currentActiveCamera = this.activeCamera;
  16778. if (this.renderTargetsEnabled) {
  16779. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  16780. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  16781. var renderTarget = this.customRenderTargets[customIndex];
  16782. if (renderTarget._shouldRender()) {
  16783. this._renderId++;
  16784. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  16785. if (!this.activeCamera)
  16786. throw new Error("Active camera not set");
  16787. // Viewport
  16788. engine.setViewport(this.activeCamera.viewport);
  16789. // Camera
  16790. this.updateTransformMatrix();
  16791. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  16792. }
  16793. }
  16794. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  16795. this._renderId++;
  16796. }
  16797. if (this.customRenderTargets.length > 0) {
  16798. engine.restoreDefaultFramebuffer();
  16799. }
  16800. this._renderTargetsDuration.endMonitoring();
  16801. this.activeCamera = currentActiveCamera;
  16802. // Procedural textures
  16803. if (this.proceduralTexturesEnabled) {
  16804. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  16805. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  16806. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  16807. if (proceduralTexture._shouldRender()) {
  16808. proceduralTexture.render();
  16809. }
  16810. }
  16811. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  16812. }
  16813. // Clear
  16814. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true);
  16815. // Shadows
  16816. if (this.shadowsEnabled) {
  16817. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  16818. var light = this.lights[lightIndex];
  16819. var shadowGenerator = light.getShadowGenerator();
  16820. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  16821. this._renderTargets.push(shadowGenerator.getShadowMap());
  16822. }
  16823. }
  16824. }
  16825. // Depth renderer
  16826. if (this._depthRenderer) {
  16827. this._renderTargets.push(this._depthRenderer.getDepthMap());
  16828. }
  16829. // RenderPipeline
  16830. this.postProcessRenderPipelineManager.update();
  16831. // Multi-cameras?
  16832. if (this.activeCameras.length > 0) {
  16833. var currentRenderId = this._renderId;
  16834. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  16835. this._renderId = currentRenderId;
  16836. if (cameraIndex > 0) {
  16837. this._engine.clear(0, false, true);
  16838. }
  16839. this._processSubCameras(this.activeCameras[cameraIndex]);
  16840. }
  16841. }
  16842. else {
  16843. if (!this.activeCamera) {
  16844. throw new Error("No camera defined");
  16845. }
  16846. this._processSubCameras(this.activeCamera);
  16847. }
  16848. // Intersection checks
  16849. this._checkIntersections();
  16850. // Update the audio listener attached to the camera
  16851. if (BABYLON.AudioEngine) {
  16852. this._updateAudioParameters();
  16853. }
  16854. // After render
  16855. if (this.afterRender) {
  16856. this.afterRender();
  16857. }
  16858. this.onAfterRenderObservable.notifyObservers(this);
  16859. // Cleaning
  16860. for (var index = 0; index < this._toBeDisposed.length; index++) {
  16861. this._toBeDisposed.data[index].dispose();
  16862. this._toBeDisposed[index] = null;
  16863. }
  16864. this._toBeDisposed.reset();
  16865. if (this.dumpNextRenderTargets) {
  16866. this.dumpNextRenderTargets = false;
  16867. }
  16868. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  16869. this._lastFrameDuration.endMonitoring();
  16870. this._totalMeshesCounter.addCount(this.meshes.length, true);
  16871. this._totalLightsCounter.addCount(this.lights.length, true);
  16872. this._totalMaterialsCounter.addCount(this.materials.length, true);
  16873. this._totalTexturesCounter.addCount(this.textures.length, true);
  16874. this._activeBones.addCount(0, true);
  16875. this._activeIndices.addCount(0, true);
  16876. this._activeParticles.addCount(0, true);
  16877. };
  16878. Scene.prototype._updateAudioParameters = function () {
  16879. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  16880. return;
  16881. }
  16882. var listeningCamera;
  16883. var audioEngine = BABYLON.Engine.audioEngine;
  16884. if (this.activeCameras.length > 0) {
  16885. listeningCamera = this.activeCameras[0];
  16886. }
  16887. else {
  16888. listeningCamera = this.activeCamera;
  16889. }
  16890. if (listeningCamera && audioEngine.canUseWebAudio) {
  16891. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  16892. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  16893. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  16894. cameraDirection.normalize();
  16895. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  16896. var i;
  16897. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  16898. var sound = this.mainSoundTrack.soundCollection[i];
  16899. if (sound.useCustomAttenuation) {
  16900. sound.updateDistanceFromListener();
  16901. }
  16902. }
  16903. for (i = 0; i < this.soundTracks.length; i++) {
  16904. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  16905. sound = this.soundTracks[i].soundCollection[j];
  16906. if (sound.useCustomAttenuation) {
  16907. sound.updateDistanceFromListener();
  16908. }
  16909. }
  16910. }
  16911. }
  16912. };
  16913. Object.defineProperty(Scene.prototype, "audioEnabled", {
  16914. // Audio
  16915. get: function () {
  16916. return this._audioEnabled;
  16917. },
  16918. set: function (value) {
  16919. this._audioEnabled = value;
  16920. if (BABYLON.AudioEngine) {
  16921. if (this._audioEnabled) {
  16922. this._enableAudio();
  16923. }
  16924. else {
  16925. this._disableAudio();
  16926. }
  16927. }
  16928. },
  16929. enumerable: true,
  16930. configurable: true
  16931. });
  16932. Scene.prototype._disableAudio = function () {
  16933. var i;
  16934. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  16935. this.mainSoundTrack.soundCollection[i].pause();
  16936. }
  16937. for (i = 0; i < this.soundTracks.length; i++) {
  16938. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  16939. this.soundTracks[i].soundCollection[j].pause();
  16940. }
  16941. }
  16942. };
  16943. Scene.prototype._enableAudio = function () {
  16944. var i;
  16945. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  16946. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  16947. this.mainSoundTrack.soundCollection[i].play();
  16948. }
  16949. }
  16950. for (i = 0; i < this.soundTracks.length; i++) {
  16951. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  16952. if (this.soundTracks[i].soundCollection[j].isPaused) {
  16953. this.soundTracks[i].soundCollection[j].play();
  16954. }
  16955. }
  16956. }
  16957. };
  16958. Object.defineProperty(Scene.prototype, "headphone", {
  16959. get: function () {
  16960. return this._headphone;
  16961. },
  16962. set: function (value) {
  16963. this._headphone = value;
  16964. if (BABYLON.AudioEngine) {
  16965. if (this._headphone) {
  16966. this._switchAudioModeForHeadphones();
  16967. }
  16968. else {
  16969. this._switchAudioModeForNormalSpeakers();
  16970. }
  16971. }
  16972. },
  16973. enumerable: true,
  16974. configurable: true
  16975. });
  16976. Scene.prototype._switchAudioModeForHeadphones = function () {
  16977. this.mainSoundTrack.switchPanningModelToHRTF();
  16978. for (var i = 0; i < this.soundTracks.length; i++) {
  16979. this.soundTracks[i].switchPanningModelToHRTF();
  16980. }
  16981. };
  16982. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  16983. this.mainSoundTrack.switchPanningModelToEqualPower();
  16984. for (var i = 0; i < this.soundTracks.length; i++) {
  16985. this.soundTracks[i].switchPanningModelToEqualPower();
  16986. }
  16987. };
  16988. Scene.prototype.enableDepthRenderer = function () {
  16989. if (this._depthRenderer) {
  16990. return this._depthRenderer;
  16991. }
  16992. this._depthRenderer = new BABYLON.DepthRenderer(this);
  16993. return this._depthRenderer;
  16994. };
  16995. Scene.prototype.disableDepthRenderer = function () {
  16996. if (!this._depthRenderer) {
  16997. return;
  16998. }
  16999. this._depthRenderer.dispose();
  17000. this._depthRenderer = null;
  17001. };
  17002. Scene.prototype.freezeMaterials = function () {
  17003. for (var i = 0; i < this.materials.length; i++) {
  17004. this.materials[i].freeze();
  17005. }
  17006. };
  17007. Scene.prototype.unfreezeMaterials = function () {
  17008. for (var i = 0; i < this.materials.length; i++) {
  17009. this.materials[i].unfreeze();
  17010. }
  17011. };
  17012. Scene.prototype.dispose = function () {
  17013. this.beforeRender = null;
  17014. this.afterRender = null;
  17015. this.skeletons = [];
  17016. this._boundingBoxRenderer.dispose();
  17017. if (this._depthRenderer) {
  17018. this._depthRenderer.dispose();
  17019. }
  17020. // Debug layer
  17021. if (this._debugLayer) {
  17022. this._debugLayer.hide();
  17023. }
  17024. // Events
  17025. this.onDisposeObservable.notifyObservers(this);
  17026. this.onDisposeObservable.clear();
  17027. this.onBeforeRenderObservable.clear();
  17028. this.onAfterRenderObservable.clear();
  17029. this.detachControl();
  17030. // Release sounds & sounds tracks
  17031. if (BABYLON.AudioEngine) {
  17032. this.disposeSounds();
  17033. }
  17034. // Detach cameras
  17035. var canvas = this._engine.getRenderingCanvas();
  17036. var index;
  17037. for (index = 0; index < this.cameras.length; index++) {
  17038. this.cameras[index].detachControl(canvas);
  17039. }
  17040. // Release lights
  17041. while (this.lights.length) {
  17042. this.lights[0].dispose();
  17043. }
  17044. // Release meshes
  17045. while (this.meshes.length) {
  17046. this.meshes[0].dispose(true);
  17047. }
  17048. // Release cameras
  17049. while (this.cameras.length) {
  17050. this.cameras[0].dispose();
  17051. }
  17052. // Release materials
  17053. while (this.materials.length) {
  17054. this.materials[0].dispose();
  17055. }
  17056. // Release particles
  17057. while (this.particleSystems.length) {
  17058. this.particleSystems[0].dispose();
  17059. }
  17060. // Release sprites
  17061. while (this.spriteManagers.length) {
  17062. this.spriteManagers[0].dispose();
  17063. }
  17064. // Release layers
  17065. while (this.layers.length) {
  17066. this.layers[0].dispose();
  17067. }
  17068. // Release textures
  17069. while (this.textures.length) {
  17070. this.textures[0].dispose();
  17071. }
  17072. // Post-processes
  17073. this.postProcessManager.dispose();
  17074. // Physics
  17075. if (this._physicsEngine) {
  17076. this.disablePhysicsEngine();
  17077. }
  17078. // Remove from engine
  17079. index = this._engine.scenes.indexOf(this);
  17080. if (index > -1) {
  17081. this._engine.scenes.splice(index, 1);
  17082. }
  17083. this._engine.wipeCaches();
  17084. };
  17085. // Release sounds & sounds tracks
  17086. Scene.prototype.disposeSounds = function () {
  17087. this.mainSoundTrack.dispose();
  17088. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  17089. this.soundTracks[scIndex].dispose();
  17090. }
  17091. };
  17092. // Octrees
  17093. Scene.prototype.getWorldExtends = function () {
  17094. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  17095. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  17096. for (var index = 0; index < this.meshes.length; index++) {
  17097. var mesh = this.meshes[index];
  17098. mesh.computeWorldMatrix(true);
  17099. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  17100. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  17101. BABYLON.Tools.CheckExtends(minBox, min, max);
  17102. BABYLON.Tools.CheckExtends(maxBox, min, max);
  17103. }
  17104. return {
  17105. min: min,
  17106. max: max
  17107. };
  17108. };
  17109. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  17110. if (maxCapacity === void 0) { maxCapacity = 64; }
  17111. if (maxDepth === void 0) { maxDepth = 2; }
  17112. if (!this._selectionOctree) {
  17113. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  17114. }
  17115. var worldExtends = this.getWorldExtends();
  17116. // Update octree
  17117. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  17118. return this._selectionOctree;
  17119. };
  17120. // Picking
  17121. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  17122. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  17123. var engine = this._engine;
  17124. if (!camera) {
  17125. if (!this.activeCamera)
  17126. throw new Error("Active camera not set");
  17127. camera = this.activeCamera;
  17128. }
  17129. var cameraViewport = camera.viewport;
  17130. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  17131. // Moving coordinates to local viewport world
  17132. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  17133. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  17134. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  17135. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  17136. };
  17137. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  17138. var engine = this._engine;
  17139. if (!camera) {
  17140. if (!this.activeCamera)
  17141. throw new Error("Active camera not set");
  17142. camera = this.activeCamera;
  17143. }
  17144. var cameraViewport = camera.viewport;
  17145. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  17146. var identity = BABYLON.Matrix.Identity();
  17147. // Moving coordinates to local viewport world
  17148. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  17149. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  17150. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  17151. };
  17152. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  17153. var pickingInfo = null;
  17154. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  17155. var mesh = this.meshes[meshIndex];
  17156. if (predicate) {
  17157. if (!predicate(mesh)) {
  17158. continue;
  17159. }
  17160. }
  17161. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  17162. continue;
  17163. }
  17164. var world = mesh.getWorldMatrix();
  17165. var ray = rayFunction(world);
  17166. var result = mesh.intersects(ray, fastCheck);
  17167. if (!result || !result.hit)
  17168. continue;
  17169. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  17170. continue;
  17171. pickingInfo = result;
  17172. if (fastCheck) {
  17173. break;
  17174. }
  17175. }
  17176. return pickingInfo || new BABYLON.PickingInfo();
  17177. };
  17178. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  17179. var pickingInfo = null;
  17180. camera = camera || this.activeCamera;
  17181. if (this.spriteManagers.length > 0) {
  17182. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  17183. var spriteManager = this.spriteManagers[spriteIndex];
  17184. if (!spriteManager.isPickable) {
  17185. continue;
  17186. }
  17187. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  17188. if (!result || !result.hit)
  17189. continue;
  17190. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  17191. continue;
  17192. pickingInfo = result;
  17193. if (fastCheck) {
  17194. break;
  17195. }
  17196. }
  17197. }
  17198. return pickingInfo || new BABYLON.PickingInfo();
  17199. };
  17200. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  17201. var _this = this;
  17202. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  17203. /// <param name="x">X position on screen</param>
  17204. /// <param name="y">Y position on screen</param>
  17205. /// <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>
  17206. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  17207. /// <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>
  17208. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  17209. };
  17210. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  17211. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  17212. /// <param name="x">X position on screen</param>
  17213. /// <param name="y">Y position on screen</param>
  17214. /// <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>
  17215. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  17216. /// <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>
  17217. return this._internalPickSprites(this.createPickingRayInCameraSpace(x, y, camera), predicate, fastCheck, camera);
  17218. };
  17219. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  17220. var _this = this;
  17221. return this._internalPick(function (world) {
  17222. if (!_this._pickWithRayInverseMatrix) {
  17223. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  17224. }
  17225. world.invertToRef(_this._pickWithRayInverseMatrix);
  17226. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  17227. }, predicate, fastCheck);
  17228. };
  17229. Scene.prototype.setPointerOverMesh = function (mesh) {
  17230. if (this._pointerOverMesh === mesh) {
  17231. return;
  17232. }
  17233. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  17234. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  17235. }
  17236. this._pointerOverMesh = mesh;
  17237. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  17238. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  17239. }
  17240. };
  17241. Scene.prototype.getPointerOverMesh = function () {
  17242. return this._pointerOverMesh;
  17243. };
  17244. Scene.prototype.setPointerOverSprite = function (sprite) {
  17245. if (this._pointerOverSprite === sprite) {
  17246. return;
  17247. }
  17248. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  17249. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  17250. }
  17251. this._pointerOverSprite = sprite;
  17252. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  17253. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  17254. }
  17255. };
  17256. Scene.prototype.getPointerOverSprite = function () {
  17257. return this._pointerOverSprite;
  17258. };
  17259. // Physics
  17260. Scene.prototype.getPhysicsEngine = function () {
  17261. return this._physicsEngine;
  17262. };
  17263. /**
  17264. * Enables physics to the current scene
  17265. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  17266. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  17267. * @return {boolean} was the physics engine initialized
  17268. */
  17269. Scene.prototype.enablePhysics = function (gravity, plugin) {
  17270. if (this._physicsEngine) {
  17271. return true;
  17272. }
  17273. try {
  17274. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  17275. return true;
  17276. }
  17277. catch (e) {
  17278. BABYLON.Tools.Error(e.message);
  17279. return false;
  17280. }
  17281. };
  17282. Scene.prototype.disablePhysicsEngine = function () {
  17283. if (!this._physicsEngine) {
  17284. return;
  17285. }
  17286. this._physicsEngine.dispose();
  17287. this._physicsEngine = undefined;
  17288. };
  17289. Scene.prototype.isPhysicsEnabled = function () {
  17290. return this._physicsEngine !== undefined;
  17291. };
  17292. /**
  17293. *
  17294. * Sets the gravity of the physics engine (and NOT of the scene)
  17295. * @param {BABYLON.Vector3} [gravity] - the new gravity to be used
  17296. */
  17297. Scene.prototype.setGravity = function (gravity) {
  17298. BABYLON.Tools.Warn("Deprecated, please use 'scene.getPhysicsEngine().setGravity()'");
  17299. if (!this._physicsEngine) {
  17300. return;
  17301. }
  17302. this._physicsEngine.setGravity(gravity);
  17303. };
  17304. /**
  17305. * Legacy support, using the new API
  17306. * @Deprecated
  17307. */
  17308. Scene.prototype.createCompoundImpostor = function (parts, options) {
  17309. BABYLON.Tools.Warn("Scene.createCompoundImpostor is deprecated. Please use PhysicsImpostor parent/child");
  17310. if (parts.parts) {
  17311. options = parts;
  17312. parts = parts.parts;
  17313. }
  17314. var mainMesh = parts[0].mesh;
  17315. mainMesh.physicsImpostor = new BABYLON.PhysicsImpostor(mainMesh, parts[0].impostor, options, this);
  17316. for (var index = 1; index < parts.length; index++) {
  17317. var mesh = parts[index].mesh;
  17318. if (mesh.parent !== mainMesh) {
  17319. mesh.position = mesh.position.subtract(mainMesh.position);
  17320. mesh.parent = mainMesh;
  17321. }
  17322. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parts[index].impostor, options, this);
  17323. }
  17324. mainMesh.physicsImpostor.forceUpdate();
  17325. };
  17326. Scene.prototype.deleteCompoundImpostor = function (compound) {
  17327. var mesh = compound.parts[0].mesh;
  17328. mesh.physicsImpostor.dispose();
  17329. mesh.physicsImpostor = null;
  17330. };
  17331. // Misc.
  17332. Scene.prototype.createDefaultCameraOrLight = function () {
  17333. // Light
  17334. if (this.lights.length === 0) {
  17335. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  17336. }
  17337. // Camera
  17338. if (!this.activeCamera) {
  17339. var camera = new BABYLON.FreeCamera("default camera", BABYLON.Vector3.Zero(), this);
  17340. // Compute position
  17341. var worldExtends = this.getWorldExtends();
  17342. var worldCenter = worldExtends.min.add(worldExtends.max.subtract(worldExtends.min).scale(0.5));
  17343. camera.position = new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z));
  17344. camera.setTarget(worldCenter);
  17345. this.activeCamera = camera;
  17346. }
  17347. };
  17348. // Tags
  17349. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  17350. if (tagsQuery === undefined) {
  17351. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  17352. return list;
  17353. }
  17354. var listByTags = [];
  17355. forEach = forEach || (function (item) { return; });
  17356. for (var i in list) {
  17357. var item = list[i];
  17358. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  17359. listByTags.push(item);
  17360. forEach(item);
  17361. }
  17362. }
  17363. return listByTags;
  17364. };
  17365. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  17366. return this._getByTags(this.meshes, tagsQuery, forEach);
  17367. };
  17368. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  17369. return this._getByTags(this.cameras, tagsQuery, forEach);
  17370. };
  17371. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  17372. return this._getByTags(this.lights, tagsQuery, forEach);
  17373. };
  17374. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  17375. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  17376. };
  17377. // Statics
  17378. Scene._FOGMODE_NONE = 0;
  17379. Scene._FOGMODE_EXP = 1;
  17380. Scene._FOGMODE_EXP2 = 2;
  17381. Scene._FOGMODE_LINEAR = 3;
  17382. Scene.MinDeltaTime = 1.0;
  17383. Scene.MaxDeltaTime = 1000.0;
  17384. return Scene;
  17385. }());
  17386. BABYLON.Scene = Scene;
  17387. })(BABYLON || (BABYLON = {}));
  17388. var BABYLON;
  17389. (function (BABYLON) {
  17390. var Buffer = (function () {
  17391. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  17392. if (engine instanceof BABYLON.Mesh) {
  17393. this._engine = engine.getScene().getEngine();
  17394. }
  17395. else {
  17396. this._engine = engine;
  17397. }
  17398. this._updatable = updatable;
  17399. this._data = data;
  17400. this._strideSize = stride;
  17401. if (!postponeInternalCreation) {
  17402. this.create();
  17403. }
  17404. this._instanced = instanced;
  17405. }
  17406. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride) {
  17407. // a lot of these parameters are ignored as they are overriden by the buffer
  17408. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, this._instanced, offset, size);
  17409. };
  17410. // Properties
  17411. Buffer.prototype.isUpdatable = function () {
  17412. return this._updatable;
  17413. };
  17414. Buffer.prototype.getData = function () {
  17415. return this._data;
  17416. };
  17417. Buffer.prototype.getBuffer = function () {
  17418. return this._buffer;
  17419. };
  17420. Buffer.prototype.getStrideSize = function () {
  17421. return this._strideSize;
  17422. };
  17423. Buffer.prototype.getIsInstanced = function () {
  17424. return this._instanced;
  17425. };
  17426. // Methods
  17427. Buffer.prototype.create = function (data) {
  17428. if (!data && this._buffer) {
  17429. return; // nothing to do
  17430. }
  17431. data = data || this._data;
  17432. if (!this._buffer) {
  17433. if (this._updatable) {
  17434. this._buffer = this._engine.createDynamicVertexBuffer(data);
  17435. this._data = data;
  17436. }
  17437. else {
  17438. this._buffer = this._engine.createVertexBuffer(data);
  17439. }
  17440. }
  17441. else if (this._updatable) {
  17442. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  17443. this._data = data;
  17444. }
  17445. };
  17446. Buffer.prototype.update = function (data) {
  17447. this.create(data);
  17448. };
  17449. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  17450. if (!this._buffer) {
  17451. return;
  17452. }
  17453. if (this._updatable) {
  17454. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  17455. this._data = null;
  17456. }
  17457. };
  17458. Buffer.prototype.dispose = function () {
  17459. if (!this._buffer) {
  17460. return;
  17461. }
  17462. if (this._engine._releaseBuffer(this._buffer)) {
  17463. this._buffer = null;
  17464. }
  17465. };
  17466. return Buffer;
  17467. }());
  17468. BABYLON.Buffer = Buffer;
  17469. })(BABYLON || (BABYLON = {}));
  17470. var BABYLON;
  17471. (function (BABYLON) {
  17472. var VertexBuffer = (function () {
  17473. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  17474. if (!stride) {
  17475. // Deduce stride from kind
  17476. switch (kind) {
  17477. case VertexBuffer.PositionKind:
  17478. stride = 3;
  17479. break;
  17480. case VertexBuffer.NormalKind:
  17481. stride = 3;
  17482. break;
  17483. case VertexBuffer.UVKind:
  17484. case VertexBuffer.UV2Kind:
  17485. case VertexBuffer.UV3Kind:
  17486. case VertexBuffer.UV4Kind:
  17487. case VertexBuffer.UV5Kind:
  17488. case VertexBuffer.UV6Kind:
  17489. stride = 2;
  17490. break;
  17491. case VertexBuffer.ColorKind:
  17492. stride = 4;
  17493. break;
  17494. case VertexBuffer.MatricesIndicesKind:
  17495. case VertexBuffer.MatricesIndicesExtraKind:
  17496. stride = 4;
  17497. break;
  17498. case VertexBuffer.MatricesWeightsKind:
  17499. case VertexBuffer.MatricesWeightsExtraKind:
  17500. stride = 4;
  17501. break;
  17502. }
  17503. }
  17504. if (data instanceof BABYLON.Buffer) {
  17505. if (!stride) {
  17506. stride = data.getStrideSize();
  17507. }
  17508. this._buffer = data;
  17509. this._ownsBuffer = false;
  17510. }
  17511. else {
  17512. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  17513. this._ownsBuffer = true;
  17514. }
  17515. this._stride = stride;
  17516. this._offset = offset ? offset : 0;
  17517. this._size = size ? size : stride;
  17518. this._kind = kind;
  17519. }
  17520. VertexBuffer.prototype.getKind = function () {
  17521. return this._kind;
  17522. };
  17523. // Properties
  17524. VertexBuffer.prototype.isUpdatable = function () {
  17525. return this._buffer.isUpdatable();
  17526. };
  17527. VertexBuffer.prototype.getData = function () {
  17528. return this._buffer.getData();
  17529. };
  17530. VertexBuffer.prototype.getBuffer = function () {
  17531. return this._buffer.getBuffer();
  17532. };
  17533. VertexBuffer.prototype.getStrideSize = function () {
  17534. return this._stride;
  17535. };
  17536. VertexBuffer.prototype.getOffset = function () {
  17537. return this._offset;
  17538. };
  17539. VertexBuffer.prototype.getSize = function () {
  17540. return this._size;
  17541. };
  17542. VertexBuffer.prototype.getIsInstanced = function () {
  17543. return this._buffer.getIsInstanced();
  17544. };
  17545. // Methods
  17546. VertexBuffer.prototype.create = function (data) {
  17547. return this._buffer.create(data);
  17548. };
  17549. VertexBuffer.prototype.update = function (data) {
  17550. return this._buffer.update(data);
  17551. };
  17552. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  17553. return this._buffer.updateDirectly(data, offset);
  17554. };
  17555. VertexBuffer.prototype.dispose = function () {
  17556. if (this._ownsBuffer) {
  17557. this._buffer.dispose();
  17558. }
  17559. };
  17560. Object.defineProperty(VertexBuffer, "PositionKind", {
  17561. get: function () {
  17562. return VertexBuffer._PositionKind;
  17563. },
  17564. enumerable: true,
  17565. configurable: true
  17566. });
  17567. Object.defineProperty(VertexBuffer, "NormalKind", {
  17568. get: function () {
  17569. return VertexBuffer._NormalKind;
  17570. },
  17571. enumerable: true,
  17572. configurable: true
  17573. });
  17574. Object.defineProperty(VertexBuffer, "UVKind", {
  17575. get: function () {
  17576. return VertexBuffer._UVKind;
  17577. },
  17578. enumerable: true,
  17579. configurable: true
  17580. });
  17581. Object.defineProperty(VertexBuffer, "UV2Kind", {
  17582. get: function () {
  17583. return VertexBuffer._UV2Kind;
  17584. },
  17585. enumerable: true,
  17586. configurable: true
  17587. });
  17588. Object.defineProperty(VertexBuffer, "UV3Kind", {
  17589. get: function () {
  17590. return VertexBuffer._UV3Kind;
  17591. },
  17592. enumerable: true,
  17593. configurable: true
  17594. });
  17595. Object.defineProperty(VertexBuffer, "UV4Kind", {
  17596. get: function () {
  17597. return VertexBuffer._UV4Kind;
  17598. },
  17599. enumerable: true,
  17600. configurable: true
  17601. });
  17602. Object.defineProperty(VertexBuffer, "UV5Kind", {
  17603. get: function () {
  17604. return VertexBuffer._UV5Kind;
  17605. },
  17606. enumerable: true,
  17607. configurable: true
  17608. });
  17609. Object.defineProperty(VertexBuffer, "UV6Kind", {
  17610. get: function () {
  17611. return VertexBuffer._UV6Kind;
  17612. },
  17613. enumerable: true,
  17614. configurable: true
  17615. });
  17616. Object.defineProperty(VertexBuffer, "ColorKind", {
  17617. get: function () {
  17618. return VertexBuffer._ColorKind;
  17619. },
  17620. enumerable: true,
  17621. configurable: true
  17622. });
  17623. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  17624. get: function () {
  17625. return VertexBuffer._MatricesIndicesKind;
  17626. },
  17627. enumerable: true,
  17628. configurable: true
  17629. });
  17630. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  17631. get: function () {
  17632. return VertexBuffer._MatricesWeightsKind;
  17633. },
  17634. enumerable: true,
  17635. configurable: true
  17636. });
  17637. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  17638. get: function () {
  17639. return VertexBuffer._MatricesIndicesExtraKind;
  17640. },
  17641. enumerable: true,
  17642. configurable: true
  17643. });
  17644. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  17645. get: function () {
  17646. return VertexBuffer._MatricesWeightsExtraKind;
  17647. },
  17648. enumerable: true,
  17649. configurable: true
  17650. });
  17651. // Enums
  17652. VertexBuffer._PositionKind = "position";
  17653. VertexBuffer._NormalKind = "normal";
  17654. VertexBuffer._UVKind = "uv";
  17655. VertexBuffer._UV2Kind = "uv2";
  17656. VertexBuffer._UV3Kind = "uv3";
  17657. VertexBuffer._UV4Kind = "uv4";
  17658. VertexBuffer._UV5Kind = "uv5";
  17659. VertexBuffer._UV6Kind = "uv6";
  17660. VertexBuffer._ColorKind = "color";
  17661. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  17662. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  17663. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  17664. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  17665. return VertexBuffer;
  17666. }());
  17667. BABYLON.VertexBuffer = VertexBuffer;
  17668. })(BABYLON || (BABYLON = {}));
  17669. var BABYLON;
  17670. (function (BABYLON) {
  17671. /**
  17672. * Creates an instance based on a source mesh.
  17673. */
  17674. var InstancedMesh = (function (_super) {
  17675. __extends(InstancedMesh, _super);
  17676. function InstancedMesh(name, source) {
  17677. _super.call(this, name, source.getScene());
  17678. source.instances.push(this);
  17679. this._sourceMesh = source;
  17680. this.position.copyFrom(source.position);
  17681. this.rotation.copyFrom(source.rotation);
  17682. this.scaling.copyFrom(source.scaling);
  17683. if (source.rotationQuaternion) {
  17684. this.rotationQuaternion = source.rotationQuaternion.clone();
  17685. }
  17686. this.infiniteDistance = source.infiniteDistance;
  17687. this.setPivotMatrix(source.getPivotMatrix());
  17688. this.refreshBoundingInfo();
  17689. this._syncSubMeshes();
  17690. }
  17691. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  17692. // Methods
  17693. get: function () {
  17694. return this._sourceMesh.receiveShadows;
  17695. },
  17696. enumerable: true,
  17697. configurable: true
  17698. });
  17699. Object.defineProperty(InstancedMesh.prototype, "material", {
  17700. get: function () {
  17701. return this._sourceMesh.material;
  17702. },
  17703. enumerable: true,
  17704. configurable: true
  17705. });
  17706. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  17707. get: function () {
  17708. return this._sourceMesh.visibility;
  17709. },
  17710. enumerable: true,
  17711. configurable: true
  17712. });
  17713. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  17714. get: function () {
  17715. return this._sourceMesh.skeleton;
  17716. },
  17717. enumerable: true,
  17718. configurable: true
  17719. });
  17720. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  17721. get: function () {
  17722. return this._sourceMesh.renderingGroupId;
  17723. },
  17724. enumerable: true,
  17725. configurable: true
  17726. });
  17727. InstancedMesh.prototype.getTotalVertices = function () {
  17728. return this._sourceMesh.getTotalVertices();
  17729. };
  17730. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  17731. get: function () {
  17732. return this._sourceMesh;
  17733. },
  17734. enumerable: true,
  17735. configurable: true
  17736. });
  17737. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  17738. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  17739. };
  17740. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  17741. return this._sourceMesh.isVerticesDataPresent(kind);
  17742. };
  17743. InstancedMesh.prototype.getIndices = function () {
  17744. return this._sourceMesh.getIndices();
  17745. };
  17746. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  17747. get: function () {
  17748. return this._sourceMesh._positions;
  17749. },
  17750. enumerable: true,
  17751. configurable: true
  17752. });
  17753. InstancedMesh.prototype.refreshBoundingInfo = function () {
  17754. var meshBB = this._sourceMesh.getBoundingInfo();
  17755. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  17756. this._updateBoundingInfo();
  17757. };
  17758. InstancedMesh.prototype._preActivate = function () {
  17759. if (this._currentLOD) {
  17760. this._currentLOD._preActivate();
  17761. }
  17762. };
  17763. InstancedMesh.prototype._activate = function (renderId) {
  17764. if (this._currentLOD) {
  17765. this._currentLOD._registerInstanceForRenderId(this, renderId);
  17766. }
  17767. };
  17768. InstancedMesh.prototype.getLOD = function (camera) {
  17769. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  17770. if (this._currentLOD === this.sourceMesh) {
  17771. return this;
  17772. }
  17773. return this._currentLOD;
  17774. };
  17775. InstancedMesh.prototype._syncSubMeshes = function () {
  17776. this.releaseSubMeshes();
  17777. if (this._sourceMesh.subMeshes) {
  17778. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  17779. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  17780. }
  17781. }
  17782. };
  17783. InstancedMesh.prototype._generatePointsArray = function () {
  17784. return this._sourceMesh._generatePointsArray();
  17785. };
  17786. // Clone
  17787. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  17788. var result = this._sourceMesh.createInstance(name);
  17789. // Deep copy
  17790. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes"], []);
  17791. // Bounding info
  17792. this.refreshBoundingInfo();
  17793. // Parent
  17794. if (newParent) {
  17795. result.parent = newParent;
  17796. }
  17797. if (!doNotCloneChildren) {
  17798. // Children
  17799. for (var index = 0; index < this.getScene().meshes.length; index++) {
  17800. var mesh = this.getScene().meshes[index];
  17801. if (mesh.parent === this) {
  17802. mesh.clone(mesh.name, result);
  17803. }
  17804. }
  17805. }
  17806. result.computeWorldMatrix(true);
  17807. return result;
  17808. };
  17809. // Dispoe
  17810. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  17811. // Remove from mesh
  17812. var index = this._sourceMesh.instances.indexOf(this);
  17813. this._sourceMesh.instances.splice(index, 1);
  17814. _super.prototype.dispose.call(this, doNotRecurse);
  17815. };
  17816. return InstancedMesh;
  17817. }(BABYLON.AbstractMesh));
  17818. BABYLON.InstancedMesh = InstancedMesh;
  17819. })(BABYLON || (BABYLON = {}));
  17820. var BABYLON;
  17821. (function (BABYLON) {
  17822. var _InstancesBatch = (function () {
  17823. function _InstancesBatch() {
  17824. this.mustReturn = false;
  17825. this.visibleInstances = new Array();
  17826. this.renderSelf = new Array();
  17827. }
  17828. return _InstancesBatch;
  17829. }());
  17830. BABYLON._InstancesBatch = _InstancesBatch;
  17831. var Mesh = (function (_super) {
  17832. __extends(Mesh, _super);
  17833. /**
  17834. * @constructor
  17835. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  17836. * @param {Scene} scene The scene to add this mesh to.
  17837. * @param {Node} parent The parent of this mesh, if it has one
  17838. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  17839. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  17840. * When false, achieved by calling a clone(), also passing False.
  17841. * This will make creation of children, recursive.
  17842. */
  17843. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  17844. if (parent === void 0) { parent = null; }
  17845. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  17846. _super.call(this, name, scene);
  17847. // Events
  17848. /**
  17849. * An event triggered before rendering the mesh
  17850. * @type {BABYLON.Observable}
  17851. */
  17852. this.onBeforeRenderObservable = new BABYLON.Observable();
  17853. /**
  17854. * An event triggered after rendering the mesh
  17855. * @type {BABYLON.Observable}
  17856. */
  17857. this.onAfterRenderObservable = new BABYLON.Observable();
  17858. /**
  17859. * An event triggered before drawing the mesh
  17860. * @type {BABYLON.Observable}
  17861. */
  17862. this.onBeforeDrawObservable = new BABYLON.Observable();
  17863. // Members
  17864. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  17865. this.instances = new Array();
  17866. this._LODLevels = new Array();
  17867. this._visibleInstances = {};
  17868. this._renderIdForInstances = new Array();
  17869. this._batchCache = new _InstancesBatch();
  17870. this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  17871. this._sideOrientation = Mesh._DEFAULTSIDE;
  17872. this._areNormalsFrozen = false; // Will be used by ribbons mainly
  17873. if (source) {
  17874. // Geometry
  17875. if (source._geometry) {
  17876. source._geometry.applyToMesh(this);
  17877. }
  17878. // Deep copy
  17879. BABYLON.Tools.DeepCopy(source, this, ["name", "material", "skeleton", "instances"], ["_poseMatrix"]);
  17880. // Pivot
  17881. this.setPivotMatrix(source.getPivotMatrix());
  17882. this.id = name + "." + source.id;
  17883. // Material
  17884. this.material = source.material;
  17885. var index;
  17886. if (!doNotCloneChildren) {
  17887. // Children
  17888. for (index = 0; index < scene.meshes.length; index++) {
  17889. var mesh = scene.meshes[index];
  17890. if (mesh.parent === source) {
  17891. // doNotCloneChildren is always going to be False
  17892. var newChild = mesh.clone(name + "." + mesh.name, this, doNotCloneChildren);
  17893. }
  17894. }
  17895. }
  17896. // Physics clone
  17897. var physicsEngine = this.getScene().getPhysicsEngine();
  17898. if (clonePhysicsImpostor && physicsEngine) {
  17899. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  17900. if (impostor) {
  17901. this.physicsImpostor = impostor.clone(this);
  17902. }
  17903. }
  17904. // Particles
  17905. for (index = 0; index < scene.particleSystems.length; index++) {
  17906. var system = scene.particleSystems[index];
  17907. if (system.emitter === source) {
  17908. system.clone(system.name, this);
  17909. }
  17910. }
  17911. this.computeWorldMatrix(true);
  17912. }
  17913. // Parent
  17914. if (parent !== null) {
  17915. this.parent = parent;
  17916. }
  17917. }
  17918. Object.defineProperty(Mesh, "FRONTSIDE", {
  17919. /**
  17920. * Mesh side orientation : usually the external or front surface
  17921. */
  17922. get: function () {
  17923. return Mesh._FRONTSIDE;
  17924. },
  17925. enumerable: true,
  17926. configurable: true
  17927. });
  17928. Object.defineProperty(Mesh, "BACKSIDE", {
  17929. /**
  17930. * Mesh side orientation : usually the internal or back surface
  17931. */
  17932. get: function () {
  17933. return Mesh._BACKSIDE;
  17934. },
  17935. enumerable: true,
  17936. configurable: true
  17937. });
  17938. Object.defineProperty(Mesh, "DOUBLESIDE", {
  17939. /**
  17940. * Mesh side orientation : both internal and external or front and back surfaces
  17941. */
  17942. get: function () {
  17943. return Mesh._DOUBLESIDE;
  17944. },
  17945. enumerable: true,
  17946. configurable: true
  17947. });
  17948. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  17949. /**
  17950. * Mesh side orientation : by default, `FRONTSIDE`
  17951. */
  17952. get: function () {
  17953. return Mesh._DEFAULTSIDE;
  17954. },
  17955. enumerable: true,
  17956. configurable: true
  17957. });
  17958. Object.defineProperty(Mesh, "NO_CAP", {
  17959. /**
  17960. * Mesh cap setting : no cap
  17961. */
  17962. get: function () {
  17963. return Mesh._NO_CAP;
  17964. },
  17965. enumerable: true,
  17966. configurable: true
  17967. });
  17968. Object.defineProperty(Mesh, "CAP_START", {
  17969. /**
  17970. * Mesh cap setting : one cap at the beginning of the mesh
  17971. */
  17972. get: function () {
  17973. return Mesh._CAP_START;
  17974. },
  17975. enumerable: true,
  17976. configurable: true
  17977. });
  17978. Object.defineProperty(Mesh, "CAP_END", {
  17979. /**
  17980. * Mesh cap setting : one cap at the end of the mesh
  17981. */
  17982. get: function () {
  17983. return Mesh._CAP_END;
  17984. },
  17985. enumerable: true,
  17986. configurable: true
  17987. });
  17988. Object.defineProperty(Mesh, "CAP_ALL", {
  17989. /**
  17990. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  17991. */
  17992. get: function () {
  17993. return Mesh._CAP_ALL;
  17994. },
  17995. enumerable: true,
  17996. configurable: true
  17997. });
  17998. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  17999. set: function (callback) {
  18000. if (this._onBeforeDrawObserver) {
  18001. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  18002. }
  18003. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  18004. },
  18005. enumerable: true,
  18006. configurable: true
  18007. });
  18008. // Methods
  18009. /**
  18010. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  18011. */
  18012. Mesh.prototype.toString = function (fullDetails) {
  18013. var ret = _super.prototype.toString.call(this, fullDetails);
  18014. ret += ", n vertices: " + this.getTotalVertices();
  18015. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  18016. if (this.animations) {
  18017. for (var i = 0; i < this.animations.length; i++) {
  18018. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  18019. }
  18020. }
  18021. if (fullDetails) {
  18022. ret += ", flat shading: " + (this._geometry ? (this.getVerticesData(BABYLON.VertexBuffer.PositionKind).length / 3 === this.getIndices().length ? "YES" : "NO") : "UNKNOWN");
  18023. }
  18024. return ret;
  18025. };
  18026. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  18027. get: function () {
  18028. return this._LODLevels.length > 0;
  18029. },
  18030. enumerable: true,
  18031. configurable: true
  18032. });
  18033. Mesh.prototype._sortLODLevels = function () {
  18034. this._LODLevels.sort(function (a, b) {
  18035. if (a.distance < b.distance) {
  18036. return 1;
  18037. }
  18038. if (a.distance > b.distance) {
  18039. return -1;
  18040. }
  18041. return 0;
  18042. });
  18043. };
  18044. /**
  18045. * Add a mesh as LOD level triggered at the given distance.
  18046. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  18047. * @param {number} distance The distance from the center of the object to show this level
  18048. * @param {Mesh} mesh The mesh to be added as LOD level
  18049. * @return {Mesh} This mesh (for chaining)
  18050. */
  18051. Mesh.prototype.addLODLevel = function (distance, mesh) {
  18052. if (mesh && mesh._masterMesh) {
  18053. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  18054. return this;
  18055. }
  18056. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  18057. this._LODLevels.push(level);
  18058. if (mesh) {
  18059. mesh._masterMesh = this;
  18060. }
  18061. this._sortLODLevels();
  18062. return this;
  18063. };
  18064. /**
  18065. * Returns the LOD level mesh at the passed distance or null if not found.
  18066. * It is related to the method `addLODLevel(distance, mesh)`.
  18067. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  18068. */
  18069. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  18070. for (var index = 0; index < this._LODLevels.length; index++) {
  18071. var level = this._LODLevels[index];
  18072. if (level.distance === distance) {
  18073. return level.mesh;
  18074. }
  18075. }
  18076. return null;
  18077. };
  18078. /**
  18079. * Remove a mesh from the LOD array
  18080. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  18081. * @param {Mesh} mesh The mesh to be removed.
  18082. * @return {Mesh} This mesh (for chaining)
  18083. */
  18084. Mesh.prototype.removeLODLevel = function (mesh) {
  18085. for (var index = 0; index < this._LODLevels.length; index++) {
  18086. if (this._LODLevels[index].mesh === mesh) {
  18087. this._LODLevels.splice(index, 1);
  18088. if (mesh) {
  18089. mesh._masterMesh = null;
  18090. }
  18091. }
  18092. }
  18093. this._sortLODLevels();
  18094. return this;
  18095. };
  18096. /**
  18097. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  18098. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  18099. */
  18100. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  18101. if (!this._LODLevels || this._LODLevels.length === 0) {
  18102. return this;
  18103. }
  18104. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.globalPosition).length();
  18105. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  18106. if (this.onLODLevelSelection) {
  18107. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  18108. }
  18109. return this;
  18110. }
  18111. for (var index = 0; index < this._LODLevels.length; index++) {
  18112. var level = this._LODLevels[index];
  18113. if (level.distance < distanceToCamera) {
  18114. if (level.mesh) {
  18115. level.mesh._preActivate();
  18116. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  18117. }
  18118. if (this.onLODLevelSelection) {
  18119. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  18120. }
  18121. return level.mesh;
  18122. }
  18123. }
  18124. if (this.onLODLevelSelection) {
  18125. this.onLODLevelSelection(distanceToCamera, this, this);
  18126. }
  18127. return this;
  18128. };
  18129. Object.defineProperty(Mesh.prototype, "geometry", {
  18130. /**
  18131. * Returns the mesh internal Geometry object.
  18132. */
  18133. get: function () {
  18134. return this._geometry;
  18135. },
  18136. enumerable: true,
  18137. configurable: true
  18138. });
  18139. /**
  18140. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  18141. */
  18142. Mesh.prototype.getTotalVertices = function () {
  18143. if (!this._geometry) {
  18144. return 0;
  18145. }
  18146. return this._geometry.getTotalVertices();
  18147. };
  18148. /**
  18149. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  18150. * 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.
  18151. * Returns null if the mesh has no geometry or no vertex buffer.
  18152. * Possible `kind` values :
  18153. * - BABYLON.VertexBuffer.PositionKind
  18154. * - BABYLON.VertexBuffer.UVKind
  18155. * - BABYLON.VertexBuffer.UV2Kind
  18156. * - BABYLON.VertexBuffer.UV3Kind
  18157. * - BABYLON.VertexBuffer.UV4Kind
  18158. * - BABYLON.VertexBuffer.UV5Kind
  18159. * - BABYLON.VertexBuffer.UV6Kind
  18160. * - BABYLON.VertexBuffer.ColorKind
  18161. * - BABYLON.VertexBuffer.MatricesIndicesKind
  18162. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  18163. * - BABYLON.VertexBuffer.MatricesWeightsKind
  18164. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  18165. */
  18166. Mesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  18167. if (!this._geometry) {
  18168. return null;
  18169. }
  18170. return this._geometry.getVerticesData(kind, copyWhenShared);
  18171. };
  18172. /**
  18173. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  18174. * Returns `undefined` if the mesh has no geometry.
  18175. * Possible `kind` values :
  18176. * - BABYLON.VertexBuffer.PositionKind
  18177. * - BABYLON.VertexBuffer.UVKind
  18178. * - BABYLON.VertexBuffer.UV2Kind
  18179. * - BABYLON.VertexBuffer.UV3Kind
  18180. * - BABYLON.VertexBuffer.UV4Kind
  18181. * - BABYLON.VertexBuffer.UV5Kind
  18182. * - BABYLON.VertexBuffer.UV6Kind
  18183. * - BABYLON.VertexBuffer.ColorKind
  18184. * - BABYLON.VertexBuffer.MatricesIndicesKind
  18185. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  18186. * - BABYLON.VertexBuffer.MatricesWeightsKind
  18187. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  18188. */
  18189. Mesh.prototype.getVertexBuffer = function (kind) {
  18190. if (!this._geometry) {
  18191. return undefined;
  18192. }
  18193. return this._geometry.getVertexBuffer(kind);
  18194. };
  18195. /**
  18196. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  18197. * Possible `kind` values :
  18198. * - BABYLON.VertexBuffer.PositionKind
  18199. * - BABYLON.VertexBuffer.UVKind
  18200. * - BABYLON.VertexBuffer.UV2Kind
  18201. * - BABYLON.VertexBuffer.UV3Kind
  18202. * - BABYLON.VertexBuffer.UV4Kind
  18203. * - BABYLON.VertexBuffer.UV5Kind
  18204. * - BABYLON.VertexBuffer.UV6Kind
  18205. * - BABYLON.VertexBuffer.ColorKind
  18206. * - BABYLON.VertexBuffer.MatricesIndicesKind
  18207. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  18208. * - BABYLON.VertexBuffer.MatricesWeightsKind
  18209. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  18210. */
  18211. Mesh.prototype.isVerticesDataPresent = function (kind) {
  18212. if (!this._geometry) {
  18213. if (this._delayInfo) {
  18214. return this._delayInfo.indexOf(kind) !== -1;
  18215. }
  18216. return false;
  18217. }
  18218. return this._geometry.isVerticesDataPresent(kind);
  18219. };
  18220. /**
  18221. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  18222. * Possible `kind` values :
  18223. * - BABYLON.VertexBuffer.PositionKind
  18224. * - BABYLON.VertexBuffer.UVKind
  18225. * - BABYLON.VertexBuffer.UV2Kind
  18226. * - BABYLON.VertexBuffer.UV3Kind
  18227. * - BABYLON.VertexBuffer.UV4Kind
  18228. * - BABYLON.VertexBuffer.UV5Kind
  18229. * - BABYLON.VertexBuffer.UV6Kind
  18230. * - BABYLON.VertexBuffer.ColorKind
  18231. * - BABYLON.VertexBuffer.MatricesIndicesKind
  18232. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  18233. * - BABYLON.VertexBuffer.MatricesWeightsKind
  18234. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  18235. */
  18236. Mesh.prototype.getVerticesDataKinds = function () {
  18237. if (!this._geometry) {
  18238. var result = [];
  18239. if (this._delayInfo) {
  18240. for (var kind in this._delayInfo) {
  18241. result.push(kind);
  18242. }
  18243. }
  18244. return result;
  18245. }
  18246. return this._geometry.getVerticesDataKinds();
  18247. };
  18248. /**
  18249. * Returns a positive integer : the total number of indices in this mesh geometry.
  18250. * Returns zero if the mesh has no geometry.
  18251. */
  18252. Mesh.prototype.getTotalIndices = function () {
  18253. if (!this._geometry) {
  18254. return 0;
  18255. }
  18256. return this._geometry.getTotalIndices();
  18257. };
  18258. /**
  18259. * Returns an array of integers or a Int32Array populated with the mesh indices.
  18260. * 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.
  18261. * Returns an empty array if the mesh has no geometry.
  18262. */
  18263. Mesh.prototype.getIndices = function (copyWhenShared) {
  18264. if (!this._geometry) {
  18265. return [];
  18266. }
  18267. return this._geometry.getIndices(copyWhenShared);
  18268. };
  18269. Object.defineProperty(Mesh.prototype, "isBlocked", {
  18270. get: function () {
  18271. return this._masterMesh !== null && this._masterMesh !== undefined;
  18272. },
  18273. enumerable: true,
  18274. configurable: true
  18275. });
  18276. /**
  18277. * Boolean : true once the mesh is ready after all the delayed process (loading, etc) are complete.
  18278. */
  18279. Mesh.prototype.isReady = function () {
  18280. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  18281. return false;
  18282. }
  18283. return _super.prototype.isReady.call(this);
  18284. };
  18285. /**
  18286. * Boolean : true if the mesh has been disposed.
  18287. */
  18288. Mesh.prototype.isDisposed = function () {
  18289. return this._isDisposed;
  18290. };
  18291. Object.defineProperty(Mesh.prototype, "sideOrientation", {
  18292. get: function () {
  18293. return this._sideOrientation;
  18294. },
  18295. /**
  18296. * Sets the mesh side orientation : BABYLON.Mesh.FRONTSIDE, BABYLON.Mesh.BACKSIDE, BABYLON.Mesh.DOUBLESIDE or BABYLON.Mesh.DEFAULTSIDE
  18297. * tuto : http://doc.babylonjs.com/tutorials/Discover_Basic_Elements#side-orientation
  18298. */
  18299. set: function (sideO) {
  18300. this._sideOrientation = sideO;
  18301. },
  18302. enumerable: true,
  18303. configurable: true
  18304. });
  18305. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  18306. /**
  18307. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  18308. * This property is pertinent only for updatable parametric shapes.
  18309. */
  18310. get: function () {
  18311. return this._areNormalsFrozen;
  18312. },
  18313. enumerable: true,
  18314. configurable: true
  18315. });
  18316. /**
  18317. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  18318. * It has no effect at all on other shapes.
  18319. * It prevents the mesh normals from being recomputed on next `positions` array update.
  18320. */
  18321. Mesh.prototype.freezeNormals = function () {
  18322. this._areNormalsFrozen = true;
  18323. };
  18324. /**
  18325. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  18326. * It has no effect at all on other shapes.
  18327. * It reactivates the mesh normals computation if it was previously frozen.
  18328. */
  18329. Mesh.prototype.unfreezeNormals = function () {
  18330. this._areNormalsFrozen = false;
  18331. };
  18332. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  18333. /**
  18334. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  18335. */
  18336. set: function (count) {
  18337. this._overridenInstanceCount = count;
  18338. },
  18339. enumerable: true,
  18340. configurable: true
  18341. });
  18342. // Methods
  18343. Mesh.prototype._preActivate = function () {
  18344. var sceneRenderId = this.getScene().getRenderId();
  18345. if (this._preActivateId === sceneRenderId) {
  18346. return;
  18347. }
  18348. this._preActivateId = sceneRenderId;
  18349. this._visibleInstances = null;
  18350. };
  18351. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  18352. if (this._visibleInstances) {
  18353. this._visibleInstances.intermediateDefaultRenderId = renderId;
  18354. }
  18355. };
  18356. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  18357. if (!this._visibleInstances) {
  18358. this._visibleInstances = {};
  18359. this._visibleInstances.defaultRenderId = renderId;
  18360. this._visibleInstances.selfDefaultRenderId = this._renderId;
  18361. }
  18362. if (!this._visibleInstances[renderId]) {
  18363. this._visibleInstances[renderId] = new Array();
  18364. }
  18365. this._visibleInstances[renderId].push(instance);
  18366. };
  18367. /**
  18368. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  18369. * This means the mesh underlying bounding box and sphere are recomputed.
  18370. */
  18371. Mesh.prototype.refreshBoundingInfo = function () {
  18372. if (this._boundingInfo.isLocked) {
  18373. return;
  18374. }
  18375. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18376. if (data) {
  18377. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  18378. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  18379. }
  18380. if (this.subMeshes) {
  18381. for (var index = 0; index < this.subMeshes.length; index++) {
  18382. this.subMeshes[index].refreshBoundingInfo();
  18383. }
  18384. }
  18385. this._updateBoundingInfo();
  18386. };
  18387. Mesh.prototype._createGlobalSubMesh = function () {
  18388. var totalVertices = this.getTotalVertices();
  18389. if (!totalVertices || !this.getIndices()) {
  18390. return null;
  18391. }
  18392. this.releaseSubMeshes();
  18393. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  18394. };
  18395. Mesh.prototype.subdivide = function (count) {
  18396. if (count < 1) {
  18397. return;
  18398. }
  18399. var totalIndices = this.getTotalIndices();
  18400. var subdivisionSize = (totalIndices / count) | 0;
  18401. var offset = 0;
  18402. // Ensure that subdivisionSize is a multiple of 3
  18403. while (subdivisionSize % 3 !== 0) {
  18404. subdivisionSize++;
  18405. }
  18406. this.releaseSubMeshes();
  18407. for (var index = 0; index < count; index++) {
  18408. if (offset >= totalIndices) {
  18409. break;
  18410. }
  18411. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  18412. offset += subdivisionSize;
  18413. }
  18414. this.synchronizeInstances();
  18415. };
  18416. /**
  18417. * Sets the vertex data of the mesh geometry for the requested `kind`.
  18418. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  18419. * The `data` are either a numeric array either a Float32Array.
  18420. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  18421. * 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).
  18422. * Note that a new underlying VertexBuffer object is created each call.
  18423. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  18424. *
  18425. * Possible `kind` values :
  18426. * - BABYLON.VertexBuffer.PositionKind
  18427. * - BABYLON.VertexBuffer.UVKind
  18428. * - BABYLON.VertexBuffer.UV2Kind
  18429. * - BABYLON.VertexBuffer.UV3Kind
  18430. * - BABYLON.VertexBuffer.UV4Kind
  18431. * - BABYLON.VertexBuffer.UV5Kind
  18432. * - BABYLON.VertexBuffer.UV6Kind
  18433. * - BABYLON.VertexBuffer.ColorKind
  18434. * - BABYLON.VertexBuffer.MatricesIndicesKind
  18435. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  18436. * - BABYLON.VertexBuffer.MatricesWeightsKind
  18437. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  18438. */
  18439. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  18440. if (!this._geometry) {
  18441. var vertexData = new BABYLON.VertexData();
  18442. vertexData.set(data, kind);
  18443. var scene = this.getScene();
  18444. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  18445. }
  18446. else {
  18447. this._geometry.setVerticesData(kind, data, updatable, stride);
  18448. }
  18449. };
  18450. Mesh.prototype.setVerticesBuffer = function (buffer) {
  18451. if (!this._geometry) {
  18452. var scene = this.getScene();
  18453. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene).applyToMesh(this);
  18454. }
  18455. this._geometry.setVerticesBuffer(buffer);
  18456. };
  18457. /**
  18458. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  18459. * If the mesh has no geometry, it is simply returned as it is.
  18460. * The `data` are either a numeric array either a Float32Array.
  18461. * No new underlying VertexBuffer object is created.
  18462. * 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.
  18463. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  18464. *
  18465. * Possible `kind` values :
  18466. * - BABYLON.VertexBuffer.PositionKind
  18467. * - BABYLON.VertexBuffer.UVKind
  18468. * - BABYLON.VertexBuffer.UV2Kind
  18469. * - BABYLON.VertexBuffer.UV3Kind
  18470. * - BABYLON.VertexBuffer.UV4Kind
  18471. * - BABYLON.VertexBuffer.UV5Kind
  18472. * - BABYLON.VertexBuffer.UV6Kind
  18473. * - BABYLON.VertexBuffer.ColorKind
  18474. * - BABYLON.VertexBuffer.MatricesIndicesKind
  18475. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  18476. * - BABYLON.VertexBuffer.MatricesWeightsKind
  18477. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  18478. */
  18479. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  18480. if (!this._geometry) {
  18481. return;
  18482. }
  18483. if (!makeItUnique) {
  18484. this._geometry.updateVerticesData(kind, data, updateExtends);
  18485. }
  18486. else {
  18487. this.makeGeometryUnique();
  18488. this.updateVerticesData(kind, data, updateExtends, false);
  18489. }
  18490. };
  18491. /**
  18492. * Deprecated since BabylonJS v2.3
  18493. */
  18494. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, offset, makeItUnique) {
  18495. BABYLON.Tools.Warn("Mesh.updateVerticesDataDirectly deprecated since 2.3.");
  18496. if (!this._geometry) {
  18497. return;
  18498. }
  18499. if (!makeItUnique) {
  18500. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  18501. }
  18502. else {
  18503. this.makeGeometryUnique();
  18504. this.updateVerticesDataDirectly(kind, data, offset, false);
  18505. }
  18506. };
  18507. /**
  18508. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  18509. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  18510. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  18511. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  18512. */
  18513. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  18514. if (computeNormals === void 0) { computeNormals = true; }
  18515. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18516. positionFunction(positions);
  18517. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  18518. if (computeNormals) {
  18519. var indices = this.getIndices();
  18520. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  18521. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  18522. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  18523. }
  18524. };
  18525. Mesh.prototype.makeGeometryUnique = function () {
  18526. if (!this._geometry) {
  18527. return;
  18528. }
  18529. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  18530. geometry.applyToMesh(this);
  18531. };
  18532. /**
  18533. * Sets the mesh indices.
  18534. * Expects an array populated with integers or a Int32Array.
  18535. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  18536. * This method creates a new index buffer each call.
  18537. */
  18538. Mesh.prototype.setIndices = function (indices, totalVertices) {
  18539. if (!this._geometry) {
  18540. var vertexData = new BABYLON.VertexData();
  18541. vertexData.indices = indices;
  18542. var scene = this.getScene();
  18543. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  18544. }
  18545. else {
  18546. this._geometry.setIndices(indices, totalVertices);
  18547. }
  18548. };
  18549. /**
  18550. * Invert the geometry to move from a right handed system to a left handed one.
  18551. */
  18552. Mesh.prototype.toLeftHanded = function () {
  18553. if (!this._geometry) {
  18554. return;
  18555. }
  18556. this._geometry.toLeftHanded();
  18557. };
  18558. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  18559. var engine = this.getScene().getEngine();
  18560. // Wireframe
  18561. var indexToBind;
  18562. if (this._unIndexed) {
  18563. indexToBind = null;
  18564. }
  18565. else {
  18566. switch (fillMode) {
  18567. case BABYLON.Material.PointFillMode:
  18568. indexToBind = null;
  18569. break;
  18570. case BABYLON.Material.WireFrameFillMode:
  18571. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  18572. break;
  18573. default:
  18574. case BABYLON.Material.TriangleFillMode:
  18575. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  18576. break;
  18577. }
  18578. }
  18579. // VBOs
  18580. engine.bindBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  18581. };
  18582. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  18583. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  18584. return;
  18585. }
  18586. this.onBeforeDrawObservable.notifyObservers(this);
  18587. var engine = this.getScene().getEngine();
  18588. // Draw order
  18589. switch (fillMode) {
  18590. case BABYLON.Material.PointFillMode:
  18591. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  18592. break;
  18593. case BABYLON.Material.WireFrameFillMode:
  18594. if (this._unIndexed) {
  18595. engine.drawUnIndexed(false, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  18596. }
  18597. else {
  18598. engine.draw(false, 0, instancesCount > 0 ? subMesh.linesIndexCount / 2 : subMesh.linesIndexCount, instancesCount);
  18599. }
  18600. break;
  18601. default:
  18602. if (this._unIndexed) {
  18603. engine.drawUnIndexed(true, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  18604. }
  18605. else {
  18606. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  18607. }
  18608. }
  18609. };
  18610. /**
  18611. * Registers for this mesh a javascript function called just before the rendering process.
  18612. * This function is passed the current mesh and doesn't return anything.
  18613. */
  18614. Mesh.prototype.registerBeforeRender = function (func) {
  18615. this.onBeforeRenderObservable.add(func);
  18616. };
  18617. /**
  18618. * Disposes a previously registered javascript function called before the rendering.
  18619. * This function is passed the current mesh and doesn't return anything.
  18620. */
  18621. Mesh.prototype.unregisterBeforeRender = function (func) {
  18622. this.onBeforeRenderObservable.removeCallback(func);
  18623. };
  18624. /**
  18625. * Registers for this mesh a javascript function called just after the rendering is complete.
  18626. * This function is passed the current mesh and doesn't return anything.
  18627. */
  18628. Mesh.prototype.registerAfterRender = function (func) {
  18629. this.onAfterRenderObservable.add(func);
  18630. };
  18631. /**
  18632. * Disposes a previously registered javascript function called after the rendering.
  18633. * This function is passed the current mesh and doesn't return anything.
  18634. */
  18635. Mesh.prototype.unregisterAfterRender = function (func) {
  18636. this.onAfterRenderObservable.removeCallback(func);
  18637. };
  18638. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  18639. var scene = this.getScene();
  18640. this._batchCache.mustReturn = false;
  18641. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  18642. this._batchCache.visibleInstances[subMeshId] = null;
  18643. if (this._visibleInstances) {
  18644. var currentRenderId = scene.getRenderId();
  18645. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  18646. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  18647. var selfRenderId = this._renderId;
  18648. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  18649. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  18650. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  18651. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  18652. }
  18653. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  18654. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  18655. this._batchCache.mustReturn = true;
  18656. return this._batchCache;
  18657. }
  18658. if (currentRenderId !== selfRenderId) {
  18659. this._batchCache.renderSelf[subMeshId] = false;
  18660. }
  18661. }
  18662. this._renderIdForInstances[subMeshId] = currentRenderId;
  18663. }
  18664. return this._batchCache;
  18665. };
  18666. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  18667. var visibleInstances = batch.visibleInstances[subMesh._id];
  18668. var matricesCount = visibleInstances.length + 1;
  18669. var bufferSize = matricesCount * 16 * 4;
  18670. var currentInstancesBufferSize = this._instancesBufferSize;
  18671. var instancesBuffer = this._instancesBuffer;
  18672. while (this._instancesBufferSize < bufferSize) {
  18673. this._instancesBufferSize *= 2;
  18674. }
  18675. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  18676. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  18677. }
  18678. var offset = 0;
  18679. var instancesCount = 0;
  18680. var world = this.getWorldMatrix();
  18681. if (batch.renderSelf[subMesh._id]) {
  18682. world.copyToArray(this._instancesData, offset);
  18683. offset += 16;
  18684. instancesCount++;
  18685. }
  18686. if (visibleInstances) {
  18687. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  18688. var instance = visibleInstances[instanceIndex];
  18689. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  18690. offset += 16;
  18691. instancesCount++;
  18692. }
  18693. }
  18694. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  18695. if (instancesBuffer) {
  18696. instancesBuffer.dispose();
  18697. }
  18698. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  18699. this._instancesBuffer = instancesBuffer;
  18700. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  18701. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  18702. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  18703. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  18704. }
  18705. else {
  18706. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  18707. }
  18708. engine.bindBuffers(this.geometry.getVertexBuffers(), this.geometry.getIndexBuffer(), effect);
  18709. this._draw(subMesh, fillMode, instancesCount);
  18710. engine.unbindInstanceAttributes();
  18711. };
  18712. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  18713. var scene = this.getScene();
  18714. var engine = scene.getEngine();
  18715. if (hardwareInstancedRendering) {
  18716. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  18717. }
  18718. else {
  18719. if (batch.renderSelf[subMesh._id]) {
  18720. // Draw
  18721. if (onBeforeDraw) {
  18722. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  18723. }
  18724. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  18725. }
  18726. if (batch.visibleInstances[subMesh._id]) {
  18727. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  18728. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  18729. // World
  18730. var world = instance.getWorldMatrix();
  18731. if (onBeforeDraw) {
  18732. onBeforeDraw(true, world, effectiveMaterial);
  18733. }
  18734. // Draw
  18735. this._draw(subMesh, fillMode);
  18736. }
  18737. }
  18738. }
  18739. };
  18740. /**
  18741. * Triggers the draw call for the mesh.
  18742. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  18743. */
  18744. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  18745. var scene = this.getScene();
  18746. // Managing instances
  18747. var batch = this._getInstancesRenderList(subMesh._id);
  18748. if (batch.mustReturn) {
  18749. return;
  18750. }
  18751. // Checking geometry state
  18752. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  18753. return;
  18754. }
  18755. var callbackIndex;
  18756. this.onBeforeRenderObservable.notifyObservers(this);
  18757. var engine = scene.getEngine();
  18758. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  18759. // Material
  18760. var effectiveMaterial = subMesh.getMaterial();
  18761. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  18762. return;
  18763. }
  18764. // Outline - step 1
  18765. var savedDepthWrite = engine.getDepthWrite();
  18766. if (this.renderOutline) {
  18767. engine.setDepthWrite(false);
  18768. scene.getOutlineRenderer().render(subMesh, batch);
  18769. engine.setDepthWrite(savedDepthWrite);
  18770. }
  18771. effectiveMaterial._preBind();
  18772. var effect = effectiveMaterial.getEffect();
  18773. // Bind
  18774. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  18775. this._bind(subMesh, effect, fillMode);
  18776. var world = this.getWorldMatrix();
  18777. effectiveMaterial.bind(world, this);
  18778. // Alpha mode
  18779. if (enableAlphaMode) {
  18780. engine.setAlphaMode(effectiveMaterial.alphaMode);
  18781. }
  18782. // Draw
  18783. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw);
  18784. // Unbind
  18785. effectiveMaterial.unbind();
  18786. // Outline - step 2
  18787. if (this.renderOutline && savedDepthWrite) {
  18788. engine.setDepthWrite(true);
  18789. engine.setColorWrite(false);
  18790. scene.getOutlineRenderer().render(subMesh, batch);
  18791. engine.setColorWrite(true);
  18792. }
  18793. // Overlay
  18794. if (this.renderOverlay) {
  18795. var currentMode = engine.getAlphaMode();
  18796. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  18797. scene.getOutlineRenderer().render(subMesh, batch, true);
  18798. engine.setAlphaMode(currentMode);
  18799. }
  18800. this.onAfterRenderObservable.notifyObservers(this);
  18801. };
  18802. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  18803. if (isInstance) {
  18804. effectiveMaterial.bindOnlyWorldMatrix(world);
  18805. }
  18806. };
  18807. /**
  18808. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  18809. */
  18810. Mesh.prototype.getEmittedParticleSystems = function () {
  18811. var results = new Array();
  18812. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  18813. var particleSystem = this.getScene().particleSystems[index];
  18814. if (particleSystem.emitter === this) {
  18815. results.push(particleSystem);
  18816. }
  18817. }
  18818. return results;
  18819. };
  18820. /**
  18821. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  18822. */
  18823. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  18824. var results = new Array();
  18825. var descendants = this.getDescendants();
  18826. descendants.push(this);
  18827. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  18828. var particleSystem = this.getScene().particleSystems[index];
  18829. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  18830. results.push(particleSystem);
  18831. }
  18832. }
  18833. return results;
  18834. };
  18835. Mesh.prototype._checkDelayState = function () {
  18836. var scene = this.getScene();
  18837. if (this._geometry) {
  18838. this._geometry.load(scene);
  18839. }
  18840. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  18841. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  18842. this._queueLoad(this, scene);
  18843. }
  18844. };
  18845. Mesh.prototype._queueLoad = function (mesh, scene) {
  18846. var _this = this;
  18847. scene._addPendingData(mesh);
  18848. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  18849. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  18850. if (data instanceof ArrayBuffer) {
  18851. _this._delayLoadingFunction(data, _this);
  18852. }
  18853. else {
  18854. _this._delayLoadingFunction(JSON.parse(data), _this);
  18855. }
  18856. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  18857. scene._removePendingData(_this);
  18858. }, function () { }, scene.database, getBinaryData);
  18859. };
  18860. /**
  18861. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  18862. */
  18863. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  18864. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  18865. return false;
  18866. }
  18867. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  18868. return false;
  18869. }
  18870. this._checkDelayState();
  18871. return true;
  18872. };
  18873. /**
  18874. * Sets the mesh material by the material or multiMaterial `id` property.
  18875. * The material `id` is a string identifying the material or the multiMaterial.
  18876. * This method returns nothing.
  18877. */
  18878. Mesh.prototype.setMaterialByID = function (id) {
  18879. var materials = this.getScene().materials;
  18880. var index;
  18881. for (index = 0; index < materials.length; index++) {
  18882. if (materials[index].id === id) {
  18883. this.material = materials[index];
  18884. return;
  18885. }
  18886. }
  18887. // Multi
  18888. var multiMaterials = this.getScene().multiMaterials;
  18889. for (index = 0; index < multiMaterials.length; index++) {
  18890. if (multiMaterials[index].id === id) {
  18891. this.material = multiMaterials[index];
  18892. return;
  18893. }
  18894. }
  18895. };
  18896. /**
  18897. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  18898. */
  18899. Mesh.prototype.getAnimatables = function () {
  18900. var results = [];
  18901. if (this.material) {
  18902. results.push(this.material);
  18903. }
  18904. if (this.skeleton) {
  18905. results.push(this.skeleton);
  18906. }
  18907. return results;
  18908. };
  18909. /**
  18910. * Modifies the mesh geometry according to the passed transformation matrix.
  18911. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  18912. * The mesh normals are modified accordingly the same transformation.
  18913. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  18914. * Note that, under the hood, this method sets a new VertexBuffer each call.
  18915. */
  18916. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  18917. // Position
  18918. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  18919. return;
  18920. }
  18921. var submeshes = this.subMeshes.splice(0);
  18922. this._resetPointsArrayCache();
  18923. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18924. var temp = [];
  18925. var index;
  18926. for (index = 0; index < data.length; index += 3) {
  18927. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  18928. }
  18929. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  18930. // Normals
  18931. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  18932. return;
  18933. }
  18934. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  18935. temp = [];
  18936. for (index = 0; index < data.length; index += 3) {
  18937. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  18938. }
  18939. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  18940. // flip faces?
  18941. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  18942. this.flipFaces();
  18943. }
  18944. // Restore submeshes
  18945. this.releaseSubMeshes();
  18946. this.subMeshes = submeshes;
  18947. };
  18948. /**
  18949. * Modifies the mesh geometry according to its own current World Matrix.
  18950. * The mesh World Matrix is then reset.
  18951. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  18952. * tuto : tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  18953. * Note that, under the hood, this method sets a new VertexBuffer each call.
  18954. */
  18955. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  18956. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  18957. this.scaling.copyFromFloats(1, 1, 1);
  18958. this.position.copyFromFloats(0, 0, 0);
  18959. this.rotation.copyFromFloats(0, 0, 0);
  18960. //only if quaternion is already set
  18961. if (this.rotationQuaternion) {
  18962. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  18963. }
  18964. this._worldMatrix = BABYLON.Matrix.Identity();
  18965. };
  18966. // Cache
  18967. Mesh.prototype._resetPointsArrayCache = function () {
  18968. this._positions = null;
  18969. };
  18970. Mesh.prototype._generatePointsArray = function () {
  18971. if (this._positions)
  18972. return true;
  18973. this._positions = [];
  18974. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18975. if (!data) {
  18976. return false;
  18977. }
  18978. for (var index = 0; index < data.length; index += 3) {
  18979. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  18980. }
  18981. return true;
  18982. };
  18983. /**
  18984. * Returns a new Mesh object generated from the current mesh properties.
  18985. * This method must not get confused with createInstance().
  18986. * The parameter `name` is a string, the name given to the new mesh.
  18987. * The optional parameter `newParent` can be any Node object (default `null`).
  18988. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  18989. * 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.
  18990. */
  18991. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  18992. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  18993. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  18994. };
  18995. /**
  18996. * Disposes the mesh.
  18997. * This also frees the memory allocated under the hood to all the buffers used by WebGL.
  18998. */
  18999. Mesh.prototype.dispose = function (doNotRecurse) {
  19000. if (this._geometry) {
  19001. this._geometry.releaseForMesh(this, true);
  19002. }
  19003. // Instances
  19004. if (this._instancesBuffer) {
  19005. this._instancesBuffer.dispose();
  19006. this._instancesBuffer = null;
  19007. }
  19008. while (this.instances.length) {
  19009. this.instances[0].dispose();
  19010. }
  19011. _super.prototype.dispose.call(this, doNotRecurse);
  19012. };
  19013. /**
  19014. * Modifies the mesh geometry according to a displacement map.
  19015. * 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.
  19016. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  19017. * This method returns nothing.
  19018. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  19019. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  19020. * 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.
  19021. */
  19022. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess) {
  19023. var _this = this;
  19024. var scene = this.getScene();
  19025. var onload = function (img) {
  19026. // Getting height map data
  19027. var canvas = document.createElement("canvas");
  19028. var context = canvas.getContext("2d");
  19029. var heightMapWidth = img.width;
  19030. var heightMapHeight = img.height;
  19031. canvas.width = heightMapWidth;
  19032. canvas.height = heightMapHeight;
  19033. context.drawImage(img, 0, 0);
  19034. // Create VertexData from map data
  19035. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  19036. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  19037. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  19038. //execute success callback, if set
  19039. if (onSuccess) {
  19040. onSuccess(_this);
  19041. }
  19042. };
  19043. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  19044. };
  19045. /**
  19046. * Modifies the mesh geometry according to a displacementMap buffer.
  19047. * 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.
  19048. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  19049. * This method returns nothing.
  19050. * 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.
  19051. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  19052. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  19053. */
  19054. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  19055. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  19056. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  19057. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  19058. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  19059. return;
  19060. }
  19061. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19062. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  19063. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  19064. var position = BABYLON.Vector3.Zero();
  19065. var normal = BABYLON.Vector3.Zero();
  19066. var uv = BABYLON.Vector2.Zero();
  19067. for (var index = 0; index < positions.length; index += 3) {
  19068. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  19069. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  19070. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  19071. // Compute height
  19072. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  19073. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  19074. var pos = (u + v * heightMapWidth) * 4;
  19075. var r = buffer[pos] / 255.0;
  19076. var g = buffer[pos + 1] / 255.0;
  19077. var b = buffer[pos + 2] / 255.0;
  19078. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  19079. normal.normalize();
  19080. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  19081. position = position.add(normal);
  19082. position.toArray(positions, index);
  19083. }
  19084. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  19085. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  19086. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  19087. };
  19088. /**
  19089. * Modify the mesh to get a flat shading rendering.
  19090. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  19091. * This method returns nothing.
  19092. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  19093. */
  19094. Mesh.prototype.convertToFlatShadedMesh = function () {
  19095. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  19096. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  19097. var kinds = this.getVerticesDataKinds();
  19098. var vbs = [];
  19099. var data = [];
  19100. var newdata = [];
  19101. var updatableNormals = false;
  19102. var kindIndex;
  19103. var kind;
  19104. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  19105. kind = kinds[kindIndex];
  19106. var vertexBuffer = this.getVertexBuffer(kind);
  19107. if (kind === BABYLON.VertexBuffer.NormalKind) {
  19108. updatableNormals = vertexBuffer.isUpdatable();
  19109. kinds.splice(kindIndex, 1);
  19110. kindIndex--;
  19111. continue;
  19112. }
  19113. vbs[kind] = vertexBuffer;
  19114. data[kind] = vbs[kind].getData();
  19115. newdata[kind] = [];
  19116. }
  19117. // Save previous submeshes
  19118. var previousSubmeshes = this.subMeshes.slice(0);
  19119. var indices = this.getIndices();
  19120. var totalIndices = this.getTotalIndices();
  19121. // Generating unique vertices per face
  19122. var index;
  19123. for (index = 0; index < totalIndices; index++) {
  19124. var vertexIndex = indices[index];
  19125. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  19126. kind = kinds[kindIndex];
  19127. var stride = vbs[kind].getStrideSize();
  19128. for (var offset = 0; offset < stride; offset++) {
  19129. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  19130. }
  19131. }
  19132. }
  19133. // Updating faces & normal
  19134. var normals = [];
  19135. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  19136. for (index = 0; index < totalIndices; index += 3) {
  19137. indices[index] = index;
  19138. indices[index + 1] = index + 1;
  19139. indices[index + 2] = index + 2;
  19140. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  19141. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  19142. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  19143. var p1p2 = p1.subtract(p2);
  19144. var p3p2 = p3.subtract(p2);
  19145. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  19146. // Store same normals for every vertex
  19147. for (var localIndex = 0; localIndex < 3; localIndex++) {
  19148. normals.push(normal.x);
  19149. normals.push(normal.y);
  19150. normals.push(normal.z);
  19151. }
  19152. }
  19153. this.setIndices(indices);
  19154. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  19155. // Updating vertex buffers
  19156. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  19157. kind = kinds[kindIndex];
  19158. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  19159. }
  19160. // Updating submeshes
  19161. this.releaseSubMeshes();
  19162. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  19163. var previousOne = previousSubmeshes[submeshIndex];
  19164. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  19165. }
  19166. this.synchronizeInstances();
  19167. };
  19168. /**
  19169. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  19170. * In other words, more vertices, no more indices and a single bigger VBO.
  19171. * This method returns nothing.
  19172. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  19173. *
  19174. */
  19175. Mesh.prototype.convertToUnIndexedMesh = function () {
  19176. /// <summary>Remove indices by unfolding faces into buffers</summary>
  19177. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  19178. var kinds = this.getVerticesDataKinds();
  19179. var vbs = [];
  19180. var data = [];
  19181. var newdata = [];
  19182. var updatableNormals = false;
  19183. var kindIndex;
  19184. var kind;
  19185. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  19186. kind = kinds[kindIndex];
  19187. var vertexBuffer = this.getVertexBuffer(kind);
  19188. vbs[kind] = vertexBuffer;
  19189. data[kind] = vbs[kind].getData();
  19190. newdata[kind] = [];
  19191. }
  19192. // Save previous submeshes
  19193. var previousSubmeshes = this.subMeshes.slice(0);
  19194. var indices = this.getIndices();
  19195. var totalIndices = this.getTotalIndices();
  19196. // Generating unique vertices per face
  19197. var index;
  19198. for (index = 0; index < totalIndices; index++) {
  19199. var vertexIndex = indices[index];
  19200. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  19201. kind = kinds[kindIndex];
  19202. var stride = vbs[kind].getStrideSize();
  19203. for (var offset = 0; offset < stride; offset++) {
  19204. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  19205. }
  19206. }
  19207. }
  19208. // Updating indices
  19209. for (index = 0; index < totalIndices; index += 3) {
  19210. indices[index] = index;
  19211. indices[index + 1] = index + 1;
  19212. indices[index + 2] = index + 2;
  19213. }
  19214. this.setIndices(indices);
  19215. // Updating vertex buffers
  19216. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  19217. kind = kinds[kindIndex];
  19218. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  19219. }
  19220. // Updating submeshes
  19221. this.releaseSubMeshes();
  19222. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  19223. var previousOne = previousSubmeshes[submeshIndex];
  19224. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  19225. }
  19226. this._unIndexed = true;
  19227. this.synchronizeInstances();
  19228. };
  19229. /**
  19230. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  19231. * This method returns nothing.
  19232. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  19233. */
  19234. Mesh.prototype.flipFaces = function (flipNormals) {
  19235. if (flipNormals === void 0) { flipNormals = false; }
  19236. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  19237. var i;
  19238. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  19239. for (i = 0; i < vertex_data.normals.length; i++) {
  19240. vertex_data.normals[i] *= -1;
  19241. }
  19242. }
  19243. var temp;
  19244. for (i = 0; i < vertex_data.indices.length; i += 3) {
  19245. // reassign indices
  19246. temp = vertex_data.indices[i + 1];
  19247. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  19248. vertex_data.indices[i + 2] = temp;
  19249. }
  19250. vertex_data.applyToMesh(this);
  19251. };
  19252. // Instances
  19253. /**
  19254. * Creates a new InstancedMesh object from the mesh model.
  19255. * An instance shares the same properties and the same material than its model.
  19256. * Only these properties of each instance can then be set individually :
  19257. * - position
  19258. * - rotation
  19259. * - rotationQuaternion
  19260. * - setPivotMatrix
  19261. * - scaling
  19262. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  19263. * Warning : this method is not supported for Line mesh and LineSystem
  19264. */
  19265. Mesh.prototype.createInstance = function (name) {
  19266. return new BABYLON.InstancedMesh(name, this);
  19267. };
  19268. /**
  19269. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  19270. * After this call, all the mesh instances have the same submeshes than the current mesh.
  19271. * This method returns nothing.
  19272. */
  19273. Mesh.prototype.synchronizeInstances = function () {
  19274. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  19275. var instance = this.instances[instanceIndex];
  19276. instance._syncSubMeshes();
  19277. }
  19278. };
  19279. /**
  19280. * Simplify the mesh according to the given array of settings.
  19281. * Function will return immediately and will simplify async. It returns nothing.
  19282. * @param settings a collection of simplification settings.
  19283. * @param parallelProcessing should all levels calculate parallel or one after the other.
  19284. * @param type the type of simplification to run.
  19285. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  19286. */
  19287. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  19288. if (parallelProcessing === void 0) { parallelProcessing = true; }
  19289. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  19290. this.getScene().simplificationQueue.addTask({
  19291. settings: settings,
  19292. parallelProcessing: parallelProcessing,
  19293. mesh: this,
  19294. simplificationType: simplificationType,
  19295. successCallback: successCallback
  19296. });
  19297. };
  19298. /**
  19299. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  19300. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  19301. * This should be used together with the simplification to avoid disappearing triangles.
  19302. * @param successCallback an optional success callback to be called after the optimization finished.
  19303. */
  19304. Mesh.prototype.optimizeIndices = function (successCallback) {
  19305. var _this = this;
  19306. var indices = this.getIndices();
  19307. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19308. var vectorPositions = [];
  19309. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  19310. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  19311. }
  19312. var dupes = [];
  19313. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  19314. var realPos = vectorPositions.length - 1 - iteration;
  19315. var testedPosition = vectorPositions[realPos];
  19316. for (var j = 0; j < realPos; ++j) {
  19317. var againstPosition = vectorPositions[j];
  19318. if (testedPosition.equals(againstPosition)) {
  19319. dupes[realPos] = j;
  19320. break;
  19321. }
  19322. }
  19323. }, function () {
  19324. for (var i = 0; i < indices.length; ++i) {
  19325. indices[i] = dupes[indices[i]] || indices[i];
  19326. }
  19327. //indices are now reordered
  19328. var originalSubMeshes = _this.subMeshes.slice(0);
  19329. _this.setIndices(indices);
  19330. _this.subMeshes = originalSubMeshes;
  19331. if (successCallback) {
  19332. successCallback(_this);
  19333. }
  19334. });
  19335. };
  19336. // Statics
  19337. /**
  19338. * Returns a new Mesh object what is a deep copy of the passed mesh.
  19339. * The parameter `parsedMesh` is the mesh to be copied.
  19340. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  19341. */
  19342. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  19343. var mesh = new Mesh(parsedMesh.name, scene);
  19344. mesh.id = parsedMesh.id;
  19345. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  19346. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  19347. if (parsedMesh.rotationQuaternion) {
  19348. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  19349. }
  19350. else if (parsedMesh.rotation) {
  19351. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  19352. }
  19353. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  19354. if (parsedMesh.localMatrix) {
  19355. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  19356. }
  19357. else if (parsedMesh.pivotMatrix) {
  19358. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  19359. }
  19360. mesh.setEnabled(parsedMesh.isEnabled);
  19361. mesh.isVisible = parsedMesh.isVisible;
  19362. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  19363. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  19364. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  19365. if (parsedMesh.applyFog !== undefined) {
  19366. mesh.applyFog = parsedMesh.applyFog;
  19367. }
  19368. if (parsedMesh.pickable !== undefined) {
  19369. mesh.isPickable = parsedMesh.pickable;
  19370. }
  19371. if (parsedMesh.alphaIndex !== undefined) {
  19372. mesh.alphaIndex = parsedMesh.alphaIndex;
  19373. }
  19374. mesh.receiveShadows = parsedMesh.receiveShadows;
  19375. mesh.billboardMode = parsedMesh.billboardMode;
  19376. if (parsedMesh.visibility !== undefined) {
  19377. mesh.visibility = parsedMesh.visibility;
  19378. }
  19379. mesh.checkCollisions = parsedMesh.checkCollisions;
  19380. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  19381. // freezeWorldMatrix
  19382. if (parsedMesh.freezeWorldMatrix) {
  19383. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  19384. }
  19385. // Parent
  19386. if (parsedMesh.parentId) {
  19387. mesh._waitingParentId = parsedMesh.parentId;
  19388. }
  19389. // Actions
  19390. if (parsedMesh.actions !== undefined) {
  19391. mesh._waitingActions = parsedMesh.actions;
  19392. }
  19393. // Geometry
  19394. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  19395. if (parsedMesh.delayLoadingFile) {
  19396. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  19397. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  19398. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  19399. if (parsedMesh._binaryInfo) {
  19400. mesh._binaryInfo = parsedMesh._binaryInfo;
  19401. }
  19402. mesh._delayInfo = [];
  19403. if (parsedMesh.hasUVs) {
  19404. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  19405. }
  19406. if (parsedMesh.hasUVs2) {
  19407. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  19408. }
  19409. if (parsedMesh.hasUVs3) {
  19410. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  19411. }
  19412. if (parsedMesh.hasUVs4) {
  19413. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  19414. }
  19415. if (parsedMesh.hasUVs5) {
  19416. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  19417. }
  19418. if (parsedMesh.hasUVs6) {
  19419. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  19420. }
  19421. if (parsedMesh.hasColors) {
  19422. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  19423. }
  19424. if (parsedMesh.hasMatricesIndices) {
  19425. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  19426. }
  19427. if (parsedMesh.hasMatricesWeights) {
  19428. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  19429. }
  19430. mesh._delayLoadingFunction = BABYLON.Geometry.ImportGeometry;
  19431. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  19432. mesh._checkDelayState();
  19433. }
  19434. }
  19435. else {
  19436. BABYLON.Geometry.ImportGeometry(parsedMesh, mesh);
  19437. }
  19438. // Material
  19439. if (parsedMesh.materialId) {
  19440. mesh.setMaterialByID(parsedMesh.materialId);
  19441. }
  19442. else {
  19443. mesh.material = null;
  19444. }
  19445. // Skeleton
  19446. if (parsedMesh.skeletonId > -1) {
  19447. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  19448. if (parsedMesh.numBoneInfluencers) {
  19449. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  19450. }
  19451. }
  19452. // Animations
  19453. if (parsedMesh.animations) {
  19454. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  19455. var parsedAnimation = parsedMesh.animations[animationIndex];
  19456. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  19457. }
  19458. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  19459. }
  19460. if (parsedMesh.autoAnimate) {
  19461. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  19462. }
  19463. // Layer Mask
  19464. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  19465. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  19466. }
  19467. else {
  19468. mesh.layerMask = 0x0FFFFFFF;
  19469. }
  19470. //(Deprecated) physics
  19471. if (parsedMesh.physicsImpostor) {
  19472. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  19473. mass: parsedMesh.physicsMass,
  19474. friction: parsedMesh.physicsFriction,
  19475. restitution: parsedMesh.physicsRestitution
  19476. }, scene);
  19477. }
  19478. // Instances
  19479. if (parsedMesh.instances) {
  19480. for (var index = 0; index < parsedMesh.instances.length; index++) {
  19481. var parsedInstance = parsedMesh.instances[index];
  19482. var instance = mesh.createInstance(parsedInstance.name);
  19483. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  19484. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  19485. if (parsedInstance.rotationQuaternion) {
  19486. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  19487. }
  19488. else if (parsedInstance.rotation) {
  19489. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  19490. }
  19491. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  19492. instance.checkCollisions = mesh.checkCollisions;
  19493. if (parsedMesh.animations) {
  19494. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  19495. parsedAnimation = parsedMesh.animations[animationIndex];
  19496. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  19497. }
  19498. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  19499. }
  19500. }
  19501. }
  19502. return mesh;
  19503. };
  19504. /**
  19505. * Creates a ribbon mesh.
  19506. * Please consider using the same method from the MeshBuilder class instead.
  19507. * 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.
  19508. *
  19509. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  19510. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  19511. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  19512. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  19513. * 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.
  19514. * 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.
  19515. * 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
  19516. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19517. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19518. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19519. */
  19520. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  19521. return BABYLON.MeshBuilder.CreateRibbon(name, {
  19522. pathArray: pathArray,
  19523. closeArray: closeArray,
  19524. closePath: closePath,
  19525. offset: offset,
  19526. updatable: updatable,
  19527. sideOrientation: sideOrientation,
  19528. instance: instance
  19529. }, scene);
  19530. };
  19531. /**
  19532. * Creates a plane polygonal mesh. By default, this is a disc.
  19533. * Please consider using the same method from the MeshBuilder class instead.
  19534. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  19535. * 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.
  19536. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19537. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19538. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19539. */
  19540. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  19541. var options = {
  19542. radius: radius,
  19543. tessellation: tessellation,
  19544. sideOrientation: sideOrientation,
  19545. updatable: updatable
  19546. };
  19547. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  19548. };
  19549. /**
  19550. * Creates a box mesh.
  19551. * Please consider using the same method from the MeshBuilder class instead.
  19552. * The parameter `size` sets the size (float) of each box side (default 1).
  19553. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19554. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19555. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19556. */
  19557. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  19558. var options = {
  19559. size: size,
  19560. sideOrientation: sideOrientation,
  19561. updatable: updatable
  19562. };
  19563. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  19564. };
  19565. /**
  19566. * Creates a sphere mesh.
  19567. * Please consider using the same method from the MeshBuilder class instead.
  19568. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  19569. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  19570. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19571. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19572. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19573. */
  19574. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  19575. var options = {
  19576. segments: segments,
  19577. diameterX: diameter,
  19578. diameterY: diameter,
  19579. diameterZ: diameter,
  19580. sideOrientation: sideOrientation,
  19581. updatable: updatable
  19582. };
  19583. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  19584. };
  19585. /**
  19586. * Creates a cylinder or a cone mesh.
  19587. * Please consider using the same method from the MeshBuilder class instead.
  19588. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  19589. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  19590. * 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.
  19591. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  19592. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  19593. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19594. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19595. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19596. */
  19597. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  19598. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  19599. if (scene !== undefined) {
  19600. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  19601. updatable = scene;
  19602. }
  19603. scene = subdivisions;
  19604. subdivisions = 1;
  19605. }
  19606. var options = {
  19607. height: height,
  19608. diameterTop: diameterTop,
  19609. diameterBottom: diameterBottom,
  19610. tessellation: tessellation,
  19611. subdivisions: subdivisions,
  19612. sideOrientation: sideOrientation,
  19613. updatable: updatable
  19614. };
  19615. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  19616. };
  19617. // Torus (Code from SharpDX.org)
  19618. /**
  19619. * Creates a torus mesh.
  19620. * Please consider using the same method from the MeshBuilder class instead.
  19621. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  19622. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  19623. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  19624. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19625. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19626. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19627. */
  19628. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  19629. var options = {
  19630. diameter: diameter,
  19631. thickness: thickness,
  19632. tessellation: tessellation,
  19633. sideOrientation: sideOrientation,
  19634. updatable: updatable
  19635. };
  19636. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  19637. };
  19638. /**
  19639. * Creates a torus knot mesh.
  19640. * Please consider using the same method from the MeshBuilder class instead.
  19641. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  19642. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  19643. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  19644. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  19645. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19646. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19647. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19648. */
  19649. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  19650. var options = {
  19651. radius: radius,
  19652. tube: tube,
  19653. radialSegments: radialSegments,
  19654. tubularSegments: tubularSegments,
  19655. p: p,
  19656. q: q,
  19657. sideOrientation: sideOrientation,
  19658. updatable: updatable
  19659. };
  19660. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  19661. };
  19662. /**
  19663. * Creates a line mesh.
  19664. * Please consider using the same method from the MeshBuilder class instead.
  19665. * 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.
  19666. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  19667. * The parameter `points` is an array successive Vector3.
  19668. * 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
  19669. * When updating an instance, remember that only point positions can change, not the number of points.
  19670. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19671. */
  19672. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  19673. var options = {
  19674. points: points,
  19675. updatable: updatable,
  19676. instance: instance
  19677. };
  19678. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  19679. };
  19680. /**
  19681. * Creates a dashed line mesh.
  19682. * Please consider using the same method from the MeshBuilder class instead.
  19683. * 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.
  19684. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  19685. * The parameter `points` is an array successive Vector3.
  19686. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  19687. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  19688. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  19689. * 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
  19690. * When updating an instance, remember that only point positions can change, not the number of points.
  19691. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19692. */
  19693. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  19694. var options = {
  19695. points: points,
  19696. dashSize: dashSize,
  19697. gapSize: gapSize,
  19698. dashNb: dashNb,
  19699. updatable: updatable,
  19700. instance: instance
  19701. };
  19702. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  19703. };
  19704. /**
  19705. * Creates an extruded shape mesh.
  19706. * 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.
  19707. * Please consider using the same method from the MeshBuilder class instead.
  19708. *
  19709. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  19710. * 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
  19711. * extruded along the Z axis.
  19712. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  19713. * 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.
  19714. * The parameter `scale` (float, default 1) is the value to scale the shape.
  19715. * 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
  19716. * 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
  19717. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  19718. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19719. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19720. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19721. */
  19722. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  19723. var options = {
  19724. shape: shape,
  19725. path: path,
  19726. scale: scale,
  19727. rotation: rotation,
  19728. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  19729. sideOrientation: sideOrientation,
  19730. instance: instance,
  19731. updatable: updatable
  19732. };
  19733. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  19734. };
  19735. /**
  19736. * Creates an custom extruded shape mesh.
  19737. * 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.
  19738. * Please consider using the same method from the MeshBuilder class instead.
  19739. *
  19740. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  19741. * 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
  19742. * extruded along the Z axis.
  19743. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  19744. * 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
  19745. * and the distance of this point from the begining of the path :
  19746. * ```javascript
  19747. * var rotationFunction = function(i, distance) {
  19748. * // do things
  19749. * return rotationValue; }
  19750. * ```
  19751. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  19752. * 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
  19753. * and the distance of this point from the begining of the path :
  19754. * ```javascript
  19755. * var scaleFunction = function(i, distance) {
  19756. * // do things
  19757. * return scaleValue;}
  19758. * ```
  19759. * It must returns a float value that will be the scale value applied to the shape on each path point.
  19760. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  19761. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  19762. * 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
  19763. * 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
  19764. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  19765. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19766. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19767. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19768. */
  19769. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  19770. var options = {
  19771. shape: shape,
  19772. path: path,
  19773. scaleFunction: scaleFunction,
  19774. rotationFunction: rotationFunction,
  19775. ribbonCloseArray: ribbonCloseArray,
  19776. ribbonClosePath: ribbonClosePath,
  19777. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  19778. sideOrientation: sideOrientation,
  19779. instance: instance,
  19780. updatable: updatable
  19781. };
  19782. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  19783. };
  19784. /**
  19785. * Creates lathe mesh.
  19786. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  19787. * Please consider using the same method from the MeshBuilder class instead.
  19788. * 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
  19789. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  19790. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  19791. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  19792. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19793. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19794. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19795. */
  19796. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  19797. var options = {
  19798. shape: shape,
  19799. radius: radius,
  19800. tessellation: tessellation,
  19801. sideOrientation: sideOrientation,
  19802. updatable: updatable
  19803. };
  19804. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  19805. };
  19806. /**
  19807. * Creates a plane mesh.
  19808. * Please consider using the same method from the MeshBuilder class instead.
  19809. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  19810. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19811. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19812. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19813. */
  19814. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  19815. var options = {
  19816. size: size,
  19817. width: size,
  19818. height: size,
  19819. sideOrientation: sideOrientation,
  19820. updatable: updatable
  19821. };
  19822. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  19823. };
  19824. /**
  19825. * Creates a ground mesh.
  19826. * Please consider using the same method from the MeshBuilder class instead.
  19827. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  19828. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  19829. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19830. */
  19831. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  19832. var options = {
  19833. width: width,
  19834. height: height,
  19835. subdivisions: subdivisions,
  19836. updatable: updatable
  19837. };
  19838. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  19839. };
  19840. /**
  19841. * Creates a tiled ground mesh.
  19842. * Please consider using the same method from the MeshBuilder class instead.
  19843. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  19844. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  19845. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  19846. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  19847. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  19848. * numbers of subdivisions on the ground width and height of each tile.
  19849. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19850. */
  19851. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  19852. var options = {
  19853. xmin: xmin,
  19854. zmin: zmin,
  19855. xmax: xmax,
  19856. zmax: zmax,
  19857. subdivisions: subdivisions,
  19858. precision: precision,
  19859. updatable: updatable
  19860. };
  19861. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  19862. };
  19863. /**
  19864. * Creates a ground mesh from a height map.
  19865. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  19866. * Please consider using the same method from the MeshBuilder class instead.
  19867. * The parameter `url` sets the URL of the height map image resource.
  19868. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  19869. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  19870. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  19871. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  19872. * 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).
  19873. * This function is passed the newly built mesh :
  19874. * ```javascript
  19875. * function(mesh) { // do things
  19876. * return; }
  19877. * ```
  19878. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19879. */
  19880. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  19881. var options = {
  19882. width: width,
  19883. height: height,
  19884. subdivisions: subdivisions,
  19885. minHeight: minHeight,
  19886. maxHeight: maxHeight,
  19887. updatable: updatable,
  19888. onReady: onReady
  19889. };
  19890. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  19891. };
  19892. /**
  19893. * Creates a tube mesh.
  19894. * 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.
  19895. * Please consider using the same method from the MeshBuilder class instead.
  19896. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  19897. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  19898. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  19899. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  19900. * 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.
  19901. * It must return a radius value (positive float) :
  19902. * ```javascript
  19903. * var radiusFunction = function(i, distance) {
  19904. * // do things
  19905. * return radius; }
  19906. * ```
  19907. * 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
  19908. * 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
  19909. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19910. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19911. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19912. */
  19913. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  19914. var options = {
  19915. path: path,
  19916. radius: radius,
  19917. tessellation: tessellation,
  19918. radiusFunction: radiusFunction,
  19919. arc: 1,
  19920. cap: cap,
  19921. updatable: updatable,
  19922. sideOrientation: sideOrientation,
  19923. instance: instance
  19924. };
  19925. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  19926. };
  19927. /**
  19928. * Creates a polyhedron mesh.
  19929. * Please consider using the same method from the MeshBuilder class instead.
  19930. * 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
  19931. * to choose the wanted type.
  19932. * The parameter `size` (positive float, default 1) sets the polygon size.
  19933. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  19934. * 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`.
  19935. * 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
  19936. * 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)`).
  19937. * 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
  19938. * 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.
  19939. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19940. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19941. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19942. */
  19943. Mesh.CreatePolyhedron = function (name, options, scene) {
  19944. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  19945. };
  19946. /**
  19947. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  19948. * Please consider using the same method from the MeshBuilder class instead.
  19949. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  19950. * 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`).
  19951. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  19952. * 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.
  19953. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19954. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19955. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19956. */
  19957. Mesh.CreateIcoSphere = function (name, options, scene) {
  19958. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  19959. };
  19960. /**
  19961. * Creates a decal mesh.
  19962. * Please consider using the same method from the MeshBuilder class instead.
  19963. * 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.
  19964. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  19965. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  19966. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  19967. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  19968. */
  19969. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  19970. var options = {
  19971. position: position,
  19972. normal: normal,
  19973. size: size,
  19974. angle: angle
  19975. };
  19976. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  19977. };
  19978. // Skeletons
  19979. /**
  19980. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  19981. */
  19982. Mesh.prototype.setPositionsForCPUSkinning = function () {
  19983. var source;
  19984. if (!this._sourcePositions) {
  19985. source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19986. this._sourcePositions = new Float32Array(source);
  19987. if (!this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable()) {
  19988. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  19989. }
  19990. }
  19991. return this._sourcePositions;
  19992. };
  19993. /**
  19994. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  19995. */
  19996. Mesh.prototype.setNormalsForCPUSkinning = function () {
  19997. var source;
  19998. if (!this._sourceNormals) {
  19999. source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20000. this._sourceNormals = new Float32Array(source);
  20001. if (!this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable()) {
  20002. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  20003. }
  20004. }
  20005. return this._sourceNormals;
  20006. };
  20007. /**
  20008. * Update the vertex buffers by applying transformation from the bones
  20009. * @param {skeleton} skeleton to apply
  20010. */
  20011. Mesh.prototype.applySkeleton = function (skeleton) {
  20012. if (!this.geometry) {
  20013. return;
  20014. }
  20015. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  20016. return;
  20017. }
  20018. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  20019. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  20020. return this;
  20021. }
  20022. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  20023. return this;
  20024. }
  20025. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  20026. return this;
  20027. }
  20028. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  20029. return this;
  20030. }
  20031. if (!this._sourcePositions) {
  20032. this.setPositionsForCPUSkinning();
  20033. }
  20034. if (!this._sourceNormals) {
  20035. this.setNormalsForCPUSkinning();
  20036. }
  20037. // positionsData checks for not being Float32Array will only pass at most once
  20038. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20039. if (!(positionsData instanceof Float32Array)) {
  20040. positionsData = new Float32Array(positionsData);
  20041. }
  20042. // normalsData checks for not being Float32Array will only pass at most once
  20043. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20044. if (!(normalsData instanceof Float32Array)) {
  20045. normalsData = new Float32Array(normalsData);
  20046. }
  20047. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  20048. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  20049. var needExtras = this.numBoneInfluencers > 4;
  20050. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  20051. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  20052. var skeletonMatrices = skeleton.getTransformMatrices(this);
  20053. var tempVector3 = BABYLON.Vector3.Zero();
  20054. var finalMatrix = new BABYLON.Matrix();
  20055. var tempMatrix = new BABYLON.Matrix();
  20056. var matWeightIdx = 0;
  20057. var inf;
  20058. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  20059. var weight;
  20060. for (inf = 0; inf < 4; inf++) {
  20061. weight = matricesWeightsData[matWeightIdx + inf];
  20062. if (weight > 0) {
  20063. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  20064. finalMatrix.addToSelf(tempMatrix);
  20065. }
  20066. else
  20067. break;
  20068. }
  20069. if (needExtras) {
  20070. for (inf = 0; inf < 4; inf++) {
  20071. weight = matricesWeightsExtraData[matWeightIdx + inf];
  20072. if (weight > 0) {
  20073. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  20074. finalMatrix.addToSelf(tempMatrix);
  20075. }
  20076. else
  20077. break;
  20078. }
  20079. }
  20080. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  20081. tempVector3.toArray(positionsData, index);
  20082. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  20083. tempVector3.toArray(normalsData, index);
  20084. finalMatrix.reset();
  20085. }
  20086. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  20087. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  20088. return this;
  20089. };
  20090. // Tools
  20091. /**
  20092. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  20093. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  20094. */
  20095. Mesh.MinMax = function (meshes) {
  20096. var minVector = null;
  20097. var maxVector = null;
  20098. for (var i in meshes) {
  20099. var mesh = meshes[i];
  20100. var boundingBox = mesh.getBoundingInfo().boundingBox;
  20101. if (!minVector) {
  20102. minVector = boundingBox.minimumWorld;
  20103. maxVector = boundingBox.maximumWorld;
  20104. continue;
  20105. }
  20106. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  20107. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  20108. }
  20109. return {
  20110. min: minVector,
  20111. max: maxVector
  20112. };
  20113. };
  20114. /**
  20115. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  20116. */
  20117. Mesh.Center = function (meshesOrMinMaxVector) {
  20118. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : Mesh.MinMax(meshesOrMinMaxVector);
  20119. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  20120. };
  20121. /**
  20122. * Merge the array of meshes into a single mesh for performance reasons.
  20123. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  20124. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  20125. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  20126. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  20127. */
  20128. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass) {
  20129. if (disposeSource === void 0) { disposeSource = true; }
  20130. var index;
  20131. if (!allow32BitsIndices) {
  20132. var totalVertices = 0;
  20133. // Counting vertices
  20134. for (index = 0; index < meshes.length; index++) {
  20135. if (meshes[index]) {
  20136. totalVertices += meshes[index].getTotalVertices();
  20137. if (totalVertices > 65536) {
  20138. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  20139. return null;
  20140. }
  20141. }
  20142. }
  20143. }
  20144. // Merge
  20145. var vertexData;
  20146. var otherVertexData;
  20147. var source;
  20148. for (index = 0; index < meshes.length; index++) {
  20149. if (meshes[index]) {
  20150. meshes[index].computeWorldMatrix(true);
  20151. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  20152. otherVertexData.transform(meshes[index].getWorldMatrix());
  20153. if (vertexData) {
  20154. vertexData.merge(otherVertexData);
  20155. }
  20156. else {
  20157. vertexData = otherVertexData;
  20158. source = meshes[index];
  20159. }
  20160. }
  20161. }
  20162. if (!meshSubclass) {
  20163. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  20164. }
  20165. vertexData.applyToMesh(meshSubclass);
  20166. // Setting properties
  20167. meshSubclass.material = source.material;
  20168. meshSubclass.checkCollisions = source.checkCollisions;
  20169. // Cleaning
  20170. if (disposeSource) {
  20171. for (index = 0; index < meshes.length; index++) {
  20172. if (meshes[index]) {
  20173. meshes[index].dispose();
  20174. }
  20175. }
  20176. }
  20177. return meshSubclass;
  20178. };
  20179. // Consts
  20180. Mesh._FRONTSIDE = 0;
  20181. Mesh._BACKSIDE = 1;
  20182. Mesh._DOUBLESIDE = 2;
  20183. Mesh._DEFAULTSIDE = 0;
  20184. Mesh._NO_CAP = 0;
  20185. Mesh._CAP_START = 1;
  20186. Mesh._CAP_END = 2;
  20187. Mesh._CAP_ALL = 3;
  20188. return Mesh;
  20189. }(BABYLON.AbstractMesh));
  20190. BABYLON.Mesh = Mesh;
  20191. })(BABYLON || (BABYLON = {}));
  20192. var BABYLON;
  20193. (function (BABYLON) {
  20194. var SubMesh = (function () {
  20195. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  20196. if (createBoundingBox === void 0) { createBoundingBox = true; }
  20197. this.materialIndex = materialIndex;
  20198. this.verticesStart = verticesStart;
  20199. this.verticesCount = verticesCount;
  20200. this.indexStart = indexStart;
  20201. this.indexCount = indexCount;
  20202. this._renderId = 0;
  20203. this._mesh = mesh;
  20204. this._renderingMesh = renderingMesh || mesh;
  20205. mesh.subMeshes.push(this);
  20206. this._trianglePlanes = [];
  20207. this._id = mesh.subMeshes.length - 1;
  20208. if (createBoundingBox) {
  20209. this.refreshBoundingInfo();
  20210. mesh.computeWorldMatrix(true);
  20211. }
  20212. }
  20213. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  20214. get: function () {
  20215. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  20216. },
  20217. enumerable: true,
  20218. configurable: true
  20219. });
  20220. SubMesh.prototype.getBoundingInfo = function () {
  20221. if (this.IsGlobal) {
  20222. return this._mesh.getBoundingInfo();
  20223. }
  20224. return this._boundingInfo;
  20225. };
  20226. SubMesh.prototype.getMesh = function () {
  20227. return this._mesh;
  20228. };
  20229. SubMesh.prototype.getRenderingMesh = function () {
  20230. return this._renderingMesh;
  20231. };
  20232. SubMesh.prototype.getMaterial = function () {
  20233. var rootMaterial = this._renderingMesh.material;
  20234. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  20235. var multiMaterial = rootMaterial;
  20236. return multiMaterial.getSubMaterial(this.materialIndex);
  20237. }
  20238. if (!rootMaterial) {
  20239. return this._mesh.getScene().defaultMaterial;
  20240. }
  20241. return rootMaterial;
  20242. };
  20243. // Methods
  20244. SubMesh.prototype.refreshBoundingInfo = function () {
  20245. this._lastColliderWorldVertices = null;
  20246. if (this.IsGlobal) {
  20247. return;
  20248. }
  20249. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20250. if (!data) {
  20251. this._boundingInfo = this._mesh._boundingInfo;
  20252. return;
  20253. }
  20254. var indices = this._renderingMesh.getIndices();
  20255. var extend;
  20256. //is this the only submesh?
  20257. if (this.indexStart === 0 && this.indexCount === indices.length) {
  20258. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  20259. extend = { minimum: this._renderingMesh.getBoundingInfo().minimum.clone(), maximum: this._renderingMesh.getBoundingInfo().maximum.clone() };
  20260. }
  20261. else {
  20262. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  20263. }
  20264. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  20265. };
  20266. SubMesh.prototype._checkCollision = function (collider) {
  20267. return this.getBoundingInfo()._checkCollision(collider);
  20268. };
  20269. SubMesh.prototype.updateBoundingInfo = function (world) {
  20270. if (!this.getBoundingInfo()) {
  20271. this.refreshBoundingInfo();
  20272. }
  20273. this.getBoundingInfo().update(world);
  20274. };
  20275. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  20276. return this.getBoundingInfo().isInFrustum(frustumPlanes);
  20277. };
  20278. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  20279. return this.getBoundingInfo().isCompletelyInFrustum(frustumPlanes);
  20280. };
  20281. SubMesh.prototype.render = function (enableAlphaMode) {
  20282. this._renderingMesh.render(this, enableAlphaMode);
  20283. };
  20284. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  20285. if (!this._linesIndexBuffer) {
  20286. var linesIndices = [];
  20287. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  20288. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  20289. }
  20290. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  20291. this.linesIndexCount = linesIndices.length;
  20292. }
  20293. return this._linesIndexBuffer;
  20294. };
  20295. SubMesh.prototype.canIntersects = function (ray) {
  20296. return ray.intersectsBox(this.getBoundingInfo().boundingBox);
  20297. };
  20298. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  20299. var intersectInfo = null;
  20300. // LineMesh first as it's also a Mesh...
  20301. if (this._mesh instanceof BABYLON.LinesMesh) {
  20302. var lineMesh = this._mesh;
  20303. // Line test
  20304. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  20305. var p0 = positions[indices[index]];
  20306. var p1 = positions[indices[index + 1]];
  20307. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  20308. if (length < 0) {
  20309. continue;
  20310. }
  20311. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  20312. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  20313. if (fastCheck) {
  20314. break;
  20315. }
  20316. }
  20317. }
  20318. }
  20319. else {
  20320. // Triangles test
  20321. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  20322. var p0 = positions[indices[index]];
  20323. var p1 = positions[indices[index + 1]];
  20324. var p2 = positions[indices[index + 2]];
  20325. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  20326. if (currentIntersectInfo) {
  20327. if (currentIntersectInfo.distance < 0) {
  20328. continue;
  20329. }
  20330. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  20331. intersectInfo = currentIntersectInfo;
  20332. intersectInfo.faceId = index / 3;
  20333. if (fastCheck) {
  20334. break;
  20335. }
  20336. }
  20337. }
  20338. }
  20339. }
  20340. return intersectInfo;
  20341. };
  20342. // Clone
  20343. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  20344. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  20345. if (!this.IsGlobal) {
  20346. result._boundingInfo = new BABYLON.BoundingInfo(this.getBoundingInfo().minimum, this.getBoundingInfo().maximum);
  20347. }
  20348. return result;
  20349. };
  20350. // Dispose
  20351. SubMesh.prototype.dispose = function () {
  20352. if (this._linesIndexBuffer) {
  20353. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  20354. this._linesIndexBuffer = null;
  20355. }
  20356. // Remove from mesh
  20357. var index = this._mesh.subMeshes.indexOf(this);
  20358. this._mesh.subMeshes.splice(index, 1);
  20359. };
  20360. // Statics
  20361. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  20362. var minVertexIndex = Number.MAX_VALUE;
  20363. var maxVertexIndex = -Number.MAX_VALUE;
  20364. renderingMesh = renderingMesh || mesh;
  20365. var indices = renderingMesh.getIndices();
  20366. for (var index = startIndex; index < startIndex + indexCount; index++) {
  20367. var vertexIndex = indices[index];
  20368. if (vertexIndex < minVertexIndex)
  20369. minVertexIndex = vertexIndex;
  20370. if (vertexIndex > maxVertexIndex)
  20371. maxVertexIndex = vertexIndex;
  20372. }
  20373. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  20374. };
  20375. return SubMesh;
  20376. }());
  20377. BABYLON.SubMesh = SubMesh;
  20378. })(BABYLON || (BABYLON = {}));
  20379. var BABYLON;
  20380. (function (BABYLON) {
  20381. var MeshBuilder = (function () {
  20382. function MeshBuilder() {
  20383. }
  20384. /**
  20385. * Creates a box mesh.
  20386. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  20387. * The parameter `size` sets the size (float) of each box side (default 1).
  20388. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  20389. * 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).
  20390. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  20391. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20392. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20393. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20394. */
  20395. MeshBuilder.CreateBox = function (name, options, scene) {
  20396. var box = new BABYLON.Mesh(name, scene);
  20397. var vertexData = BABYLON.VertexData.CreateBox(options);
  20398. vertexData.applyToMesh(box, options.updatable);
  20399. return box;
  20400. };
  20401. /**
  20402. * Creates a sphere mesh.
  20403. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  20404. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  20405. * 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`).
  20406. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  20407. * 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
  20408. * 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).
  20409. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20410. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20411. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20412. */
  20413. MeshBuilder.CreateSphere = function (name, options, scene) {
  20414. var sphere = new BABYLON.Mesh(name, scene);
  20415. var vertexData = BABYLON.VertexData.CreateSphere(options);
  20416. vertexData.applyToMesh(sphere, options.updatable);
  20417. return sphere;
  20418. };
  20419. /**
  20420. * Creates a plane polygonal mesh. By default, this is a disc.
  20421. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  20422. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  20423. * 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.
  20424. * 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
  20425. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20426. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20427. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20428. */
  20429. MeshBuilder.CreateDisc = function (name, options, scene) {
  20430. var disc = new BABYLON.Mesh(name, scene);
  20431. var vertexData = BABYLON.VertexData.CreateDisc(options);
  20432. vertexData.applyToMesh(disc, options.updatable);
  20433. return disc;
  20434. };
  20435. /**
  20436. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  20437. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  20438. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  20439. * 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`).
  20440. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  20441. * 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.
  20442. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20443. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20444. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20445. */
  20446. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  20447. var sphere = new BABYLON.Mesh(name, scene);
  20448. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  20449. vertexData.applyToMesh(sphere, options.updatable);
  20450. return sphere;
  20451. };
  20452. ;
  20453. /**
  20454. * Creates a ribbon mesh.
  20455. * 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.
  20456. *
  20457. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  20458. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  20459. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  20460. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  20461. * 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.
  20462. * 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.
  20463. * 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
  20464. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20465. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20466. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  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.CreateRibbon = function (name, options, scene) {
  20470. var pathArray = options.pathArray;
  20471. var closeArray = options.closeArray;
  20472. var closePath = options.closePath;
  20473. var offset = options.offset;
  20474. var sideOrientation = options.sideOrientation;
  20475. var instance = options.instance;
  20476. var updatable = options.updatable;
  20477. if (instance) {
  20478. // positionFunction : ribbon case
  20479. // only pathArray and sideOrientation parameters are taken into account for positions update
  20480. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  20481. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  20482. var positionFunction = function (positions) {
  20483. var minlg = pathArray[0].length;
  20484. var i = 0;
  20485. var ns = (instance.sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  20486. for (var si = 1; si <= ns; si++) {
  20487. for (var p = 0; p < pathArray.length; p++) {
  20488. var path = pathArray[p];
  20489. var l = path.length;
  20490. minlg = (minlg < l) ? minlg : l;
  20491. var j = 0;
  20492. while (j < minlg) {
  20493. positions[i] = path[j].x;
  20494. positions[i + 1] = path[j].y;
  20495. positions[i + 2] = path[j].z;
  20496. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  20497. BABYLON.Tmp.Vector3[0].x = path[j].x;
  20498. }
  20499. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  20500. BABYLON.Tmp.Vector3[1].x = path[j].x;
  20501. }
  20502. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  20503. BABYLON.Tmp.Vector3[0].y = path[j].y;
  20504. }
  20505. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  20506. BABYLON.Tmp.Vector3[1].y = path[j].y;
  20507. }
  20508. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  20509. BABYLON.Tmp.Vector3[0].z = path[j].z;
  20510. }
  20511. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  20512. BABYLON.Tmp.Vector3[1].z = path[j].z;
  20513. }
  20514. j++;
  20515. i += 3;
  20516. }
  20517. if (instance._closePath) {
  20518. positions[i] = path[0].x;
  20519. positions[i + 1] = path[0].y;
  20520. positions[i + 2] = path[0].z;
  20521. i += 3;
  20522. }
  20523. }
  20524. }
  20525. };
  20526. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20527. positionFunction(positions);
  20528. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  20529. instance._boundingInfo.update(instance._worldMatrix);
  20530. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  20531. if (!(instance.areNormalsFrozen)) {
  20532. var indices = instance.getIndices();
  20533. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20534. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  20535. if (instance._closePath) {
  20536. var indexFirst = 0;
  20537. var indexLast = 0;
  20538. for (var p = 0; p < pathArray.length; p++) {
  20539. indexFirst = instance._idx[p] * 3;
  20540. if (p + 1 < pathArray.length) {
  20541. indexLast = (instance._idx[p + 1] - 1) * 3;
  20542. }
  20543. else {
  20544. indexLast = normals.length - 3;
  20545. }
  20546. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  20547. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  20548. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  20549. normals[indexLast] = normals[indexFirst];
  20550. normals[indexLast + 1] = normals[indexFirst + 1];
  20551. normals[indexLast + 2] = normals[indexFirst + 2];
  20552. }
  20553. }
  20554. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  20555. }
  20556. return instance;
  20557. }
  20558. else {
  20559. var ribbon = new BABYLON.Mesh(name, scene);
  20560. ribbon.sideOrientation = sideOrientation;
  20561. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  20562. if (closePath) {
  20563. ribbon._idx = vertexData._idx;
  20564. }
  20565. ribbon._closePath = closePath;
  20566. ribbon._closeArray = closeArray;
  20567. vertexData.applyToMesh(ribbon, updatable);
  20568. return ribbon;
  20569. }
  20570. };
  20571. /**
  20572. * Creates a cylinder or a cone mesh.
  20573. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  20574. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  20575. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  20576. * 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.
  20577. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  20578. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  20579. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  20580. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  20581. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  20582. * 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).
  20583. * 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
  20584. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  20585. * 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
  20586. * 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.
  20587. * If `enclose` is false, a ring surface is one element.
  20588. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  20589. * 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
  20590. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20591. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20592. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20593. */
  20594. MeshBuilder.CreateCylinder = function (name, options, scene) {
  20595. var cylinder = new BABYLON.Mesh(name, scene);
  20596. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  20597. vertexData.applyToMesh(cylinder, options.updatable);
  20598. return cylinder;
  20599. };
  20600. /**
  20601. * Creates a torus mesh.
  20602. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  20603. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  20604. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  20605. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  20606. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20607. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20608. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20609. */
  20610. MeshBuilder.CreateTorus = function (name, options, scene) {
  20611. var torus = new BABYLON.Mesh(name, scene);
  20612. var vertexData = BABYLON.VertexData.CreateTorus(options);
  20613. vertexData.applyToMesh(torus, options.updatable);
  20614. return torus;
  20615. };
  20616. /**
  20617. * Creates a torus knot mesh.
  20618. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  20619. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  20620. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  20621. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  20622. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  20623. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20624. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20625. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20626. */
  20627. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  20628. var torusKnot = new BABYLON.Mesh(name, scene);
  20629. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  20630. vertexData.applyToMesh(torusKnot, options.updatable);
  20631. return torusKnot;
  20632. };
  20633. /**
  20634. * Creates a line system mesh.
  20635. * A line system is a pool of many lines gathered in a single mesh.
  20636. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  20637. * 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.
  20638. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  20639. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  20640. * 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
  20641. * 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
  20642. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  20643. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20644. */
  20645. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  20646. var instance = options.instance;
  20647. var lines = options.lines;
  20648. if (instance) {
  20649. var positionFunction = function (positions) {
  20650. var i = 0;
  20651. for (var l = 0; l < lines.length; l++) {
  20652. var points = lines[l];
  20653. for (var p = 0; p < points.length; p++) {
  20654. positions[i] = points[p].x;
  20655. positions[i + 1] = points[p].y;
  20656. positions[i + 2] = points[p].z;
  20657. i += 3;
  20658. }
  20659. }
  20660. };
  20661. instance.updateMeshPositions(positionFunction, false);
  20662. return instance;
  20663. }
  20664. // line system creation
  20665. var lineSystem = new BABYLON.LinesMesh(name, scene);
  20666. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  20667. vertexData.applyToMesh(lineSystem, options.updatable);
  20668. return lineSystem;
  20669. };
  20670. /**
  20671. * Creates a line mesh.
  20672. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  20673. * 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.
  20674. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  20675. * The parameter `points` is an array successive Vector3.
  20676. * 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
  20677. * When updating an instance, remember that only point positions can change, not the number of points.
  20678. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20679. */
  20680. MeshBuilder.CreateLines = function (name, options, scene) {
  20681. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance }, scene);
  20682. return lines;
  20683. };
  20684. /**
  20685. * Creates a dashed line mesh.
  20686. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  20687. * 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.
  20688. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  20689. * The parameter `points` is an array successive Vector3.
  20690. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  20691. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  20692. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  20693. * 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
  20694. * When updating an instance, remember that only point positions can change, not the number of points.
  20695. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20696. */
  20697. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  20698. var points = options.points;
  20699. var instance = options.instance;
  20700. var gapSize = options.gapSize;
  20701. var dashNb = options.dashNb;
  20702. var dashSize = options.dashSize;
  20703. if (instance) {
  20704. var positionFunction = function (positions) {
  20705. var curvect = BABYLON.Vector3.Zero();
  20706. var nbSeg = positions.length / 6;
  20707. var lg = 0;
  20708. var nb = 0;
  20709. var shft = 0;
  20710. var dashshft = 0;
  20711. var curshft = 0;
  20712. var p = 0;
  20713. var i = 0;
  20714. var j = 0;
  20715. for (i = 0; i < points.length - 1; i++) {
  20716. points[i + 1].subtractToRef(points[i], curvect);
  20717. lg += curvect.length();
  20718. }
  20719. shft = lg / nbSeg;
  20720. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  20721. for (i = 0; i < points.length - 1; i++) {
  20722. points[i + 1].subtractToRef(points[i], curvect);
  20723. nb = Math.floor(curvect.length() / shft);
  20724. curvect.normalize();
  20725. j = 0;
  20726. while (j < nb && p < positions.length) {
  20727. curshft = shft * j;
  20728. positions[p] = points[i].x + curshft * curvect.x;
  20729. positions[p + 1] = points[i].y + curshft * curvect.y;
  20730. positions[p + 2] = points[i].z + curshft * curvect.z;
  20731. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  20732. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  20733. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  20734. p += 6;
  20735. j++;
  20736. }
  20737. }
  20738. while (p < positions.length) {
  20739. positions[p] = points[i].x;
  20740. positions[p + 1] = points[i].y;
  20741. positions[p + 2] = points[i].z;
  20742. p += 3;
  20743. }
  20744. };
  20745. instance.updateMeshPositions(positionFunction, false);
  20746. return instance;
  20747. }
  20748. // dashed lines creation
  20749. var dashedLines = new BABYLON.LinesMesh(name, scene);
  20750. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  20751. vertexData.applyToMesh(dashedLines, options.updatable);
  20752. dashedLines.dashSize = dashSize;
  20753. dashedLines.gapSize = gapSize;
  20754. return dashedLines;
  20755. };
  20756. /**
  20757. * Creates an extruded shape mesh.
  20758. * 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.
  20759. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  20760. *
  20761. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  20762. * 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
  20763. * extruded along the Z axis.
  20764. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  20765. * 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.
  20766. * The parameter `scale` (float, default 1) is the value to scale the shape.
  20767. * 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
  20768. * 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
  20769. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  20770. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20771. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20772. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  20773. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20774. */
  20775. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  20776. var path = options.path;
  20777. var shape = options.shape;
  20778. var scale = options.scale || 1;
  20779. var rotation = options.rotation || 0;
  20780. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  20781. var updatable = options.updatable;
  20782. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  20783. var instance = options.instance;
  20784. var invertUV = options.invertUV || false;
  20785. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, instance, invertUV);
  20786. };
  20787. /**
  20788. * Creates an custom extruded shape mesh.
  20789. * 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.
  20790. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  20791. *
  20792. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  20793. * 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
  20794. * extruded along the Z axis.
  20795. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  20796. * 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
  20797. * and the distance of this point from the begining of the path :
  20798. * ```javascript
  20799. * var rotationFunction = function(i, distance) {
  20800. * // do things
  20801. * return rotationValue; }
  20802. * ```
  20803. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  20804. * 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
  20805. * and the distance of this point from the begining of the path :
  20806. * ```javascript
  20807. * var scaleFunction = function(i, distance) {
  20808. * // do things
  20809. * return scaleValue;}
  20810. * ```
  20811. * It must returns a float value that will be the scale value applied to the shape on each path point.
  20812. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  20813. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  20814. * 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
  20815. * 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
  20816. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  20817. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20818. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20819. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  20820. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20821. */
  20822. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  20823. var path = options.path;
  20824. var shape = options.shape;
  20825. var scaleFunction = options.scaleFunction || (function () { return 1; });
  20826. var rotationFunction = options.rotationFunction || (function () { return 0; });
  20827. var ribbonCloseArray = options.ribbonCloseArray || false;
  20828. var ribbonClosePath = options.ribbonClosePath || false;
  20829. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  20830. var updatable = options.updatable;
  20831. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  20832. var instance = options.instance;
  20833. var invertUV = options.invertUV || false;
  20834. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, instance, invertUV);
  20835. };
  20836. /**
  20837. * Creates lathe mesh.
  20838. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  20839. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  20840. *
  20841. * 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
  20842. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  20843. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  20844. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  20845. * 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.
  20846. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  20847. * 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
  20848. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20849. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20850. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  20851. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20852. */
  20853. MeshBuilder.CreateLathe = function (name, options, scene) {
  20854. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  20855. var closed = (options.closed === undefined) ? true : options.closed;
  20856. var shape = options.shape;
  20857. var radius = options.radius || 1;
  20858. var tessellation = options.tessellation || 64;
  20859. var updatable = options.updatable;
  20860. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  20861. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  20862. var pi2 = Math.PI * 2;
  20863. var paths = new Array();
  20864. var invertUV = options.invertUV || false;
  20865. var i = 0;
  20866. var p = 0;
  20867. var step = pi2 / tessellation * arc;
  20868. var rotated;
  20869. var path = new Array();
  20870. ;
  20871. for (i = 0; i <= tessellation; i++) {
  20872. var path = [];
  20873. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  20874. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  20875. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  20876. }
  20877. for (p = 0; p < shape.length; p++) {
  20878. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  20879. path.push(rotated);
  20880. }
  20881. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  20882. 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));
  20883. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  20884. }
  20885. paths.push(path);
  20886. }
  20887. // lathe ribbon
  20888. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV }, scene);
  20889. return lathe;
  20890. };
  20891. /**
  20892. * Creates a plane mesh.
  20893. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  20894. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  20895. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  20896. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  20897. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20898. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20899. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20900. */
  20901. MeshBuilder.CreatePlane = function (name, options, scene) {
  20902. var plane = new BABYLON.Mesh(name, scene);
  20903. var vertexData = BABYLON.VertexData.CreatePlane(options);
  20904. vertexData.applyToMesh(plane, options.updatable);
  20905. if (options.sourcePlane) {
  20906. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  20907. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  20908. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  20909. plane.rotate(vectorProduct, product);
  20910. }
  20911. return plane;
  20912. };
  20913. /**
  20914. * Creates a ground mesh.
  20915. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  20916. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  20917. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  20918. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20919. */
  20920. MeshBuilder.CreateGround = function (name, options, scene) {
  20921. var ground = new BABYLON.GroundMesh(name, scene);
  20922. ground._setReady(false);
  20923. ground._subdivisions = options.subdivisions || 1;
  20924. ground._width = options.width || 1;
  20925. ground._height = options.height || 1;
  20926. ground._maxX = ground._width / 2;
  20927. ground._maxZ = ground._height / 2;
  20928. ground._minX = -ground._maxX;
  20929. ground._minZ = -ground._maxZ;
  20930. var vertexData = BABYLON.VertexData.CreateGround(options);
  20931. vertexData.applyToMesh(ground, options.updatable);
  20932. ground._setReady(true);
  20933. return ground;
  20934. };
  20935. /**
  20936. * Creates a tiled ground mesh.
  20937. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  20938. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  20939. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  20940. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  20941. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  20942. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  20943. * numbers of subdivisions on the ground width and height of each tile.
  20944. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20945. */
  20946. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  20947. var tiledGround = new BABYLON.Mesh(name, scene);
  20948. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  20949. vertexData.applyToMesh(tiledGround, options.updatable);
  20950. return tiledGround;
  20951. };
  20952. /**
  20953. * Creates a ground mesh from a height map.
  20954. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  20955. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  20956. * The parameter `url` sets the URL of the height map image resource.
  20957. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  20958. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  20959. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  20960. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  20961. * 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).
  20962. * This function is passed the newly built mesh :
  20963. * ```javascript
  20964. * function(mesh) { // do things
  20965. * return; }
  20966. * ```
  20967. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20968. */
  20969. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  20970. var width = options.width || 10.0;
  20971. var height = options.height || 10.0;
  20972. var subdivisions = options.subdivisions || 1 | 0;
  20973. var minHeight = options.minHeight || 0.0;
  20974. var maxHeight = options.maxHeight || 10.0;
  20975. var updatable = options.updatable;
  20976. var onReady = options.onReady;
  20977. var ground = new BABYLON.GroundMesh(name, scene);
  20978. ground._subdivisions = subdivisions;
  20979. ground._width = width;
  20980. ground._height = height;
  20981. ground._maxX = ground._width / 2.0;
  20982. ground._maxZ = ground._height / 2.0;
  20983. ground._minX = -ground._maxX;
  20984. ground._minZ = -ground._maxZ;
  20985. ground._setReady(false);
  20986. var onload = function (img) {
  20987. // Getting height map data
  20988. var canvas = document.createElement("canvas");
  20989. var context = canvas.getContext("2d");
  20990. var bufferWidth = img.width;
  20991. var bufferHeight = img.height;
  20992. canvas.width = bufferWidth;
  20993. canvas.height = bufferHeight;
  20994. context.drawImage(img, 0, 0);
  20995. // Create VertexData from map data
  20996. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  20997. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  20998. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  20999. width: width, height: height,
  21000. subdivisions: subdivisions,
  21001. minHeight: minHeight, maxHeight: maxHeight,
  21002. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  21003. });
  21004. vertexData.applyToMesh(ground, updatable);
  21005. ground._setReady(true);
  21006. //execute ready callback, if set
  21007. if (onReady) {
  21008. onReady(ground);
  21009. }
  21010. };
  21011. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  21012. return ground;
  21013. };
  21014. /**
  21015. * Creates a tube mesh.
  21016. * 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.
  21017. *
  21018. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  21019. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  21020. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  21021. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  21022. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  21023. * 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.
  21024. * It must return a radius value (positive float) :
  21025. * ```javascript
  21026. * var radiusFunction = function(i, distance) {
  21027. * // do things
  21028. * return radius; }
  21029. * ```
  21030. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  21031. * 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
  21032. * 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
  21033. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21034. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21035. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  21036. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21037. */
  21038. MeshBuilder.CreateTube = function (name, options, scene) {
  21039. var path = options.path;
  21040. var radius = options.radius || 1.0;
  21041. var tessellation = options.tessellation || 64 | 0;
  21042. var radiusFunction = options.radiusFunction;
  21043. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  21044. var invertUV = options.invertUV || false;
  21045. var updatable = options.updatable;
  21046. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  21047. var instance = options.instance;
  21048. options.arc = (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  21049. // tube geometry
  21050. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  21051. var tangents = path3D.getTangents();
  21052. var normals = path3D.getNormals();
  21053. var distances = path3D.getDistances();
  21054. var pi2 = Math.PI * 2;
  21055. var step = pi2 / tessellation * arc;
  21056. var returnRadius = function () { return radius; };
  21057. var radiusFunctionFinal = radiusFunction || returnRadius;
  21058. var circlePath;
  21059. var rad;
  21060. var normal;
  21061. var rotated;
  21062. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  21063. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  21064. for (var i = 0; i < path.length; i++) {
  21065. rad = radiusFunctionFinal(i, distances[i]); // current radius
  21066. circlePath = Array(); // current circle array
  21067. normal = normals[i]; // current normal
  21068. for (var t = 0; t < tessellation; t++) {
  21069. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  21070. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  21071. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  21072. rotated.scaleInPlace(rad).addInPlace(path[i]);
  21073. circlePath[t] = rotated;
  21074. }
  21075. circlePaths[index] = circlePath;
  21076. index++;
  21077. }
  21078. // cap
  21079. var capPath = function (nbPoints, pathIndex) {
  21080. var pointCap = Array();
  21081. for (var i = 0; i < nbPoints; i++) {
  21082. pointCap.push(path[pathIndex]);
  21083. }
  21084. return pointCap;
  21085. };
  21086. switch (cap) {
  21087. case BABYLON.Mesh.NO_CAP:
  21088. break;
  21089. case BABYLON.Mesh.CAP_START:
  21090. circlePaths[0] = capPath(tessellation, 0);
  21091. circlePaths[1] = circlePaths[2].slice(0);
  21092. break;
  21093. case BABYLON.Mesh.CAP_END:
  21094. circlePaths[index] = circlePaths[index - 1].slice(0);
  21095. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  21096. break;
  21097. case BABYLON.Mesh.CAP_ALL:
  21098. circlePaths[0] = capPath(tessellation, 0);
  21099. circlePaths[1] = circlePaths[2].slice(0);
  21100. circlePaths[index] = circlePaths[index - 1].slice(0);
  21101. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  21102. break;
  21103. default:
  21104. break;
  21105. }
  21106. return circlePaths;
  21107. };
  21108. var path3D;
  21109. var pathArray;
  21110. if (instance) {
  21111. var arc = options.arc || instance.arc;
  21112. path3D = (instance.path3D).update(path);
  21113. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  21114. instance = MeshBuilder.CreateRibbon(null, { pathArray: pathArray, instance: instance });
  21115. instance.path3D = path3D;
  21116. instance.pathArray = pathArray;
  21117. instance.arc = arc;
  21118. return instance;
  21119. }
  21120. // tube creation
  21121. path3D = new BABYLON.Path3D(path);
  21122. var newPathArray = new Array();
  21123. cap = (cap < 0 || cap > 3) ? 0 : cap;
  21124. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  21125. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV }, scene);
  21126. tube.pathArray = pathArray;
  21127. tube.path3D = path3D;
  21128. tube.tessellation = tessellation;
  21129. tube.cap = cap;
  21130. tube.arc = options.arc;
  21131. return tube;
  21132. };
  21133. /**
  21134. * Creates a polyhedron mesh.
  21135. *
  21136. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  21137. * 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
  21138. * to choose the wanted type.
  21139. * The parameter `size` (positive float, default 1) sets the polygon size.
  21140. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  21141. * 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`.
  21142. * 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
  21143. * 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)`).
  21144. * 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
  21145. * 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.
  21146. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21147. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21148. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21149. */
  21150. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  21151. var polyhedron = new BABYLON.Mesh(name, scene);
  21152. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  21153. vertexData.applyToMesh(polyhedron, options.updatable);
  21154. return polyhedron;
  21155. };
  21156. /**
  21157. * Creates a decal mesh.
  21158. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  21159. * 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.
  21160. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  21161. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  21162. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  21163. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  21164. */
  21165. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  21166. var indices = sourceMesh.getIndices();
  21167. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21168. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21169. var position = options.position || BABYLON.Vector3.Zero();
  21170. var normal = options.normal || BABYLON.Vector3.Up();
  21171. var size = options.size || new BABYLON.Vector3(1, 1, 1);
  21172. var angle = options.angle || 0;
  21173. // Getting correct rotation
  21174. if (!normal) {
  21175. var target = new BABYLON.Vector3(0, 0, 1);
  21176. var camera = sourceMesh.getScene().activeCamera;
  21177. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  21178. normal = camera.globalPosition.subtract(cameraWorldTarget);
  21179. }
  21180. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  21181. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  21182. var pitch = Math.atan2(normal.y, len);
  21183. // Matrix
  21184. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  21185. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  21186. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  21187. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  21188. var vertexData = new BABYLON.VertexData();
  21189. vertexData.indices = [];
  21190. vertexData.positions = [];
  21191. vertexData.normals = [];
  21192. vertexData.uvs = [];
  21193. var currentVertexDataIndex = 0;
  21194. var extractDecalVector3 = function (indexId) {
  21195. var vertexId = indices[indexId];
  21196. var result = new BABYLON.PositionNormalVertex();
  21197. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  21198. // Send vector to decal local world
  21199. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  21200. // Get normal
  21201. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  21202. return result;
  21203. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  21204. var clip = function (vertices, axis) {
  21205. if (vertices.length === 0) {
  21206. return vertices;
  21207. }
  21208. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  21209. var clipVertices = function (v0, v1) {
  21210. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  21211. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  21212. };
  21213. var result = new Array();
  21214. for (var index = 0; index < vertices.length; index += 3) {
  21215. var v1Out;
  21216. var v2Out;
  21217. var v3Out;
  21218. var total = 0;
  21219. var nV1, nV2, nV3, nV4;
  21220. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  21221. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  21222. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  21223. v1Out = d1 > 0;
  21224. v2Out = d2 > 0;
  21225. v3Out = d3 > 0;
  21226. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  21227. switch (total) {
  21228. case 0:
  21229. result.push(vertices[index]);
  21230. result.push(vertices[index + 1]);
  21231. result.push(vertices[index + 2]);
  21232. break;
  21233. case 1:
  21234. if (v1Out) {
  21235. nV1 = vertices[index + 1];
  21236. nV2 = vertices[index + 2];
  21237. nV3 = clipVertices(vertices[index], nV1);
  21238. nV4 = clipVertices(vertices[index], nV2);
  21239. }
  21240. if (v2Out) {
  21241. nV1 = vertices[index];
  21242. nV2 = vertices[index + 2];
  21243. nV3 = clipVertices(vertices[index + 1], nV1);
  21244. nV4 = clipVertices(vertices[index + 1], nV2);
  21245. result.push(nV3);
  21246. result.push(nV2.clone());
  21247. result.push(nV1.clone());
  21248. result.push(nV2.clone());
  21249. result.push(nV3.clone());
  21250. result.push(nV4);
  21251. break;
  21252. }
  21253. if (v3Out) {
  21254. nV1 = vertices[index];
  21255. nV2 = vertices[index + 1];
  21256. nV3 = clipVertices(vertices[index + 2], nV1);
  21257. nV4 = clipVertices(vertices[index + 2], nV2);
  21258. }
  21259. result.push(nV1.clone());
  21260. result.push(nV2.clone());
  21261. result.push(nV3);
  21262. result.push(nV4);
  21263. result.push(nV3.clone());
  21264. result.push(nV2.clone());
  21265. break;
  21266. case 2:
  21267. if (!v1Out) {
  21268. nV1 = vertices[index].clone();
  21269. nV2 = clipVertices(nV1, vertices[index + 1]);
  21270. nV3 = clipVertices(nV1, vertices[index + 2]);
  21271. result.push(nV1);
  21272. result.push(nV2);
  21273. result.push(nV3);
  21274. }
  21275. if (!v2Out) {
  21276. nV1 = vertices[index + 1].clone();
  21277. nV2 = clipVertices(nV1, vertices[index + 2]);
  21278. nV3 = clipVertices(nV1, vertices[index]);
  21279. result.push(nV1);
  21280. result.push(nV2);
  21281. result.push(nV3);
  21282. }
  21283. if (!v3Out) {
  21284. nV1 = vertices[index + 2].clone();
  21285. nV2 = clipVertices(nV1, vertices[index]);
  21286. nV3 = clipVertices(nV1, vertices[index + 1]);
  21287. result.push(nV1);
  21288. result.push(nV2);
  21289. result.push(nV3);
  21290. }
  21291. break;
  21292. case 3:
  21293. break;
  21294. }
  21295. }
  21296. return result;
  21297. };
  21298. for (var index = 0; index < indices.length; index += 3) {
  21299. var faceVertices = new Array();
  21300. faceVertices.push(extractDecalVector3(index));
  21301. faceVertices.push(extractDecalVector3(index + 1));
  21302. faceVertices.push(extractDecalVector3(index + 2));
  21303. // Clip
  21304. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  21305. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  21306. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  21307. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  21308. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  21309. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  21310. if (faceVertices.length === 0) {
  21311. continue;
  21312. }
  21313. // Add UVs and get back to world
  21314. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  21315. var vertex = faceVertices[vIndex];
  21316. //TODO check for Int32Array
  21317. vertexData.indices.push(currentVertexDataIndex);
  21318. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  21319. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  21320. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  21321. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  21322. currentVertexDataIndex++;
  21323. }
  21324. }
  21325. // Return mesh
  21326. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  21327. vertexData.applyToMesh(decal);
  21328. decal.position = position.clone();
  21329. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  21330. return decal;
  21331. };
  21332. // Privates
  21333. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV) {
  21334. // extrusion geometry
  21335. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  21336. var tangents = path3D.getTangents();
  21337. var normals = path3D.getNormals();
  21338. var binormals = path3D.getBinormals();
  21339. var distances = path3D.getDistances();
  21340. var angle = 0;
  21341. var returnScale = function () { return scale; };
  21342. var returnRotation = function () { return rotation; };
  21343. var rotate = custom ? rotateFunction : returnRotation;
  21344. var scl = custom ? scaleFunction : returnScale;
  21345. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  21346. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  21347. for (var i = 0; i < curve.length; i++) {
  21348. var shapePath = new Array();
  21349. var angleStep = rotate(i, distances[i]);
  21350. var scaleRatio = scl(i, distances[i]);
  21351. for (var p = 0; p < shape.length; p++) {
  21352. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  21353. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  21354. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  21355. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  21356. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  21357. shapePath[p] = rotated;
  21358. }
  21359. shapePaths[index] = shapePath;
  21360. angle += angleStep;
  21361. index++;
  21362. }
  21363. // cap
  21364. var capPath = function (shapePath) {
  21365. var pointCap = Array();
  21366. var barycenter = BABYLON.Vector3.Zero();
  21367. var i;
  21368. for (i = 0; i < shapePath.length; i++) {
  21369. barycenter.addInPlace(shapePath[i]);
  21370. }
  21371. barycenter.scaleInPlace(1 / shapePath.length);
  21372. for (i = 0; i < shapePath.length; i++) {
  21373. pointCap.push(barycenter);
  21374. }
  21375. return pointCap;
  21376. };
  21377. switch (cap) {
  21378. case BABYLON.Mesh.NO_CAP:
  21379. break;
  21380. case BABYLON.Mesh.CAP_START:
  21381. shapePaths[0] = capPath(shapePaths[2]);
  21382. shapePaths[1] = shapePaths[2].slice(0);
  21383. break;
  21384. case BABYLON.Mesh.CAP_END:
  21385. shapePaths[index] = shapePaths[index - 1];
  21386. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  21387. break;
  21388. case BABYLON.Mesh.CAP_ALL:
  21389. shapePaths[0] = capPath(shapePaths[2]);
  21390. shapePaths[1] = shapePaths[2].slice(0);
  21391. shapePaths[index] = shapePaths[index - 1];
  21392. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  21393. break;
  21394. default:
  21395. break;
  21396. }
  21397. return shapePaths;
  21398. };
  21399. var path3D;
  21400. var pathArray;
  21401. if (instance) {
  21402. path3D = (instance.path3D).update(curve);
  21403. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  21404. instance = BABYLON.Mesh.CreateRibbon(null, pathArray, null, null, null, null, null, null, instance);
  21405. return instance;
  21406. }
  21407. // extruded shape creation
  21408. path3D = new BABYLON.Path3D(curve);
  21409. var newShapePaths = new Array();
  21410. cap = (cap < 0 || cap > 3) ? 0 : cap;
  21411. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  21412. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV }, scene);
  21413. extrudedGeneric.pathArray = pathArray;
  21414. extrudedGeneric.path3D = path3D;
  21415. extrudedGeneric.cap = cap;
  21416. return extrudedGeneric;
  21417. };
  21418. return MeshBuilder;
  21419. }());
  21420. BABYLON.MeshBuilder = MeshBuilder;
  21421. })(BABYLON || (BABYLON = {}));
  21422. var BABYLON;
  21423. (function (BABYLON) {
  21424. var BaseTexture = (function () {
  21425. function BaseTexture(scene) {
  21426. this.hasAlpha = false;
  21427. this.getAlphaFromRGB = false;
  21428. this.level = 1;
  21429. this.coordinatesIndex = 0;
  21430. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  21431. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  21432. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  21433. this.anisotropicFilteringLevel = 4;
  21434. this.isCube = false;
  21435. this.isRenderTarget = false;
  21436. this.animations = new Array();
  21437. /**
  21438. * An event triggered when the texture is disposed.
  21439. * @type {BABYLON.Observable}
  21440. */
  21441. this.onDisposeObservable = new BABYLON.Observable();
  21442. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  21443. this._scene = scene;
  21444. this._scene.textures.push(this);
  21445. }
  21446. BaseTexture.prototype.toString = function () {
  21447. return this.name;
  21448. };
  21449. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  21450. set: function (callback) {
  21451. if (this._onDisposeObserver) {
  21452. this.onDisposeObservable.remove(this._onDisposeObserver);
  21453. }
  21454. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  21455. },
  21456. enumerable: true,
  21457. configurable: true
  21458. });
  21459. BaseTexture.prototype.getScene = function () {
  21460. return this._scene;
  21461. };
  21462. BaseTexture.prototype.getTextureMatrix = function () {
  21463. return null;
  21464. };
  21465. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  21466. return null;
  21467. };
  21468. BaseTexture.prototype.getInternalTexture = function () {
  21469. return this._texture;
  21470. };
  21471. BaseTexture.prototype.isReady = function () {
  21472. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  21473. return true;
  21474. }
  21475. if (this._texture) {
  21476. return this._texture.isReady;
  21477. }
  21478. return false;
  21479. };
  21480. BaseTexture.prototype.getSize = function () {
  21481. if (this._texture._width) {
  21482. return new BABYLON.Size(this._texture._width, this._texture._height);
  21483. }
  21484. if (this._texture._size) {
  21485. return new BABYLON.Size(this._texture._size, this._texture._size);
  21486. }
  21487. return BABYLON.Size.Zero();
  21488. };
  21489. BaseTexture.prototype.getBaseSize = function () {
  21490. if (!this.isReady() || !this._texture)
  21491. return BABYLON.Size.Zero();
  21492. if (this._texture._size) {
  21493. return new BABYLON.Size(this._texture._size, this._texture._size);
  21494. }
  21495. return new BABYLON.Size(this._texture._baseWidth, this._texture._baseHeight);
  21496. };
  21497. BaseTexture.prototype.scale = function (ratio) {
  21498. };
  21499. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  21500. get: function () {
  21501. return false;
  21502. },
  21503. enumerable: true,
  21504. configurable: true
  21505. });
  21506. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  21507. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  21508. for (var index = 0; index < texturesCache.length; index++) {
  21509. var texturesCacheEntry = texturesCache[index];
  21510. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  21511. texturesCache.splice(index, 1);
  21512. return;
  21513. }
  21514. }
  21515. };
  21516. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  21517. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  21518. for (var index = 0; index < texturesCache.length; index++) {
  21519. var texturesCacheEntry = texturesCache[index];
  21520. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  21521. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  21522. texturesCacheEntry.references++;
  21523. return texturesCacheEntry;
  21524. }
  21525. }
  21526. }
  21527. return null;
  21528. };
  21529. BaseTexture.prototype.delayLoad = function () {
  21530. };
  21531. BaseTexture.prototype.clone = function () {
  21532. return null;
  21533. };
  21534. BaseTexture.prototype.releaseInternalTexture = function () {
  21535. if (this._texture) {
  21536. this._scene.getEngine().releaseInternalTexture(this._texture);
  21537. delete this._texture;
  21538. }
  21539. };
  21540. BaseTexture.prototype.dispose = function () {
  21541. // Animations
  21542. this.getScene().stopAnimation(this);
  21543. // Remove from scene
  21544. var index = this._scene.textures.indexOf(this);
  21545. if (index >= 0) {
  21546. this._scene.textures.splice(index, 1);
  21547. }
  21548. if (this._texture === undefined) {
  21549. return;
  21550. }
  21551. // Release
  21552. this.releaseInternalTexture();
  21553. // Callback
  21554. this.onDisposeObservable.notifyObservers(this);
  21555. this.onDisposeObservable.clear();
  21556. };
  21557. BaseTexture.prototype.serialize = function () {
  21558. if (!this.name) {
  21559. return null;
  21560. }
  21561. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  21562. // Animations
  21563. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  21564. return serializationObject;
  21565. };
  21566. __decorate([
  21567. BABYLON.serialize()
  21568. ], BaseTexture.prototype, "name", void 0);
  21569. __decorate([
  21570. BABYLON.serialize()
  21571. ], BaseTexture.prototype, "hasAlpha", void 0);
  21572. __decorate([
  21573. BABYLON.serialize()
  21574. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  21575. __decorate([
  21576. BABYLON.serialize()
  21577. ], BaseTexture.prototype, "level", void 0);
  21578. __decorate([
  21579. BABYLON.serialize()
  21580. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  21581. __decorate([
  21582. BABYLON.serialize()
  21583. ], BaseTexture.prototype, "coordinatesMode", void 0);
  21584. __decorate([
  21585. BABYLON.serialize()
  21586. ], BaseTexture.prototype, "wrapU", void 0);
  21587. __decorate([
  21588. BABYLON.serialize()
  21589. ], BaseTexture.prototype, "wrapV", void 0);
  21590. __decorate([
  21591. BABYLON.serialize()
  21592. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  21593. __decorate([
  21594. BABYLON.serialize()
  21595. ], BaseTexture.prototype, "isCube", void 0);
  21596. __decorate([
  21597. BABYLON.serialize()
  21598. ], BaseTexture.prototype, "isRenderTarget", void 0);
  21599. return BaseTexture;
  21600. }());
  21601. BABYLON.BaseTexture = BaseTexture;
  21602. })(BABYLON || (BABYLON = {}));
  21603. var BABYLON;
  21604. (function (BABYLON) {
  21605. var Texture = (function (_super) {
  21606. __extends(Texture, _super);
  21607. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
  21608. var _this = this;
  21609. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  21610. if (onLoad === void 0) { onLoad = null; }
  21611. if (onError === void 0) { onError = null; }
  21612. if (buffer === void 0) { buffer = null; }
  21613. if (deleteBuffer === void 0) { deleteBuffer = false; }
  21614. _super.call(this, scene);
  21615. this.uOffset = 0;
  21616. this.vOffset = 0;
  21617. this.uScale = 1.0;
  21618. this.vScale = 1.0;
  21619. this.uAng = 0;
  21620. this.vAng = 0;
  21621. this.wAng = 0;
  21622. this.name = url;
  21623. this.url = url;
  21624. this._noMipmap = noMipmap;
  21625. this._invertY = invertY;
  21626. this._samplingMode = samplingMode;
  21627. this._buffer = buffer;
  21628. this._deleteBuffer = deleteBuffer;
  21629. if (!url) {
  21630. return;
  21631. }
  21632. this._texture = this._getFromCache(url, noMipmap, samplingMode);
  21633. var load = function () {
  21634. if (_this._onLoadObservarble && _this._onLoadObservarble.hasObservers()) {
  21635. _this.onLoadObservable.notifyObservers(true);
  21636. }
  21637. if (onLoad) {
  21638. onLoad();
  21639. }
  21640. };
  21641. if (!this._texture) {
  21642. if (!scene.useDelayedTextureLoading) {
  21643. this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, this._samplingMode, load, onError, this._buffer);
  21644. if (deleteBuffer) {
  21645. delete this._buffer;
  21646. }
  21647. }
  21648. else {
  21649. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  21650. this._delayedOnLoad = load;
  21651. this._delayedOnError = onError;
  21652. }
  21653. }
  21654. else {
  21655. BABYLON.Tools.SetImmediate(function () { return load(); });
  21656. }
  21657. }
  21658. Object.defineProperty(Texture.prototype, "noMipmap", {
  21659. get: function () {
  21660. return this._noMipmap;
  21661. },
  21662. enumerable: true,
  21663. configurable: true
  21664. });
  21665. Texture.prototype.delayLoad = function () {
  21666. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  21667. return;
  21668. }
  21669. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  21670. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  21671. if (!this._texture) {
  21672. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer);
  21673. if (this._deleteBuffer) {
  21674. delete this._buffer;
  21675. }
  21676. }
  21677. };
  21678. Texture.prototype.updateSamplingMode = function (samplingMode) {
  21679. if (!this._texture) {
  21680. return;
  21681. }
  21682. this._samplingMode = samplingMode;
  21683. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  21684. };
  21685. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  21686. x *= this.uScale;
  21687. y *= this.vScale;
  21688. x -= 0.5 * this.uScale;
  21689. y -= 0.5 * this.vScale;
  21690. z -= 0.5;
  21691. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  21692. t.x += 0.5 * this.uScale + this.uOffset;
  21693. t.y += 0.5 * this.vScale + this.vOffset;
  21694. t.z += 0.5;
  21695. };
  21696. Texture.prototype.getTextureMatrix = function () {
  21697. if (this.uOffset === this._cachedUOffset &&
  21698. this.vOffset === this._cachedVOffset &&
  21699. this.uScale === this._cachedUScale &&
  21700. this.vScale === this._cachedVScale &&
  21701. this.uAng === this._cachedUAng &&
  21702. this.vAng === this._cachedVAng &&
  21703. this.wAng === this._cachedWAng) {
  21704. return this._cachedTextureMatrix;
  21705. }
  21706. this._cachedUOffset = this.uOffset;
  21707. this._cachedVOffset = this.vOffset;
  21708. this._cachedUScale = this.uScale;
  21709. this._cachedVScale = this.vScale;
  21710. this._cachedUAng = this.uAng;
  21711. this._cachedVAng = this.vAng;
  21712. this._cachedWAng = this.wAng;
  21713. if (!this._cachedTextureMatrix) {
  21714. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  21715. this._rowGenerationMatrix = new BABYLON.Matrix();
  21716. this._t0 = BABYLON.Vector3.Zero();
  21717. this._t1 = BABYLON.Vector3.Zero();
  21718. this._t2 = BABYLON.Vector3.Zero();
  21719. }
  21720. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  21721. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  21722. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  21723. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  21724. this._t1.subtractInPlace(this._t0);
  21725. this._t2.subtractInPlace(this._t0);
  21726. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  21727. this._cachedTextureMatrix.m[0] = this._t1.x;
  21728. this._cachedTextureMatrix.m[1] = this._t1.y;
  21729. this._cachedTextureMatrix.m[2] = this._t1.z;
  21730. this._cachedTextureMatrix.m[4] = this._t2.x;
  21731. this._cachedTextureMatrix.m[5] = this._t2.y;
  21732. this._cachedTextureMatrix.m[6] = this._t2.z;
  21733. this._cachedTextureMatrix.m[8] = this._t0.x;
  21734. this._cachedTextureMatrix.m[9] = this._t0.y;
  21735. this._cachedTextureMatrix.m[10] = this._t0.z;
  21736. return this._cachedTextureMatrix;
  21737. };
  21738. Texture.prototype.getReflectionTextureMatrix = function () {
  21739. if (this.uOffset === this._cachedUOffset &&
  21740. this.vOffset === this._cachedVOffset &&
  21741. this.uScale === this._cachedUScale &&
  21742. this.vScale === this._cachedVScale &&
  21743. this.coordinatesMode === this._cachedCoordinatesMode) {
  21744. return this._cachedTextureMatrix;
  21745. }
  21746. if (!this._cachedTextureMatrix) {
  21747. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  21748. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  21749. }
  21750. this._cachedCoordinatesMode = this.coordinatesMode;
  21751. switch (this.coordinatesMode) {
  21752. case Texture.PLANAR_MODE:
  21753. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  21754. this._cachedTextureMatrix[0] = this.uScale;
  21755. this._cachedTextureMatrix[5] = this.vScale;
  21756. this._cachedTextureMatrix[12] = this.uOffset;
  21757. this._cachedTextureMatrix[13] = this.vOffset;
  21758. break;
  21759. case Texture.PROJECTION_MODE:
  21760. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  21761. this._projectionModeMatrix.m[0] = 0.5;
  21762. this._projectionModeMatrix.m[5] = -0.5;
  21763. this._projectionModeMatrix.m[10] = 0.0;
  21764. this._projectionModeMatrix.m[12] = 0.5;
  21765. this._projectionModeMatrix.m[13] = 0.5;
  21766. this._projectionModeMatrix.m[14] = 1.0;
  21767. this._projectionModeMatrix.m[15] = 1.0;
  21768. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  21769. break;
  21770. default:
  21771. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  21772. break;
  21773. }
  21774. return this._cachedTextureMatrix;
  21775. };
  21776. Texture.prototype.clone = function () {
  21777. var _this = this;
  21778. return BABYLON.SerializationHelper.Clone(function () {
  21779. return new Texture(_this._texture.url, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  21780. }, this);
  21781. };
  21782. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  21783. get: function () {
  21784. if (!this._onLoadObservarble) {
  21785. this._onLoadObservarble = new BABYLON.Observable();
  21786. }
  21787. return this._onLoadObservarble;
  21788. },
  21789. enumerable: true,
  21790. configurable: true
  21791. });
  21792. // Statics
  21793. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError) {
  21794. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  21795. if (onLoad === void 0) { onLoad = null; }
  21796. if (onError === void 0) { onError = null; }
  21797. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data);
  21798. };
  21799. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  21800. if (parsedTexture.isCube) {
  21801. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  21802. }
  21803. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  21804. return null;
  21805. }
  21806. var texture = BABYLON.SerializationHelper.Parse(function () {
  21807. if (parsedTexture.customType) {
  21808. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  21809. return customTexture.Parse(parsedTexture, scene, rootUrl);
  21810. }
  21811. else if (parsedTexture.mirrorPlane) {
  21812. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  21813. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  21814. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  21815. return mirrorTexture;
  21816. }
  21817. else if (parsedTexture.isRenderTarget) {
  21818. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  21819. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  21820. return renderTargetTexture;
  21821. }
  21822. else {
  21823. var texture;
  21824. if (parsedTexture.base64String) {
  21825. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
  21826. }
  21827. else {
  21828. texture = new Texture(rootUrl + parsedTexture.name, scene);
  21829. }
  21830. return texture;
  21831. }
  21832. }, parsedTexture, scene);
  21833. // Animations
  21834. if (parsedTexture.animations) {
  21835. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  21836. var parsedAnimation = parsedTexture.animations[animationIndex];
  21837. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  21838. }
  21839. }
  21840. return texture;
  21841. };
  21842. // Constants
  21843. Texture.NEAREST_SAMPLINGMODE = 1;
  21844. Texture.BILINEAR_SAMPLINGMODE = 2;
  21845. Texture.TRILINEAR_SAMPLINGMODE = 3;
  21846. Texture.EXPLICIT_MODE = 0;
  21847. Texture.SPHERICAL_MODE = 1;
  21848. Texture.PLANAR_MODE = 2;
  21849. Texture.CUBIC_MODE = 3;
  21850. Texture.PROJECTION_MODE = 4;
  21851. Texture.SKYBOX_MODE = 5;
  21852. Texture.INVCUBIC_MODE = 6;
  21853. Texture.EQUIRECTANGULAR_MODE = 7;
  21854. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  21855. Texture.CLAMP_ADDRESSMODE = 0;
  21856. Texture.WRAP_ADDRESSMODE = 1;
  21857. Texture.MIRROR_ADDRESSMODE = 2;
  21858. __decorate([
  21859. BABYLON.serialize()
  21860. ], Texture.prototype, "url", void 0);
  21861. __decorate([
  21862. BABYLON.serialize()
  21863. ], Texture.prototype, "uOffset", void 0);
  21864. __decorate([
  21865. BABYLON.serialize()
  21866. ], Texture.prototype, "vOffset", void 0);
  21867. __decorate([
  21868. BABYLON.serialize()
  21869. ], Texture.prototype, "uScale", void 0);
  21870. __decorate([
  21871. BABYLON.serialize()
  21872. ], Texture.prototype, "vScale", void 0);
  21873. __decorate([
  21874. BABYLON.serialize()
  21875. ], Texture.prototype, "uAng", void 0);
  21876. __decorate([
  21877. BABYLON.serialize()
  21878. ], Texture.prototype, "vAng", void 0);
  21879. __decorate([
  21880. BABYLON.serialize()
  21881. ], Texture.prototype, "wAng", void 0);
  21882. return Texture;
  21883. }(BABYLON.BaseTexture));
  21884. BABYLON.Texture = Texture;
  21885. })(BABYLON || (BABYLON = {}));
  21886. var BABYLON;
  21887. (function (BABYLON) {
  21888. var CubeTexture = (function (_super) {
  21889. __extends(CubeTexture, _super);
  21890. function CubeTexture(rootUrl, scene, extensions, noMipmap, files) {
  21891. _super.call(this, scene);
  21892. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  21893. this.name = rootUrl;
  21894. this.url = rootUrl;
  21895. this._noMipmap = noMipmap;
  21896. this.hasAlpha = false;
  21897. if (!rootUrl && !files) {
  21898. return;
  21899. }
  21900. this._texture = this._getFromCache(rootUrl, noMipmap);
  21901. if (!files) {
  21902. if (!extensions) {
  21903. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  21904. }
  21905. files = [];
  21906. for (var index = 0; index < extensions.length; index++) {
  21907. files.push(rootUrl + extensions[index]);
  21908. }
  21909. this._extensions = extensions;
  21910. }
  21911. this._files = files;
  21912. if (!this._texture) {
  21913. if (!scene.useDelayedTextureLoading) {
  21914. this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap);
  21915. }
  21916. else {
  21917. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  21918. }
  21919. }
  21920. this.isCube = true;
  21921. this._textureMatrix = BABYLON.Matrix.Identity();
  21922. }
  21923. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  21924. return new CubeTexture("", scene, null, noMipmap, files);
  21925. };
  21926. // Methods
  21927. CubeTexture.prototype.delayLoad = function () {
  21928. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  21929. return;
  21930. }
  21931. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  21932. this._texture = this._getFromCache(this.url, this._noMipmap);
  21933. if (!this._texture) {
  21934. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._files, this._noMipmap);
  21935. }
  21936. };
  21937. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  21938. return this._textureMatrix;
  21939. };
  21940. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  21941. var texture = BABYLON.SerializationHelper.Parse(function () {
  21942. return new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  21943. }, parsedTexture, scene);
  21944. // Animations
  21945. if (parsedTexture.animations) {
  21946. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  21947. var parsedAnimation = parsedTexture.animations[animationIndex];
  21948. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  21949. }
  21950. }
  21951. return texture;
  21952. };
  21953. CubeTexture.prototype.clone = function () {
  21954. var _this = this;
  21955. return BABYLON.SerializationHelper.Clone(function () {
  21956. return new CubeTexture(_this.url, _this.getScene(), _this._extensions, _this._noMipmap, _this._files);
  21957. }, this);
  21958. };
  21959. return CubeTexture;
  21960. }(BABYLON.BaseTexture));
  21961. BABYLON.CubeTexture = CubeTexture;
  21962. })(BABYLON || (BABYLON = {}));
  21963. var BABYLON;
  21964. (function (BABYLON) {
  21965. var RenderTargetTexture = (function (_super) {
  21966. __extends(RenderTargetTexture, _super);
  21967. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode) {
  21968. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  21969. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  21970. if (isCube === void 0) { isCube = false; }
  21971. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  21972. _super.call(this, null, scene, !generateMipMaps);
  21973. this.isCube = isCube;
  21974. /**
  21975. * Use this list to define the list of mesh you want to render.
  21976. */
  21977. this.renderList = new Array();
  21978. this.renderParticles = true;
  21979. this.renderSprites = false;
  21980. this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  21981. // Events
  21982. /**
  21983. * An event triggered when the texture is unbind.
  21984. * @type {BABYLON.Observable}
  21985. */
  21986. this.onAfterUnbindObservable = new BABYLON.Observable();
  21987. /**
  21988. * An event triggered before rendering the texture
  21989. * @type {BABYLON.Observable}
  21990. */
  21991. this.onBeforeRenderObservable = new BABYLON.Observable();
  21992. /**
  21993. * An event triggered after rendering the texture
  21994. * @type {BABYLON.Observable}
  21995. */
  21996. this.onAfterRenderObservable = new BABYLON.Observable();
  21997. /**
  21998. * An event triggered after the texture clear
  21999. * @type {BABYLON.Observable}
  22000. */
  22001. this.onClearObservable = new BABYLON.Observable();
  22002. this._currentRefreshId = -1;
  22003. this._refreshRate = 1;
  22004. this.name = name;
  22005. this.isRenderTarget = true;
  22006. this._size = size;
  22007. this._generateMipMaps = generateMipMaps;
  22008. this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  22009. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  22010. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  22011. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  22012. }
  22013. if (isCube) {
  22014. this._texture = scene.getEngine().createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps, samplingMode: samplingMode });
  22015. this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  22016. this._textureMatrix = BABYLON.Matrix.Identity();
  22017. }
  22018. else {
  22019. this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: generateMipMaps, type: type, samplingMode: samplingMode });
  22020. }
  22021. // Rendering groups
  22022. this._renderingManager = new BABYLON.RenderingManager(scene);
  22023. }
  22024. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  22025. get: function () {
  22026. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  22027. },
  22028. enumerable: true,
  22029. configurable: true
  22030. });
  22031. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  22032. get: function () {
  22033. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  22034. },
  22035. enumerable: true,
  22036. configurable: true
  22037. });
  22038. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  22039. get: function () {
  22040. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  22041. },
  22042. enumerable: true,
  22043. configurable: true
  22044. });
  22045. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  22046. set: function (callback) {
  22047. if (this._onAfterUnbindObserver) {
  22048. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  22049. }
  22050. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  22051. },
  22052. enumerable: true,
  22053. configurable: true
  22054. });
  22055. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  22056. set: function (callback) {
  22057. if (this._onBeforeRenderObserver) {
  22058. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  22059. }
  22060. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  22061. },
  22062. enumerable: true,
  22063. configurable: true
  22064. });
  22065. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  22066. set: function (callback) {
  22067. if (this._onAfterRenderObserver) {
  22068. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  22069. }
  22070. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  22071. },
  22072. enumerable: true,
  22073. configurable: true
  22074. });
  22075. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  22076. set: function (callback) {
  22077. if (this._onClearObserver) {
  22078. this.onClearObservable.remove(this._onClearObserver);
  22079. }
  22080. this._onClearObserver = this.onClearObservable.add(callback);
  22081. },
  22082. enumerable: true,
  22083. configurable: true
  22084. });
  22085. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  22086. this._currentRefreshId = -1;
  22087. };
  22088. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  22089. get: function () {
  22090. return this._refreshRate;
  22091. },
  22092. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  22093. set: function (value) {
  22094. this._refreshRate = value;
  22095. this.resetRefreshCounter();
  22096. },
  22097. enumerable: true,
  22098. configurable: true
  22099. });
  22100. RenderTargetTexture.prototype._shouldRender = function () {
  22101. if (this._currentRefreshId === -1) {
  22102. this._currentRefreshId = 1;
  22103. return true;
  22104. }
  22105. if (this.refreshRate === this._currentRefreshId) {
  22106. this._currentRefreshId = 1;
  22107. return true;
  22108. }
  22109. this._currentRefreshId++;
  22110. return false;
  22111. };
  22112. RenderTargetTexture.prototype.isReady = function () {
  22113. if (!this.getScene().renderTargetsEnabled) {
  22114. return false;
  22115. }
  22116. return _super.prototype.isReady.call(this);
  22117. };
  22118. RenderTargetTexture.prototype.getRenderSize = function () {
  22119. return this._size;
  22120. };
  22121. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  22122. get: function () {
  22123. return true;
  22124. },
  22125. enumerable: true,
  22126. configurable: true
  22127. });
  22128. RenderTargetTexture.prototype.scale = function (ratio) {
  22129. var newSize = this._size * ratio;
  22130. this.resize(newSize, this._generateMipMaps);
  22131. };
  22132. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  22133. if (this.isCube) {
  22134. return this._textureMatrix;
  22135. }
  22136. return _super.prototype.getReflectionTextureMatrix.call(this);
  22137. };
  22138. RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
  22139. this.releaseInternalTexture();
  22140. if (this.isCube) {
  22141. this._texture = this.getScene().getEngine().createRenderTargetCubeTexture(size);
  22142. }
  22143. else {
  22144. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  22145. }
  22146. };
  22147. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  22148. var scene = this.getScene();
  22149. if (this.useCameraPostProcesses !== undefined) {
  22150. useCameraPostProcess = this.useCameraPostProcesses;
  22151. }
  22152. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  22153. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  22154. }
  22155. if (this._waitingRenderList) {
  22156. this.renderList = [];
  22157. for (var index = 0; index < this._waitingRenderList.length; index++) {
  22158. var id = this._waitingRenderList[index];
  22159. this.renderList.push(scene.getMeshByID(id));
  22160. }
  22161. delete this._waitingRenderList;
  22162. }
  22163. // Is predicate defined?
  22164. if (this.renderListPredicate) {
  22165. this.renderList.splice(0); // Clear previous renderList
  22166. var sceneMeshes = this.getScene().meshes;
  22167. for (var index = 0; index < sceneMeshes.length; index++) {
  22168. var mesh = sceneMeshes[index];
  22169. if (this.renderListPredicate(mesh)) {
  22170. this.renderList.push(mesh);
  22171. }
  22172. }
  22173. }
  22174. if (this.renderList && this.renderList.length === 0) {
  22175. return;
  22176. }
  22177. // Prepare renderingManager
  22178. this._renderingManager.reset();
  22179. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  22180. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  22181. var sceneRenderId = scene.getRenderId();
  22182. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  22183. var mesh = currentRenderList[meshIndex];
  22184. if (mesh) {
  22185. if (!mesh.isReady()) {
  22186. // Reset _currentRefreshId
  22187. this.resetRefreshCounter();
  22188. continue;
  22189. }
  22190. mesh._preActivateForIntermediateRendering(sceneRenderId);
  22191. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
  22192. mesh._activate(sceneRenderId);
  22193. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  22194. var subMesh = mesh.subMeshes[subIndex];
  22195. scene._activeIndices.addCount(subMesh.indexCount, false);
  22196. this._renderingManager.dispatch(subMesh);
  22197. }
  22198. }
  22199. }
  22200. }
  22201. if (this.isCube) {
  22202. for (var face = 0; face < 6; face++) {
  22203. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  22204. scene.incrementRenderId();
  22205. scene.resetCachedMaterial();
  22206. }
  22207. }
  22208. else {
  22209. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  22210. }
  22211. this.onAfterUnbindObservable.notifyObservers(this);
  22212. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  22213. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  22214. }
  22215. scene.resetCachedMaterial();
  22216. };
  22217. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  22218. var scene = this.getScene();
  22219. var engine = scene.getEngine();
  22220. // Bind
  22221. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  22222. if (this.isCube) {
  22223. engine.bindFramebuffer(this._texture, faceIndex);
  22224. }
  22225. else {
  22226. engine.bindFramebuffer(this._texture);
  22227. }
  22228. }
  22229. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  22230. // Clear
  22231. if (this.onClearObservable.hasObservers()) {
  22232. this.onClearObservable.notifyObservers(engine);
  22233. }
  22234. else {
  22235. engine.clear(scene.clearColor, true, true);
  22236. }
  22237. if (!this._doNotChangeAspectRatio) {
  22238. scene.updateTransformMatrix(true);
  22239. }
  22240. // Render
  22241. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  22242. if (useCameraPostProcess) {
  22243. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  22244. }
  22245. if (!this._doNotChangeAspectRatio) {
  22246. scene.updateTransformMatrix(true);
  22247. }
  22248. this.onAfterRenderObservable.notifyObservers(faceIndex);
  22249. // Dump ?
  22250. if (dumpForDebug) {
  22251. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  22252. }
  22253. // Unbind
  22254. if (!this.isCube || faceIndex === 5) {
  22255. if (this.isCube) {
  22256. if (faceIndex === 5) {
  22257. engine.generateMipMapsForCubemap(this._texture);
  22258. }
  22259. }
  22260. engine.unBindFramebuffer(this._texture, this.isCube);
  22261. }
  22262. };
  22263. RenderTargetTexture.prototype.clone = function () {
  22264. var textureSize = this.getSize();
  22265. var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  22266. // Base texture
  22267. newTexture.hasAlpha = this.hasAlpha;
  22268. newTexture.level = this.level;
  22269. // RenderTarget Texture
  22270. newTexture.coordinatesMode = this.coordinatesMode;
  22271. newTexture.renderList = this.renderList.slice(0);
  22272. return newTexture;
  22273. };
  22274. RenderTargetTexture.prototype.serialize = function () {
  22275. if (!this.name) {
  22276. return null;
  22277. }
  22278. var serializationObject = _super.prototype.serialize.call(this);
  22279. serializationObject.renderTargetSize = this.getRenderSize();
  22280. serializationObject.renderList = [];
  22281. for (var index = 0; index < this.renderList.length; index++) {
  22282. serializationObject.renderList.push(this.renderList[index].id);
  22283. }
  22284. return serializationObject;
  22285. };
  22286. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  22287. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  22288. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  22289. return RenderTargetTexture;
  22290. }(BABYLON.Texture));
  22291. BABYLON.RenderTargetTexture = RenderTargetTexture;
  22292. })(BABYLON || (BABYLON = {}));
  22293. var BABYLON;
  22294. (function (BABYLON) {
  22295. var ProceduralTexture = (function (_super) {
  22296. __extends(ProceduralTexture, _super);
  22297. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  22298. if (generateMipMaps === void 0) { generateMipMaps = true; }
  22299. if (isCube === void 0) { isCube = false; }
  22300. _super.call(this, null, scene, !generateMipMaps);
  22301. this.isCube = isCube;
  22302. this.isEnabled = true;
  22303. this._currentRefreshId = -1;
  22304. this._refreshRate = 1;
  22305. this._vertexBuffers = {};
  22306. this._uniforms = new Array();
  22307. this._samplers = new Array();
  22308. this._textures = new Array();
  22309. this._floats = new Array();
  22310. this._floatsArrays = {};
  22311. this._colors3 = new Array();
  22312. this._colors4 = new Array();
  22313. this._vectors2 = new Array();
  22314. this._vectors3 = new Array();
  22315. this._matrices = new Array();
  22316. this._fallbackTextureUsed = false;
  22317. scene._proceduralTextures.push(this);
  22318. this.name = name;
  22319. this.isRenderTarget = true;
  22320. this._size = size;
  22321. this._generateMipMaps = generateMipMaps;
  22322. this.setFragment(fragment);
  22323. this._fallbackTexture = fallbackTexture;
  22324. var engine = scene.getEngine();
  22325. if (isCube) {
  22326. this._texture = engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  22327. this.setFloat("face", 0);
  22328. }
  22329. else {
  22330. this._texture = engine.createRenderTargetTexture(size, generateMipMaps);
  22331. }
  22332. // VBO
  22333. var vertices = [];
  22334. vertices.push(1, 1);
  22335. vertices.push(-1, 1);
  22336. vertices.push(-1, -1);
  22337. vertices.push(1, -1);
  22338. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  22339. // Indices
  22340. var indices = [];
  22341. indices.push(0);
  22342. indices.push(1);
  22343. indices.push(2);
  22344. indices.push(0);
  22345. indices.push(2);
  22346. indices.push(3);
  22347. this._indexBuffer = engine.createIndexBuffer(indices);
  22348. }
  22349. ProceduralTexture.prototype.reset = function () {
  22350. if (this._effect === undefined) {
  22351. return;
  22352. }
  22353. var engine = this.getScene().getEngine();
  22354. engine._releaseEffect(this._effect);
  22355. };
  22356. ProceduralTexture.prototype.isReady = function () {
  22357. var _this = this;
  22358. var engine = this.getScene().getEngine();
  22359. var shaders;
  22360. if (!this._fragment) {
  22361. return false;
  22362. }
  22363. if (this._fallbackTextureUsed) {
  22364. return true;
  22365. }
  22366. if (this._fragment.fragmentElement !== undefined) {
  22367. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  22368. }
  22369. else {
  22370. shaders = { vertex: "procedural", fragment: this._fragment };
  22371. }
  22372. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", null, null, function () {
  22373. _this.releaseInternalTexture();
  22374. if (_this._fallbackTexture) {
  22375. _this._texture = _this._fallbackTexture._texture;
  22376. _this._texture.references++;
  22377. }
  22378. _this._fallbackTextureUsed = true;
  22379. });
  22380. return this._effect.isReady();
  22381. };
  22382. ProceduralTexture.prototype.resetRefreshCounter = function () {
  22383. this._currentRefreshId = -1;
  22384. };
  22385. ProceduralTexture.prototype.setFragment = function (fragment) {
  22386. this._fragment = fragment;
  22387. };
  22388. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  22389. get: function () {
  22390. return this._refreshRate;
  22391. },
  22392. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  22393. set: function (value) {
  22394. this._refreshRate = value;
  22395. this.resetRefreshCounter();
  22396. },
  22397. enumerable: true,
  22398. configurable: true
  22399. });
  22400. ProceduralTexture.prototype._shouldRender = function () {
  22401. if (!this.isEnabled || !this.isReady() || !this._texture) {
  22402. return false;
  22403. }
  22404. if (this._fallbackTextureUsed) {
  22405. return false;
  22406. }
  22407. if (this._currentRefreshId === -1) {
  22408. this._currentRefreshId = 1;
  22409. return true;
  22410. }
  22411. if (this.refreshRate === this._currentRefreshId) {
  22412. this._currentRefreshId = 1;
  22413. return true;
  22414. }
  22415. this._currentRefreshId++;
  22416. return false;
  22417. };
  22418. ProceduralTexture.prototype.getRenderSize = function () {
  22419. return this._size;
  22420. };
  22421. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  22422. if (this._fallbackTextureUsed) {
  22423. return;
  22424. }
  22425. this.releaseInternalTexture();
  22426. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  22427. };
  22428. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  22429. if (this._uniforms.indexOf(uniformName) === -1) {
  22430. this._uniforms.push(uniformName);
  22431. }
  22432. };
  22433. ProceduralTexture.prototype.setTexture = function (name, texture) {
  22434. if (this._samplers.indexOf(name) === -1) {
  22435. this._samplers.push(name);
  22436. }
  22437. this._textures[name] = texture;
  22438. return this;
  22439. };
  22440. ProceduralTexture.prototype.setFloat = function (name, value) {
  22441. this._checkUniform(name);
  22442. this._floats[name] = value;
  22443. return this;
  22444. };
  22445. ProceduralTexture.prototype.setFloats = function (name, value) {
  22446. this._checkUniform(name);
  22447. this._floatsArrays[name] = value;
  22448. return this;
  22449. };
  22450. ProceduralTexture.prototype.setColor3 = function (name, value) {
  22451. this._checkUniform(name);
  22452. this._colors3[name] = value;
  22453. return this;
  22454. };
  22455. ProceduralTexture.prototype.setColor4 = function (name, value) {
  22456. this._checkUniform(name);
  22457. this._colors4[name] = value;
  22458. return this;
  22459. };
  22460. ProceduralTexture.prototype.setVector2 = function (name, value) {
  22461. this._checkUniform(name);
  22462. this._vectors2[name] = value;
  22463. return this;
  22464. };
  22465. ProceduralTexture.prototype.setVector3 = function (name, value) {
  22466. this._checkUniform(name);
  22467. this._vectors3[name] = value;
  22468. return this;
  22469. };
  22470. ProceduralTexture.prototype.setMatrix = function (name, value) {
  22471. this._checkUniform(name);
  22472. this._matrices[name] = value;
  22473. return this;
  22474. };
  22475. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  22476. var scene = this.getScene();
  22477. var engine = scene.getEngine();
  22478. // Render
  22479. engine.enableEffect(this._effect);
  22480. engine.setState(false);
  22481. // Texture
  22482. for (var name in this._textures) {
  22483. this._effect.setTexture(name, this._textures[name]);
  22484. }
  22485. // Float
  22486. for (name in this._floats) {
  22487. this._effect.setFloat(name, this._floats[name]);
  22488. }
  22489. // Floats
  22490. for (name in this._floatsArrays) {
  22491. this._effect.setArray(name, this._floatsArrays[name]);
  22492. }
  22493. // Color3
  22494. for (name in this._colors3) {
  22495. this._effect.setColor3(name, this._colors3[name]);
  22496. }
  22497. // Color4
  22498. for (name in this._colors4) {
  22499. var color = this._colors4[name];
  22500. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  22501. }
  22502. // Vector2
  22503. for (name in this._vectors2) {
  22504. this._effect.setVector2(name, this._vectors2[name]);
  22505. }
  22506. // Vector3
  22507. for (name in this._vectors3) {
  22508. this._effect.setVector3(name, this._vectors3[name]);
  22509. }
  22510. // Matrix
  22511. for (name in this._matrices) {
  22512. this._effect.setMatrix(name, this._matrices[name]);
  22513. }
  22514. // VBOs
  22515. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  22516. if (this.isCube) {
  22517. for (var face = 0; face < 6; face++) {
  22518. engine.bindFramebuffer(this._texture, face);
  22519. this._effect.setFloat("face", face);
  22520. // Clear
  22521. engine.clear(scene.clearColor, true, true);
  22522. // Draw order
  22523. engine.draw(true, 0, 6);
  22524. // Mipmaps
  22525. if (face === 5) {
  22526. engine.generateMipMapsForCubemap(this._texture);
  22527. }
  22528. }
  22529. }
  22530. else {
  22531. engine.bindFramebuffer(this._texture);
  22532. // Clear
  22533. engine.clear(scene.clearColor, true, true);
  22534. // Draw order
  22535. engine.draw(true, 0, 6);
  22536. }
  22537. // Unbind
  22538. engine.unBindFramebuffer(this._texture, this.isCube);
  22539. if (this.onGenerated) {
  22540. this.onGenerated();
  22541. }
  22542. };
  22543. ProceduralTexture.prototype.clone = function () {
  22544. var textureSize = this.getSize();
  22545. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  22546. // Base texture
  22547. newTexture.hasAlpha = this.hasAlpha;
  22548. newTexture.level = this.level;
  22549. // RenderTarget Texture
  22550. newTexture.coordinatesMode = this.coordinatesMode;
  22551. return newTexture;
  22552. };
  22553. ProceduralTexture.prototype.dispose = function () {
  22554. var index = this.getScene()._proceduralTextures.indexOf(this);
  22555. if (index >= 0) {
  22556. this.getScene()._proceduralTextures.splice(index, 1);
  22557. }
  22558. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  22559. if (vertexBuffer) {
  22560. vertexBuffer.dispose();
  22561. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  22562. }
  22563. if (this._indexBuffer && this.getScene().getEngine()._releaseBuffer(this._indexBuffer)) {
  22564. this._indexBuffer = null;
  22565. }
  22566. _super.prototype.dispose.call(this);
  22567. };
  22568. return ProceduralTexture;
  22569. }(BABYLON.Texture));
  22570. BABYLON.ProceduralTexture = ProceduralTexture;
  22571. })(BABYLON || (BABYLON = {}));
  22572. var BABYLON;
  22573. (function (BABYLON) {
  22574. var MirrorTexture = (function (_super) {
  22575. __extends(MirrorTexture, _super);
  22576. function MirrorTexture(name, size, scene, generateMipMaps) {
  22577. var _this = this;
  22578. _super.call(this, name, size, scene, generateMipMaps, true);
  22579. this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  22580. this._transformMatrix = BABYLON.Matrix.Zero();
  22581. this._mirrorMatrix = BABYLON.Matrix.Zero();
  22582. this.onBeforeRenderObservable.add(function () {
  22583. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  22584. _this._savedViewMatrix = scene.getViewMatrix();
  22585. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  22586. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  22587. scene.clipPlane = _this.mirrorPlane;
  22588. scene.getEngine().cullBackFaces = false;
  22589. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.position, _this._mirrorMatrix);
  22590. });
  22591. this.onAfterRenderObservable.add(function () {
  22592. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  22593. scene.getEngine().cullBackFaces = true;
  22594. scene._mirroredCameraPosition = null;
  22595. delete scene.clipPlane;
  22596. });
  22597. }
  22598. MirrorTexture.prototype.clone = function () {
  22599. var textureSize = this.getSize();
  22600. var newTexture = new MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  22601. // Base texture
  22602. newTexture.hasAlpha = this.hasAlpha;
  22603. newTexture.level = this.level;
  22604. // Mirror Texture
  22605. newTexture.mirrorPlane = this.mirrorPlane.clone();
  22606. newTexture.renderList = this.renderList.slice(0);
  22607. return newTexture;
  22608. };
  22609. MirrorTexture.prototype.serialize = function () {
  22610. if (!this.name) {
  22611. return null;
  22612. }
  22613. var serializationObject = _super.prototype.serialize.call(this);
  22614. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  22615. return serializationObject;
  22616. };
  22617. return MirrorTexture;
  22618. }(BABYLON.RenderTargetTexture));
  22619. BABYLON.MirrorTexture = MirrorTexture;
  22620. })(BABYLON || (BABYLON = {}));
  22621. var BABYLON;
  22622. (function (BABYLON) {
  22623. /**
  22624. * Creates a refraction texture used by refraction channel of the standard material.
  22625. * @param name the texture name
  22626. * @param size size of the underlying texture
  22627. * @param scene root scene
  22628. */
  22629. var RefractionTexture = (function (_super) {
  22630. __extends(RefractionTexture, _super);
  22631. function RefractionTexture(name, size, scene, generateMipMaps) {
  22632. var _this = this;
  22633. _super.call(this, name, size, scene, generateMipMaps, true);
  22634. this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  22635. this.depth = 2.0;
  22636. this.onBeforeRenderObservable.add(function () {
  22637. scene.clipPlane = _this.refractionPlane;
  22638. });
  22639. this.onAfterRenderObservable.add(function () {
  22640. delete scene.clipPlane;
  22641. });
  22642. }
  22643. RefractionTexture.prototype.clone = function () {
  22644. var textureSize = this.getSize();
  22645. var newTexture = new RefractionTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  22646. // Base texture
  22647. newTexture.hasAlpha = this.hasAlpha;
  22648. newTexture.level = this.level;
  22649. // Refraction Texture
  22650. newTexture.refractionPlane = this.refractionPlane.clone();
  22651. newTexture.renderList = this.renderList.slice(0);
  22652. newTexture.depth = this.depth;
  22653. return newTexture;
  22654. };
  22655. RefractionTexture.prototype.serialize = function () {
  22656. if (!this.name) {
  22657. return null;
  22658. }
  22659. var serializationObject = _super.prototype.serialize.call(this);
  22660. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  22661. serializationObject.depth = this.depth;
  22662. return serializationObject;
  22663. };
  22664. return RefractionTexture;
  22665. }(BABYLON.RenderTargetTexture));
  22666. BABYLON.RefractionTexture = RefractionTexture;
  22667. })(BABYLON || (BABYLON = {}));
  22668. var BABYLON;
  22669. (function (BABYLON) {
  22670. var DynamicTexture = (function (_super) {
  22671. __extends(DynamicTexture, _super);
  22672. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  22673. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  22674. _super.call(this, null, scene, !generateMipMaps);
  22675. this.name = name;
  22676. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  22677. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  22678. this._generateMipMaps = generateMipMaps;
  22679. if (options.getContext) {
  22680. this._canvas = options;
  22681. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  22682. }
  22683. else {
  22684. this._canvas = document.createElement("canvas");
  22685. if (options.width) {
  22686. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  22687. }
  22688. else {
  22689. this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  22690. }
  22691. }
  22692. var textureSize = this.getSize();
  22693. this._canvas.width = textureSize.width;
  22694. this._canvas.height = textureSize.height;
  22695. this._context = this._canvas.getContext("2d");
  22696. }
  22697. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  22698. get: function () {
  22699. return true;
  22700. },
  22701. enumerable: true,
  22702. configurable: true
  22703. });
  22704. DynamicTexture.prototype.scale = function (ratio) {
  22705. var textureSize = this.getSize();
  22706. textureSize.width *= ratio;
  22707. textureSize.height *= ratio;
  22708. this._canvas.width = textureSize.width;
  22709. this._canvas.height = textureSize.height;
  22710. this.releaseInternalTexture();
  22711. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  22712. };
  22713. DynamicTexture.prototype.getContext = function () {
  22714. return this._context;
  22715. };
  22716. DynamicTexture.prototype.clear = function () {
  22717. var size = this.getSize();
  22718. this._context.fillRect(0, 0, size.width, size.height);
  22719. };
  22720. DynamicTexture.prototype.update = function (invertY) {
  22721. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  22722. };
  22723. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  22724. if (update === void 0) { update = true; }
  22725. var size = this.getSize();
  22726. if (clearColor) {
  22727. this._context.fillStyle = clearColor;
  22728. this._context.fillRect(0, 0, size.width, size.height);
  22729. }
  22730. this._context.font = font;
  22731. if (x === null) {
  22732. var textSize = this._context.measureText(text);
  22733. x = (size.width - textSize.width) / 2;
  22734. }
  22735. this._context.fillStyle = color;
  22736. this._context.fillText(text, x, y);
  22737. if (update) {
  22738. this.update(invertY);
  22739. }
  22740. };
  22741. DynamicTexture.prototype.clone = function () {
  22742. var textureSize = this.getSize();
  22743. var newTexture = new DynamicTexture(this.name, textureSize, this.getScene(), this._generateMipMaps);
  22744. // Base texture
  22745. newTexture.hasAlpha = this.hasAlpha;
  22746. newTexture.level = this.level;
  22747. // Dynamic Texture
  22748. newTexture.wrapU = this.wrapU;
  22749. newTexture.wrapV = this.wrapV;
  22750. return newTexture;
  22751. };
  22752. return DynamicTexture;
  22753. }(BABYLON.Texture));
  22754. BABYLON.DynamicTexture = DynamicTexture;
  22755. })(BABYLON || (BABYLON = {}));
  22756. var BABYLON;
  22757. (function (BABYLON) {
  22758. var VideoTexture = (function (_super) {
  22759. __extends(VideoTexture, _super);
  22760. /**
  22761. * Creates a video texture.
  22762. * Sample : https://doc.babylonjs.com/tutorials/01._Advanced_Texturing
  22763. * @param {Array} urlsOrVideo can be used to provide an array of urls or an already setup HTML video element.
  22764. * @param {BABYLON.Scene} scene is obviously the current scene.
  22765. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  22766. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  22767. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  22768. */
  22769. function VideoTexture(name, urlsOrVideo, scene, generateMipMaps, invertY, samplingMode) {
  22770. var _this = this;
  22771. if (generateMipMaps === void 0) { generateMipMaps = false; }
  22772. if (invertY === void 0) { invertY = false; }
  22773. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  22774. _super.call(this, null, scene, !generateMipMaps, invertY);
  22775. this._autoLaunch = true;
  22776. var urls;
  22777. this.name = name;
  22778. if (urlsOrVideo instanceof HTMLVideoElement) {
  22779. this.video = urlsOrVideo;
  22780. }
  22781. else {
  22782. urls = urlsOrVideo;
  22783. this.video = document.createElement("video");
  22784. this.video.autoplay = false;
  22785. this.video.loop = true;
  22786. }
  22787. this._generateMipMaps = generateMipMaps;
  22788. this._samplingMode = samplingMode;
  22789. if (BABYLON.Tools.IsExponentOfTwo(this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(this.video.videoHeight)) {
  22790. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  22791. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  22792. }
  22793. else {
  22794. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  22795. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  22796. this._generateMipMaps = false;
  22797. }
  22798. if (urls) {
  22799. this.video.addEventListener("canplaythrough", function () {
  22800. _this._createTexture();
  22801. });
  22802. urls.forEach(function (url) {
  22803. var source = document.createElement("source");
  22804. source.src = url;
  22805. _this.video.appendChild(source);
  22806. });
  22807. }
  22808. else {
  22809. this._createTexture();
  22810. }
  22811. this._lastUpdate = BABYLON.Tools.Now;
  22812. }
  22813. VideoTexture.prototype._createTexture = function () {
  22814. this._texture = this.getScene().getEngine().createDynamicTexture(this.video.videoWidth, this.video.videoHeight, this._generateMipMaps, this._samplingMode);
  22815. this._texture.isReady = true;
  22816. };
  22817. VideoTexture.prototype.update = function () {
  22818. if (this._autoLaunch) {
  22819. this._autoLaunch = false;
  22820. this.video.play();
  22821. }
  22822. var now = BABYLON.Tools.Now;
  22823. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  22824. return false;
  22825. }
  22826. this._lastUpdate = now;
  22827. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  22828. return true;
  22829. };
  22830. return VideoTexture;
  22831. }(BABYLON.Texture));
  22832. BABYLON.VideoTexture = VideoTexture;
  22833. })(BABYLON || (BABYLON = {}));
  22834. var BABYLON;
  22835. (function (BABYLON) {
  22836. var CustomProceduralTexture = (function (_super) {
  22837. __extends(CustomProceduralTexture, _super);
  22838. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  22839. _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps);
  22840. this._animate = true;
  22841. this._time = 0;
  22842. this._texturePath = texturePath;
  22843. //Try to load json
  22844. this.loadJson(texturePath);
  22845. this.refreshRate = 1;
  22846. }
  22847. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  22848. var _this = this;
  22849. var that = this;
  22850. function noConfigFile() {
  22851. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  22852. try {
  22853. that.setFragment(that._texturePath);
  22854. }
  22855. catch (ex) {
  22856. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  22857. }
  22858. }
  22859. var configFileUrl = jsonUrl + "/config.json";
  22860. var xhr = new XMLHttpRequest();
  22861. xhr.open("GET", configFileUrl, true);
  22862. xhr.addEventListener("load", function () {
  22863. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  22864. try {
  22865. _this._config = JSON.parse(xhr.response);
  22866. _this.updateShaderUniforms();
  22867. _this.updateTextures();
  22868. _this.setFragment(_this._texturePath + "/custom");
  22869. _this._animate = _this._config.animate;
  22870. _this.refreshRate = _this._config.refreshrate;
  22871. }
  22872. catch (ex) {
  22873. noConfigFile();
  22874. }
  22875. }
  22876. else {
  22877. noConfigFile();
  22878. }
  22879. }, false);
  22880. xhr.addEventListener("error", function () {
  22881. noConfigFile();
  22882. }, false);
  22883. try {
  22884. xhr.send();
  22885. }
  22886. catch (ex) {
  22887. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  22888. }
  22889. };
  22890. CustomProceduralTexture.prototype.isReady = function () {
  22891. if (!_super.prototype.isReady.call(this)) {
  22892. return false;
  22893. }
  22894. for (var name in this._textures) {
  22895. var texture = this._textures[name];
  22896. if (!texture.isReady()) {
  22897. return false;
  22898. }
  22899. }
  22900. return true;
  22901. };
  22902. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  22903. if (this._animate) {
  22904. this._time += this.getScene().getAnimationRatio() * 0.03;
  22905. this.updateShaderUniforms();
  22906. }
  22907. _super.prototype.render.call(this, useCameraPostProcess);
  22908. };
  22909. CustomProceduralTexture.prototype.updateTextures = function () {
  22910. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  22911. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  22912. }
  22913. };
  22914. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  22915. if (this._config) {
  22916. for (var j = 0; j < this._config.uniforms.length; j++) {
  22917. var uniform = this._config.uniforms[j];
  22918. switch (uniform.type) {
  22919. case "float":
  22920. this.setFloat(uniform.name, uniform.value);
  22921. break;
  22922. case "color3":
  22923. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  22924. break;
  22925. case "color4":
  22926. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  22927. break;
  22928. case "vector2":
  22929. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  22930. break;
  22931. case "vector3":
  22932. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  22933. break;
  22934. }
  22935. }
  22936. }
  22937. this.setFloat("time", this._time);
  22938. };
  22939. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  22940. get: function () {
  22941. return this._animate;
  22942. },
  22943. set: function (value) {
  22944. this._animate = value;
  22945. },
  22946. enumerable: true,
  22947. configurable: true
  22948. });
  22949. return CustomProceduralTexture;
  22950. }(BABYLON.ProceduralTexture));
  22951. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  22952. })(BABYLON || (BABYLON = {}));
  22953. var BABYLON;
  22954. (function (BABYLON) {
  22955. var EffectFallbacks = (function () {
  22956. function EffectFallbacks() {
  22957. this._defines = {};
  22958. this._currentRank = 32;
  22959. this._maxRank = -1;
  22960. }
  22961. EffectFallbacks.prototype.addFallback = function (rank, define) {
  22962. if (!this._defines[rank]) {
  22963. if (rank < this._currentRank) {
  22964. this._currentRank = rank;
  22965. }
  22966. if (rank > this._maxRank) {
  22967. this._maxRank = rank;
  22968. }
  22969. this._defines[rank] = new Array();
  22970. }
  22971. this._defines[rank].push(define);
  22972. };
  22973. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  22974. this._meshRank = rank;
  22975. this._mesh = mesh;
  22976. if (rank > this._maxRank) {
  22977. this._maxRank = rank;
  22978. }
  22979. };
  22980. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  22981. get: function () {
  22982. return this._currentRank <= this._maxRank;
  22983. },
  22984. enumerable: true,
  22985. configurable: true
  22986. });
  22987. EffectFallbacks.prototype.reduce = function (currentDefines) {
  22988. var currentFallbacks = this._defines[this._currentRank];
  22989. for (var index = 0; index < currentFallbacks.length; index++) {
  22990. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  22991. }
  22992. if (this._mesh && this._currentRank === this._meshRank) {
  22993. this._mesh.computeBonesUsingShaders = false;
  22994. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  22995. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  22996. }
  22997. this._currentRank++;
  22998. return currentDefines;
  22999. };
  23000. return EffectFallbacks;
  23001. }());
  23002. BABYLON.EffectFallbacks = EffectFallbacks;
  23003. var Effect = (function () {
  23004. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  23005. var _this = this;
  23006. this._isReady = false;
  23007. this._compilationError = "";
  23008. this._valueCache = {};
  23009. this._engine = engine;
  23010. this.name = baseName;
  23011. this.defines = defines;
  23012. this._uniformsNames = uniformsNames.concat(samplers);
  23013. this._samplers = samplers;
  23014. this._attributesNames = attributesNames;
  23015. this.onError = onError;
  23016. this.onCompiled = onCompiled;
  23017. this._indexParameters = indexParameters;
  23018. var vertexSource;
  23019. var fragmentSource;
  23020. if (baseName.vertexElement) {
  23021. vertexSource = document.getElementById(baseName.vertexElement);
  23022. if (!vertexSource) {
  23023. vertexSource = baseName.vertexElement;
  23024. }
  23025. }
  23026. else {
  23027. vertexSource = baseName.vertex || baseName;
  23028. }
  23029. if (baseName.fragmentElement) {
  23030. fragmentSource = document.getElementById(baseName.fragmentElement);
  23031. if (!fragmentSource) {
  23032. fragmentSource = baseName.fragmentElement;
  23033. }
  23034. }
  23035. else {
  23036. fragmentSource = baseName.fragment || baseName;
  23037. }
  23038. this._loadVertexShader(vertexSource, function (vertexCode) {
  23039. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  23040. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  23041. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  23042. _this._prepareEffect(vertexCodeWithIncludes, fragmentCodeWithIncludes, attributesNames, defines, fallbacks);
  23043. });
  23044. });
  23045. });
  23046. });
  23047. }
  23048. // Properties
  23049. Effect.prototype.isReady = function () {
  23050. return this._isReady;
  23051. };
  23052. Effect.prototype.getProgram = function () {
  23053. return this._program;
  23054. };
  23055. Effect.prototype.getAttributesNames = function () {
  23056. return this._attributesNames;
  23057. };
  23058. Effect.prototype.getAttributeLocation = function (index) {
  23059. return this._attributes[index];
  23060. };
  23061. Effect.prototype.getAttributeLocationByName = function (name) {
  23062. var index = this._attributesNames.indexOf(name);
  23063. return this._attributes[index];
  23064. };
  23065. Effect.prototype.getAttributesCount = function () {
  23066. return this._attributes.length;
  23067. };
  23068. Effect.prototype.getUniformIndex = function (uniformName) {
  23069. return this._uniformsNames.indexOf(uniformName);
  23070. };
  23071. Effect.prototype.getUniform = function (uniformName) {
  23072. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  23073. };
  23074. Effect.prototype.getSamplers = function () {
  23075. return this._samplers;
  23076. };
  23077. Effect.prototype.getCompilationError = function () {
  23078. return this._compilationError;
  23079. };
  23080. // Methods
  23081. Effect.prototype._loadVertexShader = function (vertex, callback) {
  23082. // DOM element ?
  23083. if (vertex instanceof HTMLElement) {
  23084. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  23085. callback(vertexCode);
  23086. return;
  23087. }
  23088. // Is in local store ?
  23089. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  23090. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  23091. return;
  23092. }
  23093. var vertexShaderUrl;
  23094. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  23095. vertexShaderUrl = vertex;
  23096. }
  23097. else {
  23098. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  23099. }
  23100. // Vertex shader
  23101. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  23102. };
  23103. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  23104. // DOM element ?
  23105. if (fragment instanceof HTMLElement) {
  23106. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  23107. callback(fragmentCode);
  23108. return;
  23109. }
  23110. // Is in local store ?
  23111. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  23112. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  23113. return;
  23114. }
  23115. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  23116. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  23117. return;
  23118. }
  23119. var fragmentShaderUrl;
  23120. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  23121. fragmentShaderUrl = fragment;
  23122. }
  23123. else {
  23124. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  23125. }
  23126. // Fragment shader
  23127. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  23128. };
  23129. Effect.prototype._dumpShadersName = function () {
  23130. if (this.name.vertexElement) {
  23131. BABYLON.Tools.Error("Vertex shader:" + this.name.vertexElement);
  23132. BABYLON.Tools.Error("Fragment shader:" + this.name.fragmentElement);
  23133. }
  23134. else if (this.name.vertex) {
  23135. BABYLON.Tools.Error("Vertex shader:" + this.name.vertex);
  23136. BABYLON.Tools.Error("Fragment shader:" + this.name.fragment);
  23137. }
  23138. else {
  23139. BABYLON.Tools.Error("Vertex shader:" + this.name);
  23140. BABYLON.Tools.Error("Fragment shader:" + this.name);
  23141. }
  23142. };
  23143. Effect.prototype._processIncludes = function (sourceCode, callback) {
  23144. var _this = this;
  23145. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  23146. var match = regex.exec(sourceCode);
  23147. var returnValue = new String(sourceCode);
  23148. while (match != null) {
  23149. var includeFile = match[1];
  23150. if (Effect.IncludesShadersStore[includeFile]) {
  23151. // Substitution
  23152. var includeContent = Effect.IncludesShadersStore[includeFile];
  23153. if (match[2]) {
  23154. var splits = match[3].split(",");
  23155. for (var index = 0; index < splits.length; index += 2) {
  23156. var source = new RegExp(splits[index], "g");
  23157. var dest = splits[index + 1];
  23158. includeContent = includeContent.replace(source, dest);
  23159. }
  23160. }
  23161. if (match[4]) {
  23162. var indexString = match[5];
  23163. if (indexString.indexOf("..") !== -1) {
  23164. var indexSplits = indexString.split("..");
  23165. var minIndex = parseInt(indexSplits[0]);
  23166. var maxIndex = parseInt(indexSplits[1]);
  23167. var sourceIncludeContent = includeContent.slice(0);
  23168. includeContent = "";
  23169. if (isNaN(maxIndex)) {
  23170. maxIndex = this._indexParameters[indexSplits[1]];
  23171. }
  23172. for (var i = minIndex; i <= maxIndex; i++) {
  23173. includeContent += sourceIncludeContent.replace(/\{X\}/g, i) + "\n";
  23174. }
  23175. }
  23176. else {
  23177. includeContent = includeContent.replace(/\{X\}/g, indexString);
  23178. }
  23179. }
  23180. // Replace
  23181. returnValue = returnValue.replace(match[0], includeContent);
  23182. }
  23183. else {
  23184. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  23185. BABYLON.Tools.LoadFile(includeShaderUrl, function (fileContent) {
  23186. Effect.IncludesShadersStore[includeFile] = fileContent;
  23187. _this._processIncludes(returnValue, callback);
  23188. });
  23189. return;
  23190. }
  23191. match = regex.exec(sourceCode);
  23192. }
  23193. callback(returnValue);
  23194. };
  23195. Effect.prototype._processPrecision = function (source) {
  23196. if (source.indexOf("precision highp float") === -1) {
  23197. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  23198. source = "precision mediump float;\n" + source;
  23199. }
  23200. else {
  23201. source = "precision highp float;\n" + source;
  23202. }
  23203. }
  23204. else {
  23205. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  23206. source = source.replace("precision highp float", "precision mediump float");
  23207. }
  23208. }
  23209. return source;
  23210. };
  23211. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  23212. try {
  23213. var engine = this._engine;
  23214. // Precision
  23215. vertexSourceCode = this._processPrecision(vertexSourceCode);
  23216. fragmentSourceCode = this._processPrecision(fragmentSourceCode);
  23217. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  23218. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  23219. this._attributes = engine.getAttributes(this._program, attributesNames);
  23220. var index;
  23221. for (index = 0; index < this._samplers.length; index++) {
  23222. var sampler = this.getUniform(this._samplers[index]);
  23223. if (sampler == null) {
  23224. this._samplers.splice(index, 1);
  23225. index--;
  23226. }
  23227. }
  23228. engine.bindSamplers(this);
  23229. this._isReady = true;
  23230. if (this.onCompiled) {
  23231. this.onCompiled(this);
  23232. }
  23233. }
  23234. catch (e) {
  23235. // Let's go through fallbacks then
  23236. if (fallbacks && fallbacks.isMoreFallbacks) {
  23237. BABYLON.Tools.Error("Unable to compile effect with current defines. Trying next fallback.");
  23238. this._dumpShadersName();
  23239. defines = fallbacks.reduce(defines);
  23240. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  23241. }
  23242. else {
  23243. BABYLON.Tools.Error("Unable to compile effect: ");
  23244. this._dumpShadersName();
  23245. BABYLON.Tools.Error("Defines: " + defines);
  23246. BABYLON.Tools.Error("Error: " + e.message);
  23247. this._compilationError = e.message;
  23248. if (this.onError) {
  23249. this.onError(this, this._compilationError);
  23250. }
  23251. }
  23252. }
  23253. };
  23254. Object.defineProperty(Effect.prototype, "isSupported", {
  23255. get: function () {
  23256. return this._compilationError === "";
  23257. },
  23258. enumerable: true,
  23259. configurable: true
  23260. });
  23261. Effect.prototype._bindTexture = function (channel, texture) {
  23262. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  23263. };
  23264. Effect.prototype.setTexture = function (channel, texture) {
  23265. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  23266. };
  23267. Effect.prototype.setTextureArray = function (channel, textures) {
  23268. if (this._samplers.indexOf(channel + "Ex") === -1) {
  23269. var initialPos = this._samplers.indexOf(channel);
  23270. for (var index = 1; index < textures.length; index++) {
  23271. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  23272. }
  23273. }
  23274. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  23275. };
  23276. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  23277. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  23278. };
  23279. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  23280. var changed = false;
  23281. var cache = this._valueCache[uniformName];
  23282. if (!cache || !(cache instanceof BABYLON.Matrix)) {
  23283. changed = true;
  23284. cache = new BABYLON.Matrix();
  23285. }
  23286. var tm = cache.m;
  23287. var om = matrix.m;
  23288. for (var index = 0; index < 16; index++) {
  23289. if (tm[index] !== om[index]) {
  23290. tm[index] = om[index];
  23291. changed = true;
  23292. }
  23293. }
  23294. this._valueCache[uniformName] = cache;
  23295. return changed;
  23296. };
  23297. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  23298. var cache = this._valueCache[uniformName];
  23299. if (!cache) {
  23300. cache = [x, y];
  23301. this._valueCache[uniformName] = cache;
  23302. return true;
  23303. }
  23304. var changed = false;
  23305. if (cache[0] !== x) {
  23306. cache[0] = x;
  23307. changed = true;
  23308. }
  23309. if (cache[1] !== y) {
  23310. cache[1] = y;
  23311. changed = true;
  23312. }
  23313. return changed;
  23314. };
  23315. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  23316. var cache = this._valueCache[uniformName];
  23317. if (!cache) {
  23318. cache = [x, y, z];
  23319. this._valueCache[uniformName] = cache;
  23320. return true;
  23321. }
  23322. var changed = false;
  23323. if (cache[0] !== x) {
  23324. cache[0] = x;
  23325. changed = true;
  23326. }
  23327. if (cache[1] !== y) {
  23328. cache[1] = y;
  23329. changed = true;
  23330. }
  23331. if (cache[2] !== z) {
  23332. cache[2] = z;
  23333. changed = true;
  23334. }
  23335. return changed;
  23336. };
  23337. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  23338. var cache = this._valueCache[uniformName];
  23339. if (!cache) {
  23340. cache = [x, y, z, w];
  23341. this._valueCache[uniformName] = cache;
  23342. return true;
  23343. }
  23344. var changed = false;
  23345. if (cache[0] !== x) {
  23346. cache[0] = x;
  23347. changed = true;
  23348. }
  23349. if (cache[1] !== y) {
  23350. cache[1] = y;
  23351. changed = true;
  23352. }
  23353. if (cache[2] !== z) {
  23354. cache[2] = z;
  23355. changed = true;
  23356. }
  23357. if (cache[3] !== w) {
  23358. cache[3] = w;
  23359. changed = true;
  23360. }
  23361. return changed;
  23362. };
  23363. Effect.prototype.setIntArray = function (uniformName, array) {
  23364. this._valueCache[uniformName] = null;
  23365. this._engine.setIntArray(this.getUniform(uniformName), array);
  23366. return this;
  23367. };
  23368. Effect.prototype.setIntArray2 = function (uniformName, array) {
  23369. this._valueCache[uniformName] = null;
  23370. this._engine.setIntArray2(this.getUniform(uniformName), array);
  23371. return this;
  23372. };
  23373. Effect.prototype.setIntArray3 = function (uniformName, array) {
  23374. this._valueCache[uniformName] = null;
  23375. this._engine.setIntArray3(this.getUniform(uniformName), array);
  23376. return this;
  23377. };
  23378. Effect.prototype.setIntArray4 = function (uniformName, array) {
  23379. this._valueCache[uniformName] = null;
  23380. this._engine.setIntArray4(this.getUniform(uniformName), array);
  23381. return this;
  23382. };
  23383. Effect.prototype.setFloatArray = function (uniformName, array) {
  23384. this._valueCache[uniformName] = null;
  23385. this._engine.setFloatArray(this.getUniform(uniformName), array);
  23386. return this;
  23387. };
  23388. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  23389. this._valueCache[uniformName] = null;
  23390. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  23391. return this;
  23392. };
  23393. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  23394. this._valueCache[uniformName] = null;
  23395. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  23396. return this;
  23397. };
  23398. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  23399. this._valueCache[uniformName] = null;
  23400. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  23401. return this;
  23402. };
  23403. Effect.prototype.setArray = function (uniformName, array) {
  23404. this._valueCache[uniformName] = null;
  23405. this._engine.setArray(this.getUniform(uniformName), array);
  23406. return this;
  23407. };
  23408. Effect.prototype.setArray2 = function (uniformName, array) {
  23409. this._valueCache[uniformName] = null;
  23410. this._engine.setArray2(this.getUniform(uniformName), array);
  23411. return this;
  23412. };
  23413. Effect.prototype.setArray3 = function (uniformName, array) {
  23414. this._valueCache[uniformName] = null;
  23415. this._engine.setArray3(this.getUniform(uniformName), array);
  23416. return this;
  23417. };
  23418. Effect.prototype.setArray4 = function (uniformName, array) {
  23419. this._valueCache[uniformName] = null;
  23420. this._engine.setArray4(this.getUniform(uniformName), array);
  23421. return this;
  23422. };
  23423. Effect.prototype.setMatrices = function (uniformName, matrices) {
  23424. this._valueCache[uniformName] = null;
  23425. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  23426. return this;
  23427. };
  23428. Effect.prototype.setMatrix = function (uniformName, matrix) {
  23429. if (this._cacheMatrix(uniformName, matrix)) {
  23430. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  23431. }
  23432. return this;
  23433. };
  23434. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  23435. this._valueCache[uniformName] = null;
  23436. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  23437. return this;
  23438. };
  23439. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  23440. this._valueCache[uniformName] = null;
  23441. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  23442. return this;
  23443. };
  23444. Effect.prototype.setFloat = function (uniformName, value) {
  23445. var cache = this._valueCache[uniformName];
  23446. if (cache !== undefined && cache === value)
  23447. return this;
  23448. this._valueCache[uniformName] = value;
  23449. this._engine.setFloat(this.getUniform(uniformName), value);
  23450. return this;
  23451. };
  23452. Effect.prototype.setBool = function (uniformName, bool) {
  23453. var cache = this._valueCache[uniformName];
  23454. if (cache !== undefined && cache === bool)
  23455. return this;
  23456. this._valueCache[uniformName] = bool;
  23457. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  23458. return this;
  23459. };
  23460. Effect.prototype.setVector2 = function (uniformName, vector2) {
  23461. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  23462. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  23463. }
  23464. return this;
  23465. };
  23466. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  23467. if (this._cacheFloat2(uniformName, x, y)) {
  23468. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  23469. }
  23470. return this;
  23471. };
  23472. Effect.prototype.setVector3 = function (uniformName, vector3) {
  23473. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  23474. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  23475. }
  23476. return this;
  23477. };
  23478. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  23479. if (this._cacheFloat3(uniformName, x, y, z)) {
  23480. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  23481. }
  23482. return this;
  23483. };
  23484. Effect.prototype.setVector4 = function (uniformName, vector4) {
  23485. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  23486. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  23487. }
  23488. return this;
  23489. };
  23490. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  23491. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  23492. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  23493. }
  23494. return this;
  23495. };
  23496. Effect.prototype.setColor3 = function (uniformName, color3) {
  23497. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  23498. this._engine.setColor3(this.getUniform(uniformName), color3);
  23499. }
  23500. return this;
  23501. };
  23502. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  23503. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  23504. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  23505. }
  23506. return this;
  23507. };
  23508. // Statics
  23509. Effect.ShadersStore = {};
  23510. Effect.IncludesShadersStore = {};
  23511. return Effect;
  23512. }());
  23513. BABYLON.Effect = Effect;
  23514. })(BABYLON || (BABYLON = {}));
  23515. var BABYLON;
  23516. (function (BABYLON) {
  23517. var MaterialHelper = (function () {
  23518. function MaterialHelper() {
  23519. }
  23520. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, maxSimultaneousLights) {
  23521. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  23522. var lightIndex = 0;
  23523. var needNormals = false;
  23524. var needRebuild = false;
  23525. var needShadows = false;
  23526. for (var index = 0; index < scene.lights.length; index++) {
  23527. var light = scene.lights[index];
  23528. if (!light.isEnabled()) {
  23529. continue;
  23530. }
  23531. // Excluded check
  23532. if (light._excludedMeshesIds.length > 0) {
  23533. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  23534. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  23535. if (excludedMesh) {
  23536. light.excludedMeshes.push(excludedMesh);
  23537. }
  23538. }
  23539. light._excludedMeshesIds = [];
  23540. }
  23541. // Included check
  23542. if (light._includedOnlyMeshesIds.length > 0) {
  23543. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  23544. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  23545. if (includedOnlyMesh) {
  23546. light.includedOnlyMeshes.push(includedOnlyMesh);
  23547. }
  23548. }
  23549. light._includedOnlyMeshesIds = [];
  23550. }
  23551. if (!light.canAffectMesh(mesh)) {
  23552. continue;
  23553. }
  23554. needNormals = true;
  23555. if (defines["LIGHT" + lightIndex] === undefined) {
  23556. needRebuild = true;
  23557. }
  23558. defines["LIGHT" + lightIndex] = true;
  23559. var type;
  23560. if (light instanceof BABYLON.SpotLight) {
  23561. type = "SPOTLIGHT" + lightIndex;
  23562. }
  23563. else if (light instanceof BABYLON.HemisphericLight) {
  23564. type = "HEMILIGHT" + lightIndex;
  23565. }
  23566. else if (light instanceof BABYLON.PointLight) {
  23567. type = "POINTLIGHT" + lightIndex;
  23568. }
  23569. else {
  23570. type = "DIRLIGHT" + lightIndex;
  23571. }
  23572. if (defines[type] === undefined) {
  23573. needRebuild = true;
  23574. }
  23575. defines[type] = true;
  23576. // Specular
  23577. if (!light.specular.equalsFloats(0, 0, 0) && defines["SPECULARTERM"] !== undefined) {
  23578. defines["SPECULARTERM"] = true;
  23579. }
  23580. // Shadows
  23581. if (scene.shadowsEnabled) {
  23582. var shadowGenerator = light.getShadowGenerator();
  23583. if (mesh && mesh.receiveShadows && shadowGenerator) {
  23584. if (defines["SHADOW" + lightIndex] === undefined) {
  23585. needRebuild = true;
  23586. }
  23587. defines["SHADOW" + lightIndex] = true;
  23588. defines["SHADOWS"] = true;
  23589. if (shadowGenerator.useVarianceShadowMap || shadowGenerator.useBlurVarianceShadowMap) {
  23590. if (defines["SHADOWVSM" + lightIndex] === undefined) {
  23591. needRebuild = true;
  23592. }
  23593. defines["SHADOWVSM" + lightIndex] = true;
  23594. }
  23595. if (shadowGenerator.usePoissonSampling) {
  23596. if (defines["SHADOWPCF" + lightIndex] === undefined) {
  23597. needRebuild = true;
  23598. }
  23599. defines["SHADOWPCF" + lightIndex] = true;
  23600. }
  23601. needShadows = true;
  23602. }
  23603. }
  23604. lightIndex++;
  23605. if (lightIndex === maxSimultaneousLights)
  23606. break;
  23607. }
  23608. var caps = scene.getEngine().getCaps();
  23609. if (needShadows && caps.textureFloat && caps.textureFloatLinearFiltering && caps.textureFloatRender) {
  23610. if (defines["SHADOWFULLFLOAT"] === undefined) {
  23611. needRebuild = true;
  23612. }
  23613. defines["SHADOWFULLFLOAT"] = true;
  23614. }
  23615. if (needRebuild) {
  23616. defines.rebuild();
  23617. }
  23618. return needNormals;
  23619. };
  23620. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsList, samplersList, defines, maxSimultaneousLights) {
  23621. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  23622. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  23623. if (!defines["LIGHT" + lightIndex]) {
  23624. break;
  23625. }
  23626. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex);
  23627. samplersList.push("shadowSampler" + lightIndex);
  23628. }
  23629. };
  23630. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights) {
  23631. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  23632. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  23633. if (!defines["LIGHT" + lightIndex]) {
  23634. break;
  23635. }
  23636. if (lightIndex > 0) {
  23637. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  23638. }
  23639. if (defines["SHADOW" + lightIndex]) {
  23640. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  23641. }
  23642. if (defines["SHADOWPCF" + lightIndex]) {
  23643. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  23644. }
  23645. if (defines["SHADOWVSM" + lightIndex]) {
  23646. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  23647. }
  23648. }
  23649. };
  23650. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  23651. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  23652. fallbacks.addCPUSkinningFallback(0, mesh);
  23653. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  23654. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  23655. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  23656. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  23657. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  23658. }
  23659. }
  23660. };
  23661. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  23662. if (defines["INSTANCES"]) {
  23663. attribs.push("world0");
  23664. attribs.push("world1");
  23665. attribs.push("world2");
  23666. attribs.push("world3");
  23667. }
  23668. };
  23669. // Bindings
  23670. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect, depthValuesAlreadySet) {
  23671. var shadowGenerator = light.getShadowGenerator();
  23672. if (mesh.receiveShadows && shadowGenerator) {
  23673. if (!light.needCube()) {
  23674. effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  23675. }
  23676. else {
  23677. if (!depthValuesAlreadySet) {
  23678. depthValuesAlreadySet = true;
  23679. effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  23680. }
  23681. }
  23682. effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMapForRendering());
  23683. effect.setFloat3("shadowsInfo" + lightIndex, shadowGenerator.getDarkness(), shadowGenerator.blurScale / shadowGenerator.getShadowMap().getSize().width, shadowGenerator.bias);
  23684. }
  23685. return depthValuesAlreadySet;
  23686. };
  23687. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  23688. if (light instanceof BABYLON.PointLight) {
  23689. // Point Light
  23690. light.transferToEffect(effect, "vLightData" + lightIndex);
  23691. }
  23692. else if (light instanceof BABYLON.DirectionalLight) {
  23693. // Directional Light
  23694. light.transferToEffect(effect, "vLightData" + lightIndex);
  23695. }
  23696. else if (light instanceof BABYLON.SpotLight) {
  23697. // Spot Light
  23698. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  23699. }
  23700. else if (light instanceof BABYLON.HemisphericLight) {
  23701. // Hemispheric Light
  23702. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  23703. }
  23704. };
  23705. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights) {
  23706. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  23707. var lightIndex = 0;
  23708. var depthValuesAlreadySet = false;
  23709. for (var index = 0; index < scene.lights.length; index++) {
  23710. var light = scene.lights[index];
  23711. if (!light.isEnabled()) {
  23712. continue;
  23713. }
  23714. if (!light.canAffectMesh(mesh)) {
  23715. continue;
  23716. }
  23717. MaterialHelper.BindLightProperties(light, effect, lightIndex);
  23718. light.diffuse.scaleToRef(light.intensity, BABYLON.Tmp.Color3[0]);
  23719. effect.setColor4("vLightDiffuse" + lightIndex, BABYLON.Tmp.Color3[0], light.range);
  23720. if (defines["SPECULARTERM"]) {
  23721. light.specular.scaleToRef(light.intensity, BABYLON.Tmp.Color3[1]);
  23722. effect.setColor3("vLightSpecular" + lightIndex, BABYLON.Tmp.Color3[1]);
  23723. }
  23724. // Shadows
  23725. if (scene.shadowsEnabled) {
  23726. depthValuesAlreadySet = this.BindLightShadow(light, scene, mesh, lightIndex, effect, depthValuesAlreadySet);
  23727. }
  23728. lightIndex++;
  23729. if (lightIndex === maxSimultaneousLights)
  23730. break;
  23731. }
  23732. };
  23733. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  23734. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  23735. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  23736. effect.setColor3("vFogColor", scene.fogColor);
  23737. }
  23738. };
  23739. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  23740. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  23741. effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  23742. }
  23743. };
  23744. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  23745. if (defines["LOGARITHMICDEPTH"]) {
  23746. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  23747. }
  23748. };
  23749. MaterialHelper.BindClipPlane = function (effect, scene) {
  23750. if (scene.clipPlane) {
  23751. var clipPlane = scene.clipPlane;
  23752. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  23753. }
  23754. };
  23755. return MaterialHelper;
  23756. }());
  23757. BABYLON.MaterialHelper = MaterialHelper;
  23758. })(BABYLON || (BABYLON = {}));
  23759. var BABYLON;
  23760. (function (BABYLON) {
  23761. var FresnelParameters = (function () {
  23762. function FresnelParameters() {
  23763. this.isEnabled = true;
  23764. this.leftColor = BABYLON.Color3.White();
  23765. this.rightColor = BABYLON.Color3.Black();
  23766. this.bias = 0;
  23767. this.power = 1;
  23768. }
  23769. FresnelParameters.prototype.clone = function () {
  23770. var newFresnelParameters = new FresnelParameters();
  23771. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  23772. return new FresnelParameters;
  23773. };
  23774. FresnelParameters.prototype.serialize = function () {
  23775. var serializationObject = {};
  23776. serializationObject.isEnabled = this.isEnabled;
  23777. serializationObject.leftColor = this.leftColor;
  23778. serializationObject.rightColor = this.rightColor;
  23779. serializationObject.bias = this.bias;
  23780. serializationObject.power = this.power;
  23781. return serializationObject;
  23782. };
  23783. FresnelParameters.Parse = function (parsedFresnelParameters) {
  23784. var fresnelParameters = new FresnelParameters();
  23785. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  23786. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  23787. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  23788. fresnelParameters.bias = parsedFresnelParameters.bias;
  23789. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  23790. return fresnelParameters;
  23791. };
  23792. return FresnelParameters;
  23793. }());
  23794. BABYLON.FresnelParameters = FresnelParameters;
  23795. })(BABYLON || (BABYLON = {}));
  23796. var BABYLON;
  23797. (function (BABYLON) {
  23798. var MaterialDefines = (function () {
  23799. function MaterialDefines() {
  23800. }
  23801. MaterialDefines.prototype.rebuild = function () {
  23802. if (this._keys) {
  23803. delete this._keys;
  23804. }
  23805. this._keys = Object.keys(this);
  23806. };
  23807. MaterialDefines.prototype.isEqual = function (other) {
  23808. if (this._keys.length !== other._keys.length) {
  23809. return false;
  23810. }
  23811. for (var index = 0; index < this._keys.length; index++) {
  23812. var prop = this._keys[index];
  23813. if (this[prop] !== other[prop]) {
  23814. return false;
  23815. }
  23816. }
  23817. return true;
  23818. };
  23819. MaterialDefines.prototype.cloneTo = function (other) {
  23820. if (this._keys.length !== other._keys.length) {
  23821. other._keys = this._keys.slice(0);
  23822. }
  23823. for (var index = 0; index < this._keys.length; index++) {
  23824. var prop = this._keys[index];
  23825. other[prop] = this[prop];
  23826. }
  23827. };
  23828. MaterialDefines.prototype.reset = function () {
  23829. for (var index = 0; index < this._keys.length; index++) {
  23830. var prop = this._keys[index];
  23831. if (typeof (this[prop]) === "number") {
  23832. this[prop] = 0;
  23833. }
  23834. else {
  23835. this[prop] = false;
  23836. }
  23837. }
  23838. };
  23839. MaterialDefines.prototype.toString = function () {
  23840. var result = "";
  23841. for (var index = 0; index < this._keys.length; index++) {
  23842. var prop = this._keys[index];
  23843. if (typeof (this[prop]) === "number") {
  23844. result += "#define " + prop + " " + this[prop] + "\n";
  23845. }
  23846. else if (this[prop]) {
  23847. result += "#define " + prop + "\n";
  23848. }
  23849. }
  23850. return result;
  23851. };
  23852. return MaterialDefines;
  23853. }());
  23854. BABYLON.MaterialDefines = MaterialDefines;
  23855. var Material = (function () {
  23856. function Material(name, scene, doNotAdd) {
  23857. this.name = name;
  23858. this.checkReadyOnEveryCall = false;
  23859. this.checkReadyOnlyOnce = false;
  23860. this.state = "";
  23861. this.alpha = 1.0;
  23862. this.backFaceCulling = true;
  23863. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  23864. /**
  23865. * An event triggered when the material is disposed.
  23866. * @type {BABYLON.Observable}
  23867. */
  23868. this.onDisposeObservable = new BABYLON.Observable();
  23869. /**
  23870. * An event triggered when the material is compiled.
  23871. * @type {BABYLON.Observable}
  23872. */
  23873. this.onBindObservable = new BABYLON.Observable();
  23874. this.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  23875. this.disableDepthWrite = false;
  23876. this.fogEnabled = true;
  23877. this.pointSize = 1.0;
  23878. this.zOffset = 0;
  23879. this._wasPreviouslyReady = false;
  23880. this._fillMode = Material.TriangleFillMode;
  23881. this.id = name;
  23882. this._scene = scene;
  23883. if (!doNotAdd) {
  23884. scene.materials.push(this);
  23885. }
  23886. }
  23887. Object.defineProperty(Material, "TriangleFillMode", {
  23888. get: function () {
  23889. return Material._TriangleFillMode;
  23890. },
  23891. enumerable: true,
  23892. configurable: true
  23893. });
  23894. Object.defineProperty(Material, "WireFrameFillMode", {
  23895. get: function () {
  23896. return Material._WireFrameFillMode;
  23897. },
  23898. enumerable: true,
  23899. configurable: true
  23900. });
  23901. Object.defineProperty(Material, "PointFillMode", {
  23902. get: function () {
  23903. return Material._PointFillMode;
  23904. },
  23905. enumerable: true,
  23906. configurable: true
  23907. });
  23908. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  23909. get: function () {
  23910. return Material._ClockWiseSideOrientation;
  23911. },
  23912. enumerable: true,
  23913. configurable: true
  23914. });
  23915. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  23916. get: function () {
  23917. return Material._CounterClockWiseSideOrientation;
  23918. },
  23919. enumerable: true,
  23920. configurable: true
  23921. });
  23922. Object.defineProperty(Material.prototype, "onDispose", {
  23923. set: function (callback) {
  23924. if (this._onDisposeObserver) {
  23925. this.onDisposeObservable.remove(this._onDisposeObserver);
  23926. }
  23927. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  23928. },
  23929. enumerable: true,
  23930. configurable: true
  23931. });
  23932. Object.defineProperty(Material.prototype, "onBind", {
  23933. set: function (callback) {
  23934. if (this._onBindObserver) {
  23935. this.onBindObservable.remove(this._onBindObserver);
  23936. }
  23937. this._onBindObserver = this.onBindObservable.add(callback);
  23938. },
  23939. enumerable: true,
  23940. configurable: true
  23941. });
  23942. Object.defineProperty(Material.prototype, "wireframe", {
  23943. get: function () {
  23944. return this._fillMode === Material.WireFrameFillMode;
  23945. },
  23946. set: function (value) {
  23947. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  23948. },
  23949. enumerable: true,
  23950. configurable: true
  23951. });
  23952. Object.defineProperty(Material.prototype, "pointsCloud", {
  23953. get: function () {
  23954. return this._fillMode === Material.PointFillMode;
  23955. },
  23956. set: function (value) {
  23957. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  23958. },
  23959. enumerable: true,
  23960. configurable: true
  23961. });
  23962. Object.defineProperty(Material.prototype, "fillMode", {
  23963. get: function () {
  23964. return this._fillMode;
  23965. },
  23966. set: function (value) {
  23967. this._fillMode = value;
  23968. },
  23969. enumerable: true,
  23970. configurable: true
  23971. });
  23972. /**
  23973. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  23974. * subclasses should override adding information pertainent to themselves
  23975. */
  23976. Material.prototype.toString = function (fullDetails) {
  23977. var ret = "Name: " + this.name;
  23978. if (fullDetails) {
  23979. }
  23980. return ret;
  23981. };
  23982. Object.defineProperty(Material.prototype, "isFrozen", {
  23983. get: function () {
  23984. return this.checkReadyOnlyOnce;
  23985. },
  23986. enumerable: true,
  23987. configurable: true
  23988. });
  23989. Material.prototype.freeze = function () {
  23990. this.checkReadyOnlyOnce = true;
  23991. };
  23992. Material.prototype.unfreeze = function () {
  23993. this.checkReadyOnlyOnce = false;
  23994. };
  23995. Material.prototype.isReady = function (mesh, useInstances) {
  23996. return true;
  23997. };
  23998. Material.prototype.getEffect = function () {
  23999. return this._effect;
  24000. };
  24001. Material.prototype.getScene = function () {
  24002. return this._scene;
  24003. };
  24004. Material.prototype.needAlphaBlending = function () {
  24005. return (this.alpha < 1.0);
  24006. };
  24007. Material.prototype.needAlphaTesting = function () {
  24008. return false;
  24009. };
  24010. Material.prototype.getAlphaTestTexture = function () {
  24011. return null;
  24012. };
  24013. Material.prototype.markDirty = function () {
  24014. this._wasPreviouslyReady = false;
  24015. };
  24016. Material.prototype._preBind = function () {
  24017. var engine = this._scene.getEngine();
  24018. engine.enableEffect(this._effect);
  24019. engine.setState(this.backFaceCulling, this.zOffset, false, this.sideOrientation === Material.ClockWiseSideOrientation);
  24020. };
  24021. Material.prototype.bind = function (world, mesh) {
  24022. this._scene._cachedMaterial = this;
  24023. this.onBindObservable.notifyObservers(mesh);
  24024. if (this.disableDepthWrite) {
  24025. var engine = this._scene.getEngine();
  24026. this._cachedDepthWriteState = engine.getDepthWrite();
  24027. engine.setDepthWrite(false);
  24028. }
  24029. };
  24030. Material.prototype.bindOnlyWorldMatrix = function (world) {
  24031. };
  24032. Material.prototype.unbind = function () {
  24033. if (this.disableDepthWrite) {
  24034. var engine = this._scene.getEngine();
  24035. engine.setDepthWrite(this._cachedDepthWriteState);
  24036. }
  24037. };
  24038. Material.prototype.clone = function (name) {
  24039. return null;
  24040. };
  24041. Material.prototype.getBindedMeshes = function () {
  24042. var result = new Array();
  24043. for (var index = 0; index < this._scene.meshes.length; index++) {
  24044. var mesh = this._scene.meshes[index];
  24045. if (mesh.material === this) {
  24046. result.push(mesh);
  24047. }
  24048. }
  24049. return result;
  24050. };
  24051. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  24052. // Animations
  24053. this.getScene().stopAnimation(this);
  24054. // Remove from scene
  24055. var index = this._scene.materials.indexOf(this);
  24056. if (index >= 0) {
  24057. this._scene.materials.splice(index, 1);
  24058. }
  24059. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  24060. if (forceDisposeEffect && this._effect) {
  24061. this._scene.getEngine()._releaseEffect(this._effect);
  24062. this._effect = null;
  24063. }
  24064. // Remove from meshes
  24065. for (index = 0; index < this._scene.meshes.length; index++) {
  24066. var mesh = this._scene.meshes[index];
  24067. if (mesh.material === this) {
  24068. mesh.material = null;
  24069. }
  24070. }
  24071. // Callback
  24072. this.onDisposeObservable.notifyObservers(this);
  24073. this.onDisposeObservable.clear();
  24074. this.onBindObservable.clear();
  24075. };
  24076. Material.prototype.serialize = function () {
  24077. return BABYLON.SerializationHelper.Serialize(this);
  24078. };
  24079. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  24080. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  24081. multiMaterial.id = parsedMultiMaterial.id;
  24082. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  24083. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  24084. var subMatId = parsedMultiMaterial.materials[matIndex];
  24085. if (subMatId) {
  24086. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  24087. }
  24088. else {
  24089. multiMaterial.subMaterials.push(null);
  24090. }
  24091. }
  24092. return multiMaterial;
  24093. };
  24094. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  24095. if (!parsedMaterial.customType) {
  24096. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  24097. }
  24098. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  24099. return materialType.Parse(parsedMaterial, scene, rootUrl);
  24100. ;
  24101. };
  24102. Material._TriangleFillMode = 0;
  24103. Material._WireFrameFillMode = 1;
  24104. Material._PointFillMode = 2;
  24105. Material._ClockWiseSideOrientation = 0;
  24106. Material._CounterClockWiseSideOrientation = 1;
  24107. __decorate([
  24108. BABYLON.serialize()
  24109. ], Material.prototype, "id", void 0);
  24110. __decorate([
  24111. BABYLON.serialize()
  24112. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  24113. __decorate([
  24114. BABYLON.serialize()
  24115. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  24116. __decorate([
  24117. BABYLON.serialize()
  24118. ], Material.prototype, "state", void 0);
  24119. __decorate([
  24120. BABYLON.serialize()
  24121. ], Material.prototype, "alpha", void 0);
  24122. __decorate([
  24123. BABYLON.serialize()
  24124. ], Material.prototype, "backFaceCulling", void 0);
  24125. __decorate([
  24126. BABYLON.serialize()
  24127. ], Material.prototype, "sideOrientation", void 0);
  24128. __decorate([
  24129. BABYLON.serialize()
  24130. ], Material.prototype, "alphaMode", void 0);
  24131. __decorate([
  24132. BABYLON.serialize()
  24133. ], Material.prototype, "disableDepthWrite", void 0);
  24134. __decorate([
  24135. BABYLON.serialize()
  24136. ], Material.prototype, "fogEnabled", void 0);
  24137. __decorate([
  24138. BABYLON.serialize()
  24139. ], Material.prototype, "pointSize", void 0);
  24140. __decorate([
  24141. BABYLON.serialize()
  24142. ], Material.prototype, "zOffset", void 0);
  24143. __decorate([
  24144. BABYLON.serialize()
  24145. ], Material.prototype, "wireframe", null);
  24146. __decorate([
  24147. BABYLON.serialize()
  24148. ], Material.prototype, "pointsCloud", null);
  24149. __decorate([
  24150. BABYLON.serialize()
  24151. ], Material.prototype, "fillMode", null);
  24152. return Material;
  24153. }());
  24154. BABYLON.Material = Material;
  24155. })(BABYLON || (BABYLON = {}));
  24156. var BABYLON;
  24157. (function (BABYLON) {
  24158. var StandardMaterialDefines = (function (_super) {
  24159. __extends(StandardMaterialDefines, _super);
  24160. function StandardMaterialDefines() {
  24161. _super.call(this);
  24162. this.DIFFUSE = false;
  24163. this.AMBIENT = false;
  24164. this.OPACITY = false;
  24165. this.OPACITYRGB = false;
  24166. this.REFLECTION = false;
  24167. this.EMISSIVE = false;
  24168. this.SPECULAR = false;
  24169. this.BUMP = false;
  24170. this.PARALLAX = false;
  24171. this.PARALLAXOCCLUSION = false;
  24172. this.SPECULAROVERALPHA = false;
  24173. this.CLIPPLANE = false;
  24174. this.ALPHATEST = false;
  24175. this.ALPHAFROMDIFFUSE = false;
  24176. this.POINTSIZE = false;
  24177. this.FOG = false;
  24178. this.SPECULARTERM = false;
  24179. this.DIFFUSEFRESNEL = false;
  24180. this.OPACITYFRESNEL = false;
  24181. this.REFLECTIONFRESNEL = false;
  24182. this.REFRACTIONFRESNEL = false;
  24183. this.EMISSIVEFRESNEL = false;
  24184. this.FRESNEL = false;
  24185. this.NORMAL = false;
  24186. this.UV1 = false;
  24187. this.UV2 = false;
  24188. this.VERTEXCOLOR = false;
  24189. this.VERTEXALPHA = false;
  24190. this.NUM_BONE_INFLUENCERS = 0;
  24191. this.BonesPerMesh = 0;
  24192. this.INSTANCES = false;
  24193. this.GLOSSINESS = false;
  24194. this.ROUGHNESS = false;
  24195. this.EMISSIVEASILLUMINATION = false;
  24196. this.LINKEMISSIVEWITHDIFFUSE = false;
  24197. this.REFLECTIONFRESNELFROMSPECULAR = false;
  24198. this.LIGHTMAP = false;
  24199. this.USELIGHTMAPASSHADOWMAP = false;
  24200. this.REFLECTIONMAP_3D = false;
  24201. this.REFLECTIONMAP_SPHERICAL = false;
  24202. this.REFLECTIONMAP_PLANAR = false;
  24203. this.REFLECTIONMAP_CUBIC = false;
  24204. this.REFLECTIONMAP_PROJECTION = false;
  24205. this.REFLECTIONMAP_SKYBOX = false;
  24206. this.REFLECTIONMAP_EXPLICIT = false;
  24207. this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  24208. this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  24209. this.INVERTCUBICMAP = false;
  24210. this.LOGARITHMICDEPTH = false;
  24211. this.REFRACTION = false;
  24212. this.REFRACTIONMAP_3D = false;
  24213. this.REFLECTIONOVERALPHA = false;
  24214. this.INVERTNORMALMAPX = false;
  24215. this.INVERTNORMALMAPY = false;
  24216. this.SHADOWFULLFLOAT = false;
  24217. this.CAMERACOLORGRADING = false;
  24218. this.CAMERACOLORCURVES = false;
  24219. this.rebuild();
  24220. }
  24221. return StandardMaterialDefines;
  24222. }(BABYLON.MaterialDefines));
  24223. var StandardMaterial = (function (_super) {
  24224. __extends(StandardMaterial, _super);
  24225. function StandardMaterial(name, scene) {
  24226. var _this = this;
  24227. _super.call(this, name, scene);
  24228. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  24229. this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  24230. this.specularColor = new BABYLON.Color3(1, 1, 1);
  24231. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  24232. this.specularPower = 64;
  24233. this.useAlphaFromDiffuseTexture = false;
  24234. this.useEmissiveAsIllumination = false;
  24235. this.linkEmissiveWithDiffuse = false;
  24236. this.useReflectionFresnelFromSpecular = false;
  24237. this.useSpecularOverAlpha = false;
  24238. this.useReflectionOverAlpha = false;
  24239. this.disableLighting = false;
  24240. this.useParallax = false;
  24241. this.useParallaxOcclusion = false;
  24242. this.parallaxScaleBias = 0.05;
  24243. this.roughness = 0;
  24244. this.indexOfRefraction = 0.98;
  24245. this.invertRefractionY = true;
  24246. this.useLightmapAsShadowmap = false;
  24247. this.useGlossinessFromSpecularMapAlpha = false;
  24248. this.maxSimultaneousLights = 4;
  24249. /**
  24250. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  24251. */
  24252. this.invertNormalMapX = false;
  24253. /**
  24254. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  24255. */
  24256. this.invertNormalMapY = false;
  24257. /**
  24258. * Color Grading 2D Lookup Texture.
  24259. * This allows special effects like sepia, black and white to sixties rendering style.
  24260. */
  24261. this.cameraColorGradingTexture = null;
  24262. /**
  24263. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  24264. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  24265. * 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;
  24266. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  24267. */
  24268. this.cameraColorCurves = null;
  24269. this._renderTargets = new BABYLON.SmartArray(16);
  24270. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  24271. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  24272. this._defines = new StandardMaterialDefines();
  24273. this._cachedDefines = new StandardMaterialDefines();
  24274. this._cachedDefines.BonesPerMesh = -1;
  24275. this.getRenderTargetTextures = function () {
  24276. _this._renderTargets.reset();
  24277. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  24278. _this._renderTargets.push(_this.reflectionTexture);
  24279. }
  24280. if (_this.refractionTexture && _this.refractionTexture.isRenderTarget) {
  24281. _this._renderTargets.push(_this.refractionTexture);
  24282. }
  24283. return _this._renderTargets;
  24284. };
  24285. }
  24286. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  24287. get: function () {
  24288. return this._useLogarithmicDepth;
  24289. },
  24290. set: function (value) {
  24291. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  24292. },
  24293. enumerable: true,
  24294. configurable: true
  24295. });
  24296. StandardMaterial.prototype.needAlphaBlending = function () {
  24297. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  24298. };
  24299. StandardMaterial.prototype.needAlphaTesting = function () {
  24300. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha;
  24301. };
  24302. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  24303. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  24304. };
  24305. StandardMaterial.prototype.getAlphaTestTexture = function () {
  24306. return this.diffuseTexture;
  24307. };
  24308. // Methods
  24309. StandardMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  24310. if (!mesh) {
  24311. return true;
  24312. }
  24313. if (this._defines.INSTANCES !== useInstances) {
  24314. return false;
  24315. }
  24316. if (mesh._materialDefines && mesh._materialDefines.isEqual(this._defines)) {
  24317. return true;
  24318. }
  24319. return false;
  24320. };
  24321. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  24322. if (this.isFrozen) {
  24323. if (this._wasPreviouslyReady) {
  24324. return true;
  24325. }
  24326. }
  24327. var scene = this.getScene();
  24328. if (!this.checkReadyOnEveryCall) {
  24329. if (this._renderId === scene.getRenderId()) {
  24330. if (this._checkCache(scene, mesh, useInstances)) {
  24331. return true;
  24332. }
  24333. }
  24334. }
  24335. var engine = scene.getEngine();
  24336. var needNormals = false;
  24337. var needUVs = false;
  24338. this._defines.reset();
  24339. // Textures
  24340. if (scene.texturesEnabled) {
  24341. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  24342. if (!this.diffuseTexture.isReady()) {
  24343. return false;
  24344. }
  24345. else {
  24346. needUVs = true;
  24347. this._defines.DIFFUSE = true;
  24348. }
  24349. }
  24350. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  24351. if (!this.ambientTexture.isReady()) {
  24352. return false;
  24353. }
  24354. else {
  24355. needUVs = true;
  24356. this._defines.AMBIENT = true;
  24357. }
  24358. }
  24359. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  24360. if (!this.opacityTexture.isReady()) {
  24361. return false;
  24362. }
  24363. else {
  24364. needUVs = true;
  24365. this._defines.OPACITY = true;
  24366. if (this.opacityTexture.getAlphaFromRGB) {
  24367. this._defines.OPACITYRGB = true;
  24368. }
  24369. }
  24370. }
  24371. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  24372. if (!this.reflectionTexture.isReady()) {
  24373. return false;
  24374. }
  24375. else {
  24376. needNormals = true;
  24377. this._defines.REFLECTION = true;
  24378. if (this.roughness > 0) {
  24379. this._defines.ROUGHNESS = true;
  24380. }
  24381. if (this.useReflectionOverAlpha) {
  24382. this._defines.REFLECTIONOVERALPHA = true;
  24383. }
  24384. if (this.reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  24385. this._defines.INVERTCUBICMAP = true;
  24386. }
  24387. this._defines.REFLECTIONMAP_3D = this.reflectionTexture.isCube;
  24388. switch (this.reflectionTexture.coordinatesMode) {
  24389. case BABYLON.Texture.CUBIC_MODE:
  24390. case BABYLON.Texture.INVCUBIC_MODE:
  24391. this._defines.REFLECTIONMAP_CUBIC = true;
  24392. break;
  24393. case BABYLON.Texture.EXPLICIT_MODE:
  24394. this._defines.REFLECTIONMAP_EXPLICIT = true;
  24395. break;
  24396. case BABYLON.Texture.PLANAR_MODE:
  24397. this._defines.REFLECTIONMAP_PLANAR = true;
  24398. break;
  24399. case BABYLON.Texture.PROJECTION_MODE:
  24400. this._defines.REFLECTIONMAP_PROJECTION = true;
  24401. break;
  24402. case BABYLON.Texture.SKYBOX_MODE:
  24403. this._defines.REFLECTIONMAP_SKYBOX = true;
  24404. break;
  24405. case BABYLON.Texture.SPHERICAL_MODE:
  24406. this._defines.REFLECTIONMAP_SPHERICAL = true;
  24407. break;
  24408. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  24409. this._defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  24410. break;
  24411. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  24412. this._defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  24413. break;
  24414. }
  24415. }
  24416. }
  24417. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  24418. if (!this.emissiveTexture.isReady()) {
  24419. return false;
  24420. }
  24421. else {
  24422. needUVs = true;
  24423. this._defines.EMISSIVE = true;
  24424. }
  24425. }
  24426. if (this.lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  24427. if (!this.lightmapTexture.isReady()) {
  24428. return false;
  24429. }
  24430. else {
  24431. needUVs = true;
  24432. this._defines.LIGHTMAP = true;
  24433. this._defines.USELIGHTMAPASSHADOWMAP = this.useLightmapAsShadowmap;
  24434. }
  24435. }
  24436. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  24437. if (!this.specularTexture.isReady()) {
  24438. return false;
  24439. }
  24440. else {
  24441. needUVs = true;
  24442. this._defines.SPECULAR = true;
  24443. this._defines.GLOSSINESS = this.useGlossinessFromSpecularMapAlpha;
  24444. }
  24445. }
  24446. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && StandardMaterial.BumpTextureEnabled) {
  24447. if (!this.bumpTexture.isReady()) {
  24448. return false;
  24449. }
  24450. else {
  24451. needUVs = true;
  24452. this._defines.BUMP = true;
  24453. if (this.useParallax) {
  24454. this._defines.PARALLAX = true;
  24455. if (this.useParallaxOcclusion) {
  24456. this._defines.PARALLAXOCCLUSION = true;
  24457. }
  24458. }
  24459. if (this.invertNormalMapX) {
  24460. this._defines.INVERTNORMALMAPX = true;
  24461. }
  24462. if (this.invertNormalMapY) {
  24463. this._defines.INVERTNORMALMAPY = true;
  24464. }
  24465. }
  24466. }
  24467. if (this.refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  24468. if (!this.refractionTexture.isReady()) {
  24469. return false;
  24470. }
  24471. else {
  24472. needUVs = true;
  24473. this._defines.REFRACTION = true;
  24474. this._defines.REFRACTIONMAP_3D = this.refractionTexture.isCube;
  24475. }
  24476. }
  24477. if (this.cameraColorGradingTexture && StandardMaterial.ColorGradingTextureEnabled) {
  24478. if (!this.cameraColorGradingTexture.isReady()) {
  24479. return false;
  24480. }
  24481. else {
  24482. this._defines.CAMERACOLORGRADING = true;
  24483. }
  24484. }
  24485. }
  24486. // Effect
  24487. if (scene.clipPlane) {
  24488. this._defines.CLIPPLANE = true;
  24489. }
  24490. if (engine.getAlphaTesting()) {
  24491. this._defines.ALPHATEST = true;
  24492. }
  24493. if (this._shouldUseAlphaFromDiffuseTexture()) {
  24494. this._defines.ALPHAFROMDIFFUSE = true;
  24495. }
  24496. if (this.useEmissiveAsIllumination) {
  24497. this._defines.EMISSIVEASILLUMINATION = true;
  24498. }
  24499. if (this.linkEmissiveWithDiffuse) {
  24500. this._defines.LINKEMISSIVEWITHDIFFUSE = true;
  24501. }
  24502. if (this.useLogarithmicDepth) {
  24503. this._defines.LOGARITHMICDEPTH = true;
  24504. }
  24505. if (this.cameraColorCurves) {
  24506. this._defines.CAMERACOLORCURVES = true;
  24507. }
  24508. // Point size
  24509. if (this.pointsCloud || scene.forcePointsCloud) {
  24510. this._defines.POINTSIZE = true;
  24511. }
  24512. // Fog
  24513. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  24514. this._defines.FOG = true;
  24515. }
  24516. if (scene.lightsEnabled && !this.disableLighting) {
  24517. needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, this._defines, this.maxSimultaneousLights);
  24518. }
  24519. if (StandardMaterial.FresnelEnabled) {
  24520. // Fresnel
  24521. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled ||
  24522. this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  24523. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled ||
  24524. this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled ||
  24525. this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  24526. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  24527. this._defines.DIFFUSEFRESNEL = true;
  24528. }
  24529. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  24530. this._defines.OPACITYFRESNEL = true;
  24531. }
  24532. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  24533. this._defines.REFLECTIONFRESNEL = true;
  24534. if (this.useReflectionFresnelFromSpecular) {
  24535. this._defines.REFLECTIONFRESNELFROMSPECULAR = true;
  24536. }
  24537. }
  24538. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  24539. this._defines.REFRACTIONFRESNEL = true;
  24540. }
  24541. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  24542. this._defines.EMISSIVEFRESNEL = true;
  24543. }
  24544. needNormals = true;
  24545. this._defines.FRESNEL = true;
  24546. }
  24547. }
  24548. if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
  24549. this._defines.SPECULAROVERALPHA = true;
  24550. }
  24551. // Attribs
  24552. if (mesh) {
  24553. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  24554. this._defines.NORMAL = true;
  24555. }
  24556. if (needUVs) {
  24557. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  24558. this._defines.UV1 = true;
  24559. }
  24560. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  24561. this._defines.UV2 = true;
  24562. }
  24563. }
  24564. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  24565. this._defines.VERTEXCOLOR = true;
  24566. if (mesh.hasVertexAlpha) {
  24567. this._defines.VERTEXALPHA = true;
  24568. }
  24569. }
  24570. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  24571. this._defines.NUM_BONE_INFLUENCERS = mesh.numBoneInfluencers;
  24572. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  24573. }
  24574. // Instances
  24575. if (useInstances) {
  24576. this._defines.INSTANCES = true;
  24577. }
  24578. }
  24579. // Get correct effect
  24580. if (!this._defines.isEqual(this._cachedDefines)) {
  24581. this._defines.cloneTo(this._cachedDefines);
  24582. scene.resetCachedMaterial();
  24583. // Fallbacks
  24584. var fallbacks = new BABYLON.EffectFallbacks();
  24585. if (this._defines.REFLECTION) {
  24586. fallbacks.addFallback(0, "REFLECTION");
  24587. }
  24588. if (this._defines.SPECULAR) {
  24589. fallbacks.addFallback(0, "SPECULAR");
  24590. }
  24591. if (this._defines.BUMP) {
  24592. fallbacks.addFallback(0, "BUMP");
  24593. }
  24594. if (this._defines.PARALLAX) {
  24595. fallbacks.addFallback(1, "PARALLAX");
  24596. }
  24597. if (this._defines.PARALLAXOCCLUSION) {
  24598. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  24599. }
  24600. if (this._defines.SPECULAROVERALPHA) {
  24601. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  24602. }
  24603. if (this._defines.FOG) {
  24604. fallbacks.addFallback(1, "FOG");
  24605. }
  24606. if (this._defines.POINTSIZE) {
  24607. fallbacks.addFallback(0, "POINTSIZE");
  24608. }
  24609. if (this._defines.LOGARITHMICDEPTH) {
  24610. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  24611. }
  24612. BABYLON.MaterialHelper.HandleFallbacksForShadows(this._defines, fallbacks, this.maxSimultaneousLights);
  24613. if (this._defines.SPECULARTERM) {
  24614. fallbacks.addFallback(0, "SPECULARTERM");
  24615. }
  24616. if (this._defines.DIFFUSEFRESNEL) {
  24617. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  24618. }
  24619. if (this._defines.OPACITYFRESNEL) {
  24620. fallbacks.addFallback(2, "OPACITYFRESNEL");
  24621. }
  24622. if (this._defines.REFLECTIONFRESNEL) {
  24623. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  24624. }
  24625. if (this._defines.EMISSIVEFRESNEL) {
  24626. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  24627. }
  24628. if (this._defines.FRESNEL) {
  24629. fallbacks.addFallback(4, "FRESNEL");
  24630. }
  24631. //Attributes
  24632. var attribs = [BABYLON.VertexBuffer.PositionKind];
  24633. if (this._defines.NORMAL) {
  24634. attribs.push(BABYLON.VertexBuffer.NormalKind);
  24635. }
  24636. if (this._defines.UV1) {
  24637. attribs.push(BABYLON.VertexBuffer.UVKind);
  24638. }
  24639. if (this._defines.UV2) {
  24640. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  24641. }
  24642. if (this._defines.VERTEXCOLOR) {
  24643. attribs.push(BABYLON.VertexBuffer.ColorKind);
  24644. }
  24645. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, this._defines, fallbacks);
  24646. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, this._defines);
  24647. var shaderName = "default";
  24648. var join = this._defines.toString();
  24649. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  24650. "vFogInfos", "vFogColor", "pointSize",
  24651. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  24652. "mBones",
  24653. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  24654. "depthValues",
  24655. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  24656. "logarithmicDepthConstant"
  24657. ];
  24658. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  24659. if (this._defines.CAMERACOLORCURVES) {
  24660. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  24661. }
  24662. if (this._defines.CAMERACOLORGRADING) {
  24663. BABYLON.ColorGradingTexture.PrepareUniformsAndSamplers(uniforms, samplers);
  24664. }
  24665. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList(uniforms, samplers, this._defines, this.maxSimultaneousLights);
  24666. this._effect = scene.getEngine().createEffect(shaderName, attribs, uniforms, samplers, join, fallbacks, this.onCompiled, this.onError, { maxSimultaneousLights: this.maxSimultaneousLights - 1 });
  24667. }
  24668. if (!this._effect.isReady()) {
  24669. return false;
  24670. }
  24671. this._renderId = scene.getRenderId();
  24672. this._wasPreviouslyReady = true;
  24673. if (mesh) {
  24674. if (!mesh._materialDefines) {
  24675. mesh._materialDefines = new StandardMaterialDefines();
  24676. }
  24677. this._defines.cloneTo(mesh._materialDefines);
  24678. }
  24679. return true;
  24680. };
  24681. StandardMaterial.prototype.unbind = function () {
  24682. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  24683. this._effect.setTexture("reflection2DSampler", null);
  24684. }
  24685. if (this.refractionTexture && this.refractionTexture.isRenderTarget) {
  24686. this._effect.setTexture("refraction2DSampler", null);
  24687. }
  24688. _super.prototype.unbind.call(this);
  24689. };
  24690. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  24691. this._effect.setMatrix("world", world);
  24692. };
  24693. StandardMaterial.prototype.bind = function (world, mesh) {
  24694. var scene = this.getScene();
  24695. // Matrices
  24696. this.bindOnlyWorldMatrix(world);
  24697. // Bones
  24698. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  24699. if (scene.getCachedMaterial() !== this) {
  24700. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  24701. if (StandardMaterial.FresnelEnabled) {
  24702. // Fresnel
  24703. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  24704. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  24705. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  24706. }
  24707. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  24708. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  24709. }
  24710. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  24711. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  24712. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  24713. }
  24714. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  24715. this._effect.setColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  24716. this._effect.setColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  24717. }
  24718. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  24719. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  24720. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  24721. }
  24722. }
  24723. // Textures
  24724. if (scene.texturesEnabled) {
  24725. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  24726. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  24727. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  24728. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  24729. }
  24730. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  24731. this._effect.setTexture("ambientSampler", this.ambientTexture);
  24732. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  24733. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  24734. }
  24735. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  24736. this._effect.setTexture("opacitySampler", this.opacityTexture);
  24737. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  24738. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  24739. }
  24740. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  24741. if (this.reflectionTexture.isCube) {
  24742. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  24743. }
  24744. else {
  24745. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  24746. }
  24747. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  24748. this._effect.setFloat2("vReflectionInfos", this.reflectionTexture.level, this.roughness);
  24749. }
  24750. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  24751. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  24752. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  24753. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  24754. }
  24755. if (this.lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  24756. this._effect.setTexture("lightmapSampler", this.lightmapTexture);
  24757. this._effect.setFloat2("vLightmapInfos", this.lightmapTexture.coordinatesIndex, this.lightmapTexture.level);
  24758. this._effect.setMatrix("lightmapMatrix", this.lightmapTexture.getTextureMatrix());
  24759. }
  24760. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  24761. this._effect.setTexture("specularSampler", this.specularTexture);
  24762. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  24763. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  24764. }
  24765. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  24766. this._effect.setTexture("bumpSampler", this.bumpTexture);
  24767. this._effect.setFloat3("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level, this.parallaxScaleBias);
  24768. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  24769. }
  24770. if (this.refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  24771. var depth = 1.0;
  24772. if (this.refractionTexture.isCube) {
  24773. this._effect.setTexture("refractionCubeSampler", this.refractionTexture);
  24774. }
  24775. else {
  24776. this._effect.setTexture("refraction2DSampler", this.refractionTexture);
  24777. this._effect.setMatrix("refractionMatrix", this.refractionTexture.getReflectionTextureMatrix());
  24778. if (this.refractionTexture.depth) {
  24779. depth = this.refractionTexture.depth;
  24780. }
  24781. }
  24782. this._effect.setFloat4("vRefractionInfos", this.refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  24783. }
  24784. if (this.cameraColorGradingTexture && StandardMaterial.ColorGradingTextureEnabled) {
  24785. BABYLON.ColorGradingTexture.Bind(this.cameraColorGradingTexture, this._effect);
  24786. }
  24787. }
  24788. // Clip plane
  24789. BABYLON.MaterialHelper.BindClipPlane(this._effect, scene);
  24790. // Point size
  24791. if (this.pointsCloud) {
  24792. this._effect.setFloat("pointSize", this.pointSize);
  24793. }
  24794. // Colors
  24795. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  24796. this._effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.position);
  24797. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  24798. if (this._defines.SPECULARTERM) {
  24799. this._effect.setColor4("vSpecularColor", this.specularColor, this.specularPower);
  24800. }
  24801. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  24802. }
  24803. if (scene.getCachedMaterial() !== this || !this.isFrozen) {
  24804. // Diffuse
  24805. this._effect.setColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  24806. // Lights
  24807. if (scene.lightsEnabled && !this.disableLighting) {
  24808. BABYLON.MaterialHelper.BindLights(scene, mesh, this._effect, this._defines, this.maxSimultaneousLights);
  24809. }
  24810. // View
  24811. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture || this.refractionTexture) {
  24812. this._effect.setMatrix("view", scene.getViewMatrix());
  24813. }
  24814. // Fog
  24815. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._effect);
  24816. // Log. depth
  24817. BABYLON.MaterialHelper.BindLogDepth(this._defines, this._effect, scene);
  24818. // Color Curves
  24819. if (this.cameraColorCurves) {
  24820. BABYLON.ColorCurves.Bind(this.cameraColorCurves, this._effect);
  24821. }
  24822. }
  24823. _super.prototype.bind.call(this, world, mesh);
  24824. };
  24825. StandardMaterial.prototype.getAnimatables = function () {
  24826. var results = [];
  24827. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  24828. results.push(this.diffuseTexture);
  24829. }
  24830. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  24831. results.push(this.ambientTexture);
  24832. }
  24833. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  24834. results.push(this.opacityTexture);
  24835. }
  24836. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  24837. results.push(this.reflectionTexture);
  24838. }
  24839. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  24840. results.push(this.emissiveTexture);
  24841. }
  24842. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  24843. results.push(this.specularTexture);
  24844. }
  24845. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  24846. results.push(this.bumpTexture);
  24847. }
  24848. if (this.lightmapTexture && this.lightmapTexture.animations && this.lightmapTexture.animations.length > 0) {
  24849. results.push(this.lightmapTexture);
  24850. }
  24851. if (this.refractionTexture && this.refractionTexture.animations && this.refractionTexture.animations.length > 0) {
  24852. results.push(this.refractionTexture);
  24853. }
  24854. if (this.cameraColorGradingTexture && this.cameraColorGradingTexture.animations && this.cameraColorGradingTexture.animations.length > 0) {
  24855. results.push(this.cameraColorGradingTexture);
  24856. }
  24857. return results;
  24858. };
  24859. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  24860. if (forceDisposeTextures) {
  24861. if (this.diffuseTexture) {
  24862. this.diffuseTexture.dispose();
  24863. }
  24864. if (this.ambientTexture) {
  24865. this.ambientTexture.dispose();
  24866. }
  24867. if (this.opacityTexture) {
  24868. this.opacityTexture.dispose();
  24869. }
  24870. if (this.reflectionTexture) {
  24871. this.reflectionTexture.dispose();
  24872. }
  24873. if (this.emissiveTexture) {
  24874. this.emissiveTexture.dispose();
  24875. }
  24876. if (this.specularTexture) {
  24877. this.specularTexture.dispose();
  24878. }
  24879. if (this.bumpTexture) {
  24880. this.bumpTexture.dispose();
  24881. }
  24882. if (this.lightmapTexture) {
  24883. this.lightmapTexture.dispose();
  24884. }
  24885. if (this.refractionTexture) {
  24886. this.refractionTexture.dispose();
  24887. }
  24888. if (this.cameraColorGradingTexture) {
  24889. this.cameraColorGradingTexture.dispose();
  24890. }
  24891. }
  24892. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  24893. };
  24894. StandardMaterial.prototype.clone = function (name) {
  24895. var _this = this;
  24896. return BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  24897. };
  24898. StandardMaterial.prototype.serialize = function () {
  24899. return BABYLON.SerializationHelper.Serialize(this);
  24900. };
  24901. // Statics
  24902. StandardMaterial.Parse = function (source, scene, rootUrl) {
  24903. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  24904. };
  24905. // Flags used to enable or disable a type of texture for all Standard Materials
  24906. StandardMaterial.DiffuseTextureEnabled = true;
  24907. StandardMaterial.AmbientTextureEnabled = true;
  24908. StandardMaterial.OpacityTextureEnabled = true;
  24909. StandardMaterial.ReflectionTextureEnabled = true;
  24910. StandardMaterial.EmissiveTextureEnabled = true;
  24911. StandardMaterial.SpecularTextureEnabled = true;
  24912. StandardMaterial.BumpTextureEnabled = true;
  24913. StandardMaterial.FresnelEnabled = true;
  24914. StandardMaterial.LightmapTextureEnabled = true;
  24915. StandardMaterial.RefractionTextureEnabled = true;
  24916. StandardMaterial.ColorGradingTextureEnabled = true;
  24917. __decorate([
  24918. BABYLON.serializeAsTexture()
  24919. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  24920. __decorate([
  24921. BABYLON.serializeAsTexture()
  24922. ], StandardMaterial.prototype, "ambientTexture", void 0);
  24923. __decorate([
  24924. BABYLON.serializeAsTexture()
  24925. ], StandardMaterial.prototype, "opacityTexture", void 0);
  24926. __decorate([
  24927. BABYLON.serializeAsTexture()
  24928. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  24929. __decorate([
  24930. BABYLON.serializeAsTexture()
  24931. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  24932. __decorate([
  24933. BABYLON.serializeAsTexture()
  24934. ], StandardMaterial.prototype, "specularTexture", void 0);
  24935. __decorate([
  24936. BABYLON.serializeAsTexture()
  24937. ], StandardMaterial.prototype, "bumpTexture", void 0);
  24938. __decorate([
  24939. BABYLON.serializeAsTexture()
  24940. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  24941. __decorate([
  24942. BABYLON.serializeAsTexture()
  24943. ], StandardMaterial.prototype, "refractionTexture", void 0);
  24944. __decorate([
  24945. BABYLON.serializeAsColor3("ambient")
  24946. ], StandardMaterial.prototype, "ambientColor", void 0);
  24947. __decorate([
  24948. BABYLON.serializeAsColor3("diffuse")
  24949. ], StandardMaterial.prototype, "diffuseColor", void 0);
  24950. __decorate([
  24951. BABYLON.serializeAsColor3("specular")
  24952. ], StandardMaterial.prototype, "specularColor", void 0);
  24953. __decorate([
  24954. BABYLON.serializeAsColor3("emissive")
  24955. ], StandardMaterial.prototype, "emissiveColor", void 0);
  24956. __decorate([
  24957. BABYLON.serialize()
  24958. ], StandardMaterial.prototype, "specularPower", void 0);
  24959. __decorate([
  24960. BABYLON.serialize()
  24961. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  24962. __decorate([
  24963. BABYLON.serialize()
  24964. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  24965. __decorate([
  24966. BABYLON.serialize()
  24967. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  24968. __decorate([
  24969. BABYLON.serialize()
  24970. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  24971. __decorate([
  24972. BABYLON.serialize()
  24973. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  24974. __decorate([
  24975. BABYLON.serialize()
  24976. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  24977. __decorate([
  24978. BABYLON.serialize()
  24979. ], StandardMaterial.prototype, "disableLighting", void 0);
  24980. __decorate([
  24981. BABYLON.serialize()
  24982. ], StandardMaterial.prototype, "useParallax", void 0);
  24983. __decorate([
  24984. BABYLON.serialize()
  24985. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  24986. __decorate([
  24987. BABYLON.serialize()
  24988. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  24989. __decorate([
  24990. BABYLON.serialize()
  24991. ], StandardMaterial.prototype, "roughness", void 0);
  24992. __decorate([
  24993. BABYLON.serialize()
  24994. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  24995. __decorate([
  24996. BABYLON.serialize()
  24997. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  24998. __decorate([
  24999. BABYLON.serialize()
  25000. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  25001. __decorate([
  25002. BABYLON.serializeAsFresnelParameters()
  25003. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  25004. __decorate([
  25005. BABYLON.serializeAsFresnelParameters()
  25006. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  25007. __decorate([
  25008. BABYLON.serializeAsFresnelParameters()
  25009. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  25010. __decorate([
  25011. BABYLON.serializeAsFresnelParameters()
  25012. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  25013. __decorate([
  25014. BABYLON.serializeAsFresnelParameters()
  25015. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  25016. __decorate([
  25017. BABYLON.serialize()
  25018. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  25019. __decorate([
  25020. BABYLON.serialize()
  25021. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  25022. __decorate([
  25023. BABYLON.serialize()
  25024. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  25025. __decorate([
  25026. BABYLON.serialize()
  25027. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  25028. __decorate([
  25029. BABYLON.serializeAsTexture()
  25030. ], StandardMaterial.prototype, "cameraColorGradingTexture", void 0);
  25031. __decorate([
  25032. BABYLON.serializeAsColorCurves()
  25033. ], StandardMaterial.prototype, "cameraColorCurves", void 0);
  25034. __decorate([
  25035. BABYLON.serialize()
  25036. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  25037. return StandardMaterial;
  25038. }(BABYLON.Material));
  25039. BABYLON.StandardMaterial = StandardMaterial;
  25040. })(BABYLON || (BABYLON = {}));
  25041. var BABYLON;
  25042. (function (BABYLON) {
  25043. var MultiMaterial = (function (_super) {
  25044. __extends(MultiMaterial, _super);
  25045. function MultiMaterial(name, scene) {
  25046. _super.call(this, name, scene, true);
  25047. this.subMaterials = new Array();
  25048. scene.multiMaterials.push(this);
  25049. }
  25050. // Properties
  25051. MultiMaterial.prototype.getSubMaterial = function (index) {
  25052. if (index < 0 || index >= this.subMaterials.length) {
  25053. return this.getScene().defaultMaterial;
  25054. }
  25055. return this.subMaterials[index];
  25056. };
  25057. // Methods
  25058. MultiMaterial.prototype.isReady = function (mesh) {
  25059. for (var index = 0; index < this.subMaterials.length; index++) {
  25060. var subMaterial = this.subMaterials[index];
  25061. if (subMaterial) {
  25062. if (!this.subMaterials[index].isReady(mesh)) {
  25063. return false;
  25064. }
  25065. }
  25066. }
  25067. return true;
  25068. };
  25069. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  25070. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  25071. for (var index = 0; index < this.subMaterials.length; index++) {
  25072. var subMaterial = null;
  25073. if (cloneChildren) {
  25074. subMaterial = this.subMaterials[index].clone(name + "-" + this.subMaterials[index].name);
  25075. }
  25076. else {
  25077. subMaterial = this.subMaterials[index];
  25078. }
  25079. newMultiMaterial.subMaterials.push(subMaterial);
  25080. }
  25081. return newMultiMaterial;
  25082. };
  25083. MultiMaterial.prototype.serialize = function () {
  25084. var serializationObject = {};
  25085. serializationObject.name = this.name;
  25086. serializationObject.id = this.id;
  25087. serializationObject.tags = BABYLON.Tags.GetTags(this);
  25088. serializationObject.materials = [];
  25089. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  25090. var subMat = this.subMaterials[matIndex];
  25091. if (subMat) {
  25092. serializationObject.materials.push(subMat.id);
  25093. }
  25094. else {
  25095. serializationObject.materials.push(null);
  25096. }
  25097. }
  25098. return serializationObject;
  25099. };
  25100. return MultiMaterial;
  25101. }(BABYLON.Material));
  25102. BABYLON.MultiMaterial = MultiMaterial;
  25103. })(BABYLON || (BABYLON = {}));
  25104. var BABYLON;
  25105. (function (BABYLON) {
  25106. var SceneLoader = (function () {
  25107. function SceneLoader() {
  25108. }
  25109. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  25110. get: function () {
  25111. return 0;
  25112. },
  25113. enumerable: true,
  25114. configurable: true
  25115. });
  25116. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  25117. get: function () {
  25118. return 1;
  25119. },
  25120. enumerable: true,
  25121. configurable: true
  25122. });
  25123. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  25124. get: function () {
  25125. return 2;
  25126. },
  25127. enumerable: true,
  25128. configurable: true
  25129. });
  25130. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  25131. get: function () {
  25132. return 3;
  25133. },
  25134. enumerable: true,
  25135. configurable: true
  25136. });
  25137. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  25138. get: function () {
  25139. return SceneLoader._ForceFullSceneLoadingForIncremental;
  25140. },
  25141. set: function (value) {
  25142. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  25143. },
  25144. enumerable: true,
  25145. configurable: true
  25146. });
  25147. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  25148. get: function () {
  25149. return SceneLoader._ShowLoadingScreen;
  25150. },
  25151. set: function (value) {
  25152. SceneLoader._ShowLoadingScreen = value;
  25153. },
  25154. enumerable: true,
  25155. configurable: true
  25156. });
  25157. Object.defineProperty(SceneLoader, "loggingLevel", {
  25158. get: function () {
  25159. return SceneLoader._loggingLevel;
  25160. },
  25161. set: function (value) {
  25162. SceneLoader._loggingLevel = value;
  25163. },
  25164. enumerable: true,
  25165. configurable: true
  25166. });
  25167. SceneLoader._getPluginForFilename = function (sceneFilename) {
  25168. var dotPosition = sceneFilename.lastIndexOf(".");
  25169. var queryStringPosition = sceneFilename.indexOf("?");
  25170. if (queryStringPosition === -1) {
  25171. queryStringPosition = sceneFilename.length;
  25172. }
  25173. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  25174. for (var index = 0; index < this._registeredPlugins.length; index++) {
  25175. var plugin = this._registeredPlugins[index];
  25176. if (plugin.extensions.indexOf(extension) !== -1) {
  25177. return plugin;
  25178. }
  25179. }
  25180. return this._registeredPlugins[0];
  25181. };
  25182. // Public functions
  25183. SceneLoader.GetPluginForExtension = function (extension) {
  25184. for (var index = 0; index < this._registeredPlugins.length; index++) {
  25185. var plugin = this._registeredPlugins[index];
  25186. if (plugin.extensions.indexOf(extension) !== -1) {
  25187. return plugin;
  25188. }
  25189. }
  25190. return null;
  25191. };
  25192. SceneLoader.RegisterPlugin = function (plugin) {
  25193. plugin.extensions = plugin.extensions.toLowerCase();
  25194. SceneLoader._registeredPlugins.push(plugin);
  25195. };
  25196. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  25197. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  25198. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  25199. return;
  25200. }
  25201. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  25202. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  25203. return;
  25204. }
  25205. var loadingToken = {};
  25206. scene._addPendingData(loadingToken);
  25207. var manifestChecked = function (success) {
  25208. scene.database = database;
  25209. var plugin = SceneLoader._getPluginForFilename(sceneFilename);
  25210. var importMeshFromData = function (data) {
  25211. var meshes = [];
  25212. var particleSystems = [];
  25213. var skeletons = [];
  25214. try {
  25215. if (plugin.importMesh) {
  25216. var syncedPlugin = plugin;
  25217. if (!syncedPlugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  25218. if (onerror) {
  25219. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  25220. }
  25221. scene._removePendingData(loadingToken);
  25222. return;
  25223. }
  25224. if (onsuccess) {
  25225. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  25226. onsuccess(meshes, particleSystems, skeletons);
  25227. scene._removePendingData(loadingToken);
  25228. }
  25229. }
  25230. else {
  25231. var asyncedPlugin = plugin;
  25232. asyncedPlugin.importMeshAsync(meshesNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  25233. if (onsuccess) {
  25234. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  25235. onsuccess(meshes, particleSystems, skeletons);
  25236. scene._removePendingData(loadingToken);
  25237. }
  25238. }, function () {
  25239. if (onerror) {
  25240. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  25241. }
  25242. scene._removePendingData(loadingToken);
  25243. });
  25244. }
  25245. }
  25246. catch (e) {
  25247. if (onerror) {
  25248. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename, e);
  25249. }
  25250. scene._removePendingData(loadingToken);
  25251. }
  25252. };
  25253. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  25254. // Direct load
  25255. importMeshFromData(sceneFilename.substr(5));
  25256. return;
  25257. }
  25258. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  25259. importMeshFromData(data);
  25260. }, progressCallBack, database);
  25261. };
  25262. if (scene.getEngine().enableOfflineSupport && !(sceneFilename.substr && sceneFilename.substr(0, 5) === "data:")) {
  25263. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  25264. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  25265. }
  25266. else {
  25267. // If the scene is a data stream or offline support is not enabled, it's a direct load
  25268. manifestChecked(true);
  25269. }
  25270. };
  25271. /**
  25272. * Load a scene
  25273. * @param rootUrl a string that defines the root url for scene and resources
  25274. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  25275. * @param engine is the instance of BABYLON.Engine to use to create the scene
  25276. */
  25277. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  25278. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  25279. };
  25280. /**
  25281. * Append a scene
  25282. * @param rootUrl a string that defines the root url for scene and resources
  25283. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  25284. * @param scene is the instance of BABYLON.Scene to append to
  25285. */
  25286. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  25287. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  25288. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  25289. return;
  25290. }
  25291. var plugin = this._getPluginForFilename(sceneFilename.name || sceneFilename);
  25292. var database;
  25293. var loadingToken = {};
  25294. scene._addPendingData(loadingToken);
  25295. if (SceneLoader.ShowLoadingScreen) {
  25296. scene.getEngine().displayLoadingUI();
  25297. }
  25298. var loadSceneFromData = function (data) {
  25299. scene.database = database;
  25300. if (plugin.load) {
  25301. var syncedPlugin = plugin;
  25302. if (!syncedPlugin.load(scene, data, rootUrl)) {
  25303. if (onerror) {
  25304. onerror(scene);
  25305. }
  25306. scene._removePendingData(loadingToken);
  25307. scene.getEngine().hideLoadingUI();
  25308. return;
  25309. }
  25310. if (onsuccess) {
  25311. onsuccess(scene);
  25312. }
  25313. scene._removePendingData(loadingToken);
  25314. }
  25315. else {
  25316. var asyncedPlugin = plugin;
  25317. asyncedPlugin.loadAsync(scene, data, rootUrl, function () {
  25318. if (onsuccess) {
  25319. onsuccess(scene);
  25320. }
  25321. }, function () {
  25322. if (onerror) {
  25323. onerror(scene);
  25324. }
  25325. scene._removePendingData(loadingToken);
  25326. scene.getEngine().hideLoadingUI();
  25327. });
  25328. }
  25329. if (SceneLoader.ShowLoadingScreen) {
  25330. scene.executeWhenReady(function () {
  25331. scene.getEngine().hideLoadingUI();
  25332. });
  25333. }
  25334. };
  25335. var manifestChecked = function (success) {
  25336. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database);
  25337. };
  25338. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  25339. // Direct load
  25340. loadSceneFromData(sceneFilename.substr(5));
  25341. return;
  25342. }
  25343. if (rootUrl.indexOf("file:") === -1) {
  25344. if (scene.getEngine().enableOfflineSupport) {
  25345. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  25346. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  25347. }
  25348. else {
  25349. manifestChecked(true);
  25350. }
  25351. }
  25352. else {
  25353. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack);
  25354. }
  25355. };
  25356. // Flags
  25357. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  25358. SceneLoader._ShowLoadingScreen = true;
  25359. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  25360. // Members
  25361. SceneLoader._registeredPlugins = new Array();
  25362. return SceneLoader;
  25363. }());
  25364. BABYLON.SceneLoader = SceneLoader;
  25365. ;
  25366. })(BABYLON || (BABYLON = {}));
  25367. var BABYLON;
  25368. (function (BABYLON) {
  25369. var Internals;
  25370. (function (Internals) {
  25371. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  25372. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  25373. var parsedMaterial = parsedData.materials[index];
  25374. if (parsedMaterial.id === id) {
  25375. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  25376. }
  25377. }
  25378. return null;
  25379. };
  25380. var isDescendantOf = function (mesh, names, hierarchyIds) {
  25381. names = (names instanceof Array) ? names : [names];
  25382. for (var i in names) {
  25383. if (mesh.name === names[i]) {
  25384. hierarchyIds.push(mesh.id);
  25385. return true;
  25386. }
  25387. }
  25388. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  25389. hierarchyIds.push(mesh.id);
  25390. return true;
  25391. }
  25392. return false;
  25393. };
  25394. var logOperation = function (operation, producer) {
  25395. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  25396. };
  25397. BABYLON.SceneLoader.RegisterPlugin({
  25398. extensions: ".babylon",
  25399. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  25400. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  25401. // when SceneLoader.debugLogging = true (default), or exception encountered.
  25402. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  25403. // and avoid problems with multiple concurrent .babylon loads.
  25404. var log = "importMesh has failed JSON parse";
  25405. try {
  25406. var parsedData = JSON.parse(data);
  25407. log = "";
  25408. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  25409. var loadedSkeletonsIds = [];
  25410. var loadedMaterialsIds = [];
  25411. var hierarchyIds = [];
  25412. var index;
  25413. var cache;
  25414. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  25415. var parsedMesh = parsedData.meshes[index];
  25416. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  25417. if (meshesNames instanceof Array) {
  25418. // Remove found mesh name from list.
  25419. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  25420. }
  25421. //Geometry?
  25422. if (parsedMesh.geometryId) {
  25423. //does the file contain geometries?
  25424. if (parsedData.geometries) {
  25425. //find the correct geometry and add it to the scene
  25426. var found = false;
  25427. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  25428. if (found || !parsedData.geometries[geometryType] || !(parsedData.geometries[geometryType] instanceof Array)) {
  25429. return;
  25430. }
  25431. else {
  25432. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  25433. if (parsedGeometryData.id === parsedMesh.geometryId) {
  25434. switch (geometryType) {
  25435. case "boxes":
  25436. BABYLON.Geometry.Primitives.Box.Parse(parsedGeometryData, scene);
  25437. break;
  25438. case "spheres":
  25439. BABYLON.Geometry.Primitives.Sphere.Parse(parsedGeometryData, scene);
  25440. break;
  25441. case "cylinders":
  25442. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedGeometryData, scene);
  25443. break;
  25444. case "toruses":
  25445. BABYLON.Geometry.Primitives.Torus.Parse(parsedGeometryData, scene);
  25446. break;
  25447. case "grounds":
  25448. BABYLON.Geometry.Primitives.Ground.Parse(parsedGeometryData, scene);
  25449. break;
  25450. case "planes":
  25451. BABYLON.Geometry.Primitives.Plane.Parse(parsedGeometryData, scene);
  25452. break;
  25453. case "torusKnots":
  25454. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedGeometryData, scene);
  25455. break;
  25456. case "vertexData":
  25457. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  25458. break;
  25459. }
  25460. found = true;
  25461. }
  25462. });
  25463. }
  25464. });
  25465. if (!found) {
  25466. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  25467. }
  25468. }
  25469. }
  25470. // Material ?
  25471. if (parsedMesh.materialId) {
  25472. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  25473. if (!materialFound && parsedData.multiMaterials) {
  25474. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  25475. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  25476. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  25477. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  25478. var subMatId = parsedMultiMaterial.materials[matIndex];
  25479. loadedMaterialsIds.push(subMatId);
  25480. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  25481. log += "\n\tMaterial " + mat.toString(fullDetails);
  25482. }
  25483. loadedMaterialsIds.push(parsedMultiMaterial.id);
  25484. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  25485. materialFound = true;
  25486. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  25487. break;
  25488. }
  25489. }
  25490. }
  25491. if (!materialFound) {
  25492. loadedMaterialsIds.push(parsedMesh.materialId);
  25493. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  25494. if (!mat) {
  25495. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  25496. }
  25497. else {
  25498. log += "\n\tMaterial " + mat.toString(fullDetails);
  25499. }
  25500. }
  25501. }
  25502. // Skeleton ?
  25503. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  25504. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  25505. if (!skeletonAlreadyLoaded) {
  25506. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  25507. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  25508. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  25509. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  25510. skeletons.push(skeleton);
  25511. loadedSkeletonsIds.push(parsedSkeleton.id);
  25512. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  25513. }
  25514. }
  25515. }
  25516. }
  25517. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  25518. meshes.push(mesh);
  25519. log += "\n\tMesh " + mesh.toString(fullDetails);
  25520. }
  25521. }
  25522. // Connecting parents
  25523. var currentMesh;
  25524. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  25525. currentMesh = scene.meshes[index];
  25526. if (currentMesh._waitingParentId) {
  25527. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  25528. currentMesh._waitingParentId = undefined;
  25529. }
  25530. }
  25531. // freeze and compute world matrix application
  25532. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  25533. currentMesh = scene.meshes[index];
  25534. if (currentMesh._waitingFreezeWorldMatrix) {
  25535. currentMesh.freezeWorldMatrix();
  25536. currentMesh._waitingFreezeWorldMatrix = undefined;
  25537. }
  25538. else {
  25539. currentMesh.computeWorldMatrix(true);
  25540. }
  25541. }
  25542. // Particles
  25543. if (parsedData.particleSystems) {
  25544. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  25545. var parsedParticleSystem = parsedData.particleSystems[index];
  25546. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  25547. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  25548. }
  25549. }
  25550. }
  25551. return true;
  25552. }
  25553. catch (err) {
  25554. BABYLON.Tools.Log(logOperation("importMesh", parsedData.producer) + log);
  25555. log = null;
  25556. throw err;
  25557. }
  25558. finally {
  25559. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  25560. BABYLON.Tools.Log(logOperation("importMesh", parsedData.producer) + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  25561. }
  25562. }
  25563. },
  25564. load: function (scene, data, rootUrl) {
  25565. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  25566. // when SceneLoader.debugLogging = true (default), or exception encountered.
  25567. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  25568. // and avoid problems with multiple concurrent .babylon loads.
  25569. var log = "importScene has failed JSON parse";
  25570. try {
  25571. var parsedData = JSON.parse(data);
  25572. log = "";
  25573. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  25574. // Scene
  25575. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  25576. scene.autoClear = parsedData.autoClear;
  25577. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  25578. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  25579. if (parsedData.gravity) {
  25580. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  25581. }
  25582. // Fog
  25583. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  25584. scene.fogMode = parsedData.fogMode;
  25585. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  25586. scene.fogStart = parsedData.fogStart;
  25587. scene.fogEnd = parsedData.fogEnd;
  25588. scene.fogDensity = parsedData.fogDensity;
  25589. log += "\tFog mode for scene: ";
  25590. switch (scene.fogMode) {
  25591. // getters not compiling, so using hardcoded
  25592. case 1:
  25593. log += "exp\n";
  25594. break;
  25595. case 2:
  25596. log += "exp2\n";
  25597. break;
  25598. case 3:
  25599. log += "linear\n";
  25600. break;
  25601. }
  25602. }
  25603. //Physics
  25604. if (parsedData.physicsEnabled) {
  25605. var physicsPlugin;
  25606. if (parsedData.physicsEngine === "cannon") {
  25607. physicsPlugin = new BABYLON.CannonJSPlugin();
  25608. }
  25609. else if (parsedData.physicsEngine === "oimo") {
  25610. physicsPlugin = new BABYLON.OimoJSPlugin();
  25611. }
  25612. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  25613. //else - default engine, which is currently oimo
  25614. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  25615. scene.enablePhysics(physicsGravity, physicsPlugin);
  25616. }
  25617. //collisions, if defined. otherwise, default is true
  25618. if (parsedData.collisionsEnabled != undefined) {
  25619. scene.collisionsEnabled = parsedData.collisionsEnabled;
  25620. }
  25621. scene.workerCollisions = !!parsedData.workerCollisions;
  25622. var index;
  25623. var cache;
  25624. // Lights
  25625. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  25626. var parsedLight = parsedData.lights[index];
  25627. var light = BABYLON.Light.Parse(parsedLight, scene);
  25628. log += (index === 0 ? "\n\tLights:" : "");
  25629. log += "\n\t\t" + light.toString(fullDetails);
  25630. }
  25631. // Animations
  25632. if (parsedData.animations) {
  25633. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  25634. var parsedAnimation = parsedData.animations[index];
  25635. var animation = BABYLON.Animation.Parse(parsedAnimation);
  25636. scene.animations.push(animation);
  25637. log += (index === 0 ? "\n\tAnimations:" : "");
  25638. log += "\n\t\t" + animation.toString(fullDetails);
  25639. }
  25640. }
  25641. if (parsedData.autoAnimate) {
  25642. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  25643. }
  25644. // Materials
  25645. if (parsedData.materials) {
  25646. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  25647. var parsedMaterial = parsedData.materials[index];
  25648. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  25649. log += (index === 0 ? "\n\tMaterials:" : "");
  25650. log += "\n\t\t" + mat.toString(fullDetails);
  25651. }
  25652. }
  25653. if (parsedData.multiMaterials) {
  25654. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  25655. var parsedMultiMaterial = parsedData.multiMaterials[index];
  25656. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  25657. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  25658. log += "\n\t\t" + mmat.toString(fullDetails);
  25659. }
  25660. }
  25661. // Skeletons
  25662. if (parsedData.skeletons) {
  25663. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  25664. var parsedSkeleton = parsedData.skeletons[index];
  25665. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  25666. log += (index === 0 ? "\n\tSkeletons:" : "");
  25667. log += "\n\t\t" + skeleton.toString(fullDetails);
  25668. }
  25669. }
  25670. // Geometries
  25671. var geometries = parsedData.geometries;
  25672. if (geometries) {
  25673. // Boxes
  25674. var boxes = geometries.boxes;
  25675. if (boxes) {
  25676. for (index = 0, cache = boxes.length; index < cache; index++) {
  25677. var parsedBox = boxes[index];
  25678. BABYLON.Geometry.Primitives.Box.Parse(parsedBox, scene);
  25679. }
  25680. }
  25681. // Spheres
  25682. var spheres = geometries.spheres;
  25683. if (spheres) {
  25684. for (index = 0, cache = spheres.length; index < cache; index++) {
  25685. var parsedSphere = spheres[index];
  25686. BABYLON.Geometry.Primitives.Sphere.Parse(parsedSphere, scene);
  25687. }
  25688. }
  25689. // Cylinders
  25690. var cylinders = geometries.cylinders;
  25691. if (cylinders) {
  25692. for (index = 0, cache = cylinders.length; index < cache; index++) {
  25693. var parsedCylinder = cylinders[index];
  25694. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedCylinder, scene);
  25695. }
  25696. }
  25697. // Toruses
  25698. var toruses = geometries.toruses;
  25699. if (toruses) {
  25700. for (index = 0, cache = toruses.length; index < cache; index++) {
  25701. var parsedTorus = toruses[index];
  25702. BABYLON.Geometry.Primitives.Torus.Parse(parsedTorus, scene);
  25703. }
  25704. }
  25705. // Grounds
  25706. var grounds = geometries.grounds;
  25707. if (grounds) {
  25708. for (index = 0, cache = grounds.length; index < cache; index++) {
  25709. var parsedGround = grounds[index];
  25710. BABYLON.Geometry.Primitives.Ground.Parse(parsedGround, scene);
  25711. }
  25712. }
  25713. // Planes
  25714. var planes = geometries.planes;
  25715. if (planes) {
  25716. for (index = 0, cache = planes.length; index < cache; index++) {
  25717. var parsedPlane = planes[index];
  25718. BABYLON.Geometry.Primitives.Plane.Parse(parsedPlane, scene);
  25719. }
  25720. }
  25721. // TorusKnots
  25722. var torusKnots = geometries.torusKnots;
  25723. if (torusKnots) {
  25724. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  25725. var parsedTorusKnot = torusKnots[index];
  25726. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedTorusKnot, scene);
  25727. }
  25728. }
  25729. // VertexData
  25730. var vertexData = geometries.vertexData;
  25731. if (vertexData) {
  25732. for (index = 0, cache = vertexData.length; index < cache; index++) {
  25733. var parsedVertexData = vertexData[index];
  25734. BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl);
  25735. }
  25736. }
  25737. }
  25738. // Meshes
  25739. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  25740. var parsedMesh = parsedData.meshes[index];
  25741. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  25742. log += (index === 0 ? "\n\tMeshes:" : "");
  25743. log += "\n\t\t" + mesh.toString(fullDetails);
  25744. }
  25745. // Cameras
  25746. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  25747. var parsedCamera = parsedData.cameras[index];
  25748. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  25749. log += (index === 0 ? "\n\tCameras:" : "");
  25750. log += "\n\t\t" + camera.toString(fullDetails);
  25751. }
  25752. if (parsedData.activeCameraID) {
  25753. scene.setActiveCameraByID(parsedData.activeCameraID);
  25754. }
  25755. // Browsing all the graph to connect the dots
  25756. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  25757. var camera = scene.cameras[index];
  25758. if (camera._waitingParentId) {
  25759. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  25760. camera._waitingParentId = undefined;
  25761. }
  25762. }
  25763. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  25764. var light = scene.lights[index];
  25765. if (light._waitingParentId) {
  25766. light.parent = scene.getLastEntryByID(light._waitingParentId);
  25767. light._waitingParentId = undefined;
  25768. }
  25769. }
  25770. // Sounds
  25771. var loadedSounds = [];
  25772. var loadedSound;
  25773. if (BABYLON.AudioEngine && parsedData.sounds) {
  25774. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  25775. var parsedSound = parsedData.sounds[index];
  25776. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  25777. if (!parsedSound.url)
  25778. parsedSound.url = parsedSound.name;
  25779. if (!loadedSounds[parsedSound.url]) {
  25780. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  25781. loadedSounds[parsedSound.url] = loadedSound;
  25782. }
  25783. else {
  25784. BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]);
  25785. }
  25786. }
  25787. else {
  25788. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  25789. }
  25790. }
  25791. }
  25792. loadedSounds = [];
  25793. // Connect parents & children and parse actions
  25794. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  25795. var mesh = scene.meshes[index];
  25796. if (mesh._waitingParentId) {
  25797. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  25798. mesh._waitingParentId = undefined;
  25799. }
  25800. if (mesh._waitingActions) {
  25801. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  25802. mesh._waitingActions = undefined;
  25803. }
  25804. }
  25805. // freeze world matrix application
  25806. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  25807. var currentMesh = scene.meshes[index];
  25808. if (currentMesh._waitingFreezeWorldMatrix) {
  25809. currentMesh.freezeWorldMatrix();
  25810. currentMesh._waitingFreezeWorldMatrix = undefined;
  25811. }
  25812. else {
  25813. currentMesh.computeWorldMatrix(true);
  25814. }
  25815. }
  25816. // Particles Systems
  25817. if (parsedData.particleSystems) {
  25818. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  25819. var parsedParticleSystem = parsedData.particleSystems[index];
  25820. BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  25821. }
  25822. }
  25823. // Lens flares
  25824. if (parsedData.lensFlareSystems) {
  25825. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  25826. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  25827. BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  25828. }
  25829. }
  25830. // Shadows
  25831. if (parsedData.shadowGenerators) {
  25832. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  25833. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  25834. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  25835. }
  25836. }
  25837. // Actions (scene)
  25838. if (parsedData.actions) {
  25839. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  25840. }
  25841. // Finish
  25842. return true;
  25843. }
  25844. catch (err) {
  25845. BABYLON.Tools.Log(logOperation("importScene", parsedData.producer) + log);
  25846. log = null;
  25847. throw err;
  25848. }
  25849. finally {
  25850. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  25851. BABYLON.Tools.Log(logOperation("importScene", parsedData.producer) + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  25852. }
  25853. }
  25854. }
  25855. });
  25856. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  25857. })(BABYLON || (BABYLON = {}));
  25858. var BABYLON;
  25859. (function (BABYLON) {
  25860. var SpriteManager = (function () {
  25861. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  25862. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  25863. this.name = name;
  25864. this.sprites = new Array();
  25865. this.renderingGroupId = 0;
  25866. this.layerMask = 0x0FFFFFFF;
  25867. this.fogEnabled = true;
  25868. this.isPickable = false;
  25869. /**
  25870. * An event triggered when the manager is disposed.
  25871. * @type {BABYLON.Observable}
  25872. */
  25873. this.onDisposeObservable = new BABYLON.Observable();
  25874. this._vertexBuffers = {};
  25875. this._capacity = capacity;
  25876. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  25877. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  25878. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  25879. this._epsilon = epsilon === undefined ? 0.01 : epsilon;
  25880. if (cellSize.width) {
  25881. this.cellWidth = cellSize.width;
  25882. this.cellHeight = cellSize.height;
  25883. }
  25884. else {
  25885. this.cellWidth = cellSize;
  25886. this.cellHeight = cellSize;
  25887. }
  25888. this._scene = scene;
  25889. this._scene.spriteManagers.push(this);
  25890. var indices = [];
  25891. var index = 0;
  25892. for (var count = 0; count < capacity; count++) {
  25893. indices.push(index);
  25894. indices.push(index + 1);
  25895. indices.push(index + 2);
  25896. indices.push(index);
  25897. indices.push(index + 2);
  25898. indices.push(index + 3);
  25899. index += 4;
  25900. }
  25901. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  25902. // VBO
  25903. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  25904. this._vertexData = new Float32Array(capacity * 16 * 4);
  25905. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  25906. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  25907. var options = this._buffer.createVertexBuffer("options", 4, 4);
  25908. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  25909. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  25910. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  25911. this._vertexBuffers["options"] = options;
  25912. this._vertexBuffers["cellInfo"] = cellInfo;
  25913. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  25914. // Effects
  25915. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  25916. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  25917. }
  25918. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  25919. set: function (callback) {
  25920. if (this._onDisposeObserver) {
  25921. this.onDisposeObservable.remove(this._onDisposeObserver);
  25922. }
  25923. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  25924. },
  25925. enumerable: true,
  25926. configurable: true
  25927. });
  25928. Object.defineProperty(SpriteManager.prototype, "texture", {
  25929. get: function () {
  25930. return this._spriteTexture;
  25931. },
  25932. set: function (value) {
  25933. this._spriteTexture = value;
  25934. },
  25935. enumerable: true,
  25936. configurable: true
  25937. });
  25938. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  25939. var arrayOffset = index * 16;
  25940. if (offsetX === 0)
  25941. offsetX = this._epsilon;
  25942. else if (offsetX === 1)
  25943. offsetX = 1 - this._epsilon;
  25944. if (offsetY === 0)
  25945. offsetY = this._epsilon;
  25946. else if (offsetY === 1)
  25947. offsetY = 1 - this._epsilon;
  25948. this._vertexData[arrayOffset] = sprite.position.x;
  25949. this._vertexData[arrayOffset + 1] = sprite.position.y;
  25950. this._vertexData[arrayOffset + 2] = sprite.position.z;
  25951. this._vertexData[arrayOffset + 3] = sprite.angle;
  25952. this._vertexData[arrayOffset + 4] = sprite.width;
  25953. this._vertexData[arrayOffset + 5] = sprite.height;
  25954. this._vertexData[arrayOffset + 6] = offsetX;
  25955. this._vertexData[arrayOffset + 7] = offsetY;
  25956. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  25957. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  25958. var offset = (sprite.cellIndex / rowSize) >> 0;
  25959. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  25960. this._vertexData[arrayOffset + 11] = offset;
  25961. // Color
  25962. this._vertexData[arrayOffset + 12] = sprite.color.r;
  25963. this._vertexData[arrayOffset + 13] = sprite.color.g;
  25964. this._vertexData[arrayOffset + 14] = sprite.color.b;
  25965. this._vertexData[arrayOffset + 15] = sprite.color.a;
  25966. };
  25967. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  25968. var count = Math.min(this._capacity, this.sprites.length);
  25969. var min = BABYLON.Vector3.Zero();
  25970. var max = BABYLON.Vector3.Zero();
  25971. var distance = Number.MAX_VALUE;
  25972. var currentSprite;
  25973. var cameraSpacePosition = BABYLON.Vector3.Zero();
  25974. var cameraView = camera.getViewMatrix();
  25975. for (var index = 0; index < count; index++) {
  25976. var sprite = this.sprites[index];
  25977. if (!sprite) {
  25978. continue;
  25979. }
  25980. if (predicate) {
  25981. if (!predicate(sprite)) {
  25982. continue;
  25983. }
  25984. }
  25985. else if (!sprite.isPickable) {
  25986. continue;
  25987. }
  25988. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  25989. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  25990. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  25991. if (ray.intersectsBoxMinMax(min, max)) {
  25992. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  25993. if (distance > currentDistance) {
  25994. distance = currentDistance;
  25995. currentSprite = sprite;
  25996. if (fastCheck) {
  25997. break;
  25998. }
  25999. }
  26000. }
  26001. }
  26002. if (currentSprite) {
  26003. var result = new BABYLON.PickingInfo();
  26004. result.hit = true;
  26005. result.pickedSprite = currentSprite;
  26006. result.distance = distance;
  26007. return result;
  26008. }
  26009. return null;
  26010. };
  26011. SpriteManager.prototype.render = function () {
  26012. // Check
  26013. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  26014. return;
  26015. var engine = this._scene.getEngine();
  26016. var baseSize = this._spriteTexture.getBaseSize();
  26017. // Sprites
  26018. var deltaTime = engine.getDeltaTime();
  26019. var max = Math.min(this._capacity, this.sprites.length);
  26020. var rowSize = baseSize.width / this.cellWidth;
  26021. var offset = 0;
  26022. for (var index = 0; index < max; index++) {
  26023. var sprite = this.sprites[index];
  26024. if (!sprite) {
  26025. continue;
  26026. }
  26027. sprite._animate(deltaTime);
  26028. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  26029. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  26030. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  26031. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  26032. }
  26033. this._buffer.update(this._vertexData);
  26034. // Render
  26035. var effect = this._effectBase;
  26036. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  26037. effect = this._effectFog;
  26038. }
  26039. engine.enableEffect(effect);
  26040. var viewMatrix = this._scene.getViewMatrix();
  26041. effect.setTexture("diffuseSampler", this._spriteTexture);
  26042. effect.setMatrix("view", viewMatrix);
  26043. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  26044. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  26045. // Fog
  26046. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  26047. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  26048. effect.setColor3("vFogColor", this._scene.fogColor);
  26049. }
  26050. // VBOs
  26051. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  26052. // Draw order
  26053. engine.setDepthFunctionToLessOrEqual();
  26054. effect.setBool("alphaTest", true);
  26055. engine.setColorWrite(false);
  26056. engine.draw(true, 0, max * 6);
  26057. engine.setColorWrite(true);
  26058. effect.setBool("alphaTest", false);
  26059. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  26060. engine.draw(true, 0, max * 6);
  26061. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  26062. };
  26063. SpriteManager.prototype.dispose = function () {
  26064. if (this._buffer) {
  26065. this._buffer.dispose();
  26066. this._buffer = null;
  26067. }
  26068. if (this._indexBuffer) {
  26069. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  26070. this._indexBuffer = null;
  26071. }
  26072. if (this._spriteTexture) {
  26073. this._spriteTexture.dispose();
  26074. this._spriteTexture = null;
  26075. }
  26076. // Remove from scene
  26077. var index = this._scene.spriteManagers.indexOf(this);
  26078. this._scene.spriteManagers.splice(index, 1);
  26079. // Callback
  26080. this.onDisposeObservable.notifyObservers(this);
  26081. this.onDisposeObservable.clear();
  26082. };
  26083. return SpriteManager;
  26084. }());
  26085. BABYLON.SpriteManager = SpriteManager;
  26086. })(BABYLON || (BABYLON = {}));
  26087. var BABYLON;
  26088. (function (BABYLON) {
  26089. var Sprite = (function () {
  26090. function Sprite(name, manager) {
  26091. this.name = name;
  26092. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  26093. this.width = 1.0;
  26094. this.height = 1.0;
  26095. this.angle = 0;
  26096. this.cellIndex = 0;
  26097. this.invertU = 0;
  26098. this.invertV = 0;
  26099. this.animations = new Array();
  26100. this.isPickable = false;
  26101. this._animationStarted = false;
  26102. this._loopAnimation = false;
  26103. this._fromIndex = 0;
  26104. this._toIndex = 0;
  26105. this._delay = 0;
  26106. this._direction = 1;
  26107. this._frameCount = 0;
  26108. this._time = 0;
  26109. this._manager = manager;
  26110. this._manager.sprites.push(this);
  26111. this.position = BABYLON.Vector3.Zero();
  26112. }
  26113. Object.defineProperty(Sprite.prototype, "size", {
  26114. get: function () {
  26115. return this.width;
  26116. },
  26117. set: function (value) {
  26118. this.width = value;
  26119. this.height = value;
  26120. },
  26121. enumerable: true,
  26122. configurable: true
  26123. });
  26124. Sprite.prototype.playAnimation = function (from, to, loop, delay) {
  26125. this._fromIndex = from;
  26126. this._toIndex = to;
  26127. this._loopAnimation = loop;
  26128. this._delay = delay;
  26129. this._animationStarted = true;
  26130. this._direction = from < to ? 1 : -1;
  26131. this.cellIndex = from;
  26132. this._time = 0;
  26133. };
  26134. Sprite.prototype.stopAnimation = function () {
  26135. this._animationStarted = false;
  26136. };
  26137. Sprite.prototype._animate = function (deltaTime) {
  26138. if (!this._animationStarted)
  26139. return;
  26140. this._time += deltaTime;
  26141. if (this._time > this._delay) {
  26142. this._time = this._time % this._delay;
  26143. this.cellIndex += this._direction;
  26144. if (this.cellIndex == this._toIndex) {
  26145. if (this._loopAnimation) {
  26146. this.cellIndex = this._fromIndex;
  26147. }
  26148. else {
  26149. this._animationStarted = false;
  26150. if (this.disposeWhenFinishedAnimating) {
  26151. this.dispose();
  26152. }
  26153. }
  26154. }
  26155. }
  26156. };
  26157. Sprite.prototype.dispose = function () {
  26158. for (var i = 0; i < this._manager.sprites.length; i++) {
  26159. if (this._manager.sprites[i] == this) {
  26160. this._manager.sprites.splice(i, 1);
  26161. }
  26162. }
  26163. };
  26164. return Sprite;
  26165. }());
  26166. BABYLON.Sprite = Sprite;
  26167. })(BABYLON || (BABYLON = {}));
  26168. var BABYLON;
  26169. (function (BABYLON) {
  26170. var Layer = (function () {
  26171. function Layer(name, imgUrl, scene, isBackground, color) {
  26172. this.name = name;
  26173. this.scale = new BABYLON.Vector2(1, 1);
  26174. this.offset = new BABYLON.Vector2(0, 0);
  26175. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  26176. this._vertexBuffers = {};
  26177. // Events
  26178. /**
  26179. * An event triggered when the layer is disposed.
  26180. * @type {BABYLON.Observable}
  26181. */
  26182. this.onDisposeObservable = new BABYLON.Observable();
  26183. /**
  26184. * An event triggered before rendering the scene
  26185. * @type {BABYLON.Observable}
  26186. */
  26187. this.onBeforeRenderObservable = new BABYLON.Observable();
  26188. /**
  26189. * An event triggered after rendering the scene
  26190. * @type {BABYLON.Observable}
  26191. */
  26192. this.onAfterRenderObservable = new BABYLON.Observable();
  26193. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  26194. this.isBackground = isBackground === undefined ? true : isBackground;
  26195. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  26196. this._scene = scene;
  26197. this._scene.layers.push(this);
  26198. var engine = scene.getEngine();
  26199. // VBO
  26200. var vertices = [];
  26201. vertices.push(1, 1);
  26202. vertices.push(-1, 1);
  26203. vertices.push(-1, -1);
  26204. vertices.push(1, -1);
  26205. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  26206. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  26207. // Indices
  26208. var indices = [];
  26209. indices.push(0);
  26210. indices.push(1);
  26211. indices.push(2);
  26212. indices.push(0);
  26213. indices.push(2);
  26214. indices.push(3);
  26215. this._indexBuffer = engine.createIndexBuffer(indices);
  26216. // Effects
  26217. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  26218. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  26219. }
  26220. Object.defineProperty(Layer.prototype, "onDispose", {
  26221. set: function (callback) {
  26222. if (this._onDisposeObserver) {
  26223. this.onDisposeObservable.remove(this._onDisposeObserver);
  26224. }
  26225. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  26226. },
  26227. enumerable: true,
  26228. configurable: true
  26229. });
  26230. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  26231. set: function (callback) {
  26232. if (this._onBeforeRenderObserver) {
  26233. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  26234. }
  26235. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  26236. },
  26237. enumerable: true,
  26238. configurable: true
  26239. });
  26240. Object.defineProperty(Layer.prototype, "onAfterRender", {
  26241. set: function (callback) {
  26242. if (this._onAfterRenderObserver) {
  26243. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  26244. }
  26245. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  26246. },
  26247. enumerable: true,
  26248. configurable: true
  26249. });
  26250. Layer.prototype.render = function () {
  26251. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  26252. // Check
  26253. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  26254. return;
  26255. var engine = this._scene.getEngine();
  26256. this.onBeforeRenderObservable.notifyObservers(this);
  26257. // Render
  26258. engine.enableEffect(currentEffect);
  26259. engine.setState(false);
  26260. // Texture
  26261. currentEffect.setTexture("textureSampler", this.texture);
  26262. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  26263. // Color
  26264. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  26265. // Scale / offset
  26266. currentEffect.setVector2("offset", this.offset);
  26267. currentEffect.setVector2("scale", this.scale);
  26268. // VBOs
  26269. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  26270. // Draw order
  26271. if (!this._alphaTestEffect) {
  26272. engine.setAlphaMode(this.alphaBlendingMode);
  26273. engine.draw(true, 0, 6);
  26274. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  26275. }
  26276. else {
  26277. engine.draw(true, 0, 6);
  26278. }
  26279. this.onAfterRenderObservable.notifyObservers(this);
  26280. };
  26281. Layer.prototype.dispose = function () {
  26282. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  26283. if (vertexBuffer) {
  26284. vertexBuffer.dispose();
  26285. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  26286. }
  26287. if (this._indexBuffer) {
  26288. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  26289. this._indexBuffer = null;
  26290. }
  26291. if (this.texture) {
  26292. this.texture.dispose();
  26293. this.texture = null;
  26294. }
  26295. // Remove from scene
  26296. var index = this._scene.layers.indexOf(this);
  26297. this._scene.layers.splice(index, 1);
  26298. // Callback
  26299. this.onDisposeObservable.notifyObservers(this);
  26300. this.onDisposeObservable.clear();
  26301. this.onAfterRenderObservable.clear();
  26302. this.onBeforeRenderObservable.clear();
  26303. };
  26304. return Layer;
  26305. }());
  26306. BABYLON.Layer = Layer;
  26307. })(BABYLON || (BABYLON = {}));
  26308. var BABYLON;
  26309. (function (BABYLON) {
  26310. var Particle = (function () {
  26311. function Particle() {
  26312. this.position = BABYLON.Vector3.Zero();
  26313. this.direction = BABYLON.Vector3.Zero();
  26314. this.color = new BABYLON.Color4(0, 0, 0, 0);
  26315. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  26316. this.lifeTime = 1.0;
  26317. this.age = 0;
  26318. this.size = 0;
  26319. this.angle = 0;
  26320. this.angularSpeed = 0;
  26321. }
  26322. Particle.prototype.copyTo = function (other) {
  26323. other.position.copyFrom(this.position);
  26324. other.direction.copyFrom(this.direction);
  26325. other.color.copyFrom(this.color);
  26326. other.colorStep.copyFrom(this.colorStep);
  26327. other.lifeTime = this.lifeTime;
  26328. other.age = this.age;
  26329. other.size = this.size;
  26330. other.angle = this.angle;
  26331. other.angularSpeed = this.angularSpeed;
  26332. };
  26333. return Particle;
  26334. }());
  26335. BABYLON.Particle = Particle;
  26336. })(BABYLON || (BABYLON = {}));
  26337. var BABYLON;
  26338. (function (BABYLON) {
  26339. var randomNumber = function (min, max) {
  26340. if (min === max) {
  26341. return (min);
  26342. }
  26343. var random = Math.random();
  26344. return ((random * (max - min)) + min);
  26345. };
  26346. var ParticleSystem = (function () {
  26347. function ParticleSystem(name, capacity, scene, customEffect) {
  26348. var _this = this;
  26349. this.name = name;
  26350. // Members
  26351. this.animations = [];
  26352. this.renderingGroupId = 0;
  26353. this.emitter = null;
  26354. this.emitRate = 10;
  26355. this.manualEmitCount = -1;
  26356. this.updateSpeed = 0.01;
  26357. this.targetStopDuration = 0;
  26358. this.disposeOnStop = false;
  26359. this.minEmitPower = 1;
  26360. this.maxEmitPower = 1;
  26361. this.minLifeTime = 1;
  26362. this.maxLifeTime = 1;
  26363. this.minSize = 1;
  26364. this.maxSize = 1;
  26365. this.minAngularSpeed = 0;
  26366. this.maxAngularSpeed = 0;
  26367. this.layerMask = 0x0FFFFFFF;
  26368. /**
  26369. * An event triggered when the system is disposed.
  26370. * @type {BABYLON.Observable}
  26371. */
  26372. this.onDisposeObservable = new BABYLON.Observable();
  26373. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  26374. this.forceDepthWrite = false;
  26375. this.gravity = BABYLON.Vector3.Zero();
  26376. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  26377. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  26378. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  26379. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  26380. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  26381. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  26382. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  26383. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  26384. this.particles = new Array();
  26385. this._stockParticles = new Array();
  26386. this._newPartsExcess = 0;
  26387. this._vertexBuffers = {};
  26388. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  26389. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  26390. this._scaledDirection = BABYLON.Vector3.Zero();
  26391. this._scaledGravity = BABYLON.Vector3.Zero();
  26392. this._currentRenderId = -1;
  26393. this._started = false;
  26394. this._stopped = false;
  26395. this._actualFrame = 0;
  26396. this.id = name;
  26397. this._capacity = capacity;
  26398. this._scene = scene;
  26399. this._customEffect = customEffect;
  26400. scene.particleSystems.push(this);
  26401. var indices = [];
  26402. var index = 0;
  26403. for (var count = 0; count < capacity; count++) {
  26404. indices.push(index);
  26405. indices.push(index + 1);
  26406. indices.push(index + 2);
  26407. indices.push(index);
  26408. indices.push(index + 2);
  26409. indices.push(index + 3);
  26410. index += 4;
  26411. }
  26412. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  26413. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  26414. this._vertexData = new Float32Array(capacity * 11 * 4);
  26415. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 11);
  26416. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  26417. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  26418. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  26419. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  26420. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  26421. this._vertexBuffers["options"] = options;
  26422. // Default behaviors
  26423. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  26424. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  26425. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  26426. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  26427. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  26428. };
  26429. this.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  26430. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  26431. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  26432. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  26433. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  26434. };
  26435. this.updateFunction = function (particles) {
  26436. for (var index = 0; index < particles.length; index++) {
  26437. var particle = particles[index];
  26438. particle.age += _this._scaledUpdateSpeed;
  26439. if (particle.age >= particle.lifeTime) {
  26440. _this.recycleParticle(particle);
  26441. index--;
  26442. continue;
  26443. }
  26444. else {
  26445. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  26446. particle.color.addInPlace(_this._scaledColorStep);
  26447. if (particle.color.a < 0)
  26448. particle.color.a = 0;
  26449. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  26450. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  26451. particle.position.addInPlace(_this._scaledDirection);
  26452. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  26453. particle.direction.addInPlace(_this._scaledGravity);
  26454. }
  26455. }
  26456. };
  26457. }
  26458. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  26459. set: function (callback) {
  26460. if (this._onDisposeObserver) {
  26461. this.onDisposeObservable.remove(this._onDisposeObserver);
  26462. }
  26463. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  26464. },
  26465. enumerable: true,
  26466. configurable: true
  26467. });
  26468. ParticleSystem.prototype.recycleParticle = function (particle) {
  26469. var lastParticle = this.particles.pop();
  26470. if (lastParticle !== particle) {
  26471. lastParticle.copyTo(particle);
  26472. this._stockParticles.push(lastParticle);
  26473. }
  26474. };
  26475. ParticleSystem.prototype.getCapacity = function () {
  26476. return this._capacity;
  26477. };
  26478. ParticleSystem.prototype.isAlive = function () {
  26479. return this._alive;
  26480. };
  26481. ParticleSystem.prototype.isStarted = function () {
  26482. return this._started;
  26483. };
  26484. ParticleSystem.prototype.start = function () {
  26485. this._started = true;
  26486. this._stopped = false;
  26487. this._actualFrame = 0;
  26488. };
  26489. ParticleSystem.prototype.stop = function () {
  26490. this._stopped = true;
  26491. };
  26492. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  26493. var offset = index * 11;
  26494. this._vertexData[offset] = particle.position.x;
  26495. this._vertexData[offset + 1] = particle.position.y;
  26496. this._vertexData[offset + 2] = particle.position.z;
  26497. this._vertexData[offset + 3] = particle.color.r;
  26498. this._vertexData[offset + 4] = particle.color.g;
  26499. this._vertexData[offset + 5] = particle.color.b;
  26500. this._vertexData[offset + 6] = particle.color.a;
  26501. this._vertexData[offset + 7] = particle.angle;
  26502. this._vertexData[offset + 8] = particle.size;
  26503. this._vertexData[offset + 9] = offsetX;
  26504. this._vertexData[offset + 10] = offsetY;
  26505. };
  26506. ParticleSystem.prototype._update = function (newParticles) {
  26507. // Update current
  26508. this._alive = this.particles.length > 0;
  26509. this.updateFunction(this.particles);
  26510. // Add new ones
  26511. var worldMatrix;
  26512. if (this.emitter.position) {
  26513. worldMatrix = this.emitter.getWorldMatrix();
  26514. }
  26515. else {
  26516. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  26517. }
  26518. var particle;
  26519. for (var index = 0; index < newParticles; index++) {
  26520. if (this.particles.length === this._capacity) {
  26521. break;
  26522. }
  26523. if (this._stockParticles.length !== 0) {
  26524. particle = this._stockParticles.pop();
  26525. particle.age = 0;
  26526. }
  26527. else {
  26528. particle = new BABYLON.Particle();
  26529. }
  26530. this.particles.push(particle);
  26531. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  26532. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  26533. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  26534. particle.size = randomNumber(this.minSize, this.maxSize);
  26535. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  26536. this.startPositionFunction(worldMatrix, particle.position, particle);
  26537. var step = randomNumber(0, 1.0);
  26538. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  26539. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  26540. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  26541. }
  26542. };
  26543. ParticleSystem.prototype._getEffect = function () {
  26544. if (this._customEffect) {
  26545. return this._customEffect;
  26546. }
  26547. ;
  26548. var defines = [];
  26549. if (this._scene.clipPlane) {
  26550. defines.push("#define CLIPPLANE");
  26551. }
  26552. // Effect
  26553. var join = defines.join("\n");
  26554. if (this._cachedDefines !== join) {
  26555. this._cachedDefines = join;
  26556. this._effect = this._scene.getEngine().createEffect("particles", [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  26557. }
  26558. return this._effect;
  26559. };
  26560. ParticleSystem.prototype.animate = function () {
  26561. if (!this._started)
  26562. return;
  26563. var effect = this._getEffect();
  26564. // Check
  26565. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  26566. return;
  26567. if (this._currentRenderId === this._scene.getRenderId()) {
  26568. return;
  26569. }
  26570. this._currentRenderId = this._scene.getRenderId();
  26571. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  26572. // determine the number of particles we need to create
  26573. var newParticles;
  26574. if (this.manualEmitCount > -1) {
  26575. newParticles = this.manualEmitCount;
  26576. this._newPartsExcess = 0;
  26577. this.manualEmitCount = 0;
  26578. }
  26579. else {
  26580. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  26581. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  26582. }
  26583. if (this._newPartsExcess > 1.0) {
  26584. newParticles += this._newPartsExcess >> 0;
  26585. this._newPartsExcess -= this._newPartsExcess >> 0;
  26586. }
  26587. this._alive = false;
  26588. if (!this._stopped) {
  26589. this._actualFrame += this._scaledUpdateSpeed;
  26590. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  26591. this.stop();
  26592. }
  26593. else {
  26594. newParticles = 0;
  26595. }
  26596. this._update(newParticles);
  26597. // Stopped?
  26598. if (this._stopped) {
  26599. if (!this._alive) {
  26600. this._started = false;
  26601. if (this.disposeOnStop) {
  26602. this._scene._toBeDisposed.push(this);
  26603. }
  26604. }
  26605. }
  26606. // Update VBO
  26607. var offset = 0;
  26608. for (var index = 0; index < this.particles.length; index++) {
  26609. var particle = this.particles[index];
  26610. this._appendParticleVertex(offset++, particle, 0, 0);
  26611. this._appendParticleVertex(offset++, particle, 1, 0);
  26612. this._appendParticleVertex(offset++, particle, 1, 1);
  26613. this._appendParticleVertex(offset++, particle, 0, 1);
  26614. }
  26615. this._vertexBuffer.update(this._vertexData);
  26616. };
  26617. ParticleSystem.prototype.render = function () {
  26618. var effect = this._getEffect();
  26619. // Check
  26620. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  26621. return 0;
  26622. var engine = this._scene.getEngine();
  26623. // Render
  26624. engine.enableEffect(effect);
  26625. engine.setState(false);
  26626. var viewMatrix = this._scene.getViewMatrix();
  26627. effect.setTexture("diffuseSampler", this.particleTexture);
  26628. effect.setMatrix("view", viewMatrix);
  26629. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  26630. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  26631. if (this._scene.clipPlane) {
  26632. var clipPlane = this._scene.clipPlane;
  26633. var invView = viewMatrix.clone();
  26634. invView.invert();
  26635. effect.setMatrix("invView", invView);
  26636. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  26637. }
  26638. // VBOs
  26639. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  26640. // Draw order
  26641. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  26642. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  26643. }
  26644. else {
  26645. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  26646. }
  26647. if (this.forceDepthWrite) {
  26648. engine.setDepthWrite(true);
  26649. }
  26650. engine.draw(true, 0, this.particles.length * 6);
  26651. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  26652. return this.particles.length;
  26653. };
  26654. ParticleSystem.prototype.dispose = function () {
  26655. if (this._vertexBuffer) {
  26656. this._vertexBuffer.dispose();
  26657. this._vertexBuffer = null;
  26658. }
  26659. if (this._indexBuffer) {
  26660. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  26661. this._indexBuffer = null;
  26662. }
  26663. if (this.particleTexture) {
  26664. this.particleTexture.dispose();
  26665. this.particleTexture = null;
  26666. }
  26667. // Remove from scene
  26668. var index = this._scene.particleSystems.indexOf(this);
  26669. this._scene.particleSystems.splice(index, 1);
  26670. // Callback
  26671. this.onDisposeObservable.notifyObservers(this);
  26672. this.onDisposeObservable.clear();
  26673. };
  26674. // Clone
  26675. ParticleSystem.prototype.clone = function (name, newEmitter) {
  26676. var result = new ParticleSystem(name, this._capacity, this._scene);
  26677. BABYLON.Tools.DeepCopy(this, result, ["particles"]);
  26678. if (newEmitter === undefined) {
  26679. newEmitter = this.emitter;
  26680. }
  26681. result.emitter = newEmitter;
  26682. if (this.particleTexture) {
  26683. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  26684. }
  26685. result.start();
  26686. return result;
  26687. };
  26688. ParticleSystem.prototype.serialize = function () {
  26689. var serializationObject = {};
  26690. serializationObject.name = this.name;
  26691. serializationObject.id = this.id;
  26692. // Emitter
  26693. if (this.emitter.position) {
  26694. serializationObject.emitterId = this.emitter.id;
  26695. }
  26696. else {
  26697. serializationObject.emitter = this.emitter.asArray();
  26698. }
  26699. serializationObject.capacity = this.getCapacity();
  26700. if (this.particleTexture) {
  26701. serializationObject.textureName = this.particleTexture.name;
  26702. }
  26703. // Animations
  26704. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  26705. // Particle system
  26706. serializationObject.minAngularSpeed = this.minAngularSpeed;
  26707. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  26708. serializationObject.minSize = this.minSize;
  26709. serializationObject.maxSize = this.maxSize;
  26710. serializationObject.minEmitPower = this.minEmitPower;
  26711. serializationObject.maxEmitPower = this.maxEmitPower;
  26712. serializationObject.minLifeTime = this.minLifeTime;
  26713. serializationObject.maxLifeTime = this.maxLifeTime;
  26714. serializationObject.emitRate = this.emitRate;
  26715. serializationObject.minEmitBox = this.minEmitBox.asArray();
  26716. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  26717. serializationObject.gravity = this.gravity.asArray();
  26718. serializationObject.direction1 = this.direction1.asArray();
  26719. serializationObject.direction2 = this.direction2.asArray();
  26720. serializationObject.color1 = this.color1.asArray();
  26721. serializationObject.color2 = this.color2.asArray();
  26722. serializationObject.colorDead = this.colorDead.asArray();
  26723. serializationObject.updateSpeed = this.updateSpeed;
  26724. serializationObject.targetStopDuration = this.targetStopDuration;
  26725. serializationObject.textureMask = this.textureMask.asArray();
  26726. serializationObject.blendMode = this.blendMode;
  26727. return serializationObject;
  26728. };
  26729. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  26730. var name = parsedParticleSystem.name;
  26731. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene);
  26732. if (parsedParticleSystem.id) {
  26733. particleSystem.id = parsedParticleSystem.id;
  26734. }
  26735. // Texture
  26736. if (parsedParticleSystem.textureName) {
  26737. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  26738. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  26739. }
  26740. // Emitter
  26741. if (parsedParticleSystem.emitterId) {
  26742. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  26743. }
  26744. else {
  26745. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  26746. }
  26747. // Animations
  26748. if (parsedParticleSystem.animations) {
  26749. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  26750. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  26751. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  26752. }
  26753. }
  26754. if (parsedParticleSystem.autoAnimate) {
  26755. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  26756. }
  26757. // Particle system
  26758. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  26759. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  26760. particleSystem.minSize = parsedParticleSystem.minSize;
  26761. particleSystem.maxSize = parsedParticleSystem.maxSize;
  26762. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  26763. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  26764. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  26765. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  26766. particleSystem.emitRate = parsedParticleSystem.emitRate;
  26767. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  26768. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  26769. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  26770. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  26771. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  26772. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  26773. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  26774. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  26775. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  26776. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  26777. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  26778. particleSystem.blendMode = parsedParticleSystem.blendMode;
  26779. if (!parsedParticleSystem.preventAutoStart) {
  26780. particleSystem.start();
  26781. }
  26782. return particleSystem;
  26783. };
  26784. // Statics
  26785. ParticleSystem.BLENDMODE_ONEONE = 0;
  26786. ParticleSystem.BLENDMODE_STANDARD = 1;
  26787. return ParticleSystem;
  26788. }());
  26789. BABYLON.ParticleSystem = ParticleSystem;
  26790. })(BABYLON || (BABYLON = {}));
  26791. var BABYLON;
  26792. (function (BABYLON) {
  26793. var AnimationRange = (function () {
  26794. function AnimationRange(name, from, to) {
  26795. this.name = name;
  26796. this.from = from;
  26797. this.to = to;
  26798. }
  26799. AnimationRange.prototype.clone = function () {
  26800. return new AnimationRange(this.name, this.from, this.to);
  26801. };
  26802. return AnimationRange;
  26803. }());
  26804. BABYLON.AnimationRange = AnimationRange;
  26805. /**
  26806. * Composed of a frame, and an action function
  26807. */
  26808. var AnimationEvent = (function () {
  26809. function AnimationEvent(frame, action, onlyOnce) {
  26810. this.frame = frame;
  26811. this.action = action;
  26812. this.onlyOnce = onlyOnce;
  26813. this.isDone = false;
  26814. }
  26815. return AnimationEvent;
  26816. }());
  26817. BABYLON.AnimationEvent = AnimationEvent;
  26818. var PathCursor = (function () {
  26819. function PathCursor(path) {
  26820. this.path = path;
  26821. this._onchange = new Array();
  26822. this.value = 0;
  26823. this.animations = new Array();
  26824. }
  26825. PathCursor.prototype.getPoint = function () {
  26826. var point = this.path.getPointAtLengthPosition(this.value);
  26827. return new BABYLON.Vector3(point.x, 0, point.y);
  26828. };
  26829. PathCursor.prototype.moveAhead = function (step) {
  26830. if (step === void 0) { step = 0.002; }
  26831. this.move(step);
  26832. return this;
  26833. };
  26834. PathCursor.prototype.moveBack = function (step) {
  26835. if (step === void 0) { step = 0.002; }
  26836. this.move(-step);
  26837. return this;
  26838. };
  26839. PathCursor.prototype.move = function (step) {
  26840. if (Math.abs(step) > 1) {
  26841. throw "step size should be less than 1.";
  26842. }
  26843. this.value += step;
  26844. this.ensureLimits();
  26845. this.raiseOnChange();
  26846. return this;
  26847. };
  26848. PathCursor.prototype.ensureLimits = function () {
  26849. while (this.value > 1) {
  26850. this.value -= 1;
  26851. }
  26852. while (this.value < 0) {
  26853. this.value += 1;
  26854. }
  26855. return this;
  26856. };
  26857. // used by animation engine
  26858. PathCursor.prototype.markAsDirty = function (propertyName) {
  26859. this.ensureLimits();
  26860. this.raiseOnChange();
  26861. return this;
  26862. };
  26863. PathCursor.prototype.raiseOnChange = function () {
  26864. var _this = this;
  26865. this._onchange.forEach(function (f) { return f(_this); });
  26866. return this;
  26867. };
  26868. PathCursor.prototype.onchange = function (f) {
  26869. this._onchange.push(f);
  26870. return this;
  26871. };
  26872. return PathCursor;
  26873. }());
  26874. BABYLON.PathCursor = PathCursor;
  26875. var Animation = (function () {
  26876. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  26877. this.name = name;
  26878. this.targetProperty = targetProperty;
  26879. this.framePerSecond = framePerSecond;
  26880. this.dataType = dataType;
  26881. this.loopMode = loopMode;
  26882. this.enableBlending = enableBlending;
  26883. this._offsetsCache = {};
  26884. this._highLimitsCache = {};
  26885. this._stopped = false;
  26886. this._blendingFactor = 0;
  26887. // The set of event that will be linked to this animation
  26888. this._events = new Array();
  26889. this.allowMatricesInterpolation = false;
  26890. this.blendingSpeed = 0.01;
  26891. this._ranges = {};
  26892. this.targetPropertyPath = targetProperty.split(".");
  26893. this.dataType = dataType;
  26894. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  26895. }
  26896. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  26897. var dataType = undefined;
  26898. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  26899. dataType = Animation.ANIMATIONTYPE_FLOAT;
  26900. }
  26901. else if (from instanceof BABYLON.Quaternion) {
  26902. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  26903. }
  26904. else if (from instanceof BABYLON.Vector3) {
  26905. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  26906. }
  26907. else if (from instanceof BABYLON.Vector2) {
  26908. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  26909. }
  26910. else if (from instanceof BABYLON.Color3) {
  26911. dataType = Animation.ANIMATIONTYPE_COLOR3;
  26912. }
  26913. else if (from instanceof BABYLON.Size) {
  26914. dataType = Animation.ANIMATIONTYPE_SIZE;
  26915. }
  26916. if (dataType == undefined) {
  26917. return null;
  26918. }
  26919. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  26920. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  26921. animation.setKeys(keys);
  26922. if (easingFunction !== undefined) {
  26923. animation.setEasingFunction(easingFunction);
  26924. }
  26925. return animation;
  26926. };
  26927. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  26928. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  26929. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  26930. };
  26931. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  26932. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  26933. node.animations.push(animation);
  26934. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  26935. };
  26936. // Methods
  26937. /**
  26938. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  26939. */
  26940. Animation.prototype.toString = function (fullDetails) {
  26941. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  26942. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  26943. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  26944. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  26945. if (fullDetails) {
  26946. ret += ", Ranges: {";
  26947. var first = true;
  26948. for (var name in this._ranges) {
  26949. if (first) {
  26950. ret += ", ";
  26951. first = false;
  26952. }
  26953. ret += name;
  26954. }
  26955. ret += "}";
  26956. }
  26957. return ret;
  26958. };
  26959. /**
  26960. * Add an event to this animation.
  26961. */
  26962. Animation.prototype.addEvent = function (event) {
  26963. this._events.push(event);
  26964. };
  26965. /**
  26966. * Remove all events found at the given frame
  26967. * @param frame
  26968. */
  26969. Animation.prototype.removeEvents = function (frame) {
  26970. for (var index = 0; index < this._events.length; index++) {
  26971. if (this._events[index].frame === frame) {
  26972. this._events.splice(index, 1);
  26973. index--;
  26974. }
  26975. }
  26976. };
  26977. Animation.prototype.createRange = function (name, from, to) {
  26978. // check name not already in use; could happen for bones after serialized
  26979. if (!this._ranges[name]) {
  26980. this._ranges[name] = new AnimationRange(name, from, to);
  26981. }
  26982. };
  26983. Animation.prototype.deleteRange = function (name, deleteFrames) {
  26984. if (deleteFrames === void 0) { deleteFrames = true; }
  26985. if (this._ranges[name]) {
  26986. if (deleteFrames) {
  26987. var from = this._ranges[name].from;
  26988. var to = this._ranges[name].to;
  26989. // this loop MUST go high to low for multiple splices to work
  26990. for (var key = this._keys.length - 1; key >= 0; key--) {
  26991. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  26992. this._keys.splice(key, 1);
  26993. }
  26994. }
  26995. }
  26996. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  26997. }
  26998. };
  26999. Animation.prototype.getRange = function (name) {
  27000. return this._ranges[name];
  27001. };
  27002. Animation.prototype.reset = function () {
  27003. this._offsetsCache = {};
  27004. this._highLimitsCache = {};
  27005. this.currentFrame = 0;
  27006. this._blendingFactor = 0;
  27007. this._originalBlendValue = null;
  27008. };
  27009. Animation.prototype.isStopped = function () {
  27010. return this._stopped;
  27011. };
  27012. Animation.prototype.getKeys = function () {
  27013. return this._keys;
  27014. };
  27015. Animation.prototype.getHighestFrame = function () {
  27016. var ret = 0;
  27017. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  27018. if (ret < this._keys[key].frame) {
  27019. ret = this._keys[key].frame;
  27020. }
  27021. }
  27022. return ret;
  27023. };
  27024. Animation.prototype.getEasingFunction = function () {
  27025. return this._easingFunction;
  27026. };
  27027. Animation.prototype.setEasingFunction = function (easingFunction) {
  27028. this._easingFunction = easingFunction;
  27029. };
  27030. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  27031. return startValue + (endValue - startValue) * gradient;
  27032. };
  27033. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  27034. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  27035. };
  27036. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  27037. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  27038. };
  27039. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  27040. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  27041. };
  27042. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  27043. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  27044. };
  27045. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  27046. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  27047. };
  27048. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  27049. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  27050. };
  27051. Animation.prototype.clone = function () {
  27052. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  27053. if (this._keys) {
  27054. clone.setKeys(this._keys);
  27055. }
  27056. if (this._ranges) {
  27057. clone._ranges = {};
  27058. for (var name in this._ranges) {
  27059. clone._ranges[name] = this._ranges[name].clone();
  27060. }
  27061. }
  27062. return clone;
  27063. };
  27064. Animation.prototype.setKeys = function (values) {
  27065. this._keys = values.slice(0);
  27066. this._offsetsCache = {};
  27067. this._highLimitsCache = {};
  27068. };
  27069. Animation.prototype._getKeyValue = function (value) {
  27070. if (typeof value === "function") {
  27071. return value();
  27072. }
  27073. return value;
  27074. };
  27075. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  27076. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  27077. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  27078. }
  27079. this.currentFrame = currentFrame;
  27080. // Try to get a hash to find the right key
  27081. 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));
  27082. if (this._keys[startKey].frame >= currentFrame) {
  27083. while (startKey - 1 >= 0 && this._keys[startKey].frame >= currentFrame) {
  27084. startKey--;
  27085. }
  27086. }
  27087. for (var key = startKey; key < this._keys.length; key++) {
  27088. if (this._keys[key + 1].frame >= currentFrame) {
  27089. var startValue = this._getKeyValue(this._keys[key].value);
  27090. var endValue = this._getKeyValue(this._keys[key + 1].value);
  27091. // gradient : percent of currentFrame between the frame inf and the frame sup
  27092. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  27093. // check for easingFunction and correction of gradient
  27094. if (this._easingFunction != null) {
  27095. gradient = this._easingFunction.ease(gradient);
  27096. }
  27097. switch (this.dataType) {
  27098. // Float
  27099. case Animation.ANIMATIONTYPE_FLOAT:
  27100. switch (loopMode) {
  27101. case Animation.ANIMATIONLOOPMODE_CYCLE:
  27102. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  27103. return this.floatInterpolateFunction(startValue, endValue, gradient);
  27104. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  27105. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  27106. }
  27107. break;
  27108. // Quaternion
  27109. case Animation.ANIMATIONTYPE_QUATERNION:
  27110. var quaternion = null;
  27111. switch (loopMode) {
  27112. case Animation.ANIMATIONLOOPMODE_CYCLE:
  27113. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  27114. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  27115. break;
  27116. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  27117. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  27118. break;
  27119. }
  27120. return quaternion;
  27121. // Vector3
  27122. case Animation.ANIMATIONTYPE_VECTOR3:
  27123. switch (loopMode) {
  27124. case Animation.ANIMATIONLOOPMODE_CYCLE:
  27125. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  27126. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  27127. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  27128. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  27129. }
  27130. // Vector2
  27131. case Animation.ANIMATIONTYPE_VECTOR2:
  27132. switch (loopMode) {
  27133. case Animation.ANIMATIONLOOPMODE_CYCLE:
  27134. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  27135. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  27136. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  27137. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  27138. }
  27139. // Size
  27140. case Animation.ANIMATIONTYPE_SIZE:
  27141. switch (loopMode) {
  27142. case Animation.ANIMATIONLOOPMODE_CYCLE:
  27143. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  27144. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  27145. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  27146. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  27147. }
  27148. // Color3
  27149. case Animation.ANIMATIONTYPE_COLOR3:
  27150. switch (loopMode) {
  27151. case Animation.ANIMATIONLOOPMODE_CYCLE:
  27152. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  27153. return this.color3InterpolateFunction(startValue, endValue, gradient);
  27154. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  27155. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  27156. }
  27157. // Matrix
  27158. case Animation.ANIMATIONTYPE_MATRIX:
  27159. switch (loopMode) {
  27160. case Animation.ANIMATIONLOOPMODE_CYCLE:
  27161. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  27162. if (this.allowMatricesInterpolation) {
  27163. return this.matrixInterpolateFunction(startValue, endValue, gradient);
  27164. }
  27165. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  27166. return startValue;
  27167. }
  27168. default:
  27169. break;
  27170. }
  27171. break;
  27172. }
  27173. }
  27174. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  27175. };
  27176. Animation.prototype.setValue = function (currentValue, blend) {
  27177. if (blend === void 0) { blend = false; }
  27178. // Set value
  27179. var path;
  27180. var destination;
  27181. if (this.targetPropertyPath.length > 1) {
  27182. var property = this._target[this.targetPropertyPath[0]];
  27183. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  27184. property = property[this.targetPropertyPath[index]];
  27185. }
  27186. path = this.targetPropertyPath[this.targetPropertyPath.length - 1];
  27187. destination = property;
  27188. }
  27189. else {
  27190. path = this.targetPropertyPath[0];
  27191. destination = this._target;
  27192. }
  27193. // Blending
  27194. if (this.enableBlending && this._blendingFactor <= 1.0) {
  27195. if (!this._originalBlendValue) {
  27196. if (destination[path].clone) {
  27197. this._originalBlendValue = destination[path].clone();
  27198. }
  27199. else {
  27200. this._originalBlendValue = destination[path];
  27201. }
  27202. }
  27203. if (this._originalBlendValue.prototype) {
  27204. if (this._originalBlendValue.prototype.Lerp) {
  27205. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  27206. }
  27207. else {
  27208. destination[path] = currentValue;
  27209. }
  27210. }
  27211. else if (this._originalBlendValue.m) {
  27212. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  27213. }
  27214. else {
  27215. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  27216. }
  27217. this._blendingFactor += this.blendingSpeed;
  27218. }
  27219. else {
  27220. destination[path] = currentValue;
  27221. }
  27222. if (this._target.markAsDirty) {
  27223. this._target.markAsDirty(this.targetProperty);
  27224. }
  27225. };
  27226. Animation.prototype.goToFrame = function (frame) {
  27227. if (frame < this._keys[0].frame) {
  27228. frame = this._keys[0].frame;
  27229. }
  27230. else if (frame > this._keys[this._keys.length - 1].frame) {
  27231. frame = this._keys[this._keys.length - 1].frame;
  27232. }
  27233. var currentValue = this._interpolate(frame, 0, this.loopMode);
  27234. this.setValue(currentValue);
  27235. };
  27236. Animation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  27237. if (blend === void 0) { blend = false; }
  27238. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  27239. this._stopped = true;
  27240. return false;
  27241. }
  27242. var returnValue = true;
  27243. // Adding a start key at frame 0 if missing
  27244. if (this._keys[0].frame !== 0) {
  27245. var newKey = { frame: 0, value: this._keys[0].value };
  27246. this._keys.splice(0, 0, newKey);
  27247. }
  27248. // Check limits
  27249. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  27250. from = this._keys[0].frame;
  27251. }
  27252. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  27253. to = this._keys[this._keys.length - 1].frame;
  27254. }
  27255. // Compute ratio
  27256. var range = to - from;
  27257. var offsetValue;
  27258. // ratio represents the frame delta between from and to
  27259. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  27260. var highLimitValue = 0;
  27261. if (ratio > range && !loop) {
  27262. returnValue = false;
  27263. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  27264. }
  27265. else {
  27266. // Get max value if required
  27267. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  27268. var keyOffset = to.toString() + from.toString();
  27269. if (!this._offsetsCache[keyOffset]) {
  27270. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  27271. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  27272. switch (this.dataType) {
  27273. // Float
  27274. case Animation.ANIMATIONTYPE_FLOAT:
  27275. this._offsetsCache[keyOffset] = toValue - fromValue;
  27276. break;
  27277. // Quaternion
  27278. case Animation.ANIMATIONTYPE_QUATERNION:
  27279. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  27280. break;
  27281. // Vector3
  27282. case Animation.ANIMATIONTYPE_VECTOR3:
  27283. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  27284. // Vector2
  27285. case Animation.ANIMATIONTYPE_VECTOR2:
  27286. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  27287. // Size
  27288. case Animation.ANIMATIONTYPE_SIZE:
  27289. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  27290. // Color3
  27291. case Animation.ANIMATIONTYPE_COLOR3:
  27292. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  27293. default:
  27294. break;
  27295. }
  27296. this._highLimitsCache[keyOffset] = toValue;
  27297. }
  27298. highLimitValue = this._highLimitsCache[keyOffset];
  27299. offsetValue = this._offsetsCache[keyOffset];
  27300. }
  27301. }
  27302. if (offsetValue === undefined) {
  27303. switch (this.dataType) {
  27304. // Float
  27305. case Animation.ANIMATIONTYPE_FLOAT:
  27306. offsetValue = 0;
  27307. break;
  27308. // Quaternion
  27309. case Animation.ANIMATIONTYPE_QUATERNION:
  27310. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  27311. break;
  27312. // Vector3
  27313. case Animation.ANIMATIONTYPE_VECTOR3:
  27314. offsetValue = BABYLON.Vector3.Zero();
  27315. break;
  27316. // Vector2
  27317. case Animation.ANIMATIONTYPE_VECTOR2:
  27318. offsetValue = BABYLON.Vector2.Zero();
  27319. break;
  27320. // Size
  27321. case Animation.ANIMATIONTYPE_SIZE:
  27322. offsetValue = BABYLON.Size.Zero();
  27323. break;
  27324. // Color3
  27325. case Animation.ANIMATIONTYPE_COLOR3:
  27326. offsetValue = BABYLON.Color3.Black();
  27327. }
  27328. }
  27329. // Compute value
  27330. var repeatCount = (ratio / range) >> 0;
  27331. var currentFrame = returnValue ? from + ratio % range : to;
  27332. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  27333. // Set value
  27334. this.setValue(currentValue);
  27335. // Check events
  27336. for (var index = 0; index < this._events.length; index++) {
  27337. if (currentFrame >= this._events[index].frame) {
  27338. var event = this._events[index];
  27339. if (!event.isDone) {
  27340. // If event should be done only once, remove it.
  27341. if (event.onlyOnce) {
  27342. this._events.splice(index, 1);
  27343. index--;
  27344. }
  27345. event.isDone = true;
  27346. event.action();
  27347. } // Don't do anything if the event has already be done.
  27348. }
  27349. else if (this._events[index].isDone && !this._events[index].onlyOnce) {
  27350. // reset event, the animation is looping
  27351. this._events[index].isDone = false;
  27352. }
  27353. }
  27354. if (!returnValue) {
  27355. this._stopped = true;
  27356. }
  27357. return returnValue;
  27358. };
  27359. Animation.prototype.serialize = function () {
  27360. var serializationObject = {};
  27361. serializationObject.name = this.name;
  27362. serializationObject.property = this.targetProperty;
  27363. serializationObject.framePerSecond = this.framePerSecond;
  27364. serializationObject.dataType = this.dataType;
  27365. serializationObject.loopBehavior = this.loopMode;
  27366. var dataType = this.dataType;
  27367. serializationObject.keys = [];
  27368. var keys = this.getKeys();
  27369. for (var index = 0; index < keys.length; index++) {
  27370. var animationKey = keys[index];
  27371. var key = {};
  27372. key.frame = animationKey.frame;
  27373. switch (dataType) {
  27374. case Animation.ANIMATIONTYPE_FLOAT:
  27375. key.values = [animationKey.value];
  27376. break;
  27377. case Animation.ANIMATIONTYPE_QUATERNION:
  27378. case Animation.ANIMATIONTYPE_MATRIX:
  27379. case Animation.ANIMATIONTYPE_VECTOR3:
  27380. case Animation.ANIMATIONTYPE_COLOR3:
  27381. key.values = animationKey.value.asArray();
  27382. break;
  27383. }
  27384. serializationObject.keys.push(key);
  27385. }
  27386. serializationObject.ranges = [];
  27387. for (var name in this._ranges) {
  27388. var range = {};
  27389. range.name = name;
  27390. range.from = this._ranges[name].from;
  27391. range.to = this._ranges[name].to;
  27392. serializationObject.ranges.push(range);
  27393. }
  27394. return serializationObject;
  27395. };
  27396. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  27397. get: function () {
  27398. return Animation._ANIMATIONTYPE_FLOAT;
  27399. },
  27400. enumerable: true,
  27401. configurable: true
  27402. });
  27403. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  27404. get: function () {
  27405. return Animation._ANIMATIONTYPE_VECTOR3;
  27406. },
  27407. enumerable: true,
  27408. configurable: true
  27409. });
  27410. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  27411. get: function () {
  27412. return Animation._ANIMATIONTYPE_VECTOR2;
  27413. },
  27414. enumerable: true,
  27415. configurable: true
  27416. });
  27417. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  27418. get: function () {
  27419. return Animation._ANIMATIONTYPE_SIZE;
  27420. },
  27421. enumerable: true,
  27422. configurable: true
  27423. });
  27424. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  27425. get: function () {
  27426. return Animation._ANIMATIONTYPE_QUATERNION;
  27427. },
  27428. enumerable: true,
  27429. configurable: true
  27430. });
  27431. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  27432. get: function () {
  27433. return Animation._ANIMATIONTYPE_MATRIX;
  27434. },
  27435. enumerable: true,
  27436. configurable: true
  27437. });
  27438. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  27439. get: function () {
  27440. return Animation._ANIMATIONTYPE_COLOR3;
  27441. },
  27442. enumerable: true,
  27443. configurable: true
  27444. });
  27445. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  27446. get: function () {
  27447. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  27448. },
  27449. enumerable: true,
  27450. configurable: true
  27451. });
  27452. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  27453. get: function () {
  27454. return Animation._ANIMATIONLOOPMODE_CYCLE;
  27455. },
  27456. enumerable: true,
  27457. configurable: true
  27458. });
  27459. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  27460. get: function () {
  27461. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  27462. },
  27463. enumerable: true,
  27464. configurable: true
  27465. });
  27466. Animation.Parse = function (parsedAnimation) {
  27467. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  27468. var dataType = parsedAnimation.dataType;
  27469. var keys = [];
  27470. var data;
  27471. var index;
  27472. for (index = 0; index < parsedAnimation.keys.length; index++) {
  27473. var key = parsedAnimation.keys[index];
  27474. switch (dataType) {
  27475. case Animation.ANIMATIONTYPE_FLOAT:
  27476. data = key.values[0];
  27477. break;
  27478. case Animation.ANIMATIONTYPE_QUATERNION:
  27479. data = BABYLON.Quaternion.FromArray(key.values);
  27480. break;
  27481. case Animation.ANIMATIONTYPE_MATRIX:
  27482. data = BABYLON.Matrix.FromArray(key.values);
  27483. break;
  27484. case Animation.ANIMATIONTYPE_COLOR3:
  27485. data = BABYLON.Color3.FromArray(key.values);
  27486. break;
  27487. case Animation.ANIMATIONTYPE_VECTOR3:
  27488. default:
  27489. data = BABYLON.Vector3.FromArray(key.values);
  27490. break;
  27491. }
  27492. keys.push({
  27493. frame: key.frame,
  27494. value: data
  27495. });
  27496. }
  27497. animation.setKeys(keys);
  27498. if (parsedAnimation.ranges) {
  27499. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  27500. data = parsedAnimation.ranges[index];
  27501. animation.createRange(data.name, data.from, data.to);
  27502. }
  27503. }
  27504. return animation;
  27505. };
  27506. Animation.AppendSerializedAnimations = function (source, destination) {
  27507. if (source.animations) {
  27508. destination.animations = [];
  27509. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  27510. var animation = source.animations[animationIndex];
  27511. destination.animations.push(animation.serialize());
  27512. }
  27513. }
  27514. };
  27515. // Statics
  27516. Animation._ANIMATIONTYPE_FLOAT = 0;
  27517. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  27518. Animation._ANIMATIONTYPE_QUATERNION = 2;
  27519. Animation._ANIMATIONTYPE_MATRIX = 3;
  27520. Animation._ANIMATIONTYPE_COLOR3 = 4;
  27521. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  27522. Animation._ANIMATIONTYPE_SIZE = 6;
  27523. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  27524. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  27525. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  27526. return Animation;
  27527. }());
  27528. BABYLON.Animation = Animation;
  27529. })(BABYLON || (BABYLON = {}));
  27530. var BABYLON;
  27531. (function (BABYLON) {
  27532. var Animatable = (function () {
  27533. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  27534. if (fromFrame === void 0) { fromFrame = 0; }
  27535. if (toFrame === void 0) { toFrame = 100; }
  27536. if (loopAnimation === void 0) { loopAnimation = false; }
  27537. if (speedRatio === void 0) { speedRatio = 1.0; }
  27538. this.target = target;
  27539. this.fromFrame = fromFrame;
  27540. this.toFrame = toFrame;
  27541. this.loopAnimation = loopAnimation;
  27542. this.speedRatio = speedRatio;
  27543. this.onAnimationEnd = onAnimationEnd;
  27544. this._animations = new Array();
  27545. this._paused = false;
  27546. this.animationStarted = false;
  27547. if (animations) {
  27548. this.appendAnimations(target, animations);
  27549. }
  27550. this._scene = scene;
  27551. scene._activeAnimatables.push(this);
  27552. }
  27553. // Methods
  27554. Animatable.prototype.getAnimations = function () {
  27555. return this._animations;
  27556. };
  27557. Animatable.prototype.appendAnimations = function (target, animations) {
  27558. for (var index = 0; index < animations.length; index++) {
  27559. var animation = animations[index];
  27560. animation._target = target;
  27561. this._animations.push(animation);
  27562. }
  27563. };
  27564. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  27565. var animations = this._animations;
  27566. for (var index = 0; index < animations.length; index++) {
  27567. if (animations[index].targetProperty === property) {
  27568. return animations[index];
  27569. }
  27570. }
  27571. return null;
  27572. };
  27573. Animatable.prototype.reset = function () {
  27574. var animations = this._animations;
  27575. for (var index = 0; index < animations.length; index++) {
  27576. animations[index].reset();
  27577. }
  27578. this._localDelayOffset = null;
  27579. this._pausedDelay = null;
  27580. };
  27581. Animatable.prototype.enableBlending = function (blendingSpeed) {
  27582. var animations = this._animations;
  27583. for (var index = 0; index < animations.length; index++) {
  27584. animations[index].enableBlending = true;
  27585. animations[index].blendingSpeed = blendingSpeed;
  27586. }
  27587. };
  27588. Animatable.prototype.disableBlending = function () {
  27589. var animations = this._animations;
  27590. for (var index = 0; index < animations.length; index++) {
  27591. animations[index].enableBlending = false;
  27592. }
  27593. };
  27594. Animatable.prototype.goToFrame = function (frame) {
  27595. var animations = this._animations;
  27596. for (var index = 0; index < animations.length; index++) {
  27597. animations[index].goToFrame(frame);
  27598. }
  27599. };
  27600. Animatable.prototype.pause = function () {
  27601. if (this._paused) {
  27602. return;
  27603. }
  27604. this._paused = true;
  27605. };
  27606. Animatable.prototype.restart = function () {
  27607. this._paused = false;
  27608. };
  27609. Animatable.prototype.stop = function () {
  27610. var index = this._scene._activeAnimatables.indexOf(this);
  27611. if (index > -1) {
  27612. this._scene._activeAnimatables.splice(index, 1);
  27613. var animations = this._animations;
  27614. for (var index = 0; index < animations.length; index++) {
  27615. animations[index].reset();
  27616. }
  27617. if (this.onAnimationEnd) {
  27618. this.onAnimationEnd();
  27619. }
  27620. }
  27621. };
  27622. Animatable.prototype._animate = function (delay) {
  27623. if (this._paused) {
  27624. this.animationStarted = false;
  27625. if (!this._pausedDelay) {
  27626. this._pausedDelay = delay;
  27627. }
  27628. return true;
  27629. }
  27630. if (!this._localDelayOffset) {
  27631. this._localDelayOffset = delay;
  27632. }
  27633. else if (this._pausedDelay) {
  27634. this._localDelayOffset += delay - this._pausedDelay;
  27635. this._pausedDelay = null;
  27636. }
  27637. // Animating
  27638. var running = false;
  27639. var animations = this._animations;
  27640. var index;
  27641. for (index = 0; index < animations.length; index++) {
  27642. var animation = animations[index];
  27643. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  27644. running = running || isRunning;
  27645. }
  27646. this.animationStarted = running;
  27647. if (!running) {
  27648. // Remove from active animatables
  27649. index = this._scene._activeAnimatables.indexOf(this);
  27650. this._scene._activeAnimatables.splice(index, 1);
  27651. }
  27652. if (!running && this.onAnimationEnd) {
  27653. this.onAnimationEnd();
  27654. this.onAnimationEnd = null;
  27655. }
  27656. return running;
  27657. };
  27658. return Animatable;
  27659. }());
  27660. BABYLON.Animatable = Animatable;
  27661. })(BABYLON || (BABYLON = {}));
  27662. var BABYLON;
  27663. (function (BABYLON) {
  27664. var EasingFunction = (function () {
  27665. function EasingFunction() {
  27666. // Properties
  27667. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  27668. }
  27669. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  27670. get: function () {
  27671. return EasingFunction._EASINGMODE_EASEIN;
  27672. },
  27673. enumerable: true,
  27674. configurable: true
  27675. });
  27676. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  27677. get: function () {
  27678. return EasingFunction._EASINGMODE_EASEOUT;
  27679. },
  27680. enumerable: true,
  27681. configurable: true
  27682. });
  27683. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  27684. get: function () {
  27685. return EasingFunction._EASINGMODE_EASEINOUT;
  27686. },
  27687. enumerable: true,
  27688. configurable: true
  27689. });
  27690. EasingFunction.prototype.setEasingMode = function (easingMode) {
  27691. var n = Math.min(Math.max(easingMode, 0), 2);
  27692. this._easingMode = n;
  27693. };
  27694. EasingFunction.prototype.getEasingMode = function () {
  27695. return this._easingMode;
  27696. };
  27697. EasingFunction.prototype.easeInCore = function (gradient) {
  27698. throw new Error('You must implement this method');
  27699. };
  27700. EasingFunction.prototype.ease = function (gradient) {
  27701. switch (this._easingMode) {
  27702. case EasingFunction.EASINGMODE_EASEIN:
  27703. return this.easeInCore(gradient);
  27704. case EasingFunction.EASINGMODE_EASEOUT:
  27705. return (1 - this.easeInCore(1 - gradient));
  27706. }
  27707. if (gradient >= 0.5) {
  27708. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  27709. }
  27710. return (this.easeInCore(gradient * 2) * 0.5);
  27711. };
  27712. //Statics
  27713. EasingFunction._EASINGMODE_EASEIN = 0;
  27714. EasingFunction._EASINGMODE_EASEOUT = 1;
  27715. EasingFunction._EASINGMODE_EASEINOUT = 2;
  27716. return EasingFunction;
  27717. }());
  27718. BABYLON.EasingFunction = EasingFunction;
  27719. var CircleEase = (function (_super) {
  27720. __extends(CircleEase, _super);
  27721. function CircleEase() {
  27722. _super.apply(this, arguments);
  27723. }
  27724. CircleEase.prototype.easeInCore = function (gradient) {
  27725. gradient = Math.max(0, Math.min(1, gradient));
  27726. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  27727. };
  27728. return CircleEase;
  27729. }(EasingFunction));
  27730. BABYLON.CircleEase = CircleEase;
  27731. var BackEase = (function (_super) {
  27732. __extends(BackEase, _super);
  27733. function BackEase(amplitude) {
  27734. if (amplitude === void 0) { amplitude = 1; }
  27735. _super.call(this);
  27736. this.amplitude = amplitude;
  27737. }
  27738. BackEase.prototype.easeInCore = function (gradient) {
  27739. var num = Math.max(0, this.amplitude);
  27740. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  27741. };
  27742. return BackEase;
  27743. }(EasingFunction));
  27744. BABYLON.BackEase = BackEase;
  27745. var BounceEase = (function (_super) {
  27746. __extends(BounceEase, _super);
  27747. function BounceEase(bounces, bounciness) {
  27748. if (bounces === void 0) { bounces = 3; }
  27749. if (bounciness === void 0) { bounciness = 2; }
  27750. _super.call(this);
  27751. this.bounces = bounces;
  27752. this.bounciness = bounciness;
  27753. }
  27754. BounceEase.prototype.easeInCore = function (gradient) {
  27755. var y = Math.max(0.0, this.bounces);
  27756. var bounciness = this.bounciness;
  27757. if (bounciness <= 1.0) {
  27758. bounciness = 1.001;
  27759. }
  27760. var num9 = Math.pow(bounciness, y);
  27761. var num5 = 1.0 - bounciness;
  27762. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  27763. var num15 = gradient * num4;
  27764. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  27765. var num3 = Math.floor(num65);
  27766. var num13 = num3 + 1.0;
  27767. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  27768. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  27769. var num7 = (num8 + num12) * 0.5;
  27770. var num6 = gradient - num7;
  27771. var num2 = num7 - num8;
  27772. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  27773. };
  27774. return BounceEase;
  27775. }(EasingFunction));
  27776. BABYLON.BounceEase = BounceEase;
  27777. var CubicEase = (function (_super) {
  27778. __extends(CubicEase, _super);
  27779. function CubicEase() {
  27780. _super.apply(this, arguments);
  27781. }
  27782. CubicEase.prototype.easeInCore = function (gradient) {
  27783. return (gradient * gradient * gradient);
  27784. };
  27785. return CubicEase;
  27786. }(EasingFunction));
  27787. BABYLON.CubicEase = CubicEase;
  27788. var ElasticEase = (function (_super) {
  27789. __extends(ElasticEase, _super);
  27790. function ElasticEase(oscillations, springiness) {
  27791. if (oscillations === void 0) { oscillations = 3; }
  27792. if (springiness === void 0) { springiness = 3; }
  27793. _super.call(this);
  27794. this.oscillations = oscillations;
  27795. this.springiness = springiness;
  27796. }
  27797. ElasticEase.prototype.easeInCore = function (gradient) {
  27798. var num2;
  27799. var num3 = Math.max(0.0, this.oscillations);
  27800. var num = Math.max(0.0, this.springiness);
  27801. if (num == 0) {
  27802. num2 = gradient;
  27803. }
  27804. else {
  27805. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  27806. }
  27807. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  27808. };
  27809. return ElasticEase;
  27810. }(EasingFunction));
  27811. BABYLON.ElasticEase = ElasticEase;
  27812. var ExponentialEase = (function (_super) {
  27813. __extends(ExponentialEase, _super);
  27814. function ExponentialEase(exponent) {
  27815. if (exponent === void 0) { exponent = 2; }
  27816. _super.call(this);
  27817. this.exponent = exponent;
  27818. }
  27819. ExponentialEase.prototype.easeInCore = function (gradient) {
  27820. if (this.exponent <= 0) {
  27821. return gradient;
  27822. }
  27823. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  27824. };
  27825. return ExponentialEase;
  27826. }(EasingFunction));
  27827. BABYLON.ExponentialEase = ExponentialEase;
  27828. var PowerEase = (function (_super) {
  27829. __extends(PowerEase, _super);
  27830. function PowerEase(power) {
  27831. if (power === void 0) { power = 2; }
  27832. _super.call(this);
  27833. this.power = power;
  27834. }
  27835. PowerEase.prototype.easeInCore = function (gradient) {
  27836. var y = Math.max(0.0, this.power);
  27837. return Math.pow(gradient, y);
  27838. };
  27839. return PowerEase;
  27840. }(EasingFunction));
  27841. BABYLON.PowerEase = PowerEase;
  27842. var QuadraticEase = (function (_super) {
  27843. __extends(QuadraticEase, _super);
  27844. function QuadraticEase() {
  27845. _super.apply(this, arguments);
  27846. }
  27847. QuadraticEase.prototype.easeInCore = function (gradient) {
  27848. return (gradient * gradient);
  27849. };
  27850. return QuadraticEase;
  27851. }(EasingFunction));
  27852. BABYLON.QuadraticEase = QuadraticEase;
  27853. var QuarticEase = (function (_super) {
  27854. __extends(QuarticEase, _super);
  27855. function QuarticEase() {
  27856. _super.apply(this, arguments);
  27857. }
  27858. QuarticEase.prototype.easeInCore = function (gradient) {
  27859. return (gradient * gradient * gradient * gradient);
  27860. };
  27861. return QuarticEase;
  27862. }(EasingFunction));
  27863. BABYLON.QuarticEase = QuarticEase;
  27864. var QuinticEase = (function (_super) {
  27865. __extends(QuinticEase, _super);
  27866. function QuinticEase() {
  27867. _super.apply(this, arguments);
  27868. }
  27869. QuinticEase.prototype.easeInCore = function (gradient) {
  27870. return (gradient * gradient * gradient * gradient * gradient);
  27871. };
  27872. return QuinticEase;
  27873. }(EasingFunction));
  27874. BABYLON.QuinticEase = QuinticEase;
  27875. var SineEase = (function (_super) {
  27876. __extends(SineEase, _super);
  27877. function SineEase() {
  27878. _super.apply(this, arguments);
  27879. }
  27880. SineEase.prototype.easeInCore = function (gradient) {
  27881. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  27882. };
  27883. return SineEase;
  27884. }(EasingFunction));
  27885. BABYLON.SineEase = SineEase;
  27886. var BezierCurveEase = (function (_super) {
  27887. __extends(BezierCurveEase, _super);
  27888. function BezierCurveEase(x1, y1, x2, y2) {
  27889. if (x1 === void 0) { x1 = 0; }
  27890. if (y1 === void 0) { y1 = 0; }
  27891. if (x2 === void 0) { x2 = 1; }
  27892. if (y2 === void 0) { y2 = 1; }
  27893. _super.call(this);
  27894. this.x1 = x1;
  27895. this.y1 = y1;
  27896. this.x2 = x2;
  27897. this.y2 = y2;
  27898. }
  27899. BezierCurveEase.prototype.easeInCore = function (gradient) {
  27900. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  27901. };
  27902. return BezierCurveEase;
  27903. }(EasingFunction));
  27904. BABYLON.BezierCurveEase = BezierCurveEase;
  27905. })(BABYLON || (BABYLON = {}));
  27906. var BABYLON;
  27907. (function (BABYLON) {
  27908. var Bone = (function (_super) {
  27909. __extends(Bone, _super);
  27910. function Bone(name, skeleton, parentBone, matrix, restPose) {
  27911. _super.call(this, name, skeleton.getScene());
  27912. this.name = name;
  27913. this.children = new Array();
  27914. this.animations = new Array();
  27915. this._worldTransform = new BABYLON.Matrix();
  27916. this._absoluteTransform = new BABYLON.Matrix();
  27917. this._invertedAbsoluteTransform = new BABYLON.Matrix();
  27918. this._skeleton = skeleton;
  27919. this._matrix = matrix;
  27920. this._baseMatrix = matrix;
  27921. this._restPose = restPose ? restPose : matrix.clone();
  27922. skeleton.bones.push(this);
  27923. if (parentBone) {
  27924. this._parent = parentBone;
  27925. parentBone.children.push(this);
  27926. }
  27927. else {
  27928. this._parent = null;
  27929. }
  27930. this._updateDifferenceMatrix();
  27931. }
  27932. // Members
  27933. Bone.prototype.getParent = function () {
  27934. return this._parent;
  27935. };
  27936. Bone.prototype.getLocalMatrix = function () {
  27937. return this._matrix;
  27938. };
  27939. Bone.prototype.getBaseMatrix = function () {
  27940. return this._baseMatrix;
  27941. };
  27942. Bone.prototype.getRestPose = function () {
  27943. return this._restPose;
  27944. };
  27945. Bone.prototype.returnToRest = function () {
  27946. this.updateMatrix(this._restPose.clone());
  27947. };
  27948. Bone.prototype.getWorldMatrix = function () {
  27949. return this._worldTransform;
  27950. };
  27951. Bone.prototype.getInvertedAbsoluteTransform = function () {
  27952. return this._invertedAbsoluteTransform;
  27953. };
  27954. Bone.prototype.getAbsoluteTransform = function () {
  27955. return this._absoluteTransform;
  27956. };
  27957. // Methods
  27958. Bone.prototype.updateMatrix = function (matrix) {
  27959. this._baseMatrix = matrix.clone();
  27960. this._matrix = matrix.clone();
  27961. this._skeleton._markAsDirty();
  27962. this._updateDifferenceMatrix();
  27963. };
  27964. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  27965. if (!rootMatrix) {
  27966. rootMatrix = this._baseMatrix;
  27967. }
  27968. if (this._parent) {
  27969. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  27970. }
  27971. else {
  27972. this._absoluteTransform.copyFrom(rootMatrix);
  27973. }
  27974. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  27975. for (var index = 0; index < this.children.length; index++) {
  27976. this.children[index]._updateDifferenceMatrix();
  27977. }
  27978. };
  27979. Bone.prototype.markAsDirty = function () {
  27980. this._currentRenderId++;
  27981. this._skeleton._markAsDirty();
  27982. };
  27983. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  27984. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  27985. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  27986. // all animation may be coming from a library skeleton, so may need to create animation
  27987. if (this.animations.length === 0) {
  27988. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  27989. this.animations[0].setKeys([]);
  27990. }
  27991. // get animation info / verify there is such a range from the source bone
  27992. var sourceRange = source.animations[0].getRange(rangeName);
  27993. if (!sourceRange) {
  27994. return false;
  27995. }
  27996. var from = sourceRange.from;
  27997. var to = sourceRange.to;
  27998. var sourceKeys = source.animations[0].getKeys();
  27999. // rescaling prep
  28000. var sourceBoneLength = source.length;
  28001. var sourceParent = source.getParent();
  28002. var parent = this.getParent();
  28003. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  28004. var parentRatio = parentScalingReqd ? parent.length / sourceParent.length : null;
  28005. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  28006. var destKeys = this.animations[0].getKeys();
  28007. // loop vars declaration
  28008. var orig;
  28009. var origTranslation;
  28010. var mat;
  28011. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  28012. orig = sourceKeys[key];
  28013. if (orig.frame >= from && orig.frame <= to) {
  28014. if (rescaleAsRequired) {
  28015. mat = orig.value.clone();
  28016. // scale based on parent ratio, when bone has parent
  28017. if (parentScalingReqd) {
  28018. origTranslation = mat.getTranslation();
  28019. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  28020. }
  28021. else if (dimensionsScalingReqd) {
  28022. origTranslation = mat.getTranslation();
  28023. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  28024. }
  28025. else {
  28026. mat = orig.value;
  28027. }
  28028. }
  28029. else {
  28030. mat = orig.value;
  28031. }
  28032. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  28033. }
  28034. }
  28035. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  28036. return true;
  28037. };
  28038. return Bone;
  28039. }(BABYLON.Node));
  28040. BABYLON.Bone = Bone;
  28041. })(BABYLON || (BABYLON = {}));
  28042. var BABYLON;
  28043. (function (BABYLON) {
  28044. var Skeleton = (function () {
  28045. function Skeleton(name, id, scene) {
  28046. this.name = name;
  28047. this.id = id;
  28048. this.bones = new Array();
  28049. this.needInitialSkinMatrix = false;
  28050. this._isDirty = true;
  28051. this._meshesWithPoseMatrix = new Array();
  28052. this._identity = BABYLON.Matrix.Identity();
  28053. this._ranges = {};
  28054. this.bones = [];
  28055. this._scene = scene;
  28056. scene.skeletons.push(this);
  28057. //make sure it will recalculate the matrix next time prepare is called.
  28058. this._isDirty = true;
  28059. }
  28060. // Members
  28061. Skeleton.prototype.getTransformMatrices = function (mesh) {
  28062. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  28063. return mesh._bonesTransformMatrices;
  28064. }
  28065. return this._transformMatrices;
  28066. };
  28067. Skeleton.prototype.getScene = function () {
  28068. return this._scene;
  28069. };
  28070. // Methods
  28071. /**
  28072. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  28073. */
  28074. Skeleton.prototype.toString = function (fullDetails) {
  28075. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  28076. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  28077. if (fullDetails) {
  28078. ret += ", Ranges: {";
  28079. var first = true;
  28080. for (var name_1 in this._ranges) {
  28081. if (first) {
  28082. ret += ", ";
  28083. first = false;
  28084. }
  28085. ret += name_1;
  28086. }
  28087. ret += "}";
  28088. }
  28089. return ret;
  28090. };
  28091. /**
  28092. * Get bone's index searching by name
  28093. * @param {string} name is bone's name to search for
  28094. * @return {number} Indice of the bone. Returns -1 if not found
  28095. */
  28096. Skeleton.prototype.getBoneIndexByName = function (name) {
  28097. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  28098. if (this.bones[boneIndex].name === name) {
  28099. return boneIndex;
  28100. }
  28101. }
  28102. return -1;
  28103. };
  28104. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  28105. // check name not already in use
  28106. if (!this._ranges[name]) {
  28107. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  28108. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  28109. if (this.bones[i].animations[0]) {
  28110. this.bones[i].animations[0].createRange(name, from, to);
  28111. }
  28112. }
  28113. }
  28114. };
  28115. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  28116. if (deleteFrames === void 0) { deleteFrames = true; }
  28117. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  28118. if (this.bones[i].animations[0]) {
  28119. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  28120. }
  28121. }
  28122. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  28123. };
  28124. Skeleton.prototype.getAnimationRange = function (name) {
  28125. return this._ranges[name];
  28126. };
  28127. /**
  28128. * Returns as an Array, all AnimationRanges defined on this skeleton
  28129. */
  28130. Skeleton.prototype.getAnimationRanges = function () {
  28131. var animationRanges = [];
  28132. var name;
  28133. var i = 0;
  28134. for (name in this._ranges) {
  28135. animationRanges[i] = this._ranges[name];
  28136. i++;
  28137. }
  28138. return animationRanges;
  28139. };
  28140. /**
  28141. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  28142. */
  28143. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  28144. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  28145. if (this._ranges[name] || !source.getAnimationRange(name)) {
  28146. return false;
  28147. }
  28148. var ret = true;
  28149. var frameOffset = this._getHighestAnimationFrame() + 1;
  28150. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  28151. var boneDict = {};
  28152. var sourceBones = source.bones;
  28153. var nBones;
  28154. var i;
  28155. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  28156. boneDict[sourceBones[i].name] = sourceBones[i];
  28157. }
  28158. if (this.bones.length !== sourceBones.length) {
  28159. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  28160. ret = false;
  28161. }
  28162. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  28163. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  28164. var boneName = this.bones[i].name;
  28165. var sourceBone = boneDict[boneName];
  28166. if (sourceBone) {
  28167. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  28168. }
  28169. else {
  28170. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  28171. ret = false;
  28172. }
  28173. }
  28174. // do not call createAnimationRange(), since it also is done to bones, which was already done
  28175. var range = source.getAnimationRange(name);
  28176. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  28177. return ret;
  28178. };
  28179. Skeleton.prototype.returnToRest = function () {
  28180. for (var index = 0; index < this.bones.length; index++) {
  28181. this.bones[index].returnToRest();
  28182. }
  28183. };
  28184. Skeleton.prototype._getHighestAnimationFrame = function () {
  28185. var ret = 0;
  28186. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  28187. if (this.bones[i].animations[0]) {
  28188. var highest = this.bones[i].animations[0].getHighestFrame();
  28189. if (ret < highest) {
  28190. ret = highest;
  28191. }
  28192. }
  28193. }
  28194. return ret;
  28195. };
  28196. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  28197. var range = this.getAnimationRange(name);
  28198. if (!range) {
  28199. return null;
  28200. }
  28201. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  28202. };
  28203. Skeleton.prototype._markAsDirty = function () {
  28204. this._isDirty = true;
  28205. };
  28206. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  28207. this._meshesWithPoseMatrix.push(mesh);
  28208. };
  28209. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  28210. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  28211. if (index > -1) {
  28212. this._meshesWithPoseMatrix.splice(index, 1);
  28213. }
  28214. };
  28215. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  28216. for (var index = 0; index < this.bones.length; index++) {
  28217. var bone = this.bones[index];
  28218. var parentBone = bone.getParent();
  28219. if (parentBone) {
  28220. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  28221. }
  28222. else {
  28223. if (initialSkinMatrix) {
  28224. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  28225. }
  28226. else {
  28227. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  28228. }
  28229. }
  28230. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, index * 16);
  28231. }
  28232. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  28233. };
  28234. Skeleton.prototype.prepare = function () {
  28235. if (!this._isDirty) {
  28236. return;
  28237. }
  28238. if (this.needInitialSkinMatrix) {
  28239. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  28240. var mesh = this._meshesWithPoseMatrix[index];
  28241. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  28242. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  28243. }
  28244. var poseMatrix = mesh.getPoseMatrix();
  28245. // Prepare bones
  28246. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  28247. var bone = this.bones[boneIndex];
  28248. if (!bone.getParent()) {
  28249. var matrix = bone.getBaseMatrix();
  28250. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[0]);
  28251. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[0]);
  28252. }
  28253. }
  28254. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  28255. }
  28256. }
  28257. else {
  28258. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  28259. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  28260. }
  28261. this._computeTransformMatrices(this._transformMatrices, null);
  28262. }
  28263. this._isDirty = false;
  28264. this._scene._activeBones.addCount(this.bones.length, false);
  28265. };
  28266. Skeleton.prototype.getAnimatables = function () {
  28267. if (!this._animatables || this._animatables.length !== this.bones.length) {
  28268. this._animatables = [];
  28269. for (var index = 0; index < this.bones.length; index++) {
  28270. this._animatables.push(this.bones[index]);
  28271. }
  28272. }
  28273. return this._animatables;
  28274. };
  28275. Skeleton.prototype.clone = function (name, id) {
  28276. var result = new Skeleton(name, id || name, this._scene);
  28277. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  28278. for (var index = 0; index < this.bones.length; index++) {
  28279. var source = this.bones[index];
  28280. var parentBone = null;
  28281. if (source.getParent()) {
  28282. var parentIndex = this.bones.indexOf(source.getParent());
  28283. parentBone = result.bones[parentIndex];
  28284. }
  28285. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  28286. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  28287. }
  28288. if (this._ranges) {
  28289. result._ranges = {};
  28290. for (var rangeName in this._ranges) {
  28291. result._ranges[rangeName] = this._ranges[rangeName].clone();
  28292. }
  28293. }
  28294. this._isDirty = true;
  28295. return result;
  28296. };
  28297. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  28298. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  28299. this.bones.forEach(function (bone) {
  28300. bone.animations.forEach(function (animation) {
  28301. animation.enableBlending = true;
  28302. animation.blendingSpeed = blendingSpeed;
  28303. });
  28304. });
  28305. };
  28306. Skeleton.prototype.dispose = function () {
  28307. this._meshesWithPoseMatrix = [];
  28308. // Animations
  28309. this.getScene().stopAnimation(this);
  28310. // Remove from scene
  28311. this.getScene().removeSkeleton(this);
  28312. };
  28313. Skeleton.prototype.serialize = function () {
  28314. var serializationObject = {};
  28315. serializationObject.name = this.name;
  28316. serializationObject.id = this.id;
  28317. serializationObject.dimensionsAtRest = this.dimensionsAtRest;
  28318. serializationObject.bones = [];
  28319. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  28320. for (var index = 0; index < this.bones.length; index++) {
  28321. var bone = this.bones[index];
  28322. var serializedBone = {
  28323. parentBoneIndex: bone.getParent() ? this.bones.indexOf(bone.getParent()) : -1,
  28324. name: bone.name,
  28325. matrix: bone.getLocalMatrix().toArray(),
  28326. rest: bone.getRestPose().toArray()
  28327. };
  28328. serializationObject.bones.push(serializedBone);
  28329. if (bone.length) {
  28330. serializedBone.length = bone.length;
  28331. }
  28332. if (bone.animations && bone.animations.length > 0) {
  28333. serializedBone.animation = bone.animations[0].serialize();
  28334. }
  28335. serializationObject.ranges = [];
  28336. for (var name in this._ranges) {
  28337. var range = {};
  28338. range.name = name;
  28339. range.from = this._ranges[name].from;
  28340. range.to = this._ranges[name].to;
  28341. serializationObject.ranges.push(range);
  28342. }
  28343. }
  28344. return serializationObject;
  28345. };
  28346. Skeleton.Parse = function (parsedSkeleton, scene) {
  28347. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  28348. if (parsedSkeleton.dimensionsAtRest) {
  28349. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  28350. }
  28351. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  28352. var index;
  28353. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  28354. var parsedBone = parsedSkeleton.bones[index];
  28355. var parentBone = null;
  28356. if (parsedBone.parentBoneIndex > -1) {
  28357. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  28358. }
  28359. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  28360. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  28361. if (parsedBone.length) {
  28362. bone.length = parsedBone.length;
  28363. }
  28364. if (parsedBone.animation) {
  28365. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  28366. }
  28367. }
  28368. // placed after bones, so createAnimationRange can cascade down
  28369. if (parsedSkeleton.ranges) {
  28370. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  28371. var data = parsedSkeleton.ranges[index];
  28372. skeleton.createAnimationRange(data.name, data.from, data.to);
  28373. }
  28374. }
  28375. return skeleton;
  28376. };
  28377. return Skeleton;
  28378. }());
  28379. BABYLON.Skeleton = Skeleton;
  28380. })(BABYLON || (BABYLON = {}));
  28381. var BABYLON;
  28382. (function (BABYLON) {
  28383. var PostProcess = (function () {
  28384. function PostProcess(name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType) {
  28385. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  28386. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  28387. this.name = name;
  28388. this.width = -1;
  28389. this.height = -1;
  28390. /*
  28391. Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  28392. Can only be used on a single postprocess or on the last one of a chain.
  28393. */
  28394. this.enablePixelPerfectMode = false;
  28395. this._reusable = false;
  28396. this._textures = new BABYLON.SmartArray(2);
  28397. this._currentRenderTextureInd = 0;
  28398. this._scaleRatio = new BABYLON.Vector2(1, 1);
  28399. // Events
  28400. /**
  28401. * An event triggered when the postprocess is activated.
  28402. * @type {BABYLON.Observable}
  28403. */
  28404. this.onActivateObservable = new BABYLON.Observable();
  28405. /**
  28406. * An event triggered when the postprocess changes its size.
  28407. * @type {BABYLON.Observable}
  28408. */
  28409. this.onSizeChangedObservable = new BABYLON.Observable();
  28410. /**
  28411. * An event triggered when the postprocess applies its effect.
  28412. * @type {BABYLON.Observable}
  28413. */
  28414. this.onApplyObservable = new BABYLON.Observable();
  28415. /**
  28416. * An event triggered before rendering the postprocess
  28417. * @type {BABYLON.Observable}
  28418. */
  28419. this.onBeforeRenderObservable = new BABYLON.Observable();
  28420. /**
  28421. * An event triggered after rendering the postprocess
  28422. * @type {BABYLON.Observable}
  28423. */
  28424. this.onAfterRenderObservable = new BABYLON.Observable();
  28425. if (camera != null) {
  28426. this._camera = camera;
  28427. this._scene = camera.getScene();
  28428. camera.attachPostProcess(this);
  28429. this._engine = this._scene.getEngine();
  28430. }
  28431. else {
  28432. this._engine = engine;
  28433. }
  28434. this._options = options;
  28435. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  28436. this._reusable = reusable || false;
  28437. this._textureType = textureType;
  28438. this._samplers = samplers || [];
  28439. this._samplers.push("textureSampler");
  28440. this._fragmentUrl = fragmentUrl;
  28441. this._parameters = parameters || [];
  28442. this._parameters.push("scale");
  28443. this.updateEffect(defines);
  28444. }
  28445. Object.defineProperty(PostProcess.prototype, "onActivate", {
  28446. set: function (callback) {
  28447. if (this._onActivateObserver) {
  28448. this.onActivateObservable.remove(this._onActivateObserver);
  28449. }
  28450. this._onActivateObserver = this.onActivateObservable.add(callback);
  28451. },
  28452. enumerable: true,
  28453. configurable: true
  28454. });
  28455. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  28456. set: function (callback) {
  28457. if (this._onSizeChangedObserver) {
  28458. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  28459. }
  28460. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  28461. },
  28462. enumerable: true,
  28463. configurable: true
  28464. });
  28465. Object.defineProperty(PostProcess.prototype, "onApply", {
  28466. set: function (callback) {
  28467. if (this._onApplyObserver) {
  28468. this.onApplyObservable.remove(this._onApplyObserver);
  28469. }
  28470. this._onApplyObserver = this.onApplyObservable.add(callback);
  28471. },
  28472. enumerable: true,
  28473. configurable: true
  28474. });
  28475. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  28476. set: function (callback) {
  28477. if (this._onBeforeRenderObserver) {
  28478. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  28479. }
  28480. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  28481. },
  28482. enumerable: true,
  28483. configurable: true
  28484. });
  28485. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  28486. set: function (callback) {
  28487. if (this._onAfterRenderObserver) {
  28488. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  28489. }
  28490. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  28491. },
  28492. enumerable: true,
  28493. configurable: true
  28494. });
  28495. PostProcess.prototype.updateEffect = function (defines) {
  28496. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: this._fragmentUrl }, ["position"], this._parameters, this._samplers, defines !== undefined ? defines : "");
  28497. };
  28498. PostProcess.prototype.isReusable = function () {
  28499. return this._reusable;
  28500. };
  28501. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  28502. PostProcess.prototype.markTextureDirty = function () {
  28503. this.width = -1;
  28504. };
  28505. PostProcess.prototype.activate = function (camera, sourceTexture) {
  28506. camera = camera || this._camera;
  28507. var scene = camera.getScene();
  28508. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  28509. var requiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._options) | 0;
  28510. var requiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._options) | 0;
  28511. var desiredWidth = this._options.width || requiredWidth;
  28512. var desiredHeight = this._options.height || requiredHeight;
  28513. if (this.renderTargetSamplingMode !== BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  28514. if (!this._options.width) {
  28515. desiredWidth = BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize);
  28516. }
  28517. if (!this._options.height) {
  28518. desiredHeight = BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize);
  28519. }
  28520. }
  28521. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  28522. if (this._textures.length > 0) {
  28523. for (var i = 0; i < this._textures.length; i++) {
  28524. this._engine._releaseTexture(this._textures.data[i]);
  28525. }
  28526. this._textures.reset();
  28527. }
  28528. this.width = desiredWidth;
  28529. this.height = desiredHeight;
  28530. 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 }));
  28531. if (this._reusable) {
  28532. 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 }));
  28533. }
  28534. this.onSizeChangedObservable.notifyObservers(this);
  28535. }
  28536. if (this.enablePixelPerfectMode) {
  28537. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  28538. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd], 0, requiredWidth, requiredHeight);
  28539. }
  28540. else {
  28541. this._scaleRatio.copyFromFloats(1, 1);
  28542. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  28543. }
  28544. this.onActivateObservable.notifyObservers(camera);
  28545. // Clear
  28546. if (this.clearColor) {
  28547. this._engine.clear(this.clearColor, true, true);
  28548. }
  28549. else {
  28550. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true);
  28551. }
  28552. if (this._reusable) {
  28553. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  28554. }
  28555. };
  28556. Object.defineProperty(PostProcess.prototype, "isSupported", {
  28557. get: function () {
  28558. return this._effect.isSupported;
  28559. },
  28560. enumerable: true,
  28561. configurable: true
  28562. });
  28563. PostProcess.prototype.apply = function () {
  28564. // Check
  28565. if (!this._effect.isReady())
  28566. return null;
  28567. // States
  28568. this._engine.enableEffect(this._effect);
  28569. this._engine.setState(false);
  28570. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  28571. this._engine.setDepthBuffer(false);
  28572. this._engine.setDepthWrite(false);
  28573. // Texture
  28574. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  28575. // Parameters
  28576. this._effect.setVector2("scale", this._scaleRatio);
  28577. this.onApplyObservable.notifyObservers(this._effect);
  28578. return this._effect;
  28579. };
  28580. PostProcess.prototype.dispose = function (camera) {
  28581. camera = camera || this._camera;
  28582. if (this._textures.length > 0) {
  28583. for (var i = 0; i < this._textures.length; i++) {
  28584. this._engine._releaseTexture(this._textures.data[i]);
  28585. }
  28586. this._textures.reset();
  28587. }
  28588. if (!camera) {
  28589. return;
  28590. }
  28591. camera.detachPostProcess(this);
  28592. var index = camera._postProcesses.indexOf(this);
  28593. if (index === 0 && camera._postProcesses.length > 0) {
  28594. this._camera._postProcesses[0].markTextureDirty();
  28595. }
  28596. this.onActivateObservable.clear();
  28597. this.onAfterRenderObservable.clear();
  28598. this.onApplyObservable.clear();
  28599. this.onBeforeRenderObservable.clear();
  28600. this.onSizeChangedObservable.clear();
  28601. };
  28602. return PostProcess;
  28603. }());
  28604. BABYLON.PostProcess = PostProcess;
  28605. })(BABYLON || (BABYLON = {}));
  28606. var BABYLON;
  28607. (function (BABYLON) {
  28608. var PostProcessManager = (function () {
  28609. function PostProcessManager(scene) {
  28610. this._vertexBuffers = {};
  28611. this._scene = scene;
  28612. }
  28613. PostProcessManager.prototype._prepareBuffers = function () {
  28614. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  28615. return;
  28616. }
  28617. // VBO
  28618. var vertices = [];
  28619. vertices.push(1, 1);
  28620. vertices.push(-1, 1);
  28621. vertices.push(-1, -1);
  28622. vertices.push(1, -1);
  28623. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  28624. // Indices
  28625. var indices = [];
  28626. indices.push(0);
  28627. indices.push(1);
  28628. indices.push(2);
  28629. indices.push(0);
  28630. indices.push(2);
  28631. indices.push(3);
  28632. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  28633. };
  28634. // Methods
  28635. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  28636. var postProcesses = this._scene.activeCamera._postProcesses;
  28637. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  28638. return false;
  28639. }
  28640. postProcesses[0].activate(this._scene.activeCamera, sourceTexture);
  28641. return true;
  28642. };
  28643. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
  28644. var engine = this._scene.getEngine();
  28645. for (var index = 0; index < postProcesses.length; index++) {
  28646. if (index < postProcesses.length - 1) {
  28647. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  28648. }
  28649. else {
  28650. if (targetTexture) {
  28651. engine.bindFramebuffer(targetTexture);
  28652. }
  28653. else {
  28654. engine.restoreDefaultFramebuffer();
  28655. }
  28656. }
  28657. var pp = postProcesses[index];
  28658. var effect = pp.apply();
  28659. if (effect) {
  28660. pp.onBeforeRenderObservable.notifyObservers(effect);
  28661. // VBOs
  28662. this._prepareBuffers();
  28663. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  28664. // Draw order
  28665. engine.draw(true, 0, 6);
  28666. pp.onAfterRenderObservable.notifyObservers(effect);
  28667. }
  28668. }
  28669. // Restore depth buffer
  28670. engine.setDepthBuffer(true);
  28671. engine.setDepthWrite(true);
  28672. };
  28673. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses) {
  28674. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  28675. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  28676. return;
  28677. }
  28678. var engine = this._scene.getEngine();
  28679. for (var index = 0, len = postProcesses.length; index < len; index++) {
  28680. if (index < len - 1) {
  28681. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  28682. }
  28683. else {
  28684. if (targetTexture) {
  28685. engine.bindFramebuffer(targetTexture, faceIndex);
  28686. }
  28687. else {
  28688. engine.restoreDefaultFramebuffer();
  28689. }
  28690. }
  28691. if (doNotPresent) {
  28692. break;
  28693. }
  28694. var pp = postProcesses[index];
  28695. var effect = pp.apply();
  28696. if (effect) {
  28697. pp.onBeforeRenderObservable.notifyObservers(effect);
  28698. // VBOs
  28699. this._prepareBuffers();
  28700. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  28701. // Draw order
  28702. engine.draw(true, 0, 6);
  28703. pp.onAfterRenderObservable.notifyObservers(effect);
  28704. }
  28705. }
  28706. // Restore depth buffer
  28707. engine.setDepthBuffer(true);
  28708. engine.setDepthWrite(true);
  28709. };
  28710. PostProcessManager.prototype.dispose = function () {
  28711. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  28712. if (buffer) {
  28713. buffer.dispose();
  28714. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  28715. }
  28716. if (this._indexBuffer) {
  28717. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  28718. this._indexBuffer = null;
  28719. }
  28720. };
  28721. return PostProcessManager;
  28722. }());
  28723. BABYLON.PostProcessManager = PostProcessManager;
  28724. })(BABYLON || (BABYLON = {}));
  28725. var BABYLON;
  28726. (function (BABYLON) {
  28727. var PassPostProcess = (function (_super) {
  28728. __extends(PassPostProcess, _super);
  28729. function PassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  28730. _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable);
  28731. }
  28732. return PassPostProcess;
  28733. }(BABYLON.PostProcess));
  28734. BABYLON.PassPostProcess = PassPostProcess;
  28735. })(BABYLON || (BABYLON = {}));
  28736. var BABYLON;
  28737. (function (BABYLON) {
  28738. /**
  28739. * This is a holder class for the physics joint created by the physics plugin.
  28740. * It holds a set of functions to control the underlying joint.
  28741. */
  28742. var PhysicsJoint = (function () {
  28743. function PhysicsJoint(type, jointData) {
  28744. this.type = type;
  28745. this.jointData = jointData;
  28746. jointData.nativeParams = jointData.nativeParams || {};
  28747. }
  28748. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  28749. get: function () {
  28750. return this._physicsJoint;
  28751. },
  28752. set: function (newJoint) {
  28753. if (this._physicsJoint) {
  28754. }
  28755. this._physicsJoint = newJoint;
  28756. },
  28757. enumerable: true,
  28758. configurable: true
  28759. });
  28760. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  28761. set: function (physicsPlugin) {
  28762. this._physicsPlugin = physicsPlugin;
  28763. },
  28764. enumerable: true,
  28765. configurable: true
  28766. });
  28767. /**
  28768. * Execute a function that is physics-plugin specific.
  28769. * @param {Function} func the function that will be executed.
  28770. * It accepts two parameters: the physics world and the physics joint.
  28771. */
  28772. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  28773. func(this._physicsPlugin.world, this._physicsJoint);
  28774. };
  28775. //TODO check if the native joints are the same
  28776. //Joint Types
  28777. PhysicsJoint.DistanceJoint = 0;
  28778. PhysicsJoint.HingeJoint = 1;
  28779. PhysicsJoint.BallAndSocketJoint = 2;
  28780. PhysicsJoint.WheelJoint = 3;
  28781. PhysicsJoint.SliderJoint = 4;
  28782. //OIMO
  28783. PhysicsJoint.PrismaticJoint = 5;
  28784. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  28785. PhysicsJoint.UniversalJoint = 6;
  28786. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  28787. //Cannon
  28788. //Similar to a Ball-Joint. Different in params
  28789. PhysicsJoint.PointToPointJoint = 8;
  28790. //Cannon only at the moment
  28791. PhysicsJoint.SpringJoint = 9;
  28792. PhysicsJoint.LockJoint = 10;
  28793. return PhysicsJoint;
  28794. }());
  28795. BABYLON.PhysicsJoint = PhysicsJoint;
  28796. /**
  28797. * A class representing a physics distance joint.
  28798. */
  28799. var DistanceJoint = (function (_super) {
  28800. __extends(DistanceJoint, _super);
  28801. function DistanceJoint(jointData) {
  28802. _super.call(this, PhysicsJoint.DistanceJoint, jointData);
  28803. }
  28804. /**
  28805. * Update the predefined distance.
  28806. */
  28807. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  28808. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  28809. };
  28810. return DistanceJoint;
  28811. }(PhysicsJoint));
  28812. BABYLON.DistanceJoint = DistanceJoint;
  28813. var MotorEnabledJoint = (function (_super) {
  28814. __extends(MotorEnabledJoint, _super);
  28815. function MotorEnabledJoint(type, jointData) {
  28816. _super.call(this, type, jointData);
  28817. }
  28818. /**
  28819. * Set the motor values.
  28820. * Attention, this function is plugin specific. Engines won't react 100% the same.
  28821. * @param {number} force the force to apply
  28822. * @param {number} maxForce max force for this motor.
  28823. */
  28824. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  28825. this._physicsPlugin.setMotor(this, force, maxForce);
  28826. };
  28827. /**
  28828. * Set the motor's limits.
  28829. * Attention, this function is plugin specific. Engines won't react 100% the same.
  28830. */
  28831. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  28832. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  28833. };
  28834. return MotorEnabledJoint;
  28835. }(PhysicsJoint));
  28836. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  28837. /**
  28838. * This class represents a single hinge physics joint
  28839. */
  28840. var HingeJoint = (function (_super) {
  28841. __extends(HingeJoint, _super);
  28842. function HingeJoint(jointData) {
  28843. _super.call(this, PhysicsJoint.HingeJoint, jointData);
  28844. }
  28845. /**
  28846. * Set the motor values.
  28847. * Attention, this function is plugin specific. Engines won't react 100% the same.
  28848. * @param {number} force the force to apply
  28849. * @param {number} maxForce max force for this motor.
  28850. */
  28851. HingeJoint.prototype.setMotor = function (force, maxForce) {
  28852. this._physicsPlugin.setMotor(this, force, maxForce);
  28853. };
  28854. /**
  28855. * Set the motor's limits.
  28856. * Attention, this function is plugin specific. Engines won't react 100% the same.
  28857. */
  28858. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  28859. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  28860. };
  28861. return HingeJoint;
  28862. }(MotorEnabledJoint));
  28863. BABYLON.HingeJoint = HingeJoint;
  28864. /**
  28865. * This class represents a dual hinge physics joint (same as wheel joint)
  28866. */
  28867. var Hinge2Joint = (function (_super) {
  28868. __extends(Hinge2Joint, _super);
  28869. function Hinge2Joint(jointData) {
  28870. _super.call(this, PhysicsJoint.Hinge2Joint, jointData);
  28871. }
  28872. /**
  28873. * Set the motor values.
  28874. * Attention, this function is plugin specific. Engines won't react 100% the same.
  28875. * @param {number} force the force to apply
  28876. * @param {number} maxForce max force for this motor.
  28877. * @param {motorIndex} the motor's index, 0 or 1.
  28878. */
  28879. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  28880. if (motorIndex === void 0) { motorIndex = 0; }
  28881. this._physicsPlugin.setMotor(this, force, maxForce, motorIndex);
  28882. };
  28883. /**
  28884. * Set the motor limits.
  28885. * Attention, this function is plugin specific. Engines won't react 100% the same.
  28886. * @param {number} upperLimit the upper limit
  28887. * @param {number} lowerLimit lower limit
  28888. * @param {motorIndex} the motor's index, 0 or 1.
  28889. */
  28890. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  28891. if (motorIndex === void 0) { motorIndex = 0; }
  28892. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  28893. };
  28894. return Hinge2Joint;
  28895. }(MotorEnabledJoint));
  28896. BABYLON.Hinge2Joint = Hinge2Joint;
  28897. })(BABYLON || (BABYLON = {}));
  28898. var BABYLON;
  28899. (function (BABYLON) {
  28900. var PhysicsImpostor = (function () {
  28901. function PhysicsImpostor(object, type, _options, _scene) {
  28902. var _this = this;
  28903. if (_options === void 0) { _options = { mass: 0 }; }
  28904. this.object = object;
  28905. this.type = type;
  28906. this._options = _options;
  28907. this._scene = _scene;
  28908. this._bodyUpdateRequired = false;
  28909. this._onBeforePhysicsStepCallbacks = new Array();
  28910. this._onAfterPhysicsStepCallbacks = new Array();
  28911. this._onPhysicsCollideCallbacks = [];
  28912. this._deltaPosition = BABYLON.Vector3.Zero();
  28913. this._tmpPositionWithDelta = BABYLON.Vector3.Zero();
  28914. this._tmpRotationWithDelta = new BABYLON.Quaternion();
  28915. /**
  28916. * this function is executed by the physics engine.
  28917. */
  28918. this.beforeStep = function () {
  28919. _this.object.position.subtractToRef(_this._deltaPosition, _this._tmpPositionWithDelta);
  28920. //conjugate deltaRotation
  28921. if (_this._deltaRotationConjugated) {
  28922. _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this._tmpRotationWithDelta);
  28923. }
  28924. else {
  28925. _this._tmpRotationWithDelta.copyFrom(_this.object.rotationQuaternion);
  28926. }
  28927. _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, _this._tmpPositionWithDelta, _this._tmpRotationWithDelta);
  28928. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  28929. func(_this);
  28930. });
  28931. };
  28932. /**
  28933. * this function is executed by the physics engine.
  28934. */
  28935. this.afterStep = function () {
  28936. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  28937. func(_this);
  28938. });
  28939. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  28940. _this.object.position.addInPlace(_this._deltaPosition);
  28941. if (_this._deltaRotation) {
  28942. _this.object.rotationQuaternion.multiplyInPlace(_this._deltaRotation);
  28943. }
  28944. };
  28945. //event and body object due to cannon's event-based architecture.
  28946. this.onCollide = function (e) {
  28947. if (!_this._onPhysicsCollideCallbacks.length)
  28948. return;
  28949. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  28950. if (otherImpostor) {
  28951. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  28952. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  28953. }).forEach(function (obj) {
  28954. obj.callback(_this, otherImpostor);
  28955. });
  28956. }
  28957. };
  28958. //sanity check!
  28959. if (!this.object) {
  28960. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  28961. return;
  28962. }
  28963. //legacy support for old syntax.
  28964. if (!this._scene && object.getScene) {
  28965. this._scene = object.getScene();
  28966. }
  28967. this._physicsEngine = this._scene.getPhysicsEngine();
  28968. if (!this._physicsEngine) {
  28969. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  28970. }
  28971. else {
  28972. //set the object's quaternion, if not set
  28973. if (!this.object.rotationQuaternion) {
  28974. if (this.object.rotation) {
  28975. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  28976. }
  28977. else {
  28978. this.object.rotationQuaternion = new BABYLON.Quaternion();
  28979. }
  28980. }
  28981. //default options params
  28982. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  28983. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  28984. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  28985. this._joints = [];
  28986. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  28987. if (!this.object.parent) {
  28988. this._init();
  28989. }
  28990. }
  28991. }
  28992. /**
  28993. * This function will completly initialize this impostor.
  28994. * It will create a new body - but only if this mesh has no parent.
  28995. * If it has, this impostor will not be used other than to define the impostor
  28996. * of the child mesh.
  28997. */
  28998. PhysicsImpostor.prototype._init = function () {
  28999. this._physicsEngine.removeImpostor(this);
  29000. this.physicsBody = null;
  29001. this._parent = this._parent || this._getPhysicsParent();
  29002. if (!this.parent) {
  29003. this._physicsEngine.addImpostor(this);
  29004. }
  29005. };
  29006. PhysicsImpostor.prototype._getPhysicsParent = function () {
  29007. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  29008. var parentMesh = this.object.parent;
  29009. return parentMesh.physicsImpostor;
  29010. }
  29011. return;
  29012. };
  29013. /**
  29014. * Should a new body be generated.
  29015. */
  29016. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  29017. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  29018. };
  29019. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  29020. this.forceUpdate();
  29021. };
  29022. /**
  29023. * Force a regeneration of this or the parent's impostor's body.
  29024. * Use under cautious - This will remove all joints already implemented.
  29025. */
  29026. PhysicsImpostor.prototype.forceUpdate = function () {
  29027. this._init();
  29028. if (this.parent) {
  29029. this.parent.forceUpdate();
  29030. }
  29031. };
  29032. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  29033. /*public get mesh(): AbstractMesh {
  29034. return this._mesh;
  29035. }*/
  29036. /**
  29037. * Gets the body that holds this impostor. Either its own, or its parent.
  29038. */
  29039. get: function () {
  29040. return this._parent ? this._parent.physicsBody : this._physicsBody;
  29041. },
  29042. /**
  29043. * Set the physics body. Used mainly by the physics engine/plugin
  29044. */
  29045. set: function (physicsBody) {
  29046. if (this._physicsBody) {
  29047. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  29048. }
  29049. this._physicsBody = physicsBody;
  29050. this.resetUpdateFlags();
  29051. },
  29052. enumerable: true,
  29053. configurable: true
  29054. });
  29055. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  29056. get: function () {
  29057. return this._parent;
  29058. },
  29059. enumerable: true,
  29060. configurable: true
  29061. });
  29062. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  29063. this._bodyUpdateRequired = false;
  29064. };
  29065. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  29066. if (this.object.getBoundingInfo) {
  29067. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  29068. return this.object.getBoundingInfo().boundingBox.extendSize.scale(2).multiply(this.object.scaling);
  29069. }
  29070. else {
  29071. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  29072. }
  29073. };
  29074. PhysicsImpostor.prototype.getObjectCenter = function () {
  29075. if (this.object.getBoundingInfo) {
  29076. return this.object.getBoundingInfo().boundingBox.center;
  29077. }
  29078. else {
  29079. return this.object.position;
  29080. }
  29081. };
  29082. /**
  29083. * Get a specific parametes from the options parameter.
  29084. */
  29085. PhysicsImpostor.prototype.getParam = function (paramName) {
  29086. return this._options[paramName];
  29087. };
  29088. /**
  29089. * Sets a specific parameter in the options given to the physics plugin
  29090. */
  29091. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  29092. this._options[paramName] = value;
  29093. this._bodyUpdateRequired = true;
  29094. };
  29095. /**
  29096. * Specifically change the body's mass option. Won't recreate the physics body object
  29097. */
  29098. PhysicsImpostor.prototype.setMass = function (mass) {
  29099. if (this.getParam("mass") !== mass) {
  29100. this.setParam("mass", mass);
  29101. }
  29102. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  29103. };
  29104. PhysicsImpostor.prototype.getLinearVelocity = function () {
  29105. return this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this);
  29106. };
  29107. /**
  29108. * Set the body's linear velocity.
  29109. */
  29110. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  29111. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  29112. };
  29113. PhysicsImpostor.prototype.getAngularVelocity = function () {
  29114. return this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this);
  29115. };
  29116. /**
  29117. * Set the body's linear velocity.
  29118. */
  29119. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  29120. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  29121. };
  29122. /**
  29123. * Execute a function with the physics plugin native code.
  29124. * Provide a function the will have two variables - the world object and the physics body object.
  29125. */
  29126. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  29127. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  29128. };
  29129. /**
  29130. * Register a function that will be executed before the physics world is stepping forward.
  29131. */
  29132. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  29133. this._onBeforePhysicsStepCallbacks.push(func);
  29134. };
  29135. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  29136. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  29137. if (index > -1) {
  29138. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  29139. }
  29140. else {
  29141. BABYLON.Tools.Warn("Function to remove was not found");
  29142. }
  29143. };
  29144. /**
  29145. * Register a function that will be executed after the physics step
  29146. */
  29147. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  29148. this._onAfterPhysicsStepCallbacks.push(func);
  29149. };
  29150. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  29151. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  29152. if (index > -1) {
  29153. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  29154. }
  29155. else {
  29156. BABYLON.Tools.Warn("Function to remove was not found");
  29157. }
  29158. };
  29159. /**
  29160. * register a function that will be executed when this impostor collides against a different body.
  29161. */
  29162. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  29163. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  29164. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  29165. };
  29166. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  29167. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  29168. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  29169. if (index > -1) {
  29170. this._onPhysicsCollideCallbacks.splice(index, 1);
  29171. }
  29172. else {
  29173. BABYLON.Tools.Warn("Function to remove was not found");
  29174. }
  29175. };
  29176. /**
  29177. * Apply a force
  29178. */
  29179. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  29180. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  29181. };
  29182. /**
  29183. * Apply an impulse
  29184. */
  29185. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  29186. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  29187. };
  29188. /**
  29189. * A help function to create a joint.
  29190. */
  29191. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  29192. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  29193. this.addJoint(otherImpostor, joint);
  29194. };
  29195. /**
  29196. * Add a joint to this impostor with a different impostor.
  29197. */
  29198. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  29199. this._joints.push({
  29200. otherImpostor: otherImpostor,
  29201. joint: joint
  29202. });
  29203. this._physicsEngine.addJoint(this, otherImpostor, joint);
  29204. };
  29205. /**
  29206. * Will keep this body still, in a sleep mode.
  29207. */
  29208. PhysicsImpostor.prototype.sleep = function () {
  29209. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  29210. };
  29211. /**
  29212. * Wake the body up.
  29213. */
  29214. PhysicsImpostor.prototype.wakeUp = function () {
  29215. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  29216. };
  29217. PhysicsImpostor.prototype.clone = function (newObject) {
  29218. if (!newObject)
  29219. return null;
  29220. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  29221. };
  29222. PhysicsImpostor.prototype.dispose = function () {
  29223. var _this = this;
  29224. //no dispose if no physics engine is available.
  29225. if (!this._physicsEngine) {
  29226. return;
  29227. }
  29228. this._joints.forEach(function (j) {
  29229. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  29230. });
  29231. //dispose the physics body
  29232. this._physicsEngine.removeImpostor(this);
  29233. if (this.parent) {
  29234. this.parent.forceUpdate();
  29235. }
  29236. else {
  29237. }
  29238. };
  29239. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  29240. this._deltaPosition.copyFrom(position);
  29241. };
  29242. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  29243. if (!this._deltaRotation) {
  29244. this._deltaRotation = new BABYLON.Quaternion();
  29245. }
  29246. this._deltaRotation.copyFrom(rotation);
  29247. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  29248. };
  29249. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  29250. //Impostor types
  29251. PhysicsImpostor.NoImpostor = 0;
  29252. PhysicsImpostor.SphereImpostor = 1;
  29253. PhysicsImpostor.BoxImpostor = 2;
  29254. PhysicsImpostor.PlaneImpostor = 3;
  29255. PhysicsImpostor.MeshImpostor = 4;
  29256. PhysicsImpostor.CylinderImpostor = 7;
  29257. PhysicsImpostor.ParticleImpostor = 8;
  29258. PhysicsImpostor.HeightmapImpostor = 9;
  29259. return PhysicsImpostor;
  29260. }());
  29261. BABYLON.PhysicsImpostor = PhysicsImpostor;
  29262. })(BABYLON || (BABYLON = {}));
  29263. var BABYLON;
  29264. (function (BABYLON) {
  29265. var PhysicsEngine = (function () {
  29266. function PhysicsEngine(gravity, _physicsPlugin) {
  29267. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  29268. this._physicsPlugin = _physicsPlugin;
  29269. //new methods and parameters
  29270. this._impostors = [];
  29271. this._joints = [];
  29272. if (!this._physicsPlugin.isSupported()) {
  29273. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  29274. + "Please make sure it is included.");
  29275. }
  29276. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  29277. this.setGravity(gravity);
  29278. this.setTimeStep();
  29279. }
  29280. PhysicsEngine.prototype.setGravity = function (gravity) {
  29281. this.gravity = gravity;
  29282. this._physicsPlugin.setGravity(this.gravity);
  29283. };
  29284. /**
  29285. * Set the time step of the physics engine.
  29286. * default is 1/60.
  29287. * To slow it down, enter 1/600 for example.
  29288. * To speed it up, 1/30
  29289. * @param {number} newTimeStep the new timestep to apply to this world.
  29290. */
  29291. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  29292. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  29293. this._physicsPlugin.setTimeStep(newTimeStep);
  29294. };
  29295. PhysicsEngine.prototype.dispose = function () {
  29296. this._impostors.forEach(function (impostor) {
  29297. impostor.dispose();
  29298. });
  29299. this._physicsPlugin.dispose();
  29300. };
  29301. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  29302. return this._physicsPlugin.name;
  29303. };
  29304. /**
  29305. * Adding a new impostor for the impostor tracking.
  29306. * This will be done by the impostor itself.
  29307. * @param {PhysicsImpostor} impostor the impostor to add
  29308. */
  29309. PhysicsEngine.prototype.addImpostor = function (impostor) {
  29310. impostor.uniqueId = this._impostors.push(impostor);
  29311. //if no parent, generate the body
  29312. if (!impostor.parent) {
  29313. this._physicsPlugin.generatePhysicsBody(impostor);
  29314. }
  29315. };
  29316. /**
  29317. * Remove an impostor from the engine.
  29318. * This impostor and its mesh will not longer be updated by the physics engine.
  29319. * @param {PhysicsImpostor} impostor the impostor to remove
  29320. */
  29321. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  29322. var index = this._impostors.indexOf(impostor);
  29323. if (index > -1) {
  29324. var removed = this._impostors.splice(index, 1);
  29325. //Is it needed?
  29326. if (removed.length) {
  29327. //this will also remove it from the world.
  29328. removed[0].physicsBody = null;
  29329. }
  29330. }
  29331. };
  29332. /**
  29333. * Add a joint to the physics engine
  29334. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  29335. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  29336. * @param {PhysicsJoint} the joint that will connect both impostors.
  29337. */
  29338. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  29339. var impostorJoint = {
  29340. mainImpostor: mainImpostor,
  29341. connectedImpostor: connectedImpostor,
  29342. joint: joint
  29343. };
  29344. joint.physicsPlugin = this._physicsPlugin;
  29345. this._joints.push(impostorJoint);
  29346. this._physicsPlugin.generateJoint(impostorJoint);
  29347. };
  29348. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  29349. var matchingJoints = this._joints.filter(function (impostorJoint) {
  29350. return (impostorJoint.connectedImpostor === connectedImpostor
  29351. && impostorJoint.joint === joint
  29352. && impostorJoint.mainImpostor === mainImpostor);
  29353. });
  29354. if (matchingJoints.length) {
  29355. this._physicsPlugin.removeJoint(matchingJoints[0]);
  29356. }
  29357. };
  29358. /**
  29359. * Called by the scene. no need to call it.
  29360. */
  29361. PhysicsEngine.prototype._step = function (delta) {
  29362. var _this = this;
  29363. //check if any mesh has no body / requires an update
  29364. this._impostors.forEach(function (impostor) {
  29365. if (impostor.isBodyInitRequired()) {
  29366. _this._physicsPlugin.generatePhysicsBody(impostor);
  29367. }
  29368. });
  29369. if (delta > 0.1) {
  29370. delta = 0.1;
  29371. }
  29372. else if (delta <= 0) {
  29373. delta = 1.0 / 60.0;
  29374. }
  29375. this._physicsPlugin.executeStep(delta, this._impostors);
  29376. };
  29377. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  29378. return this._physicsPlugin;
  29379. };
  29380. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  29381. for (var i = 0; i < this._impostors.length; ++i) {
  29382. if (this._impostors[i].object === object) {
  29383. return this._impostors[i];
  29384. }
  29385. }
  29386. };
  29387. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  29388. for (var i = 0; i < this._impostors.length; ++i) {
  29389. if (this._impostors[i].physicsBody === body) {
  29390. return this._impostors[i];
  29391. }
  29392. }
  29393. };
  29394. // Statics, Legacy support.
  29395. /**
  29396. * @Deprecated
  29397. *
  29398. */
  29399. PhysicsEngine.NoImpostor = BABYLON.PhysicsImpostor.NoImpostor;
  29400. PhysicsEngine.SphereImpostor = BABYLON.PhysicsImpostor.SphereImpostor;
  29401. PhysicsEngine.BoxImpostor = BABYLON.PhysicsImpostor.BoxImpostor;
  29402. PhysicsEngine.PlaneImpostor = BABYLON.PhysicsImpostor.PlaneImpostor;
  29403. PhysicsEngine.MeshImpostor = BABYLON.PhysicsImpostor.MeshImpostor;
  29404. PhysicsEngine.CylinderImpostor = BABYLON.PhysicsImpostor.CylinderImpostor;
  29405. PhysicsEngine.HeightmapImpostor = BABYLON.PhysicsImpostor.HeightmapImpostor;
  29406. PhysicsEngine.CapsuleImpostor = -1;
  29407. PhysicsEngine.ConeImpostor = -1;
  29408. PhysicsEngine.ConvexHullImpostor = -1;
  29409. PhysicsEngine.Epsilon = 0.001;
  29410. return PhysicsEngine;
  29411. }());
  29412. BABYLON.PhysicsEngine = PhysicsEngine;
  29413. })(BABYLON || (BABYLON = {}));
  29414. var BABYLON;
  29415. (function (BABYLON) {
  29416. var VertexData = (function () {
  29417. function VertexData() {
  29418. }
  29419. VertexData.prototype.set = function (data, kind) {
  29420. switch (kind) {
  29421. case BABYLON.VertexBuffer.PositionKind:
  29422. this.positions = data;
  29423. break;
  29424. case BABYLON.VertexBuffer.NormalKind:
  29425. this.normals = data;
  29426. break;
  29427. case BABYLON.VertexBuffer.UVKind:
  29428. this.uvs = data;
  29429. break;
  29430. case BABYLON.VertexBuffer.UV2Kind:
  29431. this.uvs2 = data;
  29432. break;
  29433. case BABYLON.VertexBuffer.UV3Kind:
  29434. this.uvs3 = data;
  29435. break;
  29436. case BABYLON.VertexBuffer.UV4Kind:
  29437. this.uvs4 = data;
  29438. break;
  29439. case BABYLON.VertexBuffer.UV5Kind:
  29440. this.uvs5 = data;
  29441. break;
  29442. case BABYLON.VertexBuffer.UV6Kind:
  29443. this.uvs6 = data;
  29444. break;
  29445. case BABYLON.VertexBuffer.ColorKind:
  29446. this.colors = data;
  29447. break;
  29448. case BABYLON.VertexBuffer.MatricesIndicesKind:
  29449. this.matricesIndices = data;
  29450. break;
  29451. case BABYLON.VertexBuffer.MatricesWeightsKind:
  29452. this.matricesWeights = data;
  29453. break;
  29454. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  29455. this.matricesIndicesExtra = data;
  29456. break;
  29457. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  29458. this.matricesWeightsExtra = data;
  29459. break;
  29460. }
  29461. };
  29462. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  29463. this._applyTo(mesh, updatable);
  29464. };
  29465. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  29466. this._applyTo(geometry, updatable);
  29467. };
  29468. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  29469. this._update(mesh);
  29470. };
  29471. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  29472. this._update(geometry);
  29473. };
  29474. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  29475. if (this.positions) {
  29476. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  29477. }
  29478. if (this.normals) {
  29479. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  29480. }
  29481. if (this.uvs) {
  29482. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  29483. }
  29484. if (this.uvs2) {
  29485. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  29486. }
  29487. if (this.uvs3) {
  29488. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  29489. }
  29490. if (this.uvs4) {
  29491. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  29492. }
  29493. if (this.uvs5) {
  29494. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  29495. }
  29496. if (this.uvs6) {
  29497. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  29498. }
  29499. if (this.colors) {
  29500. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  29501. }
  29502. if (this.matricesIndices) {
  29503. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  29504. }
  29505. if (this.matricesWeights) {
  29506. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  29507. }
  29508. if (this.matricesIndicesExtra) {
  29509. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  29510. }
  29511. if (this.matricesWeightsExtra) {
  29512. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  29513. }
  29514. if (this.indices) {
  29515. meshOrGeometry.setIndices(this.indices);
  29516. }
  29517. };
  29518. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  29519. if (this.positions) {
  29520. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  29521. }
  29522. if (this.normals) {
  29523. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  29524. }
  29525. if (this.uvs) {
  29526. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  29527. }
  29528. if (this.uvs2) {
  29529. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  29530. }
  29531. if (this.uvs3) {
  29532. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  29533. }
  29534. if (this.uvs4) {
  29535. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  29536. }
  29537. if (this.uvs5) {
  29538. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  29539. }
  29540. if (this.uvs6) {
  29541. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  29542. }
  29543. if (this.colors) {
  29544. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  29545. }
  29546. if (this.matricesIndices) {
  29547. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  29548. }
  29549. if (this.matricesWeights) {
  29550. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  29551. }
  29552. if (this.matricesIndicesExtra) {
  29553. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  29554. }
  29555. if (this.matricesWeightsExtra) {
  29556. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  29557. }
  29558. if (this.indices) {
  29559. meshOrGeometry.setIndices(this.indices);
  29560. }
  29561. };
  29562. VertexData.prototype.transform = function (matrix) {
  29563. var transformed = BABYLON.Vector3.Zero();
  29564. var index;
  29565. if (this.positions) {
  29566. var position = BABYLON.Vector3.Zero();
  29567. for (index = 0; index < this.positions.length; index += 3) {
  29568. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  29569. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  29570. this.positions[index] = transformed.x;
  29571. this.positions[index + 1] = transformed.y;
  29572. this.positions[index + 2] = transformed.z;
  29573. }
  29574. }
  29575. if (this.normals) {
  29576. var normal = BABYLON.Vector3.Zero();
  29577. for (index = 0; index < this.normals.length; index += 3) {
  29578. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  29579. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  29580. this.normals[index] = transformed.x;
  29581. this.normals[index + 1] = transformed.y;
  29582. this.normals[index + 2] = transformed.z;
  29583. }
  29584. }
  29585. };
  29586. VertexData.prototype.merge = function (other) {
  29587. if (other.indices) {
  29588. if (!this.indices) {
  29589. this.indices = [];
  29590. }
  29591. var offset = this.positions ? this.positions.length / 3 : 0;
  29592. for (var index = 0; index < other.indices.length; index++) {
  29593. //TODO check type - if Int32Array!
  29594. this.indices.push(other.indices[index] + offset);
  29595. }
  29596. }
  29597. this.positions = this._mergeElement(this.positions, other.positions);
  29598. this.normals = this._mergeElement(this.normals, other.normals);
  29599. this.uvs = this._mergeElement(this.uvs, other.uvs);
  29600. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  29601. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  29602. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  29603. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  29604. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  29605. this.colors = this._mergeElement(this.colors, other.colors);
  29606. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  29607. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  29608. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  29609. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  29610. };
  29611. VertexData.prototype._mergeElement = function (source, other) {
  29612. if (!other)
  29613. return source;
  29614. if (!source)
  29615. return other;
  29616. var len = other.length + source.length;
  29617. var isSrcTypedArray = source instanceof Float32Array;
  29618. var isOthTypedArray = other instanceof Float32Array;
  29619. // use non-loop method when the source is Float32Array
  29620. if (isSrcTypedArray) {
  29621. var ret32 = new Float32Array(len);
  29622. ret32.set(source);
  29623. ret32.set(other, source.length);
  29624. return ret32;
  29625. }
  29626. else if (!isOthTypedArray) {
  29627. return source.concat(other);
  29628. }
  29629. else {
  29630. var ret = source.slice(0); // copy source to a separate array
  29631. for (var i = 0, len = other.length; i < len; i++) {
  29632. ret.push(other[i]);
  29633. }
  29634. return ret;
  29635. }
  29636. };
  29637. VertexData.prototype.serialize = function () {
  29638. var serializationObject = this.serialize();
  29639. if (this.positions) {
  29640. serializationObject.positions = this.positions;
  29641. }
  29642. if (this.normals) {
  29643. serializationObject.normals = this.normals;
  29644. }
  29645. if (this.uvs) {
  29646. serializationObject.uvs = this.uvs;
  29647. }
  29648. if (this.uvs2) {
  29649. serializationObject.uvs2 = this.uvs2;
  29650. }
  29651. if (this.uvs3) {
  29652. serializationObject.uvs3 = this.uvs3;
  29653. }
  29654. if (this.uvs4) {
  29655. serializationObject.uvs4 = this.uvs4;
  29656. }
  29657. if (this.uvs5) {
  29658. serializationObject.uvs5 = this.uvs5;
  29659. }
  29660. if (this.uvs6) {
  29661. serializationObject.uvs6 = this.uvs6;
  29662. }
  29663. if (this.colors) {
  29664. serializationObject.colors = this.colors;
  29665. }
  29666. if (this.matricesIndices) {
  29667. serializationObject.matricesIndices = this.matricesIndices;
  29668. serializationObject.matricesIndices._isExpanded = true;
  29669. }
  29670. if (this.matricesWeights) {
  29671. serializationObject.matricesWeights = this.matricesWeights;
  29672. }
  29673. if (this.matricesIndicesExtra) {
  29674. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  29675. serializationObject.matricesIndicesExtra._isExpanded = true;
  29676. }
  29677. if (this.matricesWeightsExtra) {
  29678. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  29679. }
  29680. serializationObject.indices = this.indices;
  29681. return serializationObject;
  29682. };
  29683. // Statics
  29684. VertexData.ExtractFromMesh = function (mesh, copyWhenShared) {
  29685. return VertexData._ExtractFrom(mesh, copyWhenShared);
  29686. };
  29687. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared) {
  29688. return VertexData._ExtractFrom(geometry, copyWhenShared);
  29689. };
  29690. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared) {
  29691. var result = new VertexData();
  29692. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  29693. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared);
  29694. }
  29695. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  29696. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared);
  29697. }
  29698. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  29699. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared);
  29700. }
  29701. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  29702. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared);
  29703. }
  29704. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  29705. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared);
  29706. }
  29707. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  29708. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared);
  29709. }
  29710. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  29711. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared);
  29712. }
  29713. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  29714. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared);
  29715. }
  29716. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  29717. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared);
  29718. }
  29719. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  29720. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared);
  29721. }
  29722. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  29723. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared);
  29724. }
  29725. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  29726. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared);
  29727. }
  29728. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  29729. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared);
  29730. }
  29731. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  29732. return result;
  29733. };
  29734. VertexData.CreateRibbon = function (options) {
  29735. var pathArray = options.pathArray;
  29736. var closeArray = options.closeArray || false;
  29737. var closePath = options.closePath || false;
  29738. var invertUV = options.invertUV || false;
  29739. var defaultOffset = Math.floor(pathArray[0].length / 2);
  29740. var offset = options.offset || defaultOffset;
  29741. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  29742. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29743. var positions = [];
  29744. var indices = [];
  29745. var normals = [];
  29746. var uvs = [];
  29747. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  29748. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  29749. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  29750. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  29751. var minlg; // minimal length among all paths from pathArray
  29752. var lg = []; // array of path lengths : nb of vertex per path
  29753. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  29754. var p; // path iterator
  29755. var i; // point iterator
  29756. var j; // point iterator
  29757. // if single path in pathArray
  29758. if (pathArray.length < 2) {
  29759. var ar1 = [];
  29760. var ar2 = [];
  29761. for (i = 0; i < pathArray[0].length - offset; i++) {
  29762. ar1.push(pathArray[0][i]);
  29763. ar2.push(pathArray[0][i + offset]);
  29764. }
  29765. pathArray = [ar1, ar2];
  29766. }
  29767. // positions and horizontal distances (u)
  29768. var idc = 0;
  29769. var closePathCorr = (closePath) ? 1 : 0;
  29770. var path;
  29771. var l;
  29772. minlg = pathArray[0].length;
  29773. var vectlg;
  29774. var dist;
  29775. for (p = 0; p < pathArray.length; p++) {
  29776. uTotalDistance[p] = 0;
  29777. us[p] = [0];
  29778. path = pathArray[p];
  29779. l = path.length;
  29780. minlg = (minlg < l) ? minlg : l;
  29781. j = 0;
  29782. while (j < l) {
  29783. positions.push(path[j].x, path[j].y, path[j].z);
  29784. if (j > 0) {
  29785. vectlg = path[j].subtract(path[j - 1]).length();
  29786. dist = vectlg + uTotalDistance[p];
  29787. us[p].push(dist);
  29788. uTotalDistance[p] = dist;
  29789. }
  29790. j++;
  29791. }
  29792. if (closePath) {
  29793. j--;
  29794. positions.push(path[0].x, path[0].y, path[0].z);
  29795. vectlg = path[j].subtract(path[0]).length();
  29796. dist = vectlg + uTotalDistance[p];
  29797. us[p].push(dist);
  29798. uTotalDistance[p] = dist;
  29799. }
  29800. lg[p] = l + closePathCorr;
  29801. idx[p] = idc;
  29802. idc += (l + closePathCorr);
  29803. }
  29804. // vertical distances (v)
  29805. var path1;
  29806. var path2;
  29807. var vertex1;
  29808. var vertex2;
  29809. for (i = 0; i < minlg + closePathCorr; i++) {
  29810. vTotalDistance[i] = 0;
  29811. vs[i] = [0];
  29812. for (p = 0; p < pathArray.length - 1; p++) {
  29813. path1 = pathArray[p];
  29814. path2 = pathArray[p + 1];
  29815. if (i === minlg) {
  29816. vertex1 = path1[0];
  29817. vertex2 = path2[0];
  29818. }
  29819. else {
  29820. vertex1 = path1[i];
  29821. vertex2 = path2[i];
  29822. }
  29823. vectlg = vertex2.subtract(vertex1).length();
  29824. dist = vectlg + vTotalDistance[i];
  29825. vs[i].push(dist);
  29826. vTotalDistance[i] = dist;
  29827. }
  29828. if (closeArray) {
  29829. path1 = pathArray[p];
  29830. path2 = pathArray[0];
  29831. if (i === minlg) {
  29832. vertex2 = path2[0];
  29833. }
  29834. vectlg = vertex2.subtract(vertex1).length();
  29835. dist = vectlg + vTotalDistance[i];
  29836. vTotalDistance[i] = dist;
  29837. }
  29838. }
  29839. // uvs
  29840. var u;
  29841. var v;
  29842. for (p = 0; p < pathArray.length; p++) {
  29843. for (i = 0; i < minlg + closePathCorr; i++) {
  29844. u = us[p][i] / uTotalDistance[p];
  29845. v = vs[i][p] / vTotalDistance[i];
  29846. if (invertUV) {
  29847. uvs.push(v, u);
  29848. }
  29849. else {
  29850. uvs.push(u, v);
  29851. }
  29852. }
  29853. }
  29854. // indices
  29855. p = 0; // path index
  29856. var pi = 0; // positions array index
  29857. var l1 = lg[p] - 1; // path1 length
  29858. var l2 = lg[p + 1] - 1; // path2 length
  29859. var min = (l1 < l2) ? l1 : l2; // current path stop index
  29860. var shft = idx[1] - idx[0]; // shift
  29861. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  29862. while (pi <= min && p < path1nb) {
  29863. // 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
  29864. indices.push(pi, pi + shft, pi + 1);
  29865. indices.push(pi + shft + 1, pi + 1, pi + shft);
  29866. pi += 1;
  29867. if (pi === min) {
  29868. p++;
  29869. if (p === lg.length - 1) {
  29870. shft = idx[0] - idx[p];
  29871. l1 = lg[p] - 1;
  29872. l2 = lg[0] - 1;
  29873. }
  29874. else {
  29875. shft = idx[p + 1] - idx[p];
  29876. l1 = lg[p] - 1;
  29877. l2 = lg[p + 1] - 1;
  29878. }
  29879. pi = idx[p];
  29880. min = (l1 < l2) ? l1 + pi : l2 + pi;
  29881. }
  29882. }
  29883. // normals
  29884. VertexData.ComputeNormals(positions, indices, normals);
  29885. if (closePath) {
  29886. var indexFirst = 0;
  29887. var indexLast = 0;
  29888. for (p = 0; p < pathArray.length; p++) {
  29889. indexFirst = idx[p] * 3;
  29890. if (p + 1 < pathArray.length) {
  29891. indexLast = (idx[p + 1] - 1) * 3;
  29892. }
  29893. else {
  29894. indexLast = normals.length - 3;
  29895. }
  29896. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  29897. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  29898. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  29899. normals[indexLast] = normals[indexFirst];
  29900. normals[indexLast + 1] = normals[indexFirst + 1];
  29901. normals[indexLast + 2] = normals[indexFirst + 2];
  29902. }
  29903. }
  29904. // sides
  29905. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  29906. // Result
  29907. var vertexData = new VertexData();
  29908. vertexData.indices = indices;
  29909. vertexData.positions = positions;
  29910. vertexData.normals = normals;
  29911. vertexData.uvs = uvs;
  29912. if (closePath) {
  29913. vertexData._idx = idx;
  29914. }
  29915. return vertexData;
  29916. };
  29917. VertexData.CreateBox = function (options) {
  29918. var normalsSource = [
  29919. new BABYLON.Vector3(0, 0, 1),
  29920. new BABYLON.Vector3(0, 0, -1),
  29921. new BABYLON.Vector3(1, 0, 0),
  29922. new BABYLON.Vector3(-1, 0, 0),
  29923. new BABYLON.Vector3(0, 1, 0),
  29924. new BABYLON.Vector3(0, -1, 0)
  29925. ];
  29926. var indices = [];
  29927. var positions = [];
  29928. var normals = [];
  29929. var uvs = [];
  29930. var width = options.width || options.size || 1;
  29931. var height = options.height || options.size || 1;
  29932. var depth = options.depth || options.size || 1;
  29933. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29934. var faceUV = options.faceUV || new Array(6);
  29935. var faceColors = options.faceColors;
  29936. var colors = [];
  29937. // default face colors and UV if undefined
  29938. for (var f = 0; f < 6; f++) {
  29939. if (faceUV[f] === undefined) {
  29940. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  29941. }
  29942. if (faceColors && faceColors[f] === undefined) {
  29943. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  29944. }
  29945. }
  29946. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  29947. // Create each face in turn.
  29948. for (var index = 0; index < normalsSource.length; index++) {
  29949. var normal = normalsSource[index];
  29950. // Get two vectors perpendicular to the face normal and to each other.
  29951. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  29952. var side2 = BABYLON.Vector3.Cross(normal, side1);
  29953. // Six indices (two triangles) per face.
  29954. var verticesLength = positions.length / 3;
  29955. indices.push(verticesLength);
  29956. indices.push(verticesLength + 1);
  29957. indices.push(verticesLength + 2);
  29958. indices.push(verticesLength);
  29959. indices.push(verticesLength + 2);
  29960. indices.push(verticesLength + 3);
  29961. // Four vertices per face.
  29962. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  29963. positions.push(vertex.x, vertex.y, vertex.z);
  29964. normals.push(normal.x, normal.y, normal.z);
  29965. uvs.push(faceUV[index].z, faceUV[index].w);
  29966. if (faceColors) {
  29967. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  29968. }
  29969. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  29970. positions.push(vertex.x, vertex.y, vertex.z);
  29971. normals.push(normal.x, normal.y, normal.z);
  29972. uvs.push(faceUV[index].x, faceUV[index].w);
  29973. if (faceColors) {
  29974. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  29975. }
  29976. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  29977. positions.push(vertex.x, vertex.y, vertex.z);
  29978. normals.push(normal.x, normal.y, normal.z);
  29979. uvs.push(faceUV[index].x, faceUV[index].y);
  29980. if (faceColors) {
  29981. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  29982. }
  29983. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  29984. positions.push(vertex.x, vertex.y, vertex.z);
  29985. normals.push(normal.x, normal.y, normal.z);
  29986. uvs.push(faceUV[index].z, faceUV[index].y);
  29987. if (faceColors) {
  29988. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  29989. }
  29990. }
  29991. // sides
  29992. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  29993. // Result
  29994. var vertexData = new VertexData();
  29995. vertexData.indices = indices;
  29996. vertexData.positions = positions;
  29997. vertexData.normals = normals;
  29998. vertexData.uvs = uvs;
  29999. if (faceColors) {
  30000. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  30001. vertexData.colors = totalColors;
  30002. }
  30003. return vertexData;
  30004. };
  30005. VertexData.CreateSphere = function (options) {
  30006. var segments = options.segments || 32;
  30007. var diameterX = options.diameterX || options.diameter || 1;
  30008. var diameterY = options.diameterY || options.diameter || 1;
  30009. var diameterZ = options.diameterZ || options.diameter || 1;
  30010. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  30011. var slice = (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  30012. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30013. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  30014. var totalZRotationSteps = 2 + segments;
  30015. var totalYRotationSteps = 2 * totalZRotationSteps;
  30016. var indices = [];
  30017. var positions = [];
  30018. var normals = [];
  30019. var uvs = [];
  30020. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  30021. var normalizedZ = zRotationStep / totalZRotationSteps;
  30022. var angleZ = normalizedZ * Math.PI * slice;
  30023. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  30024. var normalizedY = yRotationStep / totalYRotationSteps;
  30025. var angleY = normalizedY * Math.PI * 2 * arc;
  30026. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  30027. var rotationY = BABYLON.Matrix.RotationY(angleY);
  30028. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  30029. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  30030. var vertex = complete.multiply(radius);
  30031. var normal = complete.divide(radius).normalize();
  30032. positions.push(vertex.x, vertex.y, vertex.z);
  30033. normals.push(normal.x, normal.y, normal.z);
  30034. uvs.push(normalizedY, normalizedZ);
  30035. }
  30036. if (zRotationStep > 0) {
  30037. var verticesCount = positions.length / 3;
  30038. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  30039. indices.push((firstIndex));
  30040. indices.push((firstIndex + 1));
  30041. indices.push(firstIndex + totalYRotationSteps + 1);
  30042. indices.push((firstIndex + totalYRotationSteps + 1));
  30043. indices.push((firstIndex + 1));
  30044. indices.push((firstIndex + totalYRotationSteps + 2));
  30045. }
  30046. }
  30047. }
  30048. // Sides
  30049. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  30050. // Result
  30051. var vertexData = new VertexData();
  30052. vertexData.indices = indices;
  30053. vertexData.positions = positions;
  30054. vertexData.normals = normals;
  30055. vertexData.uvs = uvs;
  30056. return vertexData;
  30057. };
  30058. // Cylinder and cone
  30059. VertexData.CreateCylinder = function (options) {
  30060. var height = options.height || 2;
  30061. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  30062. var diameterBottom = options.diameterBottom || options.diameter || 1;
  30063. var tessellation = options.tessellation || 24;
  30064. var subdivisions = options.subdivisions || 1;
  30065. var hasRings = options.hasRings;
  30066. var enclose = options.enclose;
  30067. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  30068. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30069. var faceUV = options.faceUV || new Array(3);
  30070. var faceColors = options.faceColors;
  30071. // default face colors and UV if undefined
  30072. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  30073. var ringNb = (hasRings) ? subdivisions : 1;
  30074. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  30075. var f;
  30076. for (f = 0; f < surfaceNb; f++) {
  30077. if (faceColors && faceColors[f] === undefined) {
  30078. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  30079. }
  30080. }
  30081. for (f = 0; f < surfaceNb; f++) {
  30082. if (faceUV && faceUV[f] === undefined) {
  30083. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  30084. }
  30085. }
  30086. var indices = [];
  30087. var positions = [];
  30088. var normals = [];
  30089. var uvs = [];
  30090. var colors = [];
  30091. var angle_step = Math.PI * 2 * arc / tessellation;
  30092. var angle;
  30093. var h;
  30094. var radius;
  30095. var tan = (diameterBottom - diameterTop) / 2 / height;
  30096. var ringVertex = BABYLON.Vector3.Zero();
  30097. var ringNormal = BABYLON.Vector3.Zero();
  30098. var ringFirstVertex = BABYLON.Vector3.Zero();
  30099. var ringFirstNormal = BABYLON.Vector3.Zero();
  30100. var quadNormal = BABYLON.Vector3.Zero();
  30101. var Y = BABYLON.Axis.Y;
  30102. // positions, normals, uvs
  30103. var i;
  30104. var j;
  30105. var r;
  30106. var ringIdx = 1;
  30107. var s = 1; // surface index
  30108. var cs = 0;
  30109. var v = 0;
  30110. for (i = 0; i <= subdivisions; i++) {
  30111. h = i / subdivisions;
  30112. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  30113. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  30114. for (r = 0; r < ringIdx; r++) {
  30115. if (hasRings) {
  30116. s += r;
  30117. }
  30118. if (enclose) {
  30119. s += 2 * r;
  30120. }
  30121. for (j = 0; j <= tessellation; j++) {
  30122. angle = j * angle_step;
  30123. // position
  30124. ringVertex.x = Math.cos(-angle) * radius;
  30125. ringVertex.y = -height / 2 + h * height;
  30126. ringVertex.z = Math.sin(-angle) * radius;
  30127. // normal
  30128. if (diameterTop === 0 && i === subdivisions) {
  30129. // if no top cap, reuse former normals
  30130. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  30131. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  30132. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  30133. }
  30134. else {
  30135. ringNormal.x = ringVertex.x;
  30136. ringNormal.z = ringVertex.z;
  30137. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  30138. ringNormal.normalize();
  30139. }
  30140. // keep first ring vertex values for enclose
  30141. if (j === 0) {
  30142. ringFirstVertex.copyFrom(ringVertex);
  30143. ringFirstNormal.copyFrom(ringNormal);
  30144. }
  30145. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  30146. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  30147. if (hasRings) {
  30148. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  30149. }
  30150. else {
  30151. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  30152. }
  30153. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  30154. if (faceColors) {
  30155. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  30156. }
  30157. }
  30158. // if enclose, add four vertices and their dedicated normals
  30159. if (arc !== 1 && enclose) {
  30160. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  30161. positions.push(0, ringVertex.y, 0);
  30162. positions.push(0, ringVertex.y, 0);
  30163. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  30164. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  30165. quadNormal.normalize();
  30166. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  30167. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  30168. quadNormal.normalize();
  30169. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  30170. if (hasRings) {
  30171. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  30172. }
  30173. else {
  30174. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  30175. }
  30176. uvs.push(faceUV[s + 1].x, v);
  30177. uvs.push(faceUV[s + 1].z, v);
  30178. if (hasRings) {
  30179. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  30180. }
  30181. else {
  30182. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  30183. }
  30184. uvs.push(faceUV[s + 2].x, v);
  30185. uvs.push(faceUV[s + 2].z, v);
  30186. if (faceColors) {
  30187. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  30188. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  30189. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  30190. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  30191. }
  30192. }
  30193. if (cs !== s) {
  30194. cs = s;
  30195. }
  30196. }
  30197. }
  30198. // indices
  30199. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  30200. var s;
  30201. i = 0;
  30202. for (s = 0; s < subdivisions; s++) {
  30203. for (j = 0; j < tessellation; j++) {
  30204. var i0 = i * (e + 1) + j;
  30205. var i1 = (i + 1) * (e + 1) + j;
  30206. var i2 = i * (e + 1) + (j + 1);
  30207. var i3 = (i + 1) * (e + 1) + (j + 1);
  30208. indices.push(i0, i1, i2);
  30209. indices.push(i3, i2, i1);
  30210. }
  30211. if (arc !== 1 && enclose) {
  30212. indices.push(i0 + 2, i1 + 2, i2 + 2);
  30213. indices.push(i3 + 2, i2 + 2, i1 + 2);
  30214. indices.push(i0 + 4, i1 + 4, i2 + 4);
  30215. indices.push(i3 + 4, i2 + 4, i1 + 4);
  30216. }
  30217. i = (hasRings) ? (i + 2) : (i + 1);
  30218. }
  30219. // Caps
  30220. var createCylinderCap = function (isTop) {
  30221. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  30222. if (radius === 0) {
  30223. return;
  30224. }
  30225. // Cap positions, normals & uvs
  30226. var angle;
  30227. var circleVector;
  30228. var i;
  30229. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  30230. var c;
  30231. if (faceColors) {
  30232. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  30233. }
  30234. // cap center
  30235. var vbase = positions.length / 3;
  30236. var offset = isTop ? height / 2 : -height / 2;
  30237. var center = new BABYLON.Vector3(0, offset, 0);
  30238. positions.push(center.x, center.y, center.z);
  30239. normals.push(0, isTop ? 1 : -1, 0);
  30240. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  30241. if (faceColors) {
  30242. colors.push(c.r, c.g, c.b, c.a);
  30243. }
  30244. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  30245. for (i = 0; i <= tessellation; i++) {
  30246. angle = Math.PI * 2 * i * arc / tessellation;
  30247. var cos = Math.cos(-angle);
  30248. var sin = Math.sin(-angle);
  30249. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  30250. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  30251. positions.push(circleVector.x, circleVector.y, circleVector.z);
  30252. normals.push(0, isTop ? 1 : -1, 0);
  30253. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  30254. if (faceColors) {
  30255. colors.push(c.r, c.g, c.b, c.a);
  30256. }
  30257. }
  30258. // Cap indices
  30259. for (i = 0; i < tessellation; i++) {
  30260. if (!isTop) {
  30261. indices.push(vbase);
  30262. indices.push(vbase + (i + 1));
  30263. indices.push(vbase + (i + 2));
  30264. }
  30265. else {
  30266. indices.push(vbase);
  30267. indices.push(vbase + (i + 2));
  30268. indices.push(vbase + (i + 1));
  30269. }
  30270. }
  30271. };
  30272. // add caps to geometry
  30273. createCylinderCap(false);
  30274. createCylinderCap(true);
  30275. // Sides
  30276. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  30277. var vertexData = new VertexData();
  30278. vertexData.indices = indices;
  30279. vertexData.positions = positions;
  30280. vertexData.normals = normals;
  30281. vertexData.uvs = uvs;
  30282. if (faceColors) {
  30283. vertexData.colors = colors;
  30284. }
  30285. return vertexData;
  30286. };
  30287. VertexData.CreateTorus = function (options) {
  30288. var indices = [];
  30289. var positions = [];
  30290. var normals = [];
  30291. var uvs = [];
  30292. var diameter = options.diameter || 1;
  30293. var thickness = options.thickness || 0.5;
  30294. var tessellation = options.tessellation || 16;
  30295. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30296. var stride = tessellation + 1;
  30297. for (var i = 0; i <= tessellation; i++) {
  30298. var u = i / tessellation;
  30299. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  30300. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  30301. for (var j = 0; j <= tessellation; j++) {
  30302. var v = 1 - j / tessellation;
  30303. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  30304. var dx = Math.cos(innerAngle);
  30305. var dy = Math.sin(innerAngle);
  30306. // Create a vertex.
  30307. var normal = new BABYLON.Vector3(dx, dy, 0);
  30308. var position = normal.scale(thickness / 2);
  30309. var textureCoordinate = new BABYLON.Vector2(u, v);
  30310. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  30311. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  30312. positions.push(position.x, position.y, position.z);
  30313. normals.push(normal.x, normal.y, normal.z);
  30314. uvs.push(textureCoordinate.x, textureCoordinate.y);
  30315. // And create indices for two triangles.
  30316. var nextI = (i + 1) % stride;
  30317. var nextJ = (j + 1) % stride;
  30318. indices.push(i * stride + j);
  30319. indices.push(i * stride + nextJ);
  30320. indices.push(nextI * stride + j);
  30321. indices.push(i * stride + nextJ);
  30322. indices.push(nextI * stride + nextJ);
  30323. indices.push(nextI * stride + j);
  30324. }
  30325. }
  30326. // Sides
  30327. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  30328. // Result
  30329. var vertexData = new VertexData();
  30330. vertexData.indices = indices;
  30331. vertexData.positions = positions;
  30332. vertexData.normals = normals;
  30333. vertexData.uvs = uvs;
  30334. return vertexData;
  30335. };
  30336. VertexData.CreateLineSystem = function (options) {
  30337. var indices = [];
  30338. var positions = [];
  30339. var lines = options.lines;
  30340. var idx = 0;
  30341. for (var l = 0; l < lines.length; l++) {
  30342. var points = lines[l];
  30343. for (var index = 0; index < points.length; index++) {
  30344. positions.push(points[index].x, points[index].y, points[index].z);
  30345. if (index > 0) {
  30346. indices.push(idx - 1);
  30347. indices.push(idx);
  30348. }
  30349. idx++;
  30350. }
  30351. }
  30352. var vertexData = new VertexData();
  30353. vertexData.indices = indices;
  30354. vertexData.positions = positions;
  30355. return vertexData;
  30356. };
  30357. VertexData.CreateDashedLines = function (options) {
  30358. var dashSize = options.dashSize || 3;
  30359. var gapSize = options.gapSize || 1;
  30360. var dashNb = options.dashNb || 200;
  30361. var points = options.points;
  30362. var positions = new Array();
  30363. var indices = new Array();
  30364. var curvect = BABYLON.Vector3.Zero();
  30365. var lg = 0;
  30366. var nb = 0;
  30367. var shft = 0;
  30368. var dashshft = 0;
  30369. var curshft = 0;
  30370. var idx = 0;
  30371. var i = 0;
  30372. for (i = 0; i < points.length - 1; i++) {
  30373. points[i + 1].subtractToRef(points[i], curvect);
  30374. lg += curvect.length();
  30375. }
  30376. shft = lg / dashNb;
  30377. dashshft = dashSize * shft / (dashSize + gapSize);
  30378. for (i = 0; i < points.length - 1; i++) {
  30379. points[i + 1].subtractToRef(points[i], curvect);
  30380. nb = Math.floor(curvect.length() / shft);
  30381. curvect.normalize();
  30382. for (var j = 0; j < nb; j++) {
  30383. curshft = shft * j;
  30384. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  30385. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  30386. indices.push(idx, idx + 1);
  30387. idx += 2;
  30388. }
  30389. }
  30390. // Result
  30391. var vertexData = new VertexData();
  30392. vertexData.positions = positions;
  30393. vertexData.indices = indices;
  30394. return vertexData;
  30395. };
  30396. VertexData.CreateGround = function (options) {
  30397. var indices = [];
  30398. var positions = [];
  30399. var normals = [];
  30400. var uvs = [];
  30401. var row, col;
  30402. var width = options.width || 1;
  30403. var height = options.height || 1;
  30404. var subdivisions = options.subdivisions || 1;
  30405. for (row = 0; row <= subdivisions; row++) {
  30406. for (col = 0; col <= subdivisions; col++) {
  30407. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  30408. var normal = new BABYLON.Vector3(0, 1.0, 0);
  30409. positions.push(position.x, position.y, position.z);
  30410. normals.push(normal.x, normal.y, normal.z);
  30411. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  30412. }
  30413. }
  30414. for (row = 0; row < subdivisions; row++) {
  30415. for (col = 0; col < subdivisions; col++) {
  30416. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  30417. indices.push(col + 1 + row * (subdivisions + 1));
  30418. indices.push(col + row * (subdivisions + 1));
  30419. indices.push(col + (row + 1) * (subdivisions + 1));
  30420. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  30421. indices.push(col + row * (subdivisions + 1));
  30422. }
  30423. }
  30424. // Result
  30425. var vertexData = new VertexData();
  30426. vertexData.indices = indices;
  30427. vertexData.positions = positions;
  30428. vertexData.normals = normals;
  30429. vertexData.uvs = uvs;
  30430. return vertexData;
  30431. };
  30432. VertexData.CreateTiledGround = function (options) {
  30433. var xmin = options.xmin || -1.0;
  30434. var zmin = options.zmin || -1.0;
  30435. var xmax = options.xmax || 1.0;
  30436. var zmax = options.zmax || 1.0;
  30437. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  30438. var precision = options.precision || { w: 1, h: 1 };
  30439. var indices = [];
  30440. var positions = [];
  30441. var normals = [];
  30442. var uvs = [];
  30443. var row, col, tileRow, tileCol;
  30444. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  30445. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  30446. precision.w = (precision.w < 1) ? 1 : precision.w;
  30447. precision.h = (precision.h < 1) ? 1 : precision.h;
  30448. var tileSize = {
  30449. 'w': (xmax - xmin) / subdivisions.w,
  30450. 'h': (zmax - zmin) / subdivisions.h
  30451. };
  30452. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  30453. // Indices
  30454. var base = positions.length / 3;
  30455. var rowLength = precision.w + 1;
  30456. for (row = 0; row < precision.h; row++) {
  30457. for (col = 0; col < precision.w; col++) {
  30458. var square = [
  30459. base + col + row * rowLength,
  30460. base + (col + 1) + row * rowLength,
  30461. base + (col + 1) + (row + 1) * rowLength,
  30462. base + col + (row + 1) * rowLength
  30463. ];
  30464. indices.push(square[1]);
  30465. indices.push(square[2]);
  30466. indices.push(square[3]);
  30467. indices.push(square[0]);
  30468. indices.push(square[1]);
  30469. indices.push(square[3]);
  30470. }
  30471. }
  30472. // Position, normals and uvs
  30473. var position = BABYLON.Vector3.Zero();
  30474. var normal = new BABYLON.Vector3(0, 1.0, 0);
  30475. for (row = 0; row <= precision.h; row++) {
  30476. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  30477. for (col = 0; col <= precision.w; col++) {
  30478. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  30479. position.y = 0;
  30480. positions.push(position.x, position.y, position.z);
  30481. normals.push(normal.x, normal.y, normal.z);
  30482. uvs.push(col / precision.w, row / precision.h);
  30483. }
  30484. }
  30485. }
  30486. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  30487. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  30488. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  30489. }
  30490. }
  30491. // Result
  30492. var vertexData = new VertexData();
  30493. vertexData.indices = indices;
  30494. vertexData.positions = positions;
  30495. vertexData.normals = normals;
  30496. vertexData.uvs = uvs;
  30497. return vertexData;
  30498. };
  30499. VertexData.CreateGroundFromHeightMap = function (options) {
  30500. var indices = [];
  30501. var positions = [];
  30502. var normals = [];
  30503. var uvs = [];
  30504. var row, col;
  30505. // Vertices
  30506. for (row = 0; row <= options.subdivisions; row++) {
  30507. for (col = 0; col <= options.subdivisions; col++) {
  30508. 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));
  30509. // Compute height
  30510. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  30511. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  30512. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  30513. var r = options.buffer[pos] / 255.0;
  30514. var g = options.buffer[pos + 1] / 255.0;
  30515. var b = options.buffer[pos + 2] / 255.0;
  30516. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  30517. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  30518. // Add vertex
  30519. positions.push(position.x, position.y, position.z);
  30520. normals.push(0, 0, 0);
  30521. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  30522. }
  30523. }
  30524. // Indices
  30525. for (row = 0; row < options.subdivisions; row++) {
  30526. for (col = 0; col < options.subdivisions; col++) {
  30527. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  30528. indices.push(col + 1 + row * (options.subdivisions + 1));
  30529. indices.push(col + row * (options.subdivisions + 1));
  30530. indices.push(col + (row + 1) * (options.subdivisions + 1));
  30531. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  30532. indices.push(col + row * (options.subdivisions + 1));
  30533. }
  30534. }
  30535. // Normals
  30536. VertexData.ComputeNormals(positions, indices, normals);
  30537. // Result
  30538. var vertexData = new VertexData();
  30539. vertexData.indices = indices;
  30540. vertexData.positions = positions;
  30541. vertexData.normals = normals;
  30542. vertexData.uvs = uvs;
  30543. return vertexData;
  30544. };
  30545. VertexData.CreatePlane = function (options) {
  30546. var indices = [];
  30547. var positions = [];
  30548. var normals = [];
  30549. var uvs = [];
  30550. var width = options.width || options.size || 1;
  30551. var height = options.height || options.size || 1;
  30552. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30553. // Vertices
  30554. var halfWidth = width / 2.0;
  30555. var halfHeight = height / 2.0;
  30556. positions.push(-halfWidth, -halfHeight, 0);
  30557. normals.push(0, 0, -1.0);
  30558. uvs.push(0.0, 0.0);
  30559. positions.push(halfWidth, -halfHeight, 0);
  30560. normals.push(0, 0, -1.0);
  30561. uvs.push(1.0, 0.0);
  30562. positions.push(halfWidth, halfHeight, 0);
  30563. normals.push(0, 0, -1.0);
  30564. uvs.push(1.0, 1.0);
  30565. positions.push(-halfWidth, halfHeight, 0);
  30566. normals.push(0, 0, -1.0);
  30567. uvs.push(0.0, 1.0);
  30568. // Indices
  30569. indices.push(0);
  30570. indices.push(1);
  30571. indices.push(2);
  30572. indices.push(0);
  30573. indices.push(2);
  30574. indices.push(3);
  30575. // Sides
  30576. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  30577. // Result
  30578. var vertexData = new VertexData();
  30579. vertexData.indices = indices;
  30580. vertexData.positions = positions;
  30581. vertexData.normals = normals;
  30582. vertexData.uvs = uvs;
  30583. return vertexData;
  30584. };
  30585. VertexData.CreateDisc = function (options) {
  30586. var positions = [];
  30587. var indices = [];
  30588. var normals = [];
  30589. var uvs = [];
  30590. var radius = options.radius || 0.5;
  30591. var tessellation = options.tessellation || 64;
  30592. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  30593. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30594. // positions and uvs
  30595. positions.push(0, 0, 0); // disc center first
  30596. uvs.push(0.5, 0.5);
  30597. var theta = Math.PI * 2 * arc;
  30598. var step = theta / tessellation;
  30599. for (var a = 0; a < theta; a += step) {
  30600. var x = Math.cos(a);
  30601. var y = Math.sin(a);
  30602. var u = (x + 1) / 2;
  30603. var v = (1 - y) / 2;
  30604. positions.push(radius * x, radius * y, 0);
  30605. uvs.push(u, v);
  30606. }
  30607. if (arc === 1) {
  30608. positions.push(positions[3], positions[4], positions[5]); // close the circle
  30609. uvs.push(uvs[2], uvs[3]);
  30610. }
  30611. //indices
  30612. var vertexNb = positions.length / 3;
  30613. for (var i = 1; i < vertexNb - 1; i++) {
  30614. indices.push(i + 1, 0, i);
  30615. }
  30616. // result
  30617. VertexData.ComputeNormals(positions, indices, normals);
  30618. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  30619. var vertexData = new VertexData();
  30620. vertexData.indices = indices;
  30621. vertexData.positions = positions;
  30622. vertexData.normals = normals;
  30623. vertexData.uvs = uvs;
  30624. return vertexData;
  30625. };
  30626. VertexData.CreateIcoSphere = function (options) {
  30627. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30628. var radius = options.radius || 1;
  30629. var flat = (options.flat === undefined) ? true : options.flat;
  30630. var subdivisions = options.subdivisions || 4;
  30631. var radiusX = options.radiusX || radius;
  30632. var radiusY = options.radiusY || radius;
  30633. var radiusZ = options.radiusZ || radius;
  30634. var t = (1 + Math.sqrt(5)) / 2;
  30635. // 12 vertex x,y,z
  30636. var ico_vertices = [
  30637. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  30638. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  30639. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  30640. ];
  30641. // index of 3 vertex makes a face of icopshere
  30642. var ico_indices = [
  30643. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  30644. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  30645. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  30646. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  30647. ];
  30648. // vertex for uv have aliased position, not for UV
  30649. var vertices_unalias_id = [
  30650. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  30651. // vertex alias
  30652. 0,
  30653. 2,
  30654. 3,
  30655. 3,
  30656. 3,
  30657. 4,
  30658. 7,
  30659. 8,
  30660. 9,
  30661. 9,
  30662. 10,
  30663. 11 // 23: B + 12
  30664. ];
  30665. // uv as integer step (not pixels !)
  30666. var ico_vertexuv = [
  30667. 5, 1, 3, 1, 6, 4, 0, 0,
  30668. 5, 3, 4, 2, 2, 2, 4, 0,
  30669. 2, 0, 1, 1, 6, 0, 6, 2,
  30670. // vertex alias (for same vertex on different faces)
  30671. 0, 4,
  30672. 3, 3,
  30673. 4, 4,
  30674. 3, 1,
  30675. 4, 2,
  30676. 4, 4,
  30677. 0, 2,
  30678. 1, 1,
  30679. 2, 2,
  30680. 3, 3,
  30681. 1, 3,
  30682. 2, 4 // 23: B + 12
  30683. ];
  30684. // Vertices[0, 1, ...9, A, B] : position on UV plane
  30685. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  30686. // First island of uv mapping
  30687. // v = 4h 3+ 2
  30688. // v = 3h 9+ 4
  30689. // v = 2h 9+ 5 B
  30690. // v = 1h 9 1 0
  30691. // v = 0h 3 8 7 A
  30692. // u = 0 1 2 3 4 5 6 *a
  30693. // Second island of uv mapping
  30694. // v = 4h 0+ B+ 4+
  30695. // v = 3h A+ 2+
  30696. // v = 2h 7+ 6 3+
  30697. // v = 1h 8+ 3+
  30698. // v = 0h
  30699. // u = 0 1 2 3 4 5 6 *a
  30700. // Face layout on texture UV mapping
  30701. // ============
  30702. // \ 4 /\ 16 / ======
  30703. // \ / \ / /\ 11 /
  30704. // \/ 7 \/ / \ /
  30705. // ======= / 10 \/
  30706. // /\ 17 /\ =======
  30707. // / \ / \ \ 15 /\
  30708. // / 8 \/ 12 \ \ / \
  30709. // ============ \/ 6 \
  30710. // \ 18 /\ ============
  30711. // \ / \ \ 5 /\ 0 /
  30712. // \/ 13 \ \ / \ /
  30713. // ======= \/ 1 \/
  30714. // =============
  30715. // /\ 19 /\ 2 /\
  30716. // / \ / \ / \
  30717. // / 14 \/ 9 \/ 3 \
  30718. // ===================
  30719. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  30720. var ustep = 138 / 1024;
  30721. var vstep = 239 / 1024;
  30722. var uoffset = 60 / 1024;
  30723. var voffset = 26 / 1024;
  30724. // Second island should have margin, not to touch the first island
  30725. // avoid any borderline artefact in pixel rounding
  30726. var island_u_offset = -40 / 1024;
  30727. var island_v_offset = +20 / 1024;
  30728. // face is either island 0 or 1 :
  30729. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  30730. var island = [
  30731. 0, 0, 0, 0, 1,
  30732. 0, 0, 1, 1, 0,
  30733. 0, 0, 1, 1, 0,
  30734. 0, 1, 1, 1, 0 // 15 - 19
  30735. ];
  30736. var indices = [];
  30737. var positions = [];
  30738. var normals = [];
  30739. var uvs = [];
  30740. var current_indice = 0;
  30741. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  30742. var face_vertex_pos = new Array(3);
  30743. var face_vertex_uv = new Array(3);
  30744. var v012;
  30745. for (v012 = 0; v012 < 3; v012++) {
  30746. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  30747. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  30748. }
  30749. // create all with normals
  30750. for (var face = 0; face < 20; face++) {
  30751. // 3 vertex per face
  30752. for (v012 = 0; v012 < 3; v012++) {
  30753. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  30754. var v_id = ico_indices[3 * face + v012];
  30755. // vertex have 3D position (x,y,z)
  30756. 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]);
  30757. // Normalize to get normal, then scale to radius
  30758. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  30759. // uv Coordinates from vertex ID
  30760. 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);
  30761. }
  30762. // Subdivide the face (interpolate pos, norm, uv)
  30763. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  30764. // - norm is linear interpolation of vertex corner normal
  30765. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  30766. // - uv is linear interpolation
  30767. //
  30768. // Topology is as below for sub-divide by 2
  30769. // vertex shown as v0,v1,v2
  30770. // interp index is i1 to progress in range [v0,v1[
  30771. // interp index is i2 to progress in range [v0,v2[
  30772. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  30773. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  30774. //
  30775. //
  30776. // i2 v2
  30777. // ^ ^
  30778. // / / \
  30779. // / / \
  30780. // / / \
  30781. // / / (0,1) \
  30782. // / #---------\
  30783. // / / \ (0,0)'/ \
  30784. // / / \ / \
  30785. // / / \ / \
  30786. // / / (0,0) \ / (1,0) \
  30787. // / #---------#---------\
  30788. // v0 v1
  30789. //
  30790. // --------------------> i1
  30791. //
  30792. // interp of (i1,i2):
  30793. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  30794. // along i1 : lerp(x0,x1, i1/(S-i2))
  30795. //
  30796. // centroid of triangle is needed to get help normal computation
  30797. // (c1,c2) are used for centroid location
  30798. var interp_vertex = function (i1, i2, c1, c2) {
  30799. // vertex is interpolated from
  30800. // - face_vertex_pos[0..2]
  30801. // - face_vertex_uv[0..2]
  30802. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  30803. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  30804. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  30805. pos_interp.normalize();
  30806. var vertex_normal;
  30807. if (flat) {
  30808. // in flat mode, recalculate normal as face centroid normal
  30809. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  30810. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  30811. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  30812. }
  30813. else {
  30814. // in smooth mode, recalculate normal from each single vertex position
  30815. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  30816. }
  30817. // Vertex normal need correction due to X,Y,Z radius scaling
  30818. vertex_normal.x /= radiusX;
  30819. vertex_normal.y /= radiusY;
  30820. vertex_normal.z /= radiusZ;
  30821. vertex_normal.normalize();
  30822. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  30823. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  30824. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  30825. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  30826. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  30827. uvs.push(uv_interp.x, uv_interp.y);
  30828. // push each vertex has member of a face
  30829. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  30830. indices.push(current_indice);
  30831. current_indice++;
  30832. };
  30833. for (var i2 = 0; i2 < subdivisions; i2++) {
  30834. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  30835. // face : (i1,i2) for /\ :
  30836. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  30837. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  30838. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  30839. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  30840. if (i1 + i2 + 1 < subdivisions) {
  30841. // face : (i1,i2)' for \/ :
  30842. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  30843. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  30844. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  30845. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  30846. }
  30847. }
  30848. }
  30849. }
  30850. // Sides
  30851. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  30852. // Result
  30853. var vertexData = new VertexData();
  30854. vertexData.indices = indices;
  30855. vertexData.positions = positions;
  30856. vertexData.normals = normals;
  30857. vertexData.uvs = uvs;
  30858. return vertexData;
  30859. };
  30860. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  30861. VertexData.CreatePolyhedron = function (options) {
  30862. // provided polyhedron types :
  30863. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  30864. // 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)
  30865. var polyhedra = [];
  30866. 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]] };
  30867. 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]] };
  30868. polyhedra[2] = {
  30869. 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]],
  30870. 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]]
  30871. };
  30872. polyhedra[3] = {
  30873. 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]],
  30874. 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]]
  30875. };
  30876. polyhedra[4] = {
  30877. 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]],
  30878. 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]]
  30879. };
  30880. 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]] };
  30881. 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]] };
  30882. 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]] };
  30883. 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]] };
  30884. 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]] };
  30885. 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]] };
  30886. 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]] };
  30887. 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]] };
  30888. 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]] };
  30889. polyhedra[14] = {
  30890. 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]],
  30891. 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]]
  30892. };
  30893. var type = (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  30894. var size = options.size;
  30895. var sizeX = options.sizeX || size || 1;
  30896. var sizeY = options.sizeY || size || 1;
  30897. var sizeZ = options.sizeZ || size || 1;
  30898. var data = options.custom || polyhedra[type];
  30899. var nbfaces = data.face.length;
  30900. var faceUV = options.faceUV || new Array(nbfaces);
  30901. var faceColors = options.faceColors;
  30902. var flat = (options.flat === undefined) ? true : options.flat;
  30903. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30904. var positions = [];
  30905. var indices = [];
  30906. var normals = [];
  30907. var uvs = [];
  30908. var colors = [];
  30909. var index = 0;
  30910. var faceIdx = 0; // face cursor in the array "indexes"
  30911. var indexes = [];
  30912. var i = 0;
  30913. var f = 0;
  30914. var u, v, ang, x, y, tmp;
  30915. // default face colors and UV if undefined
  30916. if (flat) {
  30917. for (f = 0; f < nbfaces; f++) {
  30918. if (faceColors && faceColors[f] === undefined) {
  30919. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  30920. }
  30921. if (faceUV && faceUV[f] === undefined) {
  30922. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  30923. }
  30924. }
  30925. }
  30926. if (!flat) {
  30927. for (i = 0; i < data.vertex.length; i++) {
  30928. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  30929. uvs.push(0, 0);
  30930. }
  30931. for (f = 0; f < nbfaces; f++) {
  30932. for (i = 0; i < data.face[f].length - 2; i++) {
  30933. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  30934. }
  30935. }
  30936. }
  30937. else {
  30938. for (f = 0; f < nbfaces; f++) {
  30939. var fl = data.face[f].length; // number of vertices of the current face
  30940. ang = 2 * Math.PI / fl;
  30941. x = 0.5 * Math.tan(ang / 2);
  30942. y = 0.5;
  30943. // positions, uvs, colors
  30944. for (i = 0; i < fl; i++) {
  30945. // positions
  30946. 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);
  30947. indexes.push(index);
  30948. index++;
  30949. // uvs
  30950. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  30951. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  30952. uvs.push(u, v);
  30953. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  30954. y = x * Math.sin(ang) + y * Math.cos(ang);
  30955. x = tmp;
  30956. // colors
  30957. if (faceColors) {
  30958. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  30959. }
  30960. }
  30961. // indices from indexes
  30962. for (i = 0; i < fl - 2; i++) {
  30963. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  30964. }
  30965. faceIdx += fl;
  30966. }
  30967. }
  30968. VertexData.ComputeNormals(positions, indices, normals);
  30969. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  30970. var vertexData = new VertexData();
  30971. vertexData.positions = positions;
  30972. vertexData.indices = indices;
  30973. vertexData.normals = normals;
  30974. vertexData.uvs = uvs;
  30975. if (faceColors && flat) {
  30976. vertexData.colors = colors;
  30977. }
  30978. return vertexData;
  30979. };
  30980. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  30981. VertexData.CreateTorusKnot = function (options) {
  30982. var indices = [];
  30983. var positions = [];
  30984. var normals = [];
  30985. var uvs = [];
  30986. var radius = options.radius || 2;
  30987. var tube = options.tube || 0.5;
  30988. var radialSegments = options.radialSegments || 32;
  30989. var tubularSegments = options.tubularSegments || 32;
  30990. var p = options.p || 2;
  30991. var q = options.q || 3;
  30992. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30993. // Helper
  30994. var getPos = function (angle) {
  30995. var cu = Math.cos(angle);
  30996. var su = Math.sin(angle);
  30997. var quOverP = q / p * angle;
  30998. var cs = Math.cos(quOverP);
  30999. var tx = radius * (2 + cs) * 0.5 * cu;
  31000. var ty = radius * (2 + cs) * su * 0.5;
  31001. var tz = radius * Math.sin(quOverP) * 0.5;
  31002. return new BABYLON.Vector3(tx, ty, tz);
  31003. };
  31004. // Vertices
  31005. var i;
  31006. var j;
  31007. for (i = 0; i <= radialSegments; i++) {
  31008. var modI = i % radialSegments;
  31009. var u = modI / radialSegments * 2 * p * Math.PI;
  31010. var p1 = getPos(u);
  31011. var p2 = getPos(u + 0.01);
  31012. var tang = p2.subtract(p1);
  31013. var n = p2.add(p1);
  31014. var bitan = BABYLON.Vector3.Cross(tang, n);
  31015. n = BABYLON.Vector3.Cross(bitan, tang);
  31016. bitan.normalize();
  31017. n.normalize();
  31018. for (j = 0; j < tubularSegments; j++) {
  31019. var modJ = j % tubularSegments;
  31020. var v = modJ / tubularSegments * 2 * Math.PI;
  31021. var cx = -tube * Math.cos(v);
  31022. var cy = tube * Math.sin(v);
  31023. positions.push(p1.x + cx * n.x + cy * bitan.x);
  31024. positions.push(p1.y + cx * n.y + cy * bitan.y);
  31025. positions.push(p1.z + cx * n.z + cy * bitan.z);
  31026. uvs.push(i / radialSegments);
  31027. uvs.push(j / tubularSegments);
  31028. }
  31029. }
  31030. for (i = 0; i < radialSegments; i++) {
  31031. for (j = 0; j < tubularSegments; j++) {
  31032. var jNext = (j + 1) % tubularSegments;
  31033. var a = i * tubularSegments + j;
  31034. var b = (i + 1) * tubularSegments + j;
  31035. var c = (i + 1) * tubularSegments + jNext;
  31036. var d = i * tubularSegments + jNext;
  31037. indices.push(d);
  31038. indices.push(b);
  31039. indices.push(a);
  31040. indices.push(d);
  31041. indices.push(c);
  31042. indices.push(b);
  31043. }
  31044. }
  31045. // Normals
  31046. VertexData.ComputeNormals(positions, indices, normals);
  31047. // Sides
  31048. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  31049. // Result
  31050. var vertexData = new VertexData();
  31051. vertexData.indices = indices;
  31052. vertexData.positions = positions;
  31053. vertexData.normals = normals;
  31054. vertexData.uvs = uvs;
  31055. return vertexData;
  31056. };
  31057. // Tools
  31058. /**
  31059. * @param {any} - positions (number[] or Float32Array)
  31060. * @param {any} - indices (number[] or Uint16Array)
  31061. * @param {any} - normals (number[] or Float32Array)
  31062. */
  31063. VertexData.ComputeNormals = function (positions, indices, normals) {
  31064. var index = 0;
  31065. var p1p2x = 0.0;
  31066. var p1p2y = 0.0;
  31067. var p1p2z = 0.0;
  31068. var p3p2x = 0.0;
  31069. var p3p2y = 0.0;
  31070. var p3p2z = 0.0;
  31071. var faceNormalx = 0.0;
  31072. var faceNormaly = 0.0;
  31073. var faceNormalz = 0.0;
  31074. var length = 0.0;
  31075. var i1 = 0;
  31076. var i2 = 0;
  31077. var i3 = 0;
  31078. for (index = 0; index < positions.length; index++) {
  31079. normals[index] = 0.0;
  31080. }
  31081. // indice triplet = 1 face
  31082. var nbFaces = indices.length / 3;
  31083. for (index = 0; index < nbFaces; index++) {
  31084. i1 = indices[index * 3]; // get the indexes of each vertex of the face
  31085. i2 = indices[index * 3 + 1];
  31086. i3 = indices[index * 3 + 2];
  31087. p1p2x = positions[i1 * 3] - positions[i2 * 3]; // compute two vectors per face
  31088. p1p2y = positions[i1 * 3 + 1] - positions[i2 * 3 + 1];
  31089. p1p2z = positions[i1 * 3 + 2] - positions[i2 * 3 + 2];
  31090. p3p2x = positions[i3 * 3] - positions[i2 * 3];
  31091. p3p2y = positions[i3 * 3 + 1] - positions[i2 * 3 + 1];
  31092. p3p2z = positions[i3 * 3 + 2] - positions[i2 * 3 + 2];
  31093. faceNormalx = p1p2y * p3p2z - p1p2z * p3p2y; // compute the face normal with cross product
  31094. faceNormaly = p1p2z * p3p2x - p1p2x * p3p2z;
  31095. faceNormalz = p1p2x * p3p2y - p1p2y * p3p2x;
  31096. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  31097. length = (length === 0) ? 1.0 : length;
  31098. faceNormalx /= length; // normalize this normal
  31099. faceNormaly /= length;
  31100. faceNormalz /= length;
  31101. normals[i1 * 3] += faceNormalx; // accumulate all the normals per face
  31102. normals[i1 * 3 + 1] += faceNormaly;
  31103. normals[i1 * 3 + 2] += faceNormalz;
  31104. normals[i2 * 3] += faceNormalx;
  31105. normals[i2 * 3 + 1] += faceNormaly;
  31106. normals[i2 * 3 + 2] += faceNormalz;
  31107. normals[i3 * 3] += faceNormalx;
  31108. normals[i3 * 3 + 1] += faceNormaly;
  31109. normals[i3 * 3 + 2] += faceNormalz;
  31110. }
  31111. // last normalization of each normal
  31112. for (index = 0; index < normals.length / 3; index++) {
  31113. faceNormalx = normals[index * 3];
  31114. faceNormaly = normals[index * 3 + 1];
  31115. faceNormalz = normals[index * 3 + 2];
  31116. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  31117. length = (length === 0) ? 1.0 : length;
  31118. faceNormalx /= length;
  31119. faceNormaly /= length;
  31120. faceNormalz /= length;
  31121. normals[index * 3] = faceNormalx;
  31122. normals[index * 3 + 1] = faceNormaly;
  31123. normals[index * 3 + 2] = faceNormalz;
  31124. }
  31125. };
  31126. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs) {
  31127. var li = indices.length;
  31128. var ln = normals.length;
  31129. var i;
  31130. var n;
  31131. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31132. switch (sideOrientation) {
  31133. case BABYLON.Mesh.FRONTSIDE:
  31134. // nothing changed
  31135. break;
  31136. case BABYLON.Mesh.BACKSIDE:
  31137. var tmp;
  31138. // indices
  31139. for (i = 0; i < li; i += 3) {
  31140. tmp = indices[i];
  31141. indices[i] = indices[i + 2];
  31142. indices[i + 2] = tmp;
  31143. }
  31144. // normals
  31145. for (n = 0; n < ln; n++) {
  31146. normals[n] = -normals[n];
  31147. }
  31148. break;
  31149. case BABYLON.Mesh.DOUBLESIDE:
  31150. // positions
  31151. var lp = positions.length;
  31152. var l = lp / 3;
  31153. for (var p = 0; p < lp; p++) {
  31154. positions[lp + p] = positions[p];
  31155. }
  31156. // indices
  31157. for (i = 0; i < li; i += 3) {
  31158. indices[i + li] = indices[i + 2] + l;
  31159. indices[i + 1 + li] = indices[i + 1] + l;
  31160. indices[i + 2 + li] = indices[i] + l;
  31161. }
  31162. // normals
  31163. for (n = 0; n < ln; n++) {
  31164. normals[ln + n] = -normals[n];
  31165. }
  31166. // uvs
  31167. var lu = uvs.length;
  31168. for (var u = 0; u < lu; u++) {
  31169. uvs[u + lu] = uvs[u];
  31170. }
  31171. break;
  31172. }
  31173. };
  31174. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  31175. var vertexData = new VertexData();
  31176. // positions
  31177. var positions = parsedVertexData.positions;
  31178. if (positions) {
  31179. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  31180. }
  31181. // normals
  31182. var normals = parsedVertexData.normals;
  31183. if (normals) {
  31184. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  31185. }
  31186. // uvs
  31187. var uvs = parsedVertexData.uvs;
  31188. if (uvs) {
  31189. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  31190. }
  31191. // uv2s
  31192. var uv2s = parsedVertexData.uv2s;
  31193. if (uv2s) {
  31194. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  31195. }
  31196. // uv3s
  31197. var uv3s = parsedVertexData.uv3s;
  31198. if (uv3s) {
  31199. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  31200. }
  31201. // uv4s
  31202. var uv4s = parsedVertexData.uv4s;
  31203. if (uv4s) {
  31204. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  31205. }
  31206. // uv5s
  31207. var uv5s = parsedVertexData.uv5s;
  31208. if (uv5s) {
  31209. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  31210. }
  31211. // uv6s
  31212. var uv6s = parsedVertexData.uv6s;
  31213. if (uv6s) {
  31214. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  31215. }
  31216. // colors
  31217. var colors = parsedVertexData.colors;
  31218. if (colors) {
  31219. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  31220. }
  31221. // matricesIndices
  31222. var matricesIndices = parsedVertexData.matricesIndices;
  31223. if (matricesIndices) {
  31224. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  31225. }
  31226. // matricesWeights
  31227. var matricesWeights = parsedVertexData.matricesWeights;
  31228. if (matricesWeights) {
  31229. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  31230. }
  31231. // indices
  31232. var indices = parsedVertexData.indices;
  31233. if (indices) {
  31234. vertexData.indices = indices;
  31235. }
  31236. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  31237. };
  31238. return VertexData;
  31239. }());
  31240. BABYLON.VertexData = VertexData;
  31241. })(BABYLON || (BABYLON = {}));
  31242. var BABYLON;
  31243. (function (BABYLON) {
  31244. var Tags = (function () {
  31245. function Tags() {
  31246. }
  31247. Tags.EnableFor = function (obj) {
  31248. obj._tags = obj._tags || {};
  31249. obj.hasTags = function () {
  31250. return Tags.HasTags(obj);
  31251. };
  31252. obj.addTags = function (tagsString) {
  31253. return Tags.AddTagsTo(obj, tagsString);
  31254. };
  31255. obj.removeTags = function (tagsString) {
  31256. return Tags.RemoveTagsFrom(obj, tagsString);
  31257. };
  31258. obj.matchesTagsQuery = function (tagsQuery) {
  31259. return Tags.MatchesQuery(obj, tagsQuery);
  31260. };
  31261. };
  31262. Tags.DisableFor = function (obj) {
  31263. delete obj._tags;
  31264. delete obj.hasTags;
  31265. delete obj.addTags;
  31266. delete obj.removeTags;
  31267. delete obj.matchesTagsQuery;
  31268. };
  31269. Tags.HasTags = function (obj) {
  31270. if (!obj._tags) {
  31271. return false;
  31272. }
  31273. return !BABYLON.Tools.IsEmpty(obj._tags);
  31274. };
  31275. Tags.GetTags = function (obj, asString) {
  31276. if (asString === void 0) { asString = true; }
  31277. if (!obj._tags) {
  31278. return null;
  31279. }
  31280. if (asString) {
  31281. var tagsArray = [];
  31282. for (var tag in obj._tags) {
  31283. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  31284. tagsArray.push(tag);
  31285. }
  31286. }
  31287. return tagsArray.join(" ");
  31288. }
  31289. else {
  31290. return obj._tags;
  31291. }
  31292. };
  31293. // the tags 'true' and 'false' are reserved and cannot be used as tags
  31294. // a tag cannot start with '||', '&&', and '!'
  31295. // it cannot contain whitespaces
  31296. Tags.AddTagsTo = function (obj, tagsString) {
  31297. if (!tagsString) {
  31298. return;
  31299. }
  31300. if (typeof tagsString !== "string") {
  31301. return;
  31302. }
  31303. var tags = tagsString.split(" ");
  31304. for (var t in tags) {
  31305. Tags._AddTagTo(obj, tags[t]);
  31306. }
  31307. };
  31308. Tags._AddTagTo = function (obj, tag) {
  31309. tag = tag.trim();
  31310. if (tag === "" || tag === "true" || tag === "false") {
  31311. return;
  31312. }
  31313. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  31314. return;
  31315. }
  31316. Tags.EnableFor(obj);
  31317. obj._tags[tag] = true;
  31318. };
  31319. Tags.RemoveTagsFrom = function (obj, tagsString) {
  31320. if (!Tags.HasTags(obj)) {
  31321. return;
  31322. }
  31323. var tags = tagsString.split(" ");
  31324. for (var t in tags) {
  31325. Tags._RemoveTagFrom(obj, tags[t]);
  31326. }
  31327. };
  31328. Tags._RemoveTagFrom = function (obj, tag) {
  31329. delete obj._tags[tag];
  31330. };
  31331. Tags.MatchesQuery = function (obj, tagsQuery) {
  31332. if (tagsQuery === undefined) {
  31333. return true;
  31334. }
  31335. if (tagsQuery === "") {
  31336. return Tags.HasTags(obj);
  31337. }
  31338. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  31339. };
  31340. return Tags;
  31341. }());
  31342. BABYLON.Tags = Tags;
  31343. })(BABYLON || (BABYLON = {}));
  31344. var BABYLON;
  31345. (function (BABYLON) {
  31346. var Internals;
  31347. (function (Internals) {
  31348. var AndOrNotEvaluator = (function () {
  31349. function AndOrNotEvaluator() {
  31350. }
  31351. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  31352. if (!query.match(/\([^\(\)]*\)/g)) {
  31353. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  31354. }
  31355. else {
  31356. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  31357. // remove parenthesis
  31358. r = r.slice(1, r.length - 1);
  31359. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  31360. });
  31361. }
  31362. if (query === "true") {
  31363. return true;
  31364. }
  31365. if (query === "false") {
  31366. return false;
  31367. }
  31368. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  31369. };
  31370. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  31371. evaluateCallback = evaluateCallback || (function (r) {
  31372. return r === "true" ? true : false;
  31373. });
  31374. var result;
  31375. var or = parenthesisContent.split("||");
  31376. for (var i in or) {
  31377. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  31378. var and = ori.split("&&");
  31379. if (and.length > 1) {
  31380. for (var j = 0; j < and.length; ++j) {
  31381. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  31382. if (andj !== "true" && andj !== "false") {
  31383. if (andj[0] === "!") {
  31384. result = !evaluateCallback(andj.substring(1));
  31385. }
  31386. else {
  31387. result = evaluateCallback(andj);
  31388. }
  31389. }
  31390. else {
  31391. result = andj === "true" ? true : false;
  31392. }
  31393. if (!result) {
  31394. ori = "false";
  31395. break;
  31396. }
  31397. }
  31398. }
  31399. if (result || ori === "true") {
  31400. result = true;
  31401. break;
  31402. }
  31403. // result equals false (or undefined)
  31404. if (ori !== "true" && ori !== "false") {
  31405. if (ori[0] === "!") {
  31406. result = !evaluateCallback(ori.substring(1));
  31407. }
  31408. else {
  31409. result = evaluateCallback(ori);
  31410. }
  31411. }
  31412. else {
  31413. result = ori === "true" ? true : false;
  31414. }
  31415. }
  31416. // the whole parenthesis scope is replaced by 'true' or 'false'
  31417. return result ? "true" : "false";
  31418. };
  31419. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  31420. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  31421. // remove whitespaces
  31422. r = r.replace(/[\s]/g, function () { return ""; });
  31423. return r.length % 2 ? "!" : "";
  31424. });
  31425. booleanString = booleanString.trim();
  31426. if (booleanString === "!true") {
  31427. booleanString = "false";
  31428. }
  31429. else if (booleanString === "!false") {
  31430. booleanString = "true";
  31431. }
  31432. return booleanString;
  31433. };
  31434. return AndOrNotEvaluator;
  31435. }());
  31436. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  31437. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  31438. })(BABYLON || (BABYLON = {}));
  31439. var BABYLON;
  31440. (function (BABYLON) {
  31441. var PostProcessRenderPass = (function () {
  31442. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  31443. this._enabled = true;
  31444. this._refCount = 0;
  31445. this._name = name;
  31446. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  31447. this.setRenderList(renderList);
  31448. this._renderTexture.onBeforeRenderObservable.add(beforeRender);
  31449. this._renderTexture.onAfterRenderObservable.add(afterRender);
  31450. this._scene = scene;
  31451. this._renderList = renderList;
  31452. }
  31453. // private
  31454. PostProcessRenderPass.prototype._incRefCount = function () {
  31455. if (this._refCount === 0) {
  31456. this._scene.customRenderTargets.push(this._renderTexture);
  31457. }
  31458. return ++this._refCount;
  31459. };
  31460. PostProcessRenderPass.prototype._decRefCount = function () {
  31461. this._refCount--;
  31462. if (this._refCount <= 0) {
  31463. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  31464. }
  31465. return this._refCount;
  31466. };
  31467. PostProcessRenderPass.prototype._update = function () {
  31468. this.setRenderList(this._renderList);
  31469. };
  31470. // public
  31471. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  31472. this._renderTexture.renderList = renderList;
  31473. };
  31474. PostProcessRenderPass.prototype.getRenderTexture = function () {
  31475. return this._renderTexture;
  31476. };
  31477. return PostProcessRenderPass;
  31478. }());
  31479. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  31480. })(BABYLON || (BABYLON = {}));
  31481. var BABYLON;
  31482. (function (BABYLON) {
  31483. var PostProcessRenderEffect = (function () {
  31484. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  31485. this._engine = engine;
  31486. this._name = name;
  31487. this._singleInstance = singleInstance || true;
  31488. this._getPostProcess = getPostProcess;
  31489. this._cameras = [];
  31490. this._indicesForCamera = [];
  31491. this._postProcesses = {};
  31492. this._renderPasses = {};
  31493. this._renderEffectAsPasses = {};
  31494. }
  31495. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  31496. get: function () {
  31497. for (var index in this._postProcesses) {
  31498. if (!this._postProcesses[index].isSupported) {
  31499. return false;
  31500. }
  31501. }
  31502. return true;
  31503. },
  31504. enumerable: true,
  31505. configurable: true
  31506. });
  31507. PostProcessRenderEffect.prototype._update = function () {
  31508. for (var renderPassName in this._renderPasses) {
  31509. this._renderPasses[renderPassName]._update();
  31510. }
  31511. };
  31512. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  31513. this._renderPasses[renderPass._name] = renderPass;
  31514. this._linkParameters();
  31515. };
  31516. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  31517. delete this._renderPasses[renderPass._name];
  31518. this._linkParameters();
  31519. };
  31520. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  31521. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  31522. this._linkParameters();
  31523. };
  31524. PostProcessRenderEffect.prototype.getPass = function (passName) {
  31525. for (var renderPassName in this._renderPasses) {
  31526. if (renderPassName === passName) {
  31527. return this._renderPasses[passName];
  31528. }
  31529. }
  31530. };
  31531. PostProcessRenderEffect.prototype.emptyPasses = function () {
  31532. this._renderPasses = {};
  31533. this._linkParameters();
  31534. };
  31535. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  31536. var cameraKey;
  31537. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  31538. for (var i = 0; i < _cam.length; i++) {
  31539. var camera = _cam[i];
  31540. var cameraName = camera.name;
  31541. if (this._singleInstance) {
  31542. cameraKey = 0;
  31543. }
  31544. else {
  31545. cameraKey = cameraName;
  31546. }
  31547. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  31548. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  31549. if (!this._indicesForCamera[cameraName]) {
  31550. this._indicesForCamera[cameraName] = [];
  31551. }
  31552. this._indicesForCamera[cameraName].push(index);
  31553. if (this._cameras.indexOf(camera) === -1) {
  31554. this._cameras[cameraName] = camera;
  31555. }
  31556. for (var passName in this._renderPasses) {
  31557. this._renderPasses[passName]._incRefCount();
  31558. }
  31559. }
  31560. this._linkParameters();
  31561. };
  31562. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  31563. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  31564. for (var i = 0; i < _cam.length; i++) {
  31565. var camera = _cam[i];
  31566. var cameraName = camera.name;
  31567. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  31568. var index = this._cameras.indexOf(cameraName);
  31569. this._indicesForCamera.splice(index, 1);
  31570. this._cameras.splice(index, 1);
  31571. for (var passName in this._renderPasses) {
  31572. this._renderPasses[passName]._decRefCount();
  31573. }
  31574. }
  31575. };
  31576. PostProcessRenderEffect.prototype._enable = function (cameras) {
  31577. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  31578. for (var i = 0; i < _cam.length; i++) {
  31579. var camera = _cam[i];
  31580. var cameraName = camera.name;
  31581. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  31582. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  31583. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  31584. }
  31585. }
  31586. for (var passName in this._renderPasses) {
  31587. this._renderPasses[passName]._incRefCount();
  31588. }
  31589. }
  31590. };
  31591. PostProcessRenderEffect.prototype._disable = function (cameras) {
  31592. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  31593. for (var i = 0; i < _cam.length; i++) {
  31594. var camera = _cam[i];
  31595. var cameraName = camera.Name;
  31596. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  31597. for (var passName in this._renderPasses) {
  31598. this._renderPasses[passName]._decRefCount();
  31599. }
  31600. }
  31601. };
  31602. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  31603. if (this._singleInstance) {
  31604. return this._postProcesses[0];
  31605. }
  31606. else {
  31607. return this._postProcesses[camera.name];
  31608. }
  31609. };
  31610. PostProcessRenderEffect.prototype._linkParameters = function () {
  31611. var _this = this;
  31612. for (var index in this._postProcesses) {
  31613. if (this.applyParameters) {
  31614. this.applyParameters(this._postProcesses[index]);
  31615. }
  31616. this._postProcesses[index].onBeforeRenderObservable.add(function (effect) {
  31617. _this._linkTextures(effect);
  31618. });
  31619. }
  31620. };
  31621. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  31622. for (var renderPassName in this._renderPasses) {
  31623. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  31624. }
  31625. for (var renderEffectName in this._renderEffectAsPasses) {
  31626. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  31627. }
  31628. };
  31629. return PostProcessRenderEffect;
  31630. }());
  31631. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  31632. })(BABYLON || (BABYLON = {}));
  31633. var BABYLON;
  31634. (function (BABYLON) {
  31635. var PostProcessRenderPipeline = (function () {
  31636. function PostProcessRenderPipeline(engine, name) {
  31637. this._engine = engine;
  31638. this._name = name;
  31639. this._renderEffects = {};
  31640. this._renderEffectsForIsolatedPass = {};
  31641. this._cameras = [];
  31642. }
  31643. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  31644. get: function () {
  31645. for (var renderEffectName in this._renderEffects) {
  31646. if (!this._renderEffects[renderEffectName].isSupported) {
  31647. return false;
  31648. }
  31649. }
  31650. return true;
  31651. },
  31652. enumerable: true,
  31653. configurable: true
  31654. });
  31655. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  31656. this._renderEffects[renderEffect._name] = renderEffect;
  31657. };
  31658. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  31659. var renderEffects = this._renderEffects[renderEffectName];
  31660. if (!renderEffects) {
  31661. return;
  31662. }
  31663. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  31664. };
  31665. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  31666. var renderEffects = this._renderEffects[renderEffectName];
  31667. if (!renderEffects) {
  31668. return;
  31669. }
  31670. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  31671. };
  31672. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  31673. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  31674. var indicesToDelete = [];
  31675. var i;
  31676. for (i = 0; i < _cam.length; i++) {
  31677. var camera = _cam[i];
  31678. var cameraName = camera.name;
  31679. if (this._cameras.indexOf(camera) === -1) {
  31680. this._cameras[cameraName] = camera;
  31681. }
  31682. else if (unique) {
  31683. indicesToDelete.push(i);
  31684. }
  31685. }
  31686. for (i = 0; i < indicesToDelete.length; i++) {
  31687. cameras.splice(indicesToDelete[i], 1);
  31688. }
  31689. for (var renderEffectName in this._renderEffects) {
  31690. this._renderEffects[renderEffectName]._attachCameras(_cam);
  31691. }
  31692. };
  31693. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  31694. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  31695. for (var renderEffectName in this._renderEffects) {
  31696. this._renderEffects[renderEffectName]._detachCameras(_cam);
  31697. }
  31698. for (var i = 0; i < _cam.length; i++) {
  31699. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  31700. }
  31701. };
  31702. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  31703. var _this = this;
  31704. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  31705. var pass = null;
  31706. var renderEffectName;
  31707. for (renderEffectName in this._renderEffects) {
  31708. pass = this._renderEffects[renderEffectName].getPass(passName);
  31709. if (pass != null) {
  31710. break;
  31711. }
  31712. }
  31713. if (pass === null) {
  31714. return;
  31715. }
  31716. for (renderEffectName in this._renderEffects) {
  31717. this._renderEffects[renderEffectName]._disable(_cam);
  31718. }
  31719. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  31720. for (var i = 0; i < _cam.length; i++) {
  31721. var camera = _cam[i];
  31722. var cameraName = camera.name;
  31723. 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); });
  31724. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  31725. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  31726. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  31727. }
  31728. };
  31729. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  31730. var _this = this;
  31731. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  31732. for (var i = 0; i < _cam.length; i++) {
  31733. var camera = _cam[i];
  31734. var cameraName = camera.name;
  31735. 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); });
  31736. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  31737. }
  31738. for (var renderEffectName in this._renderEffects) {
  31739. this._renderEffects[renderEffectName]._enable(_cam);
  31740. }
  31741. };
  31742. PostProcessRenderPipeline.prototype._update = function () {
  31743. for (var renderEffectName in this._renderEffects) {
  31744. this._renderEffects[renderEffectName]._update();
  31745. }
  31746. for (var i = 0; i < this._cameras.length; i++) {
  31747. var cameraName = this._cameras[i].name;
  31748. if (this._renderEffectsForIsolatedPass[cameraName]) {
  31749. this._renderEffectsForIsolatedPass[cameraName]._update();
  31750. }
  31751. }
  31752. };
  31753. PostProcessRenderPipeline.prototype.dispose = function () {
  31754. // Must be implemented by children
  31755. };
  31756. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  31757. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  31758. return PostProcessRenderPipeline;
  31759. }());
  31760. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  31761. })(BABYLON || (BABYLON = {}));
  31762. var BABYLON;
  31763. (function (BABYLON) {
  31764. var PostProcessRenderPipelineManager = (function () {
  31765. function PostProcessRenderPipelineManager() {
  31766. this._renderPipelines = {};
  31767. }
  31768. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  31769. this._renderPipelines[renderPipeline._name] = renderPipeline;
  31770. };
  31771. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  31772. var renderPipeline = this._renderPipelines[renderPipelineName];
  31773. if (!renderPipeline) {
  31774. return;
  31775. }
  31776. renderPipeline._attachCameras(cameras, unique);
  31777. };
  31778. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  31779. var renderPipeline = this._renderPipelines[renderPipelineName];
  31780. if (!renderPipeline) {
  31781. return;
  31782. }
  31783. renderPipeline._detachCameras(cameras);
  31784. };
  31785. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  31786. var renderPipeline = this._renderPipelines[renderPipelineName];
  31787. if (!renderPipeline) {
  31788. return;
  31789. }
  31790. renderPipeline._enableEffect(renderEffectName, cameras);
  31791. };
  31792. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  31793. var renderPipeline = this._renderPipelines[renderPipelineName];
  31794. if (!renderPipeline) {
  31795. return;
  31796. }
  31797. renderPipeline._disableEffect(renderEffectName, cameras);
  31798. };
  31799. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  31800. var renderPipeline = this._renderPipelines[renderPipelineName];
  31801. if (!renderPipeline) {
  31802. return;
  31803. }
  31804. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  31805. };
  31806. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  31807. var renderPipeline = this._renderPipelines[renderPipelineName];
  31808. if (!renderPipeline) {
  31809. return;
  31810. }
  31811. renderPipeline._disableDisplayOnlyPass(cameras);
  31812. };
  31813. PostProcessRenderPipelineManager.prototype.update = function () {
  31814. for (var renderPipelineName in this._renderPipelines) {
  31815. var pipeline = this._renderPipelines[renderPipelineName];
  31816. if (!pipeline.isSupported) {
  31817. pipeline.dispose();
  31818. delete this._renderPipelines[renderPipelineName];
  31819. }
  31820. else {
  31821. pipeline._update();
  31822. }
  31823. }
  31824. };
  31825. return PostProcessRenderPipelineManager;
  31826. }());
  31827. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  31828. })(BABYLON || (BABYLON = {}));
  31829. var BABYLON;
  31830. (function (BABYLON) {
  31831. var BoundingBoxRenderer = (function () {
  31832. function BoundingBoxRenderer(scene) {
  31833. this.frontColor = new BABYLON.Color3(1, 1, 1);
  31834. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  31835. this.showBackLines = true;
  31836. this.renderList = new BABYLON.SmartArray(32);
  31837. this._vertexBuffers = {};
  31838. this._scene = scene;
  31839. }
  31840. BoundingBoxRenderer.prototype._prepareRessources = function () {
  31841. if (this._colorShader) {
  31842. return;
  31843. }
  31844. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  31845. attributes: [BABYLON.VertexBuffer.PositionKind],
  31846. uniforms: ["worldViewProjection", "color"]
  31847. });
  31848. var engine = this._scene.getEngine();
  31849. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  31850. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  31851. 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]);
  31852. };
  31853. BoundingBoxRenderer.prototype.reset = function () {
  31854. this.renderList.reset();
  31855. };
  31856. BoundingBoxRenderer.prototype.render = function () {
  31857. if (this.renderList.length === 0) {
  31858. return;
  31859. }
  31860. this._prepareRessources();
  31861. if (!this._colorShader.isReady()) {
  31862. return;
  31863. }
  31864. var engine = this._scene.getEngine();
  31865. engine.setDepthWrite(false);
  31866. this._colorShader._preBind();
  31867. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  31868. var boundingBox = this.renderList.data[boundingBoxIndex];
  31869. var min = boundingBox.minimum;
  31870. var max = boundingBox.maximum;
  31871. var diff = max.subtract(min);
  31872. var median = min.add(diff.scale(0.5));
  31873. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  31874. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  31875. .multiply(boundingBox.getWorldMatrix());
  31876. // VBOs
  31877. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  31878. if (this.showBackLines) {
  31879. // Back
  31880. engine.setDepthFunctionToGreaterOrEqual();
  31881. this._scene.resetCachedMaterial();
  31882. this._colorShader.setColor4("color", this.backColor.toColor4());
  31883. this._colorShader.bind(worldMatrix);
  31884. // Draw order
  31885. engine.draw(false, 0, 24);
  31886. }
  31887. // Front
  31888. engine.setDepthFunctionToLess();
  31889. this._scene.resetCachedMaterial();
  31890. this._colorShader.setColor4("color", this.frontColor.toColor4());
  31891. this._colorShader.bind(worldMatrix);
  31892. // Draw order
  31893. engine.draw(false, 0, 24);
  31894. }
  31895. this._colorShader.unbind();
  31896. engine.setDepthFunctionToLessOrEqual();
  31897. engine.setDepthWrite(true);
  31898. };
  31899. BoundingBoxRenderer.prototype.dispose = function () {
  31900. if (!this._colorShader) {
  31901. return;
  31902. }
  31903. this._colorShader.dispose();
  31904. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  31905. if (buffer) {
  31906. buffer.dispose();
  31907. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  31908. }
  31909. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  31910. };
  31911. return BoundingBoxRenderer;
  31912. }());
  31913. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  31914. })(BABYLON || (BABYLON = {}));
  31915. var BABYLON;
  31916. (function (BABYLON) {
  31917. var Condition = (function () {
  31918. function Condition(actionManager) {
  31919. this._actionManager = actionManager;
  31920. }
  31921. Condition.prototype.isValid = function () {
  31922. return true;
  31923. };
  31924. Condition.prototype._getProperty = function (propertyPath) {
  31925. return this._actionManager._getProperty(propertyPath);
  31926. };
  31927. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  31928. return this._actionManager._getEffectiveTarget(target, propertyPath);
  31929. };
  31930. Condition.prototype.serialize = function () {
  31931. };
  31932. Condition.prototype._serialize = function (serializedCondition) {
  31933. return {
  31934. type: 2,
  31935. children: [],
  31936. name: serializedCondition.name,
  31937. properties: serializedCondition.properties
  31938. };
  31939. };
  31940. return Condition;
  31941. }());
  31942. BABYLON.Condition = Condition;
  31943. var ValueCondition = (function (_super) {
  31944. __extends(ValueCondition, _super);
  31945. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  31946. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  31947. _super.call(this, actionManager);
  31948. this.propertyPath = propertyPath;
  31949. this.value = value;
  31950. this.operator = operator;
  31951. this._target = target;
  31952. this._effectiveTarget = this._getEffectiveTarget(target, this.propertyPath);
  31953. this._property = this._getProperty(this.propertyPath);
  31954. }
  31955. Object.defineProperty(ValueCondition, "IsEqual", {
  31956. get: function () {
  31957. return ValueCondition._IsEqual;
  31958. },
  31959. enumerable: true,
  31960. configurable: true
  31961. });
  31962. Object.defineProperty(ValueCondition, "IsDifferent", {
  31963. get: function () {
  31964. return ValueCondition._IsDifferent;
  31965. },
  31966. enumerable: true,
  31967. configurable: true
  31968. });
  31969. Object.defineProperty(ValueCondition, "IsGreater", {
  31970. get: function () {
  31971. return ValueCondition._IsGreater;
  31972. },
  31973. enumerable: true,
  31974. configurable: true
  31975. });
  31976. Object.defineProperty(ValueCondition, "IsLesser", {
  31977. get: function () {
  31978. return ValueCondition._IsLesser;
  31979. },
  31980. enumerable: true,
  31981. configurable: true
  31982. });
  31983. // Methods
  31984. ValueCondition.prototype.isValid = function () {
  31985. switch (this.operator) {
  31986. case ValueCondition.IsGreater:
  31987. return this._effectiveTarget[this._property] > this.value;
  31988. case ValueCondition.IsLesser:
  31989. return this._effectiveTarget[this._property] < this.value;
  31990. case ValueCondition.IsEqual:
  31991. case ValueCondition.IsDifferent:
  31992. var check;
  31993. if (this.value.equals) {
  31994. check = this.value.equals(this._effectiveTarget[this._property]);
  31995. }
  31996. else {
  31997. check = this.value === this._effectiveTarget[this._property];
  31998. }
  31999. return this.operator === ValueCondition.IsEqual ? check : !check;
  32000. }
  32001. return false;
  32002. };
  32003. ValueCondition.prototype.serialize = function () {
  32004. return this._serialize({
  32005. name: "ValueCondition",
  32006. properties: [
  32007. BABYLON.Action._GetTargetProperty(this._target),
  32008. { name: "propertyPath", value: this.propertyPath },
  32009. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  32010. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  32011. ]
  32012. });
  32013. };
  32014. ValueCondition.GetOperatorName = function (operator) {
  32015. switch (operator) {
  32016. case ValueCondition._IsEqual: return "IsEqual";
  32017. case ValueCondition._IsDifferent: return "IsDifferent";
  32018. case ValueCondition._IsGreater: return "IsGreater";
  32019. case ValueCondition._IsLesser: return "IsLesser";
  32020. default: return "";
  32021. }
  32022. };
  32023. // Statics
  32024. ValueCondition._IsEqual = 0;
  32025. ValueCondition._IsDifferent = 1;
  32026. ValueCondition._IsGreater = 2;
  32027. ValueCondition._IsLesser = 3;
  32028. return ValueCondition;
  32029. }(Condition));
  32030. BABYLON.ValueCondition = ValueCondition;
  32031. var PredicateCondition = (function (_super) {
  32032. __extends(PredicateCondition, _super);
  32033. function PredicateCondition(actionManager, predicate) {
  32034. _super.call(this, actionManager);
  32035. this.predicate = predicate;
  32036. }
  32037. PredicateCondition.prototype.isValid = function () {
  32038. return this.predicate();
  32039. };
  32040. return PredicateCondition;
  32041. }(Condition));
  32042. BABYLON.PredicateCondition = PredicateCondition;
  32043. var StateCondition = (function (_super) {
  32044. __extends(StateCondition, _super);
  32045. function StateCondition(actionManager, target, value) {
  32046. _super.call(this, actionManager);
  32047. this.value = value;
  32048. this._target = target;
  32049. }
  32050. // Methods
  32051. StateCondition.prototype.isValid = function () {
  32052. return this._target.state === this.value;
  32053. };
  32054. StateCondition.prototype.serialize = function () {
  32055. return this._serialize({
  32056. name: "StateCondition",
  32057. properties: [
  32058. BABYLON.Action._GetTargetProperty(this._target),
  32059. { name: "value", value: this.value }
  32060. ]
  32061. });
  32062. };
  32063. return StateCondition;
  32064. }(Condition));
  32065. BABYLON.StateCondition = StateCondition;
  32066. })(BABYLON || (BABYLON = {}));
  32067. var BABYLON;
  32068. (function (BABYLON) {
  32069. var Action = (function () {
  32070. function Action(triggerOptions, condition) {
  32071. this.triggerOptions = triggerOptions;
  32072. if (triggerOptions.parameter) {
  32073. this.trigger = triggerOptions.trigger;
  32074. this._triggerParameter = triggerOptions.parameter;
  32075. }
  32076. else {
  32077. this.trigger = triggerOptions;
  32078. }
  32079. this._nextActiveAction = this;
  32080. this._condition = condition;
  32081. }
  32082. // Methods
  32083. Action.prototype._prepare = function () {
  32084. };
  32085. Action.prototype.getTriggerParameter = function () {
  32086. return this._triggerParameter;
  32087. };
  32088. Action.prototype._executeCurrent = function (evt) {
  32089. if (this._nextActiveAction._condition) {
  32090. var condition = this._nextActiveAction._condition;
  32091. var currentRenderId = this._actionManager.getScene().getRenderId();
  32092. // We cache the current evaluation for the current frame
  32093. if (condition._evaluationId === currentRenderId) {
  32094. if (!condition._currentResult) {
  32095. return;
  32096. }
  32097. }
  32098. else {
  32099. condition._evaluationId = currentRenderId;
  32100. if (!condition.isValid()) {
  32101. condition._currentResult = false;
  32102. return;
  32103. }
  32104. condition._currentResult = true;
  32105. }
  32106. }
  32107. this._nextActiveAction.execute(evt);
  32108. this.skipToNextActiveAction();
  32109. };
  32110. Action.prototype.execute = function (evt) {
  32111. };
  32112. Action.prototype.skipToNextActiveAction = function () {
  32113. if (this._nextActiveAction._child) {
  32114. if (!this._nextActiveAction._child._actionManager) {
  32115. this._nextActiveAction._child._actionManager = this._actionManager;
  32116. }
  32117. this._nextActiveAction = this._nextActiveAction._child;
  32118. }
  32119. else {
  32120. this._nextActiveAction = this;
  32121. }
  32122. };
  32123. Action.prototype.then = function (action) {
  32124. this._child = action;
  32125. action._actionManager = this._actionManager;
  32126. action._prepare();
  32127. return action;
  32128. };
  32129. Action.prototype._getProperty = function (propertyPath) {
  32130. return this._actionManager._getProperty(propertyPath);
  32131. };
  32132. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  32133. return this._actionManager._getEffectiveTarget(target, propertyPath);
  32134. };
  32135. Action.prototype.serialize = function (parent) {
  32136. };
  32137. // Called by BABYLON.Action objects in serialize(...). Internal use
  32138. Action.prototype._serialize = function (serializedAction, parent) {
  32139. var serializationObject = {
  32140. type: 1,
  32141. children: [],
  32142. name: serializedAction.name,
  32143. properties: serializedAction.properties || []
  32144. };
  32145. // Serialize child
  32146. if (this._child) {
  32147. this._child.serialize(serializationObject);
  32148. }
  32149. // Check if "this" has a condition
  32150. if (this._condition) {
  32151. var serializedCondition = this._condition.serialize();
  32152. serializedCondition.children.push(serializationObject);
  32153. if (parent) {
  32154. parent.children.push(serializedCondition);
  32155. }
  32156. return serializedCondition;
  32157. }
  32158. if (parent) {
  32159. parent.children.push(serializationObject);
  32160. }
  32161. return serializationObject;
  32162. };
  32163. Action._SerializeValueAsString = function (value) {
  32164. if (typeof value === "number") {
  32165. return value.toString();
  32166. }
  32167. if (typeof value === "boolean") {
  32168. return value ? "true" : "false";
  32169. }
  32170. if (value instanceof BABYLON.Vector2) {
  32171. return value.x + ", " + value.y;
  32172. }
  32173. if (value instanceof BABYLON.Vector3) {
  32174. return value.x + ", " + value.y + ", " + value.z;
  32175. }
  32176. if (value instanceof BABYLON.Color3) {
  32177. return value.r + ", " + value.g + ", " + value.b;
  32178. }
  32179. if (value instanceof BABYLON.Color4) {
  32180. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  32181. }
  32182. return value; // string
  32183. };
  32184. Action._GetTargetProperty = function (target) {
  32185. return {
  32186. name: "target",
  32187. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  32188. : target instanceof BABYLON.Light ? "LightProperties"
  32189. : target instanceof BABYLON.Camera ? "CameraProperties"
  32190. : "SceneProperties",
  32191. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  32192. };
  32193. };
  32194. return Action;
  32195. }());
  32196. BABYLON.Action = Action;
  32197. })(BABYLON || (BABYLON = {}));
  32198. var BABYLON;
  32199. (function (BABYLON) {
  32200. /**
  32201. * ActionEvent is the event beint sent when an action is triggered.
  32202. */
  32203. var ActionEvent = (function () {
  32204. /**
  32205. * @constructor
  32206. * @param source The mesh or sprite that triggered the action.
  32207. * @param pointerX The X mouse cursor position at the time of the event
  32208. * @param pointerY The Y mouse cursor position at the time of the event
  32209. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  32210. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  32211. */
  32212. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  32213. this.source = source;
  32214. this.pointerX = pointerX;
  32215. this.pointerY = pointerY;
  32216. this.meshUnderPointer = meshUnderPointer;
  32217. this.sourceEvent = sourceEvent;
  32218. this.additionalData = additionalData;
  32219. }
  32220. /**
  32221. * Helper function to auto-create an ActionEvent from a source mesh.
  32222. * @param source The source mesh that triggered the event
  32223. * @param evt {Event} The original (browser) event
  32224. */
  32225. ActionEvent.CreateNew = function (source, evt, additionalData) {
  32226. var scene = source.getScene();
  32227. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  32228. };
  32229. /**
  32230. * Helper function to auto-create an ActionEvent from a source mesh.
  32231. * @param source The source sprite that triggered the event
  32232. * @param scene Scene associated with the sprite
  32233. * @param evt {Event} The original (browser) event
  32234. */
  32235. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  32236. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  32237. };
  32238. /**
  32239. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  32240. * @param scene the scene where the event occurred
  32241. * @param evt {Event} The original (browser) event
  32242. */
  32243. ActionEvent.CreateNewFromScene = function (scene, evt) {
  32244. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  32245. };
  32246. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  32247. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  32248. };
  32249. return ActionEvent;
  32250. }());
  32251. BABYLON.ActionEvent = ActionEvent;
  32252. /**
  32253. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  32254. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  32255. */
  32256. var ActionManager = (function () {
  32257. function ActionManager(scene) {
  32258. // Members
  32259. this.actions = new Array();
  32260. this._scene = scene;
  32261. scene._actionManagers.push(this);
  32262. }
  32263. Object.defineProperty(ActionManager, "NothingTrigger", {
  32264. get: function () {
  32265. return ActionManager._NothingTrigger;
  32266. },
  32267. enumerable: true,
  32268. configurable: true
  32269. });
  32270. Object.defineProperty(ActionManager, "OnPickTrigger", {
  32271. get: function () {
  32272. return ActionManager._OnPickTrigger;
  32273. },
  32274. enumerable: true,
  32275. configurable: true
  32276. });
  32277. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  32278. get: function () {
  32279. return ActionManager._OnLeftPickTrigger;
  32280. },
  32281. enumerable: true,
  32282. configurable: true
  32283. });
  32284. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  32285. get: function () {
  32286. return ActionManager._OnRightPickTrigger;
  32287. },
  32288. enumerable: true,
  32289. configurable: true
  32290. });
  32291. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  32292. get: function () {
  32293. return ActionManager._OnCenterPickTrigger;
  32294. },
  32295. enumerable: true,
  32296. configurable: true
  32297. });
  32298. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  32299. get: function () {
  32300. return ActionManager._OnPickDownTrigger;
  32301. },
  32302. enumerable: true,
  32303. configurable: true
  32304. });
  32305. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  32306. get: function () {
  32307. return ActionManager._OnPickUpTrigger;
  32308. },
  32309. enumerable: true,
  32310. configurable: true
  32311. });
  32312. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  32313. /// This trigger will only be raised if you also declared a OnPickDown
  32314. get: function () {
  32315. return ActionManager._OnPickOutTrigger;
  32316. },
  32317. enumerable: true,
  32318. configurable: true
  32319. });
  32320. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  32321. get: function () {
  32322. return ActionManager._OnLongPressTrigger;
  32323. },
  32324. enumerable: true,
  32325. configurable: true
  32326. });
  32327. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  32328. get: function () {
  32329. return ActionManager._OnPointerOverTrigger;
  32330. },
  32331. enumerable: true,
  32332. configurable: true
  32333. });
  32334. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  32335. get: function () {
  32336. return ActionManager._OnPointerOutTrigger;
  32337. },
  32338. enumerable: true,
  32339. configurable: true
  32340. });
  32341. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  32342. get: function () {
  32343. return ActionManager._OnEveryFrameTrigger;
  32344. },
  32345. enumerable: true,
  32346. configurable: true
  32347. });
  32348. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  32349. get: function () {
  32350. return ActionManager._OnIntersectionEnterTrigger;
  32351. },
  32352. enumerable: true,
  32353. configurable: true
  32354. });
  32355. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  32356. get: function () {
  32357. return ActionManager._OnIntersectionExitTrigger;
  32358. },
  32359. enumerable: true,
  32360. configurable: true
  32361. });
  32362. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  32363. get: function () {
  32364. return ActionManager._OnKeyDownTrigger;
  32365. },
  32366. enumerable: true,
  32367. configurable: true
  32368. });
  32369. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  32370. get: function () {
  32371. return ActionManager._OnKeyUpTrigger;
  32372. },
  32373. enumerable: true,
  32374. configurable: true
  32375. });
  32376. // Methods
  32377. ActionManager.prototype.dispose = function () {
  32378. var index = this._scene._actionManagers.indexOf(this);
  32379. if (index > -1) {
  32380. this._scene._actionManagers.splice(index, 1);
  32381. }
  32382. };
  32383. ActionManager.prototype.getScene = function () {
  32384. return this._scene;
  32385. };
  32386. /**
  32387. * Does this action manager handles actions of any of the given triggers
  32388. * @param {number[]} triggers - the triggers to be tested
  32389. * @return {boolean} whether one (or more) of the triggers is handeled
  32390. */
  32391. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  32392. for (var index = 0; index < this.actions.length; index++) {
  32393. var action = this.actions[index];
  32394. if (triggers.indexOf(action.trigger) > -1) {
  32395. return true;
  32396. }
  32397. }
  32398. return false;
  32399. };
  32400. /**
  32401. * Does this action manager handles actions of a given trigger
  32402. * @param {number} trigger - the trigger to be tested
  32403. * @return {boolean} whether the trigger is handeled
  32404. */
  32405. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  32406. for (var index = 0; index < this.actions.length; index++) {
  32407. var action = this.actions[index];
  32408. if (action.trigger === trigger) {
  32409. return true;
  32410. }
  32411. }
  32412. return false;
  32413. };
  32414. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  32415. /**
  32416. * Does this action manager has pointer triggers
  32417. * @return {boolean} whether or not it has pointer triggers
  32418. */
  32419. get: function () {
  32420. for (var index = 0; index < this.actions.length; index++) {
  32421. var action = this.actions[index];
  32422. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  32423. return true;
  32424. }
  32425. }
  32426. return false;
  32427. },
  32428. enumerable: true,
  32429. configurable: true
  32430. });
  32431. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  32432. /**
  32433. * Does this action manager has pick triggers
  32434. * @return {boolean} whether or not it has pick triggers
  32435. */
  32436. get: function () {
  32437. for (var index = 0; index < this.actions.length; index++) {
  32438. var action = this.actions[index];
  32439. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  32440. return true;
  32441. }
  32442. }
  32443. return false;
  32444. },
  32445. enumerable: true,
  32446. configurable: true
  32447. });
  32448. /**
  32449. * Registers an action to this action manager
  32450. * @param {BABYLON.Action} action - the action to be registered
  32451. * @return {BABYLON.Action} the action amended (prepared) after registration
  32452. */
  32453. ActionManager.prototype.registerAction = function (action) {
  32454. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  32455. if (this.getScene().actionManager !== this) {
  32456. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  32457. return null;
  32458. }
  32459. }
  32460. this.actions.push(action);
  32461. action._actionManager = this;
  32462. action._prepare();
  32463. return action;
  32464. };
  32465. /**
  32466. * Process a specific trigger
  32467. * @param {number} trigger - the trigger to process
  32468. * @param evt {BABYLON.ActionEvent} the event details to be processed
  32469. */
  32470. ActionManager.prototype.processTrigger = function (trigger, evt) {
  32471. for (var index = 0; index < this.actions.length; index++) {
  32472. var action = this.actions[index];
  32473. if (action.trigger === trigger) {
  32474. if (trigger === ActionManager.OnKeyUpTrigger
  32475. || trigger === ActionManager.OnKeyDownTrigger) {
  32476. var parameter = action.getTriggerParameter();
  32477. if (parameter) {
  32478. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  32479. var actualkey = String.fromCharCode(unicode).toLowerCase();
  32480. if (actualkey !== parameter.toLowerCase()) {
  32481. continue;
  32482. }
  32483. }
  32484. }
  32485. action._executeCurrent(evt);
  32486. }
  32487. }
  32488. };
  32489. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  32490. var properties = propertyPath.split(".");
  32491. for (var index = 0; index < properties.length - 1; index++) {
  32492. target = target[properties[index]];
  32493. }
  32494. return target;
  32495. };
  32496. ActionManager.prototype._getProperty = function (propertyPath) {
  32497. var properties = propertyPath.split(".");
  32498. return properties[properties.length - 1];
  32499. };
  32500. ActionManager.prototype.serialize = function (name) {
  32501. var root = {
  32502. children: [],
  32503. name: name,
  32504. type: 3,
  32505. properties: [] // Empty for root but required
  32506. };
  32507. for (var i = 0; i < this.actions.length; i++) {
  32508. var triggerObject = {
  32509. type: 0,
  32510. children: [],
  32511. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  32512. properties: []
  32513. };
  32514. var triggerOptions = this.actions[i].triggerOptions;
  32515. if (triggerOptions && typeof triggerOptions !== "number") {
  32516. if (triggerOptions.parameter instanceof BABYLON.Node) {
  32517. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  32518. }
  32519. else {
  32520. triggerObject.properties.push({ name: "parameter", targetType: null, value: triggerOptions.parameter });
  32521. }
  32522. }
  32523. // Serialize child action, recursively
  32524. this.actions[i].serialize(triggerObject);
  32525. // Add serialized trigger
  32526. root.children.push(triggerObject);
  32527. }
  32528. return root;
  32529. };
  32530. ActionManager.Parse = function (parsedActions, object, scene) {
  32531. var actionManager = new BABYLON.ActionManager(scene);
  32532. if (object === null)
  32533. scene.actionManager = actionManager;
  32534. else
  32535. object.actionManager = actionManager;
  32536. // instanciate a new object
  32537. var instanciate = function (name, params) {
  32538. var newInstance = Object.create(BABYLON[name].prototype);
  32539. newInstance.constructor.apply(newInstance, params);
  32540. return newInstance;
  32541. };
  32542. var parseParameter = function (name, value, target, propertyPath) {
  32543. if (propertyPath === null) {
  32544. // String, boolean or float
  32545. var floatValue = parseFloat(value);
  32546. if (value === "true" || value === "false")
  32547. return value === "true";
  32548. else
  32549. return isNaN(floatValue) ? value : floatValue;
  32550. }
  32551. var effectiveTarget = propertyPath.split(".");
  32552. var values = value.split(",");
  32553. // Get effective Target
  32554. for (var i = 0; i < effectiveTarget.length; i++) {
  32555. target = target[effectiveTarget[i]];
  32556. }
  32557. // Return appropriate value with its type
  32558. if (typeof (target) === "boolean")
  32559. return values[0] === "true";
  32560. if (typeof (target) === "string")
  32561. return values[0];
  32562. // Parameters with multiple values such as Vector3 etc.
  32563. var split = new Array();
  32564. for (var i = 0; i < values.length; i++)
  32565. split.push(parseFloat(values[i]));
  32566. if (target instanceof BABYLON.Vector3)
  32567. return BABYLON.Vector3.FromArray(split);
  32568. if (target instanceof BABYLON.Vector4)
  32569. return BABYLON.Vector4.FromArray(split);
  32570. if (target instanceof BABYLON.Color3)
  32571. return BABYLON.Color3.FromArray(split);
  32572. if (target instanceof BABYLON.Color4)
  32573. return BABYLON.Color4.FromArray(split);
  32574. return parseFloat(values[0]);
  32575. };
  32576. // traverse graph per trigger
  32577. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  32578. if (combineArray === void 0) { combineArray = null; }
  32579. if (parsedAction.detached)
  32580. return;
  32581. var parameters = new Array();
  32582. var target = null;
  32583. var propertyPath = null;
  32584. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  32585. // Parameters
  32586. if (parsedAction.type === 2)
  32587. parameters.push(actionManager);
  32588. else
  32589. parameters.push(trigger);
  32590. if (combine) {
  32591. var actions = new Array();
  32592. for (var j = 0; j < parsedAction.combine.length; j++) {
  32593. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  32594. }
  32595. parameters.push(actions);
  32596. }
  32597. else {
  32598. for (var i = 0; i < parsedAction.properties.length; i++) {
  32599. var value = parsedAction.properties[i].value;
  32600. var name = parsedAction.properties[i].name;
  32601. var targetType = parsedAction.properties[i].targetType;
  32602. if (name === "target")
  32603. if (targetType !== null && targetType === "SceneProperties")
  32604. value = target = scene;
  32605. else
  32606. value = target = scene.getNodeByName(value);
  32607. else if (name === "parent")
  32608. value = scene.getNodeByName(value);
  32609. else if (name === "sound")
  32610. value = scene.getSoundByName(value);
  32611. else if (name !== "propertyPath") {
  32612. if (parsedAction.type === 2 && name === "operator")
  32613. value = BABYLON.ValueCondition[value];
  32614. else
  32615. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  32616. }
  32617. else {
  32618. propertyPath = value;
  32619. }
  32620. parameters.push(value);
  32621. }
  32622. }
  32623. if (combineArray === null) {
  32624. parameters.push(condition);
  32625. }
  32626. else {
  32627. parameters.push(null);
  32628. }
  32629. // If interpolate value action
  32630. if (parsedAction.name === "InterpolateValueAction") {
  32631. var param = parameters[parameters.length - 2];
  32632. parameters[parameters.length - 1] = param;
  32633. parameters[parameters.length - 2] = condition;
  32634. }
  32635. // Action or condition(s) and not CombineAction
  32636. var newAction = instanciate(parsedAction.name, parameters);
  32637. if (newAction instanceof BABYLON.Condition && condition !== null) {
  32638. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  32639. if (action)
  32640. action.then(nothing);
  32641. else
  32642. actionManager.registerAction(nothing);
  32643. action = nothing;
  32644. }
  32645. if (combineArray === null) {
  32646. if (newAction instanceof BABYLON.Condition) {
  32647. condition = newAction;
  32648. newAction = action;
  32649. }
  32650. else {
  32651. condition = null;
  32652. if (action)
  32653. action.then(newAction);
  32654. else
  32655. actionManager.registerAction(newAction);
  32656. }
  32657. }
  32658. else {
  32659. combineArray.push(newAction);
  32660. }
  32661. for (var i = 0; i < parsedAction.children.length; i++)
  32662. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  32663. };
  32664. // triggers
  32665. for (var i = 0; i < parsedActions.children.length; i++) {
  32666. var triggerParams;
  32667. var trigger = parsedActions.children[i];
  32668. if (trigger.properties.length > 0) {
  32669. var param = trigger.properties[0].value;
  32670. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  32671. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  32672. }
  32673. else
  32674. triggerParams = BABYLON.ActionManager[trigger.name];
  32675. for (var j = 0; j < trigger.children.length; j++) {
  32676. if (!trigger.detached)
  32677. traverse(trigger.children[j], triggerParams, null, null);
  32678. }
  32679. }
  32680. };
  32681. ActionManager.GetTriggerName = function (trigger) {
  32682. switch (trigger) {
  32683. case 0: return "NothingTrigger";
  32684. case 1: return "OnPickTrigger";
  32685. case 2: return "OnLeftPickTrigger";
  32686. case 3: return "OnRightPickTrigger";
  32687. case 4: return "OnCenterPickTrigger";
  32688. case 5: return "OnPickDownTrigger";
  32689. case 6: return "OnPickUpTrigger";
  32690. case 7: return "OnLongPressTrigger";
  32691. case 8: return "OnPointerOverTrigger";
  32692. case 9: return "OnPointerOutTrigger";
  32693. case 10: return "OnEveryFrameTrigger";
  32694. case 11: return "OnIntersectionEnterTrigger";
  32695. case 12: return "OnIntersectionExitTrigger";
  32696. case 13: return "OnKeyDownTrigger";
  32697. case 14: return "OnKeyUpTrigger";
  32698. case 15: return "OnPickOutTrigger";
  32699. default: return "";
  32700. }
  32701. };
  32702. // Statics
  32703. ActionManager._NothingTrigger = 0;
  32704. ActionManager._OnPickTrigger = 1;
  32705. ActionManager._OnLeftPickTrigger = 2;
  32706. ActionManager._OnRightPickTrigger = 3;
  32707. ActionManager._OnCenterPickTrigger = 4;
  32708. ActionManager._OnPickDownTrigger = 5;
  32709. ActionManager._OnPickUpTrigger = 6;
  32710. ActionManager._OnLongPressTrigger = 7;
  32711. ActionManager._OnPointerOverTrigger = 8;
  32712. ActionManager._OnPointerOutTrigger = 9;
  32713. ActionManager._OnEveryFrameTrigger = 10;
  32714. ActionManager._OnIntersectionEnterTrigger = 11;
  32715. ActionManager._OnIntersectionExitTrigger = 12;
  32716. ActionManager._OnKeyDownTrigger = 13;
  32717. ActionManager._OnKeyUpTrigger = 14;
  32718. ActionManager._OnPickOutTrigger = 15;
  32719. ActionManager.DragMovementThreshold = 10; // in pixels
  32720. ActionManager.LongPressDelay = 500; // in milliseconds
  32721. return ActionManager;
  32722. }());
  32723. BABYLON.ActionManager = ActionManager;
  32724. })(BABYLON || (BABYLON = {}));
  32725. var BABYLON;
  32726. (function (BABYLON) {
  32727. var InterpolateValueAction = (function (_super) {
  32728. __extends(InterpolateValueAction, _super);
  32729. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  32730. if (duration === void 0) { duration = 1000; }
  32731. _super.call(this, triggerOptions, condition);
  32732. this.propertyPath = propertyPath;
  32733. this.value = value;
  32734. this.duration = duration;
  32735. this.stopOtherAnimations = stopOtherAnimations;
  32736. this.onInterpolationDone = onInterpolationDone;
  32737. this._target = this._effectiveTarget = target;
  32738. }
  32739. InterpolateValueAction.prototype._prepare = function () {
  32740. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  32741. this._property = this._getProperty(this.propertyPath);
  32742. };
  32743. InterpolateValueAction.prototype.execute = function () {
  32744. var scene = this._actionManager.getScene();
  32745. var keys = [
  32746. {
  32747. frame: 0,
  32748. value: this._effectiveTarget[this._property]
  32749. }, {
  32750. frame: 100,
  32751. value: this.value
  32752. }
  32753. ];
  32754. var dataType;
  32755. if (typeof this.value === "number") {
  32756. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  32757. }
  32758. else if (this.value instanceof BABYLON.Color3) {
  32759. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  32760. }
  32761. else if (this.value instanceof BABYLON.Vector3) {
  32762. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  32763. }
  32764. else if (this.value instanceof BABYLON.Matrix) {
  32765. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  32766. }
  32767. else if (this.value instanceof BABYLON.Quaternion) {
  32768. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  32769. }
  32770. else {
  32771. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  32772. return;
  32773. }
  32774. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  32775. animation.setKeys(keys);
  32776. if (this.stopOtherAnimations) {
  32777. scene.stopAnimation(this._effectiveTarget);
  32778. }
  32779. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, this.onInterpolationDone);
  32780. };
  32781. InterpolateValueAction.prototype.serialize = function (parent) {
  32782. return _super.prototype._serialize.call(this, {
  32783. name: "InterpolateValueAction",
  32784. properties: [
  32785. BABYLON.Action._GetTargetProperty(this._target),
  32786. { name: "propertyPath", value: this.propertyPath },
  32787. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  32788. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  32789. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  32790. ]
  32791. }, parent);
  32792. };
  32793. return InterpolateValueAction;
  32794. }(BABYLON.Action));
  32795. BABYLON.InterpolateValueAction = InterpolateValueAction;
  32796. })(BABYLON || (BABYLON = {}));
  32797. var BABYLON;
  32798. (function (BABYLON) {
  32799. var SwitchBooleanAction = (function (_super) {
  32800. __extends(SwitchBooleanAction, _super);
  32801. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  32802. _super.call(this, triggerOptions, condition);
  32803. this.propertyPath = propertyPath;
  32804. this._target = this._effectiveTarget = target;
  32805. }
  32806. SwitchBooleanAction.prototype._prepare = function () {
  32807. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  32808. this._property = this._getProperty(this.propertyPath);
  32809. };
  32810. SwitchBooleanAction.prototype.execute = function () {
  32811. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  32812. };
  32813. SwitchBooleanAction.prototype.serialize = function (parent) {
  32814. return _super.prototype._serialize.call(this, {
  32815. name: "SwitchBooleanAction",
  32816. properties: [
  32817. BABYLON.Action._GetTargetProperty(this._target),
  32818. { name: "propertyPath", value: this.propertyPath }
  32819. ]
  32820. }, parent);
  32821. };
  32822. return SwitchBooleanAction;
  32823. }(BABYLON.Action));
  32824. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  32825. var SetStateAction = (function (_super) {
  32826. __extends(SetStateAction, _super);
  32827. function SetStateAction(triggerOptions, target, value, condition) {
  32828. _super.call(this, triggerOptions, condition);
  32829. this.value = value;
  32830. this._target = target;
  32831. }
  32832. SetStateAction.prototype.execute = function () {
  32833. this._target.state = this.value;
  32834. };
  32835. SetStateAction.prototype.serialize = function (parent) {
  32836. return _super.prototype._serialize.call(this, {
  32837. name: "SetStateAction",
  32838. properties: [
  32839. BABYLON.Action._GetTargetProperty(this._target),
  32840. { name: "value", value: this.value }
  32841. ]
  32842. }, parent);
  32843. };
  32844. return SetStateAction;
  32845. }(BABYLON.Action));
  32846. BABYLON.SetStateAction = SetStateAction;
  32847. var SetValueAction = (function (_super) {
  32848. __extends(SetValueAction, _super);
  32849. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  32850. _super.call(this, triggerOptions, condition);
  32851. this.propertyPath = propertyPath;
  32852. this.value = value;
  32853. this._target = this._effectiveTarget = target;
  32854. }
  32855. SetValueAction.prototype._prepare = function () {
  32856. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  32857. this._property = this._getProperty(this.propertyPath);
  32858. };
  32859. SetValueAction.prototype.execute = function () {
  32860. this._effectiveTarget[this._property] = this.value;
  32861. if (this._target.markAsDirty) {
  32862. this._target.markAsDirty(this._property);
  32863. }
  32864. };
  32865. SetValueAction.prototype.serialize = function (parent) {
  32866. return _super.prototype._serialize.call(this, {
  32867. name: "SetValueAction",
  32868. properties: [
  32869. BABYLON.Action._GetTargetProperty(this._target),
  32870. { name: "propertyPath", value: this.propertyPath },
  32871. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  32872. ]
  32873. }, parent);
  32874. };
  32875. return SetValueAction;
  32876. }(BABYLON.Action));
  32877. BABYLON.SetValueAction = SetValueAction;
  32878. var IncrementValueAction = (function (_super) {
  32879. __extends(IncrementValueAction, _super);
  32880. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  32881. _super.call(this, triggerOptions, condition);
  32882. this.propertyPath = propertyPath;
  32883. this.value = value;
  32884. this._target = this._effectiveTarget = target;
  32885. }
  32886. IncrementValueAction.prototype._prepare = function () {
  32887. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  32888. this._property = this._getProperty(this.propertyPath);
  32889. if (typeof this._effectiveTarget[this._property] !== "number") {
  32890. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  32891. }
  32892. };
  32893. IncrementValueAction.prototype.execute = function () {
  32894. this._effectiveTarget[this._property] += this.value;
  32895. if (this._target.markAsDirty) {
  32896. this._target.markAsDirty(this._property);
  32897. }
  32898. };
  32899. IncrementValueAction.prototype.serialize = function (parent) {
  32900. return _super.prototype._serialize.call(this, {
  32901. name: "IncrementValueAction",
  32902. properties: [
  32903. BABYLON.Action._GetTargetProperty(this._target),
  32904. { name: "propertyPath", value: this.propertyPath },
  32905. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  32906. ]
  32907. }, parent);
  32908. };
  32909. return IncrementValueAction;
  32910. }(BABYLON.Action));
  32911. BABYLON.IncrementValueAction = IncrementValueAction;
  32912. var PlayAnimationAction = (function (_super) {
  32913. __extends(PlayAnimationAction, _super);
  32914. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  32915. _super.call(this, triggerOptions, condition);
  32916. this.from = from;
  32917. this.to = to;
  32918. this.loop = loop;
  32919. this._target = target;
  32920. }
  32921. PlayAnimationAction.prototype._prepare = function () {
  32922. };
  32923. PlayAnimationAction.prototype.execute = function () {
  32924. var scene = this._actionManager.getScene();
  32925. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  32926. };
  32927. PlayAnimationAction.prototype.serialize = function (parent) {
  32928. return _super.prototype._serialize.call(this, {
  32929. name: "PlayAnimationAction",
  32930. properties: [
  32931. BABYLON.Action._GetTargetProperty(this._target),
  32932. { name: "from", value: String(this.from) },
  32933. { name: "to", value: String(this.to) },
  32934. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  32935. ]
  32936. }, parent);
  32937. };
  32938. return PlayAnimationAction;
  32939. }(BABYLON.Action));
  32940. BABYLON.PlayAnimationAction = PlayAnimationAction;
  32941. var StopAnimationAction = (function (_super) {
  32942. __extends(StopAnimationAction, _super);
  32943. function StopAnimationAction(triggerOptions, target, condition) {
  32944. _super.call(this, triggerOptions, condition);
  32945. this._target = target;
  32946. }
  32947. StopAnimationAction.prototype._prepare = function () {
  32948. };
  32949. StopAnimationAction.prototype.execute = function () {
  32950. var scene = this._actionManager.getScene();
  32951. scene.stopAnimation(this._target);
  32952. };
  32953. StopAnimationAction.prototype.serialize = function (parent) {
  32954. return _super.prototype._serialize.call(this, {
  32955. name: "StopAnimationAction",
  32956. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  32957. }, parent);
  32958. };
  32959. return StopAnimationAction;
  32960. }(BABYLON.Action));
  32961. BABYLON.StopAnimationAction = StopAnimationAction;
  32962. var DoNothingAction = (function (_super) {
  32963. __extends(DoNothingAction, _super);
  32964. function DoNothingAction(triggerOptions, condition) {
  32965. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  32966. _super.call(this, triggerOptions, condition);
  32967. }
  32968. DoNothingAction.prototype.execute = function () {
  32969. };
  32970. DoNothingAction.prototype.serialize = function (parent) {
  32971. return _super.prototype._serialize.call(this, {
  32972. name: "DoNothingAction",
  32973. properties: []
  32974. }, parent);
  32975. };
  32976. return DoNothingAction;
  32977. }(BABYLON.Action));
  32978. BABYLON.DoNothingAction = DoNothingAction;
  32979. var CombineAction = (function (_super) {
  32980. __extends(CombineAction, _super);
  32981. function CombineAction(triggerOptions, children, condition) {
  32982. _super.call(this, triggerOptions, condition);
  32983. this.children = children;
  32984. }
  32985. CombineAction.prototype._prepare = function () {
  32986. for (var index = 0; index < this.children.length; index++) {
  32987. this.children[index]._actionManager = this._actionManager;
  32988. this.children[index]._prepare();
  32989. }
  32990. };
  32991. CombineAction.prototype.execute = function (evt) {
  32992. for (var index = 0; index < this.children.length; index++) {
  32993. this.children[index].execute(evt);
  32994. }
  32995. };
  32996. CombineAction.prototype.serialize = function (parent) {
  32997. var serializationObject = _super.prototype._serialize.call(this, {
  32998. name: "CombineAction",
  32999. properties: [],
  33000. combine: []
  33001. }, parent);
  33002. for (var i = 0; i < this.children.length; i++) {
  33003. serializationObject.combine.push(this.children[i].serialize(null));
  33004. }
  33005. return serializationObject;
  33006. };
  33007. return CombineAction;
  33008. }(BABYLON.Action));
  33009. BABYLON.CombineAction = CombineAction;
  33010. var ExecuteCodeAction = (function (_super) {
  33011. __extends(ExecuteCodeAction, _super);
  33012. function ExecuteCodeAction(triggerOptions, func, condition) {
  33013. _super.call(this, triggerOptions, condition);
  33014. this.func = func;
  33015. }
  33016. ExecuteCodeAction.prototype.execute = function (evt) {
  33017. this.func(evt);
  33018. };
  33019. return ExecuteCodeAction;
  33020. }(BABYLON.Action));
  33021. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  33022. var SetParentAction = (function (_super) {
  33023. __extends(SetParentAction, _super);
  33024. function SetParentAction(triggerOptions, target, parent, condition) {
  33025. _super.call(this, triggerOptions, condition);
  33026. this._target = target;
  33027. this._parent = parent;
  33028. }
  33029. SetParentAction.prototype._prepare = function () {
  33030. };
  33031. SetParentAction.prototype.execute = function () {
  33032. if (this._target.parent === this._parent) {
  33033. return;
  33034. }
  33035. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  33036. invertParentWorldMatrix.invert();
  33037. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  33038. this._target.parent = this._parent;
  33039. };
  33040. SetParentAction.prototype.serialize = function (parent) {
  33041. return _super.prototype._serialize.call(this, {
  33042. name: "SetParentAction",
  33043. properties: [
  33044. BABYLON.Action._GetTargetProperty(this._target),
  33045. BABYLON.Action._GetTargetProperty(this._parent),
  33046. ]
  33047. }, parent);
  33048. };
  33049. return SetParentAction;
  33050. }(BABYLON.Action));
  33051. BABYLON.SetParentAction = SetParentAction;
  33052. var PlaySoundAction = (function (_super) {
  33053. __extends(PlaySoundAction, _super);
  33054. function PlaySoundAction(triggerOptions, sound, condition) {
  33055. _super.call(this, triggerOptions, condition);
  33056. this._sound = sound;
  33057. }
  33058. PlaySoundAction.prototype._prepare = function () {
  33059. };
  33060. PlaySoundAction.prototype.execute = function () {
  33061. if (this._sound !== undefined)
  33062. this._sound.play();
  33063. };
  33064. PlaySoundAction.prototype.serialize = function (parent) {
  33065. return _super.prototype._serialize.call(this, {
  33066. name: "PlaySoundAction",
  33067. properties: [{ name: "sound", value: this._sound.name }]
  33068. }, parent);
  33069. };
  33070. return PlaySoundAction;
  33071. }(BABYLON.Action));
  33072. BABYLON.PlaySoundAction = PlaySoundAction;
  33073. var StopSoundAction = (function (_super) {
  33074. __extends(StopSoundAction, _super);
  33075. function StopSoundAction(triggerOptions, sound, condition) {
  33076. _super.call(this, triggerOptions, condition);
  33077. this._sound = sound;
  33078. }
  33079. StopSoundAction.prototype._prepare = function () {
  33080. };
  33081. StopSoundAction.prototype.execute = function () {
  33082. if (this._sound !== undefined)
  33083. this._sound.stop();
  33084. };
  33085. StopSoundAction.prototype.serialize = function (parent) {
  33086. return _super.prototype._serialize.call(this, {
  33087. name: "StopSoundAction",
  33088. properties: [{ name: "sound", value: this._sound.name }]
  33089. }, parent);
  33090. };
  33091. return StopSoundAction;
  33092. }(BABYLON.Action));
  33093. BABYLON.StopSoundAction = StopSoundAction;
  33094. })(BABYLON || (BABYLON = {}));
  33095. var BABYLON;
  33096. (function (BABYLON) {
  33097. var Geometry = (function () {
  33098. function Geometry(id, scene, vertexData, updatable, mesh) {
  33099. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  33100. this._totalVertices = 0;
  33101. this._isDisposed = false;
  33102. this.id = id;
  33103. this._engine = scene.getEngine();
  33104. this._meshes = [];
  33105. this._scene = scene;
  33106. //Init vertex buffer cache
  33107. this._vertexBuffers = {};
  33108. this._indices = [];
  33109. // vertexData
  33110. if (vertexData) {
  33111. this.setAllVerticesData(vertexData, updatable);
  33112. }
  33113. else {
  33114. this._totalVertices = 0;
  33115. this._indices = [];
  33116. }
  33117. // applyToMesh
  33118. if (mesh) {
  33119. if (mesh instanceof BABYLON.LinesMesh) {
  33120. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  33121. this.updateExtend();
  33122. }
  33123. this.applyToMesh(mesh);
  33124. mesh.computeWorldMatrix(true);
  33125. }
  33126. }
  33127. Object.defineProperty(Geometry.prototype, "boundingBias", {
  33128. /**
  33129. * 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
  33130. * @returns The Bias Vector
  33131. */
  33132. get: function () {
  33133. return this._boundingBias;
  33134. },
  33135. set: function (value) {
  33136. if (this._boundingBias && this._boundingBias.equals(value)) {
  33137. return;
  33138. }
  33139. this._boundingBias = value.clone();
  33140. this.updateBoundingInfo(true, null);
  33141. },
  33142. enumerable: true,
  33143. configurable: true
  33144. });
  33145. Object.defineProperty(Geometry.prototype, "extend", {
  33146. get: function () {
  33147. return this._extend;
  33148. },
  33149. enumerable: true,
  33150. configurable: true
  33151. });
  33152. Geometry.prototype.getScene = function () {
  33153. return this._scene;
  33154. };
  33155. Geometry.prototype.getEngine = function () {
  33156. return this._engine;
  33157. };
  33158. Geometry.prototype.isReady = function () {
  33159. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  33160. };
  33161. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  33162. vertexData.applyToGeometry(this, updatable);
  33163. this.notifyUpdate();
  33164. };
  33165. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  33166. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  33167. this.setVerticesBuffer(buffer);
  33168. };
  33169. Geometry.prototype.setVerticesBuffer = function (buffer) {
  33170. var kind = buffer.getKind();
  33171. if (this._vertexBuffers[kind]) {
  33172. this._vertexBuffers[kind].dispose();
  33173. }
  33174. this._vertexBuffers[kind] = buffer;
  33175. if (kind === BABYLON.VertexBuffer.PositionKind) {
  33176. var data = buffer.getData();
  33177. var stride = buffer.getStrideSize();
  33178. this._totalVertices = data.length / stride;
  33179. this.updateExtend(data, stride);
  33180. var meshes = this._meshes;
  33181. var numOfMeshes = meshes.length;
  33182. for (var index = 0; index < numOfMeshes; index++) {
  33183. var mesh = meshes[index];
  33184. mesh._resetPointsArrayCache();
  33185. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  33186. mesh._createGlobalSubMesh();
  33187. mesh.computeWorldMatrix(true);
  33188. }
  33189. }
  33190. this.notifyUpdate(kind);
  33191. };
  33192. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  33193. var vertexBuffer = this.getVertexBuffer(kind);
  33194. if (!vertexBuffer) {
  33195. return;
  33196. }
  33197. vertexBuffer.updateDirectly(data, offset);
  33198. this.notifyUpdate(kind);
  33199. };
  33200. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  33201. var vertexBuffer = this.getVertexBuffer(kind);
  33202. if (!vertexBuffer) {
  33203. return;
  33204. }
  33205. vertexBuffer.update(data);
  33206. if (kind === BABYLON.VertexBuffer.PositionKind) {
  33207. var stride = vertexBuffer.getStrideSize();
  33208. this._totalVertices = data.length / stride;
  33209. this.updateBoundingInfo(updateExtends, data);
  33210. }
  33211. this.notifyUpdate(kind);
  33212. };
  33213. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  33214. if (updateExtends) {
  33215. this.updateExtend(data);
  33216. }
  33217. var meshes = this._meshes;
  33218. var numOfMeshes = meshes.length;
  33219. for (var index = 0; index < numOfMeshes; index++) {
  33220. var mesh = meshes[index];
  33221. mesh._resetPointsArrayCache();
  33222. if (updateExtends) {
  33223. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  33224. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  33225. var subMesh = mesh.subMeshes[subIndex];
  33226. subMesh.refreshBoundingInfo();
  33227. }
  33228. }
  33229. }
  33230. };
  33231. Geometry.prototype.getTotalVertices = function () {
  33232. if (!this.isReady()) {
  33233. return 0;
  33234. }
  33235. return this._totalVertices;
  33236. };
  33237. Geometry.prototype.getVerticesData = function (kind, copyWhenShared) {
  33238. var vertexBuffer = this.getVertexBuffer(kind);
  33239. if (!vertexBuffer) {
  33240. return null;
  33241. }
  33242. var orig = vertexBuffer.getData();
  33243. if (!copyWhenShared || this._meshes.length === 1) {
  33244. return orig;
  33245. }
  33246. else {
  33247. var len = orig.length;
  33248. var copy = [];
  33249. for (var i = 0; i < len; i++) {
  33250. copy.push(orig[i]);
  33251. }
  33252. return copy;
  33253. }
  33254. };
  33255. Geometry.prototype.getVertexBuffer = function (kind) {
  33256. if (!this.isReady()) {
  33257. return null;
  33258. }
  33259. return this._vertexBuffers[kind];
  33260. };
  33261. Geometry.prototype.getVertexBuffers = function () {
  33262. if (!this.isReady()) {
  33263. return null;
  33264. }
  33265. return this._vertexBuffers;
  33266. };
  33267. Geometry.prototype.isVerticesDataPresent = function (kind) {
  33268. if (!this._vertexBuffers) {
  33269. if (this._delayInfo) {
  33270. return this._delayInfo.indexOf(kind) !== -1;
  33271. }
  33272. return false;
  33273. }
  33274. return this._vertexBuffers[kind] !== undefined;
  33275. };
  33276. Geometry.prototype.getVerticesDataKinds = function () {
  33277. var result = [];
  33278. var kind;
  33279. if (!this._vertexBuffers && this._delayInfo) {
  33280. for (kind in this._delayInfo) {
  33281. result.push(kind);
  33282. }
  33283. }
  33284. else {
  33285. for (kind in this._vertexBuffers) {
  33286. result.push(kind);
  33287. }
  33288. }
  33289. return result;
  33290. };
  33291. Geometry.prototype.setIndices = function (indices, totalVertices) {
  33292. if (this._indexBuffer) {
  33293. this._engine._releaseBuffer(this._indexBuffer);
  33294. }
  33295. this._indices = indices;
  33296. if (this._meshes.length !== 0 && this._indices) {
  33297. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  33298. }
  33299. if (totalVertices !== undefined) {
  33300. this._totalVertices = totalVertices;
  33301. }
  33302. var meshes = this._meshes;
  33303. var numOfMeshes = meshes.length;
  33304. for (var index = 0; index < numOfMeshes; index++) {
  33305. meshes[index]._createGlobalSubMesh();
  33306. }
  33307. this.notifyUpdate();
  33308. };
  33309. Geometry.prototype.getTotalIndices = function () {
  33310. if (!this.isReady()) {
  33311. return 0;
  33312. }
  33313. return this._indices.length;
  33314. };
  33315. Geometry.prototype.getIndices = function (copyWhenShared) {
  33316. if (!this.isReady()) {
  33317. return null;
  33318. }
  33319. var orig = this._indices;
  33320. if (!copyWhenShared || this._meshes.length === 1) {
  33321. return orig;
  33322. }
  33323. else {
  33324. var len = orig.length;
  33325. var copy = [];
  33326. for (var i = 0; i < len; i++) {
  33327. copy.push(orig[i]);
  33328. }
  33329. return copy;
  33330. }
  33331. };
  33332. Geometry.prototype.getIndexBuffer = function () {
  33333. if (!this.isReady()) {
  33334. return null;
  33335. }
  33336. return this._indexBuffer;
  33337. };
  33338. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  33339. var meshes = this._meshes;
  33340. var index = meshes.indexOf(mesh);
  33341. if (index === -1) {
  33342. return;
  33343. }
  33344. for (var kind in this._vertexBuffers) {
  33345. this._vertexBuffers[kind].dispose();
  33346. }
  33347. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  33348. this._indexBuffer = null;
  33349. }
  33350. meshes.splice(index, 1);
  33351. mesh._geometry = null;
  33352. if (meshes.length === 0 && shouldDispose) {
  33353. this.dispose();
  33354. }
  33355. };
  33356. Geometry.prototype.applyToMesh = function (mesh) {
  33357. if (mesh._geometry === this) {
  33358. return;
  33359. }
  33360. var previousGeometry = mesh._geometry;
  33361. if (previousGeometry) {
  33362. previousGeometry.releaseForMesh(mesh);
  33363. }
  33364. var meshes = this._meshes;
  33365. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  33366. mesh._geometry = this;
  33367. this._scene.pushGeometry(this);
  33368. meshes.push(mesh);
  33369. if (this.isReady()) {
  33370. this._applyToMesh(mesh);
  33371. }
  33372. else {
  33373. mesh._boundingInfo = this._boundingInfo;
  33374. }
  33375. };
  33376. Geometry.prototype.updateExtend = function (data, stride) {
  33377. if (data === void 0) { data = null; }
  33378. if (!data) {
  33379. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  33380. }
  33381. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  33382. };
  33383. Geometry.prototype._applyToMesh = function (mesh) {
  33384. var numOfMeshes = this._meshes.length;
  33385. // vertexBuffers
  33386. for (var kind in this._vertexBuffers) {
  33387. if (numOfMeshes === 1) {
  33388. this._vertexBuffers[kind].create();
  33389. }
  33390. this._vertexBuffers[kind].getBuffer().references = numOfMeshes;
  33391. if (kind === BABYLON.VertexBuffer.PositionKind) {
  33392. mesh._resetPointsArrayCache();
  33393. if (!this._extend) {
  33394. this.updateExtend(this._vertexBuffers[kind].getData());
  33395. }
  33396. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  33397. mesh._createGlobalSubMesh();
  33398. //bounding info was just created again, world matrix should be applied again.
  33399. mesh._updateBoundingInfo();
  33400. }
  33401. }
  33402. // indexBuffer
  33403. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  33404. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  33405. }
  33406. if (this._indexBuffer) {
  33407. this._indexBuffer.references = numOfMeshes;
  33408. }
  33409. };
  33410. Geometry.prototype.notifyUpdate = function (kind) {
  33411. if (this.onGeometryUpdated) {
  33412. this.onGeometryUpdated(this, kind);
  33413. }
  33414. };
  33415. Geometry.prototype.load = function (scene, onLoaded) {
  33416. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  33417. return;
  33418. }
  33419. if (this.isReady()) {
  33420. if (onLoaded) {
  33421. onLoaded();
  33422. }
  33423. return;
  33424. }
  33425. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  33426. this._queueLoad(scene, onLoaded);
  33427. };
  33428. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  33429. var _this = this;
  33430. scene._addPendingData(this);
  33431. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  33432. _this._delayLoadingFunction(JSON.parse(data), _this);
  33433. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  33434. _this._delayInfo = [];
  33435. scene._removePendingData(_this);
  33436. var meshes = _this._meshes;
  33437. var numOfMeshes = meshes.length;
  33438. for (var index = 0; index < numOfMeshes; index++) {
  33439. _this._applyToMesh(meshes[index]);
  33440. }
  33441. if (onLoaded) {
  33442. onLoaded();
  33443. }
  33444. }, function () { }, scene.database);
  33445. };
  33446. /**
  33447. * Invert the geometry to move from a right handed system to a left handed one.
  33448. */
  33449. Geometry.prototype.toLeftHanded = function () {
  33450. // Flip faces
  33451. var tIndices = this.getIndices(false);
  33452. if (tIndices != null && tIndices.length > 0) {
  33453. for (var i = 0; i < tIndices.length; i += 3) {
  33454. var tTemp = tIndices[i + 0];
  33455. tIndices[i + 0] = tIndices[i + 2];
  33456. tIndices[i + 2] = tTemp;
  33457. }
  33458. this.setIndices(tIndices);
  33459. }
  33460. // Negate position.z
  33461. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  33462. if (tPositions != null && tPositions.length > 0) {
  33463. for (var i = 0; i < tPositions.length; i += 3) {
  33464. tPositions[i + 2] = -tPositions[i + 2];
  33465. }
  33466. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  33467. }
  33468. // Negate normal.z
  33469. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  33470. if (tNormals != null && tNormals.length > 0) {
  33471. for (var i = 0; i < tNormals.length; i += 3) {
  33472. tNormals[i + 2] = -tNormals[i + 2];
  33473. }
  33474. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  33475. }
  33476. };
  33477. Geometry.prototype.isDisposed = function () {
  33478. return this._isDisposed;
  33479. };
  33480. Geometry.prototype.dispose = function () {
  33481. var meshes = this._meshes;
  33482. var numOfMeshes = meshes.length;
  33483. var index;
  33484. for (index = 0; index < numOfMeshes; index++) {
  33485. this.releaseForMesh(meshes[index]);
  33486. }
  33487. this._meshes = [];
  33488. for (var kind in this._vertexBuffers) {
  33489. this._vertexBuffers[kind].dispose();
  33490. }
  33491. this._vertexBuffers = {};
  33492. this._totalVertices = 0;
  33493. if (this._indexBuffer) {
  33494. this._engine._releaseBuffer(this._indexBuffer);
  33495. }
  33496. this._indexBuffer = null;
  33497. this._indices = [];
  33498. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  33499. this.delayLoadingFile = null;
  33500. this._delayLoadingFunction = null;
  33501. this._delayInfo = [];
  33502. this._boundingInfo = null;
  33503. this._scene.removeGeometry(this);
  33504. this._isDisposed = true;
  33505. };
  33506. Geometry.prototype.copy = function (id) {
  33507. var vertexData = new BABYLON.VertexData();
  33508. vertexData.indices = [];
  33509. var indices = this.getIndices();
  33510. for (var index = 0; index < indices.length; index++) {
  33511. vertexData.indices.push(indices[index]);
  33512. }
  33513. var updatable = false;
  33514. var stopChecking = false;
  33515. var kind;
  33516. for (kind in this._vertexBuffers) {
  33517. // using slice() to make a copy of the array and not just reference it
  33518. var data = this.getVerticesData(kind);
  33519. if (data instanceof Float32Array) {
  33520. vertexData.set(new Float32Array(data), kind);
  33521. }
  33522. else {
  33523. vertexData.set(data.slice(0), kind);
  33524. }
  33525. if (!stopChecking) {
  33526. updatable = this.getVertexBuffer(kind).isUpdatable();
  33527. stopChecking = !updatable;
  33528. }
  33529. }
  33530. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  33531. geometry.delayLoadState = this.delayLoadState;
  33532. geometry.delayLoadingFile = this.delayLoadingFile;
  33533. geometry._delayLoadingFunction = this._delayLoadingFunction;
  33534. for (kind in this._delayInfo) {
  33535. geometry._delayInfo = geometry._delayInfo || [];
  33536. geometry._delayInfo.push(kind);
  33537. }
  33538. // Bounding info
  33539. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  33540. return geometry;
  33541. };
  33542. Geometry.prototype.serialize = function () {
  33543. var serializationObject = {};
  33544. serializationObject.id = this.id;
  33545. if (BABYLON.Tags.HasTags(this)) {
  33546. serializationObject.tags = BABYLON.Tags.GetTags(this);
  33547. }
  33548. return serializationObject;
  33549. };
  33550. Geometry.prototype.serializeVerticeData = function () {
  33551. var serializationObject = this.serialize();
  33552. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  33553. serializationObject.positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33554. }
  33555. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  33556. serializationObject.normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33557. }
  33558. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  33559. serializationObject.uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  33560. }
  33561. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  33562. serializationObject.uvs2 = this.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  33563. }
  33564. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  33565. serializationObject.uvs3 = this.getVerticesData(BABYLON.VertexBuffer.UV3Kind);
  33566. }
  33567. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  33568. serializationObject.uvs4 = this.getVerticesData(BABYLON.VertexBuffer.UV4Kind);
  33569. }
  33570. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  33571. serializationObject.uvs5 = this.getVerticesData(BABYLON.VertexBuffer.UV5Kind);
  33572. }
  33573. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  33574. serializationObject.uvs6 = this.getVerticesData(BABYLON.VertexBuffer.UV6Kind);
  33575. }
  33576. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  33577. serializationObject.colors = this.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  33578. }
  33579. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  33580. serializationObject.matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  33581. serializationObject.matricesIndices._isExpanded = true;
  33582. }
  33583. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  33584. serializationObject.matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  33585. }
  33586. serializationObject.indices = this.getIndices();
  33587. return serializationObject;
  33588. };
  33589. // Statics
  33590. Geometry.ExtractFromMesh = function (mesh, id) {
  33591. var geometry = mesh._geometry;
  33592. if (!geometry) {
  33593. return null;
  33594. }
  33595. return geometry.copy(id);
  33596. };
  33597. // from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  33598. // be aware Math.random() could cause collisions
  33599. Geometry.RandomId = function () {
  33600. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  33601. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  33602. return v.toString(16);
  33603. });
  33604. };
  33605. Geometry.ImportGeometry = function (parsedGeometry, mesh) {
  33606. var scene = mesh.getScene();
  33607. // Geometry
  33608. var geometryId = parsedGeometry.geometryId;
  33609. if (geometryId) {
  33610. var geometry = scene.getGeometryByID(geometryId);
  33611. if (geometry) {
  33612. geometry.applyToMesh(mesh);
  33613. }
  33614. }
  33615. else if (parsedGeometry instanceof ArrayBuffer) {
  33616. var binaryInfo = mesh._binaryInfo;
  33617. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  33618. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  33619. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  33620. }
  33621. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  33622. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  33623. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  33624. }
  33625. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  33626. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  33627. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  33628. }
  33629. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  33630. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  33631. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  33632. }
  33633. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  33634. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  33635. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  33636. }
  33637. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  33638. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  33639. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  33640. }
  33641. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  33642. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  33643. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  33644. }
  33645. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  33646. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  33647. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  33648. }
  33649. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  33650. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  33651. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  33652. }
  33653. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  33654. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  33655. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  33656. }
  33657. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  33658. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  33659. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  33660. }
  33661. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  33662. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  33663. mesh.setIndices(indicesData);
  33664. }
  33665. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  33666. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  33667. mesh.subMeshes = [];
  33668. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  33669. var materialIndex = subMeshesData[(i * 5) + 0];
  33670. var verticesStart = subMeshesData[(i * 5) + 1];
  33671. var verticesCount = subMeshesData[(i * 5) + 2];
  33672. var indexStart = subMeshesData[(i * 5) + 3];
  33673. var indexCount = subMeshesData[(i * 5) + 4];
  33674. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  33675. }
  33676. }
  33677. }
  33678. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  33679. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  33680. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  33681. if (parsedGeometry.uvs) {
  33682. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  33683. }
  33684. if (parsedGeometry.uvs2) {
  33685. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  33686. }
  33687. if (parsedGeometry.uvs3) {
  33688. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, false);
  33689. }
  33690. if (parsedGeometry.uvs4) {
  33691. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, false);
  33692. }
  33693. if (parsedGeometry.uvs5) {
  33694. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, false);
  33695. }
  33696. if (parsedGeometry.uvs6) {
  33697. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, false);
  33698. }
  33699. if (parsedGeometry.colors) {
  33700. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), false);
  33701. }
  33702. if (parsedGeometry.matricesIndices) {
  33703. if (!parsedGeometry.matricesIndices._isExpanded) {
  33704. var floatIndices = [];
  33705. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  33706. var matricesIndex = parsedGeometry.matricesIndices[i];
  33707. floatIndices.push(matricesIndex & 0x000000FF);
  33708. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  33709. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  33710. floatIndices.push(matricesIndex >> 24);
  33711. }
  33712. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  33713. }
  33714. else {
  33715. delete parsedGeometry.matricesIndices._isExpanded;
  33716. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  33717. }
  33718. }
  33719. if (parsedGeometry.matricesIndicesExtra) {
  33720. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  33721. var floatIndices = [];
  33722. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  33723. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  33724. floatIndices.push(matricesIndex & 0x000000FF);
  33725. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  33726. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  33727. floatIndices.push(matricesIndex >> 24);
  33728. }
  33729. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, false);
  33730. }
  33731. else {
  33732. delete parsedGeometry.matricesIndices._isExpanded;
  33733. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, false);
  33734. }
  33735. }
  33736. if (parsedGeometry.matricesWeights) {
  33737. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  33738. }
  33739. if (parsedGeometry.matricesWeightsExtra) {
  33740. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, false);
  33741. }
  33742. mesh.setIndices(parsedGeometry.indices);
  33743. }
  33744. // SubMeshes
  33745. if (parsedGeometry.subMeshes) {
  33746. mesh.subMeshes = [];
  33747. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  33748. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  33749. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  33750. }
  33751. }
  33752. // Flat shading
  33753. if (mesh._shouldGenerateFlatShading) {
  33754. mesh.convertToFlatShadedMesh();
  33755. delete mesh._shouldGenerateFlatShading;
  33756. }
  33757. // Update
  33758. mesh.computeWorldMatrix(true);
  33759. // Octree
  33760. if (scene['_selectionOctree']) {
  33761. scene['_selectionOctree'].addMesh(mesh);
  33762. }
  33763. };
  33764. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  33765. if (scene.getGeometryByID(parsedVertexData.id)) {
  33766. return null; // null since geometry could be something else than a box...
  33767. }
  33768. var geometry = new Geometry(parsedVertexData.id, scene);
  33769. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  33770. if (parsedVertexData.delayLoadingFile) {
  33771. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  33772. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  33773. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  33774. geometry._delayInfo = [];
  33775. if (parsedVertexData.hasUVs) {
  33776. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  33777. }
  33778. if (parsedVertexData.hasUVs2) {
  33779. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  33780. }
  33781. if (parsedVertexData.hasUVs3) {
  33782. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  33783. }
  33784. if (parsedVertexData.hasUVs4) {
  33785. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  33786. }
  33787. if (parsedVertexData.hasUVs5) {
  33788. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  33789. }
  33790. if (parsedVertexData.hasUVs6) {
  33791. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  33792. }
  33793. if (parsedVertexData.hasColors) {
  33794. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  33795. }
  33796. if (parsedVertexData.hasMatricesIndices) {
  33797. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  33798. }
  33799. if (parsedVertexData.hasMatricesWeights) {
  33800. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  33801. }
  33802. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  33803. }
  33804. else {
  33805. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  33806. }
  33807. scene.pushGeometry(geometry, true);
  33808. return geometry;
  33809. };
  33810. return Geometry;
  33811. }());
  33812. BABYLON.Geometry = Geometry;
  33813. /////// Primitives //////////////////////////////////////////////
  33814. var Geometry;
  33815. (function (Geometry) {
  33816. var Primitives;
  33817. (function (Primitives) {
  33818. /// Abstract class
  33819. var _Primitive = (function (_super) {
  33820. __extends(_Primitive, _super);
  33821. function _Primitive(id, scene, _canBeRegenerated, mesh) {
  33822. _super.call(this, id, scene, null, false, mesh); // updatable = false to be sure not to update vertices
  33823. this._canBeRegenerated = _canBeRegenerated;
  33824. this._beingRegenerated = true;
  33825. this.regenerate();
  33826. this._beingRegenerated = false;
  33827. }
  33828. _Primitive.prototype.canBeRegenerated = function () {
  33829. return this._canBeRegenerated;
  33830. };
  33831. _Primitive.prototype.regenerate = function () {
  33832. if (!this._canBeRegenerated) {
  33833. return;
  33834. }
  33835. this._beingRegenerated = true;
  33836. this.setAllVerticesData(this._regenerateVertexData(), false);
  33837. this._beingRegenerated = false;
  33838. };
  33839. _Primitive.prototype.asNewGeometry = function (id) {
  33840. return _super.prototype.copy.call(this, id);
  33841. };
  33842. // overrides
  33843. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  33844. if (!this._beingRegenerated) {
  33845. return;
  33846. }
  33847. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  33848. };
  33849. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  33850. if (!this._beingRegenerated) {
  33851. return;
  33852. }
  33853. _super.prototype.setVerticesData.call(this, kind, data, false);
  33854. };
  33855. // to override
  33856. // protected
  33857. _Primitive.prototype._regenerateVertexData = function () {
  33858. throw new Error("Abstract method");
  33859. };
  33860. _Primitive.prototype.copy = function (id) {
  33861. throw new Error("Must be overriden in sub-classes.");
  33862. };
  33863. _Primitive.prototype.serialize = function () {
  33864. var serializationObject = _super.prototype.serialize.call(this);
  33865. serializationObject.canBeRegenerated = this.canBeRegenerated();
  33866. return serializationObject;
  33867. };
  33868. return _Primitive;
  33869. }(Geometry));
  33870. Primitives._Primitive = _Primitive;
  33871. var Ribbon = (function (_super) {
  33872. __extends(Ribbon, _super);
  33873. // Members
  33874. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  33875. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  33876. _super.call(this, id, scene, canBeRegenerated, mesh);
  33877. this.pathArray = pathArray;
  33878. this.closeArray = closeArray;
  33879. this.closePath = closePath;
  33880. this.offset = offset;
  33881. this.side = side;
  33882. }
  33883. Ribbon.prototype._regenerateVertexData = function () {
  33884. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  33885. };
  33886. Ribbon.prototype.copy = function (id) {
  33887. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  33888. };
  33889. return Ribbon;
  33890. }(_Primitive));
  33891. Primitives.Ribbon = Ribbon;
  33892. var Box = (function (_super) {
  33893. __extends(Box, _super);
  33894. // Members
  33895. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  33896. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  33897. _super.call(this, id, scene, canBeRegenerated, mesh);
  33898. this.size = size;
  33899. this.side = side;
  33900. }
  33901. Box.prototype._regenerateVertexData = function () {
  33902. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  33903. };
  33904. Box.prototype.copy = function (id) {
  33905. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  33906. };
  33907. Box.prototype.serialize = function () {
  33908. var serializationObject = _super.prototype.serialize.call(this);
  33909. serializationObject.size = this.size;
  33910. return serializationObject;
  33911. };
  33912. Box.Parse = function (parsedBox, scene) {
  33913. if (scene.getGeometryByID(parsedBox.id)) {
  33914. return null; // null since geometry could be something else than a box...
  33915. }
  33916. var box = new Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  33917. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  33918. scene.pushGeometry(box, true);
  33919. return box;
  33920. };
  33921. return Box;
  33922. }(_Primitive));
  33923. Primitives.Box = Box;
  33924. var Sphere = (function (_super) {
  33925. __extends(Sphere, _super);
  33926. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  33927. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  33928. _super.call(this, id, scene, canBeRegenerated, mesh);
  33929. this.segments = segments;
  33930. this.diameter = diameter;
  33931. this.side = side;
  33932. }
  33933. Sphere.prototype._regenerateVertexData = function () {
  33934. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  33935. };
  33936. Sphere.prototype.copy = function (id) {
  33937. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  33938. };
  33939. Sphere.prototype.serialize = function () {
  33940. var serializationObject = _super.prototype.serialize.call(this);
  33941. serializationObject.segments = this.segments;
  33942. serializationObject.diameter = this.diameter;
  33943. return serializationObject;
  33944. };
  33945. Sphere.Parse = function (parsedSphere, scene) {
  33946. if (scene.getGeometryByID(parsedSphere.id)) {
  33947. return null; // null since geometry could be something else than a sphere...
  33948. }
  33949. var sphere = new Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  33950. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  33951. scene.pushGeometry(sphere, true);
  33952. return sphere;
  33953. };
  33954. return Sphere;
  33955. }(_Primitive));
  33956. Primitives.Sphere = Sphere;
  33957. var Disc = (function (_super) {
  33958. __extends(Disc, _super);
  33959. // Members
  33960. function Disc(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  33961. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  33962. _super.call(this, id, scene, canBeRegenerated, mesh);
  33963. this.radius = radius;
  33964. this.tessellation = tessellation;
  33965. this.side = side;
  33966. }
  33967. Disc.prototype._regenerateVertexData = function () {
  33968. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  33969. };
  33970. Disc.prototype.copy = function (id) {
  33971. return new Disc(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  33972. };
  33973. return Disc;
  33974. }(_Primitive));
  33975. Primitives.Disc = Disc;
  33976. var Cylinder = (function (_super) {
  33977. __extends(Cylinder, _super);
  33978. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  33979. if (subdivisions === void 0) { subdivisions = 1; }
  33980. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  33981. _super.call(this, id, scene, canBeRegenerated, mesh);
  33982. this.height = height;
  33983. this.diameterTop = diameterTop;
  33984. this.diameterBottom = diameterBottom;
  33985. this.tessellation = tessellation;
  33986. this.subdivisions = subdivisions;
  33987. this.side = side;
  33988. }
  33989. Cylinder.prototype._regenerateVertexData = function () {
  33990. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  33991. };
  33992. Cylinder.prototype.copy = function (id) {
  33993. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  33994. };
  33995. Cylinder.prototype.serialize = function () {
  33996. var serializationObject = _super.prototype.serialize.call(this);
  33997. serializationObject.height = this.height;
  33998. serializationObject.diameterTop = this.diameterTop;
  33999. serializationObject.diameterBottom = this.diameterBottom;
  34000. serializationObject.tessellation = this.tessellation;
  34001. return serializationObject;
  34002. };
  34003. Cylinder.Parse = function (parsedCylinder, scene) {
  34004. if (scene.getGeometryByID(parsedCylinder.id)) {
  34005. return null; // null since geometry could be something else than a cylinder...
  34006. }
  34007. var cylinder = new Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  34008. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  34009. scene.pushGeometry(cylinder, true);
  34010. return cylinder;
  34011. };
  34012. return Cylinder;
  34013. }(_Primitive));
  34014. Primitives.Cylinder = Cylinder;
  34015. var Torus = (function (_super) {
  34016. __extends(Torus, _super);
  34017. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  34018. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  34019. _super.call(this, id, scene, canBeRegenerated, mesh);
  34020. this.diameter = diameter;
  34021. this.thickness = thickness;
  34022. this.tessellation = tessellation;
  34023. this.side = side;
  34024. }
  34025. Torus.prototype._regenerateVertexData = function () {
  34026. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  34027. };
  34028. Torus.prototype.copy = function (id) {
  34029. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  34030. };
  34031. Torus.prototype.serialize = function () {
  34032. var serializationObject = _super.prototype.serialize.call(this);
  34033. serializationObject.diameter = this.diameter;
  34034. serializationObject.thickness = this.thickness;
  34035. serializationObject.tessellation = this.tessellation;
  34036. return serializationObject;
  34037. };
  34038. Torus.Parse = function (parsedTorus, scene) {
  34039. if (scene.getGeometryByID(parsedTorus.id)) {
  34040. return null; // null since geometry could be something else than a torus...
  34041. }
  34042. var torus = new Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  34043. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  34044. scene.pushGeometry(torus, true);
  34045. return torus;
  34046. };
  34047. return Torus;
  34048. }(_Primitive));
  34049. Primitives.Torus = Torus;
  34050. var Ground = (function (_super) {
  34051. __extends(Ground, _super);
  34052. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  34053. _super.call(this, id, scene, canBeRegenerated, mesh);
  34054. this.width = width;
  34055. this.height = height;
  34056. this.subdivisions = subdivisions;
  34057. }
  34058. Ground.prototype._regenerateVertexData = function () {
  34059. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  34060. };
  34061. Ground.prototype.copy = function (id) {
  34062. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  34063. };
  34064. Ground.prototype.serialize = function () {
  34065. var serializationObject = _super.prototype.serialize.call(this);
  34066. serializationObject.width = this.width;
  34067. serializationObject.height = this.height;
  34068. serializationObject.subdivisions = this.subdivisions;
  34069. return serializationObject;
  34070. };
  34071. Ground.Parse = function (parsedGround, scene) {
  34072. if (scene.getGeometryByID(parsedGround.id)) {
  34073. return null; // null since geometry could be something else than a ground...
  34074. }
  34075. var ground = new Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  34076. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  34077. scene.pushGeometry(ground, true);
  34078. return ground;
  34079. };
  34080. return Ground;
  34081. }(_Primitive));
  34082. Primitives.Ground = Ground;
  34083. var TiledGround = (function (_super) {
  34084. __extends(TiledGround, _super);
  34085. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  34086. _super.call(this, id, scene, canBeRegenerated, mesh);
  34087. this.xmin = xmin;
  34088. this.zmin = zmin;
  34089. this.xmax = xmax;
  34090. this.zmax = zmax;
  34091. this.subdivisions = subdivisions;
  34092. this.precision = precision;
  34093. }
  34094. TiledGround.prototype._regenerateVertexData = function () {
  34095. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  34096. };
  34097. TiledGround.prototype.copy = function (id) {
  34098. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  34099. };
  34100. return TiledGround;
  34101. }(_Primitive));
  34102. Primitives.TiledGround = TiledGround;
  34103. var Plane = (function (_super) {
  34104. __extends(Plane, _super);
  34105. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  34106. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  34107. _super.call(this, id, scene, canBeRegenerated, mesh);
  34108. this.size = size;
  34109. this.side = side;
  34110. }
  34111. Plane.prototype._regenerateVertexData = function () {
  34112. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  34113. };
  34114. Plane.prototype.copy = function (id) {
  34115. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  34116. };
  34117. Plane.prototype.serialize = function () {
  34118. var serializationObject = _super.prototype.serialize.call(this);
  34119. serializationObject.size = this.size;
  34120. return serializationObject;
  34121. };
  34122. Plane.Parse = function (parsedPlane, scene) {
  34123. if (scene.getGeometryByID(parsedPlane.id)) {
  34124. return null; // null since geometry could be something else than a ground...
  34125. }
  34126. var plane = new Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  34127. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  34128. scene.pushGeometry(plane, true);
  34129. return plane;
  34130. };
  34131. return Plane;
  34132. }(_Primitive));
  34133. Primitives.Plane = Plane;
  34134. var TorusKnot = (function (_super) {
  34135. __extends(TorusKnot, _super);
  34136. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  34137. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  34138. _super.call(this, id, scene, canBeRegenerated, mesh);
  34139. this.radius = radius;
  34140. this.tube = tube;
  34141. this.radialSegments = radialSegments;
  34142. this.tubularSegments = tubularSegments;
  34143. this.p = p;
  34144. this.q = q;
  34145. this.side = side;
  34146. }
  34147. TorusKnot.prototype._regenerateVertexData = function () {
  34148. 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 });
  34149. };
  34150. TorusKnot.prototype.copy = function (id) {
  34151. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  34152. };
  34153. TorusKnot.prototype.serialize = function () {
  34154. var serializationObject = _super.prototype.serialize.call(this);
  34155. serializationObject.radius = this.radius;
  34156. serializationObject.tube = this.tube;
  34157. serializationObject.radialSegments = this.radialSegments;
  34158. serializationObject.tubularSegments = this.tubularSegments;
  34159. serializationObject.p = this.p;
  34160. serializationObject.q = this.q;
  34161. return serializationObject;
  34162. };
  34163. ;
  34164. TorusKnot.Parse = function (parsedTorusKnot, scene) {
  34165. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  34166. return null; // null since geometry could be something else than a ground...
  34167. }
  34168. var torusKnot = new Geometry.Primitives.TorusKnot(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  34169. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  34170. scene.pushGeometry(torusKnot, true);
  34171. return torusKnot;
  34172. };
  34173. return TorusKnot;
  34174. }(_Primitive));
  34175. Primitives.TorusKnot = TorusKnot;
  34176. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  34177. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  34178. })(BABYLON || (BABYLON = {}));
  34179. var BABYLON;
  34180. (function (BABYLON) {
  34181. var GroundMesh = (function (_super) {
  34182. __extends(GroundMesh, _super);
  34183. function GroundMesh(name, scene) {
  34184. _super.call(this, name, scene);
  34185. this.generateOctree = false;
  34186. this._worldInverse = new BABYLON.Matrix();
  34187. }
  34188. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  34189. get: function () {
  34190. return this._subdivisions;
  34191. },
  34192. enumerable: true,
  34193. configurable: true
  34194. });
  34195. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  34196. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  34197. this._subdivisions = chunksCount;
  34198. this.subdivide(this._subdivisions);
  34199. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  34200. };
  34201. /**
  34202. * Returns a height (y) value in the Worl system :
  34203. * the ground altitude at the coordinates (x, z) expressed in the World system.
  34204. * Returns the ground y position if (x, z) are outside the ground surface.
  34205. * Not pertinent if the ground is rotated.
  34206. */
  34207. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  34208. // express x and y in the ground local system
  34209. x -= this.position.x;
  34210. z -= this.position.z;
  34211. x /= this.scaling.x;
  34212. z /= this.scaling.z;
  34213. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  34214. return this.position.y;
  34215. }
  34216. if (!this._heightQuads || this._heightQuads.length == 0) {
  34217. this._initHeightQuads();
  34218. this._computeHeightQuads();
  34219. }
  34220. var facet = this._getFacetAt(x, z);
  34221. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  34222. // return y in the World system
  34223. return y * this.scaling.y + this.position.y;
  34224. };
  34225. /**
  34226. * Returns a normalized vector (Vector3) orthogonal to the ground
  34227. * at the ground coordinates (x, z) expressed in the World system.
  34228. * Returns Vector3(0, 1, 0) if (x, z) are outside the ground surface.
  34229. * Not pertinent if the ground is rotated.
  34230. */
  34231. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  34232. var normal = new BABYLON.Vector3(0, 1, 0);
  34233. this.getNormalAtCoordinatesToRef(x, z, normal);
  34234. return normal;
  34235. };
  34236. /**
  34237. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  34238. * at the ground coordinates (x, z) expressed in the World system.
  34239. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  34240. * Not pertinent if the ground is rotated.
  34241. */
  34242. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  34243. // express x and y in the ground local system
  34244. x -= this.position.x;
  34245. z -= this.position.z;
  34246. x /= this.scaling.x;
  34247. z /= this.scaling.z;
  34248. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  34249. return;
  34250. }
  34251. if (!this._heightQuads || this._heightQuads.length == 0) {
  34252. this._initHeightQuads();
  34253. this._computeHeightQuads();
  34254. }
  34255. var facet = this._getFacetAt(x, z);
  34256. ref.x = facet.x;
  34257. ref.y = facet.y;
  34258. ref.z = facet.z;
  34259. };
  34260. /**
  34261. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  34262. * if the ground has been updated.
  34263. * This can be used in the render loop
  34264. */
  34265. GroundMesh.prototype.updateCoordinateHeights = function () {
  34266. if (!this._heightQuads || this._heightQuads.length == 0) {
  34267. this._initHeightQuads();
  34268. }
  34269. this._computeHeightQuads();
  34270. };
  34271. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  34272. GroundMesh.prototype._getFacetAt = function (x, z) {
  34273. // retrieve col and row from x, z coordinates in the ground local system
  34274. var col = Math.floor((x + this._maxX) * this._subdivisions / this._width);
  34275. var row = Math.floor(-(z + this._maxZ) * this._subdivisions / this._height + this._subdivisions);
  34276. var quad = this._heightQuads[row * this._subdivisions + col];
  34277. var facet;
  34278. if (z < quad.slope.x * x + quad.slope.y) {
  34279. facet = quad.facet1;
  34280. }
  34281. else {
  34282. facet = quad.facet2;
  34283. }
  34284. return facet;
  34285. };
  34286. // Creates and populates the heightMap array with "facet" elements :
  34287. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  34288. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  34289. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  34290. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  34291. GroundMesh.prototype._initHeightQuads = function () {
  34292. this._heightQuads = new Array();
  34293. for (var row = 0; row < this._subdivisions; row++) {
  34294. for (var col = 0; col < this._subdivisions; col++) {
  34295. var quad = { slope: BABYLON.Vector2.Zero(), facet1: new BABYLON.Vector4(0, 0, 0, 0), facet2: new BABYLON.Vector4(0, 0, 0, 0) };
  34296. this._heightQuads[row * this._subdivisions + col] = quad;
  34297. }
  34298. }
  34299. };
  34300. // Compute each quad element values and update the the heightMap array :
  34301. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  34302. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  34303. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  34304. GroundMesh.prototype._computeHeightQuads = function () {
  34305. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34306. var v1 = BABYLON.Tmp.Vector3[3];
  34307. var v2 = BABYLON.Tmp.Vector3[2];
  34308. var v3 = BABYLON.Tmp.Vector3[1];
  34309. var v4 = BABYLON.Tmp.Vector3[0];
  34310. var v1v2 = BABYLON.Tmp.Vector3[4];
  34311. var v1v3 = BABYLON.Tmp.Vector3[5];
  34312. var v1v4 = BABYLON.Tmp.Vector3[6];
  34313. var norm1 = BABYLON.Tmp.Vector3[7];
  34314. var norm2 = BABYLON.Tmp.Vector3[8];
  34315. var i = 0;
  34316. var j = 0;
  34317. var k = 0;
  34318. var cd = 0; // 2D slope coefficient : z = cd * x + h
  34319. var h = 0;
  34320. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  34321. var d2 = 0;
  34322. for (var row = 0; row < this._subdivisions; row++) {
  34323. for (var col = 0; col < this._subdivisions; col++) {
  34324. i = col * 3;
  34325. j = row * (this._subdivisions + 1) * 3;
  34326. k = (row + 1) * (this._subdivisions + 1) * 3;
  34327. v1.x = positions[j + i];
  34328. v1.y = positions[j + i + 1];
  34329. v1.z = positions[j + i + 2];
  34330. v2.x = positions[j + i + 3];
  34331. v2.y = positions[j + i + 4];
  34332. v2.z = positions[j + i + 5];
  34333. v3.x = positions[k + i];
  34334. v3.y = positions[k + i + 1];
  34335. v3.z = positions[k + i + 2];
  34336. v4.x = positions[k + i + 3];
  34337. v4.y = positions[k + i + 4];
  34338. v4.z = positions[k + i + 5];
  34339. // 2D slope V1V4
  34340. cd = (v4.z - v1.z) / (v4.x - v1.x);
  34341. h = v1.z - cd * v1.x; // v1 belongs to the slope
  34342. // facet equations :
  34343. // we compute each facet normal vector
  34344. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  34345. // we compute the value d by applying the equation to v1 which belongs to the plane
  34346. // then we store the facet equation in a Vector4
  34347. v2.subtractToRef(v1, v1v2);
  34348. v3.subtractToRef(v1, v1v3);
  34349. v4.subtractToRef(v1, v1v4);
  34350. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  34351. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  34352. norm1.normalize();
  34353. norm2.normalize();
  34354. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  34355. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  34356. var quad = this._heightQuads[row * this._subdivisions + col];
  34357. quad.slope.copyFromFloats(cd, h);
  34358. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  34359. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  34360. }
  34361. }
  34362. };
  34363. return GroundMesh;
  34364. }(BABYLON.Mesh));
  34365. BABYLON.GroundMesh = GroundMesh;
  34366. })(BABYLON || (BABYLON = {}));
  34367. var BABYLON;
  34368. (function (BABYLON) {
  34369. var LinesMesh = (function (_super) {
  34370. __extends(LinesMesh, _super);
  34371. function LinesMesh(name, scene, parent, source, doNotCloneChildren) {
  34372. if (parent === void 0) { parent = null; }
  34373. _super.call(this, name, scene, parent, source, doNotCloneChildren);
  34374. this.color = new BABYLON.Color3(1, 1, 1);
  34375. this.alpha = 1;
  34376. this._positionBuffer = {};
  34377. if (source) {
  34378. this.color = source.color.clone();
  34379. this.alpha = source.alpha;
  34380. }
  34381. this._intersectionThreshold = 0.1;
  34382. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  34383. attributes: [BABYLON.VertexBuffer.PositionKind],
  34384. uniforms: ["worldViewProjection", "color"],
  34385. needAlphaBlending: true
  34386. });
  34387. this._positionBuffer[BABYLON.VertexBuffer.PositionKind] = null;
  34388. }
  34389. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  34390. /**
  34391. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  34392. * This margin is expressed in world space coordinates, so its value may vary.
  34393. * Default value is 0.1
  34394. * @returns the intersection Threshold value.
  34395. */
  34396. get: function () {
  34397. return this._intersectionThreshold;
  34398. },
  34399. /**
  34400. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  34401. * This margin is expressed in world space coordinates, so its value may vary.
  34402. * @param value the new threshold to apply
  34403. */
  34404. set: function (value) {
  34405. if (this._intersectionThreshold === value) {
  34406. return;
  34407. }
  34408. this._intersectionThreshold = value;
  34409. if (this.geometry) {
  34410. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  34411. }
  34412. },
  34413. enumerable: true,
  34414. configurable: true
  34415. });
  34416. Object.defineProperty(LinesMesh.prototype, "material", {
  34417. get: function () {
  34418. return this._colorShader;
  34419. },
  34420. enumerable: true,
  34421. configurable: true
  34422. });
  34423. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  34424. get: function () {
  34425. return false;
  34426. },
  34427. enumerable: true,
  34428. configurable: true
  34429. });
  34430. LinesMesh.prototype.createInstance = function (name) {
  34431. BABYLON.Tools.Log("LinesMeshes do not support createInstance.");
  34432. return null;
  34433. };
  34434. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  34435. var engine = this.getScene().getEngine();
  34436. this._positionBuffer[BABYLON.VertexBuffer.PositionKind] = this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind);
  34437. // VBOs
  34438. engine.bindBuffers(this._positionBuffer, this._geometry.getIndexBuffer(), this._colorShader.getEffect());
  34439. // Color
  34440. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  34441. };
  34442. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  34443. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  34444. return;
  34445. }
  34446. var engine = this.getScene().getEngine();
  34447. // Draw order
  34448. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  34449. };
  34450. LinesMesh.prototype.dispose = function (doNotRecurse) {
  34451. this._colorShader.dispose();
  34452. _super.prototype.dispose.call(this, doNotRecurse);
  34453. };
  34454. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  34455. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  34456. };
  34457. return LinesMesh;
  34458. }(BABYLON.Mesh));
  34459. BABYLON.LinesMesh = LinesMesh;
  34460. })(BABYLON || (BABYLON = {}));
  34461. var BABYLON;
  34462. (function (BABYLON) {
  34463. var DefaultLoadingScreen = (function () {
  34464. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  34465. var _this = this;
  34466. if (_loadingText === void 0) { _loadingText = ""; }
  34467. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  34468. this._renderingCanvas = _renderingCanvas;
  34469. this._loadingText = _loadingText;
  34470. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  34471. // Resize
  34472. this._resizeLoadingUI = function () {
  34473. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  34474. _this._loadingDiv.style.position = "absolute";
  34475. _this._loadingDiv.style.left = canvasRect.left + "px";
  34476. _this._loadingDiv.style.top = canvasRect.top + "px";
  34477. _this._loadingDiv.style.width = canvasRect.width + "px";
  34478. _this._loadingDiv.style.height = canvasRect.height + "px";
  34479. };
  34480. }
  34481. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  34482. var _this = this;
  34483. if (this._loadingDiv) {
  34484. // Do not add a loading screen if there is already one
  34485. return;
  34486. }
  34487. this._loadingDiv = document.createElement("div");
  34488. this._loadingDiv.id = "babylonjsLoadingDiv";
  34489. this._loadingDiv.style.opacity = "0";
  34490. this._loadingDiv.style.transition = "opacity 1.5s ease";
  34491. // Loading text
  34492. this._loadingTextDiv = document.createElement("div");
  34493. this._loadingTextDiv.style.position = "absolute";
  34494. this._loadingTextDiv.style.left = "0";
  34495. this._loadingTextDiv.style.top = "50%";
  34496. this._loadingTextDiv.style.marginTop = "80px";
  34497. this._loadingTextDiv.style.width = "100%";
  34498. this._loadingTextDiv.style.height = "20px";
  34499. this._loadingTextDiv.style.fontFamily = "Arial";
  34500. this._loadingTextDiv.style.fontSize = "14px";
  34501. this._loadingTextDiv.style.color = "white";
  34502. this._loadingTextDiv.style.textAlign = "center";
  34503. this._loadingTextDiv.innerHTML = "Loading";
  34504. this._loadingDiv.appendChild(this._loadingTextDiv);
  34505. //set the predefined text
  34506. this._loadingTextDiv.innerHTML = this._loadingText;
  34507. // Loading img
  34508. var imgBack = new Image();
  34509. 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==";
  34510. imgBack.style.position = "absolute";
  34511. imgBack.style.left = "50%";
  34512. imgBack.style.top = "50%";
  34513. imgBack.style.marginLeft = "-50px";
  34514. imgBack.style.marginTop = "-50px";
  34515. imgBack.style.transition = "transform 1.0s ease";
  34516. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  34517. var deg = 360;
  34518. var onTransitionEnd = function () {
  34519. deg += 360;
  34520. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  34521. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  34522. };
  34523. imgBack.addEventListener("transitionend", onTransitionEnd);
  34524. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  34525. this._loadingDiv.appendChild(imgBack);
  34526. // front image
  34527. var imgFront = new Image();
  34528. 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=";
  34529. imgFront.style.position = "absolute";
  34530. imgFront.style.left = "50%";
  34531. imgFront.style.top = "50%";
  34532. imgFront.style.marginLeft = "-50px";
  34533. imgFront.style.marginTop = "-50px";
  34534. this._loadingDiv.appendChild(imgFront);
  34535. this._resizeLoadingUI();
  34536. window.addEventListener("resize", this._resizeLoadingUI);
  34537. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  34538. document.body.appendChild(this._loadingDiv);
  34539. setTimeout(function () {
  34540. _this._loadingDiv.style.opacity = "1";
  34541. imgBack.style.transform = "rotateZ(360deg)";
  34542. imgBack.style.webkitTransform = "rotateZ(360deg)";
  34543. }, 0);
  34544. };
  34545. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  34546. var _this = this;
  34547. if (!this._loadingDiv) {
  34548. return;
  34549. }
  34550. var onTransitionEnd = function () {
  34551. if (!_this._loadingDiv) {
  34552. return;
  34553. }
  34554. document.body.removeChild(_this._loadingDiv);
  34555. window.removeEventListener("resize", _this._resizeLoadingUI);
  34556. _this._loadingDiv = null;
  34557. };
  34558. this._loadingDiv.style.opacity = "0";
  34559. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  34560. };
  34561. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  34562. set: function (text) {
  34563. this._loadingText = text;
  34564. if (this._loadingTextDiv) {
  34565. this._loadingTextDiv.innerHTML = this._loadingText;
  34566. }
  34567. },
  34568. enumerable: true,
  34569. configurable: true
  34570. });
  34571. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  34572. get: function () {
  34573. return this._loadingDivBackgroundColor;
  34574. },
  34575. set: function (color) {
  34576. this._loadingDivBackgroundColor = color;
  34577. if (!this._loadingDiv) {
  34578. return;
  34579. }
  34580. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  34581. },
  34582. enumerable: true,
  34583. configurable: true
  34584. });
  34585. return DefaultLoadingScreen;
  34586. }());
  34587. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  34588. })(BABYLON || (BABYLON = {}));
  34589. var BABYLON;
  34590. (function (BABYLON) {
  34591. var AudioEngine = (function () {
  34592. function AudioEngine() {
  34593. this._audioContext = null;
  34594. this._audioContextInitialized = false;
  34595. this.canUseWebAudio = false;
  34596. this.WarnedWebAudioUnsupported = false;
  34597. this.unlocked = false;
  34598. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  34599. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  34600. this.canUseWebAudio = true;
  34601. }
  34602. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  34603. this._unlockiOSaudio();
  34604. }
  34605. else {
  34606. this.unlocked = true;
  34607. }
  34608. }
  34609. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  34610. get: function () {
  34611. if (!this._audioContextInitialized) {
  34612. this._initializeAudioContext();
  34613. }
  34614. return this._audioContext;
  34615. },
  34616. enumerable: true,
  34617. configurable: true
  34618. });
  34619. AudioEngine.prototype._unlockiOSaudio = function () {
  34620. var _this = this;
  34621. var unlockaudio = function () {
  34622. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  34623. var source = _this.audioContext.createBufferSource();
  34624. source.buffer = buffer;
  34625. source.connect(_this.audioContext.destination);
  34626. source.start(0);
  34627. setTimeout(function () {
  34628. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  34629. _this.unlocked = true;
  34630. window.removeEventListener('touchend', unlockaudio, false);
  34631. if (_this.onAudioUnlocked) {
  34632. _this.onAudioUnlocked();
  34633. }
  34634. }
  34635. }, 0);
  34636. };
  34637. window.addEventListener('touchend', unlockaudio, false);
  34638. };
  34639. AudioEngine.prototype._initializeAudioContext = function () {
  34640. try {
  34641. if (this.canUseWebAudio) {
  34642. this._audioContext = new AudioContext();
  34643. // create a global volume gain node
  34644. this.masterGain = this._audioContext.createGain();
  34645. this.masterGain.gain.value = 1;
  34646. this.masterGain.connect(this._audioContext.destination);
  34647. this._audioContextInitialized = true;
  34648. }
  34649. }
  34650. catch (e) {
  34651. this.canUseWebAudio = false;
  34652. BABYLON.Tools.Error("Web Audio: " + e.message);
  34653. }
  34654. };
  34655. AudioEngine.prototype.dispose = function () {
  34656. if (this.canUseWebAudio && this._audioContextInitialized) {
  34657. if (this._connectedAnalyser) {
  34658. this._connectedAnalyser.stopDebugCanvas();
  34659. this._connectedAnalyser.dispose();
  34660. this.masterGain.disconnect();
  34661. this.masterGain.connect(this._audioContext.destination);
  34662. this._connectedAnalyser = null;
  34663. }
  34664. this.masterGain.gain.value = 1;
  34665. }
  34666. this.WarnedWebAudioUnsupported = false;
  34667. };
  34668. AudioEngine.prototype.getGlobalVolume = function () {
  34669. if (this.canUseWebAudio && this._audioContextInitialized) {
  34670. return this.masterGain.gain.value;
  34671. }
  34672. else {
  34673. return -1;
  34674. }
  34675. };
  34676. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  34677. if (this.canUseWebAudio && this._audioContextInitialized) {
  34678. this.masterGain.gain.value = newVolume;
  34679. }
  34680. };
  34681. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  34682. if (this._connectedAnalyser) {
  34683. this._connectedAnalyser.stopDebugCanvas();
  34684. }
  34685. if (this.canUseWebAudio && this._audioContextInitialized) {
  34686. this._connectedAnalyser = analyser;
  34687. this.masterGain.disconnect();
  34688. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  34689. }
  34690. };
  34691. return AudioEngine;
  34692. }());
  34693. BABYLON.AudioEngine = AudioEngine;
  34694. })(BABYLON || (BABYLON = {}));
  34695. var BABYLON;
  34696. (function (BABYLON) {
  34697. var Sound = (function () {
  34698. /**
  34699. * Create a sound and attach it to a scene
  34700. * @param name Name of your sound
  34701. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  34702. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  34703. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  34704. */
  34705. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  34706. var _this = this;
  34707. this.autoplay = false;
  34708. this.loop = false;
  34709. this.useCustomAttenuation = false;
  34710. this.spatialSound = false;
  34711. this.refDistance = 1;
  34712. this.rolloffFactor = 1;
  34713. this.maxDistance = 100;
  34714. this.distanceModel = "linear";
  34715. this._panningModel = "equalpower";
  34716. this._playbackRate = 1;
  34717. this._streaming = false;
  34718. this._startTime = 0;
  34719. this._startOffset = 0;
  34720. this._position = BABYLON.Vector3.Zero();
  34721. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  34722. this._volume = 1;
  34723. this._isLoaded = false;
  34724. this._isReadyToPlay = false;
  34725. this.isPlaying = false;
  34726. this.isPaused = false;
  34727. this._isDirectional = false;
  34728. // Used if you'd like to create a directional sound.
  34729. // If not set, the sound will be omnidirectional
  34730. this._coneInnerAngle = 360;
  34731. this._coneOuterAngle = 360;
  34732. this._coneOuterGain = 0;
  34733. this._isOutputConnected = false;
  34734. this.name = name;
  34735. this._scene = scene;
  34736. this._readyToPlayCallback = readyToPlayCallback;
  34737. // Default custom attenuation function is a linear attenuation
  34738. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  34739. if (currentDistance < maxDistance) {
  34740. return currentVolume * (1 - currentDistance / maxDistance);
  34741. }
  34742. else {
  34743. return 0;
  34744. }
  34745. };
  34746. if (options) {
  34747. this.autoplay = options.autoplay || false;
  34748. this.loop = options.loop || false;
  34749. // if volume === 0, we need another way to check this option
  34750. if (options.volume !== undefined) {
  34751. this._volume = options.volume;
  34752. }
  34753. this.spatialSound = options.spatialSound || false;
  34754. this.maxDistance = options.maxDistance || 100;
  34755. this.useCustomAttenuation = options.useCustomAttenuation || false;
  34756. this.rolloffFactor = options.rolloffFactor || 1;
  34757. this.refDistance = options.refDistance || 1;
  34758. this.distanceModel = options.distanceModel || "linear";
  34759. this._playbackRate = options.playbackRate || 1;
  34760. this._streaming = options.streaming || false;
  34761. }
  34762. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34763. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  34764. this._soundGain.gain.value = this._volume;
  34765. this._inputAudioNode = this._soundGain;
  34766. this._ouputAudioNode = this._soundGain;
  34767. if (this.spatialSound) {
  34768. this._createSpatialParameters();
  34769. }
  34770. this._scene.mainSoundTrack.AddSound(this);
  34771. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  34772. if (urlOrArrayBuffer) {
  34773. // If it's an URL
  34774. if (typeof (urlOrArrayBuffer) === "string") {
  34775. // Loading sound using XHR2
  34776. if (!this._streaming) {
  34777. BABYLON.Tools.LoadFile(urlOrArrayBuffer, function (data) { _this._soundLoaded(data); }, null, this._scene.database, true);
  34778. }
  34779. else {
  34780. this._htmlAudioElement = new Audio(urlOrArrayBuffer);
  34781. this._htmlAudioElement.controls = false;
  34782. this._htmlAudioElement.loop = this.loop;
  34783. this._htmlAudioElement.crossOrigin = "anonymous";
  34784. this._htmlAudioElement.preload = "auto";
  34785. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  34786. _this._isReadyToPlay = true;
  34787. if (_this.autoplay) {
  34788. _this.play();
  34789. }
  34790. if (_this._readyToPlayCallback) {
  34791. _this._readyToPlayCallback();
  34792. }
  34793. });
  34794. document.body.appendChild(this._htmlAudioElement);
  34795. }
  34796. }
  34797. else {
  34798. if (urlOrArrayBuffer instanceof ArrayBuffer) {
  34799. if (urlOrArrayBuffer.byteLength > 0) {
  34800. this._soundLoaded(urlOrArrayBuffer);
  34801. }
  34802. }
  34803. else {
  34804. BABYLON.Tools.Error("Parameter must be a URL to the sound or an ArrayBuffer of the sound.");
  34805. }
  34806. }
  34807. }
  34808. }
  34809. else {
  34810. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  34811. this._scene.mainSoundTrack.AddSound(this);
  34812. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  34813. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  34814. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  34815. }
  34816. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  34817. if (this._readyToPlayCallback) {
  34818. window.setTimeout(function () {
  34819. _this._readyToPlayCallback();
  34820. }, 1000);
  34821. }
  34822. }
  34823. }
  34824. Sound.prototype.dispose = function () {
  34825. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  34826. if (this.isPlaying) {
  34827. this.stop();
  34828. }
  34829. this._isReadyToPlay = false;
  34830. if (this.soundTrackId === -1) {
  34831. this._scene.mainSoundTrack.RemoveSound(this);
  34832. }
  34833. else {
  34834. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  34835. }
  34836. if (this._soundGain) {
  34837. this._soundGain.disconnect();
  34838. this._soundGain = null;
  34839. }
  34840. if (this._soundPanner) {
  34841. this._soundPanner.disconnect();
  34842. this._soundPanner = null;
  34843. }
  34844. if (this._soundSource) {
  34845. this._soundSource.disconnect();
  34846. this._soundSource = null;
  34847. }
  34848. this._audioBuffer = null;
  34849. if (this._htmlAudioElement) {
  34850. this._htmlAudioElement.pause();
  34851. this._htmlAudioElement.src = "";
  34852. document.body.removeChild(this._htmlAudioElement);
  34853. }
  34854. if (this._connectedMesh) {
  34855. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  34856. this._connectedMesh = null;
  34857. }
  34858. }
  34859. };
  34860. Sound.prototype._soundLoaded = function (audioData) {
  34861. var _this = this;
  34862. this._isLoaded = true;
  34863. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  34864. _this._audioBuffer = buffer;
  34865. _this._isReadyToPlay = true;
  34866. if (_this.autoplay) {
  34867. _this.play();
  34868. }
  34869. if (_this._readyToPlayCallback) {
  34870. _this._readyToPlayCallback();
  34871. }
  34872. }, function () { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name); });
  34873. };
  34874. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  34875. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34876. this._audioBuffer = audioBuffer;
  34877. this._isReadyToPlay = true;
  34878. }
  34879. };
  34880. Sound.prototype.updateOptions = function (options) {
  34881. if (options) {
  34882. this.loop = options.loop || this.loop;
  34883. this.maxDistance = options.maxDistance || this.maxDistance;
  34884. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  34885. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  34886. this.refDistance = options.refDistance || this.refDistance;
  34887. this.distanceModel = options.distanceModel || this.distanceModel;
  34888. this._playbackRate = options.playbackRate || this._playbackRate;
  34889. this._updateSpatialParameters();
  34890. if (this.isPlaying) {
  34891. if (this._streaming) {
  34892. this._htmlAudioElement.playbackRate = this._playbackRate;
  34893. }
  34894. else {
  34895. this._soundSource.playbackRate.value = this._playbackRate;
  34896. }
  34897. }
  34898. }
  34899. };
  34900. Sound.prototype._createSpatialParameters = function () {
  34901. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34902. if (this._scene.headphone) {
  34903. this._panningModel = "HRTF";
  34904. }
  34905. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  34906. this._updateSpatialParameters();
  34907. this._soundPanner.connect(this._ouputAudioNode);
  34908. this._inputAudioNode = this._soundPanner;
  34909. }
  34910. };
  34911. Sound.prototype._updateSpatialParameters = function () {
  34912. if (this.spatialSound) {
  34913. if (this.useCustomAttenuation) {
  34914. // Tricks to disable in a way embedded Web Audio attenuation
  34915. this._soundPanner.distanceModel = "linear";
  34916. this._soundPanner.maxDistance = Number.MAX_VALUE;
  34917. this._soundPanner.refDistance = 1;
  34918. this._soundPanner.rolloffFactor = 1;
  34919. this._soundPanner.panningModel = this._panningModel;
  34920. }
  34921. else {
  34922. this._soundPanner.distanceModel = this.distanceModel;
  34923. this._soundPanner.maxDistance = this.maxDistance;
  34924. this._soundPanner.refDistance = this.refDistance;
  34925. this._soundPanner.rolloffFactor = this.rolloffFactor;
  34926. this._soundPanner.panningModel = this._panningModel;
  34927. }
  34928. }
  34929. };
  34930. Sound.prototype.switchPanningModelToHRTF = function () {
  34931. this._panningModel = "HRTF";
  34932. this._switchPanningModel();
  34933. };
  34934. Sound.prototype.switchPanningModelToEqualPower = function () {
  34935. this._panningModel = "equalpower";
  34936. this._switchPanningModel();
  34937. };
  34938. Sound.prototype._switchPanningModel = function () {
  34939. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  34940. this._soundPanner.panningModel = this._panningModel;
  34941. }
  34942. };
  34943. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  34944. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34945. if (this._isOutputConnected) {
  34946. this._ouputAudioNode.disconnect();
  34947. }
  34948. this._ouputAudioNode.connect(soundTrackAudioNode);
  34949. this._isOutputConnected = true;
  34950. }
  34951. };
  34952. /**
  34953. * Transform this sound into a directional source
  34954. * @param coneInnerAngle Size of the inner cone in degree
  34955. * @param coneOuterAngle Size of the outer cone in degree
  34956. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  34957. */
  34958. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  34959. if (coneOuterAngle < coneInnerAngle) {
  34960. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  34961. return;
  34962. }
  34963. this._coneInnerAngle = coneInnerAngle;
  34964. this._coneOuterAngle = coneOuterAngle;
  34965. this._coneOuterGain = coneOuterGain;
  34966. this._isDirectional = true;
  34967. if (this.isPlaying && this.loop) {
  34968. this.stop();
  34969. this.play();
  34970. }
  34971. };
  34972. Sound.prototype.setPosition = function (newPosition) {
  34973. this._position = newPosition;
  34974. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  34975. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  34976. }
  34977. };
  34978. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  34979. this._localDirection = newLocalDirection;
  34980. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  34981. this._updateDirection();
  34982. }
  34983. };
  34984. Sound.prototype._updateDirection = function () {
  34985. var mat = this._connectedMesh.getWorldMatrix();
  34986. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  34987. direction.normalize();
  34988. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  34989. };
  34990. Sound.prototype.updateDistanceFromListener = function () {
  34991. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation) {
  34992. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  34993. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  34994. }
  34995. };
  34996. Sound.prototype.setAttenuationFunction = function (callback) {
  34997. this._customAttenuationFunction = callback;
  34998. };
  34999. /**
  35000. * Play the sound
  35001. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  35002. * @param offset (optional) Start the sound setting it at a specific time
  35003. */
  35004. Sound.prototype.play = function (time, offset) {
  35005. var _this = this;
  35006. if (this._isReadyToPlay && this._scene.audioEnabled) {
  35007. try {
  35008. if (this._startOffset < 0) {
  35009. time = -this._startOffset;
  35010. this._startOffset = 0;
  35011. }
  35012. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  35013. if (!this._soundSource || !this._streamingSource) {
  35014. if (this.spatialSound) {
  35015. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  35016. if (this._isDirectional) {
  35017. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  35018. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  35019. this._soundPanner.coneOuterGain = this._coneOuterGain;
  35020. if (this._connectedMesh) {
  35021. this._updateDirection();
  35022. }
  35023. else {
  35024. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  35025. }
  35026. }
  35027. }
  35028. }
  35029. if (this._streaming) {
  35030. if (!this._streamingSource) {
  35031. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  35032. this._htmlAudioElement.onended = function () { _this._onended(); };
  35033. this._htmlAudioElement.playbackRate = this._playbackRate;
  35034. }
  35035. this._streamingSource.disconnect();
  35036. this._streamingSource.connect(this._inputAudioNode);
  35037. this._htmlAudioElement.play();
  35038. }
  35039. else {
  35040. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  35041. this._soundSource.buffer = this._audioBuffer;
  35042. this._soundSource.connect(this._inputAudioNode);
  35043. this._soundSource.loop = this.loop;
  35044. this._soundSource.playbackRate.value = this._playbackRate;
  35045. this._soundSource.onended = function () { _this._onended(); };
  35046. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  35047. }
  35048. this._startTime = startTime;
  35049. this.isPlaying = true;
  35050. this.isPaused = false;
  35051. }
  35052. catch (ex) {
  35053. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  35054. }
  35055. }
  35056. };
  35057. Sound.prototype._onended = function () {
  35058. this.isPlaying = false;
  35059. if (this.onended) {
  35060. this.onended();
  35061. }
  35062. };
  35063. /**
  35064. * Stop the sound
  35065. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  35066. */
  35067. Sound.prototype.stop = function (time) {
  35068. if (this.isPlaying) {
  35069. if (this._streaming) {
  35070. this._htmlAudioElement.pause();
  35071. // Test needed for Firefox or it will generate an Invalid State Error
  35072. if (this._htmlAudioElement.currentTime > 0) {
  35073. this._htmlAudioElement.currentTime = 0;
  35074. }
  35075. }
  35076. else {
  35077. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  35078. this._soundSource.stop(stopTime);
  35079. this._soundSource.onended = null;
  35080. if (!this.isPaused) {
  35081. this._startOffset = 0;
  35082. }
  35083. }
  35084. this.isPlaying = false;
  35085. }
  35086. };
  35087. Sound.prototype.pause = function () {
  35088. if (this.isPlaying) {
  35089. this.isPaused = true;
  35090. if (this._streaming) {
  35091. this._htmlAudioElement.pause();
  35092. }
  35093. else {
  35094. this.stop(0);
  35095. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  35096. }
  35097. }
  35098. };
  35099. Sound.prototype.setVolume = function (newVolume, time) {
  35100. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  35101. if (time) {
  35102. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  35103. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  35104. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  35105. }
  35106. else {
  35107. this._soundGain.gain.value = newVolume;
  35108. }
  35109. }
  35110. this._volume = newVolume;
  35111. };
  35112. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  35113. this._playbackRate = newPlaybackRate;
  35114. if (this.isPlaying) {
  35115. if (this._streaming) {
  35116. this._htmlAudioElement.playbackRate = this._playbackRate;
  35117. }
  35118. else {
  35119. this._soundSource.playbackRate.value = this._playbackRate;
  35120. }
  35121. }
  35122. };
  35123. Sound.prototype.getVolume = function () {
  35124. return this._volume;
  35125. };
  35126. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  35127. var _this = this;
  35128. if (this._connectedMesh) {
  35129. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  35130. this._registerFunc = null;
  35131. }
  35132. this._connectedMesh = meshToConnectTo;
  35133. if (!this.spatialSound) {
  35134. this.spatialSound = true;
  35135. this._createSpatialParameters();
  35136. if (this.isPlaying && this.loop) {
  35137. this.stop();
  35138. this.play();
  35139. }
  35140. }
  35141. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  35142. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  35143. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  35144. };
  35145. Sound.prototype.detachFromMesh = function () {
  35146. if (this._connectedMesh) {
  35147. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  35148. this._registerFunc = null;
  35149. this._connectedMesh = null;
  35150. }
  35151. };
  35152. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  35153. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  35154. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  35155. this._updateDirection();
  35156. }
  35157. };
  35158. Sound.prototype.clone = function () {
  35159. var _this = this;
  35160. if (!this._streaming) {
  35161. var setBufferAndRun = function () {
  35162. if (_this._isReadyToPlay) {
  35163. clonedSound._audioBuffer = _this.getAudioBuffer();
  35164. clonedSound._isReadyToPlay = true;
  35165. if (clonedSound.autoplay) {
  35166. clonedSound.play();
  35167. }
  35168. }
  35169. else {
  35170. window.setTimeout(setBufferAndRun, 300);
  35171. }
  35172. };
  35173. var currentOptions = {
  35174. autoplay: this.autoplay, loop: this.loop,
  35175. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  35176. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  35177. refDistance: this.refDistance, distanceModel: this.distanceModel
  35178. };
  35179. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  35180. if (this.useCustomAttenuation) {
  35181. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  35182. }
  35183. clonedSound.setPosition(this._position);
  35184. clonedSound.setPlaybackRate(this._playbackRate);
  35185. setBufferAndRun();
  35186. return clonedSound;
  35187. }
  35188. else {
  35189. return null;
  35190. }
  35191. };
  35192. Sound.prototype.getAudioBuffer = function () {
  35193. return this._audioBuffer;
  35194. };
  35195. Sound.prototype.serialize = function () {
  35196. var serializationObject = {
  35197. name: this.name,
  35198. url: this.name,
  35199. autoplay: this.autoplay,
  35200. loop: this.loop,
  35201. volume: this._volume,
  35202. spatialSound: this.spatialSound,
  35203. maxDistance: this.maxDistance,
  35204. rolloffFactor: this.rolloffFactor,
  35205. refDistance: this.refDistance,
  35206. distanceModel: this.distanceModel,
  35207. playbackRate: this._playbackRate,
  35208. panningModel: this._panningModel,
  35209. soundTrackId: this.soundTrackId
  35210. };
  35211. if (this.spatialSound) {
  35212. if (this._connectedMesh)
  35213. serializationObject.connectedMeshId = this._connectedMesh.id;
  35214. serializationObject.position = this._position.asArray();
  35215. serializationObject.refDistance = this.refDistance;
  35216. serializationObject.distanceModel = this.distanceModel;
  35217. serializationObject.isDirectional = this._isDirectional;
  35218. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  35219. serializationObject.coneInnerAngle = this._coneInnerAngle;
  35220. serializationObject.coneOuterAngle = this._coneOuterAngle;
  35221. serializationObject.coneOuterGain = this._coneOuterGain;
  35222. }
  35223. return serializationObject;
  35224. };
  35225. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  35226. var soundName = parsedSound.name;
  35227. var soundUrl;
  35228. if (parsedSound.url) {
  35229. soundUrl = rootUrl + parsedSound.url;
  35230. }
  35231. else {
  35232. soundUrl = rootUrl + soundName;
  35233. }
  35234. var options = {
  35235. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  35236. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  35237. rolloffFactor: parsedSound.rolloffFactor,
  35238. refDistance: parsedSound.refDistance,
  35239. distanceModel: parsedSound.distanceModel,
  35240. playbackRate: parsedSound.playbackRate
  35241. };
  35242. var newSound;
  35243. if (!sourceSound) {
  35244. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  35245. scene._addPendingData(newSound);
  35246. }
  35247. else {
  35248. var setBufferAndRun = function () {
  35249. if (sourceSound._isReadyToPlay) {
  35250. newSound._audioBuffer = sourceSound.getAudioBuffer();
  35251. newSound._isReadyToPlay = true;
  35252. if (newSound.autoplay) {
  35253. newSound.play();
  35254. }
  35255. }
  35256. else {
  35257. window.setTimeout(setBufferAndRun, 300);
  35258. }
  35259. };
  35260. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  35261. setBufferAndRun();
  35262. }
  35263. if (parsedSound.position) {
  35264. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  35265. newSound.setPosition(soundPosition);
  35266. }
  35267. if (parsedSound.isDirectional) {
  35268. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  35269. if (parsedSound.localDirectionToMesh) {
  35270. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  35271. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  35272. }
  35273. }
  35274. if (parsedSound.connectedMeshId) {
  35275. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  35276. if (connectedMesh) {
  35277. newSound.attachToMesh(connectedMesh);
  35278. }
  35279. }
  35280. return newSound;
  35281. };
  35282. return Sound;
  35283. }());
  35284. BABYLON.Sound = Sound;
  35285. })(BABYLON || (BABYLON = {}));
  35286. var BABYLON;
  35287. (function (BABYLON) {
  35288. var SoundTrack = (function () {
  35289. function SoundTrack(scene, options) {
  35290. this.id = -1;
  35291. this._isMainTrack = false;
  35292. this._isInitialized = false;
  35293. this._scene = scene;
  35294. this.soundCollection = new Array();
  35295. this._options = options;
  35296. if (!this._isMainTrack) {
  35297. this._scene.soundTracks.push(this);
  35298. this.id = this._scene.soundTracks.length - 1;
  35299. }
  35300. }
  35301. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  35302. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  35303. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  35304. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  35305. if (this._options) {
  35306. if (this._options.volume) {
  35307. this._outputAudioNode.gain.value = this._options.volume;
  35308. }
  35309. if (this._options.mainTrack) {
  35310. this._isMainTrack = this._options.mainTrack;
  35311. }
  35312. }
  35313. this._isInitialized = true;
  35314. }
  35315. };
  35316. SoundTrack.prototype.dispose = function () {
  35317. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  35318. if (this._connectedAnalyser) {
  35319. this._connectedAnalyser.stopDebugCanvas();
  35320. }
  35321. while (this.soundCollection.length) {
  35322. this.soundCollection[0].dispose();
  35323. }
  35324. if (this._outputAudioNode) {
  35325. this._outputAudioNode.disconnect();
  35326. }
  35327. this._outputAudioNode = null;
  35328. }
  35329. };
  35330. SoundTrack.prototype.AddSound = function (sound) {
  35331. if (!this._isInitialized) {
  35332. this._initializeSoundTrackAudioGraph();
  35333. }
  35334. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  35335. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  35336. }
  35337. if (sound.soundTrackId) {
  35338. if (sound.soundTrackId === -1) {
  35339. this._scene.mainSoundTrack.RemoveSound(sound);
  35340. }
  35341. else {
  35342. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  35343. }
  35344. }
  35345. this.soundCollection.push(sound);
  35346. sound.soundTrackId = this.id;
  35347. };
  35348. SoundTrack.prototype.RemoveSound = function (sound) {
  35349. var index = this.soundCollection.indexOf(sound);
  35350. if (index !== -1) {
  35351. this.soundCollection.splice(index, 1);
  35352. }
  35353. };
  35354. SoundTrack.prototype.setVolume = function (newVolume) {
  35355. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  35356. this._outputAudioNode.gain.value = newVolume;
  35357. }
  35358. };
  35359. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  35360. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  35361. for (var i = 0; i < this.soundCollection.length; i++) {
  35362. this.soundCollection[i].switchPanningModelToHRTF();
  35363. }
  35364. }
  35365. };
  35366. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  35367. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  35368. for (var i = 0; i < this.soundCollection.length; i++) {
  35369. this.soundCollection[i].switchPanningModelToEqualPower();
  35370. }
  35371. }
  35372. };
  35373. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  35374. if (this._connectedAnalyser) {
  35375. this._connectedAnalyser.stopDebugCanvas();
  35376. }
  35377. this._connectedAnalyser = analyser;
  35378. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  35379. this._outputAudioNode.disconnect();
  35380. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  35381. }
  35382. };
  35383. return SoundTrack;
  35384. }());
  35385. BABYLON.SoundTrack = SoundTrack;
  35386. })(BABYLON || (BABYLON = {}));
  35387. var BABYLON;
  35388. (function (BABYLON) {
  35389. var DebugLayer = (function () {
  35390. function DebugLayer(scene) {
  35391. var _this = this;
  35392. this._transformationMatrix = BABYLON.Matrix.Identity();
  35393. this._enabled = false;
  35394. this._labelsEnabled = false;
  35395. this._displayStatistics = true;
  35396. this._displayTree = false;
  35397. this._displayLogs = false;
  35398. this._skeletonViewers = new Array();
  35399. this._identityMatrix = BABYLON.Matrix.Identity();
  35400. this.axisRatio = 0.02;
  35401. this.accentColor = "orange";
  35402. this._scene = scene;
  35403. this._syncPositions = function () {
  35404. var engine = _this._scene.getEngine();
  35405. var canvasRect = engine.getRenderingCanvasClientRect();
  35406. if (_this._showUI) {
  35407. _this._statsDiv.style.left = (canvasRect.width - 410) + "px";
  35408. _this._statsDiv.style.top = (canvasRect.height - 290) + "px";
  35409. _this._statsDiv.style.width = "400px";
  35410. _this._statsDiv.style.height = "auto";
  35411. _this._statsSubsetDiv.style.maxHeight = "240px";
  35412. _this._optionsDiv.style.left = "0px";
  35413. _this._optionsDiv.style.top = "10px";
  35414. _this._optionsDiv.style.width = "200px";
  35415. _this._optionsDiv.style.height = "auto";
  35416. _this._optionsSubsetDiv.style.maxHeight = (canvasRect.height - 225) + "px";
  35417. _this._logDiv.style.left = "0px";
  35418. _this._logDiv.style.top = (canvasRect.height - 170) + "px";
  35419. _this._logDiv.style.width = "600px";
  35420. _this._logDiv.style.height = "160px";
  35421. _this._treeDiv.style.left = (canvasRect.width - 310) + "px";
  35422. _this._treeDiv.style.top = "10px";
  35423. _this._treeDiv.style.width = "300px";
  35424. _this._treeDiv.style.height = "auto";
  35425. _this._treeSubsetDiv.style.maxHeight = (canvasRect.height - 340) + "px";
  35426. }
  35427. _this._globalDiv.style.left = canvasRect.left + "px";
  35428. _this._globalDiv.style.top = canvasRect.top + "px";
  35429. _this._drawingCanvas.style.left = "0px";
  35430. _this._drawingCanvas.style.top = "0px";
  35431. _this._drawingCanvas.style.width = engine.getRenderWidth() + "px";
  35432. _this._drawingCanvas.style.height = engine.getRenderHeight() + "px";
  35433. var devicePixelRatio = window.devicePixelRatio || 1;
  35434. var context = _this._drawingContext;
  35435. var backingStoreRatio = context.webkitBackingStorePixelRatio ||
  35436. context.mozBackingStorePixelRatio ||
  35437. context.msBackingStorePixelRatio ||
  35438. context.oBackingStorePixelRatio ||
  35439. context.backingStorePixelRatio || 1;
  35440. _this._ratio = devicePixelRatio / backingStoreRatio;
  35441. _this._drawingCanvas.width = engine.getRenderWidth() * _this._ratio;
  35442. _this._drawingCanvas.height = engine.getRenderHeight() * _this._ratio;
  35443. };
  35444. this._onCanvasClick = function (evt) {
  35445. _this._clickPosition = {
  35446. x: evt.clientX * _this._ratio,
  35447. y: evt.clientY * _this._ratio
  35448. };
  35449. };
  35450. this._syncUI = function () {
  35451. if (_this._showUI) {
  35452. if (_this._displayStatistics) {
  35453. _this._displayStats();
  35454. _this._statsDiv.style.display = "";
  35455. }
  35456. else {
  35457. _this._statsDiv.style.display = "none";
  35458. }
  35459. if (_this._displayLogs) {
  35460. _this._logDiv.style.display = "";
  35461. }
  35462. else {
  35463. _this._logDiv.style.display = "none";
  35464. }
  35465. if (_this._displayTree) {
  35466. _this._treeDiv.style.display = "";
  35467. if (_this._needToRefreshMeshesTree) {
  35468. _this._needToRefreshMeshesTree = false;
  35469. _this._refreshMeshesTreeContent();
  35470. }
  35471. }
  35472. else {
  35473. _this._treeDiv.style.display = "none";
  35474. }
  35475. }
  35476. };
  35477. this._syncData = function () {
  35478. if (_this._labelsEnabled || !_this._showUI) {
  35479. _this._camera.getViewMatrix().multiplyToRef(_this._camera.getProjectionMatrix(), _this._transformationMatrix);
  35480. _this._drawingContext.clearRect(0, 0, _this._drawingCanvas.width, _this._drawingCanvas.height);
  35481. var engine = _this._scene.getEngine();
  35482. var viewport = _this._camera.viewport;
  35483. var globalViewport = viewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  35484. // Meshes
  35485. var meshes = _this._camera.getActiveMeshes();
  35486. var index;
  35487. var projectedPosition;
  35488. for (index = 0; index < meshes.length; index++) {
  35489. var mesh = meshes.data[index];
  35490. var position = mesh.getBoundingInfo().boundingSphere.center;
  35491. projectedPosition = BABYLON.Vector3.Project(position, mesh.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  35492. if (mesh.renderOverlay || _this.shouldDisplayAxis && _this.shouldDisplayAxis(mesh)) {
  35493. _this._renderAxis(projectedPosition, mesh, globalViewport);
  35494. }
  35495. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(mesh)) {
  35496. _this._renderLabel(mesh.name, projectedPosition, 12, function () { mesh.renderOverlay = !mesh.renderOverlay; }, function () { return mesh.renderOverlay ? 'red' : 'black'; });
  35497. }
  35498. }
  35499. // Cameras
  35500. var cameras = _this._scene.cameras;
  35501. for (index = 0; index < cameras.length; index++) {
  35502. var camera = cameras[index];
  35503. if (camera === _this._camera) {
  35504. continue;
  35505. }
  35506. projectedPosition = BABYLON.Vector3.Project(BABYLON.Vector3.Zero(), camera.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  35507. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(camera)) {
  35508. _this._renderLabel(camera.name, projectedPosition, 12, function () {
  35509. _this._camera.detachControl(engine.getRenderingCanvas());
  35510. _this._camera = camera;
  35511. _this._camera.attachControl(engine.getRenderingCanvas());
  35512. }, function () { return "purple"; });
  35513. }
  35514. }
  35515. // Lights
  35516. var lights = _this._scene.lights;
  35517. for (index = 0; index < lights.length; index++) {
  35518. var light = lights[index];
  35519. if (light.position) {
  35520. projectedPosition = BABYLON.Vector3.Project(light.getAbsolutePosition(), _this._identityMatrix, _this._transformationMatrix, globalViewport);
  35521. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(light)) {
  35522. _this._renderLabel(light.name, projectedPosition, -20, function () {
  35523. light.setEnabled(!light.isEnabled());
  35524. }, function () { return light.isEnabled() ? "orange" : "gray"; });
  35525. }
  35526. }
  35527. }
  35528. }
  35529. _this._clickPosition = undefined;
  35530. };
  35531. }
  35532. DebugLayer.prototype._refreshMeshesTreeContent = function () {
  35533. while (this._treeSubsetDiv.hasChildNodes()) {
  35534. this._treeSubsetDiv.removeChild(this._treeSubsetDiv.lastChild);
  35535. }
  35536. // Add meshes
  35537. var sortedArray = this._scene.meshes.slice(0, this._scene.meshes.length);
  35538. sortedArray.sort(function (a, b) {
  35539. if (a.name === b.name) {
  35540. return 0;
  35541. }
  35542. return (a.name > b.name) ? 1 : -1;
  35543. });
  35544. for (var index = 0; index < sortedArray.length; index++) {
  35545. var mesh = sortedArray[index];
  35546. if (!mesh.isEnabled()) {
  35547. continue;
  35548. }
  35549. this._generateAdvancedCheckBox(this._treeSubsetDiv, mesh.name, mesh.getTotalVertices() + " verts", mesh.isVisible, function (element, m) {
  35550. m.isVisible = element.checked;
  35551. }, mesh);
  35552. }
  35553. };
  35554. DebugLayer.prototype._renderSingleAxis = function (zero, unit, unitText, label, color) {
  35555. this._drawingContext.beginPath();
  35556. this._drawingContext.moveTo(zero.x, zero.y);
  35557. this._drawingContext.lineTo(unit.x, unit.y);
  35558. this._drawingContext.strokeStyle = color;
  35559. this._drawingContext.lineWidth = 4;
  35560. this._drawingContext.stroke();
  35561. this._drawingContext.font = "normal 14px Segoe UI";
  35562. this._drawingContext.fillStyle = color;
  35563. this._drawingContext.fillText(label, unitText.x, unitText.y);
  35564. };
  35565. DebugLayer.prototype._renderAxis = function (projectedPosition, mesh, globalViewport) {
  35566. var position = mesh.getBoundingInfo().boundingSphere.center;
  35567. var worldMatrix = mesh.getWorldMatrix();
  35568. var unprojectedVector = BABYLON.Vector3.UnprojectFromTransform(projectedPosition.add(new BABYLON.Vector3(this._drawingCanvas.width * this.axisRatio, 0, 0)), globalViewport.width, globalViewport.height, worldMatrix, this._transformationMatrix);
  35569. var unit = (unprojectedVector.subtract(position)).length();
  35570. var xAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  35571. var xAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit * 1.5, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  35572. this._renderSingleAxis(projectedPosition, xAxis, xAxisText, "x", "#FF0000");
  35573. var yAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  35574. var yAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit * 1.5, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  35575. this._renderSingleAxis(projectedPosition, yAxis, yAxisText, "y", "#00FF00");
  35576. var zAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit)), worldMatrix, this._transformationMatrix, globalViewport);
  35577. var zAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit * 1.5)), worldMatrix, this._transformationMatrix, globalViewport);
  35578. this._renderSingleAxis(projectedPosition, zAxis, zAxisText, "z", "#0000FF");
  35579. };
  35580. DebugLayer.prototype._renderLabel = function (text, projectedPosition, labelOffset, onClick, getFillStyle) {
  35581. if (projectedPosition.z > 0 && projectedPosition.z < 1.0) {
  35582. this._drawingContext.font = "normal 12px Segoe UI";
  35583. var textMetrics = this._drawingContext.measureText(text);
  35584. var centerX = projectedPosition.x - textMetrics.width / 2;
  35585. var centerY = projectedPosition.y;
  35586. var clientRect = this._drawingCanvas.getBoundingClientRect();
  35587. if (this._showUI && this._isClickInsideRect(clientRect.left * this._ratio + centerX - 5, clientRect.top * this._ratio + centerY - labelOffset - 12, textMetrics.width + 10, 17)) {
  35588. onClick();
  35589. }
  35590. this._drawingContext.beginPath();
  35591. this._drawingContext.rect(centerX - 5, centerY - labelOffset - 12, textMetrics.width + 10, 17);
  35592. this._drawingContext.fillStyle = getFillStyle();
  35593. this._drawingContext.globalAlpha = 0.5;
  35594. this._drawingContext.fill();
  35595. this._drawingContext.globalAlpha = 1.0;
  35596. this._drawingContext.strokeStyle = '#FFFFFF';
  35597. this._drawingContext.lineWidth = 1;
  35598. this._drawingContext.stroke();
  35599. this._drawingContext.fillStyle = "#FFFFFF";
  35600. this._drawingContext.fillText(text, centerX, centerY - labelOffset);
  35601. this._drawingContext.beginPath();
  35602. this._drawingContext.arc(projectedPosition.x, centerY, 5, 0, 2 * Math.PI, false);
  35603. this._drawingContext.fill();
  35604. }
  35605. };
  35606. DebugLayer.prototype._isClickInsideRect = function (x, y, width, height) {
  35607. if (!this._clickPosition) {
  35608. return false;
  35609. }
  35610. if (this._clickPosition.x < x || this._clickPosition.x > x + width) {
  35611. return false;
  35612. }
  35613. if (this._clickPosition.y < y || this._clickPosition.y > y + height) {
  35614. return false;
  35615. }
  35616. return true;
  35617. };
  35618. DebugLayer.prototype.isVisible = function () {
  35619. return this._enabled;
  35620. };
  35621. DebugLayer.prototype.hide = function () {
  35622. if (!this._enabled) {
  35623. return;
  35624. }
  35625. this._enabled = false;
  35626. var engine = this._scene.getEngine();
  35627. this._scene.unregisterBeforeRender(this._syncData);
  35628. this._scene.unregisterAfterRender(this._syncUI);
  35629. this._rootElement.removeChild(this._globalDiv);
  35630. this._scene.forceShowBoundingBoxes = false;
  35631. this._scene.forceWireframe = false;
  35632. BABYLON.StandardMaterial.DiffuseTextureEnabled = true;
  35633. BABYLON.StandardMaterial.AmbientTextureEnabled = true;
  35634. BABYLON.StandardMaterial.SpecularTextureEnabled = true;
  35635. BABYLON.StandardMaterial.EmissiveTextureEnabled = true;
  35636. BABYLON.StandardMaterial.BumpTextureEnabled = true;
  35637. BABYLON.StandardMaterial.OpacityTextureEnabled = true;
  35638. BABYLON.StandardMaterial.ReflectionTextureEnabled = true;
  35639. BABYLON.StandardMaterial.LightmapTextureEnabled = true;
  35640. BABYLON.StandardMaterial.RefractionTextureEnabled = true;
  35641. BABYLON.StandardMaterial.ColorGradingTextureEnabled = true;
  35642. this._scene.shadowsEnabled = true;
  35643. this._scene.particlesEnabled = true;
  35644. this._scene.postProcessesEnabled = true;
  35645. this._scene.collisionsEnabled = true;
  35646. this._scene.lightsEnabled = true;
  35647. this._scene.texturesEnabled = true;
  35648. this._scene.lensFlaresEnabled = true;
  35649. this._scene.proceduralTexturesEnabled = true;
  35650. this._scene.renderTargetsEnabled = true;
  35651. this._scene.probesEnabled = true;
  35652. engine.getRenderingCanvas().removeEventListener("click", this._onCanvasClick);
  35653. this._clearSkeletonViewers();
  35654. };
  35655. DebugLayer.prototype._clearSkeletonViewers = function () {
  35656. for (var index = 0; index < this._skeletonViewers.length; index++) {
  35657. this._skeletonViewers[index].dispose();
  35658. }
  35659. this._skeletonViewers = [];
  35660. };
  35661. DebugLayer.prototype.show = function (showUI, camera, rootElement) {
  35662. if (showUI === void 0) { showUI = true; }
  35663. if (camera === void 0) { camera = null; }
  35664. if (rootElement === void 0) { rootElement = null; }
  35665. if (this._enabled) {
  35666. return;
  35667. }
  35668. this._enabled = true;
  35669. if (camera) {
  35670. this._camera = camera;
  35671. }
  35672. else {
  35673. this._camera = this._scene.activeCamera;
  35674. }
  35675. this._showUI = showUI;
  35676. var engine = this._scene.getEngine();
  35677. this._globalDiv = document.createElement("div");
  35678. this._rootElement = rootElement || document.body;
  35679. this._rootElement.appendChild(this._globalDiv);
  35680. this._generateDOMelements();
  35681. engine.getRenderingCanvas().addEventListener("click", this._onCanvasClick);
  35682. this._syncPositions();
  35683. this._scene.registerBeforeRender(this._syncData);
  35684. this._scene.registerAfterRender(this._syncUI);
  35685. };
  35686. DebugLayer.prototype._clearLabels = function () {
  35687. this._drawingContext.clearRect(0, 0, this._drawingCanvas.width, this._drawingCanvas.height);
  35688. for (var index = 0; index < this._scene.meshes.length; index++) {
  35689. var mesh = this._scene.meshes[index];
  35690. mesh.renderOverlay = false;
  35691. }
  35692. };
  35693. DebugLayer.prototype._generateheader = function (root, text) {
  35694. var header = document.createElement("div");
  35695. header.innerHTML = text + "&nbsp;";
  35696. header.style.textAlign = "right";
  35697. header.style.width = "100%";
  35698. header.style.color = "white";
  35699. header.style.backgroundColor = "Black";
  35700. header.style.padding = "5px 5px 4px 0px";
  35701. header.style.marginLeft = "-5px";
  35702. header.style.fontWeight = "bold";
  35703. root.appendChild(header);
  35704. };
  35705. DebugLayer.prototype._generateTexBox = function (root, title, color) {
  35706. var label = document.createElement("label");
  35707. label.style.display = "inline";
  35708. label.innerHTML = title;
  35709. label.style.color = color;
  35710. root.appendChild(label);
  35711. root.appendChild(document.createElement("br"));
  35712. };
  35713. DebugLayer.prototype._generateAdvancedCheckBox = function (root, leftTitle, rightTitle, initialState, task, tag) {
  35714. if (tag === void 0) { tag = null; }
  35715. var label = document.createElement("label");
  35716. label.style.display = "inline";
  35717. var boundingBoxesCheckbox = document.createElement("input");
  35718. boundingBoxesCheckbox.type = "checkbox";
  35719. boundingBoxesCheckbox.checked = initialState;
  35720. boundingBoxesCheckbox.style.display = "inline";
  35721. boundingBoxesCheckbox.style.margin = "0px 5px 0px 0px";
  35722. boundingBoxesCheckbox.style.verticalAlign = "sub";
  35723. boundingBoxesCheckbox.addEventListener("change", function (evt) {
  35724. task(evt.target, tag);
  35725. });
  35726. label.appendChild(boundingBoxesCheckbox);
  35727. var container = document.createElement("span");
  35728. var leftPart = document.createElement("span");
  35729. var rightPart = document.createElement("span");
  35730. rightPart.style.cssFloat = "right";
  35731. leftPart.innerHTML = leftTitle;
  35732. rightPart.innerHTML = rightTitle;
  35733. rightPart.style.fontSize = "12px";
  35734. rightPart.style.maxWidth = "200px";
  35735. container.appendChild(leftPart);
  35736. container.appendChild(rightPart);
  35737. label.appendChild(container);
  35738. root.appendChild(label);
  35739. root.appendChild(document.createElement("br"));
  35740. };
  35741. DebugLayer.prototype._generateCheckBox = function (root, title, initialState, task, tag) {
  35742. if (tag === void 0) { tag = null; }
  35743. var label = document.createElement("label");
  35744. label.style.display = "inline";
  35745. var checkBox = document.createElement("input");
  35746. checkBox.type = "checkbox";
  35747. checkBox.checked = initialState;
  35748. checkBox.style.display = "inline";
  35749. checkBox.style.margin = "0px 5px 0px 0px";
  35750. checkBox.style.verticalAlign = "sub";
  35751. checkBox.addEventListener("change", function (evt) {
  35752. task(evt.target, tag);
  35753. });
  35754. label.appendChild(checkBox);
  35755. label.appendChild(document.createTextNode(title));
  35756. root.appendChild(label);
  35757. root.appendChild(document.createElement("br"));
  35758. };
  35759. DebugLayer.prototype._generateButton = function (root, title, task, tag) {
  35760. if (tag === void 0) { tag = null; }
  35761. var button = document.createElement("button");
  35762. button.innerHTML = title;
  35763. button.style.height = "24px";
  35764. button.style.width = "150px";
  35765. button.style.marginBottom = "5px";
  35766. button.style.color = "#444444";
  35767. button.style.border = "1px solid white";
  35768. button.className = "debugLayerButton";
  35769. button.addEventListener("click", function (evt) {
  35770. task(evt.target, tag);
  35771. });
  35772. root.appendChild(button);
  35773. root.appendChild(document.createElement("br"));
  35774. };
  35775. DebugLayer.prototype._generateRadio = function (root, title, name, initialState, task, tag) {
  35776. if (tag === void 0) { tag = null; }
  35777. var label = document.createElement("label");
  35778. label.style.display = "inline";
  35779. var boundingBoxesRadio = document.createElement("input");
  35780. boundingBoxesRadio.type = "radio";
  35781. boundingBoxesRadio.name = name;
  35782. boundingBoxesRadio.checked = initialState;
  35783. boundingBoxesRadio.style.display = "inline";
  35784. boundingBoxesRadio.style.margin = "0px 5px 0px 0px";
  35785. boundingBoxesRadio.style.verticalAlign = "sub";
  35786. boundingBoxesRadio.addEventListener("change", function (evt) {
  35787. task(evt.target, tag);
  35788. });
  35789. label.appendChild(boundingBoxesRadio);
  35790. label.appendChild(document.createTextNode(title));
  35791. root.appendChild(label);
  35792. root.appendChild(document.createElement("br"));
  35793. };
  35794. DebugLayer.prototype._generateDOMelements = function () {
  35795. var _this = this;
  35796. this._globalDiv.id = "DebugLayer";
  35797. this._globalDiv.style.position = "absolute";
  35798. this._globalDiv.style.fontFamily = "Segoe UI, Arial";
  35799. this._globalDiv.style.fontSize = "14px";
  35800. this._globalDiv.style.color = "white";
  35801. // Drawing canvas
  35802. this._drawingCanvas = document.createElement("canvas");
  35803. this._drawingCanvas.id = "DebugLayerDrawingCanvas";
  35804. this._drawingCanvas.style.position = "absolute";
  35805. this._drawingCanvas.style.pointerEvents = "none";
  35806. this._drawingCanvas.style.backgroundColor = "transparent";
  35807. this._drawingContext = this._drawingCanvas.getContext("2d");
  35808. this._globalDiv.appendChild(this._drawingCanvas);
  35809. if (this._showUI) {
  35810. var background = "rgba(128, 128, 128, 0.4)";
  35811. var border = "rgb(180, 180, 180) solid 1px";
  35812. // Stats
  35813. this._statsDiv = document.createElement("div");
  35814. this._statsDiv.id = "DebugLayerStats";
  35815. this._statsDiv.style.border = border;
  35816. this._statsDiv.style.position = "absolute";
  35817. this._statsDiv.style.background = background;
  35818. this._statsDiv.style.padding = "0px 0px 0px 5px";
  35819. this._generateheader(this._statsDiv, "STATISTICS");
  35820. this._statsSubsetDiv = document.createElement("div");
  35821. this._statsSubsetDiv.style.paddingTop = "5px";
  35822. this._statsSubsetDiv.style.paddingBottom = "5px";
  35823. this._statsSubsetDiv.style.overflowY = "auto";
  35824. this._statsDiv.appendChild(this._statsSubsetDiv);
  35825. // Tree
  35826. this._treeDiv = document.createElement("div");
  35827. this._treeDiv.id = "DebugLayerTree";
  35828. this._treeDiv.style.border = border;
  35829. this._treeDiv.style.position = "absolute";
  35830. this._treeDiv.style.background = background;
  35831. this._treeDiv.style.padding = "0px 0px 0px 5px";
  35832. this._treeDiv.style.display = "none";
  35833. this._generateheader(this._treeDiv, "MESHES TREE");
  35834. this._treeSubsetDiv = document.createElement("div");
  35835. this._treeSubsetDiv.style.paddingTop = "5px";
  35836. this._treeSubsetDiv.style.paddingRight = "5px";
  35837. this._treeSubsetDiv.style.overflowY = "auto";
  35838. this._treeSubsetDiv.style.maxHeight = "300px";
  35839. this._treeDiv.appendChild(this._treeSubsetDiv);
  35840. this._needToRefreshMeshesTree = true;
  35841. // Logs
  35842. this._logDiv = document.createElement("div");
  35843. this._logDiv.style.border = border;
  35844. this._logDiv.id = "DebugLayerLogs";
  35845. this._logDiv.style.position = "absolute";
  35846. this._logDiv.style.background = background;
  35847. this._logDiv.style.padding = "0px 0px 0px 5px";
  35848. this._logDiv.style.display = "none";
  35849. this._generateheader(this._logDiv, "LOGS");
  35850. this._logSubsetDiv = document.createElement("div");
  35851. this._logSubsetDiv.style.height = "127px";
  35852. this._logSubsetDiv.style.paddingTop = "5px";
  35853. this._logSubsetDiv.style.overflowY = "auto";
  35854. this._logSubsetDiv.style.fontSize = "12px";
  35855. this._logSubsetDiv.style.fontFamily = "consolas";
  35856. this._logSubsetDiv.innerHTML = BABYLON.Tools.LogCache;
  35857. this._logDiv.appendChild(this._logSubsetDiv);
  35858. BABYLON.Tools.OnNewCacheEntry = function (entry) {
  35859. _this._logSubsetDiv.innerHTML = entry + _this._logSubsetDiv.innerHTML;
  35860. };
  35861. // Options
  35862. this._optionsDiv = document.createElement("div");
  35863. this._optionsDiv.id = "DebugLayerOptions";
  35864. this._optionsDiv.style.border = border;
  35865. this._optionsDiv.style.position = "absolute";
  35866. this._optionsDiv.style.background = background;
  35867. this._optionsDiv.style.padding = "0px 0px 0px 5px";
  35868. this._optionsDiv.style.overflowY = "auto";
  35869. this._generateheader(this._optionsDiv, "OPTIONS");
  35870. this._optionsSubsetDiv = document.createElement("div");
  35871. this._optionsSubsetDiv.style.paddingTop = "5px";
  35872. this._optionsSubsetDiv.style.paddingBottom = "5px";
  35873. this._optionsSubsetDiv.style.overflowY = "auto";
  35874. this._optionsSubsetDiv.style.maxHeight = "200px";
  35875. this._optionsDiv.appendChild(this._optionsSubsetDiv);
  35876. this._generateTexBox(this._optionsSubsetDiv, "<b>Windows:</b>", this.accentColor);
  35877. this._generateCheckBox(this._optionsSubsetDiv, "Statistics", this._displayStatistics, function (element) { _this._displayStatistics = element.checked; });
  35878. this._generateCheckBox(this._optionsSubsetDiv, "Logs", this._displayLogs, function (element) { _this._displayLogs = element.checked; });
  35879. this._generateCheckBox(this._optionsSubsetDiv, "Meshes tree", this._displayTree, function (element) {
  35880. _this._displayTree = element.checked;
  35881. _this._needToRefreshMeshesTree = true;
  35882. });
  35883. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  35884. this._generateTexBox(this._optionsSubsetDiv, "<b>General:</b>", this.accentColor);
  35885. this._generateCheckBox(this._optionsSubsetDiv, "Bounding boxes", this._scene.forceShowBoundingBoxes, function (element) { _this._scene.forceShowBoundingBoxes = element.checked; });
  35886. this._generateCheckBox(this._optionsSubsetDiv, "Clickable labels", this._labelsEnabled, function (element) {
  35887. _this._labelsEnabled = element.checked;
  35888. if (!_this._labelsEnabled) {
  35889. _this._clearLabels();
  35890. }
  35891. });
  35892. this._generateCheckBox(this._optionsSubsetDiv, "Generate user marks (F12)", BABYLON.Tools.PerformanceLogLevel === BABYLON.Tools.PerformanceUserMarkLogLevel, function (element) {
  35893. if (element.checked) {
  35894. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceUserMarkLogLevel;
  35895. }
  35896. else {
  35897. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceNoneLogLevel;
  35898. }
  35899. });
  35900. ;
  35901. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  35902. this._generateTexBox(this._optionsSubsetDiv, "<b>Rendering mode:</b>", this.accentColor);
  35903. this._generateRadio(this._optionsSubsetDiv, "Solid", "renderMode", !this._scene.forceWireframe && !this._scene.forcePointsCloud, function (element) {
  35904. if (element.checked) {
  35905. _this._scene.forceWireframe = false;
  35906. _this._scene.forcePointsCloud = false;
  35907. }
  35908. });
  35909. this._generateRadio(this._optionsSubsetDiv, "Wireframe", "renderMode", this._scene.forceWireframe, function (element) {
  35910. if (element.checked) {
  35911. _this._scene.forceWireframe = true;
  35912. _this._scene.forcePointsCloud = false;
  35913. }
  35914. });
  35915. this._generateRadio(this._optionsSubsetDiv, "Point", "renderMode", this._scene.forcePointsCloud, function (element) {
  35916. if (element.checked) {
  35917. _this._scene.forceWireframe = false;
  35918. _this._scene.forcePointsCloud = true;
  35919. }
  35920. });
  35921. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  35922. this._generateTexBox(this._optionsSubsetDiv, "<b>Texture channels:</b>", this.accentColor);
  35923. this._generateCheckBox(this._optionsSubsetDiv, "Diffuse", BABYLON.StandardMaterial.DiffuseTextureEnabled, function (element) { BABYLON.StandardMaterial.DiffuseTextureEnabled = element.checked; });
  35924. this._generateCheckBox(this._optionsSubsetDiv, "Ambient", BABYLON.StandardMaterial.AmbientTextureEnabled, function (element) { BABYLON.StandardMaterial.AmbientTextureEnabled = element.checked; });
  35925. this._generateCheckBox(this._optionsSubsetDiv, "Specular", BABYLON.StandardMaterial.SpecularTextureEnabled, function (element) { BABYLON.StandardMaterial.SpecularTextureEnabled = element.checked; });
  35926. this._generateCheckBox(this._optionsSubsetDiv, "Emissive", BABYLON.StandardMaterial.EmissiveTextureEnabled, function (element) { BABYLON.StandardMaterial.EmissiveTextureEnabled = element.checked; });
  35927. this._generateCheckBox(this._optionsSubsetDiv, "Bump", BABYLON.StandardMaterial.BumpTextureEnabled, function (element) { BABYLON.StandardMaterial.BumpTextureEnabled = element.checked; });
  35928. this._generateCheckBox(this._optionsSubsetDiv, "Opacity", BABYLON.StandardMaterial.OpacityTextureEnabled, function (element) { BABYLON.StandardMaterial.OpacityTextureEnabled = element.checked; });
  35929. this._generateCheckBox(this._optionsSubsetDiv, "Reflection", BABYLON.StandardMaterial.ReflectionTextureEnabled, function (element) { BABYLON.StandardMaterial.ReflectionTextureEnabled = element.checked; });
  35930. this._generateCheckBox(this._optionsSubsetDiv, "Refraction", BABYLON.StandardMaterial.RefractionTextureEnabled, function (element) { BABYLON.StandardMaterial.RefractionTextureEnabled = element.checked; });
  35931. this._generateCheckBox(this._optionsSubsetDiv, "ColorGrading", BABYLON.StandardMaterial.ColorGradingTextureEnabled, function (element) { BABYLON.StandardMaterial.ColorGradingTextureEnabled = element.checked; });
  35932. this._generateCheckBox(this._optionsSubsetDiv, "Lightmap", BABYLON.StandardMaterial.LightmapTextureEnabled, function (element) { BABYLON.StandardMaterial.LightmapTextureEnabled = element.checked; });
  35933. this._generateCheckBox(this._optionsSubsetDiv, "Fresnel", BABYLON.StandardMaterial.FresnelEnabled, function (element) { BABYLON.StandardMaterial.FresnelEnabled = element.checked; });
  35934. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  35935. this._generateTexBox(this._optionsSubsetDiv, "<b>Options:</b>", this.accentColor);
  35936. this._generateCheckBox(this._optionsSubsetDiv, "Animations", this._scene.animationsEnabled, function (element) { _this._scene.animationsEnabled = element.checked; });
  35937. this._generateCheckBox(this._optionsSubsetDiv, "Collisions", this._scene.collisionsEnabled, function (element) { _this._scene.collisionsEnabled = element.checked; });
  35938. this._generateCheckBox(this._optionsSubsetDiv, "Fog", this._scene.fogEnabled, function (element) { _this._scene.fogEnabled = element.checked; });
  35939. this._generateCheckBox(this._optionsSubsetDiv, "Lens flares", this._scene.lensFlaresEnabled, function (element) { _this._scene.lensFlaresEnabled = element.checked; });
  35940. this._generateCheckBox(this._optionsSubsetDiv, "Lights", this._scene.lightsEnabled, function (element) { _this._scene.lightsEnabled = element.checked; });
  35941. this._generateCheckBox(this._optionsSubsetDiv, "Particles", this._scene.particlesEnabled, function (element) { _this._scene.particlesEnabled = element.checked; });
  35942. this._generateCheckBox(this._optionsSubsetDiv, "Post-processes", this._scene.postProcessesEnabled, function (element) { _this._scene.postProcessesEnabled = element.checked; });
  35943. this._generateCheckBox(this._optionsSubsetDiv, "Probes", this._scene.probesEnabled, function (element) { _this._scene.probesEnabled = element.checked; });
  35944. this._generateCheckBox(this._optionsSubsetDiv, "Procedural textures", this._scene.proceduralTexturesEnabled, function (element) { _this._scene.proceduralTexturesEnabled = element.checked; });
  35945. this._generateCheckBox(this._optionsSubsetDiv, "Render targets", this._scene.renderTargetsEnabled, function (element) { _this._scene.renderTargetsEnabled = element.checked; });
  35946. this._generateCheckBox(this._optionsSubsetDiv, "Shadows", this._scene.shadowsEnabled, function (element) { _this._scene.shadowsEnabled = element.checked; });
  35947. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", this._scene.skeletonsEnabled, function (element) { _this._scene.skeletonsEnabled = element.checked; });
  35948. this._generateCheckBox(this._optionsSubsetDiv, "Sprites", this._scene.spritesEnabled, function (element) { _this._scene.spritesEnabled = element.checked; });
  35949. this._generateCheckBox(this._optionsSubsetDiv, "Textures", this._scene.texturesEnabled, function (element) { _this._scene.texturesEnabled = element.checked; });
  35950. if (BABYLON.AudioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  35951. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  35952. this._generateTexBox(this._optionsSubsetDiv, "<b>Audio:</b>", this.accentColor);
  35953. this._generateRadio(this._optionsSubsetDiv, "Headphones", "panningModel", this._scene.headphone, function (element) {
  35954. if (element.checked) {
  35955. _this._scene.headphone = true;
  35956. }
  35957. });
  35958. this._generateRadio(this._optionsSubsetDiv, "Normal Speakers", "panningModel", !this._scene.headphone, function (element) {
  35959. if (element.checked) {
  35960. _this._scene.headphone = false;
  35961. }
  35962. });
  35963. this._generateCheckBox(this._optionsSubsetDiv, "Disable audio", !this._scene.audioEnabled, function (element) {
  35964. _this._scene.audioEnabled = !element.checked;
  35965. });
  35966. }
  35967. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  35968. this._generateTexBox(this._optionsSubsetDiv, "<b>Viewers:</b>", this.accentColor);
  35969. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", false, function (element) {
  35970. if (!element.checked) {
  35971. _this._clearSkeletonViewers();
  35972. return;
  35973. }
  35974. for (var index = 0; index < _this._scene.meshes.length; index++) {
  35975. var mesh = _this._scene.meshes[index];
  35976. if (mesh.skeleton) {
  35977. var found = false;
  35978. for (var sIndex = 0; sIndex < _this._skeletonViewers.length; sIndex++) {
  35979. if (_this._skeletonViewers[sIndex].skeleton === mesh.skeleton) {
  35980. found = true;
  35981. break;
  35982. }
  35983. }
  35984. if (found) {
  35985. continue;
  35986. }
  35987. var viewer = new BABYLON.Debug.SkeletonViewer(mesh.skeleton, mesh, _this._scene);
  35988. viewer.isEnabled = true;
  35989. _this._skeletonViewers.push(viewer);
  35990. }
  35991. }
  35992. });
  35993. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  35994. this._generateTexBox(this._optionsSubsetDiv, "<b>Tools:</b>", this.accentColor);
  35995. this._generateButton(this._optionsSubsetDiv, "Dump rendertargets", function (element) { _this._scene.dumpNextRenderTargets = true; });
  35996. this._generateButton(this._optionsSubsetDiv, "Run SceneOptimizer", function (element) { BABYLON.SceneOptimizer.OptimizeAsync(_this._scene); });
  35997. this._generateButton(this._optionsSubsetDiv, "Log camera object", function (element) {
  35998. if (_this._camera) {
  35999. console.log(_this._camera);
  36000. }
  36001. else {
  36002. console.warn("No camera defined, or debug layer created before camera creation!");
  36003. }
  36004. });
  36005. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  36006. this._globalDiv.appendChild(this._statsDiv);
  36007. this._globalDiv.appendChild(this._logDiv);
  36008. this._globalDiv.appendChild(this._optionsDiv);
  36009. this._globalDiv.appendChild(this._treeDiv);
  36010. }
  36011. };
  36012. DebugLayer.prototype._displayStats = function () {
  36013. var scene = this._scene;
  36014. var engine = scene.getEngine();
  36015. var glInfo = engine.getGlInfo();
  36016. this._statsSubsetDiv.innerHTML = "Babylon.js v" + BABYLON.Engine.Version + " - <b>" + BABYLON.Tools.Format(engine.getFps(), 0) + " fps</b><br><br>"
  36017. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  36018. + "<b>Count</b><br>"
  36019. + "Total meshes: " + scene.meshes.length + "<br>"
  36020. + "Total lights: " + scene.lights.length + "<br>"
  36021. + "Total vertices: " + scene.getTotalVertices() + "<br>"
  36022. + "Total materials: " + scene.materials.length + "<br>"
  36023. + "Total textures: " + scene.textures.length + "<br>"
  36024. + "Active meshes: " + scene.getActiveMeshes().length + "<br>"
  36025. + "Active indices: " + scene.getActiveIndices() + "<br>"
  36026. + "Active bones: " + scene.getActiveBones() + "<br>"
  36027. + "Active particles: " + scene.getActiveParticles() + "<br>"
  36028. + "<b>Draw calls: " + engine.drawCalls + "</b><br><br>"
  36029. + "<b>Duration</b><br>"
  36030. + "Meshes selection:</i> " + BABYLON.Tools.Format(scene.getEvaluateActiveMeshesDuration()) + " ms<br>"
  36031. + "Render Targets: " + BABYLON.Tools.Format(scene.getRenderTargetsDuration()) + " ms<br>"
  36032. + "Particles: " + BABYLON.Tools.Format(scene.getParticlesDuration()) + " ms<br>"
  36033. + "Sprites: " + BABYLON.Tools.Format(scene.getSpritesDuration()) + " ms<br><br>"
  36034. + "Render: <b>" + BABYLON.Tools.Format(scene.getRenderDuration()) + " ms</b><br>"
  36035. + "Frame: " + BABYLON.Tools.Format(scene.getLastFrameDuration()) + " ms<br>"
  36036. + "Potential FPS: " + BABYLON.Tools.Format(1000.0 / scene.getLastFrameDuration(), 0) + "<br>"
  36037. + "Resolution: " + engine.getRenderWidth() + "x" + engine.getRenderHeight() + "<br><br>"
  36038. + "</div>"
  36039. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  36040. + "<b>Extensions</b><br>"
  36041. + "Std derivatives: " + (engine.getCaps().standardDerivatives ? "Yes" : "No") + "<br>"
  36042. + "Compressed textures: " + (engine.getCaps().s3tc ? "Yes" : "No") + "<br>"
  36043. + "Hardware instances: " + (engine.getCaps().instancedArrays ? "Yes" : "No") + "<br>"
  36044. + "Texture float: " + (engine.getCaps().textureFloat ? "Yes" : "No") + "<br><br>"
  36045. + "32bits indices: " + (engine.getCaps().uintIndices ? "Yes" : "No") + "<br>"
  36046. + "Fragment depth: " + (engine.getCaps().fragmentDepthSupported ? "Yes" : "No") + "<br>"
  36047. + "High precision shaders: " + (engine.getCaps().highPrecisionShaderSupported ? "Yes" : "No") + "<br>"
  36048. + "Draw buffers: " + (engine.getCaps().drawBuffersExtension ? "Yes" : "No") + "<br>"
  36049. + "</div><br>"
  36050. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  36051. + "<b>Caps.</b><br>"
  36052. + "Max textures units: " + engine.getCaps().maxTexturesImageUnits + "<br>"
  36053. + "Max textures size: " + engine.getCaps().maxTextureSize + "<br>"
  36054. + "Max anisotropy: " + engine.getCaps().maxAnisotropy + "<br>"
  36055. + "<b>Info</b><br>"
  36056. + "WebGL feature level: " + engine.webGLVersion + "<br>"
  36057. + glInfo.version + "<br>"
  36058. + "</div><br>"
  36059. + glInfo.renderer + "<br>";
  36060. if (this.customStatsFunction) {
  36061. this._statsSubsetDiv.innerHTML += this.customStatsFunction();
  36062. }
  36063. };
  36064. return DebugLayer;
  36065. }());
  36066. BABYLON.DebugLayer = DebugLayer;
  36067. })(BABYLON || (BABYLON = {}));
  36068. var BABYLON;
  36069. (function (BABYLON) {
  36070. var SIMDVector3 = (function () {
  36071. function SIMDVector3() {
  36072. }
  36073. SIMDVector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  36074. var v = SIMD.float32x4.loadXYZ(vector._data, 0);
  36075. var m0 = SIMD.float32x4.load(transformation.m, 0);
  36076. var m1 = SIMD.float32x4.load(transformation.m, 4);
  36077. var m2 = SIMD.float32x4.load(transformation.m, 8);
  36078. var m3 = SIMD.float32x4.load(transformation.m, 12);
  36079. 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));
  36080. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  36081. SIMD.float32x4.storeXYZ(result._data, 0, r);
  36082. };
  36083. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  36084. var v0 = SIMD.float32x4.splat(x);
  36085. var v1 = SIMD.float32x4.splat(y);
  36086. var v2 = SIMD.float32x4.splat(z);
  36087. var m0 = SIMD.float32x4.load(transformation.m, 0);
  36088. var m1 = SIMD.float32x4.load(transformation.m, 4);
  36089. var m2 = SIMD.float32x4.load(transformation.m, 8);
  36090. var m3 = SIMD.float32x4.load(transformation.m, 12);
  36091. 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));
  36092. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  36093. SIMD.float32x4.storeXYZ(result._data, 0, r);
  36094. };
  36095. return SIMDVector3;
  36096. }());
  36097. BABYLON.SIMDVector3 = SIMDVector3;
  36098. var SIMDMatrix = (function () {
  36099. function SIMDMatrix() {
  36100. }
  36101. SIMDMatrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  36102. if (offset === void 0) { offset = 0; }
  36103. var tm = this.m;
  36104. var om = other.m;
  36105. var om0 = SIMD.float32x4.load(om, 0);
  36106. var om1 = SIMD.float32x4.load(om, 4);
  36107. var om2 = SIMD.float32x4.load(om, 8);
  36108. var om3 = SIMD.float32x4.load(om, 12);
  36109. var tm0 = SIMD.float32x4.load(tm, 0);
  36110. 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)))));
  36111. var tm1 = SIMD.float32x4.load(tm, 4);
  36112. 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)))));
  36113. var tm2 = SIMD.float32x4.load(tm, 8);
  36114. 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)))));
  36115. var tm3 = SIMD.float32x4.load(tm, 12);
  36116. 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)))));
  36117. };
  36118. SIMDMatrix.prototype.invertToRefSIMD = function (other) {
  36119. var src = this.m;
  36120. var dest = other.m;
  36121. var row0, row1, row2, row3;
  36122. var tmp1;
  36123. var minor0, minor1, minor2, minor3;
  36124. var det;
  36125. // Load the 4 rows
  36126. var src0 = SIMD.float32x4.load(src, 0);
  36127. var src1 = SIMD.float32x4.load(src, 4);
  36128. var src2 = SIMD.float32x4.load(src, 8);
  36129. var src3 = SIMD.float32x4.load(src, 12);
  36130. // Transpose the source matrix. Sort of. Not a true transpose operation
  36131. tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  36132. row1 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  36133. row0 = SIMD.float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  36134. row1 = SIMD.float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  36135. tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  36136. row3 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  36137. row2 = SIMD.float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  36138. row3 = SIMD.float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  36139. // This is a true transposition, but it will lead to an incorrect result
  36140. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  36141. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  36142. //row0 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  36143. //row1 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  36144. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  36145. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  36146. //row2 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  36147. //row3 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  36148. // ----
  36149. tmp1 = SIMD.float32x4.mul(row2, row3);
  36150. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  36151. minor0 = SIMD.float32x4.mul(row1, tmp1);
  36152. minor1 = SIMD.float32x4.mul(row0, tmp1);
  36153. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  36154. minor0 = SIMD.float32x4.sub(SIMD.float32x4.mul(row1, tmp1), minor0);
  36155. minor1 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor1);
  36156. minor1 = SIMD.float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  36157. // ----
  36158. tmp1 = SIMD.float32x4.mul(row1, row2);
  36159. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  36160. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor0);
  36161. minor3 = SIMD.float32x4.mul(row0, tmp1);
  36162. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  36163. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row3, tmp1));
  36164. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor3);
  36165. minor3 = SIMD.float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  36166. // ----
  36167. tmp1 = SIMD.float32x4.mul(SIMD.float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  36168. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  36169. row2 = SIMD.float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  36170. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor0);
  36171. minor2 = SIMD.float32x4.mul(row0, tmp1);
  36172. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  36173. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row2, tmp1));
  36174. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor2);
  36175. minor2 = SIMD.float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  36176. // ----
  36177. tmp1 = SIMD.float32x4.mul(row0, row1);
  36178. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  36179. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor2);
  36180. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row2, tmp1), minor3);
  36181. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  36182. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row3, tmp1), minor2);
  36183. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row2, tmp1));
  36184. // ----
  36185. tmp1 = SIMD.float32x4.mul(row0, row3);
  36186. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  36187. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row2, tmp1));
  36188. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor2);
  36189. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  36190. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor1);
  36191. minor2 = SIMD.float32x4.sub(minor2, SIMD.float32x4.mul(row1, tmp1));
  36192. // ----
  36193. tmp1 = SIMD.float32x4.mul(row0, row2);
  36194. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  36195. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor1);
  36196. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row1, tmp1));
  36197. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  36198. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row3, tmp1));
  36199. minor3 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor3);
  36200. // Compute determinant
  36201. det = SIMD.float32x4.mul(row0, minor0);
  36202. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  36203. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  36204. tmp1 = SIMD.float32x4.reciprocalApproximation(det);
  36205. det = SIMD.float32x4.sub(SIMD.float32x4.add(tmp1, tmp1), SIMD.float32x4.mul(det, SIMD.float32x4.mul(tmp1, tmp1)));
  36206. det = SIMD.float32x4.swizzle(det, 0, 0, 0, 0);
  36207. // These shuffles aren't necessary if the faulty transposition is done
  36208. // up at the top of this function.
  36209. //minor0 = SIMD.float32x4.swizzle(minor0, 2, 1, 0, 3);
  36210. //minor1 = SIMD.float32x4.swizzle(minor1, 2, 1, 0, 3);
  36211. //minor2 = SIMD.float32x4.swizzle(minor2, 2, 1, 0, 3);
  36212. //minor3 = SIMD.float32x4.swizzle(minor3, 2, 1, 0, 3);
  36213. // Compute final values by multiplying with 1/det
  36214. minor0 = SIMD.float32x4.mul(det, minor0);
  36215. minor1 = SIMD.float32x4.mul(det, minor1);
  36216. minor2 = SIMD.float32x4.mul(det, minor2);
  36217. minor3 = SIMD.float32x4.mul(det, minor3);
  36218. SIMD.float32x4.store(dest, 0, minor0);
  36219. SIMD.float32x4.store(dest, 4, minor1);
  36220. SIMD.float32x4.store(dest, 8, minor2);
  36221. SIMD.float32x4.store(dest, 12, minor3);
  36222. return this;
  36223. };
  36224. SIMDMatrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  36225. var out = result.m;
  36226. var center = SIMD.float32x4(targetRef.x, targetRef.y, targetRef.z, 0);
  36227. var eye = SIMD.float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0);
  36228. var up = SIMD.float32x4(upRef.x, upRef.y, upRef.z, 0);
  36229. // cc.kmVec3Subtract(f, pCenter, pEye);
  36230. var f = SIMD.float32x4.sub(center, eye);
  36231. // cc.kmVec3Normalize(f, f);
  36232. var tmp = SIMD.float32x4.mul(f, f);
  36233. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  36234. f = SIMD.float32x4.mul(f, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  36235. // cc.kmVec3Assign(up, pUp);
  36236. // cc.kmVec3Normalize(up, up);
  36237. tmp = SIMD.float32x4.mul(up, up);
  36238. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  36239. up = SIMD.float32x4.mul(up, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  36240. // cc.kmVec3Cross(s, f, up);
  36241. 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)));
  36242. // cc.kmVec3Normalize(s, s);
  36243. tmp = SIMD.float32x4.mul(s, s);
  36244. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  36245. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  36246. // cc.kmVec3Cross(u, s, f);
  36247. 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)));
  36248. // cc.kmVec3Normalize(s, s);
  36249. tmp = SIMD.float32x4.mul(s, s);
  36250. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  36251. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  36252. var zero = SIMD.float32x4.splat(0.0);
  36253. s = SIMD.float32x4.neg(s);
  36254. var tmp01 = SIMD.float32x4.shuffle(s, u, 0, 1, 4, 5);
  36255. var tmp23 = SIMD.float32x4.shuffle(f, zero, 0, 1, 4, 5);
  36256. var a0 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  36257. var a1 = SIMD.float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  36258. tmp01 = SIMD.float32x4.shuffle(s, u, 2, 3, 6, 7);
  36259. tmp23 = SIMD.float32x4.shuffle(f, zero, 2, 3, 6, 7);
  36260. var a2 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  36261. var a3 = SIMD.float32x4(0.0, 0.0, 0.0, 1.0);
  36262. var b0 = SIMD.float32x4(1.0, 0.0, 0.0, 0.0);
  36263. var b1 = SIMD.float32x4(0.0, 1.0, 0.0, 0.0);
  36264. var b2 = SIMD.float32x4(0.0, 0.0, 1.0, 0.0);
  36265. var b3 = SIMD.float32x4.neg(eye);
  36266. b3 = SIMD.float32x4.withW(b3, 1.0);
  36267. 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)))));
  36268. 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)))));
  36269. 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)))));
  36270. 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)))));
  36271. };
  36272. return SIMDMatrix;
  36273. }());
  36274. BABYLON.SIMDMatrix = SIMDMatrix;
  36275. var previousMultiplyToArray = BABYLON.Matrix.prototype.multiplyToArray;
  36276. var previousInvertToRef = BABYLON.Matrix.prototype.invertToRef;
  36277. var previousLookAtLHToRef = BABYLON.Matrix.LookAtLHToRef;
  36278. var previousTransformCoordinatesToRef = BABYLON.Vector3.TransformCoordinatesToRef;
  36279. var previousTransformCoordinatesFromFloatsToRef = BABYLON.Vector3.TransformCoordinatesFromFloatsToRef;
  36280. var SIMDHelper = (function () {
  36281. function SIMDHelper() {
  36282. }
  36283. Object.defineProperty(SIMDHelper, "IsEnabled", {
  36284. get: function () {
  36285. return SIMDHelper._isEnabled;
  36286. },
  36287. enumerable: true,
  36288. configurable: true
  36289. });
  36290. SIMDHelper.DisableSIMD = function () {
  36291. // Replace functions
  36292. BABYLON.Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  36293. BABYLON.Matrix.prototype.invertToRef = previousInvertToRef;
  36294. BABYLON.Matrix.LookAtLHToRef = previousLookAtLHToRef;
  36295. BABYLON.Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  36296. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  36297. SIMDHelper._isEnabled = false;
  36298. };
  36299. SIMDHelper.EnableSIMD = function () {
  36300. if (window.SIMD === undefined) {
  36301. return;
  36302. }
  36303. // Replace functions
  36304. BABYLON.Matrix.prototype.multiplyToArray = SIMDMatrix.prototype.multiplyToArraySIMD;
  36305. BABYLON.Matrix.prototype.invertToRef = SIMDMatrix.prototype.invertToRefSIMD;
  36306. BABYLON.Matrix.LookAtLHToRef = SIMDMatrix.LookAtLHToRefSIMD;
  36307. BABYLON.Vector3.TransformCoordinatesToRef = SIMDVector3.TransformCoordinatesToRefSIMD;
  36308. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD;
  36309. Object.defineProperty(BABYLON.Vector3.prototype, "x", {
  36310. get: function () { return this._data[0]; },
  36311. set: function (value) {
  36312. if (!this._data) {
  36313. this._data = new Float32Array(3);
  36314. }
  36315. this._data[0] = value;
  36316. }
  36317. });
  36318. Object.defineProperty(BABYLON.Vector3.prototype, "y", {
  36319. get: function () { return this._data[1]; },
  36320. set: function (value) {
  36321. this._data[1] = value;
  36322. }
  36323. });
  36324. Object.defineProperty(BABYLON.Vector3.prototype, "z", {
  36325. get: function () { return this._data[2]; },
  36326. set: function (value) {
  36327. this._data[2] = value;
  36328. }
  36329. });
  36330. SIMDHelper._isEnabled = true;
  36331. };
  36332. SIMDHelper._isEnabled = false;
  36333. return SIMDHelper;
  36334. }());
  36335. BABYLON.SIMDHelper = SIMDHelper;
  36336. })(BABYLON || (BABYLON = {}));
  36337. var BABYLON;
  36338. (function (BABYLON) {
  36339. /**
  36340. * This class describe a rectangle that were added to the map.
  36341. * You have access to its coordinates either in pixel or normalized (UV)
  36342. */
  36343. var PackedRect = (function () {
  36344. function PackedRect(root, parent, pos, size) {
  36345. this._pos = pos;
  36346. this._size = size;
  36347. this._root = root;
  36348. this._parent = parent;
  36349. }
  36350. Object.defineProperty(PackedRect.prototype, "pos", {
  36351. /**
  36352. * @returns the position of this node into the map
  36353. */
  36354. get: function () {
  36355. return this._pos;
  36356. },
  36357. enumerable: true,
  36358. configurable: true
  36359. });
  36360. Object.defineProperty(PackedRect.prototype, "contentSize", {
  36361. /**
  36362. * @returns the size of the rectangle this node handles
  36363. */
  36364. get: function () {
  36365. return this._contentSize;
  36366. },
  36367. enumerable: true,
  36368. configurable: true
  36369. });
  36370. Object.defineProperty(PackedRect.prototype, "UVs", {
  36371. /**
  36372. * Compute the UV of the top/left, top/right, bottom/right, bottom/left points of the rectangle this node handles into the map
  36373. * @returns And array of 4 Vector2, containing UV coordinates for the four corners of the Rectangle into the map
  36374. */
  36375. get: function () {
  36376. return this.getUVsForCustomSize(this._root._size);
  36377. },
  36378. enumerable: true,
  36379. configurable: true
  36380. });
  36381. /**
  36382. * 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.
  36383. * This method will return the UVs for this part by given the custom size of what you really use
  36384. * @param customSize must be less/equal to the allocated size, UV will be compute from this
  36385. */
  36386. PackedRect.prototype.getUVsForCustomSize = function (customSize) {
  36387. var mainWidth = this._root._size.width;
  36388. var mainHeight = this._root._size.height;
  36389. var topLeft = new BABYLON.Vector2(this._pos.x / mainWidth, this._pos.y / mainHeight);
  36390. var rightBottom = new BABYLON.Vector2((this._pos.x + customSize.width - 1) / mainWidth, (this._pos.y + customSize.height - 1) / mainHeight);
  36391. var uvs = new Array();
  36392. uvs.push(topLeft);
  36393. uvs.push(new BABYLON.Vector2(rightBottom.x, topLeft.y));
  36394. uvs.push(rightBottom);
  36395. uvs.push(new BABYLON.Vector2(topLeft.x, rightBottom.y));
  36396. return uvs;
  36397. };
  36398. /**
  36399. * Free this rectangle from the map.
  36400. * Call this method when you no longer need the rectangle to be in the map.
  36401. */
  36402. PackedRect.prototype.freeContent = function () {
  36403. if (!this.contentSize) {
  36404. return;
  36405. }
  36406. this._contentSize = null;
  36407. // If everything below is also free, reset the whole node, and attempt to reset parents if they also become free
  36408. this.attemptDefrag();
  36409. };
  36410. Object.defineProperty(PackedRect.prototype, "isUsed", {
  36411. get: function () {
  36412. return this._contentSize != null || this._leftNode != null;
  36413. },
  36414. enumerable: true,
  36415. configurable: true
  36416. });
  36417. PackedRect.prototype.findAndSplitNode = function (contentSize) {
  36418. var node = this.findNode(contentSize);
  36419. // Not enough space...
  36420. if (!node) {
  36421. return null;
  36422. }
  36423. node.splitNode(contentSize);
  36424. return node;
  36425. };
  36426. PackedRect.prototype.findNode = function (size) {
  36427. var resNode = null;
  36428. // If this node is used, recurse to each of his subNodes to find an available one in its branch
  36429. if (this.isUsed) {
  36430. if (this._leftNode) {
  36431. resNode = this._leftNode.findNode(size);
  36432. }
  36433. if (!resNode && this._rightNode) {
  36434. resNode = this._rightNode.findNode(size);
  36435. }
  36436. if (!resNode && this._bottomNode) {
  36437. resNode = this._bottomNode.findNode(size);
  36438. }
  36439. }
  36440. else if (this._initialSize && (size.width <= this._initialSize.width) && (size.height <= this._initialSize.height)) {
  36441. resNode = this;
  36442. }
  36443. else if ((size.width <= this._size.width) && (size.height <= this._size.height)) {
  36444. resNode = this;
  36445. }
  36446. return resNode;
  36447. };
  36448. PackedRect.prototype.splitNode = function (contentSize) {
  36449. // 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)
  36450. if (!this._contentSize && this._initialSize) {
  36451. 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));
  36452. return this._leftNode.splitNode(contentSize);
  36453. }
  36454. else {
  36455. this._contentSize = contentSize.clone();
  36456. this._initialSize = contentSize.clone();
  36457. if (contentSize.width !== this._size.width) {
  36458. 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));
  36459. }
  36460. if (contentSize.height !== this._size.height) {
  36461. 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));
  36462. }
  36463. return this;
  36464. }
  36465. };
  36466. PackedRect.prototype.attemptDefrag = function () {
  36467. if (!this.isUsed && this.isRecursiveFree) {
  36468. this.clearNode();
  36469. if (this._parent) {
  36470. this._parent.attemptDefrag();
  36471. }
  36472. }
  36473. };
  36474. PackedRect.prototype.clearNode = function () {
  36475. this._initialSize = null;
  36476. this._rightNode = null;
  36477. this._bottomNode = null;
  36478. };
  36479. Object.defineProperty(PackedRect.prototype, "isRecursiveFree", {
  36480. get: function () {
  36481. return !this.contentSize && (!this._leftNode || this._leftNode.isRecursiveFree) && (!this._rightNode || this._rightNode.isRecursiveFree) && (!this._bottomNode || this._bottomNode.isRecursiveFree);
  36482. },
  36483. enumerable: true,
  36484. configurable: true
  36485. });
  36486. PackedRect.prototype.evalFreeSize = function (size) {
  36487. var levelSize = 0;
  36488. if (!this.isUsed) {
  36489. if (this._initialSize) {
  36490. levelSize = this._initialSize.surface;
  36491. }
  36492. else {
  36493. levelSize = this._size.surface;
  36494. }
  36495. }
  36496. if (this._rightNode) {
  36497. levelSize += this._rightNode.evalFreeSize(0);
  36498. }
  36499. if (this._bottomNode) {
  36500. levelSize += this._bottomNode.evalFreeSize(0);
  36501. }
  36502. return levelSize + size;
  36503. };
  36504. return PackedRect;
  36505. }());
  36506. BABYLON.PackedRect = PackedRect;
  36507. /**
  36508. * The purpose of this class is to pack several Rectangles into a big map, while trying to fit everything as optimally as possible.
  36509. * This class is typically used to build lightmaps, sprite map or to pack several little textures into a big one.
  36510. * 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.
  36511. */
  36512. var RectPackingMap = (function (_super) {
  36513. __extends(RectPackingMap, _super);
  36514. /**
  36515. * Create an instance of the object with a dimension using the given size
  36516. * @param size The dimension of the rectangle that will contain all the sub ones.
  36517. */
  36518. function RectPackingMap(size) {
  36519. _super.call(this, null, null, BABYLON.Vector2.Zero(), size);
  36520. this._root = this;
  36521. }
  36522. /**
  36523. * Add a rectangle, finding the best location to store it into the map
  36524. * @param size the dimension of the rectangle to store
  36525. * @return the Node containing the rectangle information, or null if we couldn't find a free spot
  36526. */
  36527. RectPackingMap.prototype.addRect = function (size) {
  36528. var node = this.findAndSplitNode(size);
  36529. return node;
  36530. };
  36531. Object.defineProperty(RectPackingMap.prototype, "freeSpace", {
  36532. /**
  36533. * Return the current space free normalized between [0;1]
  36534. * @returns {}
  36535. */
  36536. get: function () {
  36537. var freeSize = 0;
  36538. freeSize = this.evalFreeSize(freeSize);
  36539. return freeSize / (this._size.width * this._size.height);
  36540. },
  36541. enumerable: true,
  36542. configurable: true
  36543. });
  36544. return RectPackingMap;
  36545. }(PackedRect));
  36546. BABYLON.RectPackingMap = RectPackingMap;
  36547. })(BABYLON || (BABYLON = {}));
  36548. var BABYLON;
  36549. (function (BABYLON) {
  36550. var DynamicFloatArrayElementInfo = (function () {
  36551. function DynamicFloatArrayElementInfo() {
  36552. }
  36553. return DynamicFloatArrayElementInfo;
  36554. }());
  36555. BABYLON.DynamicFloatArrayElementInfo = DynamicFloatArrayElementInfo;
  36556. /**
  36557. * 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.
  36558. * The intent is to maintain through time data that will be bound to a WebGlBuffer with the ability to change add/remove elements.
  36559. * It was first built to efficiently maintain the WebGlBuffer that contain instancing based data.
  36560. * 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.
  36561. * 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.
  36562. * 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".
  36563. */
  36564. var DynamicFloatArray = (function () {
  36565. /**
  36566. * Construct an instance of the dynamic float array
  36567. * @param stride size of one element in float (i.e. not bytes!)
  36568. * @param initialElementCount the number of available entries at construction
  36569. */
  36570. function DynamicFloatArray(stride, initialElementCount) {
  36571. this.compareValueOffset = null;
  36572. this.sortingAscending = true;
  36573. this._stride = stride;
  36574. this.buffer = new Float32Array(stride * initialElementCount);
  36575. this._lastUsed = 0;
  36576. this._firstFree = 0;
  36577. this._allEntries = new Array(initialElementCount);
  36578. this._freeEntries = new Array(initialElementCount);
  36579. for (var i = 0; i < initialElementCount; i++) {
  36580. var element = new DynamicFloatArrayElementInfo();
  36581. element.offset = i * stride;
  36582. this._allEntries[i] = element;
  36583. this._freeEntries[initialElementCount - i - 1] = element;
  36584. }
  36585. }
  36586. /**
  36587. * Allocate an element in the array.
  36588. * @return the element info instance that contains the offset into the main buffer of the element's location.
  36589. * Beware, this offset may change when you call pack()
  36590. */
  36591. DynamicFloatArray.prototype.allocElement = function () {
  36592. if (this._freeEntries.length === 0) {
  36593. this._growBuffer();
  36594. }
  36595. var el = this._freeEntries.pop();
  36596. this._lastUsed = Math.max(el.offset, this._lastUsed);
  36597. if (el.offset === this._firstFree) {
  36598. if (this._freeEntries.length > 0) {
  36599. this._firstFree = this._freeEntries[this._freeEntries.length - 1].offset;
  36600. }
  36601. else {
  36602. this._firstFree += this._stride;
  36603. }
  36604. }
  36605. return el;
  36606. };
  36607. /**
  36608. * Free the element corresponding to the given element info
  36609. * @param elInfo the element that describe the allocated element
  36610. */
  36611. DynamicFloatArray.prototype.freeElement = function (elInfo) {
  36612. this._firstFree = Math.min(elInfo.offset, this._firstFree);
  36613. this._freeEntries.push(elInfo);
  36614. };
  36615. /**
  36616. * This method will pack all the used elements into a linear sequence and put all the free space at the end.
  36617. * 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().
  36618. * @return the subArray that is the view of the used elements area, you can use it as a source to update a WebGLBuffer
  36619. */
  36620. DynamicFloatArray.prototype.pack = function () {
  36621. // no free slot? no need to pack
  36622. if (this._freeEntries.length === 0) {
  36623. return this.buffer;
  36624. }
  36625. // If the buffer is already packed the last used will always be lower than the first free
  36626. // 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.
  36627. if (this._lastUsed < this._firstFree) {
  36628. var elementsBuffer_1 = this.buffer.subarray(0, this._lastUsed + this._stride);
  36629. return elementsBuffer_1;
  36630. }
  36631. var s = this._stride;
  36632. // 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
  36633. var lastFree = new DynamicFloatArrayElementInfo();
  36634. lastFree.offset = this.totalElementCount * s;
  36635. this._freeEntries.push(lastFree);
  36636. var sortedFree = this._freeEntries.sort(function (a, b) { return a.offset - b.offset; });
  36637. var sortedAll = this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  36638. var firstFreeSlotOffset = sortedFree[0].offset;
  36639. var freeZoneSize = 1;
  36640. var occupiedZoneSize = (this.usedElementCount + 1) * s;
  36641. var prevOffset = sortedFree[0].offset;
  36642. for (var i = 1; i < sortedFree.length; i++) {
  36643. // 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
  36644. if (firstFreeSlotOffset >= occupiedZoneSize) {
  36645. break;
  36646. }
  36647. var curFree = sortedFree[i];
  36648. var curOffset = curFree.offset;
  36649. // Compute the distance between this offset and the previous
  36650. var distance = curOffset - prevOffset;
  36651. // If the distance is the stride size, they are adjacent, it good, move to the next
  36652. if (distance === s) {
  36653. // Free zone is one element bigger
  36654. ++freeZoneSize;
  36655. // as we're about to iterate to the next, the cur becomes the previous...
  36656. prevOffset = curOffset;
  36657. continue;
  36658. }
  36659. // Distance is bigger, which means there's x element between the previous free and this one
  36660. var usedRange = (distance / s) - 1;
  36661. // Two cases the free zone is smaller than the data to move or bigger
  36662. // Copy what can fit in the free zone
  36663. var curMoveOffset = curOffset - s;
  36664. var copyCount = Math.min(freeZoneSize, usedRange);
  36665. for (var j = 0; j < copyCount; j++) {
  36666. var freeI = firstFreeSlotOffset / s;
  36667. var curI = curMoveOffset / s;
  36668. var moveEl = sortedAll[curI];
  36669. this._moveElement(moveEl, firstFreeSlotOffset);
  36670. var replacedEl = sortedAll[freeI];
  36671. // set the offset of the element we replaced with a value that will make it discard at the end of the method
  36672. replacedEl.offset = curMoveOffset;
  36673. // Swap the element we moved and the one it replaced in the sorted array to reflect the action we've made
  36674. sortedAll[freeI] = moveEl;
  36675. sortedAll[curI] = replacedEl;
  36676. curMoveOffset -= s;
  36677. firstFreeSlotOffset += s;
  36678. }
  36679. // Free Zone is smaller or equal so it's no longer a free zone, set the new one to the current location
  36680. if (freeZoneSize <= usedRange) {
  36681. firstFreeSlotOffset = curMoveOffset + s;
  36682. freeZoneSize = 1 + copyCount;
  36683. }
  36684. else {
  36685. freeZoneSize = ((curOffset - firstFreeSlotOffset) / s) + 1;
  36686. }
  36687. // as we're about to iterate to the next, the cur becomes the previous...
  36688. prevOffset = curOffset;
  36689. }
  36690. var elementsBuffer = this.buffer.subarray(0, firstFreeSlotOffset);
  36691. this._lastUsed = firstFreeSlotOffset - s;
  36692. this._firstFree = firstFreeSlotOffset;
  36693. sortedFree.pop(); // Remove the last free because that's the one we added at the start of the method
  36694. this._freeEntries = sortedFree.sort(function (a, b) { return b.offset - a.offset; });
  36695. this._allEntries = sortedAll;
  36696. return elementsBuffer;
  36697. };
  36698. DynamicFloatArray.prototype._moveElement = function (element, destOffset) {
  36699. for (var i = 0; i < this._stride; i++) {
  36700. this.buffer[destOffset + i] = this.buffer[element.offset + i];
  36701. }
  36702. element.offset = destOffset;
  36703. };
  36704. DynamicFloatArray.prototype._growBuffer = function () {
  36705. // Allocate the new buffer with 50% more entries, copy the content of the current one
  36706. var newElCount = Math.floor(this.totalElementCount * 1.5);
  36707. var newBuffer = new Float32Array(newElCount * this._stride);
  36708. newBuffer.set(this.buffer);
  36709. var curCount = this.totalElementCount;
  36710. var addedCount = newElCount - this.totalElementCount;
  36711. for (var i = 0; i < addedCount; i++) {
  36712. var element = new DynamicFloatArrayElementInfo();
  36713. element.offset = (curCount + i) * this.stride;
  36714. this._allEntries.push(element);
  36715. this._freeEntries[addedCount - i - 1] = element;
  36716. }
  36717. this._firstFree = curCount * this.stride;
  36718. this.buffer = newBuffer;
  36719. };
  36720. Object.defineProperty(DynamicFloatArray.prototype, "totalElementCount", {
  36721. /**
  36722. * Get the total count of entries that can fit in the current buffer
  36723. * @returns the elements count
  36724. */
  36725. get: function () {
  36726. return this._allEntries.length;
  36727. },
  36728. enumerable: true,
  36729. configurable: true
  36730. });
  36731. Object.defineProperty(DynamicFloatArray.prototype, "freeElementCount", {
  36732. /**
  36733. * Get the count of free entries that can still be allocated without resizing the buffer
  36734. * @returns the free elements count
  36735. */
  36736. get: function () {
  36737. return this._freeEntries.length;
  36738. },
  36739. enumerable: true,
  36740. configurable: true
  36741. });
  36742. Object.defineProperty(DynamicFloatArray.prototype, "usedElementCount", {
  36743. /**
  36744. * Get the count of allocated elements
  36745. * @returns the allocated elements count
  36746. */
  36747. get: function () {
  36748. return this._allEntries.length - this._freeEntries.length;
  36749. },
  36750. enumerable: true,
  36751. configurable: true
  36752. });
  36753. Object.defineProperty(DynamicFloatArray.prototype, "stride", {
  36754. /**
  36755. * Return the size of one element in float
  36756. * @returns the size in float
  36757. */
  36758. get: function () {
  36759. return this._stride;
  36760. },
  36761. enumerable: true,
  36762. configurable: true
  36763. });
  36764. DynamicFloatArray.prototype.sort = function () {
  36765. var _this = this;
  36766. if (!this.compareValueOffset) {
  36767. throw new Error("The DynamicFloatArray.sort() method needs a valid 'compareValueOffset' property");
  36768. }
  36769. var count = this.usedElementCount;
  36770. // Do we have to (re)create the sort table?
  36771. if (!this._sortTable || this._sortTable.length < count) {
  36772. // 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...
  36773. var newCount = Math.min(this.totalElementCount, count * 2);
  36774. this._sortTable = new Array(newCount);
  36775. }
  36776. if (!this._sortedTable || this._sortedTable.length !== count) {
  36777. this._sortedTable = new Array(count);
  36778. }
  36779. // Because, you know...
  36780. this.pack();
  36781. //let stride = this.stride;
  36782. //for (let i = 0; i < count; i++) {
  36783. // let si = this._sortTable[i];
  36784. // if (!si) {
  36785. // si = new SortInfo();
  36786. // this._sortTable[i] = si;
  36787. // }
  36788. // si.entry = this._allEntries[i];
  36789. // si.compareData = this.buffer[si.entry.offset + this.compareValueOffset];
  36790. // si.swapedOffset = null;
  36791. // this._sortedTable[i] = si;
  36792. //}
  36793. var curOffset = 0;
  36794. var stride = this.stride;
  36795. for (var i = 0; i < count; i++, curOffset += stride) {
  36796. var si = this._sortTable[i];
  36797. if (!si) {
  36798. si = new SortInfo();
  36799. this._sortTable[i] = si;
  36800. }
  36801. si.compareData = this.buffer[curOffset + this.compareValueOffset];
  36802. si.offset = curOffset;
  36803. si.swapedOffset = null;
  36804. this._sortedTable[i] = si;
  36805. }
  36806. // Let's sort the sorted table, we want to keep a track of the original one (that's why we have two buffers)
  36807. if (this.sortingAscending) {
  36808. this._sortedTable.sort(function (a, b) { return a.compareData - b.compareData; });
  36809. }
  36810. else {
  36811. this._sortedTable.sort(function (a, b) { return b.compareData - a.compareData; });
  36812. }
  36813. var swapElements = function (src, dst) {
  36814. for (var i = 0; i < stride; i++) {
  36815. var tps = _this.buffer[dst + i];
  36816. _this.buffer[dst + i] = _this.buffer[src + i];
  36817. _this.buffer[src + i] = tps;
  36818. }
  36819. };
  36820. // 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:
  36821. // 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),
  36822. // and I still want something with a good algorithm complexity.
  36823. // 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,
  36824. // we need sortTable for that, it contains the original layout of SortInfo object, not the sorted one.
  36825. // The best way is to use an extra field in SortInfo, because potentially every element can be replaced.
  36826. // 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
  36827. // until we find a SortInfo object without a swapedOffset which means we got the right location
  36828. // 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
  36829. // than a double allocation of the whole float32Array or a O(n²/2) typical algorithm.
  36830. for (var i = 0; i < count; i++) {
  36831. // Get the element to move
  36832. var sourceSI = this._sortedTable[i];
  36833. var destSI = this._sortTable[i];
  36834. var sourceOff = sourceSI.offset;
  36835. // If the source changed location, find the new one
  36836. if (sourceSI.swapedOffset) {
  36837. // Follow the swapedOffset until there's none, it will mean that curSI contains the new location in its offset member
  36838. var curSI = sourceSI;
  36839. while (curSI.swapedOffset) {
  36840. curSI = this._sortTable[curSI.swapedOffset / stride];
  36841. }
  36842. // Finally get the right location
  36843. sourceOff = curSI.offset;
  36844. }
  36845. // Tag the element being replaced with its new location
  36846. destSI.swapedOffset = sourceOff;
  36847. // Swap elements (only if needed)
  36848. if (sourceOff !== destSI.offset) {
  36849. swapElements(sourceOff, destSI.offset);
  36850. }
  36851. // Update the offset in the corresponding DFAE
  36852. //sourceSI.entry.offset = destSI.entry.offset;
  36853. this._allEntries[sourceSI.offset / stride].offset = destSI.offset;
  36854. }
  36855. this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  36856. return true;
  36857. };
  36858. return DynamicFloatArray;
  36859. }());
  36860. BABYLON.DynamicFloatArray = DynamicFloatArray;
  36861. var SortInfo = (function () {
  36862. function SortInfo() {
  36863. this.compareData = this.offset = this.swapedOffset = null;
  36864. }
  36865. return SortInfo;
  36866. }());
  36867. })(BABYLON || (BABYLON = {}));
  36868. var BABYLON;
  36869. (function (BABYLON) {
  36870. /**
  36871. * This class given information about a given character.
  36872. */
  36873. var CharInfo = (function () {
  36874. function CharInfo() {
  36875. }
  36876. return CharInfo;
  36877. }());
  36878. BABYLON.CharInfo = CharInfo;
  36879. var FontTexture = (function (_super) {
  36880. __extends(FontTexture, _super);
  36881. /**
  36882. * Create a new instance of the FontTexture class
  36883. * @param name the name of the texture
  36884. * @param font the font to use, use the W3C CSS notation
  36885. * @param scene the scene that owns the texture
  36886. * @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
  36887. * @param samplingMode the texture sampling mode
  36888. * @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.
  36889. */
  36890. function FontTexture(name, font, scene, maxCharCount, samplingMode, superSample) {
  36891. if (maxCharCount === void 0) { maxCharCount = 200; }
  36892. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  36893. if (superSample === void 0) { superSample = false; }
  36894. _super.call(this, null, scene, true, false, samplingMode);
  36895. this._charInfos = {};
  36896. this._curCharCount = 0;
  36897. this._lastUpdateCharCount = -1;
  36898. this._usedCounter = 1;
  36899. this.name = name;
  36900. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  36901. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  36902. this._superSample = false;
  36903. if (superSample) {
  36904. var sfont = this.getSuperSampleFont(font);
  36905. if (sfont) {
  36906. this._superSample = true;
  36907. font = sfont;
  36908. }
  36909. }
  36910. // First canvas creation to determine the size of the texture to create
  36911. this._canvas = document.createElement("canvas");
  36912. this._context = this._canvas.getContext("2d");
  36913. this._context.font = font;
  36914. this._context.fillStyle = "white";
  36915. var res = this.getFontHeight(font);
  36916. this._lineHeightSuper = res.height;
  36917. this._lineHeight = this._superSample ? (this._lineHeightSuper / 2) : this._lineHeightSuper;
  36918. this._offset = res.offset - 1;
  36919. var maxCharWidth = this._context.measureText("W").width;
  36920. this._spaceWidthSuper = this._context.measureText(" ").width;
  36921. this._spaceWidth = this._superSample ? (this._spaceWidthSuper / 2) : this._spaceWidthSuper;
  36922. // This is an approximate size, but should always be able to fit at least the maxCharCount
  36923. var totalEstSurface = this._lineHeightSuper * maxCharWidth * maxCharCount;
  36924. var edge = Math.sqrt(totalEstSurface);
  36925. var textSize = Math.pow(2, Math.ceil(Math.log(edge) / Math.log(2)));
  36926. // Create the texture that will store the font characters
  36927. this._texture = scene.getEngine().createDynamicTexture(textSize, textSize, false, samplingMode);
  36928. var textureSize = this.getSize();
  36929. // Recreate a new canvas with the final size: the one matching the texture (resizing the previous one doesn't work as one would expect...)
  36930. this._canvas = document.createElement("canvas");
  36931. this._canvas.width = textureSize.width;
  36932. this._canvas.height = textureSize.height;
  36933. this._context = this._canvas.getContext("2d");
  36934. this._context.textBaseline = "top";
  36935. this._context.font = font;
  36936. this._context.fillStyle = "white";
  36937. this._context.imageSmoothingEnabled = false;
  36938. this._currentFreePosition = BABYLON.Vector2.Zero();
  36939. // Add the basic ASCII based characters
  36940. for (var i = 0x20; i < 0x7F; i++) {
  36941. var c = String.fromCharCode(i);
  36942. this.getChar(c);
  36943. }
  36944. this.update();
  36945. }
  36946. Object.defineProperty(FontTexture.prototype, "isSuperSampled", {
  36947. get: function () {
  36948. return this._superSample;
  36949. },
  36950. enumerable: true,
  36951. configurable: true
  36952. });
  36953. Object.defineProperty(FontTexture.prototype, "spaceWidth", {
  36954. get: function () {
  36955. return this._spaceWidth;
  36956. },
  36957. enumerable: true,
  36958. configurable: true
  36959. });
  36960. Object.defineProperty(FontTexture.prototype, "lineHeight", {
  36961. get: function () {
  36962. return this._lineHeight;
  36963. },
  36964. enumerable: true,
  36965. configurable: true
  36966. });
  36967. FontTexture.GetCachedFontTexture = function (scene, fontName, supersample) {
  36968. if (supersample === void 0) { supersample = false; }
  36969. var s = scene;
  36970. if (!s.__fontTextureCache__) {
  36971. s.__fontTextureCache__ = new BABYLON.StringDictionary();
  36972. }
  36973. var dic = s.__fontTextureCache__;
  36974. var lfn = fontName.toLocaleLowerCase() + (supersample ? "_+SS" : "_-SS");
  36975. var ft = dic.get(lfn);
  36976. if (ft) {
  36977. ++ft._usedCounter;
  36978. return ft;
  36979. }
  36980. ft = new FontTexture(null, fontName, scene, supersample ? 100 : 200, BABYLON.Texture.BILINEAR_SAMPLINGMODE, supersample);
  36981. dic.add(lfn, ft);
  36982. return ft;
  36983. };
  36984. FontTexture.ReleaseCachedFontTexture = function (scene, fontName, supersample) {
  36985. if (supersample === void 0) { supersample = false; }
  36986. var s = scene;
  36987. var dic = s.__fontTextureCache__;
  36988. if (!dic) {
  36989. return;
  36990. }
  36991. var lfn = fontName.toLocaleLowerCase() + (supersample ? "_+SS" : "_-SS");
  36992. var font = dic.get(lfn);
  36993. if (--font._usedCounter === 0) {
  36994. dic.remove(lfn);
  36995. font.dispose();
  36996. }
  36997. };
  36998. /**
  36999. * Make sure the given char is present in the font map.
  37000. * @param char the character to get or add
  37001. * @return the CharInfo instance corresponding to the given character
  37002. */
  37003. FontTexture.prototype.getChar = function (char) {
  37004. if (char.length !== 1) {
  37005. return null;
  37006. }
  37007. var info = this._charInfos[char];
  37008. if (info) {
  37009. return info;
  37010. }
  37011. info = new CharInfo();
  37012. var measure = this._context.measureText(char);
  37013. var textureSize = this.getSize();
  37014. // we reached the end of the current line?
  37015. var width = Math.round(measure.width);
  37016. var xMargin = 1 + Math.ceil(this._lineHeightSuper / 15); // Right now this empiric formula seems to work...
  37017. var yMargin = xMargin;
  37018. if (this._currentFreePosition.x + width + xMargin > textureSize.width) {
  37019. this._currentFreePosition.x = 0;
  37020. this._currentFreePosition.y += this._lineHeightSuper + yMargin;
  37021. // No more room?
  37022. if (this._currentFreePosition.y > textureSize.height) {
  37023. return this.getChar("!");
  37024. }
  37025. }
  37026. // Draw the character in the texture
  37027. this._context.fillText(char, this._currentFreePosition.x, this._currentFreePosition.y - this._offset);
  37028. // Fill the CharInfo object
  37029. info.topLeftUV = new BABYLON.Vector2(this._currentFreePosition.x / textureSize.width, this._currentFreePosition.y / textureSize.height);
  37030. info.bottomRightUV = new BABYLON.Vector2((this._currentFreePosition.x + width) / textureSize.width, info.topLeftUV.y + ((this._lineHeightSuper + 2) / textureSize.height));
  37031. info.charWidth = this._superSample ? (width / 2) : width;
  37032. // Add the info structure
  37033. this._charInfos[char] = info;
  37034. this._curCharCount++;
  37035. // Set the next position
  37036. this._currentFreePosition.x += width + xMargin;
  37037. return info;
  37038. };
  37039. FontTexture.prototype.measureText = function (text, tabulationSize) {
  37040. if (tabulationSize === void 0) { tabulationSize = 4; }
  37041. var maxWidth = 0;
  37042. var curWidth = 0;
  37043. var lineCount = 1;
  37044. var charxpos = 0;
  37045. // Parse each char of the string
  37046. for (var _i = 0, text_1 = text; _i < text_1.length; _i++) {
  37047. var char = text_1[_i];
  37048. // Next line feed?
  37049. if (char === "\n") {
  37050. maxWidth = Math.max(maxWidth, curWidth);
  37051. charxpos = 0;
  37052. curWidth = 0;
  37053. ++lineCount;
  37054. continue;
  37055. }
  37056. // Tabulation ?
  37057. if (char === "\t") {
  37058. var nextPos = charxpos + tabulationSize;
  37059. nextPos = nextPos - (nextPos % tabulationSize);
  37060. curWidth += (nextPos - charxpos) * this.spaceWidth;
  37061. charxpos = nextPos;
  37062. continue;
  37063. }
  37064. if (char < " ") {
  37065. continue;
  37066. }
  37067. curWidth += this.getChar(char).charWidth;
  37068. ++charxpos;
  37069. }
  37070. maxWidth = Math.max(maxWidth, curWidth);
  37071. return new BABYLON.Size(maxWidth, lineCount * this.lineHeight);
  37072. };
  37073. FontTexture.prototype.getSuperSampleFont = function (font) {
  37074. // Eternal thank to http://stackoverflow.com/a/10136041/802124
  37075. 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*$/;
  37076. var res = font.toLocaleLowerCase().match(regex);
  37077. if (res == null) {
  37078. return null;
  37079. }
  37080. var size = parseInt(res[4]);
  37081. res[4] = (size * 2).toString() + (res[4].match(/\D+/) || []).pop();
  37082. var newFont = "";
  37083. for (var j = 1; j < res.length; j++) {
  37084. if (res[j] != null) {
  37085. newFont += res[j] + " ";
  37086. }
  37087. }
  37088. return newFont;
  37089. };
  37090. // More info here: https://videlais.com/2014/03/16/the-many-and-varied-problems-with-measuring-font-height-for-html5-canvas/
  37091. FontTexture.prototype.getFontHeight = function (font) {
  37092. var fontDraw = document.createElement("canvas");
  37093. var ctx = fontDraw.getContext('2d');
  37094. ctx.fillRect(0, 0, fontDraw.width, fontDraw.height);
  37095. ctx.textBaseline = 'top';
  37096. ctx.fillStyle = 'white';
  37097. ctx.font = font;
  37098. ctx.fillText('jH|', 0, 0);
  37099. var pixels = ctx.getImageData(0, 0, fontDraw.width, fontDraw.height).data;
  37100. var start = -1;
  37101. var end = -1;
  37102. for (var row = 0; row < fontDraw.height; row++) {
  37103. for (var column = 0; column < fontDraw.width; column++) {
  37104. var index = (row * fontDraw.width + column) * 4;
  37105. if (pixels[index] === 0) {
  37106. if (column === fontDraw.width - 1 && start !== -1) {
  37107. end = row;
  37108. row = fontDraw.height;
  37109. break;
  37110. }
  37111. continue;
  37112. }
  37113. else {
  37114. if (start === -1) {
  37115. start = row;
  37116. }
  37117. break;
  37118. }
  37119. }
  37120. }
  37121. return { height: (end - start) + 1, offset: start - 1 };
  37122. };
  37123. Object.defineProperty(FontTexture.prototype, "canRescale", {
  37124. get: function () {
  37125. return false;
  37126. },
  37127. enumerable: true,
  37128. configurable: true
  37129. });
  37130. FontTexture.prototype.getContext = function () {
  37131. return this._context;
  37132. };
  37133. /**
  37134. * Call this method when you've call getChar() at least one time, this will update the texture if needed.
  37135. * Don't be afraid to call it, if no new character was added, this method simply does nothing.
  37136. */
  37137. FontTexture.prototype.update = function () {
  37138. // Update only if there's new char added since the previous update
  37139. if (this._lastUpdateCharCount < this._curCharCount) {
  37140. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, false, true);
  37141. this._lastUpdateCharCount = this._curCharCount;
  37142. }
  37143. };
  37144. // cloning should be prohibited, there's no point to duplicate this texture at all
  37145. FontTexture.prototype.clone = function () {
  37146. return null;
  37147. };
  37148. return FontTexture;
  37149. }(BABYLON.Texture));
  37150. BABYLON.FontTexture = FontTexture;
  37151. })(BABYLON || (BABYLON = {}));
  37152. var BABYLON;
  37153. (function (BABYLON) {
  37154. var MapTexture = (function (_super) {
  37155. __extends(MapTexture, _super);
  37156. function MapTexture(name, scene, size, samplingMode, useMipMap) {
  37157. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  37158. if (useMipMap === void 0) { useMipMap = false; }
  37159. _super.call(this, null, scene, !useMipMap, false, samplingMode);
  37160. this.name = name;
  37161. this._size = size;
  37162. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  37163. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  37164. // Create the rectPackMap that will allocate portion of the texture
  37165. this._rectPackingMap = new BABYLON.RectPackingMap(new BABYLON.Size(size.width, size.height));
  37166. // Create the texture that will store the content
  37167. this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: !this.noMipmap, type: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT });
  37168. }
  37169. /**
  37170. * Allocate a rectangle of a given size in the texture map
  37171. * @param size the size of the rectangle to allocation
  37172. * @return the PackedRect instance corresponding to the allocated rect or null is there was not enough space to allocate it.
  37173. */
  37174. MapTexture.prototype.allocateRect = function (size) {
  37175. return this._rectPackingMap.addRect(size);
  37176. };
  37177. /**
  37178. * Free a given rectangle from the texture map
  37179. * @param rectInfo the instance corresponding to the rect to free.
  37180. */
  37181. MapTexture.prototype.freeRect = function (rectInfo) {
  37182. if (rectInfo) {
  37183. rectInfo.freeContent();
  37184. }
  37185. };
  37186. Object.defineProperty(MapTexture.prototype, "freeSpace", {
  37187. /**
  37188. * Return the available space in the range of [O;1]. 0 being not space left at all, 1 being an empty texture map.
  37189. * This is the cumulated space, not the biggest available surface. Due to fragmentation you may not allocate a rect corresponding to this surface.
  37190. * @returns {}
  37191. */
  37192. get: function () {
  37193. return this._rectPackingMap.freeSpace;
  37194. },
  37195. enumerable: true,
  37196. configurable: true
  37197. });
  37198. /**
  37199. * Bind the texture to the rendering engine to render in the zone of a given rectangle.
  37200. * 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.
  37201. * Don't forget to call unbindTexture when you're done rendering
  37202. * @param rect the zone to render to
  37203. * @param clear true to clear the portion's color/depth data
  37204. */
  37205. MapTexture.prototype.bindTextureForRect = function (rect, clear) {
  37206. return this.bindTextureForPosSize(rect.pos, rect.contentSize, clear);
  37207. };
  37208. /**
  37209. * Bind the texture to the rendering engine to render in the zone of the given size at the given position.
  37210. * 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.
  37211. * Don't forget to call unbindTexture when you're done rendering
  37212. * @param pos the position into the texture
  37213. * @param size the portion to fit the clip space to
  37214. * @param clear true to clear the portion's color/depth data
  37215. */
  37216. MapTexture.prototype.bindTextureForPosSize = function (pos, size, clear) {
  37217. var engine = this.getScene().getEngine();
  37218. engine.bindFramebuffer(this._texture);
  37219. this._replacedViewport = engine.setDirectViewport(pos.x, pos.y, size.width, size.height);
  37220. if (clear) {
  37221. // We only want to clear the part of the texture we're binding to, only the scissor can help us to achieve that
  37222. engine.scissorClear(pos.x, pos.y, size.width, size.height, new BABYLON.Color4(0, 0, 0, 0));
  37223. }
  37224. };
  37225. /**
  37226. * Unbind the texture map from the rendering engine.
  37227. * Call this method when you're done rendering. A previous call to bindTextureForRect has to be made.
  37228. * @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.
  37229. */
  37230. MapTexture.prototype.unbindTexture = function (dumpForDebug) {
  37231. // Dump ?
  37232. if (dumpForDebug) {
  37233. BABYLON.Tools.DumpFramebuffer(this._size.width, this._size.height, this.getScene().getEngine());
  37234. }
  37235. var engine = this.getScene().getEngine();
  37236. if (this._replacedViewport) {
  37237. engine.setViewport(this._replacedViewport);
  37238. this._replacedViewport = null;
  37239. }
  37240. engine.unBindFramebuffer(this._texture);
  37241. };
  37242. Object.defineProperty(MapTexture.prototype, "canRescale", {
  37243. get: function () {
  37244. return false;
  37245. },
  37246. enumerable: true,
  37247. configurable: true
  37248. });
  37249. // Note, I don't know what behavior this method should have: clone the underlying texture/rectPackingMap or just reference them?
  37250. // Anyway, there's not much point to use this method for this kind of texture I guess
  37251. MapTexture.prototype.clone = function () {
  37252. return null;
  37253. };
  37254. return MapTexture;
  37255. }(BABYLON.Texture));
  37256. BABYLON.MapTexture = MapTexture;
  37257. })(BABYLON || (BABYLON = {}));
  37258. var BABYLON;
  37259. (function (BABYLON) {
  37260. /**
  37261. * Stores 2D Bounding Information.
  37262. * This class handles a circle area and a bounding rectangle one.
  37263. */
  37264. var BoundingInfo2D = (function () {
  37265. function BoundingInfo2D() {
  37266. this.radius = 0;
  37267. this.center = BABYLON.Vector2.Zero();
  37268. this.extent = BABYLON.Vector2.Zero();
  37269. }
  37270. /**
  37271. * Create a BoundingInfo2D object from a given size
  37272. * @param size the size that will be used to set the extend, radius will be computed from it.
  37273. */
  37274. BoundingInfo2D.CreateFromSize = function (size) {
  37275. var r = new BoundingInfo2D();
  37276. BoundingInfo2D.CreateFromSizeToRef(size, r);
  37277. return r;
  37278. };
  37279. /**
  37280. * Create a BoundingInfo2D object from a given radius
  37281. * @param radius the radius to use, the extent will be computed from it.
  37282. */
  37283. BoundingInfo2D.CreateFromRadius = function (radius) {
  37284. var r = new BoundingInfo2D();
  37285. BoundingInfo2D.CreateFromRadiusToRef(radius, r);
  37286. return r;
  37287. };
  37288. /**
  37289. * Create a BoundingInfo2D object from a list of points.
  37290. * The resulted object will be the smallest bounding area that includes all the given points.
  37291. * @param points an array of points to compute the bounding object from.
  37292. */
  37293. BoundingInfo2D.CreateFromPoints = function (points) {
  37294. var r = new BoundingInfo2D();
  37295. BoundingInfo2D.CreateFromPointsToRef(points, r);
  37296. return r;
  37297. };
  37298. /**
  37299. * Update a BoundingInfo2D object using the given Size as input
  37300. * @param size the bounding data will be computed from this size.
  37301. * @param b must be a valid/allocated object, it will contain the result of the operation
  37302. */
  37303. BoundingInfo2D.CreateFromSizeToRef = function (size, b) {
  37304. if (!size) {
  37305. size = BABYLON.Size.Zero();
  37306. }
  37307. b.center.x = +size.width / 2;
  37308. b.center.y = +size.height / 2;
  37309. b.extent.x = b.center.x;
  37310. b.extent.y = b.center.y;
  37311. b.radius = b.extent.length();
  37312. };
  37313. /**
  37314. * Update a BoundingInfo2D object using the given radius as input
  37315. * @param radius the bounding data will be computed from this radius
  37316. * @param b must be a valid/allocated object, it will contain the result of the operation
  37317. */
  37318. BoundingInfo2D.CreateFromRadiusToRef = function (radius, b) {
  37319. b.center.x = b.center.y = 0;
  37320. var r = +radius;
  37321. b.extent.x = r;
  37322. b.extent.y = r;
  37323. b.radius = r;
  37324. };
  37325. /**
  37326. * Update a BoundingInfo2D object using the given points array as input
  37327. * @param points the point array to use to update the bounding data
  37328. * @param b must be a valid/allocated object, it will contain the result of the operation
  37329. */
  37330. BoundingInfo2D.CreateFromPointsToRef = function (points, b) {
  37331. var xmin = Number.MAX_VALUE, ymin = Number.MAX_VALUE, xmax = Number.MIN_VALUE, ymax = Number.MIN_VALUE;
  37332. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  37333. var p = points_1[_i];
  37334. xmin = Math.min(p.x, xmin);
  37335. xmax = Math.max(p.x, xmax);
  37336. ymin = Math.min(p.y, ymin);
  37337. ymax = Math.max(p.y, ymax);
  37338. }
  37339. BoundingInfo2D.CreateFromMinMaxToRef(xmin, xmax, ymin, ymax, b);
  37340. };
  37341. /**
  37342. * Update a BoundingInfo2D object using the given min/max values as input
  37343. * @param xmin the smallest x coordinate
  37344. * @param xmax the biggest x coordinate
  37345. * @param ymin the smallest y coordinate
  37346. * @param ymax the buggest y coordinate
  37347. * @param b must be a valid/allocated object, it will contain the result of the operation
  37348. */
  37349. BoundingInfo2D.CreateFromMinMaxToRef = function (xmin, xmax, ymin, ymax, b) {
  37350. var w = xmax - xmin;
  37351. var h = ymax - ymin;
  37352. b.center = new BABYLON.Vector2(xmin + w / 2, ymin + h / 2);
  37353. b.extent = new BABYLON.Vector2(xmax - b.center.x, ymax - b.center.y);
  37354. b.radius = b.extent.length();
  37355. };
  37356. /**
  37357. * Duplicate this instance and return a new one
  37358. * @return the duplicated instance
  37359. */
  37360. BoundingInfo2D.prototype.clone = function () {
  37361. var r = new BoundingInfo2D();
  37362. r.center = this.center.clone();
  37363. r.radius = this.radius;
  37364. r.extent = this.extent.clone();
  37365. return r;
  37366. };
  37367. BoundingInfo2D.prototype.clear = function () {
  37368. this.center.copyFromFloats(0, 0);
  37369. this.radius = 0;
  37370. this.extent.copyFromFloats(0, 0);
  37371. };
  37372. BoundingInfo2D.prototype.copyFrom = function (src) {
  37373. this.center.copyFrom(src.center);
  37374. this.radius = src.radius;
  37375. this.extent.copyFrom(src.extent);
  37376. };
  37377. /**
  37378. * return the max extend of the bounding info
  37379. */
  37380. BoundingInfo2D.prototype.max = function () {
  37381. var r = BABYLON.Vector2.Zero();
  37382. this.maxToRef(r);
  37383. return r;
  37384. };
  37385. /**
  37386. * Update a vector2 with the max extend of the bounding info
  37387. * @param result must be a valid/allocated vector2 that will contain the result of the operation
  37388. */
  37389. BoundingInfo2D.prototype.maxToRef = function (result) {
  37390. result.x = this.center.x + this.extent.x;
  37391. result.y = this.center.y + this.extent.y;
  37392. };
  37393. /**
  37394. * Apply a transformation matrix to this BoundingInfo2D and return a new instance containing the result
  37395. * @param matrix the transformation matrix to apply
  37396. * @return the new instance containing the result of the transformation applied on this BoundingInfo2D
  37397. */
  37398. BoundingInfo2D.prototype.transform = function (matrix) {
  37399. var r = new BoundingInfo2D();
  37400. this.transformToRef(matrix, r);
  37401. return r;
  37402. };
  37403. /**
  37404. * Compute the union of this BoundingInfo2D with a given one, returns a new BoundingInfo2D as a result
  37405. * @param other the second BoundingInfo2D to compute the union with this one
  37406. * @return a new instance containing the result of the union
  37407. */
  37408. BoundingInfo2D.prototype.union = function (other) {
  37409. var r = new BoundingInfo2D();
  37410. this.unionToRef(other, r);
  37411. return r;
  37412. };
  37413. /**
  37414. * Transform this BoundingInfo2D with a given matrix and store the result in an existing BoundingInfo2D instance.
  37415. * 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.
  37416. * @param matrix The matrix to use to compute the transformation
  37417. * @param result A VALID (i.e. allocated) BoundingInfo2D object where the result will be stored
  37418. */
  37419. BoundingInfo2D.prototype.transformToRef = function (matrix, result) {
  37420. // Construct a bounding box based on the extent values
  37421. var p = BoundingInfo2D._transform;
  37422. p[0].x = this.center.x + this.extent.x;
  37423. p[0].y = this.center.y + this.extent.y;
  37424. p[1].x = this.center.x + this.extent.x;
  37425. p[1].y = this.center.y - this.extent.y;
  37426. p[2].x = this.center.x - this.extent.x;
  37427. p[2].y = this.center.y - this.extent.y;
  37428. p[3].x = this.center.x - this.extent.x;
  37429. p[3].y = this.center.y + this.extent.y;
  37430. // Transform the four points of the bounding box with the matrix
  37431. for (var i = 0; i < 4; i++) {
  37432. BABYLON.Vector2.TransformToRef(p[i], matrix, p[i]);
  37433. }
  37434. BoundingInfo2D.CreateFromPointsToRef(p, result);
  37435. };
  37436. /**
  37437. * Compute the union of this BoundingInfo2D with another one and store the result in a third valid BoundingInfo2D object
  37438. * 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.
  37439. * @param other the second object used to compute the union
  37440. * @param result a VALID BoundingInfo2D instance (i.e. allocated) where the result will be stored
  37441. */
  37442. BoundingInfo2D.prototype.unionToRef = function (other, result) {
  37443. var xmax = Math.max(this.center.x + this.extent.x, other.center.x + other.extent.x);
  37444. var ymax = Math.max(this.center.y + this.extent.y, other.center.y + other.extent.y);
  37445. var xmin = Math.min(this.center.x - this.extent.x, other.center.x - other.extent.x);
  37446. var ymin = Math.min(this.center.y - this.extent.y, other.center.y - other.extent.y);
  37447. BoundingInfo2D.CreateFromMinMaxToRef(xmin, xmax, ymin, ymax, result);
  37448. };
  37449. /**
  37450. * Check if the given point is inside the BoundingInfo.
  37451. * The test is first made on the radius, then inside the rectangle described by the extent
  37452. * @param pickPosition the position to test
  37453. * @return true if the point is inside, false otherwise
  37454. */
  37455. BoundingInfo2D.prototype.doesIntersect = function (pickPosition) {
  37456. // is it inside the radius?
  37457. var pickLocal = pickPosition.subtract(this.center);
  37458. if (pickLocal.lengthSquared() <= (this.radius * this.radius)) {
  37459. // is it inside the rectangle?
  37460. return ((Math.abs(pickLocal.x) <= this.extent.x) && (Math.abs(pickLocal.y) <= this.extent.y));
  37461. }
  37462. return false;
  37463. };
  37464. BoundingInfo2D._transform = new Array(BABYLON.Vector2.Zero(), BABYLON.Vector2.Zero(), BABYLON.Vector2.Zero(), BABYLON.Vector2.Zero());
  37465. return BoundingInfo2D;
  37466. }());
  37467. BABYLON.BoundingInfo2D = BoundingInfo2D;
  37468. })(BABYLON || (BABYLON = {}));
  37469. var BABYLON;
  37470. (function (BABYLON) {
  37471. /**
  37472. * Base class implementing the ILocable interface.
  37473. * The particularity of this class is to call the protected onLock() method when the instance is about to be locked for good.
  37474. */
  37475. var LockableBase = (function () {
  37476. function LockableBase() {
  37477. }
  37478. LockableBase.prototype.isLocked = function () {
  37479. return this._isLocked;
  37480. };
  37481. LockableBase.prototype.lock = function () {
  37482. if (this._isLocked) {
  37483. return true;
  37484. }
  37485. this.onLock();
  37486. this._isLocked = true;
  37487. return false;
  37488. };
  37489. /**
  37490. * Protected handler that will be called when the instance is about to be locked.
  37491. */
  37492. LockableBase.prototype.onLock = function () {
  37493. };
  37494. return LockableBase;
  37495. }());
  37496. BABYLON.LockableBase = LockableBase;
  37497. var SolidColorBrush2D = (function (_super) {
  37498. __extends(SolidColorBrush2D, _super);
  37499. function SolidColorBrush2D(color, lock) {
  37500. if (lock === void 0) { lock = false; }
  37501. _super.call(this);
  37502. this._color = color;
  37503. if (lock) {
  37504. {
  37505. this.lock();
  37506. }
  37507. }
  37508. }
  37509. /**
  37510. * Return true if the brush is transparent, false if it's totally opaque
  37511. */
  37512. SolidColorBrush2D.prototype.isTransparent = function () {
  37513. return this._color && this._color.a < 1.0;
  37514. };
  37515. Object.defineProperty(SolidColorBrush2D.prototype, "color", {
  37516. /**
  37517. * The color used by this instance to render
  37518. * @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.
  37519. */
  37520. get: function () {
  37521. return this._color;
  37522. },
  37523. set: function (value) {
  37524. if (this.isLocked()) {
  37525. return;
  37526. }
  37527. this._color = value;
  37528. },
  37529. enumerable: true,
  37530. configurable: true
  37531. });
  37532. /**
  37533. * Return a unique identifier of the instance, which is simply the hexadecimal representation (CSS Style) of the solid color.
  37534. */
  37535. SolidColorBrush2D.prototype.toString = function () {
  37536. return this._color.toHexString();
  37537. };
  37538. SolidColorBrush2D = __decorate([
  37539. BABYLON.className("SolidColorBrush2D")
  37540. ], SolidColorBrush2D);
  37541. return SolidColorBrush2D;
  37542. }(LockableBase));
  37543. BABYLON.SolidColorBrush2D = SolidColorBrush2D;
  37544. var GradientColorBrush2D = (function (_super) {
  37545. __extends(GradientColorBrush2D, _super);
  37546. function GradientColorBrush2D(color1, color2, translation, rotation, scale, lock) {
  37547. if (translation === void 0) { translation = BABYLON.Vector2.Zero(); }
  37548. if (rotation === void 0) { rotation = 0; }
  37549. if (scale === void 0) { scale = 1; }
  37550. if (lock === void 0) { lock = false; }
  37551. _super.call(this);
  37552. this._color1 = color1;
  37553. this._color2 = color2;
  37554. this._translation = translation;
  37555. this._rotation = rotation;
  37556. this._scale = scale;
  37557. if (lock) {
  37558. this.lock();
  37559. }
  37560. }
  37561. /**
  37562. * Return true if the brush is transparent, false if it's totally opaque
  37563. */
  37564. GradientColorBrush2D.prototype.isTransparent = function () {
  37565. return (this._color1 && this._color1.a < 1.0) || (this._color2 && this._color2.a < 1.0);
  37566. };
  37567. Object.defineProperty(GradientColorBrush2D.prototype, "color1", {
  37568. /**
  37569. * First color, the blend will start from this color
  37570. */
  37571. get: function () {
  37572. return this._color1;
  37573. },
  37574. set: function (value) {
  37575. if (this.isLocked()) {
  37576. return;
  37577. }
  37578. this._color1 = value;
  37579. },
  37580. enumerable: true,
  37581. configurable: true
  37582. });
  37583. Object.defineProperty(GradientColorBrush2D.prototype, "color2", {
  37584. /**
  37585. * Second color, the blend will end to this color
  37586. */
  37587. get: function () {
  37588. return this._color2;
  37589. },
  37590. set: function (value) {
  37591. if (this.isLocked()) {
  37592. return;
  37593. }
  37594. this._color2 = value;
  37595. },
  37596. enumerable: true,
  37597. configurable: true
  37598. });
  37599. Object.defineProperty(GradientColorBrush2D.prototype, "translation", {
  37600. /**
  37601. * Translation vector to apply on the blend
  37602. * Default is [0;0]
  37603. */
  37604. get: function () {
  37605. return this._translation;
  37606. },
  37607. set: function (value) {
  37608. if (this.isLocked()) {
  37609. return;
  37610. }
  37611. this._translation = value;
  37612. },
  37613. enumerable: true,
  37614. configurable: true
  37615. });
  37616. Object.defineProperty(GradientColorBrush2D.prototype, "rotation", {
  37617. /**
  37618. * Rotation in radian to apply to the brush
  37619. * Default direction of the brush is vertical, you can change this using this property.
  37620. * Default is 0.
  37621. */
  37622. get: function () {
  37623. return this._rotation;
  37624. },
  37625. set: function (value) {
  37626. if (this.isLocked()) {
  37627. return;
  37628. }
  37629. this._rotation = value;
  37630. },
  37631. enumerable: true,
  37632. configurable: true
  37633. });
  37634. Object.defineProperty(GradientColorBrush2D.prototype, "scale", {
  37635. /**
  37636. * Scale factor to apply to the gradient.
  37637. * Default is 1: no scale.
  37638. */
  37639. get: function () {
  37640. return this._scale;
  37641. },
  37642. set: function (value) {
  37643. if (this.isLocked()) {
  37644. return;
  37645. }
  37646. this._scale = value;
  37647. },
  37648. enumerable: true,
  37649. configurable: true
  37650. });
  37651. /**
  37652. * Return a string describing the brush
  37653. */
  37654. GradientColorBrush2D.prototype.toString = function () {
  37655. return "C1:" + this._color1 + ";C2:" + this._color2 + ";T:" + this._translation.toString() + ";R:" + this._rotation + ";S:" + this._scale + ";";
  37656. };
  37657. /**
  37658. * Build a unique key string for the given parameters
  37659. */
  37660. GradientColorBrush2D.BuildKey = function (color1, color2, translation, rotation, scale) {
  37661. return "C1:" + color1 + ";C2:" + color2 + ";T:" + translation.toString() + ";R:" + rotation + ";S:" + scale + ";";
  37662. };
  37663. GradientColorBrush2D = __decorate([
  37664. BABYLON.className("GradientColorBrush2D")
  37665. ], GradientColorBrush2D);
  37666. return GradientColorBrush2D;
  37667. }(LockableBase));
  37668. BABYLON.GradientColorBrush2D = GradientColorBrush2D;
  37669. })(BABYLON || (BABYLON = {}));
  37670. var BABYLON;
  37671. (function (BABYLON) {
  37672. var Prim2DClassInfo = (function () {
  37673. function Prim2DClassInfo() {
  37674. }
  37675. return Prim2DClassInfo;
  37676. }());
  37677. BABYLON.Prim2DClassInfo = Prim2DClassInfo;
  37678. var Prim2DPropInfo = (function () {
  37679. function Prim2DPropInfo() {
  37680. }
  37681. Prim2DPropInfo.PROPKIND_MODEL = 1;
  37682. Prim2DPropInfo.PROPKIND_INSTANCE = 2;
  37683. Prim2DPropInfo.PROPKIND_DYNAMIC = 3;
  37684. return Prim2DPropInfo;
  37685. }());
  37686. BABYLON.Prim2DPropInfo = Prim2DPropInfo;
  37687. /**
  37688. * Custom type of the propertyChanged observable
  37689. */
  37690. var PropertyChangedInfo = (function () {
  37691. function PropertyChangedInfo() {
  37692. }
  37693. return PropertyChangedInfo;
  37694. }());
  37695. BABYLON.PropertyChangedInfo = PropertyChangedInfo;
  37696. var ClassTreeInfo = (function () {
  37697. function ClassTreeInfo(baseClass, type, classContentFactory) {
  37698. this._baseClass = baseClass;
  37699. this._type = type;
  37700. this._subClasses = new Array();
  37701. this._levelContent = new BABYLON.StringDictionary();
  37702. this._classContentFactory = classContentFactory;
  37703. }
  37704. Object.defineProperty(ClassTreeInfo.prototype, "classContent", {
  37705. get: function () {
  37706. if (!this._classContent) {
  37707. this._classContent = this._classContentFactory(this._baseClass ? this._baseClass.classContent : null);
  37708. }
  37709. return this._classContent;
  37710. },
  37711. enumerable: true,
  37712. configurable: true
  37713. });
  37714. Object.defineProperty(ClassTreeInfo.prototype, "type", {
  37715. get: function () {
  37716. return this._type;
  37717. },
  37718. enumerable: true,
  37719. configurable: true
  37720. });
  37721. Object.defineProperty(ClassTreeInfo.prototype, "levelContent", {
  37722. get: function () {
  37723. return this._levelContent;
  37724. },
  37725. enumerable: true,
  37726. configurable: true
  37727. });
  37728. Object.defineProperty(ClassTreeInfo.prototype, "fullContent", {
  37729. get: function () {
  37730. if (!this._fullContent) {
  37731. var dic_1 = new BABYLON.StringDictionary();
  37732. var curLevel = this;
  37733. while (curLevel) {
  37734. curLevel.levelContent.forEach(function (k, v) { return dic_1.add(k, v); });
  37735. curLevel = curLevel._baseClass;
  37736. }
  37737. this._fullContent = dic_1;
  37738. }
  37739. return this._fullContent;
  37740. },
  37741. enumerable: true,
  37742. configurable: true
  37743. });
  37744. ClassTreeInfo.prototype.getLevelOf = function (type) {
  37745. // Are we already there?
  37746. if (type === this._type) {
  37747. return this;
  37748. }
  37749. var baseProto = Object.getPrototypeOf(type);
  37750. var curProtoContent = this.getOrAddType(Object.getPrototypeOf(baseProto), baseProto);
  37751. if (!curProtoContent) {
  37752. this.getLevelOf(baseProto);
  37753. }
  37754. return this.getOrAddType(baseProto, type);
  37755. };
  37756. ClassTreeInfo.prototype.getOrAddType = function (baseType, type) {
  37757. // Are we at the level corresponding to the baseType?
  37758. // If so, get or add the level we're looking for
  37759. if (baseType === this._type) {
  37760. for (var _i = 0, _a = this._subClasses; _i < _a.length; _i++) {
  37761. var subType = _a[_i];
  37762. if (subType.type === type) {
  37763. return subType.node;
  37764. }
  37765. }
  37766. var node = new ClassTreeInfo(this, type, this._classContentFactory);
  37767. var info = { type: type, node: node };
  37768. this._subClasses.push(info);
  37769. return info.node;
  37770. }
  37771. // Recurse down to keep looking for the node corresponding to the baseTypeName
  37772. for (var _b = 0, _c = this._subClasses; _b < _c.length; _b++) {
  37773. var subType = _c[_b];
  37774. var info = subType.node.getOrAddType(baseType, type);
  37775. if (info) {
  37776. return info;
  37777. }
  37778. }
  37779. return null;
  37780. };
  37781. ClassTreeInfo.get = function (type) {
  37782. var dic = type["__classTreeInfo"];
  37783. if (!dic) {
  37784. return null;
  37785. }
  37786. return dic.getLevelOf(type);
  37787. };
  37788. ClassTreeInfo.getOrRegister = function (type, classContentFactory) {
  37789. var dic = type["__classTreeInfo"];
  37790. if (!dic) {
  37791. dic = new ClassTreeInfo(null, type, classContentFactory);
  37792. type["__classTreeInfo"] = dic;
  37793. }
  37794. return dic;
  37795. };
  37796. return ClassTreeInfo;
  37797. }());
  37798. BABYLON.ClassTreeInfo = ClassTreeInfo;
  37799. var SmartPropertyPrim = (function () {
  37800. function SmartPropertyPrim() {
  37801. this._flags = 0;
  37802. this._modelKey = null;
  37803. this._instanceDirtyFlags = 0;
  37804. this._levelBoundingInfo = new BABYLON.BoundingInfo2D();
  37805. this.animations = new Array();
  37806. }
  37807. Object.defineProperty(SmartPropertyPrim.prototype, "isDisposed", {
  37808. /**
  37809. * Check if the object is disposed or not.
  37810. * @returns true if the object is dispose, false otherwise.
  37811. */
  37812. get: function () {
  37813. return this._isFlagSet(SmartPropertyPrim.flagIsDisposed);
  37814. },
  37815. enumerable: true,
  37816. configurable: true
  37817. });
  37818. /**
  37819. * Disposable pattern, this method must be overloaded by derived types in order to clean up hardware related resources.
  37820. * @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.
  37821. */
  37822. SmartPropertyPrim.prototype.dispose = function () {
  37823. if (this.isDisposed) {
  37824. return false;
  37825. }
  37826. // Don't set to null, it may upset somebody...
  37827. this.animations.splice(0);
  37828. this._setFlags(SmartPropertyPrim.flagIsDisposed);
  37829. return true;
  37830. };
  37831. /**
  37832. * Returns as a new array populated with the Animatable used by the primitive. Must be overloaded by derived primitives.
  37833. * Look at Sprite2D for more information
  37834. */
  37835. SmartPropertyPrim.prototype.getAnimatables = function () {
  37836. return new Array();
  37837. };
  37838. Object.defineProperty(SmartPropertyPrim.prototype, "modelKey", {
  37839. /**
  37840. * Property giving the Model Key associated to the property.
  37841. * This value is constructed from the type of the primitive and all the name/value of its properties declared with the modelLevelProperty decorator
  37842. * @returns the model key string.
  37843. */
  37844. get: function () {
  37845. var _this = this;
  37846. // No need to compute it?
  37847. if (!this._isFlagSet(SmartPropertyPrim.flagModelDirty) && this._modelKey) {
  37848. return this._modelKey;
  37849. }
  37850. var modelKey = "Class:" + BABYLON.Tools.getClassName(this) + ";";
  37851. var propDic = this.propDic;
  37852. propDic.forEach(function (k, v) {
  37853. if (v.kind === Prim2DPropInfo.PROPKIND_MODEL) {
  37854. var propVal = _this[v.name];
  37855. // 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
  37856. if (propVal && propVal.constructor === Array) {
  37857. var firstVal = propVal[0];
  37858. if (!firstVal) {
  37859. propVal = 0;
  37860. }
  37861. else {
  37862. propVal = BABYLON.Tools.hashCodeFromStream(BABYLON.Tools.arrayOrStringFeeder(propVal));
  37863. }
  37864. }
  37865. modelKey += v.name + ":" + ((propVal != null) ? ((v.typeLevelCompare) ? BABYLON.Tools.getClassName(propVal) : propVal.toString()) : "[null]") + ";";
  37866. }
  37867. });
  37868. this._clearFlags(SmartPropertyPrim.flagModelDirty);
  37869. this._modelKey = modelKey;
  37870. return modelKey;
  37871. },
  37872. enumerable: true,
  37873. configurable: true
  37874. });
  37875. Object.defineProperty(SmartPropertyPrim.prototype, "isDirty", {
  37876. /**
  37877. * States if the Primitive is dirty and should be rendered again next time.
  37878. * @returns true is dirty, false otherwise
  37879. */
  37880. get: function () {
  37881. return (this._instanceDirtyFlags !== 0) || this._areSomeFlagsSet(SmartPropertyPrim.flagModelDirty | SmartPropertyPrim.flagPositioningDirty | SmartPropertyPrim.flagLayoutDirty);
  37882. },
  37883. enumerable: true,
  37884. configurable: true
  37885. });
  37886. Object.defineProperty(SmartPropertyPrim.prototype, "propDic", {
  37887. /**
  37888. * Access the dictionary of properties metadata. Only properties decorated with XXXXLevelProperty are concerned
  37889. * @returns the dictionary, the key is the property name as declared in Javascript, the value is the metadata object
  37890. */
  37891. get: function () {
  37892. if (!this._propInfo) {
  37893. var cti = ClassTreeInfo.get(Object.getPrototypeOf(this));
  37894. if (!cti) {
  37895. throw new Error("Can't access the propDic member in class definition, is this class SmartPropertyPrim based?");
  37896. }
  37897. this._propInfo = cti.fullContent;
  37898. }
  37899. return this._propInfo;
  37900. },
  37901. enumerable: true,
  37902. configurable: true
  37903. });
  37904. SmartPropertyPrim._createPropInfo = function (target, propName, propId, dirtyBoundingInfo, dirtyParentBoundingBox, typeLevelCompare, kind) {
  37905. var dic = ClassTreeInfo.getOrRegister(target, function () { return new Prim2DClassInfo(); });
  37906. var node = dic.getLevelOf(target);
  37907. var propInfo = node.levelContent.get(propId.toString());
  37908. if (propInfo) {
  37909. throw new Error("The ID " + propId + " is already taken by another property declaration named: " + propInfo.name);
  37910. }
  37911. // Create, setup and add the PropInfo object to our prop dictionary
  37912. propInfo = new Prim2DPropInfo();
  37913. propInfo.id = propId;
  37914. propInfo.flagId = Math.pow(2, propId);
  37915. propInfo.kind = kind;
  37916. propInfo.name = propName;
  37917. propInfo.dirtyBoundingInfo = dirtyBoundingInfo;
  37918. propInfo.dirtyParentBoundingInfo = dirtyParentBoundingBox;
  37919. propInfo.typeLevelCompare = typeLevelCompare;
  37920. node.levelContent.add(propName, propInfo);
  37921. return propInfo;
  37922. };
  37923. SmartPropertyPrim._checkUnchanged = function (curValue, newValue) {
  37924. // Nothing to nothing: nothing to do!
  37925. if ((curValue === null && newValue === null) || (curValue === undefined && newValue === undefined)) {
  37926. return true;
  37927. }
  37928. // Check value unchanged
  37929. if ((curValue != null) && (newValue != null)) {
  37930. if (typeof (curValue.equals) == "function") {
  37931. if (curValue.equals(newValue)) {
  37932. return true;
  37933. }
  37934. }
  37935. else {
  37936. if (curValue === newValue) {
  37937. return true;
  37938. }
  37939. }
  37940. }
  37941. return false;
  37942. };
  37943. SmartPropertyPrim.prototype.markAsDirty = function (propertyName) {
  37944. if (this.isDisposed) {
  37945. return;
  37946. }
  37947. var i = propertyName.indexOf(".");
  37948. if (i !== -1) {
  37949. propertyName = propertyName.substr(0, i);
  37950. }
  37951. var propInfo = this.propDic.get(propertyName);
  37952. if (!propInfo) {
  37953. return;
  37954. }
  37955. var newValue = this[propertyName];
  37956. this._handlePropChanged(undefined, newValue, propertyName, propInfo, propInfo.typeLevelCompare);
  37957. };
  37958. SmartPropertyPrim.prototype._boundingBoxDirty = function () {
  37959. this._setFlags(SmartPropertyPrim.flagLevelBoundingInfoDirty);
  37960. // Escalate the dirty flag in the instance hierarchy, stop when a renderable group is found or at the end
  37961. if (this instanceof BABYLON.Prim2DBase) {
  37962. var curprim = this;
  37963. while (curprim) {
  37964. curprim._setFlags(SmartPropertyPrim.flagBoundingInfoDirty);
  37965. if (curprim.isSizeAuto) {
  37966. curprim.onPrimitivePropertyDirty(BABYLON.Prim2DBase.sizeProperty.flagId);
  37967. curprim._setFlags(SmartPropertyPrim.flagPositioningDirty);
  37968. }
  37969. if (curprim instanceof BABYLON.Group2D) {
  37970. if (curprim.isRenderableGroup) {
  37971. break;
  37972. }
  37973. }
  37974. curprim = curprim.parent;
  37975. }
  37976. }
  37977. };
  37978. SmartPropertyPrim.prototype._handlePropChanged = function (curValue, newValue, propName, propInfo, typeLevelCompare) {
  37979. // If the property change also dirty the boundingInfo, update the boundingInfo dirty flags
  37980. if (propInfo.dirtyBoundingInfo) {
  37981. this._boundingBoxDirty();
  37982. }
  37983. else if (propInfo.dirtyParentBoundingInfo) {
  37984. var p = this._parent;
  37985. if (p != null) {
  37986. p._boundingBoxDirty();
  37987. }
  37988. }
  37989. // Trigger property changed
  37990. var info = SmartPropertyPrim.propChangedInfo;
  37991. info.oldValue = curValue;
  37992. info.newValue = newValue;
  37993. info.propertyName = propName;
  37994. var propMask = propInfo.flagId;
  37995. this.propertyChanged.notifyObservers(info, propMask);
  37996. // If the property belong to a group, check if it's a cached one, and dirty its render sprite accordingly
  37997. if (this instanceof BABYLON.Group2D) {
  37998. this.handleGroupChanged(propInfo);
  37999. }
  38000. // Check for parent layout dirty
  38001. if (this instanceof BABYLON.Prim2DBase) {
  38002. var p = this._parent;
  38003. if (p != null && p.layoutEngine && (p.layoutEngine.layoutDirtyOnPropertyChangedMask & propInfo.flagId) !== 0) {
  38004. p._setLayoutDirty();
  38005. }
  38006. }
  38007. // For type level compare, if there's a change of type it's a change of model, otherwise we issue an instance change
  38008. var instanceDirty = false;
  38009. if (typeLevelCompare && curValue != null && newValue != null) {
  38010. var cvProto = curValue.__proto__;
  38011. var nvProto = newValue.__proto__;
  38012. instanceDirty = (cvProto === nvProto);
  38013. }
  38014. // Set the dirty flags
  38015. if (!instanceDirty && (propInfo.kind === Prim2DPropInfo.PROPKIND_MODEL)) {
  38016. this.onPrimitivePropertyDirty(SmartPropertyPrim.flagModelDirty);
  38017. }
  38018. else if (instanceDirty || (propInfo.kind === Prim2DPropInfo.PROPKIND_INSTANCE) || (propInfo.kind === Prim2DPropInfo.PROPKIND_DYNAMIC)) {
  38019. this.onPrimitivePropertyDirty(propMask);
  38020. }
  38021. };
  38022. SmartPropertyPrim.prototype.onPrimitivePropertyDirty = function (propFlagId) {
  38023. this.onPrimBecomesDirty();
  38024. this._instanceDirtyFlags |= propFlagId;
  38025. };
  38026. SmartPropertyPrim.prototype.handleGroupChanged = function (prop) {
  38027. };
  38028. /**
  38029. * Check if a given set of properties are dirty or not.
  38030. * @param flags a ORed combination of Prim2DPropInfo.flagId values
  38031. * @return true if at least one property is dirty, false if none of them are.
  38032. */
  38033. SmartPropertyPrim.prototype.checkPropertiesDirty = function (flags) {
  38034. return (this._instanceDirtyFlags & flags) !== 0;
  38035. };
  38036. /**
  38037. * Clear a given set of properties.
  38038. * @param flags a ORed combination of Prim2DPropInfo.flagId values
  38039. * @return the new set of property still marked as dirty
  38040. */
  38041. SmartPropertyPrim.prototype.clearPropertiesDirty = function (flags) {
  38042. this._instanceDirtyFlags &= ~flags;
  38043. return this._instanceDirtyFlags;
  38044. };
  38045. SmartPropertyPrim.prototype._resetPropertiesDirty = function () {
  38046. this._instanceDirtyFlags = 0;
  38047. this._clearFlags(SmartPropertyPrim.flagPrimInDirtyList);
  38048. };
  38049. Object.defineProperty(SmartPropertyPrim.prototype, "levelBoundingInfo", {
  38050. /**
  38051. * Retrieve the boundingInfo for this Primitive, computed based on the primitive itself and NOT its children
  38052. */
  38053. get: function () {
  38054. if (this._isFlagSet(SmartPropertyPrim.flagLevelBoundingInfoDirty)) {
  38055. this.updateLevelBoundingInfo();
  38056. this._clearFlags(SmartPropertyPrim.flagLevelBoundingInfoDirty);
  38057. }
  38058. return this._levelBoundingInfo;
  38059. },
  38060. enumerable: true,
  38061. configurable: true
  38062. });
  38063. /**
  38064. * This method must be overridden by a given Primitive implementation to compute its boundingInfo
  38065. */
  38066. SmartPropertyPrim.prototype.updateLevelBoundingInfo = function () {
  38067. };
  38068. /**
  38069. * Property method called when the Primitive becomes dirty
  38070. */
  38071. SmartPropertyPrim.prototype.onPrimBecomesDirty = function () {
  38072. };
  38073. SmartPropertyPrim._hookProperty = function (propId, piStore, typeLevelCompare, dirtyBoundingInfo, dirtyParentBoundingBox, kind) {
  38074. return function (target, propName, descriptor) {
  38075. var propInfo = SmartPropertyPrim._createPropInfo(target, propName, propId, dirtyBoundingInfo, dirtyParentBoundingBox, typeLevelCompare, kind);
  38076. if (piStore) {
  38077. piStore(propInfo);
  38078. }
  38079. var getter = descriptor.get, setter = descriptor.set;
  38080. // Overload the property setter implementation to add our own logic
  38081. descriptor.set = function (val) {
  38082. // check for disposed first, do nothing
  38083. if (this.isDisposed) {
  38084. return;
  38085. }
  38086. var curVal = getter.call(this);
  38087. if (SmartPropertyPrim._checkUnchanged(curVal, val)) {
  38088. return;
  38089. }
  38090. // Cast the object we're working one
  38091. var prim = this;
  38092. // Change the value
  38093. setter.call(this, val);
  38094. // Notify change, dirty flags update
  38095. prim._handlePropChanged(curVal, val, propName, propInfo, typeLevelCompare);
  38096. };
  38097. };
  38098. };
  38099. /**
  38100. * Add an externally attached data from its key.
  38101. * This method call will fail and return false, if such key already exists.
  38102. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  38103. * @param key the unique key that identifies the data
  38104. * @param data the data object to associate to the key for this Engine instance
  38105. * @return true if no such key were already present and the data was added successfully, false otherwise
  38106. */
  38107. SmartPropertyPrim.prototype.addExternalData = function (key, data) {
  38108. if (!this._externalData) {
  38109. this._externalData = new BABYLON.StringDictionary();
  38110. }
  38111. return this._externalData.add(key, data);
  38112. };
  38113. /**
  38114. * Get an externally attached data from its key
  38115. * @param key the unique key that identifies the data
  38116. * @return the associated data, if present (can be null), or undefined if not present
  38117. */
  38118. SmartPropertyPrim.prototype.getExternalData = function (key) {
  38119. if (!this._externalData) {
  38120. return null;
  38121. }
  38122. return this._externalData.get(key);
  38123. };
  38124. /**
  38125. * Get an externally attached data from its key, create it using a factory if it's not already present
  38126. * @param key the unique key that identifies the data
  38127. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  38128. * @return the associated data, can be null if the factory returned null.
  38129. */
  38130. SmartPropertyPrim.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  38131. if (!this._externalData) {
  38132. this._externalData = new BABYLON.StringDictionary();
  38133. }
  38134. return this._externalData.getOrAddWithFactory(key, factory);
  38135. };
  38136. /**
  38137. * Remove an externally attached data from the Engine instance
  38138. * @param key the unique key that identifies the data
  38139. * @return true if the data was successfully removed, false if it doesn't exist
  38140. */
  38141. SmartPropertyPrim.prototype.removeExternalData = function (key) {
  38142. if (!this._externalData) {
  38143. return false;
  38144. }
  38145. return this._externalData.remove(key);
  38146. };
  38147. /**
  38148. * Check if a given flag is set
  38149. * @param flag the flag value
  38150. * @return true if set, false otherwise
  38151. */
  38152. SmartPropertyPrim.prototype._isFlagSet = function (flag) {
  38153. return (this._flags & flag) !== 0;
  38154. };
  38155. /**
  38156. * Check if all given flags are set
  38157. * @param flags the flags ORed
  38158. * @return true if all the flags are set, false otherwise
  38159. */
  38160. SmartPropertyPrim.prototype._areAllFlagsSet = function (flags) {
  38161. return (this._flags & flags) === flags;
  38162. };
  38163. /**
  38164. * Check if at least one flag of the given flags is set
  38165. * @param flags the flags ORed
  38166. * @return true if at least one flag is set, false otherwise
  38167. */
  38168. SmartPropertyPrim.prototype._areSomeFlagsSet = function (flags) {
  38169. return (this._flags & flags) !== 0;
  38170. };
  38171. /**
  38172. * Clear the given flags
  38173. * @param flags the flags to clear
  38174. */
  38175. SmartPropertyPrim.prototype._clearFlags = function (flags) {
  38176. this._flags &= ~flags;
  38177. };
  38178. /**
  38179. * Set the given flags to true state
  38180. * @param flags the flags ORed to set
  38181. * @return the flags state before this call
  38182. */
  38183. SmartPropertyPrim.prototype._setFlags = function (flags) {
  38184. var cur = this._flags;
  38185. this._flags |= flags;
  38186. return cur;
  38187. };
  38188. /**
  38189. * Change the state of the given flags
  38190. * @param flags the flags ORed to change
  38191. * @param state true to set them, false to clear them
  38192. */
  38193. SmartPropertyPrim.prototype._changeFlags = function (flags, state) {
  38194. if (state) {
  38195. this._flags |= flags;
  38196. }
  38197. else {
  38198. this._flags &= ~flags;
  38199. }
  38200. };
  38201. SmartPropertyPrim.propChangedInfo = new PropertyChangedInfo();
  38202. SmartPropertyPrim.flagIsDisposed = 0x0000001; // set if the object is already disposed
  38203. SmartPropertyPrim.flagLevelBoundingInfoDirty = 0x0000002; // set if the primitive's level bounding box (not including children) is dirty
  38204. SmartPropertyPrim.flagModelDirty = 0x0000004; // set if the model must be changed
  38205. SmartPropertyPrim.flagLayoutDirty = 0x0000008; // set if the layout must be computed
  38206. SmartPropertyPrim.flagLevelVisible = 0x0000010; // set if the primitive is set as visible for its level only
  38207. SmartPropertyPrim.flagBoundingInfoDirty = 0x0000020; // set if the primitive's overall bounding box (including children) is dirty
  38208. SmartPropertyPrim.flagIsPickable = 0x0000040; // set if the primitive can be picked during interaction
  38209. SmartPropertyPrim.flagIsVisible = 0x0000080; // set if the primitive is concretely visible (use the levelVisible of parents)
  38210. SmartPropertyPrim.flagVisibilityChanged = 0x0000100; // set if there was a transition between visible/hidden status
  38211. SmartPropertyPrim.flagPositioningDirty = 0x0000200; // set if the primitive positioning must be computed
  38212. SmartPropertyPrim.flagTrackedGroup = 0x0000400; // set if the group2D is tracking a scene node
  38213. SmartPropertyPrim.flagWorldCacheChanged = 0x0000800; // set if the cached bitmap of a world space canvas changed
  38214. SmartPropertyPrim.flagChildrenFlatZOrder = 0x0001000; // set if all the children (direct and indirect) will share the same Z-Order
  38215. SmartPropertyPrim.flagZOrderDirty = 0x0002000; // set if the Z-Order for this prim and its children must be recomputed
  38216. SmartPropertyPrim.flagActualOpacityDirty = 0x0004000; // set if the actualOpactity should be recomputed
  38217. SmartPropertyPrim.flagPrimInDirtyList = 0x0008000; // set if the primitive is in the primDirtyList
  38218. SmartPropertyPrim = __decorate([
  38219. BABYLON.className("SmartPropertyPrim")
  38220. ], SmartPropertyPrim);
  38221. return SmartPropertyPrim;
  38222. }());
  38223. BABYLON.SmartPropertyPrim = SmartPropertyPrim;
  38224. function modelLevelProperty(propId, piStore, typeLevelCompare, dirtyBoundingInfo, dirtyParentBoundingBox) {
  38225. if (typeLevelCompare === void 0) { typeLevelCompare = false; }
  38226. if (dirtyBoundingInfo === void 0) { dirtyBoundingInfo = false; }
  38227. if (dirtyParentBoundingBox === void 0) { dirtyParentBoundingBox = false; }
  38228. return SmartPropertyPrim._hookProperty(propId, piStore, typeLevelCompare, dirtyBoundingInfo, dirtyParentBoundingBox, Prim2DPropInfo.PROPKIND_MODEL);
  38229. }
  38230. BABYLON.modelLevelProperty = modelLevelProperty;
  38231. function instanceLevelProperty(propId, piStore, typeLevelCompare, dirtyBoundingInfo, dirtyParentBoundingBox) {
  38232. if (typeLevelCompare === void 0) { typeLevelCompare = false; }
  38233. if (dirtyBoundingInfo === void 0) { dirtyBoundingInfo = false; }
  38234. if (dirtyParentBoundingBox === void 0) { dirtyParentBoundingBox = false; }
  38235. return SmartPropertyPrim._hookProperty(propId, piStore, typeLevelCompare, dirtyBoundingInfo, dirtyParentBoundingBox, Prim2DPropInfo.PROPKIND_INSTANCE);
  38236. }
  38237. BABYLON.instanceLevelProperty = instanceLevelProperty;
  38238. function dynamicLevelProperty(propId, piStore, typeLevelCompare, dirtyBoundingInfo, dirtyParentBoundingBox) {
  38239. if (typeLevelCompare === void 0) { typeLevelCompare = false; }
  38240. if (dirtyBoundingInfo === void 0) { dirtyBoundingInfo = false; }
  38241. if (dirtyParentBoundingBox === void 0) { dirtyParentBoundingBox = false; }
  38242. return SmartPropertyPrim._hookProperty(propId, piStore, typeLevelCompare, dirtyBoundingInfo, dirtyParentBoundingBox, Prim2DPropInfo.PROPKIND_DYNAMIC);
  38243. }
  38244. BABYLON.dynamicLevelProperty = dynamicLevelProperty;
  38245. })(BABYLON || (BABYLON = {}));
  38246. var BABYLON;
  38247. (function (BABYLON) {
  38248. var PrepareRender2DContext = (function () {
  38249. function PrepareRender2DContext() {
  38250. this.forceRefreshPrimitive = false;
  38251. }
  38252. return PrepareRender2DContext;
  38253. }());
  38254. BABYLON.PrepareRender2DContext = PrepareRender2DContext;
  38255. var Render2DContext = (function () {
  38256. function Render2DContext(renderMode) {
  38257. this._renderMode = renderMode;
  38258. this.useInstancing = false;
  38259. this.groupInfoPartData = null;
  38260. this.partDataStartIndex = this.partDataEndIndex = null;
  38261. this.instancedBuffers = null;
  38262. }
  38263. Object.defineProperty(Render2DContext.prototype, "renderMode", {
  38264. /**
  38265. * Define which render Mode should be used to render the primitive: one of Render2DContext.RenderModeXxxx property
  38266. */
  38267. get: function () {
  38268. return this._renderMode;
  38269. },
  38270. enumerable: true,
  38271. configurable: true
  38272. });
  38273. Object.defineProperty(Render2DContext, "RenderModeOpaque", {
  38274. /**
  38275. * The set of primitives to render is opaque.
  38276. * This is the first rendering pass. All Opaque primitives are rendered. Depth Compare and Write are both enabled.
  38277. */
  38278. get: function () {
  38279. return Render2DContext._renderModeOpaque;
  38280. },
  38281. enumerable: true,
  38282. configurable: true
  38283. });
  38284. Object.defineProperty(Render2DContext, "RenderModeAlphaTest", {
  38285. /**
  38286. * The set of primitives to render is using Alpha Test (aka masking).
  38287. * 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.
  38288. */
  38289. get: function () {
  38290. return Render2DContext._renderModeAlphaTest;
  38291. },
  38292. enumerable: true,
  38293. configurable: true
  38294. });
  38295. Object.defineProperty(Render2DContext, "RenderModeTransparent", {
  38296. /**
  38297. * The set of primitives to render is transparent.
  38298. * 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.
  38299. */
  38300. get: function () {
  38301. return Render2DContext._renderModeTransparent;
  38302. },
  38303. enumerable: true,
  38304. configurable: true
  38305. });
  38306. Render2DContext._renderModeOpaque = 1;
  38307. Render2DContext._renderModeAlphaTest = 2;
  38308. Render2DContext._renderModeTransparent = 3;
  38309. return Render2DContext;
  38310. }());
  38311. BABYLON.Render2DContext = Render2DContext;
  38312. /**
  38313. * This class store information for the pointerEventObservable Observable.
  38314. * 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.
  38315. */
  38316. var PrimitivePointerInfo = (function () {
  38317. function PrimitivePointerInfo() {
  38318. this.primitivePointerPos = BABYLON.Vector2.Zero();
  38319. this.tilt = BABYLON.Vector2.Zero();
  38320. this.cancelBubble = false;
  38321. }
  38322. Object.defineProperty(PrimitivePointerInfo, "PointerOver", {
  38323. // 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.
  38324. /**
  38325. * This event type is raised when a pointing device is moved into the hit test boundaries of a primitive.
  38326. * Bubbles: yes
  38327. */
  38328. get: function () {
  38329. return PrimitivePointerInfo._pointerOver;
  38330. },
  38331. enumerable: true,
  38332. configurable: true
  38333. });
  38334. Object.defineProperty(PrimitivePointerInfo, "PointerEnter", {
  38335. /**
  38336. * This event type is raised when a pointing device is moved into the hit test boundaries of a primitive or one of its descendants.
  38337. * Bubbles: no
  38338. */
  38339. get: function () {
  38340. return PrimitivePointerInfo._pointerEnter;
  38341. },
  38342. enumerable: true,
  38343. configurable: true
  38344. });
  38345. Object.defineProperty(PrimitivePointerInfo, "PointerDown", {
  38346. /**
  38347. * 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.
  38348. * Bubbles: yes
  38349. */
  38350. get: function () {
  38351. return PrimitivePointerInfo._pointerDown;
  38352. },
  38353. enumerable: true,
  38354. configurable: true
  38355. });
  38356. Object.defineProperty(PrimitivePointerInfo, "PointerMouseWheel", {
  38357. /**
  38358. * This event type is raised when the pointer is a mouse and it's wheel is rolling
  38359. * Bubbles: yes
  38360. */
  38361. get: function () {
  38362. return PrimitivePointerInfo._pointerMouseWheel;
  38363. },
  38364. enumerable: true,
  38365. configurable: true
  38366. });
  38367. Object.defineProperty(PrimitivePointerInfo, "PointerMove", {
  38368. /**
  38369. * 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.
  38370. * Bubbles: yes
  38371. */
  38372. get: function () {
  38373. return PrimitivePointerInfo._pointerMove;
  38374. },
  38375. enumerable: true,
  38376. configurable: true
  38377. });
  38378. Object.defineProperty(PrimitivePointerInfo, "PointerUp", {
  38379. /**
  38380. * 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.
  38381. * Bubbles: yes
  38382. */
  38383. get: function () {
  38384. return PrimitivePointerInfo._pointerUp;
  38385. },
  38386. enumerable: true,
  38387. configurable: true
  38388. });
  38389. Object.defineProperty(PrimitivePointerInfo, "PointerOut", {
  38390. /**
  38391. * This event type is raised when a pointing device is moved out of the hit test the boundaries of a primitive.
  38392. * Bubbles: yes
  38393. */
  38394. get: function () {
  38395. return PrimitivePointerInfo._pointerOut;
  38396. },
  38397. enumerable: true,
  38398. configurable: true
  38399. });
  38400. Object.defineProperty(PrimitivePointerInfo, "PointerLeave", {
  38401. /**
  38402. * This event type is raised when a pointing device is moved out of the hit test boundaries of a primitive and all its descendants.
  38403. * Bubbles: no
  38404. */
  38405. get: function () {
  38406. return PrimitivePointerInfo._pointerLeave;
  38407. },
  38408. enumerable: true,
  38409. configurable: true
  38410. });
  38411. Object.defineProperty(PrimitivePointerInfo, "PointerGotCapture", {
  38412. /**
  38413. * 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.
  38414. * Bubbles: yes
  38415. */
  38416. get: function () {
  38417. return PrimitivePointerInfo._pointerGotCapture;
  38418. },
  38419. enumerable: true,
  38420. configurable: true
  38421. });
  38422. Object.defineProperty(PrimitivePointerInfo, "PointerLostCapture", {
  38423. /**
  38424. * This event type is raised after pointer capture is released for a pointer.
  38425. * Bubbles: yes
  38426. */
  38427. get: function () {
  38428. return PrimitivePointerInfo._pointerLostCapture;
  38429. },
  38430. enumerable: true,
  38431. configurable: true
  38432. });
  38433. Object.defineProperty(PrimitivePointerInfo, "MouseWheelPrecision", {
  38434. get: function () {
  38435. return PrimitivePointerInfo._mouseWheelPrecision;
  38436. },
  38437. enumerable: true,
  38438. configurable: true
  38439. });
  38440. PrimitivePointerInfo.prototype.updateRelatedTarget = function (prim, primPointerPos) {
  38441. this.relatedTarget = prim;
  38442. this.relatedTargetPointerPos = primPointerPos;
  38443. };
  38444. PrimitivePointerInfo.getEventTypeName = function (mask) {
  38445. switch (mask) {
  38446. case PrimitivePointerInfo.PointerOver: return "PointerOver";
  38447. case PrimitivePointerInfo.PointerEnter: return "PointerEnter";
  38448. case PrimitivePointerInfo.PointerDown: return "PointerDown";
  38449. case PrimitivePointerInfo.PointerMouseWheel: return "PointerMouseWheel";
  38450. case PrimitivePointerInfo.PointerMove: return "PointerMove";
  38451. case PrimitivePointerInfo.PointerUp: return "PointerUp";
  38452. case PrimitivePointerInfo.PointerOut: return "PointerOut";
  38453. case PrimitivePointerInfo.PointerLeave: return "PointerLeave";
  38454. case PrimitivePointerInfo.PointerGotCapture: return "PointerGotCapture";
  38455. case PrimitivePointerInfo.PointerLostCapture: return "PointerLostCapture";
  38456. }
  38457. };
  38458. PrimitivePointerInfo._pointerOver = 0x0001;
  38459. PrimitivePointerInfo._pointerEnter = 0x0002;
  38460. PrimitivePointerInfo._pointerDown = 0x0004;
  38461. PrimitivePointerInfo._pointerMouseWheel = 0x0008;
  38462. PrimitivePointerInfo._pointerMove = 0x0010;
  38463. PrimitivePointerInfo._pointerUp = 0x0020;
  38464. PrimitivePointerInfo._pointerOut = 0x0040;
  38465. PrimitivePointerInfo._pointerLeave = 0x0080;
  38466. PrimitivePointerInfo._pointerGotCapture = 0x0100;
  38467. PrimitivePointerInfo._pointerLostCapture = 0x0200;
  38468. PrimitivePointerInfo._mouseWheelPrecision = 3.0;
  38469. return PrimitivePointerInfo;
  38470. }());
  38471. BABYLON.PrimitivePointerInfo = PrimitivePointerInfo;
  38472. /**
  38473. * Defines the horizontal and vertical alignment information for a Primitive.
  38474. */
  38475. var PrimitiveAlignment = (function () {
  38476. function PrimitiveAlignment(changeCallback) {
  38477. this._changedCallback = changeCallback;
  38478. this._horizontal = PrimitiveAlignment.AlignLeft;
  38479. this._vertical = PrimitiveAlignment.AlignBottom;
  38480. }
  38481. Object.defineProperty(PrimitiveAlignment, "AlignLeft", {
  38482. /**
  38483. * Alignment is made relative to the left edge of the Primitive. Valid for horizontal alignment only.
  38484. */
  38485. get: function () { return PrimitiveAlignment._AlignLeft; },
  38486. enumerable: true,
  38487. configurable: true
  38488. });
  38489. Object.defineProperty(PrimitiveAlignment, "AlignTop", {
  38490. /**
  38491. * Alignment is made relative to the top edge of the Primitive. Valid for vertical alignment only.
  38492. */
  38493. get: function () { return PrimitiveAlignment._AlignTop; },
  38494. enumerable: true,
  38495. configurable: true
  38496. });
  38497. Object.defineProperty(PrimitiveAlignment, "AlignRight", {
  38498. /**
  38499. * Alignment is made relative to the right edge of the Primitive. Valid for horizontal alignment only.
  38500. */
  38501. get: function () { return PrimitiveAlignment._AlignRight; },
  38502. enumerable: true,
  38503. configurable: true
  38504. });
  38505. Object.defineProperty(PrimitiveAlignment, "AlignBottom", {
  38506. /**
  38507. * Alignment is made relative to the bottom edge of the Primitive. Valid for vertical alignment only.
  38508. */
  38509. get: function () { return PrimitiveAlignment._AlignBottom; },
  38510. enumerable: true,
  38511. configurable: true
  38512. });
  38513. Object.defineProperty(PrimitiveAlignment, "AlignCenter", {
  38514. /**
  38515. * Alignment is made to center the content from equal distance to the opposite edges of the Primitive
  38516. */
  38517. get: function () { return PrimitiveAlignment._AlignCenter; },
  38518. enumerable: true,
  38519. configurable: true
  38520. });
  38521. Object.defineProperty(PrimitiveAlignment, "AlignStretch", {
  38522. /**
  38523. * The content is stretched toward the opposite edges of the Primitive
  38524. */
  38525. get: function () { return PrimitiveAlignment._AlignStretch; },
  38526. enumerable: true,
  38527. configurable: true
  38528. });
  38529. Object.defineProperty(PrimitiveAlignment.prototype, "horizontal", {
  38530. /**
  38531. * Get/set the horizontal alignment. Use one of the AlignXXX static properties of this class
  38532. */
  38533. get: function () {
  38534. return this._horizontal;
  38535. },
  38536. set: function (value) {
  38537. if (this._horizontal === value) {
  38538. return;
  38539. }
  38540. this._horizontal = value;
  38541. this._changedCallback();
  38542. },
  38543. enumerable: true,
  38544. configurable: true
  38545. });
  38546. Object.defineProperty(PrimitiveAlignment.prototype, "vertical", {
  38547. /**
  38548. * Get/set the vertical alignment. Use one of the AlignXXX static properties of this class
  38549. */
  38550. get: function () {
  38551. return this._vertical;
  38552. },
  38553. set: function (value) {
  38554. if (this._vertical === value) {
  38555. return;
  38556. }
  38557. this._vertical = value;
  38558. this._changedCallback();
  38559. },
  38560. enumerable: true,
  38561. configurable: true
  38562. });
  38563. /**
  38564. * Set the horizontal alignment from a string value.
  38565. * @param text can be either: 'left','right','center','stretch'
  38566. */
  38567. PrimitiveAlignment.prototype.setHorizontal = function (text) {
  38568. var v = text.trim().toLocaleLowerCase();
  38569. switch (v) {
  38570. case "left":
  38571. this.horizontal = PrimitiveAlignment.AlignLeft;
  38572. return;
  38573. case "right":
  38574. this.horizontal = PrimitiveAlignment.AlignRight;
  38575. return;
  38576. case "center":
  38577. this.horizontal = PrimitiveAlignment.AlignCenter;
  38578. return;
  38579. case "stretch":
  38580. this.horizontal = PrimitiveAlignment.AlignStretch;
  38581. return;
  38582. }
  38583. };
  38584. /**
  38585. * Set the vertical alignment from a string value.
  38586. * @param text can be either: 'top','bottom','center','stretch'
  38587. */
  38588. PrimitiveAlignment.prototype.setVertical = function (text) {
  38589. var v = text.trim().toLocaleLowerCase();
  38590. switch (v) {
  38591. case "top":
  38592. this.vertical = PrimitiveAlignment.AlignTop;
  38593. return;
  38594. case "bottom":
  38595. this.vertical = PrimitiveAlignment.AlignBottom;
  38596. return;
  38597. case "center":
  38598. this.vertical = PrimitiveAlignment.AlignCenter;
  38599. return;
  38600. case "stretch":
  38601. this.vertical = PrimitiveAlignment.AlignStretch;
  38602. return;
  38603. }
  38604. };
  38605. /**
  38606. * Set the horizontal and or vertical alignments from a string value.
  38607. * @param text can be: [<h:|horizontal:><left|right|center|stretch>], [<v:|vertical:><top|bottom|center|stretch>]
  38608. */
  38609. PrimitiveAlignment.prototype.fromString = function (value) {
  38610. var m = value.trim().split(",");
  38611. for (var _i = 0, m_1 = m; _i < m_1.length; _i++) {
  38612. var v = m_1[_i];
  38613. v = v.toLocaleLowerCase().trim();
  38614. // Horizontal
  38615. var i = v.indexOf("h:");
  38616. if (i === -1) {
  38617. i = v.indexOf("horizontal:");
  38618. }
  38619. if (i !== -1) {
  38620. v = v.substr(v.indexOf(":") + 1);
  38621. this.setHorizontal(v);
  38622. continue;
  38623. }
  38624. // Vertical
  38625. i = v.indexOf("v:");
  38626. if (i === -1) {
  38627. i = v.indexOf("vertical:");
  38628. }
  38629. if (i !== -1) {
  38630. v = v.substr(v.indexOf(":") + 1);
  38631. this.setVertical(v);
  38632. continue;
  38633. }
  38634. }
  38635. };
  38636. PrimitiveAlignment._AlignLeft = 1;
  38637. PrimitiveAlignment._AlignTop = 1; // Same as left
  38638. PrimitiveAlignment._AlignRight = 2;
  38639. PrimitiveAlignment._AlignBottom = 2; // Same as right
  38640. PrimitiveAlignment._AlignCenter = 3;
  38641. PrimitiveAlignment._AlignStretch = 4;
  38642. return PrimitiveAlignment;
  38643. }());
  38644. BABYLON.PrimitiveAlignment = PrimitiveAlignment;
  38645. /**
  38646. * Stores information about a Primitive that was intersected
  38647. */
  38648. var PrimitiveIntersectedInfo = (function () {
  38649. function PrimitiveIntersectedInfo(prim, intersectionLocation) {
  38650. this.prim = prim;
  38651. this.intersectionLocation = intersectionLocation;
  38652. }
  38653. return PrimitiveIntersectedInfo;
  38654. }());
  38655. BABYLON.PrimitiveIntersectedInfo = PrimitiveIntersectedInfo;
  38656. /**
  38657. * Define a thickness toward every edges of a Primitive to allow margin and padding.
  38658. * The thickness can be expressed as pixels, percentages, inherit the value of the parent primitive or be auto.
  38659. */
  38660. var PrimitiveThickness = (function () {
  38661. function PrimitiveThickness(parentAccess, changedCallback) {
  38662. this._parentAccess = parentAccess;
  38663. this._changedCallback = changedCallback;
  38664. this._pixels = new Array(4);
  38665. this._percentages = new Array(4);
  38666. this._setType(0, PrimitiveThickness.Auto);
  38667. this._setType(1, PrimitiveThickness.Auto);
  38668. this._setType(2, PrimitiveThickness.Auto);
  38669. this._setType(3, PrimitiveThickness.Auto);
  38670. this._pixels[0] = 0;
  38671. this._pixels[1] = 0;
  38672. this._pixels[2] = 0;
  38673. this._pixels[3] = 0;
  38674. }
  38675. /**
  38676. * Set the thickness from a string value
  38677. * @param thickness format is "top: <value>, left:<value>, right:<value>, bottom:<value>" or "<value>" (same for all edges) each are optional, auto will be set if it's omitted.
  38678. * Values are: 'auto', 'inherit', 'XX%' for percentage, 'XXpx' or 'XX' for pixels.
  38679. */
  38680. PrimitiveThickness.prototype.fromString = function (thickness) {
  38681. this._clear();
  38682. var m = thickness.trim().split(",");
  38683. // Special case, one value to apply to all edges
  38684. if (m.length === 1 && thickness.indexOf(":") === -1) {
  38685. this._setStringValue(m[0], 0, false);
  38686. this._setStringValue(m[0], 1, false);
  38687. this._setStringValue(m[0], 2, false);
  38688. this._setStringValue(m[0], 3, false);
  38689. this._changedCallback();
  38690. return;
  38691. }
  38692. var res = false;
  38693. for (var _i = 0, m_2 = m; _i < m_2.length; _i++) {
  38694. var cm = m_2[_i];
  38695. res = this._extractString(cm, false) || res;
  38696. }
  38697. if (!res) {
  38698. throw new Error("Can't parse the string to create a PrimitiveMargin object, format must be: 'top: <value>, left:<value>, right:<value>, bottom:<value>");
  38699. }
  38700. // Check the margin that weren't set and set them in auto
  38701. if ((this._flags & 0x000F) === 0)
  38702. this._flags |= PrimitiveThickness.Pixel << 0;
  38703. if ((this._flags & 0x00F0) === 0)
  38704. this._flags |= PrimitiveThickness.Pixel << 4;
  38705. if ((this._flags & 0x0F00) === 0)
  38706. this._flags |= PrimitiveThickness.Pixel << 8;
  38707. if ((this._flags & 0xF000) === 0)
  38708. this._flags |= PrimitiveThickness.Pixel << 12;
  38709. this._changedCallback();
  38710. };
  38711. /**
  38712. * Set the thickness from multiple string
  38713. * Possible values are: 'auto', 'inherit', 'XX%' for percentage, 'XXpx' or 'XX' for pixels.
  38714. * @param top the top thickness to set
  38715. * @param left the left thickness to set
  38716. * @param right the right thickness to set
  38717. * @param bottom the bottom thickness to set
  38718. */
  38719. PrimitiveThickness.prototype.fromStrings = function (top, left, right, bottom) {
  38720. this._clear();
  38721. this._setStringValue(top, 0, false);
  38722. this._setStringValue(left, 1, false);
  38723. this._setStringValue(right, 2, false);
  38724. this._setStringValue(bottom, 3, false);
  38725. this._changedCallback();
  38726. return this;
  38727. };
  38728. /**
  38729. * Set the thickness from pixel values
  38730. * @param top the top thickness in pixels to set
  38731. * @param left the left thickness in pixels to set
  38732. * @param right the right thickness in pixels to set
  38733. * @param bottom the bottom thickness in pixels to set
  38734. */
  38735. PrimitiveThickness.prototype.fromPixels = function (top, left, right, bottom) {
  38736. this._clear();
  38737. this._pixels[0] = top;
  38738. this._pixels[1] = left;
  38739. this._pixels[2] = right;
  38740. this._pixels[3] = bottom;
  38741. this._changedCallback();
  38742. return this;
  38743. };
  38744. /**
  38745. * Apply the same pixel value to all edges
  38746. * @param margin the value to set, in pixels.
  38747. */
  38748. PrimitiveThickness.prototype.fromUniformPixels = function (margin) {
  38749. this._clear();
  38750. this._pixels[0] = margin;
  38751. this._pixels[1] = margin;
  38752. this._pixels[2] = margin;
  38753. this._pixels[3] = margin;
  38754. this._changedCallback();
  38755. return this;
  38756. };
  38757. /**
  38758. * Set all edges in auto
  38759. */
  38760. PrimitiveThickness.prototype.auto = function () {
  38761. this._clear();
  38762. this._flags = (PrimitiveThickness.Auto << 0) | (PrimitiveThickness.Auto << 4) | (PrimitiveThickness.Auto << 8) | (PrimitiveThickness.Auto << 12);
  38763. this._pixels[0] = 0;
  38764. this._pixels[1] = 0;
  38765. this._pixels[2] = 0;
  38766. this._pixels[3] = 0;
  38767. this._changedCallback();
  38768. return this;
  38769. };
  38770. PrimitiveThickness.prototype._clear = function () {
  38771. this._flags = 0;
  38772. this._pixels[0] = 0;
  38773. this._pixels[1] = 0;
  38774. this._pixels[2] = 0;
  38775. this._pixels[3] = 0;
  38776. this._percentages[0] = null;
  38777. this._percentages[1] = null;
  38778. this._percentages[2] = null;
  38779. this._percentages[3] = null;
  38780. };
  38781. PrimitiveThickness.prototype._extractString = function (value, emitChanged) {
  38782. var v = value.trim().toLocaleLowerCase();
  38783. if (v.indexOf("top:") === 0) {
  38784. v = v.substr(4).trim();
  38785. return this._setStringValue(v, 0, emitChanged);
  38786. }
  38787. if (v.indexOf("left:") === 0) {
  38788. v = v.substr(5).trim();
  38789. return this._setStringValue(v, 1, emitChanged);
  38790. }
  38791. if (v.indexOf("right:") === 0) {
  38792. v = v.substr(6).trim();
  38793. return this._setStringValue(v, 2, emitChanged);
  38794. }
  38795. if (v.indexOf("bottom:") === 0) {
  38796. v = v.substr(7).trim();
  38797. return this._setStringValue(v, 3, emitChanged);
  38798. }
  38799. return false;
  38800. };
  38801. PrimitiveThickness.prototype._setStringValue = function (value, index, emitChanged) {
  38802. // Check for auto
  38803. var v = value.trim().toLocaleLowerCase();
  38804. if (v === "auto") {
  38805. if (this._isType(index, PrimitiveThickness.Auto)) {
  38806. return true;
  38807. }
  38808. this._setType(index, PrimitiveThickness.Auto);
  38809. this._pixels[index] = 0;
  38810. if (emitChanged) {
  38811. this._changedCallback();
  38812. }
  38813. }
  38814. else if (v === "inherit") {
  38815. if (this._isType(index, PrimitiveThickness.Inherit)) {
  38816. return true;
  38817. }
  38818. this._setType(index, PrimitiveThickness.Inherit);
  38819. this._pixels[index] = null;
  38820. if (emitChanged) {
  38821. this._changedCallback();
  38822. }
  38823. }
  38824. else {
  38825. var pI = v.indexOf("%");
  38826. // Check for percentage
  38827. if (pI !== -1) {
  38828. var n_1 = v.substr(0, pI);
  38829. var number_1 = Math.round(Number(n_1)) / 100; // Normalize the percentage to [0;1] with a 0.01 precision
  38830. if (this._isType(index, PrimitiveThickness.Percentage) && (this._percentages[index] === number_1)) {
  38831. return true;
  38832. }
  38833. this._setType(index, PrimitiveThickness.Percentage);
  38834. if (isNaN(number_1)) {
  38835. return false;
  38836. }
  38837. this._percentages[index] = number_1;
  38838. if (emitChanged) {
  38839. this._changedCallback();
  38840. }
  38841. return true;
  38842. }
  38843. // Check for pixel
  38844. var n = void 0;
  38845. pI = v.indexOf("px");
  38846. if (pI !== -1) {
  38847. n = v.substr(0, pI).trim();
  38848. }
  38849. else {
  38850. n = v;
  38851. }
  38852. var number = Number(n);
  38853. if (this._isType(index, PrimitiveThickness.Pixel) && (this._pixels[index] === number)) {
  38854. return true;
  38855. }
  38856. if (isNaN(number)) {
  38857. return false;
  38858. }
  38859. this._pixels[index] = number;
  38860. this._setType(index, PrimitiveThickness.Pixel);
  38861. if (emitChanged) {
  38862. this._changedCallback();
  38863. }
  38864. return true;
  38865. }
  38866. };
  38867. PrimitiveThickness.prototype._setPixels = function (value, index, emitChanged) {
  38868. // 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
  38869. value = Math.round(value);
  38870. if (this._isType(index, PrimitiveThickness.Pixel) && this._pixels[index] === value) {
  38871. return;
  38872. }
  38873. this._setType(index, PrimitiveThickness.Pixel);
  38874. this._pixels[index] = value;
  38875. if (emitChanged) {
  38876. this._changedCallback();
  38877. }
  38878. };
  38879. PrimitiveThickness.prototype._setPercentage = function (value, index, emitChanged) {
  38880. // Clip Value to bounds
  38881. value = Math.min(1, value);
  38882. value = Math.max(0, value);
  38883. value = Math.round(value * 100) / 100; // 0.01 precision
  38884. if (this._isType(index, PrimitiveThickness.Percentage) && this._percentages[index] === value) {
  38885. return;
  38886. }
  38887. this._setType(index, PrimitiveThickness.Percentage);
  38888. this._percentages[index] = value;
  38889. if (emitChanged) {
  38890. this._changedCallback();
  38891. }
  38892. };
  38893. PrimitiveThickness.prototype._getStringValue = function (index) {
  38894. var f = (this._flags >> (index * 4)) & 0xF;
  38895. switch (f) {
  38896. case PrimitiveThickness.Auto:
  38897. return "auto";
  38898. case PrimitiveThickness.Pixel:
  38899. return this._pixels[index] + "px";
  38900. case PrimitiveThickness.Percentage:
  38901. return this._percentages[index] * 100 + "%";
  38902. case PrimitiveThickness.Inherit:
  38903. return "inherit";
  38904. }
  38905. return "";
  38906. };
  38907. PrimitiveThickness.prototype._isType = function (index, type) {
  38908. var f = (this._flags >> (index * 4)) & 0xF;
  38909. return f === type;
  38910. };
  38911. PrimitiveThickness.prototype._getType = function (index, processInherit) {
  38912. var t = (this._flags >> (index * 4)) & 0xF;
  38913. if (processInherit && (t === PrimitiveThickness.Inherit)) {
  38914. var p = this._parentAccess();
  38915. if (p) {
  38916. return p._getType(index, true);
  38917. }
  38918. return PrimitiveThickness.Auto;
  38919. }
  38920. return t;
  38921. };
  38922. PrimitiveThickness.prototype._setType = function (index, type) {
  38923. this._flags &= ~(0xF << (index * 4));
  38924. this._flags |= type << (index * 4);
  38925. };
  38926. PrimitiveThickness.prototype.setTop = function (value) {
  38927. if (typeof value === "string") {
  38928. this._setStringValue(value, 0, true);
  38929. }
  38930. else {
  38931. this.topPixels = value;
  38932. }
  38933. };
  38934. PrimitiveThickness.prototype.setLeft = function (value) {
  38935. if (typeof value === "string") {
  38936. this._setStringValue(value, 1, true);
  38937. }
  38938. else {
  38939. this.leftPixels = value;
  38940. }
  38941. };
  38942. PrimitiveThickness.prototype.setRight = function (value) {
  38943. if (typeof value === "string") {
  38944. this._setStringValue(value, 2, true);
  38945. }
  38946. else {
  38947. this.rightPixels = value;
  38948. }
  38949. };
  38950. PrimitiveThickness.prototype.setBottom = function (value) {
  38951. if (typeof value === "string") {
  38952. this._setStringValue(value, 3, true);
  38953. }
  38954. else {
  38955. this.bottomPixels = value;
  38956. }
  38957. };
  38958. Object.defineProperty(PrimitiveThickness.prototype, "top", {
  38959. /**
  38960. * Get/set the top thickness. Possible values are: 'auto', 'inherit', 'XX%' for percentage, 'XXpx' or 'XX' for pixels.
  38961. */
  38962. get: function () {
  38963. return this._getStringValue(0);
  38964. },
  38965. set: function (value) {
  38966. this._setStringValue(value, 0, true);
  38967. },
  38968. enumerable: true,
  38969. configurable: true
  38970. });
  38971. Object.defineProperty(PrimitiveThickness.prototype, "left", {
  38972. /**
  38973. * Get/set the left thickness. Possible values are: 'auto', 'inherit', 'XX%' for percentage, 'XXpx' or 'XX' for pixels.
  38974. */
  38975. get: function () {
  38976. return this._getStringValue(1);
  38977. },
  38978. set: function (value) {
  38979. this._setStringValue(value, 1, true);
  38980. },
  38981. enumerable: true,
  38982. configurable: true
  38983. });
  38984. Object.defineProperty(PrimitiveThickness.prototype, "right", {
  38985. /**
  38986. * Get/set the right thickness. Possible values are: 'auto', 'inherit', 'XX%' for percentage, 'XXpx' or 'XX' for pixels.
  38987. */
  38988. get: function () {
  38989. return this._getStringValue(2);
  38990. },
  38991. set: function (value) {
  38992. this._setStringValue(value, 2, true);
  38993. },
  38994. enumerable: true,
  38995. configurable: true
  38996. });
  38997. Object.defineProperty(PrimitiveThickness.prototype, "bottom", {
  38998. /**
  38999. * Get/set the bottom thickness. Possible values are: 'auto', 'inherit', 'XX%' for percentage, 'XXpx' or 'XX' for pixels.
  39000. */
  39001. get: function () {
  39002. return this._getStringValue(3);
  39003. },
  39004. set: function (value) {
  39005. this._setStringValue(value, 3, true);
  39006. },
  39007. enumerable: true,
  39008. configurable: true
  39009. });
  39010. Object.defineProperty(PrimitiveThickness.prototype, "topPixels", {
  39011. /**
  39012. * Get/set the top thickness in pixel.
  39013. */
  39014. get: function () {
  39015. return this._pixels[0];
  39016. },
  39017. set: function (value) {
  39018. this._setPixels(value, 0, true);
  39019. },
  39020. enumerable: true,
  39021. configurable: true
  39022. });
  39023. Object.defineProperty(PrimitiveThickness.prototype, "leftPixels", {
  39024. /**
  39025. * Get/set the left thickness in pixel.
  39026. */
  39027. get: function () {
  39028. return this._pixels[1];
  39029. },
  39030. set: function (value) {
  39031. this._setPixels(value, 1, true);
  39032. },
  39033. enumerable: true,
  39034. configurable: true
  39035. });
  39036. Object.defineProperty(PrimitiveThickness.prototype, "rightPixels", {
  39037. /**
  39038. * Get/set the right thickness in pixel.
  39039. */
  39040. get: function () {
  39041. return this._pixels[2];
  39042. },
  39043. set: function (value) {
  39044. this._setPixels(value, 2, true);
  39045. },
  39046. enumerable: true,
  39047. configurable: true
  39048. });
  39049. Object.defineProperty(PrimitiveThickness.prototype, "bottomPixels", {
  39050. /**
  39051. * Get/set the bottom thickness in pixel.
  39052. */
  39053. get: function () {
  39054. return this._pixels[3];
  39055. },
  39056. set: function (value) {
  39057. this._setPixels(value, 3, true);
  39058. },
  39059. enumerable: true,
  39060. configurable: true
  39061. });
  39062. Object.defineProperty(PrimitiveThickness.prototype, "topPercentage", {
  39063. /**
  39064. * Get/set the top thickness in percentage.
  39065. * The get will return a valid value only if the edge type is percentage.
  39066. * The Set will change the edge mode if needed
  39067. */
  39068. get: function () {
  39069. return this._percentages[0];
  39070. },
  39071. set: function (value) {
  39072. this._setPercentage(value, 0, true);
  39073. },
  39074. enumerable: true,
  39075. configurable: true
  39076. });
  39077. Object.defineProperty(PrimitiveThickness.prototype, "leftPercentage", {
  39078. /**
  39079. * Get/set the left thickness in percentage.
  39080. * The get will return a valid value only if the edge mode is percentage.
  39081. * The Set will change the edge mode if needed
  39082. */
  39083. get: function () {
  39084. return this._percentages[1];
  39085. },
  39086. set: function (value) {
  39087. this._setPercentage(value, 1, true);
  39088. },
  39089. enumerable: true,
  39090. configurable: true
  39091. });
  39092. Object.defineProperty(PrimitiveThickness.prototype, "rightPercentage", {
  39093. /**
  39094. * Get/set the right thickness in percentage.
  39095. * The get will return a valid value only if the edge mode is percentage.
  39096. * The Set will change the edge mode if needed
  39097. */
  39098. get: function () {
  39099. return this._percentages[2];
  39100. },
  39101. set: function (value) {
  39102. this._setPercentage(value, 2, true);
  39103. },
  39104. enumerable: true,
  39105. configurable: true
  39106. });
  39107. Object.defineProperty(PrimitiveThickness.prototype, "bottomPercentage", {
  39108. /**
  39109. * Get/set the bottom thickness in percentage.
  39110. * The get will return a valid value only if the edge mode is percentage.
  39111. * The Set will change the edge mode if needed
  39112. */
  39113. get: function () {
  39114. return this._percentages[3];
  39115. },
  39116. set: function (value) {
  39117. this._setPercentage(value, 3, true);
  39118. },
  39119. enumerable: true,
  39120. configurable: true
  39121. });
  39122. Object.defineProperty(PrimitiveThickness.prototype, "topMode", {
  39123. /**
  39124. * Get/set the top mode. The setter shouldn't be used, other setters with value should be preferred
  39125. */
  39126. get: function () {
  39127. return this._getType(0, false);
  39128. },
  39129. set: function (mode) {
  39130. this._setType(0, mode);
  39131. },
  39132. enumerable: true,
  39133. configurable: true
  39134. });
  39135. Object.defineProperty(PrimitiveThickness.prototype, "leftMode", {
  39136. /**
  39137. * Get/set the left mode. The setter shouldn't be used, other setters with value should be preferred
  39138. */
  39139. get: function () {
  39140. return this._getType(1, false);
  39141. },
  39142. set: function (mode) {
  39143. this._setType(1, mode);
  39144. },
  39145. enumerable: true,
  39146. configurable: true
  39147. });
  39148. Object.defineProperty(PrimitiveThickness.prototype, "rightMode", {
  39149. /**
  39150. * Get/set the right mode. The setter shouldn't be used, other setters with value should be preferred
  39151. */
  39152. get: function () {
  39153. return this._getType(2, false);
  39154. },
  39155. set: function (mode) {
  39156. this._setType(2, mode);
  39157. },
  39158. enumerable: true,
  39159. configurable: true
  39160. });
  39161. Object.defineProperty(PrimitiveThickness.prototype, "bottomMode", {
  39162. /**
  39163. * Get/set the bottom mode. The setter shouldn't be used, other setters with value should be preferred
  39164. */
  39165. get: function () {
  39166. return this._getType(3, false);
  39167. },
  39168. set: function (mode) {
  39169. this._setType(3, mode);
  39170. },
  39171. enumerable: true,
  39172. configurable: true
  39173. });
  39174. PrimitiveThickness.prototype._computePixels = function (index, sourceArea, emitChanged) {
  39175. var type = this._getType(index, false);
  39176. if (type === PrimitiveThickness.Inherit) {
  39177. this._parentAccess()._computePixels(index, sourceArea, emitChanged);
  39178. return;
  39179. }
  39180. if (type !== PrimitiveThickness.Percentage) {
  39181. return;
  39182. }
  39183. var pixels = ((index === 0 || index === 3) ? sourceArea.height : sourceArea.width) * this._percentages[index];
  39184. this._pixels[index] = pixels;
  39185. if (emitChanged) {
  39186. this._changedCallback();
  39187. }
  39188. };
  39189. /**
  39190. * Compute the positioning/size of an area considering the thickness of this object and a given alignment
  39191. * @param sourceArea the source area
  39192. * @param contentSize the content size to position/resize
  39193. * @param alignment the alignment setting
  39194. * @param dstOffset the position of the content
  39195. * @param dstArea the new size of the content
  39196. */
  39197. PrimitiveThickness.prototype.computeWithAlignment = function (sourceArea, contentSize, alignment, dstOffset, dstArea) {
  39198. // Fetch some data
  39199. var topType = this._getType(0, true);
  39200. var leftType = this._getType(1, true);
  39201. var rightType = this._getType(2, true);
  39202. var bottomType = this._getType(3, true);
  39203. var hasWidth = contentSize && (contentSize.width != null);
  39204. var hasHeight = contentSize && (contentSize.height != null);
  39205. var width = hasWidth ? contentSize.width : 0;
  39206. var height = hasHeight ? contentSize.height : 0;
  39207. var isTopAuto = topType === PrimitiveThickness.Auto;
  39208. var isLeftAuto = leftType === PrimitiveThickness.Auto;
  39209. var isRightAuto = rightType === PrimitiveThickness.Auto;
  39210. var isBottomAuto = bottomType === PrimitiveThickness.Auto;
  39211. switch (alignment.horizontal) {
  39212. case PrimitiveAlignment.AlignLeft:
  39213. {
  39214. if (isLeftAuto) {
  39215. dstOffset.x = 0;
  39216. }
  39217. else {
  39218. this._computePixels(1, sourceArea, true);
  39219. dstOffset.x = this.leftPixels;
  39220. }
  39221. dstArea.width = width;
  39222. break;
  39223. }
  39224. case PrimitiveAlignment.AlignRight:
  39225. {
  39226. if (isRightAuto) {
  39227. dstOffset.x = Math.round(sourceArea.width - width);
  39228. }
  39229. else {
  39230. this._computePixels(2, sourceArea, true);
  39231. dstOffset.x = Math.round(sourceArea.width - (width + this.rightPixels));
  39232. }
  39233. dstArea.width = width;
  39234. break;
  39235. }
  39236. case PrimitiveAlignment.AlignStretch:
  39237. {
  39238. if (isLeftAuto) {
  39239. dstOffset.x = 0;
  39240. }
  39241. else {
  39242. this._computePixels(1, sourceArea, true);
  39243. dstOffset.x = this.leftPixels;
  39244. }
  39245. var right = 0;
  39246. if (!isRightAuto) {
  39247. this._computePixels(2, sourceArea, true);
  39248. right = this.rightPixels;
  39249. }
  39250. dstArea.width = sourceArea.width - (dstOffset.x + right);
  39251. break;
  39252. }
  39253. case PrimitiveAlignment.AlignCenter:
  39254. {
  39255. if (!isLeftAuto) {
  39256. this._computePixels(1, sourceArea, true);
  39257. }
  39258. if (!isRightAuto) {
  39259. this._computePixels(2, sourceArea, true);
  39260. }
  39261. var offset = (isLeftAuto ? 0 : this.leftPixels) - (isRightAuto ? 0 : this.rightPixels);
  39262. dstOffset.x = Math.round(((sourceArea.width - width) / 2) + offset);
  39263. dstArea.width = width;
  39264. break;
  39265. }
  39266. }
  39267. switch (alignment.vertical) {
  39268. case PrimitiveAlignment.AlignTop:
  39269. {
  39270. if (isTopAuto) {
  39271. dstOffset.y = sourceArea.height - height;
  39272. }
  39273. else {
  39274. this._computePixels(0, sourceArea, true);
  39275. dstOffset.y = Math.round(sourceArea.height - (height + this.topPixels));
  39276. }
  39277. dstArea.height = height;
  39278. break;
  39279. }
  39280. case PrimitiveAlignment.AlignBottom:
  39281. {
  39282. if (isBottomAuto) {
  39283. dstOffset.y = 0;
  39284. }
  39285. else {
  39286. this._computePixels(3, sourceArea, true);
  39287. dstOffset.y = this.bottomPixels;
  39288. }
  39289. dstArea.height = height;
  39290. break;
  39291. }
  39292. case PrimitiveAlignment.AlignStretch:
  39293. {
  39294. if (isBottomAuto) {
  39295. dstOffset.y = 0;
  39296. }
  39297. else {
  39298. this._computePixels(3, sourceArea, true);
  39299. dstOffset.y = this.bottomPixels;
  39300. }
  39301. var top_1 = 0;
  39302. if (!isTopAuto) {
  39303. this._computePixels(0, sourceArea, true);
  39304. top_1 = this.topPixels;
  39305. }
  39306. dstArea.height = sourceArea.height - (dstOffset.y + top_1);
  39307. break;
  39308. }
  39309. case PrimitiveAlignment.AlignCenter:
  39310. {
  39311. if (!isTopAuto) {
  39312. this._computePixels(0, sourceArea, true);
  39313. }
  39314. if (!isBottomAuto) {
  39315. this._computePixels(3, sourceArea, true);
  39316. }
  39317. var offset = (isBottomAuto ? 0 : this.bottomPixels) - (isTopAuto ? 0 : this.topPixels);
  39318. dstOffset.y = Math.round(((sourceArea.height - height) / 2) + offset);
  39319. dstArea.height = height;
  39320. break;
  39321. }
  39322. }
  39323. };
  39324. /**
  39325. * Compute an area and its position considering this thickness properties based on a given source area
  39326. * @param sourceArea the source area
  39327. * @param dstOffset the position of the resulting area
  39328. * @param dstArea the size of the resulting area
  39329. */
  39330. PrimitiveThickness.prototype.compute = function (sourceArea, dstOffset, dstArea) {
  39331. this._computePixels(0, sourceArea, true);
  39332. this._computePixels(1, sourceArea, true);
  39333. this._computePixels(2, sourceArea, true);
  39334. this._computePixels(3, sourceArea, true);
  39335. dstOffset.x = this.leftPixels;
  39336. dstArea.width = sourceArea.width - (dstOffset.x + this.rightPixels);
  39337. dstOffset.y = this.bottomPixels;
  39338. dstArea.height = sourceArea.height - (dstOffset.y + this.topPixels);
  39339. };
  39340. /**
  39341. * Compute an area considering this thickness properties based on a given source area
  39342. * @param sourceArea the source area
  39343. * @param result the resulting area
  39344. */
  39345. PrimitiveThickness.prototype.computeArea = function (sourceArea, result) {
  39346. this._computePixels(0, sourceArea, true);
  39347. this._computePixels(1, sourceArea, true);
  39348. this._computePixels(2, sourceArea, true);
  39349. this._computePixels(3, sourceArea, true);
  39350. result.width = this.leftPixels + sourceArea.width + this.rightPixels;
  39351. result.height = this.bottomPixels + sourceArea.height + this.topPixels;
  39352. };
  39353. PrimitiveThickness.prototype.enlarge = function (sourceArea, dstOffset, enlargedArea) {
  39354. this._computePixels(0, sourceArea, true);
  39355. this._computePixels(1, sourceArea, true);
  39356. this._computePixels(2, sourceArea, true);
  39357. this._computePixels(3, sourceArea, true);
  39358. dstOffset.x = this.leftPixels;
  39359. enlargedArea.width = sourceArea.width + (dstOffset.x + this.rightPixels);
  39360. dstOffset.y = this.bottomPixels;
  39361. enlargedArea.height = sourceArea.height + (dstOffset.y + this.topPixels);
  39362. };
  39363. PrimitiveThickness.Auto = 0x1;
  39364. PrimitiveThickness.Inherit = 0x2;
  39365. PrimitiveThickness.Percentage = 0x4;
  39366. PrimitiveThickness.Pixel = 0x8;
  39367. return PrimitiveThickness;
  39368. }());
  39369. BABYLON.PrimitiveThickness = PrimitiveThickness;
  39370. /**
  39371. * Main class used for the Primitive Intersection API
  39372. */
  39373. var IntersectInfo2D = (function () {
  39374. function IntersectInfo2D() {
  39375. this.findFirstOnly = false;
  39376. this.intersectHidden = false;
  39377. this.pickPosition = BABYLON.Vector2.Zero();
  39378. }
  39379. Object.defineProperty(IntersectInfo2D.prototype, "isIntersected", {
  39380. /**
  39381. * true if at least one primitive intersected during the test
  39382. */
  39383. get: function () {
  39384. return this.intersectedPrimitives && this.intersectedPrimitives.length > 0;
  39385. },
  39386. enumerable: true,
  39387. configurable: true
  39388. });
  39389. IntersectInfo2D.prototype.isPrimIntersected = function (prim) {
  39390. for (var _i = 0, _a = this.intersectedPrimitives; _i < _a.length; _i++) {
  39391. var cur = _a[_i];
  39392. if (cur.prim === prim) {
  39393. return cur.intersectionLocation;
  39394. }
  39395. }
  39396. return null;
  39397. };
  39398. // Internals, don't use
  39399. IntersectInfo2D.prototype._exit = function (firstLevel) {
  39400. if (firstLevel) {
  39401. this._globalPickPosition = null;
  39402. }
  39403. };
  39404. return IntersectInfo2D;
  39405. }());
  39406. BABYLON.IntersectInfo2D = IntersectInfo2D;
  39407. var Prim2DBase = (function (_super) {
  39408. __extends(Prim2DBase, _super);
  39409. function Prim2DBase(settings) {
  39410. // Avoid checking every time if the object exists
  39411. if (settings == null) {
  39412. settings = {};
  39413. }
  39414. // BASE CLASS CALL
  39415. _super.call(this);
  39416. // Fetch the owner, parent. There're many ways to do it and we can end up with nothing for both
  39417. var owner;
  39418. var parent;
  39419. if (Prim2DBase._isCanvasInit) {
  39420. owner = this;
  39421. parent = null;
  39422. this._canvasPreInit(settings);
  39423. }
  39424. else {
  39425. if (settings.parent != null) {
  39426. parent = settings.parent;
  39427. owner = settings.parent.owner;
  39428. if (!owner) {
  39429. throw new Error("Parent " + parent.id + " of " + settings.id + " doesn't have a valid owner!");
  39430. }
  39431. 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)) {
  39432. 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");
  39433. }
  39434. }
  39435. }
  39436. // Fields initialization
  39437. this._layoutEngine = BABYLON.CanvasLayoutEngine.Singleton;
  39438. this._size = null; //Size.Zero();
  39439. this._actualSize = null;
  39440. this._boundingSize = BABYLON.Size.Zero();
  39441. this._layoutArea = BABYLON.Size.Zero();
  39442. this._layoutAreaPos = BABYLON.Vector2.Zero();
  39443. this._marginOffset = BABYLON.Vector2.Zero();
  39444. this._paddingOffset = BABYLON.Vector2.Zero();
  39445. this._parentPaddingOffset = BABYLON.Vector2.Zero();
  39446. this._parentContentArea = BABYLON.Size.Zero();
  39447. this._lastAutoSizeArea = BABYLON.Size.Zero();
  39448. this._contentArea = new BABYLON.Size(null, null);
  39449. this._pointerEventObservable = new BABYLON.Observable();
  39450. this._boundingInfo = new BABYLON.BoundingInfo2D();
  39451. this._owner = owner;
  39452. this._parent = null;
  39453. this._margin = null;
  39454. this._padding = null;
  39455. this._marginAlignment = null;
  39456. this._id = settings.id;
  39457. this.propertyChanged = new BABYLON.Observable();
  39458. this._children = new Array();
  39459. this._localTransform = new BABYLON.Matrix();
  39460. this._globalTransform = null;
  39461. this._invGlobalTransform = null;
  39462. this._globalTransformProcessStep = 0;
  39463. this._globalTransformStep = 0;
  39464. this._renderGroup = null;
  39465. this._primLinearPosition = 0;
  39466. this._manualZOrder = null;
  39467. this._zOrder = 0;
  39468. this._zMax = 0;
  39469. this._firstZDirtyIndex = Prim2DBase._bigInt;
  39470. this._setFlags(BABYLON.SmartPropertyPrim.flagIsPickable | BABYLON.SmartPropertyPrim.flagBoundingInfoDirty | BABYLON.SmartPropertyPrim.flagActualOpacityDirty);
  39471. if (settings.opacity != null) {
  39472. this._opacity = settings.opacity;
  39473. }
  39474. else {
  39475. this._opacity = 1;
  39476. }
  39477. if (settings.childrenFlatZOrder) {
  39478. this._setFlags(BABYLON.SmartPropertyPrim.flagChildrenFlatZOrder);
  39479. }
  39480. // If the parent is given, initialize the hierarchy/owner related data
  39481. if (parent != null) {
  39482. parent.addChild(this);
  39483. this._patchHierarchy(parent.owner);
  39484. }
  39485. // If it's a group, detect its own states
  39486. if (this.owner && this instanceof BABYLON.Group2D) {
  39487. var group = this;
  39488. group.detectGroupStates();
  39489. }
  39490. // Time to insert children if some are specified
  39491. if (settings.children != null) {
  39492. for (var _i = 0, _a = settings.children; _i < _a.length; _i++) {
  39493. var child = _a[_i];
  39494. this.addChild(child);
  39495. // Good time to patch the hierarchy, it won't go very far if there's no need to
  39496. child._patchHierarchy(this.owner);
  39497. }
  39498. }
  39499. // Set the model related properties
  39500. if (settings.position != null) {
  39501. this.position = settings.position;
  39502. }
  39503. else if (settings.x != null || settings.y != null) {
  39504. this.position = new BABYLON.Vector2(settings.x || 0, settings.y || 0);
  39505. }
  39506. else {
  39507. this._position = null;
  39508. }
  39509. this.rotation = (settings.rotation == null) ? 0 : settings.rotation;
  39510. this.scale = (settings.scale == null) ? 1 : settings.scale;
  39511. this.levelVisible = (settings.isVisible == null) ? true : settings.isVisible;
  39512. this.origin = settings.origin || new BABYLON.Vector2(0.5, 0.5);
  39513. // Layout Engine
  39514. if (settings.layoutEngine != null) {
  39515. if (typeof settings.layoutEngine === "string") {
  39516. var name_1 = settings.layoutEngine.toLocaleLowerCase().trim();
  39517. if (name_1 === "canvas" || name_1 === "canvaslayoutengine") {
  39518. this.layoutEngine = BABYLON.CanvasLayoutEngine.Singleton;
  39519. }
  39520. else if (name_1.indexOf("stackpanel") === 0 || name_1.indexOf("horizontalstackpanel") === 0) {
  39521. this.layoutEngine = BABYLON.StackPanelLayoutEngine.Horizontal;
  39522. }
  39523. else if (name_1.indexOf("verticalstackpanel") === 0) {
  39524. this.layoutEngine = BABYLON.StackPanelLayoutEngine.Vertical;
  39525. }
  39526. }
  39527. else if (settings.layoutEngine instanceof BABYLON.LayoutEngineBase) {
  39528. this.layoutEngine = settings.layoutEngine;
  39529. }
  39530. }
  39531. // Set the layout/margin stuffs
  39532. if (settings.marginTop) {
  39533. this.margin.setTop(settings.marginTop);
  39534. }
  39535. if (settings.marginLeft) {
  39536. this.margin.setLeft(settings.marginLeft);
  39537. }
  39538. if (settings.marginRight) {
  39539. this.margin.setRight(settings.marginRight);
  39540. }
  39541. if (settings.marginBottom) {
  39542. this.margin.setBottom(settings.marginBottom);
  39543. }
  39544. if (settings.margin) {
  39545. if (typeof settings.margin === "string") {
  39546. this.margin.fromString(settings.margin);
  39547. }
  39548. else {
  39549. this.margin.fromUniformPixels(settings.margin);
  39550. }
  39551. }
  39552. if (settings.marginHAlignment) {
  39553. this.marginAlignment.horizontal = settings.marginHAlignment;
  39554. }
  39555. if (settings.marginVAlignment) {
  39556. this.marginAlignment.vertical = settings.marginVAlignment;
  39557. }
  39558. if (settings.marginAlignment) {
  39559. this.marginAlignment.fromString(settings.marginAlignment);
  39560. }
  39561. if (settings.paddingTop) {
  39562. this.padding.setTop(settings.paddingTop);
  39563. }
  39564. if (settings.paddingLeft) {
  39565. this.padding.setLeft(settings.paddingLeft);
  39566. }
  39567. if (settings.paddingRight) {
  39568. this.padding.setRight(settings.paddingRight);
  39569. }
  39570. if (settings.paddingBottom) {
  39571. this.padding.setBottom(settings.paddingBottom);
  39572. }
  39573. if (settings.padding) {
  39574. this.padding.fromString(settings.padding);
  39575. }
  39576. // Dirty layout and positioning
  39577. this._parentLayoutDirty();
  39578. this._positioningDirty();
  39579. }
  39580. Object.defineProperty(Prim2DBase.prototype, "actionManager", {
  39581. get: function () {
  39582. if (!this._actionManager) {
  39583. this._actionManager = new BABYLON.ActionManager(this.owner.scene);
  39584. }
  39585. return this._actionManager;
  39586. },
  39587. enumerable: true,
  39588. configurable: true
  39589. });
  39590. /**
  39591. * From 'this' primitive, traverse up (from parent to parent) until the given predicate is true
  39592. * @param predicate the predicate to test on each parent
  39593. * @return the first primitive where the predicate was successful
  39594. */
  39595. Prim2DBase.prototype.traverseUp = function (predicate) {
  39596. var p = this;
  39597. while (p != null) {
  39598. if (predicate(p)) {
  39599. return p;
  39600. }
  39601. p = p._parent;
  39602. }
  39603. return null;
  39604. };
  39605. Object.defineProperty(Prim2DBase.prototype, "owner", {
  39606. /**
  39607. * Retrieve the owner Canvas2D
  39608. */
  39609. get: function () {
  39610. return this._owner;
  39611. },
  39612. enumerable: true,
  39613. configurable: true
  39614. });
  39615. Object.defineProperty(Prim2DBase.prototype, "parent", {
  39616. /**
  39617. * Get the parent primitive (can be the Canvas, only the Canvas has no parent)
  39618. */
  39619. get: function () {
  39620. return this._parent;
  39621. },
  39622. enumerable: true,
  39623. configurable: true
  39624. });
  39625. Object.defineProperty(Prim2DBase.prototype, "children", {
  39626. /**
  39627. * The array of direct children primitives
  39628. */
  39629. get: function () {
  39630. return this._children;
  39631. },
  39632. enumerable: true,
  39633. configurable: true
  39634. });
  39635. Object.defineProperty(Prim2DBase.prototype, "id", {
  39636. /**
  39637. * The identifier of this primitive, may not be unique, it's for information purpose only
  39638. */
  39639. get: function () {
  39640. return this._id;
  39641. },
  39642. enumerable: true,
  39643. configurable: true
  39644. });
  39645. Object.defineProperty(Prim2DBase.prototype, "actualPosition", {
  39646. get: function () {
  39647. if (this._actualPosition != null) {
  39648. return this._actualPosition;
  39649. }
  39650. if (this._position != null) {
  39651. return this._position;
  39652. }
  39653. // At least return 0,0, we can't return null on actualPosition
  39654. return Prim2DBase._nullPosition;
  39655. },
  39656. /**
  39657. * DO NOT INVOKE for internal purpose only
  39658. */
  39659. set: function (val) {
  39660. this._actualPosition = val;
  39661. },
  39662. enumerable: true,
  39663. configurable: true
  39664. });
  39665. Object.defineProperty(Prim2DBase.prototype, "actualX", {
  39666. /**
  39667. * Shortcut to actualPosition.x
  39668. */
  39669. get: function () {
  39670. return this.actualPosition.x;
  39671. },
  39672. enumerable: true,
  39673. configurable: true
  39674. });
  39675. Object.defineProperty(Prim2DBase.prototype, "actualY", {
  39676. /**
  39677. * Shortcut to actualPosition.y
  39678. */
  39679. get: function () {
  39680. return this.actualPosition.y;
  39681. },
  39682. enumerable: true,
  39683. configurable: true
  39684. });
  39685. Object.defineProperty(Prim2DBase.prototype, "position", {
  39686. /**
  39687. * Position of the primitive, relative to its parent.
  39688. * BEWARE: if you change only position.x or y it won't trigger a property change and you won't have the expected behavior.
  39689. * Use this property to set a new Vector2 object, otherwise to change only the x/y use Prim2DBase.x or y properties.
  39690. * Setting this property may have no effect is specific alignment are in effect.
  39691. */
  39692. get: function () {
  39693. return this._position || Prim2DBase._nullPosition;
  39694. },
  39695. set: function (value) {
  39696. if (!this._checkPositionChange()) {
  39697. return;
  39698. }
  39699. this._position = value;
  39700. this.markAsDirty("actualPosition");
  39701. },
  39702. enumerable: true,
  39703. configurable: true
  39704. });
  39705. Object.defineProperty(Prim2DBase.prototype, "x", {
  39706. /**
  39707. * Direct access to the position.x value of the primitive
  39708. * Use this property when you only want to change one component of the position property
  39709. */
  39710. get: function () {
  39711. if (!this._position) {
  39712. return null;
  39713. }
  39714. return this._position.x;
  39715. },
  39716. set: function (value) {
  39717. if (!this._checkPositionChange()) {
  39718. return;
  39719. }
  39720. if (!this._position) {
  39721. this._position = BABYLON.Vector2.Zero();
  39722. }
  39723. if (this._position.x === value) {
  39724. return;
  39725. }
  39726. this._position.x = value;
  39727. this.markAsDirty("position");
  39728. this.markAsDirty("actualPosition");
  39729. },
  39730. enumerable: true,
  39731. configurable: true
  39732. });
  39733. Object.defineProperty(Prim2DBase.prototype, "y", {
  39734. /**
  39735. * Direct access to the position.y value of the primitive
  39736. * Use this property when you only want to change one component of the position property
  39737. */
  39738. get: function () {
  39739. if (!this._position) {
  39740. return null;
  39741. }
  39742. return this._position.y;
  39743. },
  39744. set: function (value) {
  39745. if (!this._checkPositionChange()) {
  39746. return;
  39747. }
  39748. if (!this._position) {
  39749. this._position = BABYLON.Vector2.Zero();
  39750. }
  39751. if (this._position.y === value) {
  39752. return;
  39753. }
  39754. this._position.y = value;
  39755. this.markAsDirty("position");
  39756. this.markAsDirty("actualPosition");
  39757. },
  39758. enumerable: true,
  39759. configurable: true
  39760. });
  39761. Object.defineProperty(Prim2DBase.prototype, "size", {
  39762. /**
  39763. * Size of the primitive or its bounding area
  39764. * BEWARE: if you change only size.width or height it won't trigger a property change and you won't have the expected behavior.
  39765. * Use this property to set a new Size object, otherwise to change only the width/height use Prim2DBase.width or height properties.
  39766. */
  39767. get: function () {
  39768. if (!this._size || this._size.width == null || this._size.height == null) {
  39769. if (Prim2DBase.boundinbBoxReentrency) {
  39770. return Prim2DBase.nullSize;
  39771. }
  39772. if (!this._isFlagSet(BABYLON.SmartPropertyPrim.flagBoundingInfoDirty)) {
  39773. return this._boundingSize;
  39774. }
  39775. Prim2DBase.boundinbBoxReentrency = true;
  39776. var b = this.boundingInfo;
  39777. Prim2DBase.boundinbBoxReentrency = false;
  39778. return this._boundingSize;
  39779. }
  39780. return this._size;
  39781. },
  39782. set: function (value) {
  39783. this._size = value;
  39784. },
  39785. enumerable: true,
  39786. configurable: true
  39787. });
  39788. Object.defineProperty(Prim2DBase.prototype, "width", {
  39789. /**
  39790. * Direct access to the size.width value of the primitive
  39791. * Use this property when you only want to change one component of the size property
  39792. */
  39793. get: function () {
  39794. if (!this.size) {
  39795. return null;
  39796. }
  39797. return this.size.width;
  39798. },
  39799. set: function (value) {
  39800. if (!this.size) {
  39801. this.size = new BABYLON.Size(value, 0);
  39802. return;
  39803. }
  39804. if (this.size.width === value) {
  39805. return;
  39806. }
  39807. this.size.width = value;
  39808. this.markAsDirty("size");
  39809. this._positioningDirty();
  39810. },
  39811. enumerable: true,
  39812. configurable: true
  39813. });
  39814. Object.defineProperty(Prim2DBase.prototype, "height", {
  39815. /**
  39816. * Direct access to the size.height value of the primitive
  39817. * Use this property when you only want to change one component of the size property
  39818. */
  39819. get: function () {
  39820. if (!this.size) {
  39821. return null;
  39822. }
  39823. return this.size.height;
  39824. },
  39825. set: function (value) {
  39826. if (!this.size) {
  39827. this.size = new BABYLON.Size(0, value);
  39828. return;
  39829. }
  39830. if (this.size.height === value) {
  39831. return;
  39832. }
  39833. this.size.height = value;
  39834. this.markAsDirty("size");
  39835. this._positioningDirty();
  39836. },
  39837. enumerable: true,
  39838. configurable: true
  39839. });
  39840. Object.defineProperty(Prim2DBase.prototype, "rotation", {
  39841. get: function () {
  39842. return this._rotation;
  39843. },
  39844. set: function (value) {
  39845. this._rotation = value;
  39846. },
  39847. enumerable: true,
  39848. configurable: true
  39849. });
  39850. Object.defineProperty(Prim2DBase.prototype, "scale", {
  39851. get: function () {
  39852. return this._scale;
  39853. },
  39854. set: function (value) {
  39855. this._scale = value;
  39856. },
  39857. enumerable: true,
  39858. configurable: true
  39859. });
  39860. Object.defineProperty(Prim2DBase.prototype, "actualSize", {
  39861. /**
  39862. * Return the size of the primitive as it's being rendered into the target.
  39863. * 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.
  39864. * BEWARE: don't use the setter, it's for internal purpose only
  39865. * Note to implementers: you have to override this property and declare if necessary a @xxxxInstanceLevel decorator
  39866. */
  39867. get: function () {
  39868. if (this._actualSize) {
  39869. return this._actualSize;
  39870. }
  39871. return this._size;
  39872. },
  39873. set: function (value) {
  39874. if (this._actualSize.equals(value)) {
  39875. return;
  39876. }
  39877. this._actualSize = value;
  39878. },
  39879. enumerable: true,
  39880. configurable: true
  39881. });
  39882. Object.defineProperty(Prim2DBase.prototype, "actualZOffset", {
  39883. get: function () {
  39884. if (this._manualZOrder != null) {
  39885. return this._manualZOrder;
  39886. }
  39887. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagZOrderDirty)) {
  39888. this._updateZOrder();
  39889. }
  39890. return (1 - this._zOrder);
  39891. },
  39892. enumerable: true,
  39893. configurable: true
  39894. });
  39895. Object.defineProperty(Prim2DBase.prototype, "minSize", {
  39896. /**
  39897. * Get or set the minimal size the Layout Engine should respect when computing the primitive's actualSize.
  39898. * The Primitive's size won't be less than specified.
  39899. * The default value depends of the Primitive type
  39900. */
  39901. get: function () {
  39902. return this._minSize;
  39903. },
  39904. set: function (value) {
  39905. if (this._minSize && value && this._minSize.equals(value)) {
  39906. return;
  39907. }
  39908. this._minSize = value;
  39909. this._parentLayoutDirty();
  39910. },
  39911. enumerable: true,
  39912. configurable: true
  39913. });
  39914. Object.defineProperty(Prim2DBase.prototype, "maxSize", {
  39915. /**
  39916. * Get or set the maximal size the Layout Engine should respect when computing the primitive's actualSize.
  39917. * The Primitive's size won't be more than specified.
  39918. * The default value depends of the Primitive type
  39919. */
  39920. get: function () {
  39921. return this._maxSize;
  39922. },
  39923. set: function (value) {
  39924. if (this._maxSize && value && this._maxSize.equals(value)) {
  39925. return;
  39926. }
  39927. this._maxSize = value;
  39928. this._parentLayoutDirty();
  39929. },
  39930. enumerable: true,
  39931. configurable: true
  39932. });
  39933. Object.defineProperty(Prim2DBase.prototype, "origin", {
  39934. /**
  39935. * The origin defines the normalized coordinate of the center of the primitive, from the bottom/left corner.
  39936. * The origin is used only to compute transformation of the primitive, it has no meaning in the primitive local frame of reference
  39937. * For instance:
  39938. * 0,0 means the center is bottom/left. Which is the default for Canvas2D instances
  39939. * 0.5,0.5 means the center is at the center of the primitive, which is default of all types of Primitives
  39940. * 0,1 means the center is top/left
  39941. * @returns The normalized center.
  39942. */
  39943. get: function () {
  39944. return this._origin;
  39945. },
  39946. set: function (value) {
  39947. this._origin = value;
  39948. },
  39949. enumerable: true,
  39950. configurable: true
  39951. });
  39952. Object.defineProperty(Prim2DBase.prototype, "levelVisible", {
  39953. get: function () {
  39954. return this._isFlagSet(BABYLON.SmartPropertyPrim.flagLevelVisible);
  39955. },
  39956. set: function (value) {
  39957. this._changeFlags(BABYLON.SmartPropertyPrim.flagLevelVisible, value);
  39958. },
  39959. enumerable: true,
  39960. configurable: true
  39961. });
  39962. Object.defineProperty(Prim2DBase.prototype, "isVisible", {
  39963. get: function () {
  39964. return this._isFlagSet(BABYLON.SmartPropertyPrim.flagIsVisible);
  39965. },
  39966. set: function (value) {
  39967. this._changeFlags(BABYLON.SmartPropertyPrim.flagIsVisible, value);
  39968. },
  39969. enumerable: true,
  39970. configurable: true
  39971. });
  39972. Object.defineProperty(Prim2DBase.prototype, "zOrder", {
  39973. get: function () {
  39974. return this._manualZOrder;
  39975. },
  39976. set: function (value) {
  39977. if (this._manualZOrder === value) {
  39978. return;
  39979. }
  39980. this._manualZOrder = value;
  39981. this.onZOrderChanged();
  39982. if (this._actualZOrderChangedObservable && this._actualZOrderChangedObservable.hasObservers()) {
  39983. this._actualZOrderChangedObservable.notifyObservers(value);
  39984. }
  39985. },
  39986. enumerable: true,
  39987. configurable: true
  39988. });
  39989. Object.defineProperty(Prim2DBase.prototype, "isManualZOrder", {
  39990. get: function () {
  39991. return this._manualZOrder != null;
  39992. },
  39993. enumerable: true,
  39994. configurable: true
  39995. });
  39996. Object.defineProperty(Prim2DBase.prototype, "margin", {
  39997. get: function () {
  39998. var _this = this;
  39999. if (!this._margin) {
  40000. this._margin = new PrimitiveThickness(function () {
  40001. if (!_this.parent) {
  40002. return null;
  40003. }
  40004. return _this.parent.margin;
  40005. }, function () { return _this._positioningDirty(); });
  40006. }
  40007. return this._margin;
  40008. },
  40009. enumerable: true,
  40010. configurable: true
  40011. });
  40012. Object.defineProperty(Prim2DBase.prototype, "_hasMargin", {
  40013. get: function () {
  40014. return (this._margin !== null) || (this._marginAlignment !== null);
  40015. },
  40016. enumerable: true,
  40017. configurable: true
  40018. });
  40019. Object.defineProperty(Prim2DBase.prototype, "padding", {
  40020. get: function () {
  40021. var _this = this;
  40022. if (!this._padding) {
  40023. this._padding = new PrimitiveThickness(function () {
  40024. if (!_this.parent) {
  40025. return null;
  40026. }
  40027. return _this.parent.padding;
  40028. }, function () { return _this._positioningDirty(); });
  40029. }
  40030. return this._padding;
  40031. },
  40032. enumerable: true,
  40033. configurable: true
  40034. });
  40035. Object.defineProperty(Prim2DBase.prototype, "_hasPadding", {
  40036. get: function () {
  40037. return this._padding !== null;
  40038. },
  40039. enumerable: true,
  40040. configurable: true
  40041. });
  40042. Object.defineProperty(Prim2DBase.prototype, "marginAlignment", {
  40043. get: function () {
  40044. var _this = this;
  40045. if (!this._marginAlignment) {
  40046. this._marginAlignment = new PrimitiveAlignment(function () { return _this._positioningDirty(); });
  40047. }
  40048. return this._marginAlignment;
  40049. },
  40050. enumerable: true,
  40051. configurable: true
  40052. });
  40053. Object.defineProperty(Prim2DBase.prototype, "opacity", {
  40054. get: function () {
  40055. return this._opacity;
  40056. },
  40057. set: function (value) {
  40058. if (value < 0) {
  40059. value = 0;
  40060. }
  40061. else if (value > 1) {
  40062. value = 1;
  40063. }
  40064. if (this._opacity === value) {
  40065. return;
  40066. }
  40067. this._opacity = value;
  40068. this._updateRenderMode();
  40069. this._setFlags(BABYLON.SmartPropertyPrim.flagActualOpacityDirty);
  40070. this._spreadActualOpacityChanged();
  40071. },
  40072. enumerable: true,
  40073. configurable: true
  40074. });
  40075. Object.defineProperty(Prim2DBase.prototype, "actualOpacity", {
  40076. get: function () {
  40077. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagActualOpacityDirty)) {
  40078. var cur = this.parent;
  40079. var op = this.opacity;
  40080. while (cur) {
  40081. op *= cur.opacity;
  40082. cur = cur.parent;
  40083. }
  40084. this._actualOpacity = op;
  40085. this._clearFlags(BABYLON.SmartPropertyPrim.flagActualOpacityDirty);
  40086. }
  40087. return this._actualOpacity;
  40088. },
  40089. enumerable: true,
  40090. configurable: true
  40091. });
  40092. Object.defineProperty(Prim2DBase.prototype, "layoutEngine", {
  40093. /**
  40094. * Get/set the layout engine to use for this primitive.
  40095. * The default layout engine is the CanvasLayoutEngine.
  40096. */
  40097. get: function () {
  40098. if (!this._layoutEngine) {
  40099. this._layoutEngine = BABYLON.CanvasLayoutEngine.Singleton;
  40100. }
  40101. return this._layoutEngine;
  40102. },
  40103. set: function (value) {
  40104. if (this._layoutEngine === value) {
  40105. return;
  40106. }
  40107. this._changeLayoutEngine(value);
  40108. },
  40109. enumerable: true,
  40110. configurable: true
  40111. });
  40112. Object.defineProperty(Prim2DBase.prototype, "layoutArea", {
  40113. /**
  40114. * Get/set the layout are of this primitive.
  40115. * The Layout area is the zone allocated by the Layout Engine for this particular primitive. Margins/Alignment will be computed based on this area.
  40116. * The setter should only be called by a Layout Engine class.
  40117. */
  40118. get: function () {
  40119. return this._layoutArea;
  40120. },
  40121. set: function (val) {
  40122. if (this._layoutArea.equals(val)) {
  40123. return;
  40124. }
  40125. this._positioningDirty();
  40126. this._layoutArea = val;
  40127. },
  40128. enumerable: true,
  40129. configurable: true
  40130. });
  40131. Object.defineProperty(Prim2DBase.prototype, "layoutAreaPos", {
  40132. /**
  40133. * Get/set the layout area position (relative to the parent primitive).
  40134. * The setter should only be called by a Layout Engine class.
  40135. */
  40136. get: function () {
  40137. return this._layoutAreaPos;
  40138. },
  40139. set: function (val) {
  40140. if (this._layoutAreaPos.equals(val)) {
  40141. return;
  40142. }
  40143. this._positioningDirty();
  40144. this._layoutAreaPos = val;
  40145. },
  40146. enumerable: true,
  40147. configurable: true
  40148. });
  40149. Object.defineProperty(Prim2DBase.prototype, "isPickable", {
  40150. /**
  40151. * Define if the Primitive can be subject to intersection test or not (default is true)
  40152. */
  40153. get: function () {
  40154. return this._isFlagSet(BABYLON.SmartPropertyPrim.flagIsPickable);
  40155. },
  40156. set: function (value) {
  40157. this._changeFlags(BABYLON.SmartPropertyPrim.flagIsPickable, value);
  40158. },
  40159. enumerable: true,
  40160. configurable: true
  40161. });
  40162. Object.defineProperty(Prim2DBase.prototype, "hierarchyDepth", {
  40163. /**
  40164. * Return the depth level of the Primitive into the Canvas' Graph. A Canvas will be 0, its direct children 1, and so on.
  40165. */
  40166. get: function () {
  40167. return this._hierarchyDepth;
  40168. },
  40169. enumerable: true,
  40170. configurable: true
  40171. });
  40172. Object.defineProperty(Prim2DBase.prototype, "renderGroup", {
  40173. /**
  40174. * Retrieve the Group that is responsible to render this primitive
  40175. */
  40176. get: function () {
  40177. return this._renderGroup;
  40178. },
  40179. enumerable: true,
  40180. configurable: true
  40181. });
  40182. Object.defineProperty(Prim2DBase.prototype, "globalTransform", {
  40183. /**
  40184. * Get the global transformation matrix of the primitive
  40185. */
  40186. get: function () {
  40187. return this._globalTransform;
  40188. },
  40189. enumerable: true,
  40190. configurable: true
  40191. });
  40192. /**
  40193. * return the global position of the primitive, relative to its canvas
  40194. */
  40195. Prim2DBase.prototype.getGlobalPosition = function () {
  40196. var v = new BABYLON.Vector2(0, 0);
  40197. this.getGlobalPositionByRef(v);
  40198. return v;
  40199. };
  40200. /**
  40201. * return the global position of the primitive, relative to its canvas
  40202. * @param v the valid Vector2 object where the global position will be stored
  40203. */
  40204. Prim2DBase.prototype.getGlobalPositionByRef = function (v) {
  40205. v.x = this.globalTransform.m[12];
  40206. v.y = this.globalTransform.m[13];
  40207. };
  40208. Object.defineProperty(Prim2DBase.prototype, "invGlobalTransform", {
  40209. /**
  40210. * Get invert of the global transformation matrix of the primitive
  40211. */
  40212. get: function () {
  40213. return this._invGlobalTransform;
  40214. },
  40215. enumerable: true,
  40216. configurable: true
  40217. });
  40218. Object.defineProperty(Prim2DBase.prototype, "localTransform", {
  40219. /**
  40220. * Get the local transformation of the primitive
  40221. */
  40222. get: function () {
  40223. this._updateLocalTransform();
  40224. return this._localTransform;
  40225. },
  40226. enumerable: true,
  40227. configurable: true
  40228. });
  40229. Object.defineProperty(Prim2DBase.prototype, "boundingInfo", {
  40230. /**
  40231. * Get the boundingInfo associated to the primitive and its children.
  40232. * The value is supposed to be always up to date
  40233. */
  40234. get: function () {
  40235. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagBoundingInfoDirty)) {
  40236. if (this.owner) {
  40237. this.owner.boundingInfoRecomputeCounter.addCount(1, false);
  40238. }
  40239. if (this.isSizedByContent) {
  40240. this._boundingInfo.clear();
  40241. }
  40242. else {
  40243. this._boundingInfo.copyFrom(this.levelBoundingInfo);
  40244. }
  40245. var bi = this._boundingInfo;
  40246. var tps = new BABYLON.BoundingInfo2D();
  40247. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  40248. var curChild = _a[_i];
  40249. curChild.boundingInfo.transformToRef(curChild.localTransform, tps);
  40250. bi.unionToRef(tps, bi);
  40251. }
  40252. this._boundingInfo.maxToRef(Prim2DBase._bMax);
  40253. this._boundingSize.copyFromFloats((!this._size || this._size.width == null) ? Math.ceil(Prim2DBase._bMax.x) : this._size.width, (!this._size || this._size.height == null) ? Math.ceil(Prim2DBase._bMax.y) : this._size.height);
  40254. this._clearFlags(BABYLON.SmartPropertyPrim.flagBoundingInfoDirty);
  40255. }
  40256. return this._boundingInfo;
  40257. },
  40258. enumerable: true,
  40259. configurable: true
  40260. });
  40261. Object.defineProperty(Prim2DBase.prototype, "isSizeAuto", {
  40262. /**
  40263. * Determine if the size is automatically computed or fixed because manually specified.
  40264. * Use the actualSize property to get the final/real size of the primitive
  40265. * @returns true if the size is automatically computed, false if it were manually specified.
  40266. */
  40267. get: function () {
  40268. return this._size == null;
  40269. },
  40270. enumerable: true,
  40271. configurable: true
  40272. });
  40273. Object.defineProperty(Prim2DBase.prototype, "isSizedByContent", {
  40274. /**
  40275. * Return true if this prim has an auto size which is set by the children's global bounding box
  40276. */
  40277. get: function () {
  40278. return (this._size == null) && (this._children.length > 0);
  40279. },
  40280. enumerable: true,
  40281. configurable: true
  40282. });
  40283. Object.defineProperty(Prim2DBase.prototype, "isPositionAuto", {
  40284. /**
  40285. * Determine if the position is automatically computed or fixed because manually specified.
  40286. * Use the actualPosition property to get the final/real position of the primitive
  40287. * @returns true if the position is automatically computed, false if it were manually specified.
  40288. */
  40289. get: function () {
  40290. return this._position == null;
  40291. },
  40292. enumerable: true,
  40293. configurable: true
  40294. });
  40295. Object.defineProperty(Prim2DBase.prototype, "pointerEventObservable", {
  40296. /**
  40297. * Interaction with the primitive can be create using this Observable. See the PrimitivePointerInfo class for more information
  40298. */
  40299. get: function () {
  40300. return this._pointerEventObservable;
  40301. },
  40302. enumerable: true,
  40303. configurable: true
  40304. });
  40305. Object.defineProperty(Prim2DBase.prototype, "zActualOrderChangedObservable", {
  40306. get: function () {
  40307. if (!this._actualZOrderChangedObservable) {
  40308. this._actualZOrderChangedObservable = new BABYLON.Observable();
  40309. }
  40310. return this._actualZOrderChangedObservable;
  40311. },
  40312. enumerable: true,
  40313. configurable: true
  40314. });
  40315. Prim2DBase.prototype.findById = function (id) {
  40316. if (this._id === id) {
  40317. return this;
  40318. }
  40319. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  40320. var child = _a[_i];
  40321. var r = child.findById(id);
  40322. if (r != null) {
  40323. return r;
  40324. }
  40325. }
  40326. };
  40327. Prim2DBase.prototype.onZOrderChanged = function () {
  40328. };
  40329. Prim2DBase.prototype.levelIntersect = function (intersectInfo) {
  40330. return false;
  40331. };
  40332. /**
  40333. * Capture all the Events of the given PointerId for this primitive.
  40334. * Don't forget to call releasePointerEventsCapture when done.
  40335. * @param pointerId the Id of the pointer to capture the events from.
  40336. */
  40337. Prim2DBase.prototype.setPointerEventCapture = function (pointerId) {
  40338. return this.owner._setPointerCapture(pointerId, this);
  40339. };
  40340. /**
  40341. * Release a captured pointer made with setPointerEventCapture.
  40342. * @param pointerId the Id of the pointer to release the capture from.
  40343. */
  40344. Prim2DBase.prototype.releasePointerEventsCapture = function (pointerId) {
  40345. return this.owner._releasePointerCapture(pointerId, this);
  40346. };
  40347. /**
  40348. * Make an intersection test with the primitive, all inputs/outputs are stored in the IntersectInfo2D class, see its documentation for more information.
  40349. * @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.
  40350. */
  40351. Prim2DBase.prototype.intersect = function (intersectInfo) {
  40352. if (!intersectInfo) {
  40353. return false;
  40354. }
  40355. // If this is null it means this method is call for the first level, initialize stuffs
  40356. var firstLevel = !intersectInfo._globalPickPosition;
  40357. if (firstLevel) {
  40358. // 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).
  40359. intersectInfo._globalPickPosition = BABYLON.Vector2.Zero();
  40360. BABYLON.Vector2.TransformToRef(intersectInfo.pickPosition, this.globalTransform, intersectInfo._globalPickPosition);
  40361. intersectInfo._localPickPosition = intersectInfo.pickPosition.clone();
  40362. intersectInfo.intersectedPrimitives = new Array();
  40363. intersectInfo.topMostIntersectedPrimitive = null;
  40364. }
  40365. if (!intersectInfo.intersectHidden && !this.isVisible) {
  40366. return false;
  40367. }
  40368. // Fast rejection test with boundingInfo
  40369. if (this.isPickable && !this.boundingInfo.doesIntersect(intersectInfo._localPickPosition)) {
  40370. // Important to call this before each return to allow a good recursion next time this intersectInfo is reused
  40371. intersectInfo._exit(firstLevel);
  40372. return false;
  40373. }
  40374. // We hit the boundingInfo that bounds this primitive and its children, now we have to test on the primitive of this level
  40375. var levelIntersectRes = false;
  40376. if (this.isPickable) {
  40377. levelIntersectRes = this.levelIntersect(intersectInfo);
  40378. if (levelIntersectRes) {
  40379. var pii = new PrimitiveIntersectedInfo(this, intersectInfo._localPickPosition.clone());
  40380. intersectInfo.intersectedPrimitives.push(pii);
  40381. if (!intersectInfo.topMostIntersectedPrimitive || (intersectInfo.topMostIntersectedPrimitive.prim.actualZOffset > pii.prim.actualZOffset)) {
  40382. intersectInfo.topMostIntersectedPrimitive = pii;
  40383. }
  40384. // If we must stop at the first intersection, we're done, quit!
  40385. if (intersectInfo.findFirstOnly) {
  40386. intersectInfo._exit(firstLevel);
  40387. return true;
  40388. }
  40389. }
  40390. }
  40391. // Recurse to children if needed
  40392. if (!levelIntersectRes || !intersectInfo.findFirstOnly) {
  40393. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  40394. var curChild = _a[_i];
  40395. // Don't test primitive not pick able or if it's hidden and we don't test hidden ones
  40396. if (!curChild.isPickable || (!intersectInfo.intersectHidden && !curChild.isVisible)) {
  40397. continue;
  40398. }
  40399. // Must compute the localPickLocation for the children level
  40400. BABYLON.Vector2.TransformToRef(intersectInfo._globalPickPosition, curChild.invGlobalTransform, intersectInfo._localPickPosition);
  40401. // If we got an intersection with the child and we only need to find the first one, quit!
  40402. if (curChild.intersect(intersectInfo) && intersectInfo.findFirstOnly) {
  40403. intersectInfo._exit(firstLevel);
  40404. return true;
  40405. }
  40406. }
  40407. }
  40408. intersectInfo._exit(firstLevel);
  40409. return intersectInfo.isIntersected;
  40410. };
  40411. Prim2DBase.prototype.moveChild = function (child, previous) {
  40412. if (child.parent !== this) {
  40413. return false;
  40414. }
  40415. var childIndex = this._children.indexOf(child);
  40416. var prevIndex = previous ? this._children.indexOf(previous) : -1;
  40417. if (!this._isFlagSet(BABYLON.SmartPropertyPrim.flagChildrenFlatZOrder)) {
  40418. this._setFlags(BABYLON.SmartPropertyPrim.flagZOrderDirty);
  40419. this._firstZDirtyIndex = Math.min(this._firstZDirtyIndex, prevIndex + 1);
  40420. }
  40421. this._children.splice(prevIndex + 1, 0, this._children.splice(childIndex, 1)[0]);
  40422. };
  40423. Prim2DBase.prototype.addChild = function (child) {
  40424. child._parent = this;
  40425. this._boundingBoxDirty();
  40426. var flat = this._isFlagSet(BABYLON.SmartPropertyPrim.flagChildrenFlatZOrder);
  40427. if (flat) {
  40428. child._setFlags(BABYLON.SmartPropertyPrim.flagChildrenFlatZOrder);
  40429. child._setZOrder(this._zOrder, true);
  40430. child._zMax = this._zOrder;
  40431. }
  40432. else {
  40433. this._setFlags(BABYLON.SmartPropertyPrim.flagZOrderDirty);
  40434. }
  40435. var length = this._children.push(child);
  40436. this._firstZDirtyIndex = Math.min(this._firstZDirtyIndex, length - 1);
  40437. };
  40438. /**
  40439. * Dispose the primitive, remove it from its parent.
  40440. */
  40441. Prim2DBase.prototype.dispose = function () {
  40442. if (!_super.prototype.dispose.call(this)) {
  40443. return false;
  40444. }
  40445. if (this._actionManager) {
  40446. this._actionManager.dispose();
  40447. this._actionManager = null;
  40448. }
  40449. // If there's a parent, remove this object from its parent list
  40450. if (this._parent) {
  40451. var i = this._parent._children.indexOf(this);
  40452. if (i !== undefined) {
  40453. this._parent._children.splice(i, 1);
  40454. }
  40455. this._parent = null;
  40456. }
  40457. // Recurse dispose to children
  40458. if (this._children) {
  40459. while (this._children.length > 0) {
  40460. this._children[this._children.length - 1].dispose();
  40461. }
  40462. }
  40463. return true;
  40464. };
  40465. Prim2DBase.prototype.onPrimBecomesDirty = function () {
  40466. if (this._renderGroup && !this._isFlagSet(BABYLON.SmartPropertyPrim.flagPrimInDirtyList)) {
  40467. this._renderGroup._addPrimToDirtyList(this);
  40468. this._setFlags(BABYLON.SmartPropertyPrim.flagPrimInDirtyList);
  40469. }
  40470. };
  40471. Prim2DBase.prototype._needPrepare = function () {
  40472. return this._areSomeFlagsSet(BABYLON.SmartPropertyPrim.flagVisibilityChanged | BABYLON.SmartPropertyPrim.flagModelDirty) || (this._instanceDirtyFlags !== 0) || (this._globalTransformProcessStep !== this._globalTransformStep);
  40473. };
  40474. Prim2DBase.prototype._prepareRender = function (context) {
  40475. this._prepareRenderPre(context);
  40476. this._prepareRenderPost(context);
  40477. };
  40478. Prim2DBase.prototype._prepareRenderPre = function (context) {
  40479. };
  40480. Prim2DBase.prototype._prepareRenderPost = function (context) {
  40481. // Don't recurse if it's a renderable group, the content will be processed by the group itself
  40482. if (this instanceof BABYLON.Group2D) {
  40483. var self = this;
  40484. if (self.isRenderableGroup) {
  40485. return;
  40486. }
  40487. }
  40488. // Check if we need to recurse the prepare to children primitives
  40489. // - must have children
  40490. // - the global transform of this level have changed, or
  40491. // - the visible state of primitive has changed
  40492. if (this._children.length > 0 && ((this._globalTransformProcessStep !== this._globalTransformStep) ||
  40493. this.checkPropertiesDirty(Prim2DBase.isVisibleProperty.flagId))) {
  40494. this._children.forEach(function (c) {
  40495. // As usual stop the recursion if we meet a renderable group
  40496. if (!(c instanceof BABYLON.Group2D && c.isRenderableGroup)) {
  40497. c._prepareRender(context);
  40498. }
  40499. });
  40500. }
  40501. // Finally reset the dirty flags as we've processed everything
  40502. this._clearFlags(BABYLON.SmartPropertyPrim.flagModelDirty);
  40503. this._instanceDirtyFlags = 0;
  40504. };
  40505. Prim2DBase.prototype._canvasPreInit = function (settings) {
  40506. };
  40507. Prim2DBase.CheckParent = function (parent) {
  40508. //if (!Prim2DBase._isCanvasInit && !parent) {
  40509. // 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)");
  40510. //}
  40511. };
  40512. Prim2DBase.prototype.updateCachedStatesOf = function (list, recurse) {
  40513. for (var _i = 0, list_1 = list; _i < list_1.length; _i++) {
  40514. var cur = list_1[_i];
  40515. cur.updateCachedStates(recurse);
  40516. }
  40517. };
  40518. Prim2DBase.prototype._parentLayoutDirty = function () {
  40519. if (!this._parent || this._parent.isDisposed) {
  40520. return;
  40521. }
  40522. this._parent._setLayoutDirty();
  40523. };
  40524. Prim2DBase.prototype._setLayoutDirty = function () {
  40525. this.onPrimBecomesDirty();
  40526. this._setFlags(BABYLON.SmartPropertyPrim.flagLayoutDirty);
  40527. };
  40528. Prim2DBase.prototype._checkPositionChange = function () {
  40529. if (this.parent && this.parent.layoutEngine.isChildPositionAllowed === false) {
  40530. console.log("Can't manually set the position of " + this.id + ", the Layout Engine of its parent doesn't allow it");
  40531. return false;
  40532. }
  40533. return true;
  40534. };
  40535. Prim2DBase.prototype._positioningDirty = function () {
  40536. this.onPrimBecomesDirty();
  40537. this._setFlags(BABYLON.SmartPropertyPrim.flagPositioningDirty);
  40538. };
  40539. Prim2DBase.prototype._spreadActualOpacityChanged = function () {
  40540. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  40541. var child = _a[_i];
  40542. child._setFlags(BABYLON.SmartPropertyPrim.flagActualOpacityDirty);
  40543. child._spreadActualOpacityChanged();
  40544. }
  40545. };
  40546. Prim2DBase.prototype._changeLayoutEngine = function (engine) {
  40547. this._layoutEngine = engine;
  40548. };
  40549. Prim2DBase.prototype._updateLocalTransform = function () {
  40550. var tflags = Prim2DBase.actualPositionProperty.flagId | Prim2DBase.rotationProperty.flagId | Prim2DBase.scaleProperty.flagId | Prim2DBase.originProperty.flagId;
  40551. if (this.checkPropertiesDirty(tflags)) {
  40552. if (this.owner) {
  40553. this.owner.addupdateLocalTransformCounter(1);
  40554. }
  40555. var rot = BABYLON.Quaternion.RotationAxis(new BABYLON.Vector3(0, 0, 1), this._rotation);
  40556. var local;
  40557. var pos = this.position;
  40558. if (this._origin.x === 0 && this._origin.y === 0) {
  40559. local = BABYLON.Matrix.Compose(new BABYLON.Vector3(this._scale, this._scale, 1), rot, new BABYLON.Vector3(pos.x, pos.y, 0));
  40560. this._localTransform = local;
  40561. }
  40562. else {
  40563. // -Origin offset
  40564. var as = this.actualSize;
  40565. BABYLON.Matrix.TranslationToRef((-as.width * this._origin.x), (-as.height * this._origin.y), 0, Prim2DBase._t0);
  40566. // -Origin * rotation
  40567. rot.toRotationMatrix(Prim2DBase._t1);
  40568. Prim2DBase._t0.multiplyToRef(Prim2DBase._t1, Prim2DBase._t2);
  40569. // -Origin * rotation * scale
  40570. BABYLON.Matrix.ScalingToRef(this._scale, this._scale, 1, Prim2DBase._t0);
  40571. Prim2DBase._t2.multiplyToRef(Prim2DBase._t0, Prim2DBase._t1);
  40572. // -Origin * rotation * scale * (Origin + Position)
  40573. BABYLON.Matrix.TranslationToRef((as.width * this._origin.x) + pos.x, (as.height * this._origin.y) + pos.y, 0, Prim2DBase._t2);
  40574. Prim2DBase._t1.multiplyToRef(Prim2DBase._t2, this._localTransform);
  40575. }
  40576. this.clearPropertiesDirty(tflags);
  40577. return true;
  40578. }
  40579. return false;
  40580. };
  40581. Prim2DBase.prototype.updateCachedStates = function (recurse) {
  40582. if (this.isDisposed) {
  40583. return;
  40584. }
  40585. this.owner.addCachedGroupRenderCounter(1);
  40586. // Check if the parent is synced
  40587. if (this._parent && ((this._parent._globalTransformProcessStep !== this.owner._globalTransformProcessStep) || this._parent._areSomeFlagsSet(BABYLON.SmartPropertyPrim.flagLayoutDirty | BABYLON.SmartPropertyPrim.flagPositioningDirty | BABYLON.SmartPropertyPrim.flagZOrderDirty))) {
  40588. this._parent.updateCachedStates(false);
  40589. }
  40590. // Update Z-Order if needed
  40591. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagZOrderDirty)) {
  40592. this._updateZOrder();
  40593. }
  40594. // Update actualSize only if there' not positioning to recompute and the size changed
  40595. // Otherwise positioning will take care of it.
  40596. var sizeDirty = this.checkPropertiesDirty(Prim2DBase.sizeProperty.flagId);
  40597. if (!this._isFlagSet(BABYLON.SmartPropertyPrim.flagLayoutDirty) && !this._isFlagSet(BABYLON.SmartPropertyPrim.flagPositioningDirty) && sizeDirty) {
  40598. var size = this.size;
  40599. if (size) {
  40600. if (this.size.width != null) {
  40601. this.actualSize.width = this.size.width;
  40602. }
  40603. if (this.size.height != null) {
  40604. this.actualSize.height = this.size.height;
  40605. }
  40606. this.clearPropertiesDirty(Prim2DBase.sizeProperty.flagId);
  40607. }
  40608. }
  40609. // Check for layout update
  40610. var positioningDirty = this._isFlagSet(BABYLON.SmartPropertyPrim.flagPositioningDirty);
  40611. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagLayoutDirty)) {
  40612. this.owner.addUpdateLayoutCounter(1);
  40613. this._layoutEngine.updateLayout(this);
  40614. this._clearFlags(BABYLON.SmartPropertyPrim.flagLayoutDirty);
  40615. }
  40616. var positioningComputed = positioningDirty && !this._isFlagSet(BABYLON.SmartPropertyPrim.flagPositioningDirty);
  40617. var autoContentChanged = false;
  40618. if (this.isSizeAuto) {
  40619. if (!this._lastAutoSizeArea) {
  40620. autoContentChanged = this.size !== null;
  40621. }
  40622. else {
  40623. autoContentChanged = (!this._lastAutoSizeArea.equals(this.size));
  40624. }
  40625. }
  40626. // Check for positioning update
  40627. if (!positioningComputed && (autoContentChanged || sizeDirty || this._isFlagSet(BABYLON.SmartPropertyPrim.flagPositioningDirty) || (this._parent && !this._parent.contentArea.equals(this._parentContentArea)))) {
  40628. this._updatePositioning();
  40629. this._clearFlags(BABYLON.SmartPropertyPrim.flagPositioningDirty);
  40630. if (sizeDirty) {
  40631. this.clearPropertiesDirty(Prim2DBase.sizeProperty.flagId);
  40632. }
  40633. positioningComputed = true;
  40634. }
  40635. if (positioningComputed && this._parent) {
  40636. this._parentContentArea.copyFrom(this._parent.contentArea);
  40637. }
  40638. // Check if we must update this prim
  40639. if (this === this.owner || this._globalTransformProcessStep !== this.owner._globalTransformProcessStep) {
  40640. this.owner.addUpdateGlobalTransformCounter(1);
  40641. var curVisibleState = this.isVisible;
  40642. this.isVisible = (!this._parent || this._parent.isVisible) && this.levelVisible;
  40643. // Detect a change of visibility
  40644. this._changeFlags(BABYLON.SmartPropertyPrim.flagVisibilityChanged, curVisibleState !== this.isVisible);
  40645. // Get/compute the localTransform
  40646. var localDirty = this._updateLocalTransform();
  40647. var parentPaddingChanged = false;
  40648. var parentPaddingOffset = Prim2DBase._v0;
  40649. if (this._parent) {
  40650. parentPaddingOffset = this._parent._paddingOffset;
  40651. parentPaddingChanged = !parentPaddingOffset.equals(this._parentPaddingOffset);
  40652. }
  40653. // Check if there are changes in the parent that will force us to update the global matrix
  40654. var parentDirty = (this._parent != null) ? (this._parent._globalTransformStep !== this._parentTransformStep) : false;
  40655. // Check if we have to update the globalTransform
  40656. if (!this._globalTransform || localDirty || parentDirty || parentPaddingChanged) {
  40657. var globalTransform = this._parent ? this._parent._globalTransform : null;
  40658. var localTransform = void 0;
  40659. Prim2DBase._transMtx.copyFrom(this._localTransform);
  40660. Prim2DBase._transMtx.m[12] += this._layoutAreaPos.x + this._marginOffset.x + parentPaddingOffset.x;
  40661. Prim2DBase._transMtx.m[13] += this._layoutAreaPos.y + this._marginOffset.y + parentPaddingOffset.y;
  40662. localTransform = Prim2DBase._transMtx;
  40663. this._globalTransform = this._parent ? localTransform.multiply(globalTransform) : localTransform.clone();
  40664. this._invGlobalTransform = BABYLON.Matrix.Invert(this._globalTransform);
  40665. this._globalTransformStep = this.owner._globalTransformProcessStep + 1;
  40666. this._parentTransformStep = this._parent ? this._parent._globalTransformStep : 0;
  40667. }
  40668. this._globalTransformProcessStep = this.owner._globalTransformProcessStep;
  40669. }
  40670. if (recurse) {
  40671. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  40672. var child = _a[_i];
  40673. // Stop the recursion if we meet a renderable group
  40674. child.updateCachedStates(!(child instanceof BABYLON.Group2D && child.isRenderableGroup));
  40675. }
  40676. }
  40677. };
  40678. Prim2DBase.prototype._updatePositioning = function () {
  40679. if (this.owner) {
  40680. this.owner.addUpdatePositioningCounter(1);
  40681. }
  40682. // From this point we assume that the primitive layoutArea is computed and up to date.
  40683. // We know have to :
  40684. // 1. Determine the PaddingArea and the ActualPosition based on the margin/marginAlignment properties, which will also set the size property of the primitive
  40685. // 2. Determine the contentArea based on the padding property.
  40686. // 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
  40687. if (!this._hasMargin && (this.actualSize.width == null || this.actualSize.height == null)) {
  40688. if (this.actualSize.width == null) {
  40689. this.marginAlignment.horizontal = PrimitiveAlignment.AlignStretch;
  40690. }
  40691. if (this.actualSize.height == null) {
  40692. this.marginAlignment.vertical = PrimitiveAlignment.AlignStretch;
  40693. }
  40694. }
  40695. // Apply margin
  40696. if (this._hasMargin) {
  40697. this.margin.computeWithAlignment(this.layoutArea, this.size, this.marginAlignment, this._marginOffset, Prim2DBase._size);
  40698. this.actualSize = Prim2DBase._size.clone();
  40699. }
  40700. var isSizeAuto = this.isSizeAuto;
  40701. if (this._hasPadding) {
  40702. // Two cases from here: the size of the Primitive is Auto, its content can't be shrink, so me resize the primitive itself
  40703. if (isSizeAuto) {
  40704. var content = this.size.clone();
  40705. this._getActualSizeFromContentToRef(content, Prim2DBase._icArea);
  40706. this.padding.enlarge(Prim2DBase._icArea, this._paddingOffset, Prim2DBase._size);
  40707. this._contentArea.copyFrom(content);
  40708. this.actualSize = Prim2DBase._size.clone();
  40709. // Changing the padding has resize the prim, which forces us to recompute margin again
  40710. if (this._hasMargin) {
  40711. this.margin.computeWithAlignment(this.layoutArea, Prim2DBase._size, this.marginAlignment, this._marginOffset, Prim2DBase._size);
  40712. }
  40713. }
  40714. else {
  40715. this._getInitialContentAreaToRef(this.actualSize, Prim2DBase._icPos, Prim2DBase._icArea);
  40716. Prim2DBase._icArea.width = Math.max(0, Prim2DBase._icArea.width);
  40717. Prim2DBase._icArea.height = Math.max(0, Prim2DBase._icArea.height);
  40718. this.padding.compute(Prim2DBase._icArea, this._paddingOffset, Prim2DBase._size);
  40719. this._paddingOffset.x += Prim2DBase._icPos.x;
  40720. this._paddingOffset.y += Prim2DBase._icPos.y;
  40721. this._contentArea.copyFrom(Prim2DBase._size);
  40722. }
  40723. }
  40724. else {
  40725. this._getInitialContentAreaToRef(this.actualSize, Prim2DBase._icPos, Prim2DBase._icArea);
  40726. Prim2DBase._icArea.width = Math.max(0, Prim2DBase._icArea.width);
  40727. Prim2DBase._icArea.height = Math.max(0, Prim2DBase._icArea.height);
  40728. this._paddingOffset.copyFrom(Prim2DBase._icPos);
  40729. this._contentArea.copyFrom(Prim2DBase._icArea);
  40730. }
  40731. var aPos = new BABYLON.Vector2(this._layoutAreaPos.x + this._marginOffset.x, this._layoutAreaPos.y + this._marginOffset.y);
  40732. this.actualPosition = aPos;
  40733. if (isSizeAuto) {
  40734. this._lastAutoSizeArea = this.size;
  40735. }
  40736. };
  40737. Object.defineProperty(Prim2DBase.prototype, "contentArea", {
  40738. /**
  40739. * Get the content are of this primitive, this area is computed using the padding property and also possibly the primitive type itself.
  40740. * Children of this primitive will be positioned relative to the bottom/left corner of this area.
  40741. */
  40742. get: function () {
  40743. // Check for positioning update
  40744. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagPositioningDirty)) {
  40745. this._updatePositioning();
  40746. this._clearFlags(BABYLON.SmartPropertyPrim.flagPositioningDirty);
  40747. }
  40748. return this._contentArea;
  40749. },
  40750. enumerable: true,
  40751. configurable: true
  40752. });
  40753. Prim2DBase.prototype._patchHierarchy = function (owner) {
  40754. this._owner = owner;
  40755. // The only place we initialize the _renderGroup is this method, if it's set, we already been there, no need to execute more
  40756. if (this._renderGroup != null) {
  40757. return;
  40758. }
  40759. if (this instanceof BABYLON.Group2D) {
  40760. var group = this;
  40761. group.detectGroupStates();
  40762. if (group._trackedNode && !group._isFlagSet(BABYLON.SmartPropertyPrim.flagTrackedGroup)) {
  40763. group.owner._registerTrackedNode(this);
  40764. }
  40765. }
  40766. if (this._parent) {
  40767. this._renderGroup = this.parent.traverseUp(function (p) { return p instanceof BABYLON.Group2D && p.isRenderableGroup; });
  40768. this._parentLayoutDirty();
  40769. }
  40770. // Make sure the prim is in the dirtyList if it should be
  40771. if (this._renderGroup && this.isDirty) {
  40772. var list = this._renderGroup._renderableData._primDirtyList;
  40773. var i = list.indexOf(this);
  40774. if (i === -1) {
  40775. list.push(this);
  40776. }
  40777. }
  40778. // Recurse
  40779. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  40780. var child = _a[_i];
  40781. child._hierarchyDepth = this._hierarchyDepth + 1;
  40782. child._patchHierarchy(owner);
  40783. }
  40784. };
  40785. Prim2DBase.prototype._updateZOrder = function () {
  40786. var prevLinPos = this._primLinearPosition;
  40787. var startI = 0;
  40788. var startZ = this._zOrder;
  40789. // We must start rebuilding Z-Order from the Prim before the first one that changed, because we know its Z-Order is correct, so are its children, but it's better to recompute everything from this point instead of finding the last valid children
  40790. var childrenCount = this._children.length;
  40791. if (this._firstZDirtyIndex > 0) {
  40792. if ((this._firstZDirtyIndex - 1) < childrenCount) {
  40793. var prevPrim = this._children[this._firstZDirtyIndex - 1];
  40794. prevLinPos = prevPrim._primLinearPosition;
  40795. startI = this._firstZDirtyIndex - 1;
  40796. startZ = prevPrim._zOrder;
  40797. }
  40798. }
  40799. var startPos = prevLinPos;
  40800. // Update the linear position of the primitive from the first one to the last inside this primitive, compute the total number of prim traversed
  40801. Prim2DBase._totalCount = 0;
  40802. for (var i = startI; i < childrenCount; i++) {
  40803. var child = this._children[i];
  40804. prevLinPos = child._updatePrimitiveLinearPosition(prevLinPos);
  40805. }
  40806. // Compute the new Z-Order for all the primitives
  40807. // Add 20% to the current total count to reserve space for future insertions, except if we're rebuilding due to a zMinDelta reached
  40808. var zDelta = (this._zMax - startZ) / (Prim2DBase._totalCount * (Prim2DBase._zRebuildReentrency ? 1 : 1.2));
  40809. // If the computed delta is less than the smallest allowed by the depth buffer, we rebuild the Z-Order from the very beginning of the primitive's children (that is, the first) to redistribute uniformly the Z.
  40810. if (zDelta < BABYLON.Canvas2D._zMinDelta) {
  40811. // Check for re-entrance, if the flag is true we already attempted a rebuild but couldn't get a better zDelta, go up in the hierarchy to rebuilt one level up, hoping to get this time a decent delta, otherwise, recurse until we got it or when no parent is reached, which would mean the canvas would have more than 16 millions of primitives...
  40812. if (Prim2DBase._zRebuildReentrency) {
  40813. var p = this._parent;
  40814. if (p == null) {
  40815. // Can't find a good Z delta and we're in the canvas, which mean we're dealing with too many objects (which should never happen, but well...)
  40816. console.log("Can't compute Z-Order for " + this.id + "'s children, zDelta is too small, Z-Order is now in an unstable state");
  40817. Prim2DBase._zRebuildReentrency = false;
  40818. return;
  40819. }
  40820. p._firstZDirtyIndex = 0;
  40821. return p._updateZOrder();
  40822. }
  40823. Prim2DBase._zRebuildReentrency = true;
  40824. this._firstZDirtyIndex = 0;
  40825. this._updateZOrder();
  40826. Prim2DBase._zRebuildReentrency = false;
  40827. }
  40828. for (var i = startI; i < childrenCount; i++) {
  40829. var child = this._children[i];
  40830. child._updatePrimitiveZOrder(startPos, startZ, zDelta);
  40831. }
  40832. // Notify the Observers that we found during the Z change (we do it after to avoid any kind of re-entrance)
  40833. for (var _i = 0, _a = Prim2DBase._zOrderChangedNotifList; _i < _a.length; _i++) {
  40834. var p = _a[_i];
  40835. p._actualZOrderChangedObservable.notifyObservers(p.actualZOffset);
  40836. }
  40837. Prim2DBase._zOrderChangedNotifList.splice(0);
  40838. this._firstZDirtyIndex = Prim2DBase._bigInt;
  40839. this._clearFlags(BABYLON.SmartPropertyPrim.flagZOrderDirty);
  40840. };
  40841. Prim2DBase.prototype._updatePrimitiveLinearPosition = function (prevLinPos) {
  40842. if (this.isManualZOrder) {
  40843. return prevLinPos;
  40844. }
  40845. this._primLinearPosition = ++prevLinPos;
  40846. Prim2DBase._totalCount++;
  40847. // Check for the FlatZOrder, which means the children won't have a dedicated Z-Order but will all share the same (unique) one.
  40848. if (!this._isFlagSet(BABYLON.SmartPropertyPrim.flagChildrenFlatZOrder)) {
  40849. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  40850. var child = _a[_i];
  40851. prevLinPos = child._updatePrimitiveLinearPosition(prevLinPos);
  40852. }
  40853. }
  40854. return prevLinPos;
  40855. };
  40856. Prim2DBase.prototype._updatePrimitiveZOrder = function (startPos, startZ, deltaZ) {
  40857. if (this.isManualZOrder) {
  40858. return null;
  40859. }
  40860. var newZ = startZ + ((this._primLinearPosition - startPos) * deltaZ);
  40861. var isFlat = this._isFlagSet(BABYLON.SmartPropertyPrim.flagChildrenFlatZOrder);
  40862. this._setZOrder(newZ, false);
  40863. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagZOrderDirty)) {
  40864. this._firstZDirtyIndex = Prim2DBase._bigInt;
  40865. this._clearFlags(BABYLON.SmartPropertyPrim.flagZOrderDirty);
  40866. }
  40867. var curZ = newZ;
  40868. // Check for the FlatZOrder, which means the children won't have a dedicated Z-Order but will all share the same (unique) one.
  40869. if (isFlat) {
  40870. if (this._children.length > 0) {
  40871. //let childrenZOrder = startZ + ((this._children[0]._primLinearPosition - startPos) * deltaZ);
  40872. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  40873. var child = _a[_i];
  40874. child._updatePrimitiveFlatZOrder(this._zOrder);
  40875. }
  40876. }
  40877. }
  40878. else {
  40879. for (var _b = 0, _c = this._children; _b < _c.length; _b++) {
  40880. var child = _c[_b];
  40881. var r = child._updatePrimitiveZOrder(startPos, startZ, deltaZ);
  40882. if (r != null) {
  40883. curZ = r;
  40884. }
  40885. }
  40886. }
  40887. this._zMax = isFlat ? newZ : (curZ + deltaZ);
  40888. return curZ;
  40889. };
  40890. Prim2DBase.prototype._updatePrimitiveFlatZOrder = function (newZ) {
  40891. if (this.isManualZOrder) {
  40892. return;
  40893. }
  40894. this._setZOrder(newZ, false);
  40895. this._zMax = newZ;
  40896. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagZOrderDirty)) {
  40897. this._firstZDirtyIndex = Prim2DBase._bigInt;
  40898. this._clearFlags(BABYLON.SmartPropertyPrim.flagZOrderDirty);
  40899. }
  40900. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  40901. var child = _a[_i];
  40902. child._updatePrimitiveFlatZOrder(newZ);
  40903. }
  40904. };
  40905. Prim2DBase.prototype._setZOrder = function (newZ, directEmit) {
  40906. if (newZ !== this._zOrder) {
  40907. this._zOrder = newZ;
  40908. this.onPrimBecomesDirty();
  40909. this.onZOrderChanged();
  40910. if (this._actualZOrderChangedObservable && this._actualZOrderChangedObservable.hasObservers()) {
  40911. if (directEmit) {
  40912. this._actualZOrderChangedObservable.notifyObservers(newZ);
  40913. }
  40914. else {
  40915. Prim2DBase._zOrderChangedNotifList.push(this);
  40916. }
  40917. }
  40918. }
  40919. };
  40920. Prim2DBase.prototype._updateRenderMode = function () {
  40921. };
  40922. /**
  40923. * This method is used to alter the contentArea of the Primitive before margin is applied.
  40924. * 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.
  40925. * @param primSize the current size of the primitive
  40926. * @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!
  40927. * @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!
  40928. */
  40929. Prim2DBase.prototype._getInitialContentAreaToRef = function (primSize, initialContentPosition, initialContentArea) {
  40930. initialContentArea.copyFrom(primSize);
  40931. initialContentPosition.x = initialContentPosition.y = 0;
  40932. };
  40933. /**
  40934. * This method is used to calculate the new size of the primitive based on the content which must stay the same
  40935. * Check the Rectangle2D implementation for a concrete application.
  40936. * @param primSize the current size of the primitive
  40937. * @param newPrimSize the new size of the primitive. PLEASE ROUND THE values, we're talking about pixels and fraction of them are not our friends!
  40938. */
  40939. Prim2DBase.prototype._getActualSizeFromContentToRef = function (primSize, newPrimSize) {
  40940. newPrimSize.copyFrom(primSize);
  40941. };
  40942. Prim2DBase.PRIM2DBASE_PROPCOUNT = 15;
  40943. Prim2DBase._bigInt = Math.pow(2, 30);
  40944. Prim2DBase._nullPosition = BABYLON.Vector2.Zero();
  40945. Prim2DBase.boundinbBoxReentrency = false;
  40946. Prim2DBase.nullSize = BABYLON.Size.Zero();
  40947. Prim2DBase._bMax = BABYLON.Vector2.Zero();
  40948. Prim2DBase._isCanvasInit = false;
  40949. Prim2DBase._t0 = new BABYLON.Matrix();
  40950. Prim2DBase._t1 = new BABYLON.Matrix();
  40951. Prim2DBase._t2 = new BABYLON.Matrix();
  40952. Prim2DBase._v0 = BABYLON.Vector2.Zero(); // Must stay with the value 0,0
  40953. Prim2DBase._transMtx = BABYLON.Matrix.Zero();
  40954. Prim2DBase._icPos = BABYLON.Vector2.Zero();
  40955. Prim2DBase._icArea = BABYLON.Size.Zero();
  40956. Prim2DBase._size = BABYLON.Size.Zero();
  40957. Prim2DBase._zOrderChangedNotifList = new Array();
  40958. Prim2DBase._zRebuildReentrency = false;
  40959. Prim2DBase._totalCount = 0;
  40960. __decorate([
  40961. BABYLON.instanceLevelProperty(1, function (pi) { return Prim2DBase.actualPositionProperty = pi; }, false, false, true)
  40962. ], Prim2DBase.prototype, "actualPosition", null);
  40963. __decorate([
  40964. BABYLON.dynamicLevelProperty(2, function (pi) { return Prim2DBase.positionProperty = pi; }, false, false, true)
  40965. ], Prim2DBase.prototype, "position", null);
  40966. __decorate([
  40967. BABYLON.dynamicLevelProperty(3, function (pi) { return Prim2DBase.sizeProperty = pi; }, false, true)
  40968. ], Prim2DBase.prototype, "size", null);
  40969. __decorate([
  40970. BABYLON.instanceLevelProperty(4, function (pi) { return Prim2DBase.rotationProperty = pi; }, false, true)
  40971. ], Prim2DBase.prototype, "rotation", null);
  40972. __decorate([
  40973. BABYLON.instanceLevelProperty(5, function (pi) { return Prim2DBase.scaleProperty = pi; }, false, true)
  40974. ], Prim2DBase.prototype, "scale", null);
  40975. __decorate([
  40976. BABYLON.dynamicLevelProperty(6, function (pi) { return Prim2DBase.originProperty = pi; }, false, true)
  40977. ], Prim2DBase.prototype, "origin", null);
  40978. __decorate([
  40979. BABYLON.dynamicLevelProperty(7, function (pi) { return Prim2DBase.levelVisibleProperty = pi; })
  40980. ], Prim2DBase.prototype, "levelVisible", null);
  40981. __decorate([
  40982. BABYLON.instanceLevelProperty(8, function (pi) { return Prim2DBase.isVisibleProperty = pi; })
  40983. ], Prim2DBase.prototype, "isVisible", null);
  40984. __decorate([
  40985. BABYLON.instanceLevelProperty(9, function (pi) { return Prim2DBase.zOrderProperty = pi; })
  40986. ], Prim2DBase.prototype, "zOrder", null);
  40987. __decorate([
  40988. BABYLON.dynamicLevelProperty(10, function (pi) { return Prim2DBase.marginProperty = pi; })
  40989. ], Prim2DBase.prototype, "margin", null);
  40990. __decorate([
  40991. BABYLON.dynamicLevelProperty(11, function (pi) { return Prim2DBase.paddingProperty = pi; })
  40992. ], Prim2DBase.prototype, "padding", null);
  40993. __decorate([
  40994. BABYLON.dynamicLevelProperty(12, function (pi) { return Prim2DBase.marginAlignmentProperty = pi; })
  40995. ], Prim2DBase.prototype, "marginAlignment", null);
  40996. __decorate([
  40997. BABYLON.instanceLevelProperty(13, function (pi) { return Prim2DBase.opacityProperty = pi; })
  40998. ], Prim2DBase.prototype, "opacity", null);
  40999. Prim2DBase = __decorate([
  41000. BABYLON.className("Prim2DBase")
  41001. ], Prim2DBase);
  41002. return Prim2DBase;
  41003. }(BABYLON.SmartPropertyPrim));
  41004. BABYLON.Prim2DBase = Prim2DBase;
  41005. })(BABYLON || (BABYLON = {}));
  41006. var BABYLON;
  41007. (function (BABYLON) {
  41008. var GroupInstanceInfo = (function () {
  41009. function GroupInstanceInfo(owner, mrc, partCount) {
  41010. this._partCount = partCount;
  41011. this.owner = owner;
  41012. this.modelRenderCache = mrc;
  41013. this.modelRenderCache.addRef();
  41014. this.partIndexFromId = new BABYLON.StringDictionary();
  41015. this._usedShaderCategories = new Array(partCount);
  41016. this._strides = new Array(partCount);
  41017. this._opaqueData = null;
  41018. this._alphaTestData = null;
  41019. this._transparentData = null;
  41020. this.opaqueDirty = this.alphaTestDirty = this.transparentDirty = this.transparentOrderDirty = false;
  41021. }
  41022. GroupInstanceInfo.prototype.dispose = function () {
  41023. if (this._isDisposed) {
  41024. return false;
  41025. }
  41026. if (this.modelRenderCache) {
  41027. this.modelRenderCache.dispose();
  41028. }
  41029. var engine = this.owner.owner.engine;
  41030. if (this.opaqueData) {
  41031. this.opaqueData.forEach(function (d) { return d.dispose(engine); });
  41032. this.opaqueData = null;
  41033. }
  41034. this.partIndexFromId = null;
  41035. this._isDisposed = true;
  41036. return true;
  41037. };
  41038. Object.defineProperty(GroupInstanceInfo.prototype, "hasOpaqueData", {
  41039. get: function () {
  41040. return this._opaqueData != null;
  41041. },
  41042. enumerable: true,
  41043. configurable: true
  41044. });
  41045. Object.defineProperty(GroupInstanceInfo.prototype, "hasAlphaTestData", {
  41046. get: function () {
  41047. return this._alphaTestData != null;
  41048. },
  41049. enumerable: true,
  41050. configurable: true
  41051. });
  41052. Object.defineProperty(GroupInstanceInfo.prototype, "hasTransparentData", {
  41053. get: function () {
  41054. return this._transparentData != null;
  41055. },
  41056. enumerable: true,
  41057. configurable: true
  41058. });
  41059. Object.defineProperty(GroupInstanceInfo.prototype, "opaqueData", {
  41060. get: function () {
  41061. if (!this._opaqueData) {
  41062. this._opaqueData = new Array(this._partCount);
  41063. for (var i = 0; i < this._partCount; i++) {
  41064. this._opaqueData[i] = new GroupInfoPartData(this._strides[i]);
  41065. }
  41066. }
  41067. return this._opaqueData;
  41068. },
  41069. enumerable: true,
  41070. configurable: true
  41071. });
  41072. Object.defineProperty(GroupInstanceInfo.prototype, "alphaTestData", {
  41073. get: function () {
  41074. if (!this._alphaTestData) {
  41075. this._alphaTestData = new Array(this._partCount);
  41076. for (var i = 0; i < this._partCount; i++) {
  41077. this._alphaTestData[i] = new GroupInfoPartData(this._strides[i]);
  41078. }
  41079. }
  41080. return this._alphaTestData;
  41081. },
  41082. enumerable: true,
  41083. configurable: true
  41084. });
  41085. Object.defineProperty(GroupInstanceInfo.prototype, "transparentData", {
  41086. get: function () {
  41087. if (!this._transparentData) {
  41088. this._transparentData = new Array(this._partCount);
  41089. for (var i = 0; i < this._partCount; i++) {
  41090. var zoff = this.modelRenderCache._partData[i]._zBiasOffset;
  41091. this._transparentData[i] = new TransparentGroupInfoPartData(this._strides[i], zoff);
  41092. }
  41093. }
  41094. return this._transparentData;
  41095. },
  41096. enumerable: true,
  41097. configurable: true
  41098. });
  41099. GroupInstanceInfo.prototype.sortTransparentData = function () {
  41100. if (!this.transparentOrderDirty) {
  41101. return;
  41102. }
  41103. for (var i = 0; i < this._transparentData.length; i++) {
  41104. var td = this._transparentData[i];
  41105. td._partData.sort();
  41106. }
  41107. this.transparentOrderDirty = false;
  41108. };
  41109. Object.defineProperty(GroupInstanceInfo.prototype, "usedShaderCategories", {
  41110. get: function () {
  41111. return this._usedShaderCategories;
  41112. },
  41113. enumerable: true,
  41114. configurable: true
  41115. });
  41116. Object.defineProperty(GroupInstanceInfo.prototype, "strides", {
  41117. get: function () {
  41118. return this._strides;
  41119. },
  41120. enumerable: true,
  41121. configurable: true
  41122. });
  41123. return GroupInstanceInfo;
  41124. }());
  41125. BABYLON.GroupInstanceInfo = GroupInstanceInfo;
  41126. var TransparentSegment = (function () {
  41127. function TransparentSegment() {
  41128. this.groupInsanceInfo = null;
  41129. this.startZ = 0;
  41130. this.endZ = 0;
  41131. this.startDataIndex = 0;
  41132. this.endDataIndex = 0;
  41133. this.partBuffers = null;
  41134. }
  41135. TransparentSegment.prototype.dispose = function (engine) {
  41136. if (this.partBuffers) {
  41137. this.partBuffers.forEach(function (b) { return engine._releaseBuffer(b); });
  41138. this.partBuffers.splice(0);
  41139. this.partBuffers = null;
  41140. }
  41141. };
  41142. return TransparentSegment;
  41143. }());
  41144. BABYLON.TransparentSegment = TransparentSegment;
  41145. var GroupInfoPartData = (function () {
  41146. function GroupInfoPartData(stride) {
  41147. this._partData = null;
  41148. this._partBuffer = null;
  41149. this._partBufferSize = 0;
  41150. this._partData = new BABYLON.DynamicFloatArray(stride / 4, 50);
  41151. this._isDisposed = false;
  41152. }
  41153. GroupInfoPartData.prototype.dispose = function (engine) {
  41154. if (this._isDisposed) {
  41155. return false;
  41156. }
  41157. if (this._partBuffer) {
  41158. engine._releaseBuffer(this._partBuffer);
  41159. this._partBuffer = null;
  41160. }
  41161. this._partData = null;
  41162. this._isDisposed = true;
  41163. };
  41164. return GroupInfoPartData;
  41165. }());
  41166. BABYLON.GroupInfoPartData = GroupInfoPartData;
  41167. var TransparentGroupInfoPartData = (function (_super) {
  41168. __extends(TransparentGroupInfoPartData, _super);
  41169. function TransparentGroupInfoPartData(stride, zoff) {
  41170. _super.call(this, stride);
  41171. this._partData.compareValueOffset = zoff;
  41172. this._partData.sortingAscending = false;
  41173. }
  41174. return TransparentGroupInfoPartData;
  41175. }(GroupInfoPartData));
  41176. BABYLON.TransparentGroupInfoPartData = TransparentGroupInfoPartData;
  41177. var ModelRenderCache = (function () {
  41178. function ModelRenderCache(engine, modelKey) {
  41179. this._engine = engine;
  41180. this._modelKey = modelKey;
  41181. this._nextKey = 1;
  41182. this._refCounter = 1;
  41183. this._instancesData = new BABYLON.StringDictionary();
  41184. this._partData = null;
  41185. }
  41186. ModelRenderCache.prototype.dispose = function () {
  41187. if (--this._refCounter !== 0) {
  41188. return false;
  41189. }
  41190. // Remove the Model Render Cache from the global dictionary
  41191. var edata = this._engine.getExternalData("__BJSCANVAS2D__");
  41192. if (edata) {
  41193. edata.DisposeModelRenderCache(this);
  41194. }
  41195. return true;
  41196. };
  41197. Object.defineProperty(ModelRenderCache.prototype, "isDisposed", {
  41198. get: function () {
  41199. return this._refCounter <= 0;
  41200. },
  41201. enumerable: true,
  41202. configurable: true
  41203. });
  41204. ModelRenderCache.prototype.addRef = function () {
  41205. return ++this._refCounter;
  41206. };
  41207. Object.defineProperty(ModelRenderCache.prototype, "modelKey", {
  41208. get: function () {
  41209. return this._modelKey;
  41210. },
  41211. enumerable: true,
  41212. configurable: true
  41213. });
  41214. /**
  41215. * Render the model instances
  41216. * @param instanceInfo
  41217. * @param context
  41218. * @return must return true is the rendering succeed, false if the rendering couldn't be done (asset's not yet ready, like Effect)
  41219. */
  41220. ModelRenderCache.prototype.render = function (instanceInfo, context) {
  41221. return true;
  41222. };
  41223. ModelRenderCache.prototype.addInstanceDataParts = function (data) {
  41224. var key = this._nextKey.toString();
  41225. if (!this._instancesData.add(key, data)) {
  41226. throw Error("Key: " + key + " is already allocated");
  41227. }
  41228. ++this._nextKey;
  41229. return key;
  41230. };
  41231. ModelRenderCache.prototype.removeInstanceData = function (key) {
  41232. this._instancesData.remove(key);
  41233. };
  41234. ModelRenderCache.prototype.getPartIndexFromId = function (partId) {
  41235. for (var i = 0; i < this._partData.length; i++) {
  41236. if (this._partData[i]._partId === partId) {
  41237. return i;
  41238. }
  41239. }
  41240. return null;
  41241. };
  41242. ModelRenderCache.prototype.loadInstancingAttributes = function (partId, effect) {
  41243. var i = this.getPartIndexFromId(partId);
  41244. if (i === null) {
  41245. return null;
  41246. }
  41247. var ci = this._partsClassInfo[i];
  41248. var categories = this._partData[i]._partUsedCategories;
  41249. var res = ci.classContent.getInstancingAttributeInfos(effect, categories);
  41250. return res;
  41251. };
  41252. ModelRenderCache.prototype.setupUniforms = function (effect, partIndex, data, elementCount) {
  41253. var pd = this._partData[partIndex];
  41254. var offset = (pd._partDataStride / 4) * elementCount;
  41255. var pci = this._partsClassInfo[partIndex];
  41256. var self = this;
  41257. pci.fullContent.forEach(function (k, v) {
  41258. if (!v.category || pd._partUsedCategories.indexOf(v.category) !== -1) {
  41259. switch (v.dataType) {
  41260. case 4 /* float */:
  41261. {
  41262. var attribOffset = v.instanceOffset.get(pd._partJoinedUsedCategories);
  41263. effect.setFloat(v.attributeName, data.buffer[offset + attribOffset]);
  41264. break;
  41265. }
  41266. case 0 /* Vector2 */:
  41267. {
  41268. var attribOffset = v.instanceOffset.get(pd._partJoinedUsedCategories);
  41269. ModelRenderCache.v2.x = data.buffer[offset + attribOffset + 0];
  41270. ModelRenderCache.v2.y = data.buffer[offset + attribOffset + 1];
  41271. effect.setVector2(v.attributeName, ModelRenderCache.v2);
  41272. break;
  41273. }
  41274. case 5 /* Color3 */:
  41275. case 1 /* Vector3 */:
  41276. {
  41277. var attribOffset = v.instanceOffset.get(pd._partJoinedUsedCategories);
  41278. ModelRenderCache.v3.x = data.buffer[offset + attribOffset + 0];
  41279. ModelRenderCache.v3.y = data.buffer[offset + attribOffset + 1];
  41280. ModelRenderCache.v3.z = data.buffer[offset + attribOffset + 2];
  41281. effect.setVector3(v.attributeName, ModelRenderCache.v3);
  41282. break;
  41283. }
  41284. case 6 /* Color4 */:
  41285. case 2 /* Vector4 */:
  41286. {
  41287. var attribOffset = v.instanceOffset.get(pd._partJoinedUsedCategories);
  41288. ModelRenderCache.v4.x = data.buffer[offset + attribOffset + 0];
  41289. ModelRenderCache.v4.y = data.buffer[offset + attribOffset + 1];
  41290. ModelRenderCache.v4.z = data.buffer[offset + attribOffset + 2];
  41291. ModelRenderCache.v4.w = data.buffer[offset + attribOffset + 3];
  41292. effect.setVector4(v.attributeName, ModelRenderCache.v4);
  41293. break;
  41294. }
  41295. default:
  41296. }
  41297. }
  41298. });
  41299. };
  41300. //setupUniformsLocation(effect: Effect, uniforms: string[], partId: number) {
  41301. // let i = this.getPartIndexFromId(partId);
  41302. // if (i === null) {
  41303. // return null;
  41304. // }
  41305. // let pci = this._partsClassInfo[i];
  41306. // pci.fullContent.forEach((k, v) => {
  41307. // if (uniforms.indexOf(v.attributeName) !== -1) {
  41308. // v.uniformLocation = effect.getUniform(v.attributeName);
  41309. // }
  41310. // });
  41311. //}
  41312. ModelRenderCache.v2 = BABYLON.Vector2.Zero();
  41313. ModelRenderCache.v3 = BABYLON.Vector3.Zero();
  41314. ModelRenderCache.v4 = BABYLON.Vector4.Zero();
  41315. return ModelRenderCache;
  41316. }());
  41317. BABYLON.ModelRenderCache = ModelRenderCache;
  41318. var ModelRenderCachePartData = (function () {
  41319. function ModelRenderCachePartData() {
  41320. }
  41321. return ModelRenderCachePartData;
  41322. }());
  41323. BABYLON.ModelRenderCachePartData = ModelRenderCachePartData;
  41324. })(BABYLON || (BABYLON = {}));
  41325. var BABYLON;
  41326. (function (BABYLON) {
  41327. var InstanceClassInfo = (function () {
  41328. function InstanceClassInfo(base) {
  41329. this._baseInfo = base;
  41330. this._nextOffset = new BABYLON.StringDictionary();
  41331. this._attributes = new Array();
  41332. }
  41333. InstanceClassInfo.prototype.mapProperty = function (propInfo, push) {
  41334. var curOff = this._nextOffset.getOrAdd(InstanceClassInfo._CurCategories, 0);
  41335. propInfo.instanceOffset.add(InstanceClassInfo._CurCategories, this._getBaseOffset(InstanceClassInfo._CurCategories) + curOff);
  41336. //console.log(`[${InstanceClassInfo._CurCategories}] New PropInfo. Category: ${propInfo.category}, Name: ${propInfo.attributeName}, Offset: ${propInfo.instanceOffset.get(InstanceClassInfo._CurCategories)}, Size: ${propInfo.size / 4}`);
  41337. this._nextOffset.set(InstanceClassInfo._CurCategories, curOff + (propInfo.size / 4));
  41338. if (push) {
  41339. this._attributes.push(propInfo);
  41340. }
  41341. };
  41342. InstanceClassInfo.prototype.getInstancingAttributeInfos = function (effect, categories) {
  41343. var catInline = ";" + categories.join(";") + ";";
  41344. var res = new Array();
  41345. var curInfo = this;
  41346. while (curInfo) {
  41347. for (var _i = 0, _a = curInfo._attributes; _i < _a.length; _i++) {
  41348. var attrib = _a[_i];
  41349. // 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
  41350. if (!attrib.category || categories.indexOf(attrib.category) !== -1) {
  41351. var index = effect.getAttributeLocationByName(attrib.attributeName);
  41352. var iai = new BABYLON.InstancingAttributeInfo();
  41353. iai.index = index;
  41354. 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)
  41355. iai.offset = attrib.instanceOffset.get(catInline) * 4; // attrib.instanceOffset is in float, iai.offset must be in bytes
  41356. iai.attributeName = attrib.attributeName;
  41357. res.push(iai);
  41358. }
  41359. }
  41360. curInfo = curInfo._baseInfo;
  41361. }
  41362. return res;
  41363. };
  41364. InstanceClassInfo.prototype.getShaderAttributes = function (categories) {
  41365. var res = new Array();
  41366. var curInfo = this;
  41367. while (curInfo) {
  41368. for (var _i = 0, _a = curInfo._attributes; _i < _a.length; _i++) {
  41369. var attrib = _a[_i];
  41370. // 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
  41371. if (!attrib.category || categories.indexOf(attrib.category) !== -1) {
  41372. res.push(attrib.attributeName);
  41373. }
  41374. }
  41375. curInfo = curInfo._baseInfo;
  41376. }
  41377. return res;
  41378. };
  41379. InstanceClassInfo.prototype._getBaseOffset = function (categories) {
  41380. var curOffset = 0;
  41381. var curBase = this._baseInfo;
  41382. while (curBase) {
  41383. curOffset += curBase._nextOffset.getOrAdd(categories, 0);
  41384. curBase = curBase._baseInfo;
  41385. }
  41386. return curOffset;
  41387. };
  41388. return InstanceClassInfo;
  41389. }());
  41390. BABYLON.InstanceClassInfo = InstanceClassInfo;
  41391. var InstancePropInfo = (function () {
  41392. function InstancePropInfo() {
  41393. this.instanceOffset = new BABYLON.StringDictionary();
  41394. }
  41395. InstancePropInfo.prototype.setSize = function (val) {
  41396. if (val instanceof BABYLON.Vector2) {
  41397. this.size = 8;
  41398. this.dataType = 0 /* Vector2 */;
  41399. return;
  41400. }
  41401. if (val instanceof BABYLON.Vector3) {
  41402. this.size = 12;
  41403. this.dataType = 1 /* Vector3 */;
  41404. return;
  41405. }
  41406. if (val instanceof BABYLON.Vector4) {
  41407. this.size = 16;
  41408. this.dataType = 2 /* Vector4 */;
  41409. return;
  41410. }
  41411. if (val instanceof BABYLON.Matrix) {
  41412. throw new Error("Matrix type is not supported by WebGL Instance Buffer, you have to use four Vector4 properties instead");
  41413. }
  41414. if (typeof (val) === "number") {
  41415. this.size = 4;
  41416. this.dataType = 4 /* float */;
  41417. return;
  41418. }
  41419. if (val instanceof BABYLON.Color3) {
  41420. this.size = 12;
  41421. this.dataType = 5 /* Color3 */;
  41422. return;
  41423. }
  41424. if (val instanceof BABYLON.Color4) {
  41425. this.size = 16;
  41426. this.dataType = 6 /* Color4 */;
  41427. return;
  41428. }
  41429. if (val instanceof BABYLON.Size) {
  41430. this.size = 8;
  41431. this.dataType = 7 /* Size */;
  41432. return;
  41433. }
  41434. return;
  41435. };
  41436. InstancePropInfo.prototype.writeData = function (array, offset, val) {
  41437. switch (this.dataType) {
  41438. case 0 /* Vector2 */:
  41439. {
  41440. var v = val;
  41441. array[offset + 0] = v.x;
  41442. array[offset + 1] = v.y;
  41443. break;
  41444. }
  41445. case 1 /* Vector3 */:
  41446. {
  41447. var v = val;
  41448. array[offset + 0] = v.x;
  41449. array[offset + 1] = v.y;
  41450. array[offset + 2] = v.z;
  41451. break;
  41452. }
  41453. case 2 /* Vector4 */:
  41454. {
  41455. var v = val;
  41456. array[offset + 0] = v.x;
  41457. array[offset + 1] = v.y;
  41458. array[offset + 2] = v.z;
  41459. array[offset + 3] = v.w;
  41460. break;
  41461. }
  41462. case 5 /* Color3 */:
  41463. {
  41464. var v = val;
  41465. array[offset + 0] = v.r;
  41466. array[offset + 1] = v.g;
  41467. array[offset + 2] = v.b;
  41468. break;
  41469. }
  41470. case 6 /* Color4 */:
  41471. {
  41472. var v = val;
  41473. array[offset + 0] = v.r;
  41474. array[offset + 1] = v.g;
  41475. array[offset + 2] = v.b;
  41476. array[offset + 3] = v.a;
  41477. break;
  41478. }
  41479. case 4 /* float */:
  41480. {
  41481. var v = val;
  41482. array[offset] = v;
  41483. break;
  41484. }
  41485. case 3 /* Matrix */:
  41486. {
  41487. var v = val;
  41488. for (var i = 0; i < 16; i++) {
  41489. array[offset + i] = v.m[i];
  41490. }
  41491. break;
  41492. }
  41493. case 7 /* Size */:
  41494. {
  41495. var s = val;
  41496. array[offset + 0] = s.width;
  41497. array[offset + 1] = s.height;
  41498. break;
  41499. }
  41500. }
  41501. };
  41502. return InstancePropInfo;
  41503. }());
  41504. BABYLON.InstancePropInfo = InstancePropInfo;
  41505. function instanceData(category, shaderAttributeName) {
  41506. return function (target, propName, descriptor) {
  41507. var dic = BABYLON.ClassTreeInfo.getOrRegister(target, function (base) { return new InstanceClassInfo(base); });
  41508. var node = dic.getLevelOf(target);
  41509. var instanceDataName = propName;
  41510. shaderAttributeName = shaderAttributeName || instanceDataName;
  41511. var info = node.levelContent.get(instanceDataName);
  41512. if (info) {
  41513. throw new Error("The ID " + instanceDataName + " is already taken by another instance data");
  41514. }
  41515. info = new InstancePropInfo();
  41516. info.attributeName = shaderAttributeName;
  41517. info.category = category || null;
  41518. if (info.category) {
  41519. info.delimitedCategory = ";" + info.category + ";";
  41520. }
  41521. node.levelContent.add(instanceDataName, info);
  41522. descriptor.get = function () {
  41523. return null;
  41524. };
  41525. descriptor.set = function (val) {
  41526. // Check that we're not trying to set a property that belongs to a category that is not allowed (current)
  41527. // Quit if it's the case, otherwise we could overwrite data somewhere...
  41528. if (info.category && InstanceClassInfo._CurCategories.indexOf(info.delimitedCategory) === -1) {
  41529. return;
  41530. }
  41531. if (!info.size) {
  41532. info.setSize(val);
  41533. node.classContent.mapProperty(info, true);
  41534. }
  41535. else if (!info.instanceOffset.contains(InstanceClassInfo._CurCategories)) {
  41536. node.classContent.mapProperty(info, false);
  41537. }
  41538. var obj = this;
  41539. if (obj.dataBuffer && obj.dataElements) {
  41540. var offset = obj.dataElements[obj.curElement].offset + info.instanceOffset.get(InstanceClassInfo._CurCategories);
  41541. info.writeData(obj.dataBuffer.buffer, offset, val);
  41542. }
  41543. };
  41544. };
  41545. }
  41546. BABYLON.instanceData = instanceData;
  41547. var InstanceDataBase = (function () {
  41548. function InstanceDataBase(partId, dataElementCount) {
  41549. this.id = partId;
  41550. this.curElement = 0;
  41551. this.dataElementCount = dataElementCount;
  41552. this.renderMode = 0;
  41553. this.arrayLengthChanged = false;
  41554. }
  41555. Object.defineProperty(InstanceDataBase.prototype, "zBias", {
  41556. get: function () {
  41557. return null;
  41558. },
  41559. enumerable: true,
  41560. configurable: true
  41561. });
  41562. Object.defineProperty(InstanceDataBase.prototype, "transformX", {
  41563. get: function () {
  41564. return null;
  41565. },
  41566. enumerable: true,
  41567. configurable: true
  41568. });
  41569. Object.defineProperty(InstanceDataBase.prototype, "transformY", {
  41570. get: function () {
  41571. return null;
  41572. },
  41573. enumerable: true,
  41574. configurable: true
  41575. });
  41576. Object.defineProperty(InstanceDataBase.prototype, "opacity", {
  41577. get: function () {
  41578. return null;
  41579. },
  41580. enumerable: true,
  41581. configurable: true
  41582. });
  41583. InstanceDataBase.prototype.getClassTreeInfo = function () {
  41584. if (!this.typeInfo) {
  41585. this.typeInfo = BABYLON.ClassTreeInfo.get(Object.getPrototypeOf(this));
  41586. }
  41587. return this.typeInfo;
  41588. };
  41589. InstanceDataBase.prototype.allocElements = function () {
  41590. if (!this.dataBuffer || this.dataElements) {
  41591. return;
  41592. }
  41593. var res = new Array(this.dataElementCount);
  41594. for (var i = 0; i < this.dataElementCount; i++) {
  41595. res[i] = this.dataBuffer.allocElement();
  41596. }
  41597. this.dataElements = res;
  41598. };
  41599. InstanceDataBase.prototype.freeElements = function () {
  41600. if (!this.dataElements) {
  41601. return;
  41602. }
  41603. for (var _i = 0, _a = this.dataElements; _i < _a.length; _i++) {
  41604. var ei = _a[_i];
  41605. this.dataBuffer.freeElement(ei);
  41606. }
  41607. this.dataElements = null;
  41608. };
  41609. Object.defineProperty(InstanceDataBase.prototype, "dataElementCount", {
  41610. get: function () {
  41611. return this._dataElementCount;
  41612. },
  41613. set: function (value) {
  41614. if (value === this._dataElementCount) {
  41615. return;
  41616. }
  41617. this.arrayLengthChanged = true;
  41618. this.freeElements();
  41619. this._dataElementCount = value;
  41620. this.allocElements();
  41621. },
  41622. enumerable: true,
  41623. configurable: true
  41624. });
  41625. __decorate([
  41626. instanceData()
  41627. ], InstanceDataBase.prototype, "zBias", null);
  41628. __decorate([
  41629. instanceData()
  41630. ], InstanceDataBase.prototype, "transformX", null);
  41631. __decorate([
  41632. instanceData()
  41633. ], InstanceDataBase.prototype, "transformY", null);
  41634. __decorate([
  41635. instanceData()
  41636. ], InstanceDataBase.prototype, "opacity", null);
  41637. return InstanceDataBase;
  41638. }());
  41639. BABYLON.InstanceDataBase = InstanceDataBase;
  41640. var RenderablePrim2D = (function (_super) {
  41641. __extends(RenderablePrim2D, _super);
  41642. function RenderablePrim2D(settings) {
  41643. _super.call(this, settings);
  41644. this._isTransparent = false;
  41645. this._isAlphaTest = false;
  41646. this._transparentPrimitiveInfo = null;
  41647. }
  41648. Object.defineProperty(RenderablePrim2D.prototype, "isAlphaTest", {
  41649. get: function () {
  41650. return this._isAlphaTest;
  41651. },
  41652. set: function (value) {
  41653. if (this._isAlphaTest === value) {
  41654. return;
  41655. }
  41656. this._isAlphaTest = value;
  41657. this._updateRenderMode();
  41658. },
  41659. enumerable: true,
  41660. configurable: true
  41661. });
  41662. Object.defineProperty(RenderablePrim2D.prototype, "isTransparent", {
  41663. get: function () {
  41664. return this._isTransparent || (this._opacity < 1);
  41665. },
  41666. set: function (value) {
  41667. if (this._isTransparent === value) {
  41668. return;
  41669. }
  41670. this._isTransparent = value;
  41671. this._updateRenderMode();
  41672. },
  41673. enumerable: true,
  41674. configurable: true
  41675. });
  41676. Object.defineProperty(RenderablePrim2D.prototype, "renderMode", {
  41677. get: function () {
  41678. return this._renderMode;
  41679. },
  41680. enumerable: true,
  41681. configurable: true
  41682. });
  41683. /**
  41684. * Dispose the primitive and its resources, remove it from its parent
  41685. */
  41686. RenderablePrim2D.prototype.dispose = function () {
  41687. if (!_super.prototype.dispose.call(this)) {
  41688. return false;
  41689. }
  41690. if (this._transparentPrimitiveInfo) {
  41691. this.renderGroup._renderableData.removeTransparentPrimitiveInfo(this._transparentPrimitiveInfo);
  41692. this._transparentPrimitiveInfo = null;
  41693. }
  41694. if (this._modelRenderInstanceID) {
  41695. this._modelRenderCache.removeInstanceData(this._modelRenderInstanceID);
  41696. this._modelRenderInstanceID = null;
  41697. }
  41698. if (this._modelRenderCache) {
  41699. this._modelRenderCache.dispose();
  41700. this._modelRenderCache = null;
  41701. }
  41702. if (this._instanceDataParts) {
  41703. this._instanceDataParts.forEach(function (p) {
  41704. p.freeElements();
  41705. });
  41706. this._instanceDataParts = null;
  41707. }
  41708. return true;
  41709. };
  41710. RenderablePrim2D.prototype._prepareRenderPre = function (context) {
  41711. _super.prototype._prepareRenderPre.call(this, context);
  41712. // If the model changed and we have already an instance, we must remove this instance from the obsolete model
  41713. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagModelDirty) && this._modelRenderInstanceID) {
  41714. this._modelRenderCache.removeInstanceData(this._modelRenderInstanceID);
  41715. this._modelRenderInstanceID = null;
  41716. }
  41717. // Need to create the model?
  41718. var setupModelRenderCache = false;
  41719. if (!this._modelRenderCache || this._isFlagSet(BABYLON.SmartPropertyPrim.flagModelDirty)) {
  41720. setupModelRenderCache = this._createModelRenderCache();
  41721. }
  41722. var gii = null;
  41723. var newInstance = false;
  41724. // Need to create the instance data parts?
  41725. if (!this._modelRenderInstanceID) {
  41726. // Yes, flag it for later, more processing will have to be done
  41727. newInstance = true;
  41728. gii = this._createModelDataParts();
  41729. }
  41730. // If the ModelRenderCache is brand new, now is the time to call the implementation's specific setup method to create the rendering resources
  41731. if (setupModelRenderCache) {
  41732. this.setupModelRenderCache(this._modelRenderCache);
  41733. }
  41734. // 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.
  41735. // 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.
  41736. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagVisibilityChanged) || context.forceRefreshPrimitive || newInstance || (this._instanceDirtyFlags !== 0) || (this._globalTransformProcessStep !== this._globalTransformStep)) {
  41737. this._updateInstanceDataParts(gii);
  41738. }
  41739. };
  41740. RenderablePrim2D.prototype._createModelRenderCache = function () {
  41741. var _this = this;
  41742. var setupModelRenderCache = false;
  41743. if (this._modelRenderCache) {
  41744. this._modelRenderCache.dispose();
  41745. }
  41746. this._modelRenderCache = this.owner._engineData.GetOrAddModelCache(this.modelKey, function (key) {
  41747. var mrc = _this.createModelRenderCache(key);
  41748. setupModelRenderCache = true;
  41749. return mrc;
  41750. });
  41751. this._clearFlags(BABYLON.SmartPropertyPrim.flagModelDirty);
  41752. // if this is still false it means the MRC already exists, so we add a reference to it
  41753. if (!setupModelRenderCache) {
  41754. this._modelRenderCache.addRef();
  41755. }
  41756. return setupModelRenderCache;
  41757. };
  41758. RenderablePrim2D.prototype._createModelDataParts = function () {
  41759. var _this = this;
  41760. // Create the instance data parts of the primitive and store them
  41761. var parts = this.createInstanceDataParts();
  41762. this._instanceDataParts = parts;
  41763. // Check if the ModelRenderCache for this particular instance is also brand new, initialize it if it's the case
  41764. if (!this._modelRenderCache._partData) {
  41765. this._setupModelRenderCache(parts);
  41766. }
  41767. // The Rendering resources (Effect, VB, IB, Textures) are stored in the ModelRenderCache
  41768. // But it's the RenderGroup that will store all the Instanced related data to render all the primitive it owns.
  41769. // So for a given ModelKey we getOrAdd a GroupInstanceInfo that will store all these data
  41770. var gii = this.renderGroup._renderableData._renderGroupInstancesInfo.getOrAddWithFactory(this.modelKey, function (k) {
  41771. var res = new BABYLON.GroupInstanceInfo(_this.renderGroup, _this._modelRenderCache, _this._modelRenderCache._partData.length);
  41772. for (var j = 0; j < _this._modelRenderCache._partData.length; j++) {
  41773. var part = _this._instanceDataParts[j];
  41774. res.partIndexFromId.add(part.id.toString(), j);
  41775. res.usedShaderCategories[j] = ";" + _this.getUsedShaderCategories(part).join(";") + ";";
  41776. res.strides[j] = _this._modelRenderCache._partData[j]._partDataStride;
  41777. }
  41778. return res;
  41779. });
  41780. // Get the GroupInfoDataPart corresponding to the render category of the part
  41781. var rm = 0;
  41782. var gipd = null;
  41783. if (this.isTransparent) {
  41784. gipd = gii.transparentData;
  41785. rm = BABYLON.Render2DContext.RenderModeTransparent;
  41786. }
  41787. else if (this.isAlphaTest) {
  41788. gipd = gii.alphaTestData;
  41789. rm = BABYLON.Render2DContext.RenderModeAlphaTest;
  41790. }
  41791. else {
  41792. gipd = gii.opaqueData;
  41793. rm = BABYLON.Render2DContext.RenderModeOpaque;
  41794. }
  41795. // For each instance data part of the primitive, allocate the instanced element it needs for render
  41796. for (var i = 0; i < parts.length; i++) {
  41797. var part = parts[i];
  41798. part.dataBuffer = gipd[i]._partData;
  41799. part.allocElements();
  41800. part.renderMode = rm;
  41801. }
  41802. // 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
  41803. this._modelRenderInstanceID = this._modelRenderCache.addInstanceDataParts(this._instanceDataParts);
  41804. return gii;
  41805. };
  41806. RenderablePrim2D.prototype._setupModelRenderCache = function (parts) {
  41807. var ctiArray = new Array();
  41808. this._modelRenderCache._partData = new Array();
  41809. for (var _i = 0, parts_1 = parts; _i < parts_1.length; _i++) {
  41810. var dataPart = parts_1[_i];
  41811. var pd = new BABYLON.ModelRenderCachePartData();
  41812. this._modelRenderCache._partData.push(pd);
  41813. var cat = this.getUsedShaderCategories(dataPart);
  41814. var cti = dataPart.getClassTreeInfo();
  41815. // Make sure the instance is visible other the properties won't be set and their size/offset wont be computed
  41816. var curVisible = this.isVisible;
  41817. this.isVisible = true;
  41818. // 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.
  41819. //console.log("Build Prop Layout for " + Tools.getClassName(this._instanceDataParts[0]));
  41820. var joinCat = ";" + cat.join(";") + ";";
  41821. pd._partJoinedUsedCategories = joinCat;
  41822. InstanceClassInfo._CurCategories = joinCat;
  41823. var obj = this.beforeRefreshForLayoutConstruction(dataPart);
  41824. if (!this.refreshInstanceDataPart(dataPart)) {
  41825. console.log("Layout construction for " + BABYLON.Tools.getClassName(this._instanceDataParts[0]) + " failed because refresh returned false");
  41826. }
  41827. this.afterRefreshForLayoutConstruction(dataPart, obj);
  41828. this.isVisible = curVisible;
  41829. var size = 0;
  41830. cti.fullContent.forEach(function (k, v) {
  41831. if (!v.category || cat.indexOf(v.category) !== -1) {
  41832. if (v.attributeName === "zBias") {
  41833. pd._zBiasOffset = v.instanceOffset.get(joinCat);
  41834. }
  41835. if (!v.size) {
  41836. console.log("ERROR: Couldn't detect the size of the Property " + v.attributeName + " from type " + BABYLON.Tools.getClassName(cti.type) + ". Property is ignored.");
  41837. }
  41838. else {
  41839. size += v.size;
  41840. }
  41841. }
  41842. });
  41843. pd._partDataStride = size;
  41844. pd._partUsedCategories = cat;
  41845. pd._partId = dataPart.id;
  41846. ctiArray.push(cti);
  41847. }
  41848. this._modelRenderCache._partsClassInfo = ctiArray;
  41849. };
  41850. RenderablePrim2D.prototype.onZOrderChanged = function () {
  41851. if (this.isTransparent && this._transparentPrimitiveInfo) {
  41852. this.renderGroup._renderableData.transparentPrimitiveZChanged(this._transparentPrimitiveInfo);
  41853. var gii = this.renderGroup._renderableData._renderGroupInstancesInfo.get(this.modelKey);
  41854. // Flag the transparentData dirty has will have to sort it again
  41855. gii.transparentOrderDirty = true;
  41856. }
  41857. };
  41858. RenderablePrim2D.prototype._updateInstanceDataParts = function (gii) {
  41859. // Fetch the GroupInstanceInfo if we don't already have it
  41860. var rd = this.renderGroup._renderableData;
  41861. if (!gii) {
  41862. gii = rd._renderGroupInstancesInfo.get(this.modelKey);
  41863. }
  41864. var isTransparent = this.isTransparent;
  41865. var isAlphaTest = this.isAlphaTest;
  41866. var wereTransparent = false;
  41867. // Check a render mode change
  41868. var rmChanged = false;
  41869. if (this._instanceDataParts.length > 0) {
  41870. var firstPart = this._instanceDataParts[0];
  41871. var partRM = firstPart.renderMode;
  41872. var curRM = this.renderMode;
  41873. if (partRM !== curRM) {
  41874. wereTransparent = partRM === BABYLON.Render2DContext.RenderModeTransparent;
  41875. rmChanged = true;
  41876. var gipd = void 0;
  41877. switch (curRM) {
  41878. case BABYLON.Render2DContext.RenderModeTransparent:
  41879. gipd = gii.transparentData;
  41880. break;
  41881. case BABYLON.Render2DContext.RenderModeAlphaTest:
  41882. gipd = gii.alphaTestData;
  41883. break;
  41884. default:
  41885. gipd = gii.opaqueData;
  41886. }
  41887. for (var i = 0; i < this._instanceDataParts.length; i++) {
  41888. var part = this._instanceDataParts[i];
  41889. part.freeElements();
  41890. part.dataBuffer = gipd[i]._partData;
  41891. part.renderMode = curRM;
  41892. }
  41893. }
  41894. }
  41895. // Handle changes related to ZOffset
  41896. var visChanged = this._isFlagSet(BABYLON.SmartPropertyPrim.flagVisibilityChanged);
  41897. if (isTransparent || wereTransparent) {
  41898. // Handle visibility change, which is also triggered when the primitive just got created
  41899. if (visChanged || rmChanged) {
  41900. if (this.isVisible && !wereTransparent) {
  41901. if (!this._transparentPrimitiveInfo) {
  41902. // Add the primitive to the list of transparent ones in the group that render is
  41903. this._transparentPrimitiveInfo = rd.addNewTransparentPrimitiveInfo(this, gii);
  41904. }
  41905. }
  41906. else {
  41907. if (this._transparentPrimitiveInfo) {
  41908. rd.removeTransparentPrimitiveInfo(this._transparentPrimitiveInfo);
  41909. this._transparentPrimitiveInfo = null;
  41910. }
  41911. }
  41912. gii.transparentOrderDirty = true;
  41913. }
  41914. }
  41915. var rebuildTrans = false;
  41916. // For each Instance Data part, refresh it to update the data in the DynamicFloatArray
  41917. for (var _i = 0, _a = this._instanceDataParts; _i < _a.length; _i++) {
  41918. var part = _a[_i];
  41919. var justAllocated = false;
  41920. // Check if we need to allocate data elements (hidden prim which becomes visible again)
  41921. if (visChanged || !part.dataElements || rmChanged) {
  41922. part.allocElements();
  41923. justAllocated = true;
  41924. }
  41925. InstanceClassInfo._CurCategories = gii.usedShaderCategories[gii.partIndexFromId.get(part.id.toString())];
  41926. // Will return false if the instance should not be rendered (not visible or other any reasons)
  41927. part.arrayLengthChanged = false;
  41928. if (!this.refreshInstanceDataPart(part)) {
  41929. // Free the data element
  41930. if (part.dataElements) {
  41931. part.freeElements();
  41932. }
  41933. }
  41934. rebuildTrans = rebuildTrans || part.arrayLengthChanged || justAllocated;
  41935. }
  41936. this._instanceDirtyFlags = 0;
  41937. // Make the appropriate data dirty
  41938. if (isTransparent) {
  41939. gii.transparentDirty = true;
  41940. if (rebuildTrans) {
  41941. rd._transparentListChanged = true;
  41942. }
  41943. }
  41944. else if (isAlphaTest) {
  41945. gii.alphaTestDirty = true;
  41946. }
  41947. else {
  41948. gii.opaqueDirty = true;
  41949. }
  41950. this._clearFlags(BABYLON.SmartPropertyPrim.flagVisibilityChanged); // Reset the flag as we've handled the case
  41951. };
  41952. RenderablePrim2D.prototype._updateTransparentSegmentIndices = function (ts) {
  41953. var minOff = BABYLON.Prim2DBase._bigInt;
  41954. var maxOff = 0;
  41955. for (var _i = 0, _a = this._instanceDataParts; _i < _a.length; _i++) {
  41956. var part = _a[_i];
  41957. if (part && part.dataElements) {
  41958. part.dataBuffer.pack();
  41959. for (var _b = 0, _c = part.dataElements; _b < _c.length; _b++) {
  41960. var el = _c[_b];
  41961. minOff = Math.min(minOff, el.offset);
  41962. maxOff = Math.max(maxOff, el.offset);
  41963. }
  41964. ts.startDataIndex = minOff / part.dataBuffer.stride;
  41965. ts.endDataIndex = (maxOff / part.dataBuffer.stride) + 1; // +1 for exclusive
  41966. }
  41967. }
  41968. };
  41969. RenderablePrim2D.prototype._getPrimitiveLastIndex = function () {
  41970. var maxOff = 0;
  41971. for (var _i = 0, _a = this._instanceDataParts; _i < _a.length; _i++) {
  41972. var part = _a[_i];
  41973. if (part) {
  41974. for (var _b = 0, _c = part.dataElements; _b < _c.length; _b++) {
  41975. var el = _c[_b];
  41976. maxOff = Math.max(maxOff, el.offset);
  41977. }
  41978. return (maxOff / part.dataBuffer.stride) + 1; // +1 for exclusive
  41979. }
  41980. }
  41981. };
  41982. // This internal method is mainly used for transparency processing
  41983. RenderablePrim2D.prototype._getNextPrimZOrder = function () {
  41984. var length = this._instanceDataParts.length;
  41985. for (var i = 0; i < length; i++) {
  41986. var part = this._instanceDataParts[i];
  41987. if (part) {
  41988. var stride = part.dataBuffer.stride;
  41989. var lastElementOffset = part.dataElements[part.dataElements.length - 1].offset;
  41990. // check if it's the last in the DFA
  41991. if (part.dataBuffer.totalElementCount * stride <= lastElementOffset) {
  41992. return null;
  41993. }
  41994. // Return the Z of the next primitive that lies in the DFA
  41995. return part.dataBuffer[lastElementOffset + stride + this.modelRenderCache._partData[i]._zBiasOffset];
  41996. }
  41997. }
  41998. return null;
  41999. };
  42000. // This internal method is mainly used for transparency processing
  42001. RenderablePrim2D.prototype._getPrevPrimZOrder = function () {
  42002. var length = this._instanceDataParts.length;
  42003. for (var i = 0; i < length; i++) {
  42004. var part = this._instanceDataParts[i];
  42005. if (part) {
  42006. var stride = part.dataBuffer.stride;
  42007. var firstElementOffset = part.dataElements[0].offset;
  42008. // check if it's the first in the DFA
  42009. if (firstElementOffset === 0) {
  42010. return null;
  42011. }
  42012. // Return the Z of the previous primitive that lies in the DFA
  42013. return part.dataBuffer[firstElementOffset - stride + this.modelRenderCache._partData[i]._zBiasOffset];
  42014. }
  42015. }
  42016. return null;
  42017. };
  42018. /**
  42019. * Transform a given point using the Primitive's origin setting.
  42020. * This method requires the Primitive's actualSize to be accurate
  42021. * @param p the point to transform
  42022. * @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.
  42023. * @param res an allocated Vector2 that will receive the transformed content
  42024. */
  42025. RenderablePrim2D.prototype.transformPointWithOriginByRef = function (p, originOffset, res) {
  42026. var actualSize = this.actualSize;
  42027. res.x = p.x - ((this.origin.x + (originOffset ? originOffset.x : 0)) * actualSize.width);
  42028. res.y = p.y - ((this.origin.y + (originOffset ? originOffset.y : 0)) * actualSize.height);
  42029. };
  42030. RenderablePrim2D.prototype.transformPointWithOriginToRef = function (p, originOffset, res) {
  42031. this.transformPointWithOriginByRef(p, originOffset, res);
  42032. return res;
  42033. };
  42034. /**
  42035. * Get the info for a given effect based on the dataPart metadata
  42036. * @param dataPartId partId in part list to get the info
  42037. * @param vertexBufferAttributes vertex buffer attributes to manually add
  42038. * @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
  42039. */
  42040. RenderablePrim2D.prototype.getDataPartEffectInfo = function (dataPartId, vertexBufferAttributes, useInstanced) {
  42041. if (useInstanced === void 0) { useInstanced = null; }
  42042. var dataPart = BABYLON.Tools.first(this._instanceDataParts, function (i) { return i.id === dataPartId; });
  42043. if (!dataPart) {
  42044. return null;
  42045. }
  42046. var instancedArray = this.owner.supportInstancedArray;
  42047. if (useInstanced != null) {
  42048. // Check if the caller ask for Instanced Array and the engine does not support it, return null if it's the case
  42049. if (useInstanced && instancedArray === false) {
  42050. return null;
  42051. }
  42052. // Use the caller's setting
  42053. instancedArray = useInstanced;
  42054. }
  42055. var cti = dataPart.getClassTreeInfo();
  42056. var categories = this.getUsedShaderCategories(dataPart);
  42057. var att = cti.classContent.getShaderAttributes(categories);
  42058. var defines = "";
  42059. categories.forEach(function (c) { defines += "#define " + c + "\n"; });
  42060. if (instancedArray) {
  42061. defines += "#define Instanced\n";
  42062. }
  42063. return { attributes: instancedArray ? vertexBufferAttributes.concat(att) : vertexBufferAttributes, uniforms: instancedArray ? [] : att, defines: defines };
  42064. };
  42065. Object.defineProperty(RenderablePrim2D.prototype, "modelRenderCache", {
  42066. get: function () {
  42067. return this._modelRenderCache;
  42068. },
  42069. enumerable: true,
  42070. configurable: true
  42071. });
  42072. RenderablePrim2D.prototype.createModelRenderCache = function (modelKey) {
  42073. return null;
  42074. };
  42075. RenderablePrim2D.prototype.setupModelRenderCache = function (modelRenderCache) {
  42076. };
  42077. RenderablePrim2D.prototype.createInstanceDataParts = function () {
  42078. return null;
  42079. };
  42080. RenderablePrim2D.prototype.getUsedShaderCategories = function (dataPart) {
  42081. return [];
  42082. };
  42083. RenderablePrim2D.prototype.beforeRefreshForLayoutConstruction = function (part) {
  42084. };
  42085. RenderablePrim2D.prototype.afterRefreshForLayoutConstruction = function (part, obj) {
  42086. };
  42087. RenderablePrim2D.prototype.refreshInstanceDataPart = function (part) {
  42088. if (!this.isVisible) {
  42089. return false;
  42090. }
  42091. part.isVisible = this.isVisible;
  42092. // 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)
  42093. if (part.dataElementCount === 1) {
  42094. part.curElement = 0;
  42095. this.updateInstanceDataPart(part);
  42096. }
  42097. return true;
  42098. };
  42099. /**
  42100. * Update the instanceDataBase level properties of a part
  42101. * @param part the part to update
  42102. * @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).
  42103. */
  42104. RenderablePrim2D.prototype.updateInstanceDataPart = function (part, positionOffset) {
  42105. if (positionOffset === void 0) { positionOffset = null; }
  42106. var t = this._globalTransform.multiply(this.renderGroup.invGlobalTransform);
  42107. var size = this.renderGroup.viewportSize;
  42108. var zBias = this.actualZOffset;
  42109. var offX = 0;
  42110. var offY = 0;
  42111. // If there's an offset, apply the global transformation matrix on it to get a global offset
  42112. if (positionOffset) {
  42113. offX = positionOffset.x * t.m[0] + positionOffset.y * t.m[4];
  42114. offY = positionOffset.x * t.m[1] + positionOffset.y * t.m[5];
  42115. }
  42116. // 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
  42117. // Current coordinates are expressed in renderGroup coordinates ([0, renderGroup.actualSize.width|height]) with 0,0 being at the left/top corner
  42118. // So for X:
  42119. // - tx.x = value * 2 / width: is to switch from [0, renderGroup.width] to [0, 2]
  42120. // - 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].
  42121. var w = size.width;
  42122. var h = size.height;
  42123. var invZBias = 1 / zBias;
  42124. 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);
  42125. 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);
  42126. part.transformX = tx;
  42127. part.transformY = ty;
  42128. part.opacity = this.actualOpacity;
  42129. // 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)
  42130. part.zBias = new BABYLON.Vector2(zBias, invZBias);
  42131. };
  42132. RenderablePrim2D.prototype._updateRenderMode = function () {
  42133. if (this.isTransparent) {
  42134. this._renderMode = BABYLON.Render2DContext.RenderModeTransparent;
  42135. }
  42136. else if (this.isAlphaTest) {
  42137. this._renderMode = BABYLON.Render2DContext.RenderModeAlphaTest;
  42138. }
  42139. else {
  42140. this._renderMode = BABYLON.Render2DContext.RenderModeOpaque;
  42141. }
  42142. };
  42143. RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT = BABYLON.Prim2DBase.PRIM2DBASE_PROPCOUNT + 5;
  42144. __decorate([
  42145. BABYLON.dynamicLevelProperty(BABYLON.Prim2DBase.PRIM2DBASE_PROPCOUNT + 0, function (pi) { return RenderablePrim2D.isAlphaTestProperty = pi; })
  42146. ], RenderablePrim2D.prototype, "isAlphaTest", null);
  42147. __decorate([
  42148. BABYLON.dynamicLevelProperty(BABYLON.Prim2DBase.PRIM2DBASE_PROPCOUNT + 1, function (pi) { return RenderablePrim2D.isTransparentProperty = pi; })
  42149. ], RenderablePrim2D.prototype, "isTransparent", null);
  42150. RenderablePrim2D = __decorate([
  42151. BABYLON.className("RenderablePrim2D")
  42152. ], RenderablePrim2D);
  42153. return RenderablePrim2D;
  42154. }(BABYLON.Prim2DBase));
  42155. BABYLON.RenderablePrim2D = RenderablePrim2D;
  42156. })(BABYLON || (BABYLON = {}));
  42157. var BABYLON;
  42158. (function (BABYLON) {
  42159. var Shape2D = (function (_super) {
  42160. __extends(Shape2D, _super);
  42161. function Shape2D(settings) {
  42162. _super.call(this, settings);
  42163. if (!settings) {
  42164. settings = {};
  42165. }
  42166. var borderBrush = null;
  42167. if (settings.border) {
  42168. if (typeof (settings.border) === "string") {
  42169. borderBrush = BABYLON.Canvas2D.GetBrushFromString(settings.border);
  42170. }
  42171. else {
  42172. borderBrush = settings.border;
  42173. }
  42174. }
  42175. var fillBrush = null;
  42176. if (settings.fill) {
  42177. if (typeof (settings.fill) === "string") {
  42178. fillBrush = BABYLON.Canvas2D.GetBrushFromString(settings.fill);
  42179. }
  42180. else {
  42181. fillBrush = settings.fill;
  42182. }
  42183. }
  42184. this.border = borderBrush;
  42185. this.fill = fillBrush;
  42186. this.borderThickness = settings.borderThickness;
  42187. }
  42188. Object.defineProperty(Shape2D.prototype, "border", {
  42189. get: function () {
  42190. return this._border;
  42191. },
  42192. set: function (value) {
  42193. this._border = value;
  42194. this._updateTransparencyStatus();
  42195. },
  42196. enumerable: true,
  42197. configurable: true
  42198. });
  42199. Object.defineProperty(Shape2D.prototype, "fill", {
  42200. /**
  42201. * Get/set the brush to render the Fill part of the Primitive
  42202. */
  42203. get: function () {
  42204. return this._fill;
  42205. },
  42206. set: function (value) {
  42207. this._fill = value;
  42208. this._updateTransparencyStatus();
  42209. },
  42210. enumerable: true,
  42211. configurable: true
  42212. });
  42213. Object.defineProperty(Shape2D.prototype, "borderThickness", {
  42214. get: function () {
  42215. return this._borderThickness;
  42216. },
  42217. set: function (value) {
  42218. this._borderThickness = value;
  42219. },
  42220. enumerable: true,
  42221. configurable: true
  42222. });
  42223. Shape2D.prototype.getUsedShaderCategories = function (dataPart) {
  42224. var cat = _super.prototype.getUsedShaderCategories.call(this, dataPart);
  42225. // Fill Part
  42226. if (dataPart.id === Shape2D.SHAPE2D_FILLPARTID) {
  42227. var fill = this.fill;
  42228. if (fill instanceof BABYLON.SolidColorBrush2D) {
  42229. cat.push(Shape2D.SHAPE2D_CATEGORY_FILLSOLID);
  42230. }
  42231. if (fill instanceof BABYLON.GradientColorBrush2D) {
  42232. cat.push(Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT);
  42233. }
  42234. }
  42235. // Border Part
  42236. if (dataPart.id === Shape2D.SHAPE2D_BORDERPARTID) {
  42237. cat.push(Shape2D.SHAPE2D_CATEGORY_BORDER);
  42238. var border = this.border;
  42239. if (border instanceof BABYLON.SolidColorBrush2D) {
  42240. cat.push(Shape2D.SHAPE2D_CATEGORY_BORDERSOLID);
  42241. }
  42242. if (border instanceof BABYLON.GradientColorBrush2D) {
  42243. cat.push(Shape2D.SHAPE2D_CATEGORY_BORDERGRADIENT);
  42244. }
  42245. }
  42246. return cat;
  42247. };
  42248. Shape2D.prototype.refreshInstanceDataPart = function (part) {
  42249. if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
  42250. return false;
  42251. }
  42252. // Fill Part
  42253. if (part.id === Shape2D.SHAPE2D_FILLPARTID) {
  42254. var d = part;
  42255. if (this.fill) {
  42256. var fill = this.fill;
  42257. if (fill instanceof BABYLON.SolidColorBrush2D) {
  42258. d.fillSolidColor = fill.color;
  42259. }
  42260. else if (fill instanceof BABYLON.GradientColorBrush2D) {
  42261. d.fillGradientColor1 = fill.color1;
  42262. d.fillGradientColor2 = fill.color2;
  42263. 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));
  42264. var ty = new BABYLON.Vector4(t.m[1], t.m[5], t.m[9], t.m[13]);
  42265. d.fillGradientTY = ty;
  42266. }
  42267. }
  42268. }
  42269. else if (part.id === Shape2D.SHAPE2D_BORDERPARTID) {
  42270. var d = part;
  42271. if (this.border) {
  42272. d.borderThickness = this.borderThickness;
  42273. var border = this.border;
  42274. if (border instanceof BABYLON.SolidColorBrush2D) {
  42275. d.borderSolidColor = border.color;
  42276. }
  42277. else if (border instanceof BABYLON.GradientColorBrush2D) {
  42278. d.borderGradientColor1 = border.color1;
  42279. d.borderGradientColor2 = border.color2;
  42280. 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));
  42281. var ty = new BABYLON.Vector4(t.m[1], t.m[5], t.m[9], t.m[13]);
  42282. d.borderGradientTY = ty;
  42283. }
  42284. }
  42285. }
  42286. return true;
  42287. };
  42288. Shape2D.prototype._updateTransparencyStatus = function () {
  42289. this.isTransparent = (this._border && this._border.isTransparent()) || (this._fill && this._fill.isTransparent()) || (this.actualOpacity < 1);
  42290. };
  42291. Shape2D.SHAPE2D_BORDERPARTID = 1;
  42292. Shape2D.SHAPE2D_FILLPARTID = 2;
  42293. Shape2D.SHAPE2D_CATEGORY_BORDER = "Border";
  42294. Shape2D.SHAPE2D_CATEGORY_BORDERSOLID = "BorderSolid";
  42295. Shape2D.SHAPE2D_CATEGORY_BORDERGRADIENT = "BorderGradient";
  42296. Shape2D.SHAPE2D_CATEGORY_FILLSOLID = "FillSolid";
  42297. Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT = "FillGradient";
  42298. Shape2D.SHAPE2D_PROPCOUNT = BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 5;
  42299. __decorate([
  42300. BABYLON.modelLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 1, function (pi) { return Shape2D.borderProperty = pi; }, true)
  42301. ], Shape2D.prototype, "border", null);
  42302. __decorate([
  42303. BABYLON.modelLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 2, function (pi) { return Shape2D.fillProperty = pi; }, true)
  42304. ], Shape2D.prototype, "fill", null);
  42305. __decorate([
  42306. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 3, function (pi) { return Shape2D.borderThicknessProperty = pi; })
  42307. ], Shape2D.prototype, "borderThickness", null);
  42308. Shape2D = __decorate([
  42309. BABYLON.className("Shape2D")
  42310. ], Shape2D);
  42311. return Shape2D;
  42312. }(BABYLON.RenderablePrim2D));
  42313. BABYLON.Shape2D = Shape2D;
  42314. var Shape2DInstanceData = (function (_super) {
  42315. __extends(Shape2DInstanceData, _super);
  42316. function Shape2DInstanceData() {
  42317. _super.apply(this, arguments);
  42318. }
  42319. Object.defineProperty(Shape2DInstanceData.prototype, "fillSolidColor", {
  42320. // FILL ATTRIBUTES
  42321. get: function () {
  42322. return null;
  42323. },
  42324. enumerable: true,
  42325. configurable: true
  42326. });
  42327. Object.defineProperty(Shape2DInstanceData.prototype, "fillGradientColor1", {
  42328. get: function () {
  42329. return null;
  42330. },
  42331. enumerable: true,
  42332. configurable: true
  42333. });
  42334. Object.defineProperty(Shape2DInstanceData.prototype, "fillGradientColor2", {
  42335. get: function () {
  42336. return null;
  42337. },
  42338. enumerable: true,
  42339. configurable: true
  42340. });
  42341. Object.defineProperty(Shape2DInstanceData.prototype, "fillGradientTY", {
  42342. get: function () {
  42343. return null;
  42344. },
  42345. enumerable: true,
  42346. configurable: true
  42347. });
  42348. Object.defineProperty(Shape2DInstanceData.prototype, "borderThickness", {
  42349. // BORDER ATTRIBUTES
  42350. get: function () {
  42351. return null;
  42352. },
  42353. enumerable: true,
  42354. configurable: true
  42355. });
  42356. Object.defineProperty(Shape2DInstanceData.prototype, "borderSolidColor", {
  42357. get: function () {
  42358. return null;
  42359. },
  42360. enumerable: true,
  42361. configurable: true
  42362. });
  42363. Object.defineProperty(Shape2DInstanceData.prototype, "borderGradientColor1", {
  42364. get: function () {
  42365. return null;
  42366. },
  42367. enumerable: true,
  42368. configurable: true
  42369. });
  42370. Object.defineProperty(Shape2DInstanceData.prototype, "borderGradientColor2", {
  42371. get: function () {
  42372. return null;
  42373. },
  42374. enumerable: true,
  42375. configurable: true
  42376. });
  42377. Object.defineProperty(Shape2DInstanceData.prototype, "borderGradientTY", {
  42378. get: function () {
  42379. return null;
  42380. },
  42381. enumerable: true,
  42382. configurable: true
  42383. });
  42384. __decorate([
  42385. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_FILLSOLID)
  42386. ], Shape2DInstanceData.prototype, "fillSolidColor", null);
  42387. __decorate([
  42388. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT)
  42389. ], Shape2DInstanceData.prototype, "fillGradientColor1", null);
  42390. __decorate([
  42391. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT)
  42392. ], Shape2DInstanceData.prototype, "fillGradientColor2", null);
  42393. __decorate([
  42394. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT)
  42395. ], Shape2DInstanceData.prototype, "fillGradientTY", null);
  42396. __decorate([
  42397. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_BORDER)
  42398. ], Shape2DInstanceData.prototype, "borderThickness", null);
  42399. __decorate([
  42400. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_BORDERSOLID)
  42401. ], Shape2DInstanceData.prototype, "borderSolidColor", null);
  42402. __decorate([
  42403. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_BORDERGRADIENT)
  42404. ], Shape2DInstanceData.prototype, "borderGradientColor1", null);
  42405. __decorate([
  42406. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_BORDERGRADIENT)
  42407. ], Shape2DInstanceData.prototype, "borderGradientColor2", null);
  42408. __decorate([
  42409. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_BORDERGRADIENT)
  42410. ], Shape2DInstanceData.prototype, "borderGradientTY", null);
  42411. return Shape2DInstanceData;
  42412. }(BABYLON.InstanceDataBase));
  42413. BABYLON.Shape2DInstanceData = Shape2DInstanceData;
  42414. })(BABYLON || (BABYLON = {}));
  42415. var BABYLON;
  42416. (function (BABYLON) {
  42417. var Group2D = (function (_super) {
  42418. __extends(Group2D, _super);
  42419. /**
  42420. * Create an Logical or Renderable Group.
  42421. * @param settings a combination of settings, possible ones are
  42422. * - 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)
  42423. * - children: an array of direct children
  42424. * - id a text identifier, for information purpose
  42425. * - position: the X & Y positions relative to its parent. Alternatively the x and y properties can be set. Default is [0;0]
  42426. * - rotation: the initial rotation (in radian) of the primitive. default is 0
  42427. * - scale: the initial scale of the primitive. default is 1
  42428. * - opacity: set the overall opacity of the primitive, 1 to be opaque (default), less than 1 to be transparent.
  42429. * - origin: define the normalized origin point location, default [0.5;0.5]
  42430. * - 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.
  42431. * - cacheBehavior: Define how the group should behave regarding the Canvas's cache strategy, default is Group2D.GROUPCACHEBEHAVIOR_FOLLOWCACHESTRATEGY
  42432. * - 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).
  42433. * - isVisible: true if the group must be visible, false for hidden. Default is true.
  42434. * - childrenFlatZOrder: if true all the children (direct and indirect) will share the same Z-Order. Use this when there's a lot of children which don't overlap. The drawing order IS NOT GUARANTED!
  42435. * - marginTop: top margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  42436. * - marginLeft: left margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  42437. * - marginRight: right margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  42438. * - marginBottom: bottom margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  42439. * - margin: top, left, right and bottom margin formatted as a single string (see PrimitiveThickness.fromString)
  42440. * - marginHAlignment: one value of the PrimitiveAlignment type's static properties
  42441. * - marginVAlignment: one value of the PrimitiveAlignment type's static properties
  42442. * - marginAlignment: a string defining the alignment, see PrimitiveAlignment.fromString
  42443. * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  42444. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  42445. * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  42446. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  42447. * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
  42448. */
  42449. function Group2D(settings) {
  42450. if (settings == null) {
  42451. settings = {};
  42452. }
  42453. if (settings.origin == null) {
  42454. settings.origin = new BABYLON.Vector2(0, 0);
  42455. }
  42456. _super.call(this, settings);
  42457. var size = (!settings.size && !settings.width && !settings.height) ? null : (settings.size || (new BABYLON.Size(settings.width || 0, settings.height || 0)));
  42458. this._trackedNode = (settings.trackNode == null) ? null : settings.trackNode;
  42459. if (this._trackedNode && this.owner) {
  42460. this.owner._registerTrackedNode(this);
  42461. }
  42462. this._cacheBehavior = (settings.cacheBehavior == null) ? Group2D.GROUPCACHEBEHAVIOR_FOLLOWCACHESTRATEGY : settings.cacheBehavior;
  42463. this.size = size;
  42464. this._viewportPosition = BABYLON.Vector2.Zero();
  42465. }
  42466. Group2D._createCachedCanvasGroup = function (owner) {
  42467. var g = new Group2D({ parent: owner, id: "__cachedCanvasGroup__", position: BABYLON.Vector2.Zero(), origin: BABYLON.Vector2.Zero(), size: null, isVisible: true });
  42468. return g;
  42469. };
  42470. Group2D.prototype.applyCachedTexture = function (vertexData, material) {
  42471. this._bindCacheTarget();
  42472. if (vertexData) {
  42473. var uv = vertexData.uvs;
  42474. var nodeuv = this._renderableData._cacheNodeUVs;
  42475. for (var i = 0; i < 4; i++) {
  42476. uv[i * 2 + 0] = nodeuv[i].x;
  42477. uv[i * 2 + 1] = nodeuv[i].y;
  42478. }
  42479. }
  42480. if (material) {
  42481. material.diffuseTexture = this._renderableData._cacheTexture;
  42482. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  42483. }
  42484. this._renderableData._cacheTexture.hasAlpha = true;
  42485. this._unbindCacheTarget();
  42486. };
  42487. Object.defineProperty(Group2D.prototype, "cachedRect", {
  42488. /**
  42489. * Allow you to access the information regarding the cached rectangle of the Group2D into the MapTexture.
  42490. * 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.
  42491. */
  42492. get: function () {
  42493. if (!this._renderableData) {
  42494. return null;
  42495. }
  42496. return this._renderableData._cacheNode;
  42497. },
  42498. enumerable: true,
  42499. configurable: true
  42500. });
  42501. Object.defineProperty(Group2D.prototype, "cachedUVs", {
  42502. /**
  42503. * The UVs into the MapTexture that map the cached group
  42504. */
  42505. get: function () {
  42506. if (!this._renderableData) {
  42507. return null;
  42508. }
  42509. return this._renderableData._cacheNodeUVs;
  42510. },
  42511. enumerable: true,
  42512. configurable: true
  42513. });
  42514. Object.defineProperty(Group2D.prototype, "cachedUVsChanged", {
  42515. get: function () {
  42516. if (!this._renderableData) {
  42517. return null;
  42518. }
  42519. if (!this._renderableData._cacheNodeUVsChangedObservable) {
  42520. this._renderableData._cacheNodeUVsChangedObservable = new BABYLON.Observable();
  42521. }
  42522. return this._renderableData._cacheNodeUVsChangedObservable;
  42523. },
  42524. enumerable: true,
  42525. configurable: true
  42526. });
  42527. Object.defineProperty(Group2D.prototype, "cacheTexture", {
  42528. /**
  42529. * Access the texture that maintains a cached version of the Group2D.
  42530. * This is useful only if you're not using a WorldSpaceNode for your WorldSpace Canvas and therefore need to perform the rendering yourself.
  42531. */
  42532. get: function () {
  42533. if (!this._renderableData) {
  42534. return null;
  42535. }
  42536. return this._renderableData._cacheTexture;
  42537. },
  42538. enumerable: true,
  42539. configurable: true
  42540. });
  42541. /**
  42542. * Call this method to remove this Group and its children from the Canvas
  42543. */
  42544. Group2D.prototype.dispose = function () {
  42545. if (!_super.prototype.dispose.call(this)) {
  42546. return false;
  42547. }
  42548. if (this._trackedNode != null) {
  42549. this.owner._unregisterTrackedNode(this);
  42550. this._trackedNode = null;
  42551. }
  42552. if (this._renderableData) {
  42553. this._renderableData.dispose(this.owner.engine);
  42554. this._renderableData = null;
  42555. }
  42556. return true;
  42557. };
  42558. Object.defineProperty(Group2D.prototype, "isRenderableGroup", {
  42559. /**
  42560. * @returns Returns true if the Group render content, false if it's a logical group only
  42561. */
  42562. get: function () {
  42563. return this._isRenderableGroup;
  42564. },
  42565. enumerable: true,
  42566. configurable: true
  42567. });
  42568. Object.defineProperty(Group2D.prototype, "isCachedGroup", {
  42569. /**
  42570. * @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
  42571. */
  42572. get: function () {
  42573. return this._isCachedGroup;
  42574. },
  42575. enumerable: true,
  42576. configurable: true
  42577. });
  42578. Object.defineProperty(Group2D.prototype, "size", {
  42579. get: function () {
  42580. return this._size;
  42581. },
  42582. /**
  42583. * Get/Set the size of the group. If null the size of the group will be determine from its content.
  42584. * 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.
  42585. */
  42586. set: function (val) {
  42587. this._size = val;
  42588. },
  42589. enumerable: true,
  42590. configurable: true
  42591. });
  42592. Object.defineProperty(Group2D.prototype, "viewportSize", {
  42593. get: function () {
  42594. return this._viewportSize;
  42595. },
  42596. enumerable: true,
  42597. configurable: true
  42598. });
  42599. Object.defineProperty(Group2D.prototype, "actualSize", {
  42600. get: function () {
  42601. // The computed size will be floor on both width and height
  42602. var actualSize;
  42603. // Return the size if set by the user
  42604. if (this._size) {
  42605. actualSize = new BABYLON.Size(Math.ceil(this._size.width), Math.ceil(this._size.height));
  42606. }
  42607. else {
  42608. var m = this.boundingInfo.max();
  42609. actualSize = new BABYLON.Size(Math.ceil(m.x), Math.ceil(m.y));
  42610. }
  42611. // 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)
  42612. if (!actualSize.equals(this._actualSize)) {
  42613. this.onPrimitivePropertyDirty(Group2D.actualSizeProperty.flagId);
  42614. this._actualSize = actualSize;
  42615. this.handleGroupChanged(Group2D.actualSizeProperty);
  42616. }
  42617. return actualSize;
  42618. },
  42619. enumerable: true,
  42620. configurable: true
  42621. });
  42622. Object.defineProperty(Group2D.prototype, "cacheBehavior", {
  42623. /**
  42624. * 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.
  42625. * 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.
  42626. */
  42627. get: function () {
  42628. return this._cacheBehavior;
  42629. },
  42630. enumerable: true,
  42631. configurable: true
  42632. });
  42633. Group2D.prototype._addPrimToDirtyList = function (prim) {
  42634. this._renderableData._primDirtyList.push(prim);
  42635. };
  42636. Group2D.prototype._renderCachedCanvas = function () {
  42637. this.owner._addGroupRenderCount(1);
  42638. this.updateCachedStates(true);
  42639. var context = new BABYLON.PrepareRender2DContext();
  42640. this._prepareGroupRender(context);
  42641. this._groupRender();
  42642. };
  42643. Object.defineProperty(Group2D.prototype, "trackedNode", {
  42644. /**
  42645. * Get/set the Scene's Node that should be tracked, the group's position will follow the projected position of the Node.
  42646. */
  42647. get: function () {
  42648. return this._trackedNode;
  42649. },
  42650. set: function (val) {
  42651. if (val != null) {
  42652. if (!this._isFlagSet(BABYLON.SmartPropertyPrim.flagTrackedGroup)) {
  42653. this.owner._registerTrackedNode(this);
  42654. }
  42655. this._trackedNode = val;
  42656. }
  42657. else {
  42658. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagTrackedGroup)) {
  42659. this.owner._unregisterTrackedNode(this);
  42660. }
  42661. this._trackedNode = null;
  42662. }
  42663. },
  42664. enumerable: true,
  42665. configurable: true
  42666. });
  42667. Group2D.prototype.levelIntersect = function (intersectInfo) {
  42668. // 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
  42669. return true;
  42670. };
  42671. Group2D.prototype.updateLevelBoundingInfo = function () {
  42672. var size;
  42673. // If the size is set by the user, the boundingInfo is computed from this value
  42674. if (this.size) {
  42675. size = this.size;
  42676. }
  42677. else {
  42678. size = new BABYLON.Size(0, 0);
  42679. }
  42680. BABYLON.BoundingInfo2D.CreateFromSizeToRef(size, this._levelBoundingInfo);
  42681. };
  42682. // Method called only on renderable groups to prepare the rendering
  42683. Group2D.prototype._prepareGroupRender = function (context) {
  42684. var sortedDirtyList = null;
  42685. // Update the Global Transformation and visibility status of the changed primitives
  42686. if ((this._renderableData._primDirtyList.length > 0) || context.forceRefreshPrimitive) {
  42687. sortedDirtyList = this._renderableData._primDirtyList.sort(function (a, b) { return a.hierarchyDepth - b.hierarchyDepth; });
  42688. this.updateCachedStatesOf(sortedDirtyList, true);
  42689. }
  42690. // Setup the size of the rendering viewport
  42691. // 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
  42692. if (!this._isCachedGroup) {
  42693. // Compute the WebGL viewport's location/size
  42694. var t = this._globalTransform.getTranslation();
  42695. var s = this.actualSize.clone();
  42696. var rs = this.owner._renderingSize;
  42697. s.height = Math.min(s.height, rs.height - t.y);
  42698. s.width = Math.min(s.width, rs.width - t.x);
  42699. var x = t.x;
  42700. var y = t.y;
  42701. // 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
  42702. this._viewportPosition.x = x;
  42703. this._viewportPosition.y = y;
  42704. var vw = s.width;
  42705. var vh = s.height;
  42706. if (!this._viewportSize) {
  42707. this._viewportSize = new BABYLON.Size(vw, vh);
  42708. }
  42709. else {
  42710. if (this._viewportSize.width !== vw || this._viewportSize.height !== vh) {
  42711. context.forceRefreshPrimitive = true;
  42712. }
  42713. this._viewportSize.width = vw;
  42714. this._viewportSize.height = vh;
  42715. }
  42716. }
  42717. else {
  42718. var newSize = this.actualSize.clone();
  42719. if (!newSize.equals(this._viewportSize)) {
  42720. context.forceRefreshPrimitive = true;
  42721. }
  42722. this._viewportSize = newSize;
  42723. }
  42724. if ((this._renderableData._primDirtyList.length > 0) || context.forceRefreshPrimitive) {
  42725. // If the group is cached, set the dirty flag to true because of the incoming changes
  42726. this._cacheGroupDirty = this._isCachedGroup;
  42727. // If it's a force refresh, prepare all the children
  42728. if (context.forceRefreshPrimitive) {
  42729. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  42730. var p = _a[_i];
  42731. p._prepareRender(context);
  42732. }
  42733. }
  42734. else {
  42735. // Each primitive that changed at least once was added into the primDirtyList, we have to sort this level using
  42736. // the hierarchyDepth in order to prepare primitives from top to bottom
  42737. if (!sortedDirtyList) {
  42738. sortedDirtyList = this._renderableData._primDirtyList.sort(function (a, b) { return a.hierarchyDepth - b.hierarchyDepth; });
  42739. }
  42740. sortedDirtyList.forEach(function (p) {
  42741. // 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.
  42742. // 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.
  42743. if (!p.isDisposed && p._needPrepare()) {
  42744. p._prepareRender(context);
  42745. }
  42746. });
  42747. }
  42748. // Everything is updated, clear the dirty list
  42749. this._renderableData._primDirtyList.forEach(function (p) { return p._resetPropertiesDirty(); });
  42750. this._renderableData._primDirtyList.splice(0);
  42751. }
  42752. // A renderable group has a list of direct children that are also renderable groups, we recurse on them to also prepare them
  42753. this._renderableData._childrenRenderableGroups.forEach(function (g) {
  42754. g._prepareGroupRender(context);
  42755. });
  42756. };
  42757. Group2D.prototype._groupRender = function () {
  42758. var _this = this;
  42759. var engine = this.owner.engine;
  42760. var failedCount = 0;
  42761. // First recurse to children render group to render them (in their cache or on screen)
  42762. for (var _i = 0, _a = this._renderableData._childrenRenderableGroups; _i < _a.length; _i++) {
  42763. var childGroup = _a[_i];
  42764. childGroup._groupRender();
  42765. }
  42766. // Render the primitives if needed: either if we don't cache the content or if the content is cached but has changed
  42767. if (!this.isCachedGroup || this._cacheGroupDirty) {
  42768. this.owner._addGroupRenderCount(1);
  42769. if (this.isCachedGroup) {
  42770. this._bindCacheTarget();
  42771. }
  42772. else {
  42773. var curVP = engine.setDirectViewport(this._viewportPosition.x, this._viewportPosition.y, this._viewportSize.width, this._viewportSize.height);
  42774. }
  42775. var curAlphaTest = engine.getAlphaTesting() === true;
  42776. var curDepthWrite = engine.getDepthWrite() === true;
  42777. // ===================================================================
  42778. // First pass, update the InstancedArray and render Opaque primitives
  42779. // Disable Alpha Testing, Enable Depth Write
  42780. engine.setAlphaTesting(false);
  42781. engine.setDepthWrite(true);
  42782. // For each different model of primitive to render
  42783. var context_1 = new BABYLON.Render2DContext(BABYLON.Render2DContext.RenderModeOpaque);
  42784. this._renderableData._renderGroupInstancesInfo.forEach(function (k, v) {
  42785. // Prepare the context object, update the WebGL Instanced Array buffer if needed
  42786. var renderCount = _this._prepareContext(engine, context_1, v);
  42787. // If null is returned, there's no opaque data to render
  42788. if (renderCount === null) {
  42789. return;
  42790. }
  42791. // Submit render only if we have something to render (everything may be hidden and the floatarray empty)
  42792. if (!_this.owner.supportInstancedArray || renderCount > 0) {
  42793. // render all the instances of this model, if the render method returns true then our instances are no longer dirty
  42794. var renderFailed = !v.modelRenderCache.render(v, context_1);
  42795. // Update dirty flag/related
  42796. v.opaqueDirty = renderFailed;
  42797. failedCount += renderFailed ? 1 : 0;
  42798. }
  42799. });
  42800. // =======================================================================
  42801. // Second pass, update the InstancedArray and render AlphaTest primitives
  42802. // Enable Alpha Testing, Enable Depth Write
  42803. engine.setAlphaTesting(true);
  42804. engine.setDepthWrite(true);
  42805. // For each different model of primitive to render
  42806. context_1 = new BABYLON.Render2DContext(BABYLON.Render2DContext.RenderModeAlphaTest);
  42807. this._renderableData._renderGroupInstancesInfo.forEach(function (k, v) {
  42808. // Prepare the context object, update the WebGL Instanced Array buffer if needed
  42809. var renderCount = _this._prepareContext(engine, context_1, v);
  42810. // If null is returned, there's no opaque data to render
  42811. if (renderCount === null) {
  42812. return;
  42813. }
  42814. // Submit render only if we have something to render (everything may be hidden and the floatarray empty)
  42815. if (!_this.owner.supportInstancedArray || renderCount > 0) {
  42816. // render all the instances of this model, if the render method returns true then our instances are no longer dirty
  42817. var renderFailed = !v.modelRenderCache.render(v, context_1);
  42818. // Update dirty flag/related
  42819. v.opaqueDirty = renderFailed;
  42820. failedCount += renderFailed ? 1 : 0;
  42821. }
  42822. });
  42823. // =======================================================================
  42824. // Third pass, transparent primitive rendering
  42825. // Enable Alpha Testing, Disable Depth Write
  42826. engine.setAlphaTesting(true);
  42827. engine.setDepthWrite(false);
  42828. // First Check if the transparent List change so we can update the TransparentSegment and PartData (sort if needed)
  42829. if (this._renderableData._transparentListChanged) {
  42830. this._updateTransparentData();
  42831. }
  42832. // From this point on we have up to date data to render, so let's go
  42833. failedCount += this._renderTransparentData();
  42834. // =======================================================================
  42835. // Unbind target/restore viewport setting, clear dirty flag, and quit
  42836. // The group's content is no longer dirty
  42837. this._cacheGroupDirty = failedCount !== 0;
  42838. if (this.isCachedGroup) {
  42839. this._unbindCacheTarget();
  42840. }
  42841. else {
  42842. if (curVP) {
  42843. engine.setViewport(curVP);
  42844. }
  42845. }
  42846. // Restore saved states
  42847. engine.setAlphaTesting(curAlphaTest);
  42848. engine.setDepthWrite(curDepthWrite);
  42849. }
  42850. };
  42851. Group2D.prototype._updateTransparentData = function () {
  42852. this.owner._addUpdateTransparentDataCount(1);
  42853. var rd = this._renderableData;
  42854. // Sort all the primitive from their depth, max (bottom) to min (top)
  42855. rd._transparentPrimitives.sort(function (a, b) { return b._primitive.actualZOffset - a._primitive.actualZOffset; });
  42856. var checkAndAddPrimInSegment = function (seg, tpiI) {
  42857. var tpi = rd._transparentPrimitives[tpiI];
  42858. // Fast rejection: if gii are different
  42859. if (seg.groupInsanceInfo !== tpi._groupInstanceInfo) {
  42860. return false;
  42861. }
  42862. //let tpiZ = tpi._primitive.actualZOffset;
  42863. // We've made it so far, the tpi can be part of the segment, add it
  42864. tpi._transparentSegment = seg;
  42865. seg.endDataIndex = tpi._primitive._getPrimitiveLastIndex();
  42866. return true;
  42867. };
  42868. // Free the existing TransparentSegments
  42869. for (var _i = 0, _a = rd._transparentSegments; _i < _a.length; _i++) {
  42870. var ts = _a[_i];
  42871. ts.dispose(this.owner.engine);
  42872. }
  42873. rd._transparentSegments.splice(0);
  42874. var prevSeg = null;
  42875. for (var tpiI = 0; tpiI < rd._transparentPrimitives.length; tpiI++) {
  42876. var tpi = rd._transparentPrimitives[tpiI];
  42877. // Check if the Data in which the primitive is stored is not sorted properly
  42878. if (tpi._groupInstanceInfo.transparentOrderDirty) {
  42879. tpi._groupInstanceInfo.sortTransparentData();
  42880. }
  42881. // Reset the segment, we have to create/rebuild it
  42882. tpi._transparentSegment = null;
  42883. // If there's a previous valid segment, check if this prim can be part of it
  42884. if (prevSeg) {
  42885. checkAndAddPrimInSegment(prevSeg, tpiI);
  42886. }
  42887. // If we couldn't insert in the adjacent segments, he have to create one
  42888. if (!tpi._transparentSegment) {
  42889. var ts = new BABYLON.TransparentSegment();
  42890. ts.groupInsanceInfo = tpi._groupInstanceInfo;
  42891. var prim = tpi._primitive;
  42892. ts.startZ = prim.actualZOffset;
  42893. prim._updateTransparentSegmentIndices(ts);
  42894. ts.endZ = ts.startZ;
  42895. tpi._transparentSegment = ts;
  42896. rd._transparentSegments.push(ts);
  42897. }
  42898. // Update prevSeg
  42899. prevSeg = tpi._transparentSegment;
  42900. }
  42901. //rd._firstChangedPrim = null;
  42902. rd._transparentListChanged = false;
  42903. };
  42904. Group2D.prototype._renderTransparentData = function () {
  42905. var failedCount = 0;
  42906. var context = new BABYLON.Render2DContext(BABYLON.Render2DContext.RenderModeTransparent);
  42907. var rd = this._renderableData;
  42908. var useInstanced = this.owner.supportInstancedArray;
  42909. var length = rd._transparentSegments.length;
  42910. for (var i = 0; i < length; i++) {
  42911. context.instancedBuffers = null;
  42912. var ts = rd._transparentSegments[i];
  42913. var gii = ts.groupInsanceInfo;
  42914. var mrc = gii.modelRenderCache;
  42915. var engine = this.owner.engine;
  42916. var count = ts.endDataIndex - ts.startDataIndex;
  42917. // Use Instanced Array if it's supported and if there's at least 5 prims to draw.
  42918. // We don't want to create an Instanced Buffer for less that 5 prims
  42919. if (useInstanced && count >= 5) {
  42920. if (!ts.partBuffers) {
  42921. var buffers = new Array();
  42922. for (var j = 0; j < gii.transparentData.length; j++) {
  42923. var gitd = gii.transparentData[j];
  42924. var dfa = gitd._partData;
  42925. var data = dfa.pack();
  42926. var stride = dfa.stride;
  42927. var neededSize = count * stride * 4;
  42928. var buffer = engine.createInstancesBuffer(neededSize); // Create + bind
  42929. var segData = data.subarray(ts.startDataIndex * stride, ts.endDataIndex * stride);
  42930. engine.updateArrayBuffer(segData);
  42931. buffers.push(buffer);
  42932. }
  42933. ts.partBuffers = buffers;
  42934. }
  42935. else if (gii.transparentDirty) {
  42936. for (var j = 0; j < gii.transparentData.length; j++) {
  42937. var gitd = gii.transparentData[j];
  42938. var dfa = gitd._partData;
  42939. var data = dfa.pack();
  42940. var stride = dfa.stride;
  42941. var buffer = ts.partBuffers[j];
  42942. var segData = data.subarray(ts.startDataIndex * stride, ts.endDataIndex * stride);
  42943. engine.bindArrayBuffer(buffer);
  42944. engine.updateArrayBuffer(segData);
  42945. }
  42946. }
  42947. context.useInstancing = true;
  42948. context.instancesCount = count;
  42949. context.instancedBuffers = ts.partBuffers;
  42950. context.groupInfoPartData = gii.transparentData;
  42951. var renderFailed = !mrc.render(gii, context);
  42952. failedCount += renderFailed ? 1 : 0;
  42953. }
  42954. else {
  42955. context.useInstancing = false;
  42956. context.partDataStartIndex = ts.startDataIndex;
  42957. context.partDataEndIndex = ts.endDataIndex;
  42958. context.groupInfoPartData = gii.transparentData;
  42959. var renderFailed = !mrc.render(gii, context);
  42960. failedCount += renderFailed ? 1 : 0;
  42961. }
  42962. }
  42963. return failedCount;
  42964. };
  42965. Group2D.prototype._prepareContext = function (engine, context, gii) {
  42966. var gipd = null;
  42967. var setDirty;
  42968. var getDirty;
  42969. // Render Mode specifics
  42970. switch (context.renderMode) {
  42971. case BABYLON.Render2DContext.RenderModeOpaque:
  42972. {
  42973. if (!gii.hasOpaqueData) {
  42974. return null;
  42975. }
  42976. setDirty = function (dirty) { gii.opaqueDirty = dirty; };
  42977. getDirty = function () { return gii.opaqueDirty; };
  42978. context.groupInfoPartData = gii.opaqueData;
  42979. gipd = gii.opaqueData;
  42980. break;
  42981. }
  42982. case BABYLON.Render2DContext.RenderModeAlphaTest:
  42983. {
  42984. if (!gii.hasAlphaTestData) {
  42985. return null;
  42986. }
  42987. setDirty = function (dirty) { gii.alphaTestDirty = dirty; };
  42988. getDirty = function () { return gii.alphaTestDirty; };
  42989. context.groupInfoPartData = gii.alphaTestData;
  42990. gipd = gii.alphaTestData;
  42991. break;
  42992. }
  42993. default:
  42994. throw new Error("_prepareContext is only for opaque or alphaTest");
  42995. }
  42996. var renderCount = 0;
  42997. // This part will pack the dynamicfloatarray and update the instanced array WebGLBufffer
  42998. // Skip it if instanced arrays are not supported
  42999. if (this.owner.supportInstancedArray) {
  43000. // Flag for instancing
  43001. context.useInstancing = true;
  43002. // Make sure all the WebGLBuffers of the Instanced Array are created/up to date for the parts to render.
  43003. for (var i = 0; i < gipd.length; i++) {
  43004. var pid = gipd[i];
  43005. // If the instances of the model was changed, pack the data
  43006. var array = pid._partData;
  43007. var instanceData_1 = array.pack();
  43008. renderCount += array.usedElementCount;
  43009. // Compute the size the instance buffer should have
  43010. var neededSize = array.usedElementCount * array.stride * 4;
  43011. // Check if we have to (re)create the instancesBuffer because there's none or the size is too small
  43012. if (!pid._partBuffer || (pid._partBufferSize < neededSize)) {
  43013. if (pid._partBuffer) {
  43014. engine.deleteInstancesBuffer(pid._partBuffer);
  43015. }
  43016. pid._partBuffer = engine.createInstancesBuffer(neededSize); // Create + bind
  43017. pid._partBufferSize = neededSize;
  43018. setDirty(false);
  43019. // Update the WebGL buffer to match the new content of the instances data
  43020. engine.updateArrayBuffer(instanceData_1);
  43021. }
  43022. else if (getDirty()) {
  43023. // Update the WebGL buffer to match the new content of the instances data
  43024. engine.bindArrayBuffer(pid._partBuffer);
  43025. engine.updateArrayBuffer(instanceData_1);
  43026. }
  43027. }
  43028. setDirty(false);
  43029. }
  43030. else {
  43031. context.partDataStartIndex = 0;
  43032. // Find the first valid object to get the count
  43033. if (context.groupInfoPartData.length > 0) {
  43034. var i = 0;
  43035. while (!context.groupInfoPartData[i]) {
  43036. i++;
  43037. }
  43038. context.partDataEndIndex = context.groupInfoPartData[i]._partData.usedElementCount;
  43039. }
  43040. }
  43041. return renderCount;
  43042. };
  43043. Group2D.prototype._setRenderingScale = function (scale) {
  43044. if (this._renderableData._renderingScale === scale) {
  43045. return;
  43046. }
  43047. this._renderableData._renderingScale = scale;
  43048. };
  43049. Group2D.prototype._bindCacheTarget = function () {
  43050. var curWidth;
  43051. var curHeight;
  43052. var rd = this._renderableData;
  43053. var rs = rd._renderingScale;
  43054. Group2D._s.width = Math.ceil(this.actualSize.width * rs);
  43055. Group2D._s.height = Math.ceil(this.actualSize.height * rs);
  43056. var sizeChanged = !Group2D._s.equals(rd._cacheSize);
  43057. if (rd._cacheNode) {
  43058. var size = rd._cacheNode.contentSize;
  43059. // Check if we have to deallocate because the size is too small
  43060. if ((size.width < Group2D._s.width) || (size.height < Group2D._s.height)) {
  43061. // For Screen space: over-provisioning of 7% more to avoid frequent resizing for few pixels...
  43062. // For World space: no over-provisioning
  43063. var overprovisioning = this.owner.isScreenSpace ? 1.07 : 1;
  43064. curWidth = Math.floor(Group2D._s.width * overprovisioning);
  43065. curHeight = Math.floor(Group2D._s.height * overprovisioning);
  43066. //console.log(`[${this._globalTransformProcessStep}] Resize group ${this.id}, width: ${curWidth}, height: ${curHeight}`);
  43067. rd._cacheTexture.freeRect(rd._cacheNode);
  43068. rd._cacheNode = null;
  43069. }
  43070. }
  43071. if (!rd._cacheNode) {
  43072. // Check if we have to allocate a rendering zone in the global cache texture
  43073. var res = this.owner._allocateGroupCache(this, this.renderGroup, curWidth ? new BABYLON.Size(curWidth, curHeight) : null, rd._useMipMap, rd._anisotropicLevel);
  43074. rd._cacheNode = res.node;
  43075. rd._cacheTexture = res.texture;
  43076. rd._cacheRenderSprite = res.sprite;
  43077. sizeChanged = true;
  43078. }
  43079. if (sizeChanged) {
  43080. rd._cacheSize.copyFrom(Group2D._s);
  43081. rd._cacheNodeUVs = rd._cacheNode.getUVsForCustomSize(rd._cacheSize);
  43082. this.scale = this._renderableData._renderingScale;
  43083. if (rd._cacheNodeUVsChangedObservable && rd._cacheNodeUVsChangedObservable.hasObservers()) {
  43084. rd._cacheNodeUVsChangedObservable.notifyObservers(rd._cacheNodeUVs);
  43085. }
  43086. this._setFlags(BABYLON.SmartPropertyPrim.flagWorldCacheChanged);
  43087. }
  43088. var n = rd._cacheNode;
  43089. rd._cacheTexture.bindTextureForPosSize(n.pos, Group2D._s, true);
  43090. };
  43091. Group2D.prototype._unbindCacheTarget = function () {
  43092. if (this._renderableData._cacheTexture) {
  43093. this._renderableData._cacheTexture.unbindTexture();
  43094. }
  43095. };
  43096. Group2D.prototype.handleGroupChanged = function (prop) {
  43097. // This method is only for cachedGroup
  43098. var rd = this._renderableData;
  43099. if (!this.isCachedGroup || !rd._cacheRenderSprite) {
  43100. return;
  43101. }
  43102. // For now we only support these property changes
  43103. // TODO: add more! :)
  43104. if (prop.id === BABYLON.Prim2DBase.actualPositionProperty.id) {
  43105. rd._cacheRenderSprite.actualPosition = this.actualPosition.clone();
  43106. }
  43107. else if (prop.id === BABYLON.Prim2DBase.rotationProperty.id) {
  43108. rd._cacheRenderSprite.rotation = this.rotation;
  43109. }
  43110. else if (prop.id === BABYLON.Prim2DBase.scaleProperty.id) {
  43111. rd._cacheRenderSprite.scale = this.scale;
  43112. }
  43113. else if (prop.id === BABYLON.Prim2DBase.originProperty.id) {
  43114. rd._cacheRenderSprite.origin = this.origin.clone();
  43115. }
  43116. else if (prop.id === Group2D.actualSizeProperty.id) {
  43117. rd._cacheRenderSprite.size = this.actualSize.clone();
  43118. }
  43119. };
  43120. Group2D.prototype.detectGroupStates = function () {
  43121. var isCanvas = this instanceof BABYLON.Canvas2D;
  43122. var canvasStrat = this.owner.cachingStrategy;
  43123. // In Don't Cache mode, only the canvas is renderable, all the other groups are logical. There are not a single cached group.
  43124. if (canvasStrat === BABYLON.Canvas2D.CACHESTRATEGY_DONTCACHE) {
  43125. this._isRenderableGroup = isCanvas;
  43126. this._isCachedGroup = false;
  43127. }
  43128. else if (canvasStrat === BABYLON.Canvas2D.CACHESTRATEGY_CANVAS) {
  43129. if (isCanvas) {
  43130. this._isRenderableGroup = true;
  43131. this._isCachedGroup = true;
  43132. }
  43133. else {
  43134. this._isRenderableGroup = this.id === "__cachedCanvasGroup__";
  43135. this._isCachedGroup = false;
  43136. }
  43137. }
  43138. else if (canvasStrat === BABYLON.Canvas2D.CACHESTRATEGY_TOPLEVELGROUPS) {
  43139. if (isCanvas) {
  43140. this._isRenderableGroup = true;
  43141. this._isCachedGroup = false;
  43142. }
  43143. else {
  43144. if (this.hierarchyDepth === 1) {
  43145. this._isRenderableGroup = true;
  43146. this._isCachedGroup = true;
  43147. }
  43148. else {
  43149. this._isRenderableGroup = false;
  43150. this._isCachedGroup = false;
  43151. }
  43152. }
  43153. }
  43154. else if (canvasStrat === BABYLON.Canvas2D.CACHESTRATEGY_ALLGROUPS) {
  43155. var gcb = this.cacheBehavior;
  43156. if ((gcb === Group2D.GROUPCACHEBEHAVIOR_DONTCACHEOVERRIDE) || (gcb === Group2D.GROUPCACHEBEHAVIOR_CACHEINPARENTGROUP)) {
  43157. this._isRenderableGroup = gcb === Group2D.GROUPCACHEBEHAVIOR_DONTCACHEOVERRIDE;
  43158. this._isCachedGroup = false;
  43159. }
  43160. if (gcb === Group2D.GROUPCACHEBEHAVIOR_FOLLOWCACHESTRATEGY) {
  43161. this._isRenderableGroup = true;
  43162. this._isCachedGroup = true;
  43163. }
  43164. }
  43165. if (this._isRenderableGroup) {
  43166. // Yes, we do need that check, trust me, unfortunately we can call _detectGroupStates many time on the same object...
  43167. if (!this._renderableData) {
  43168. this._renderableData = new RenderableGroupData();
  43169. }
  43170. }
  43171. // If the group is tagged as renderable we add it to the renderable tree
  43172. if (this._isCachedGroup) {
  43173. var cur = this.parent;
  43174. while (cur) {
  43175. if (cur instanceof Group2D && cur._isRenderableGroup) {
  43176. if (cur._renderableData._childrenRenderableGroups.indexOf(this) === -1) {
  43177. cur._renderableData._childrenRenderableGroups.push(this);
  43178. }
  43179. break;
  43180. }
  43181. cur = cur.parent;
  43182. }
  43183. }
  43184. };
  43185. Group2D.GROUP2D_PROPCOUNT = BABYLON.Prim2DBase.PRIM2DBASE_PROPCOUNT + 5;
  43186. /**
  43187. * Default behavior, the group will use the caching strategy defined at the Canvas Level
  43188. */
  43189. Group2D.GROUPCACHEBEHAVIOR_FOLLOWCACHESTRATEGY = 0;
  43190. /**
  43191. * When used, this group's content won't be cached, no matter which strategy used.
  43192. * If the group is part of a WorldSpace Canvas, its content will be drawn in the Canvas cache bitmap.
  43193. */
  43194. Group2D.GROUPCACHEBEHAVIOR_DONTCACHEOVERRIDE = 1;
  43195. /**
  43196. * When used, the group's content will be cached in the nearest cached parent group/canvas
  43197. */
  43198. Group2D.GROUPCACHEBEHAVIOR_CACHEINPARENTGROUP = 2;
  43199. Group2D._s = BABYLON.Size.Zero();
  43200. __decorate([
  43201. BABYLON.instanceLevelProperty(BABYLON.Prim2DBase.PRIM2DBASE_PROPCOUNT + 1, function (pi) { return Group2D.sizeProperty = pi; }, false, true)
  43202. ], Group2D.prototype, "size", null);
  43203. __decorate([
  43204. BABYLON.instanceLevelProperty(BABYLON.Prim2DBase.PRIM2DBASE_PROPCOUNT + 2, function (pi) { return Group2D.actualSizeProperty = pi; })
  43205. ], Group2D.prototype, "actualSize", null);
  43206. Group2D = __decorate([
  43207. BABYLON.className("Group2D")
  43208. ], Group2D);
  43209. return Group2D;
  43210. }(BABYLON.Prim2DBase));
  43211. BABYLON.Group2D = Group2D;
  43212. var RenderableGroupData = (function () {
  43213. function RenderableGroupData() {
  43214. this._primDirtyList = new Array();
  43215. this._childrenRenderableGroups = new Array();
  43216. this._renderGroupInstancesInfo = new BABYLON.StringDictionary();
  43217. this._transparentPrimitives = new Array();
  43218. this._transparentSegments = new Array();
  43219. this._transparentListChanged = false;
  43220. this._cacheNode = null;
  43221. this._cacheTexture = null;
  43222. this._cacheRenderSprite = null;
  43223. this._renderingScale = 1;
  43224. this._cacheNodeUVs = null;
  43225. this._cacheNodeUVsChangedObservable = null;
  43226. this._cacheSize = BABYLON.Size.Zero();
  43227. this._useMipMap = false;
  43228. this._anisotropicLevel = 1;
  43229. }
  43230. RenderableGroupData.prototype.dispose = function (engine) {
  43231. if (this._cacheRenderSprite) {
  43232. this._cacheRenderSprite.dispose();
  43233. this._cacheRenderSprite = null;
  43234. }
  43235. if (this._cacheTexture && this._cacheNode) {
  43236. this._cacheTexture.freeRect(this._cacheNode);
  43237. this._cacheTexture = null;
  43238. this._cacheNode = null;
  43239. }
  43240. if (this._primDirtyList) {
  43241. this._primDirtyList.splice(0);
  43242. this._primDirtyList = null;
  43243. }
  43244. if (this._renderGroupInstancesInfo) {
  43245. this._renderGroupInstancesInfo.forEach(function (k, v) {
  43246. v.dispose();
  43247. });
  43248. this._renderGroupInstancesInfo = null;
  43249. }
  43250. if (this._cacheNodeUVsChangedObservable) {
  43251. this._cacheNodeUVsChangedObservable.clear();
  43252. this._cacheNodeUVsChangedObservable = null;
  43253. }
  43254. if (this._transparentSegments) {
  43255. for (var _i = 0, _a = this._transparentSegments; _i < _a.length; _i++) {
  43256. var ts = _a[_i];
  43257. ts.dispose(engine);
  43258. }
  43259. this._transparentSegments.splice(0);
  43260. this._transparentSegments = null;
  43261. }
  43262. };
  43263. RenderableGroupData.prototype.addNewTransparentPrimitiveInfo = function (prim, gii) {
  43264. var tpi = new TransparentPrimitiveInfo();
  43265. tpi._primitive = prim;
  43266. tpi._groupInstanceInfo = gii;
  43267. tpi._transparentSegment = null;
  43268. this._transparentPrimitives.push(tpi);
  43269. this._transparentListChanged = true;
  43270. return tpi;
  43271. };
  43272. RenderableGroupData.prototype.removeTransparentPrimitiveInfo = function (tpi) {
  43273. var index = this._transparentPrimitives.indexOf(tpi);
  43274. if (index !== -1) {
  43275. this._transparentPrimitives.splice(index, 1);
  43276. this._transparentListChanged = true;
  43277. }
  43278. };
  43279. RenderableGroupData.prototype.transparentPrimitiveZChanged = function (tpi) {
  43280. this._transparentListChanged = true;
  43281. //this.updateSmallestZChangedPrim(tpi);
  43282. };
  43283. return RenderableGroupData;
  43284. }());
  43285. BABYLON.RenderableGroupData = RenderableGroupData;
  43286. var TransparentPrimitiveInfo = (function () {
  43287. function TransparentPrimitiveInfo() {
  43288. }
  43289. return TransparentPrimitiveInfo;
  43290. }());
  43291. BABYLON.TransparentPrimitiveInfo = TransparentPrimitiveInfo;
  43292. })(BABYLON || (BABYLON = {}));
  43293. var BABYLON;
  43294. (function (BABYLON) {
  43295. var Rectangle2DRenderCache = (function (_super) {
  43296. __extends(Rectangle2DRenderCache, _super);
  43297. function Rectangle2DRenderCache(engine, modelKey) {
  43298. _super.call(this, engine, modelKey);
  43299. this.effectsReady = false;
  43300. this.fillVB = null;
  43301. this.fillIB = null;
  43302. this.fillIndicesCount = 0;
  43303. this.instancingFillAttributes = null;
  43304. this.effectFill = null;
  43305. this.effectFillInstanced = null;
  43306. this.borderVB = null;
  43307. this.borderIB = null;
  43308. this.borderIndicesCount = 0;
  43309. this.instancingBorderAttributes = null;
  43310. this.effectBorder = null;
  43311. this.effectBorderInstanced = null;
  43312. }
  43313. Rectangle2DRenderCache.prototype.render = function (instanceInfo, context) {
  43314. // Do nothing if the shader is still loading/preparing
  43315. if (!this.effectsReady) {
  43316. if ((this.effectFill && (!this.effectFill.isReady() || (this.effectFillInstanced && !this.effectFillInstanced.isReady()))) ||
  43317. (this.effectBorder && (!this.effectBorder.isReady() || (this.effectBorderInstanced && !this.effectBorderInstanced.isReady())))) {
  43318. return false;
  43319. }
  43320. this.effectsReady = true;
  43321. }
  43322. var canvas = instanceInfo.owner.owner;
  43323. var engine = canvas.engine;
  43324. var depthFunction = 0;
  43325. if (this.effectFill && this.effectBorder) {
  43326. depthFunction = engine.getDepthFunction();
  43327. engine.setDepthFunctionToLessOrEqual();
  43328. }
  43329. var curAlphaMode = engine.getAlphaMode();
  43330. if (this.effectFill) {
  43331. var partIndex = instanceInfo.partIndexFromId.get(BABYLON.Shape2D.SHAPE2D_FILLPARTID.toString());
  43332. var pid = context.groupInfoPartData[partIndex];
  43333. if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
  43334. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  43335. }
  43336. var effect = context.useInstancing ? this.effectFillInstanced : this.effectFill;
  43337. engine.enableEffect(effect);
  43338. engine.bindBuffersDirectly(this.fillVB, this.fillIB, [1], 4, effect);
  43339. if (context.useInstancing) {
  43340. if (!this.instancingFillAttributes) {
  43341. this.instancingFillAttributes = this.loadInstancingAttributes(BABYLON.Shape2D.SHAPE2D_FILLPARTID, effect);
  43342. }
  43343. var glBuffer = context.instancedBuffers ? context.instancedBuffers[partIndex] : pid._partBuffer;
  43344. var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
  43345. canvas._addDrawCallCount(1, context.renderMode);
  43346. engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingFillAttributes);
  43347. engine.draw(true, 0, this.fillIndicesCount, count);
  43348. engine.unbindInstanceAttributes();
  43349. }
  43350. else {
  43351. canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
  43352. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  43353. this.setupUniforms(effect, partIndex, pid._partData, i);
  43354. engine.draw(true, 0, this.fillIndicesCount);
  43355. }
  43356. }
  43357. }
  43358. if (this.effectBorder) {
  43359. var partIndex = instanceInfo.partIndexFromId.get(BABYLON.Shape2D.SHAPE2D_BORDERPARTID.toString());
  43360. var pid = context.groupInfoPartData[partIndex];
  43361. if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
  43362. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  43363. }
  43364. var effect = context.useInstancing ? this.effectBorderInstanced : this.effectBorder;
  43365. engine.enableEffect(effect);
  43366. engine.bindBuffersDirectly(this.borderVB, this.borderIB, [1], 4, effect);
  43367. if (context.useInstancing) {
  43368. if (!this.instancingBorderAttributes) {
  43369. this.instancingBorderAttributes = this.loadInstancingAttributes(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, effect);
  43370. }
  43371. var glBuffer = context.instancedBuffers ? context.instancedBuffers[partIndex] : pid._partBuffer;
  43372. var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
  43373. canvas._addDrawCallCount(1, context.renderMode);
  43374. engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingBorderAttributes);
  43375. engine.draw(true, 0, this.borderIndicesCount, count);
  43376. engine.unbindInstanceAttributes();
  43377. }
  43378. else {
  43379. canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
  43380. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  43381. this.setupUniforms(effect, partIndex, pid._partData, i);
  43382. engine.draw(true, 0, this.borderIndicesCount);
  43383. }
  43384. }
  43385. }
  43386. engine.setAlphaMode(curAlphaMode);
  43387. if (this.effectFill && this.effectBorder) {
  43388. engine.setDepthFunction(depthFunction);
  43389. }
  43390. return true;
  43391. };
  43392. Rectangle2DRenderCache.prototype.dispose = function () {
  43393. if (!_super.prototype.dispose.call(this)) {
  43394. return false;
  43395. }
  43396. if (this.fillVB) {
  43397. this._engine._releaseBuffer(this.fillVB);
  43398. this.fillVB = null;
  43399. }
  43400. if (this.fillIB) {
  43401. this._engine._releaseBuffer(this.fillIB);
  43402. this.fillIB = null;
  43403. }
  43404. if (this.effectFill) {
  43405. this._engine._releaseEffect(this.effectFill);
  43406. this.effectFill = null;
  43407. }
  43408. if (this.effectFillInstanced) {
  43409. this._engine._releaseEffect(this.effectFillInstanced);
  43410. this.effectFillInstanced = null;
  43411. }
  43412. if (this.borderVB) {
  43413. this._engine._releaseBuffer(this.borderVB);
  43414. this.borderVB = null;
  43415. }
  43416. if (this.borderIB) {
  43417. this._engine._releaseBuffer(this.borderIB);
  43418. this.borderIB = null;
  43419. }
  43420. if (this.effectBorder) {
  43421. this._engine._releaseEffect(this.effectBorder);
  43422. this.effectBorder = null;
  43423. }
  43424. if (this.effectBorderInstanced) {
  43425. this._engine._releaseEffect(this.effectBorderInstanced);
  43426. this.effectBorderInstanced = null;
  43427. }
  43428. return true;
  43429. };
  43430. return Rectangle2DRenderCache;
  43431. }(BABYLON.ModelRenderCache));
  43432. BABYLON.Rectangle2DRenderCache = Rectangle2DRenderCache;
  43433. var Rectangle2DInstanceData = (function (_super) {
  43434. __extends(Rectangle2DInstanceData, _super);
  43435. function Rectangle2DInstanceData(partId) {
  43436. _super.call(this, partId, 1);
  43437. }
  43438. Object.defineProperty(Rectangle2DInstanceData.prototype, "properties", {
  43439. get: function () {
  43440. return null;
  43441. },
  43442. enumerable: true,
  43443. configurable: true
  43444. });
  43445. __decorate([
  43446. BABYLON.instanceData()
  43447. ], Rectangle2DInstanceData.prototype, "properties", null);
  43448. return Rectangle2DInstanceData;
  43449. }(BABYLON.Shape2DInstanceData));
  43450. BABYLON.Rectangle2DInstanceData = Rectangle2DInstanceData;
  43451. var Rectangle2D = (function (_super) {
  43452. __extends(Rectangle2D, _super);
  43453. /**
  43454. * Create an Rectangle 2D Shape primitive. May be a sharp rectangle (with sharp corners), or a rounded one.
  43455. * @param settings a combination of settings, possible ones are
  43456. * - 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)
  43457. * - children: an array of direct children
  43458. * - id a text identifier, for information purpose
  43459. * - position: the X & Y positions relative to its parent. Alternatively the x and y settings can be set. Default is [0;0]
  43460. * - rotation: the initial rotation (in radian) of the primitive. default is 0
  43461. * - scale: the initial scale of the primitive. default is 1
  43462. * - opacity: set the overall opacity of the primitive, 1 to be opaque (default), less than 1 to be transparent.
  43463. * - origin: define the normalized origin point location, default [0.5;0.5]
  43464. * - size: the size of the group. Alternatively the width and height settings can be set. Default will be [10;10].
  43465. * - roundRadius: if the rectangle has rounded corner, set their radius, default is 0 (to get a sharp edges rectangle).
  43466. * - 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)
  43467. * - 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)
  43468. * - borderThickness: the thickness of the drawn border, default is 1.
  43469. * - isVisible: true if the primitive must be visible, false for hidden. Default is true.
  43470. * - childrenFlatZOrder: if true all the children (direct and indirect) will share the same Z-Order. Use this when there's a lot of children which don't overlap. The drawing order IS NOT GUARANTED!
  43471. * - marginTop: top margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  43472. * - marginLeft: left margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  43473. * - marginRight: right margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  43474. * - marginBottom: bottom margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  43475. * - margin: top, left, right and bottom margin formatted as a single string (see PrimitiveThickness.fromString)
  43476. * - marginHAlignment: one value of the PrimitiveAlignment type's static properties
  43477. * - marginVAlignment: one value of the PrimitiveAlignment type's static properties
  43478. * - marginAlignment: a string defining the alignment, see PrimitiveAlignment.fromString
  43479. * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  43480. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  43481. * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  43482. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  43483. * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
  43484. */
  43485. function Rectangle2D(settings) {
  43486. // Avoid checking every time if the object exists
  43487. if (settings == null) {
  43488. settings = {};
  43489. }
  43490. _super.call(this, settings);
  43491. if (settings.size != null) {
  43492. this.size = settings.size;
  43493. }
  43494. else if (settings.width || settings.height) {
  43495. var size = new BABYLON.Size(settings.width, settings.height);
  43496. this.size = size;
  43497. }
  43498. //let size = settings.size || (new Size((settings.width === null) ? null : (settings.width || 10), (settings.height === null) ? null : (settings.height || 10)));
  43499. var roundRadius = (settings.roundRadius == null) ? 0 : settings.roundRadius;
  43500. var borderThickness = (settings.borderThickness == null) ? 1 : settings.borderThickness;
  43501. //this.size = size;
  43502. this.roundRadius = roundRadius;
  43503. this.borderThickness = borderThickness;
  43504. }
  43505. Object.defineProperty(Rectangle2D.prototype, "actualSize", {
  43506. get: function () {
  43507. if (this._actualSize) {
  43508. return this._actualSize;
  43509. }
  43510. return this.size;
  43511. },
  43512. set: function (value) {
  43513. this._actualSize = value;
  43514. },
  43515. enumerable: true,
  43516. configurable: true
  43517. });
  43518. Object.defineProperty(Rectangle2D.prototype, "notRounded", {
  43519. get: function () {
  43520. return this._notRounded;
  43521. },
  43522. set: function (value) {
  43523. this._notRounded = value;
  43524. },
  43525. enumerable: true,
  43526. configurable: true
  43527. });
  43528. Object.defineProperty(Rectangle2D.prototype, "roundRadius", {
  43529. get: function () {
  43530. return this._roundRadius;
  43531. },
  43532. set: function (value) {
  43533. this._roundRadius = value;
  43534. this.notRounded = value === 0;
  43535. this._positioningDirty();
  43536. },
  43537. enumerable: true,
  43538. configurable: true
  43539. });
  43540. Rectangle2D.prototype.levelIntersect = function (intersectInfo) {
  43541. // If we got there it mean the boundingInfo intersection succeed, if the rectangle has not roundRadius, it means it succeed!
  43542. if (this.notRounded) {
  43543. return true;
  43544. }
  43545. // 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.
  43546. // 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)
  43547. // 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.
  43548. // First let remove the origin out the equation, to have the rectangle with an origin at bottom/left
  43549. var size = this.size;
  43550. Rectangle2D._i0.x = intersectInfo._localPickPosition.x;
  43551. Rectangle2D._i0.y = intersectInfo._localPickPosition.y;
  43552. var rr = this.roundRadius;
  43553. var rrs = rr * rr;
  43554. // Check if the point is in the bottom/left quarter area
  43555. Rectangle2D._i1.x = rr;
  43556. Rectangle2D._i1.y = rr;
  43557. if (Rectangle2D._i0.x <= Rectangle2D._i1.x && Rectangle2D._i0.y <= Rectangle2D._i1.y) {
  43558. // Compute the intersection point in the quarter local space
  43559. Rectangle2D._i2.x = Rectangle2D._i0.x - Rectangle2D._i1.x;
  43560. Rectangle2D._i2.y = Rectangle2D._i0.y - Rectangle2D._i1.y;
  43561. // It's a hit if the squared distance is less/equal to the squared radius of the round circle
  43562. return Rectangle2D._i2.lengthSquared() <= rrs;
  43563. }
  43564. // Check if the point is in the top/left quarter area
  43565. Rectangle2D._i1.x = rr;
  43566. Rectangle2D._i1.y = size.height - rr;
  43567. if (Rectangle2D._i0.x <= Rectangle2D._i1.x && Rectangle2D._i0.y >= Rectangle2D._i1.y) {
  43568. // Compute the intersection point in the quarter local space
  43569. Rectangle2D._i2.x = Rectangle2D._i0.x - Rectangle2D._i1.x;
  43570. Rectangle2D._i2.y = Rectangle2D._i0.y - Rectangle2D._i1.y;
  43571. // It's a hit if the squared distance is less/equal to the squared radius of the round circle
  43572. return Rectangle2D._i2.lengthSquared() <= rrs;
  43573. }
  43574. // Check if the point is in the top/right quarter area
  43575. Rectangle2D._i1.x = size.width - rr;
  43576. Rectangle2D._i1.y = size.height - rr;
  43577. if (Rectangle2D._i0.x >= Rectangle2D._i1.x && Rectangle2D._i0.y >= Rectangle2D._i1.y) {
  43578. // Compute the intersection point in the quarter local space
  43579. Rectangle2D._i2.x = Rectangle2D._i0.x - Rectangle2D._i1.x;
  43580. Rectangle2D._i2.y = Rectangle2D._i0.y - Rectangle2D._i1.y;
  43581. // It's a hit if the squared distance is less/equal to the squared radius of the round circle
  43582. return Rectangle2D._i2.lengthSquared() <= rrs;
  43583. }
  43584. // Check if the point is in the bottom/right quarter area
  43585. Rectangle2D._i1.x = size.width - rr;
  43586. Rectangle2D._i1.y = rr;
  43587. if (Rectangle2D._i0.x >= Rectangle2D._i1.x && Rectangle2D._i0.y <= Rectangle2D._i1.y) {
  43588. // Compute the intersection point in the quarter local space
  43589. Rectangle2D._i2.x = Rectangle2D._i0.x - Rectangle2D._i1.x;
  43590. Rectangle2D._i2.y = Rectangle2D._i0.y - Rectangle2D._i1.y;
  43591. // It's a hit if the squared distance is less/equal to the squared radius of the round circle
  43592. return Rectangle2D._i2.lengthSquared() <= rrs;
  43593. }
  43594. // At any other locations the point is guarantied to be inside
  43595. return true;
  43596. };
  43597. Rectangle2D.prototype.updateLevelBoundingInfo = function () {
  43598. BABYLON.BoundingInfo2D.CreateFromSizeToRef(this.actualSize, this._levelBoundingInfo);
  43599. };
  43600. Rectangle2D.prototype.createModelRenderCache = function (modelKey) {
  43601. var renderCache = new Rectangle2DRenderCache(this.owner.engine, modelKey);
  43602. return renderCache;
  43603. };
  43604. Rectangle2D.prototype.setupModelRenderCache = function (modelRenderCache) {
  43605. var renderCache = modelRenderCache;
  43606. var engine = this.owner.engine;
  43607. // Need to create WebGL resources for fill part?
  43608. if (this.fill) {
  43609. var vbSize = ((this.notRounded ? 1 : Rectangle2D.roundSubdivisions) * 4) + 1;
  43610. var vb = new Float32Array(vbSize);
  43611. for (var i = 0; i < vbSize; i++) {
  43612. vb[i] = i;
  43613. }
  43614. renderCache.fillVB = engine.createVertexBuffer(vb);
  43615. var triCount = vbSize - 1;
  43616. var ib = new Float32Array(triCount * 3);
  43617. for (var i = 0; i < triCount; i++) {
  43618. ib[i * 3 + 0] = 0;
  43619. ib[i * 3 + 2] = i + 1;
  43620. ib[i * 3 + 1] = i + 2;
  43621. }
  43622. ib[triCount * 3 - 2] = 1;
  43623. renderCache.fillIB = engine.createIndexBuffer(ib);
  43624. renderCache.fillIndicesCount = triCount * 3;
  43625. // 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
  43626. var ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_FILLPARTID, ["index"], true);
  43627. if (ei) {
  43628. renderCache.effectFillInstanced = engine.createEffect("rect2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  43629. }
  43630. // Get the non instanced version
  43631. ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_FILLPARTID, ["index"], false);
  43632. renderCache.effectFill = engine.createEffect("rect2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  43633. }
  43634. // Need to create WebGL resource for border part?
  43635. if (this.border) {
  43636. var vbSize = (this.notRounded ? 1 : Rectangle2D.roundSubdivisions) * 4 * 2;
  43637. var vb = new Float32Array(vbSize);
  43638. for (var i = 0; i < vbSize; i++) {
  43639. vb[i] = i;
  43640. }
  43641. renderCache.borderVB = engine.createVertexBuffer(vb);
  43642. var triCount = vbSize;
  43643. var rs = triCount / 2;
  43644. var ib = new Float32Array(triCount * 3);
  43645. for (var i = 0; i < rs; i++) {
  43646. var r0 = i;
  43647. var r1 = (i + 1) % rs;
  43648. ib[i * 6 + 0] = rs + r1;
  43649. ib[i * 6 + 1] = rs + r0;
  43650. ib[i * 6 + 2] = r0;
  43651. ib[i * 6 + 3] = r1;
  43652. ib[i * 6 + 4] = rs + r1;
  43653. ib[i * 6 + 5] = r0;
  43654. }
  43655. renderCache.borderIB = engine.createIndexBuffer(ib);
  43656. renderCache.borderIndicesCount = triCount * 3;
  43657. // 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
  43658. var ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, ["index"], true);
  43659. if (ei) {
  43660. renderCache.effectBorderInstanced = engine.createEffect("rect2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  43661. }
  43662. // Get the non instanced version
  43663. ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, ["index"], false);
  43664. renderCache.effectBorder = engine.createEffect("rect2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  43665. }
  43666. return renderCache;
  43667. };
  43668. // 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
  43669. Rectangle2D.prototype._getInitialContentAreaToRef = function (primSize, initialContentPosition, initialContentArea) {
  43670. // Fall back to default implementation if there's no round Radius
  43671. if (this._notRounded) {
  43672. _super.prototype._getInitialContentAreaToRef.call(this, primSize, initialContentPosition, initialContentArea);
  43673. }
  43674. else {
  43675. var rr = Math.round((this.roundRadius - (this.roundRadius / Math.sqrt(2))) * 1.3);
  43676. initialContentPosition.x = initialContentPosition.y = rr;
  43677. initialContentArea.width = Math.max(0, primSize.width - (rr * 2));
  43678. initialContentArea.height = Math.max(0, primSize.height - (rr * 2));
  43679. }
  43680. };
  43681. Rectangle2D.prototype._getActualSizeFromContentToRef = function (primSize, newPrimSize) {
  43682. // Fall back to default implementation if there's no round Radius
  43683. if (this._notRounded) {
  43684. _super.prototype._getActualSizeFromContentToRef.call(this, primSize, newPrimSize);
  43685. }
  43686. else {
  43687. var rr = Math.round((this.roundRadius - (this.roundRadius / Math.sqrt(2))) * 1.3);
  43688. newPrimSize.copyFrom(primSize);
  43689. newPrimSize.width += rr * 2;
  43690. newPrimSize.height += rr * 2;
  43691. }
  43692. };
  43693. Rectangle2D.prototype.createInstanceDataParts = function () {
  43694. var res = new Array();
  43695. if (this.border) {
  43696. res.push(new Rectangle2DInstanceData(BABYLON.Shape2D.SHAPE2D_BORDERPARTID));
  43697. }
  43698. if (this.fill) {
  43699. res.push(new Rectangle2DInstanceData(BABYLON.Shape2D.SHAPE2D_FILLPARTID));
  43700. }
  43701. return res;
  43702. };
  43703. Rectangle2D.prototype.refreshInstanceDataPart = function (part) {
  43704. if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
  43705. return false;
  43706. }
  43707. if (part.id === BABYLON.Shape2D.SHAPE2D_BORDERPARTID) {
  43708. var d = part;
  43709. var size = this.actualSize;
  43710. d.properties = new BABYLON.Vector3(size.width, size.height, this.roundRadius || 0);
  43711. }
  43712. else if (part.id === BABYLON.Shape2D.SHAPE2D_FILLPARTID) {
  43713. var d = part;
  43714. var size = this.actualSize;
  43715. d.properties = new BABYLON.Vector3(size.width, size.height, this.roundRadius || 0);
  43716. }
  43717. return true;
  43718. };
  43719. Rectangle2D._i0 = BABYLON.Vector2.Zero();
  43720. Rectangle2D._i1 = BABYLON.Vector2.Zero();
  43721. Rectangle2D._i2 = BABYLON.Vector2.Zero();
  43722. Rectangle2D.roundSubdivisions = 16;
  43723. __decorate([
  43724. BABYLON.instanceLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 1, function (pi) { return Rectangle2D.actualSizeProperty = pi; }, false, true)
  43725. ], Rectangle2D.prototype, "actualSize", null);
  43726. __decorate([
  43727. BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 2, function (pi) { return Rectangle2D.notRoundedProperty = pi; })
  43728. ], Rectangle2D.prototype, "notRounded", null);
  43729. __decorate([
  43730. BABYLON.instanceLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 3, function (pi) { return Rectangle2D.roundRadiusProperty = pi; })
  43731. ], Rectangle2D.prototype, "roundRadius", null);
  43732. Rectangle2D = __decorate([
  43733. BABYLON.className("Rectangle2D")
  43734. ], Rectangle2D);
  43735. return Rectangle2D;
  43736. }(BABYLON.Shape2D));
  43737. BABYLON.Rectangle2D = Rectangle2D;
  43738. })(BABYLON || (BABYLON = {}));
  43739. var BABYLON;
  43740. (function (BABYLON) {
  43741. var Ellipse2DRenderCache = (function (_super) {
  43742. __extends(Ellipse2DRenderCache, _super);
  43743. function Ellipse2DRenderCache(engine, modelKey) {
  43744. _super.call(this, engine, modelKey);
  43745. this.effectsReady = false;
  43746. this.fillVB = null;
  43747. this.fillIB = null;
  43748. this.fillIndicesCount = 0;
  43749. this.instancingFillAttributes = null;
  43750. this.effectFillInstanced = null;
  43751. this.effectFill = null;
  43752. this.borderVB = null;
  43753. this.borderIB = null;
  43754. this.borderIndicesCount = 0;
  43755. this.instancingBorderAttributes = null;
  43756. this.effectBorderInstanced = null;
  43757. this.effectBorder = null;
  43758. }
  43759. Ellipse2DRenderCache.prototype.render = function (instanceInfo, context) {
  43760. // Do nothing if the shader is still loading/preparing
  43761. if (!this.effectsReady) {
  43762. if ((this.effectFill && (!this.effectFill.isReady() || (this.effectFillInstanced && !this.effectFillInstanced.isReady()))) ||
  43763. (this.effectBorder && (!this.effectBorder.isReady() || (this.effectBorderInstanced && !this.effectBorderInstanced.isReady())))) {
  43764. return false;
  43765. }
  43766. this.effectsReady = true;
  43767. }
  43768. var canvas = instanceInfo.owner.owner;
  43769. var engine = canvas.engine;
  43770. var depthFunction = 0;
  43771. if (this.effectFill && this.effectBorder) {
  43772. depthFunction = engine.getDepthFunction();
  43773. engine.setDepthFunctionToLessOrEqual();
  43774. }
  43775. var curAlphaMode = engine.getAlphaMode();
  43776. if (this.effectFill) {
  43777. var partIndex = instanceInfo.partIndexFromId.get(BABYLON.Shape2D.SHAPE2D_FILLPARTID.toString());
  43778. var pid = context.groupInfoPartData[partIndex];
  43779. if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
  43780. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  43781. }
  43782. var effect = context.useInstancing ? this.effectFillInstanced : this.effectFill;
  43783. engine.enableEffect(effect);
  43784. engine.bindBuffersDirectly(this.fillVB, this.fillIB, [1], 4, effect);
  43785. if (context.useInstancing) {
  43786. if (!this.instancingFillAttributes) {
  43787. this.instancingFillAttributes = this.loadInstancingAttributes(BABYLON.Shape2D.SHAPE2D_FILLPARTID, effect);
  43788. }
  43789. var glBuffer = context.instancedBuffers ? context.instancedBuffers[partIndex] : pid._partBuffer;
  43790. var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
  43791. canvas._addDrawCallCount(1, context.renderMode);
  43792. engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingFillAttributes);
  43793. engine.draw(true, 0, this.fillIndicesCount, count);
  43794. engine.unbindInstanceAttributes();
  43795. }
  43796. else {
  43797. canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
  43798. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  43799. this.setupUniforms(effect, partIndex, pid._partData, i);
  43800. engine.draw(true, 0, this.fillIndicesCount);
  43801. }
  43802. }
  43803. }
  43804. if (this.effectBorder) {
  43805. var partIndex = instanceInfo.partIndexFromId.get(BABYLON.Shape2D.SHAPE2D_BORDERPARTID.toString());
  43806. var pid = context.groupInfoPartData[partIndex];
  43807. if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
  43808. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  43809. }
  43810. var effect = context.useInstancing ? this.effectBorderInstanced : this.effectBorder;
  43811. engine.enableEffect(effect);
  43812. engine.bindBuffersDirectly(this.borderVB, this.borderIB, [1], 4, effect);
  43813. if (context.useInstancing) {
  43814. if (!this.instancingBorderAttributes) {
  43815. this.instancingBorderAttributes = this.loadInstancingAttributes(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, effect);
  43816. }
  43817. var glBuffer = context.instancedBuffers ? context.instancedBuffers[partIndex] : pid._partBuffer;
  43818. var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
  43819. canvas._addDrawCallCount(1, context.renderMode);
  43820. engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingBorderAttributes);
  43821. engine.draw(true, 0, this.borderIndicesCount, count);
  43822. engine.unbindInstanceAttributes();
  43823. }
  43824. else {
  43825. canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
  43826. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  43827. this.setupUniforms(effect, partIndex, pid._partData, i);
  43828. engine.draw(true, 0, this.borderIndicesCount);
  43829. }
  43830. }
  43831. }
  43832. engine.setAlphaMode(curAlphaMode);
  43833. if (this.effectFill && this.effectBorder) {
  43834. engine.setDepthFunction(depthFunction);
  43835. }
  43836. return true;
  43837. };
  43838. Ellipse2DRenderCache.prototype.dispose = function () {
  43839. if (!_super.prototype.dispose.call(this)) {
  43840. return false;
  43841. }
  43842. if (this.fillVB) {
  43843. this._engine._releaseBuffer(this.fillVB);
  43844. this.fillVB = null;
  43845. }
  43846. if (this.fillIB) {
  43847. this._engine._releaseBuffer(this.fillIB);
  43848. this.fillIB = null;
  43849. }
  43850. if (this.effectFill) {
  43851. this._engine._releaseEffect(this.effectFill);
  43852. this.effectFill = null;
  43853. }
  43854. if (this.effectFillInstanced) {
  43855. this._engine._releaseEffect(this.effectFillInstanced);
  43856. this.effectFillInstanced = null;
  43857. }
  43858. if (this.borderVB) {
  43859. this._engine._releaseBuffer(this.borderVB);
  43860. this.borderVB = null;
  43861. }
  43862. if (this.borderIB) {
  43863. this._engine._releaseBuffer(this.borderIB);
  43864. this.borderIB = null;
  43865. }
  43866. if (this.effectBorder) {
  43867. this._engine._releaseEffect(this.effectBorder);
  43868. this.effectBorder = null;
  43869. }
  43870. if (this.effectBorderInstanced) {
  43871. this._engine._releaseEffect(this.effectBorderInstanced);
  43872. this.effectBorderInstanced = null;
  43873. }
  43874. return true;
  43875. };
  43876. return Ellipse2DRenderCache;
  43877. }(BABYLON.ModelRenderCache));
  43878. BABYLON.Ellipse2DRenderCache = Ellipse2DRenderCache;
  43879. var Ellipse2DInstanceData = (function (_super) {
  43880. __extends(Ellipse2DInstanceData, _super);
  43881. function Ellipse2DInstanceData(partId) {
  43882. _super.call(this, partId, 1);
  43883. }
  43884. Object.defineProperty(Ellipse2DInstanceData.prototype, "properties", {
  43885. get: function () {
  43886. return null;
  43887. },
  43888. enumerable: true,
  43889. configurable: true
  43890. });
  43891. __decorate([
  43892. BABYLON.instanceData()
  43893. ], Ellipse2DInstanceData.prototype, "properties", null);
  43894. return Ellipse2DInstanceData;
  43895. }(BABYLON.Shape2DInstanceData));
  43896. BABYLON.Ellipse2DInstanceData = Ellipse2DInstanceData;
  43897. var Ellipse2D = (function (_super) {
  43898. __extends(Ellipse2D, _super);
  43899. /**
  43900. * Create an Ellipse 2D Shape primitive
  43901. * @param settings a combination of settings, possible ones are
  43902. * - 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)
  43903. * - children: an array of direct children
  43904. * - id: a text identifier, for information purpose
  43905. * - position: the X & Y positions relative to its parent. Alternatively the x and y properties can be set. Default is [0;0]
  43906. * - rotation: the initial rotation (in radian) of the primitive. default is 0
  43907. * - scale: the initial scale of the primitive. default is 1
  43908. * - opacity: set the overall opacity of the primitive, 1 to be opaque (default), less than 1 to be transparent.
  43909. * - origin: define the normalized origin point location, default [0.5;0.5]
  43910. * - size: the size of the group. Alternatively the width and height properties can be set. Default will be [10;10].
  43911. * - subdivision: the number of subdivision to create the ellipse perimeter, default is 64.
  43912. * - 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)
  43913. * - 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)
  43914. * - borderThickness: the thickness of the drawn border, default is 1.
  43915. * - isVisible: true if the group must be visible, false for hidden. Default is true.
  43916. * - childrenFlatZOrder: if true all the children (direct and indirect) will share the same Z-Order. Use this when there's a lot of children which don't overlap. The drawing order IS NOT GUARANTED!
  43917. * - marginTop: top margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  43918. * - marginLeft: left margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  43919. * - marginRight: right margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  43920. * - marginBottom: bottom margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  43921. * - margin: top, left, right and bottom margin formatted as a single string (see PrimitiveThickness.fromString)
  43922. * - marginHAlignment: one value of the PrimitiveAlignment type's static properties
  43923. * - marginVAlignment: one value of the PrimitiveAlignment type's static properties
  43924. * - marginAlignment: a string defining the alignment, see PrimitiveAlignment.fromString
  43925. * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  43926. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  43927. * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  43928. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  43929. * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
  43930. */
  43931. function Ellipse2D(settings) {
  43932. // Avoid checking every time if the object exists
  43933. if (settings == null) {
  43934. settings = {};
  43935. }
  43936. _super.call(this, settings);
  43937. if (settings.size != null) {
  43938. this.size = settings.size;
  43939. }
  43940. else if (settings.width || settings.height) {
  43941. var size = new BABYLON.Size(settings.width, settings.height);
  43942. this.size = size;
  43943. }
  43944. var sub = (settings.subdivisions == null) ? 64 : settings.subdivisions;
  43945. this.subdivisions = sub;
  43946. }
  43947. Object.defineProperty(Ellipse2D.prototype, "actualSize", {
  43948. get: function () {
  43949. if (this._actualSize) {
  43950. return this._actualSize;
  43951. }
  43952. return this.size;
  43953. },
  43954. set: function (value) {
  43955. this._actualSize = value;
  43956. },
  43957. enumerable: true,
  43958. configurable: true
  43959. });
  43960. Object.defineProperty(Ellipse2D.prototype, "subdivisions", {
  43961. get: function () {
  43962. return this._subdivisions;
  43963. },
  43964. set: function (value) {
  43965. this._subdivisions = value;
  43966. },
  43967. enumerable: true,
  43968. configurable: true
  43969. });
  43970. Ellipse2D.prototype.levelIntersect = function (intersectInfo) {
  43971. var w = this.size.width / 2;
  43972. var h = this.size.height / 2;
  43973. var x = intersectInfo._localPickPosition.x - w;
  43974. var y = intersectInfo._localPickPosition.y - h;
  43975. return ((x * x) / (w * w) + (y * y) / (h * h)) <= 1;
  43976. };
  43977. Ellipse2D.prototype.updateLevelBoundingInfo = function () {
  43978. BABYLON.BoundingInfo2D.CreateFromSizeToRef(this.actualSize, this._levelBoundingInfo);
  43979. };
  43980. Ellipse2D.prototype.createModelRenderCache = function (modelKey) {
  43981. var renderCache = new Ellipse2DRenderCache(this.owner.engine, modelKey);
  43982. return renderCache;
  43983. };
  43984. Ellipse2D.prototype.setupModelRenderCache = function (modelRenderCache) {
  43985. var renderCache = modelRenderCache;
  43986. var engine = this.owner.engine;
  43987. // Need to create WebGL resources for fill part?
  43988. if (this.fill) {
  43989. var vbSize = this.subdivisions + 1;
  43990. var vb = new Float32Array(vbSize);
  43991. for (var i = 0; i < vbSize; i++) {
  43992. vb[i] = i;
  43993. }
  43994. renderCache.fillVB = engine.createVertexBuffer(vb);
  43995. var triCount = vbSize - 1;
  43996. var ib = new Float32Array(triCount * 3);
  43997. for (var i = 0; i < triCount; i++) {
  43998. ib[i * 3 + 0] = 0;
  43999. ib[i * 3 + 2] = i + 1;
  44000. ib[i * 3 + 1] = i + 2;
  44001. }
  44002. ib[triCount * 3 - 2] = 1;
  44003. renderCache.fillIB = engine.createIndexBuffer(ib);
  44004. renderCache.fillIndicesCount = triCount * 3;
  44005. // 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
  44006. var ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_FILLPARTID, ["index"], true);
  44007. if (ei) {
  44008. renderCache.effectFillInstanced = engine.createEffect({ vertex: "ellipse2d", fragment: "ellipse2d" }, ei.attributes, ei.uniforms, [], ei.defines, null);
  44009. }
  44010. // Get the non instanced version
  44011. ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_FILLPARTID, ["index"], false);
  44012. renderCache.effectFill = engine.createEffect({ vertex: "ellipse2d", fragment: "ellipse2d" }, ei.attributes, ei.uniforms, [], ei.defines, null);
  44013. }
  44014. // Need to create WebGL resource for border part?
  44015. if (this.border) {
  44016. var vbSize = this.subdivisions * 2;
  44017. var vb = new Float32Array(vbSize);
  44018. for (var i = 0; i < vbSize; i++) {
  44019. vb[i] = i;
  44020. }
  44021. renderCache.borderVB = engine.createVertexBuffer(vb);
  44022. var triCount = vbSize;
  44023. var rs = triCount / 2;
  44024. var ib = new Float32Array(triCount * 3);
  44025. for (var i = 0; i < rs; i++) {
  44026. var r0 = i;
  44027. var r1 = (i + 1) % rs;
  44028. ib[i * 6 + 0] = rs + r1;
  44029. ib[i * 6 + 1] = rs + r0;
  44030. ib[i * 6 + 2] = r0;
  44031. ib[i * 6 + 3] = r1;
  44032. ib[i * 6 + 4] = rs + r1;
  44033. ib[i * 6 + 5] = r0;
  44034. }
  44035. renderCache.borderIB = engine.createIndexBuffer(ib);
  44036. renderCache.borderIndicesCount = (triCount * 3);
  44037. // 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
  44038. var ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, ["index"], true);
  44039. if (ei) {
  44040. renderCache.effectBorderInstanced = engine.createEffect("ellipse2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  44041. }
  44042. // Get the non instanced version
  44043. ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, ["index"], false);
  44044. renderCache.effectBorder = engine.createEffect("ellipse2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  44045. }
  44046. return renderCache;
  44047. };
  44048. Ellipse2D.prototype.createInstanceDataParts = function () {
  44049. var res = new Array();
  44050. if (this.border) {
  44051. res.push(new Ellipse2DInstanceData(BABYLON.Shape2D.SHAPE2D_BORDERPARTID));
  44052. }
  44053. if (this.fill) {
  44054. res.push(new Ellipse2DInstanceData(BABYLON.Shape2D.SHAPE2D_FILLPARTID));
  44055. }
  44056. return res;
  44057. };
  44058. Ellipse2D.prototype.refreshInstanceDataPart = function (part) {
  44059. if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
  44060. return false;
  44061. }
  44062. if (part.id === BABYLON.Shape2D.SHAPE2D_BORDERPARTID) {
  44063. var d = part;
  44064. var size = this.actualSize;
  44065. d.properties = new BABYLON.Vector3(size.width, size.height, this.subdivisions);
  44066. }
  44067. else if (part.id === BABYLON.Shape2D.SHAPE2D_FILLPARTID) {
  44068. var d = part;
  44069. var size = this.actualSize;
  44070. d.properties = new BABYLON.Vector3(size.width, size.height, this.subdivisions);
  44071. }
  44072. return true;
  44073. };
  44074. __decorate([
  44075. BABYLON.instanceLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 1, function (pi) { return Ellipse2D.acutalSizeProperty = pi; }, false, true)
  44076. ], Ellipse2D.prototype, "actualSize", null);
  44077. __decorate([
  44078. BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 2, function (pi) { return Ellipse2D.subdivisionsProperty = pi; })
  44079. ], Ellipse2D.prototype, "subdivisions", null);
  44080. Ellipse2D = __decorate([
  44081. BABYLON.className("Ellipse2D")
  44082. ], Ellipse2D);
  44083. return Ellipse2D;
  44084. }(BABYLON.Shape2D));
  44085. BABYLON.Ellipse2D = Ellipse2D;
  44086. })(BABYLON || (BABYLON = {}));
  44087. var BABYLON;
  44088. (function (BABYLON) {
  44089. var Sprite2DRenderCache = (function (_super) {
  44090. __extends(Sprite2DRenderCache, _super);
  44091. function Sprite2DRenderCache() {
  44092. _super.apply(this, arguments);
  44093. this.effectsReady = false;
  44094. this.vb = null;
  44095. this.ib = null;
  44096. this.instancingAttributes = null;
  44097. this.texture = null;
  44098. this.effect = null;
  44099. this.effectInstanced = null;
  44100. }
  44101. Sprite2DRenderCache.prototype.render = function (instanceInfo, context) {
  44102. // Do nothing if the shader is still loading/preparing
  44103. if (!this.effectsReady) {
  44104. if ((this.effect && (!this.effect.isReady() || (this.effectInstanced && !this.effectInstanced.isReady())))) {
  44105. return false;
  44106. }
  44107. this.effectsReady = true;
  44108. }
  44109. // Compute the offset locations of the attributes in the vertex shader that will be mapped to the instance buffer data
  44110. var canvas = instanceInfo.owner.owner;
  44111. var engine = canvas.engine;
  44112. var cur = engine.getAlphaMode();
  44113. var effect = context.useInstancing ? this.effectInstanced : this.effect;
  44114. engine.enableEffect(effect);
  44115. effect.setTexture("diffuseSampler", this.texture);
  44116. engine.bindBuffersDirectly(this.vb, this.ib, [1], 4, effect);
  44117. if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
  44118. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  44119. }
  44120. var pid = context.groupInfoPartData[0];
  44121. if (context.useInstancing) {
  44122. if (!this.instancingAttributes) {
  44123. this.instancingAttributes = this.loadInstancingAttributes(Sprite2D.SPRITE2D_MAINPARTID, effect);
  44124. }
  44125. var glBuffer = context.instancedBuffers ? context.instancedBuffers[0] : pid._partBuffer;
  44126. var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
  44127. canvas._addDrawCallCount(1, context.renderMode);
  44128. engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingAttributes);
  44129. engine.draw(true, 0, 6, count);
  44130. engine.unbindInstanceAttributes();
  44131. }
  44132. else {
  44133. canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
  44134. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  44135. this.setupUniforms(effect, 0, pid._partData, i);
  44136. engine.draw(true, 0, 6);
  44137. }
  44138. }
  44139. engine.setAlphaMode(cur);
  44140. return true;
  44141. };
  44142. Sprite2DRenderCache.prototype.dispose = function () {
  44143. if (!_super.prototype.dispose.call(this)) {
  44144. return false;
  44145. }
  44146. if (this.vb) {
  44147. this._engine._releaseBuffer(this.vb);
  44148. this.vb = null;
  44149. }
  44150. if (this.ib) {
  44151. this._engine._releaseBuffer(this.ib);
  44152. this.ib = null;
  44153. }
  44154. if (this.texture) {
  44155. this.texture.dispose();
  44156. this.texture = null;
  44157. }
  44158. if (this.effect) {
  44159. this._engine._releaseEffect(this.effect);
  44160. this.effect = null;
  44161. }
  44162. if (this.effectInstanced) {
  44163. this._engine._releaseEffect(this.effectInstanced);
  44164. this.effectInstanced = null;
  44165. }
  44166. return true;
  44167. };
  44168. return Sprite2DRenderCache;
  44169. }(BABYLON.ModelRenderCache));
  44170. BABYLON.Sprite2DRenderCache = Sprite2DRenderCache;
  44171. var Sprite2DInstanceData = (function (_super) {
  44172. __extends(Sprite2DInstanceData, _super);
  44173. function Sprite2DInstanceData(partId) {
  44174. _super.call(this, partId, 1);
  44175. }
  44176. Object.defineProperty(Sprite2DInstanceData.prototype, "topLeftUV", {
  44177. get: function () {
  44178. return null;
  44179. },
  44180. enumerable: true,
  44181. configurable: true
  44182. });
  44183. Object.defineProperty(Sprite2DInstanceData.prototype, "sizeUV", {
  44184. get: function () {
  44185. return null;
  44186. },
  44187. enumerable: true,
  44188. configurable: true
  44189. });
  44190. Object.defineProperty(Sprite2DInstanceData.prototype, "textureSize", {
  44191. get: function () {
  44192. return null;
  44193. },
  44194. enumerable: true,
  44195. configurable: true
  44196. });
  44197. Object.defineProperty(Sprite2DInstanceData.prototype, "properties", {
  44198. // 3 floats being:
  44199. // - x: frame number to display
  44200. // - y: invertY setting
  44201. // - z: alignToPixel setting
  44202. get: function () {
  44203. return null;
  44204. },
  44205. enumerable: true,
  44206. configurable: true
  44207. });
  44208. __decorate([
  44209. BABYLON.instanceData()
  44210. ], Sprite2DInstanceData.prototype, "topLeftUV", null);
  44211. __decorate([
  44212. BABYLON.instanceData()
  44213. ], Sprite2DInstanceData.prototype, "sizeUV", null);
  44214. __decorate([
  44215. BABYLON.instanceData()
  44216. ], Sprite2DInstanceData.prototype, "textureSize", null);
  44217. __decorate([
  44218. BABYLON.instanceData()
  44219. ], Sprite2DInstanceData.prototype, "properties", null);
  44220. return Sprite2DInstanceData;
  44221. }(BABYLON.InstanceDataBase));
  44222. BABYLON.Sprite2DInstanceData = Sprite2DInstanceData;
  44223. var Sprite2D = (function (_super) {
  44224. __extends(Sprite2D, _super);
  44225. /**
  44226. * Create an 2D Sprite primitive
  44227. * @param texture the texture that stores the sprite to render
  44228. * @param settings a combination of settings, possible ones are
  44229. * - 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)
  44230. * - children: an array of direct children
  44231. * - id a text identifier, for information purpose
  44232. * - position: the X & Y positions relative to its parent. Alternatively the x and y properties can be set. Default is [0;0]
  44233. * - rotation: the initial rotation (in radian) of the primitive. default is 0
  44234. * - scale: the initial scale of the primitive. default is 1
  44235. * - opacity: set the overall opacity of the primitive, 1 to be opaque (default), less than 1 to be transparent.
  44236. * - origin: define the normalized origin point location, default [0.5;0.5]
  44237. * - spriteSize: the size of the sprite (in pixels), if null the size of the given texture will be used, default is null.
  44238. * - spriteLocation: the location (in pixels) in the texture of the top/left corner of the Sprite to display, default is null (0,0)
  44239. * - invertY: if true the texture Y will be inverted, default is false.
  44240. * - 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.
  44241. * - isVisible: true if the sprite must be visible, false for hidden. Default is true.
  44242. * - childrenFlatZOrder: if true all the children (direct and indirect) will share the same Z-Order. Use this when there's a lot of children which don't overlap. The drawing order IS NOT GUARANTED!
  44243. * - marginTop: top margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44244. * - marginLeft: left margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44245. * - marginRight: right margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44246. * - marginBottom: bottom margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44247. * - margin: top, left, right and bottom margin formatted as a single string (see PrimitiveThickness.fromString)
  44248. * - marginHAlignment: one value of the PrimitiveAlignment type's static properties
  44249. * - marginVAlignment: one value of the PrimitiveAlignment type's static properties
  44250. * - marginAlignment: a string defining the alignment, see PrimitiveAlignment.fromString
  44251. * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44252. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44253. * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44254. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44255. * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
  44256. */
  44257. function Sprite2D(texture, settings) {
  44258. var _this = this;
  44259. if (!settings) {
  44260. settings = {};
  44261. }
  44262. _super.call(this, settings);
  44263. this.texture = texture;
  44264. this.texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  44265. this.texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  44266. this.size = settings.spriteSize;
  44267. this.spriteLocation = settings.spriteLocation || new BABYLON.Vector2(0, 0);
  44268. this.spriteFrame = 0;
  44269. this.invertY = (settings.invertY == null) ? false : settings.invertY;
  44270. this.alignToPixel = (settings.alignToPixel == null) ? true : settings.alignToPixel;
  44271. this.isAlphaTest = true;
  44272. if (settings.spriteSize == null || !texture.isReady()) {
  44273. if (texture.isReady()) {
  44274. this.size = texture.getSize();
  44275. }
  44276. else {
  44277. texture.onLoadObservable.add(function () {
  44278. if (settings.spriteSize == null) {
  44279. _this.size = texture.getSize();
  44280. }
  44281. _this._positioningDirty();
  44282. });
  44283. }
  44284. }
  44285. }
  44286. Object.defineProperty(Sprite2D.prototype, "texture", {
  44287. get: function () {
  44288. return this._texture;
  44289. },
  44290. set: function (value) {
  44291. this._texture = value;
  44292. },
  44293. enumerable: true,
  44294. configurable: true
  44295. });
  44296. Object.defineProperty(Sprite2D.prototype, "actualSize", {
  44297. get: function () {
  44298. if (this._actualSize) {
  44299. return this._actualSize;
  44300. }
  44301. return this.size;
  44302. },
  44303. set: function (value) {
  44304. this._actualSize = value;
  44305. },
  44306. enumerable: true,
  44307. configurable: true
  44308. });
  44309. Object.defineProperty(Sprite2D.prototype, "spriteLocation", {
  44310. get: function () {
  44311. return this._location;
  44312. },
  44313. set: function (value) {
  44314. this._location = value;
  44315. },
  44316. enumerable: true,
  44317. configurable: true
  44318. });
  44319. Object.defineProperty(Sprite2D.prototype, "spriteFrame", {
  44320. get: function () {
  44321. return this._spriteFrame;
  44322. },
  44323. set: function (value) {
  44324. this._spriteFrame = value;
  44325. },
  44326. enumerable: true,
  44327. configurable: true
  44328. });
  44329. Object.defineProperty(Sprite2D.prototype, "invertY", {
  44330. get: function () {
  44331. return this._invertY;
  44332. },
  44333. set: function (value) {
  44334. this._invertY = value;
  44335. },
  44336. enumerable: true,
  44337. configurable: true
  44338. });
  44339. Object.defineProperty(Sprite2D.prototype, "alignToPixel", {
  44340. /**
  44341. * Get/set if the sprite rendering should be aligned to the target rendering device pixel or not
  44342. */
  44343. get: function () {
  44344. return this._alignToPixel;
  44345. },
  44346. set: function (value) {
  44347. this._alignToPixel = value;
  44348. },
  44349. enumerable: true,
  44350. configurable: true
  44351. });
  44352. Sprite2D.prototype.updateLevelBoundingInfo = function () {
  44353. BABYLON.BoundingInfo2D.CreateFromSizeToRef(this.size, this._levelBoundingInfo);
  44354. };
  44355. /**
  44356. * Get the animatable array (see http://doc.babylonjs.com/tutorials/Animations)
  44357. */
  44358. Sprite2D.prototype.getAnimatables = function () {
  44359. var res = new Array();
  44360. if (this.texture && this.texture.animations && this.texture.animations.length > 0) {
  44361. res.push(this.texture);
  44362. }
  44363. return res;
  44364. };
  44365. Sprite2D.prototype.levelIntersect = function (intersectInfo) {
  44366. // 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
  44367. return true;
  44368. };
  44369. Sprite2D._createCachedCanvasSprite = function (owner, texture, size, pos) {
  44370. var sprite = new Sprite2D(texture, { parent: owner, id: "__cachedCanvasSprite__", position: BABYLON.Vector2.Zero(), origin: BABYLON.Vector2.Zero(), spriteSize: size, spriteLocation: pos, alignToPixel: true });
  44371. return sprite;
  44372. };
  44373. Sprite2D.prototype.createModelRenderCache = function (modelKey) {
  44374. var renderCache = new Sprite2DRenderCache(this.owner.engine, modelKey);
  44375. return renderCache;
  44376. };
  44377. Sprite2D.prototype.setupModelRenderCache = function (modelRenderCache) {
  44378. var renderCache = modelRenderCache;
  44379. var engine = this.owner.engine;
  44380. var vb = new Float32Array(4);
  44381. for (var i = 0; i < 4; i++) {
  44382. vb[i] = i;
  44383. }
  44384. renderCache.vb = engine.createVertexBuffer(vb);
  44385. var ib = new Float32Array(6);
  44386. ib[0] = 0;
  44387. ib[1] = 2;
  44388. ib[2] = 1;
  44389. ib[3] = 0;
  44390. ib[4] = 3;
  44391. ib[5] = 2;
  44392. renderCache.ib = engine.createIndexBuffer(ib);
  44393. renderCache.texture = this.texture;
  44394. // 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
  44395. var ei = this.getDataPartEffectInfo(Sprite2D.SPRITE2D_MAINPARTID, ["index"], true);
  44396. if (ei) {
  44397. renderCache.effectInstanced = engine.createEffect("sprite2d", ei.attributes, ei.uniforms, ["diffuseSampler"], ei.defines, null);
  44398. }
  44399. ei = this.getDataPartEffectInfo(Sprite2D.SPRITE2D_MAINPARTID, ["index"], false);
  44400. renderCache.effect = engine.createEffect("sprite2d", ei.attributes, ei.uniforms, ["diffuseSampler"], ei.defines, null);
  44401. return renderCache;
  44402. };
  44403. Sprite2D.prototype.createInstanceDataParts = function () {
  44404. return [new Sprite2DInstanceData(Sprite2D.SPRITE2D_MAINPARTID)];
  44405. };
  44406. Sprite2D.prototype.beforeRefreshForLayoutConstruction = function (part) {
  44407. Sprite2D.layoutConstructMode = true;
  44408. };
  44409. // if obj contains something, we restore the _text property
  44410. Sprite2D.prototype.afterRefreshForLayoutConstruction = function (part, obj) {
  44411. Sprite2D.layoutConstructMode = false;
  44412. };
  44413. Sprite2D.prototype.refreshInstanceDataPart = function (part) {
  44414. if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
  44415. return false;
  44416. }
  44417. if (!this.texture.isReady() && !Sprite2D.layoutConstructMode) {
  44418. return false;
  44419. }
  44420. if (part.id === Sprite2D.SPRITE2D_MAINPARTID) {
  44421. var d = this._instanceDataParts[0];
  44422. if (Sprite2D.layoutConstructMode) {
  44423. d.topLeftUV = BABYLON.Vector2.Zero();
  44424. d.sizeUV = BABYLON.Vector2.Zero();
  44425. d.properties = BABYLON.Vector3.Zero();
  44426. d.textureSize = BABYLON.Vector2.Zero();
  44427. }
  44428. else {
  44429. var ts = this.texture.getBaseSize();
  44430. var sl = this.spriteLocation;
  44431. var ss = this.actualSize;
  44432. d.topLeftUV = new BABYLON.Vector2(sl.x / ts.width, sl.y / ts.height);
  44433. var suv = new BABYLON.Vector2(ss.width / ts.width, ss.height / ts.height);
  44434. d.sizeUV = suv;
  44435. Sprite2D._prop.x = this.spriteFrame;
  44436. Sprite2D._prop.y = this.invertY ? 1 : 0;
  44437. Sprite2D._prop.z = this.alignToPixel ? 1 : 0;
  44438. d.properties = Sprite2D._prop;
  44439. d.textureSize = new BABYLON.Vector2(ts.width, ts.height);
  44440. }
  44441. }
  44442. return true;
  44443. };
  44444. Sprite2D.SPRITE2D_MAINPARTID = 1;
  44445. Sprite2D._prop = BABYLON.Vector3.Zero();
  44446. Sprite2D.layoutConstructMode = false;
  44447. __decorate([
  44448. BABYLON.modelLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 1, function (pi) { return Sprite2D.textureProperty = pi; })
  44449. ], Sprite2D.prototype, "texture", null);
  44450. __decorate([
  44451. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 2, function (pi) { return Sprite2D.actualSizeProperty = pi; }, false, true)
  44452. ], Sprite2D.prototype, "actualSize", null);
  44453. __decorate([
  44454. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 3, function (pi) { return Sprite2D.spriteLocationProperty = pi; })
  44455. ], Sprite2D.prototype, "spriteLocation", null);
  44456. __decorate([
  44457. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 4, function (pi) { return Sprite2D.spriteFrameProperty = pi; })
  44458. ], Sprite2D.prototype, "spriteFrame", null);
  44459. __decorate([
  44460. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 5, function (pi) { return Sprite2D.invertYProperty = pi; })
  44461. ], Sprite2D.prototype, "invertY", null);
  44462. Sprite2D = __decorate([
  44463. BABYLON.className("Sprite2D")
  44464. ], Sprite2D);
  44465. return Sprite2D;
  44466. }(BABYLON.RenderablePrim2D));
  44467. BABYLON.Sprite2D = Sprite2D;
  44468. })(BABYLON || (BABYLON = {}));
  44469. var BABYLON;
  44470. (function (BABYLON) {
  44471. var Text2DRenderCache = (function (_super) {
  44472. __extends(Text2DRenderCache, _super);
  44473. function Text2DRenderCache() {
  44474. _super.apply(this, arguments);
  44475. this.effectsReady = false;
  44476. this.vb = null;
  44477. this.ib = null;
  44478. this.instancingAttributes = null;
  44479. this.fontTexture = null;
  44480. this.effect = null;
  44481. this.effectInstanced = null;
  44482. }
  44483. Text2DRenderCache.prototype.render = function (instanceInfo, context) {
  44484. // Do nothing if the shader is still loading/preparing
  44485. if (!this.effectsReady) {
  44486. if ((this.effect && (!this.effect.isReady() || (this.effectInstanced && !this.effectInstanced.isReady())))) {
  44487. return false;
  44488. }
  44489. this.effectsReady = true;
  44490. }
  44491. var canvas = instanceInfo.owner.owner;
  44492. var engine = canvas.engine;
  44493. this.fontTexture.update();
  44494. var effect = context.useInstancing ? this.effectInstanced : this.effect;
  44495. engine.enableEffect(effect);
  44496. effect.setTexture("diffuseSampler", this.fontTexture);
  44497. engine.bindBuffersDirectly(this.vb, this.ib, [1], 4, effect);
  44498. var curAlphaMode = engine.getAlphaMode();
  44499. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE, true);
  44500. var pid = context.groupInfoPartData[0];
  44501. if (context.useInstancing) {
  44502. if (!this.instancingAttributes) {
  44503. this.instancingAttributes = this.loadInstancingAttributes(Text2D.TEXT2D_MAINPARTID, effect);
  44504. }
  44505. var glBuffer = context.instancedBuffers ? context.instancedBuffers[0] : pid._partBuffer;
  44506. var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
  44507. canvas._addDrawCallCount(1, context.renderMode);
  44508. engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingAttributes);
  44509. engine.draw(true, 0, 6, count);
  44510. engine.unbindInstanceAttributes();
  44511. }
  44512. else {
  44513. canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
  44514. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  44515. this.setupUniforms(effect, 0, pid._partData, i);
  44516. engine.draw(true, 0, 6);
  44517. }
  44518. }
  44519. engine.setAlphaMode(curAlphaMode);
  44520. return true;
  44521. };
  44522. Text2DRenderCache.prototype.dispose = function () {
  44523. if (!_super.prototype.dispose.call(this)) {
  44524. return false;
  44525. }
  44526. if (this.vb) {
  44527. this._engine._releaseBuffer(this.vb);
  44528. this.vb = null;
  44529. }
  44530. if (this.ib) {
  44531. this._engine._releaseBuffer(this.ib);
  44532. this.ib = null;
  44533. }
  44534. if (this.fontTexture) {
  44535. this.fontTexture.dispose();
  44536. this.fontTexture = null;
  44537. }
  44538. if (this.effect) {
  44539. this._engine._releaseEffect(this.effect);
  44540. this.effect = null;
  44541. }
  44542. if (this.effectInstanced) {
  44543. this._engine._releaseEffect(this.effectInstanced);
  44544. this.effectInstanced = null;
  44545. }
  44546. return true;
  44547. };
  44548. return Text2DRenderCache;
  44549. }(BABYLON.ModelRenderCache));
  44550. BABYLON.Text2DRenderCache = Text2DRenderCache;
  44551. var Text2DInstanceData = (function (_super) {
  44552. __extends(Text2DInstanceData, _super);
  44553. function Text2DInstanceData(partId, dataElementCount) {
  44554. _super.call(this, partId, dataElementCount);
  44555. }
  44556. Object.defineProperty(Text2DInstanceData.prototype, "topLeftUV", {
  44557. get: function () {
  44558. return null;
  44559. },
  44560. enumerable: true,
  44561. configurable: true
  44562. });
  44563. Object.defineProperty(Text2DInstanceData.prototype, "sizeUV", {
  44564. get: function () {
  44565. return null;
  44566. },
  44567. enumerable: true,
  44568. configurable: true
  44569. });
  44570. Object.defineProperty(Text2DInstanceData.prototype, "textureSize", {
  44571. get: function () {
  44572. return null;
  44573. },
  44574. enumerable: true,
  44575. configurable: true
  44576. });
  44577. Object.defineProperty(Text2DInstanceData.prototype, "color", {
  44578. get: function () {
  44579. return null;
  44580. },
  44581. enumerable: true,
  44582. configurable: true
  44583. });
  44584. Object.defineProperty(Text2DInstanceData.prototype, "superSampleFactor", {
  44585. get: function () {
  44586. return null;
  44587. },
  44588. enumerable: true,
  44589. configurable: true
  44590. });
  44591. __decorate([
  44592. BABYLON.instanceData()
  44593. ], Text2DInstanceData.prototype, "topLeftUV", null);
  44594. __decorate([
  44595. BABYLON.instanceData()
  44596. ], Text2DInstanceData.prototype, "sizeUV", null);
  44597. __decorate([
  44598. BABYLON.instanceData()
  44599. ], Text2DInstanceData.prototype, "textureSize", null);
  44600. __decorate([
  44601. BABYLON.instanceData()
  44602. ], Text2DInstanceData.prototype, "color", null);
  44603. __decorate([
  44604. BABYLON.instanceData()
  44605. ], Text2DInstanceData.prototype, "superSampleFactor", null);
  44606. return Text2DInstanceData;
  44607. }(BABYLON.InstanceDataBase));
  44608. BABYLON.Text2DInstanceData = Text2DInstanceData;
  44609. var Text2D = (function (_super) {
  44610. __extends(Text2D, _super);
  44611. /**
  44612. * Create a Text primitive
  44613. * @param text the text to display
  44614. * @param settings a combination of settings, possible ones are
  44615. * - 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)
  44616. * - children: an array of direct children
  44617. * - id a text identifier, for information purpose
  44618. * - position: the X & Y positions relative to its parent. Alternatively the x and y properties can be set. Default is [0;0]
  44619. * - rotation: the initial rotation (in radian) of the primitive. default is 0
  44620. * - scale: the initial scale of the primitive. default is 1
  44621. * - opacity: set the overall opacity of the primitive, 1 to be opaque (default), less than 1 to be transparent.
  44622. * - origin: define the normalized origin point location, default [0.5;0.5]
  44623. * - fontName: the name/size/style of the font to use, following the CSS notation. Default is "12pt Arial".
  44624. * - 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.
  44625. * - defaultColor: the color by default to apply on each letter of the text to display, default is plain white.
  44626. * - areaSize: the size of the area in which to display the text, default is auto-fit from text content.
  44627. * - tabulationSize: number of space character to insert when a tabulation is encountered, default is 4
  44628. * - isVisible: true if the text must be visible, false for hidden. Default is true.
  44629. * - childrenFlatZOrder: if true all the children (direct and indirect) will share the same Z-Order. Use this when there's a lot of children which don't overlap. The drawing order IS NOT GUARANTED!
  44630. * - marginTop: top margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44631. * - marginLeft: left margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44632. * - marginRight: right margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44633. * - marginBottom: bottom margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44634. * - margin: top, left, right and bottom margin formatted as a single string (see PrimitiveThickness.fromString)
  44635. * - marginHAlignment: one value of the PrimitiveAlignment type's static properties
  44636. * - marginVAlignment: one value of the PrimitiveAlignment type's static properties
  44637. * - marginAlignment: a string defining the alignment, see PrimitiveAlignment.fromString
  44638. * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44639. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44640. * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44641. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44642. * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
  44643. */
  44644. function Text2D(text, settings) {
  44645. if (!settings) {
  44646. settings = {};
  44647. }
  44648. _super.call(this, settings);
  44649. this.fontName = (settings.fontName == null) ? "12pt Arial" : settings.fontName;
  44650. this._fontSuperSample = (settings.fontSuperSample != null && settings.fontSuperSample);
  44651. this.defaultFontColor = (settings.defaultFontColor == null) ? new BABYLON.Color4(1, 1, 1, 1) : settings.defaultFontColor;
  44652. this._tabulationSize = (settings.tabulationSize == null) ? 4 : settings.tabulationSize;
  44653. this._textSize = null;
  44654. this.text = text;
  44655. this.size = (settings.size == null) ? null : settings.size;
  44656. this.isTransparent = true;
  44657. }
  44658. Object.defineProperty(Text2D.prototype, "fontName", {
  44659. get: function () {
  44660. return this._fontName;
  44661. },
  44662. set: function (value) {
  44663. if (this._fontName) {
  44664. throw new Error("Font Name change is not supported right now.");
  44665. }
  44666. this._fontName = value;
  44667. },
  44668. enumerable: true,
  44669. configurable: true
  44670. });
  44671. Object.defineProperty(Text2D.prototype, "defaultFontColor", {
  44672. get: function () {
  44673. return this._defaultFontColor;
  44674. },
  44675. set: function (value) {
  44676. this._defaultFontColor = value;
  44677. },
  44678. enumerable: true,
  44679. configurable: true
  44680. });
  44681. Object.defineProperty(Text2D.prototype, "text", {
  44682. get: function () {
  44683. return this._text;
  44684. },
  44685. set: function (value) {
  44686. this._text = value;
  44687. this._textSize = null; // A change of text will reset the TextSize which will be recomputed next time it's used
  44688. this._size = null;
  44689. this._updateCharCount();
  44690. // Trigger a textSize to for a sizeChange if necessary, which is needed for layout to recompute
  44691. var s = this.textSize;
  44692. },
  44693. enumerable: true,
  44694. configurable: true
  44695. });
  44696. Object.defineProperty(Text2D.prototype, "size", {
  44697. get: function () {
  44698. if (this._size != null) {
  44699. return this._size;
  44700. }
  44701. return this.textSize;
  44702. },
  44703. set: function (value) {
  44704. this._size = value;
  44705. },
  44706. enumerable: true,
  44707. configurable: true
  44708. });
  44709. Object.defineProperty(Text2D.prototype, "actualSize", {
  44710. /**
  44711. * Get the actual size of the Text2D primitive
  44712. */
  44713. get: function () {
  44714. if (this._actualSize) {
  44715. return this._actualSize;
  44716. }
  44717. return this.size;
  44718. },
  44719. enumerable: true,
  44720. configurable: true
  44721. });
  44722. Object.defineProperty(Text2D.prototype, "textSize", {
  44723. /**
  44724. * Get the area that bounds the text associated to the primitive
  44725. */
  44726. get: function () {
  44727. if (!this._textSize) {
  44728. if (this.owner) {
  44729. var newSize = this.fontTexture.measureText(this._text, this._tabulationSize);
  44730. if (!newSize.equals(this._textSize)) {
  44731. this.onPrimitivePropertyDirty(BABYLON.Prim2DBase.sizeProperty.flagId);
  44732. this._positioningDirty();
  44733. }
  44734. this._textSize = newSize;
  44735. }
  44736. else {
  44737. return Text2D.nullSize;
  44738. }
  44739. }
  44740. return this._textSize;
  44741. },
  44742. enumerable: true,
  44743. configurable: true
  44744. });
  44745. Object.defineProperty(Text2D.prototype, "fontTexture", {
  44746. get: function () {
  44747. if (this._fontTexture) {
  44748. return this._fontTexture;
  44749. }
  44750. this._fontTexture = BABYLON.FontTexture.GetCachedFontTexture(this.owner.scene, this.fontName, this._fontSuperSample);
  44751. return this._fontTexture;
  44752. },
  44753. enumerable: true,
  44754. configurable: true
  44755. });
  44756. /**
  44757. * Dispose the primitive, remove it from its parent
  44758. */
  44759. Text2D.prototype.dispose = function () {
  44760. if (!_super.prototype.dispose.call(this)) {
  44761. return false;
  44762. }
  44763. if (this._fontTexture) {
  44764. BABYLON.FontTexture.ReleaseCachedFontTexture(this.owner.scene, this.fontName, this._fontSuperSample);
  44765. this._fontTexture = null;
  44766. }
  44767. return true;
  44768. };
  44769. Text2D.prototype.updateLevelBoundingInfo = function () {
  44770. BABYLON.BoundingInfo2D.CreateFromSizeToRef(this.actualSize, this._levelBoundingInfo);
  44771. };
  44772. Text2D.prototype.levelIntersect = function (intersectInfo) {
  44773. // 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...
  44774. return true;
  44775. };
  44776. Text2D.prototype.createModelRenderCache = function (modelKey) {
  44777. var renderCache = new Text2DRenderCache(this.owner.engine, modelKey);
  44778. return renderCache;
  44779. };
  44780. Text2D.prototype.setupModelRenderCache = function (modelRenderCache) {
  44781. var renderCache = modelRenderCache;
  44782. var engine = this.owner.engine;
  44783. renderCache.fontTexture = this.fontTexture;
  44784. var vb = new Float32Array(4);
  44785. for (var i = 0; i < 4; i++) {
  44786. vb[i] = i;
  44787. }
  44788. renderCache.vb = engine.createVertexBuffer(vb);
  44789. var ib = new Float32Array(6);
  44790. ib[0] = 0;
  44791. ib[1] = 2;
  44792. ib[2] = 1;
  44793. ib[3] = 0;
  44794. ib[4] = 3;
  44795. ib[5] = 2;
  44796. renderCache.ib = engine.createIndexBuffer(ib);
  44797. // 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
  44798. var ei = this.getDataPartEffectInfo(Text2D.TEXT2D_MAINPARTID, ["index"], true);
  44799. if (ei) {
  44800. renderCache.effectInstanced = engine.createEffect("text2d", ei.attributes, ei.uniforms, ["diffuseSampler"], ei.defines, null);
  44801. }
  44802. ei = this.getDataPartEffectInfo(Text2D.TEXT2D_MAINPARTID, ["index"], false);
  44803. renderCache.effect = engine.createEffect("text2d", ei.attributes, ei.uniforms, ["diffuseSampler"], ei.defines, null);
  44804. return renderCache;
  44805. };
  44806. Text2D.prototype.createInstanceDataParts = function () {
  44807. return [new Text2DInstanceData(Text2D.TEXT2D_MAINPARTID, this._charCount)];
  44808. };
  44809. // Looks like a hack!? Yes! Because that's what it is!
  44810. // 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
  44811. // 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)
  44812. Text2D.prototype.beforeRefreshForLayoutConstruction = function (part) {
  44813. if (!this._charCount) {
  44814. var curText = this._text;
  44815. this.text = "A";
  44816. return curText;
  44817. }
  44818. };
  44819. // if obj contains something, we restore the _text property
  44820. Text2D.prototype.afterRefreshForLayoutConstruction = function (part, obj) {
  44821. if (obj !== undefined) {
  44822. this.text = obj;
  44823. }
  44824. };
  44825. Text2D.prototype.refreshInstanceDataPart = function (part) {
  44826. if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
  44827. return false;
  44828. }
  44829. if (part.id === Text2D.TEXT2D_MAINPARTID) {
  44830. var d = part;
  44831. var texture = this.fontTexture;
  44832. var superSampleFactor = texture.isSuperSampled ? 0.5 : 1;
  44833. var ts = texture.getSize();
  44834. var offset = BABYLON.Vector2.Zero();
  44835. var lh = this.fontTexture.lineHeight;
  44836. 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
  44837. var charxpos = 0;
  44838. d.dataElementCount = this._charCount;
  44839. d.curElement = 0;
  44840. for (var _i = 0, _a = this.text; _i < _a.length; _i++) {
  44841. var char = _a[_i];
  44842. // Line feed
  44843. if (char === "\n") {
  44844. offset.x = 0;
  44845. offset.y -= texture.lineHeight;
  44846. }
  44847. // Tabulation ?
  44848. if (char === "\t") {
  44849. var nextPos = charxpos + this._tabulationSize;
  44850. nextPos = nextPos - (nextPos % this._tabulationSize);
  44851. offset.x += (nextPos - charxpos) * texture.spaceWidth;
  44852. charxpos = nextPos;
  44853. continue;
  44854. }
  44855. if (char < " ") {
  44856. continue;
  44857. }
  44858. this.updateInstanceDataPart(d, offset);
  44859. var ci = texture.getChar(char);
  44860. offset.x += ci.charWidth;
  44861. d.topLeftUV = ci.topLeftUV;
  44862. var suv = ci.bottomRightUV.subtract(ci.topLeftUV);
  44863. d.sizeUV = suv;
  44864. d.textureSize = new BABYLON.Vector2(ts.width, ts.height);
  44865. d.color = this.defaultFontColor;
  44866. d.superSampleFactor = superSampleFactor;
  44867. ++d.curElement;
  44868. }
  44869. }
  44870. return true;
  44871. };
  44872. Text2D.prototype._updateCharCount = function () {
  44873. var count = 0;
  44874. for (var _i = 0, _a = this._text; _i < _a.length; _i++) {
  44875. var char = _a[_i];
  44876. if (char === "\r" || char === "\n" || char === "\t" || char < " ") {
  44877. continue;
  44878. }
  44879. ++count;
  44880. }
  44881. this._charCount = count;
  44882. };
  44883. Text2D.TEXT2D_MAINPARTID = 1;
  44884. __decorate([
  44885. BABYLON.modelLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 1, function (pi) { return Text2D.fontProperty = pi; }, false, true)
  44886. ], Text2D.prototype, "fontName", null);
  44887. __decorate([
  44888. BABYLON.dynamicLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 2, function (pi) { return Text2D.defaultFontColorProperty = pi; })
  44889. ], Text2D.prototype, "defaultFontColor", null);
  44890. __decorate([
  44891. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 3, function (pi) { return Text2D.textProperty = pi; }, false, true)
  44892. ], Text2D.prototype, "text", null);
  44893. __decorate([
  44894. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 4, function (pi) { return Text2D.sizeProperty = pi; })
  44895. ], Text2D.prototype, "size", null);
  44896. Text2D = __decorate([
  44897. BABYLON.className("Text2D")
  44898. ], Text2D);
  44899. return Text2D;
  44900. }(BABYLON.RenderablePrim2D));
  44901. BABYLON.Text2D = Text2D;
  44902. })(BABYLON || (BABYLON = {}));
  44903. var BABYLON;
  44904. (function (BABYLON) {
  44905. var Lines2DRenderCache = (function (_super) {
  44906. __extends(Lines2DRenderCache, _super);
  44907. function Lines2DRenderCache(engine, modelKey) {
  44908. _super.call(this, engine, modelKey);
  44909. this.effectsReady = false;
  44910. this.fillVB = null;
  44911. this.fillIB = null;
  44912. this.fillIndicesCount = 0;
  44913. this.instancingFillAttributes = null;
  44914. this.effectFill = null;
  44915. this.effectFillInstanced = null;
  44916. this.borderVB = null;
  44917. this.borderIB = null;
  44918. this.borderIndicesCount = 0;
  44919. this.instancingBorderAttributes = null;
  44920. this.effectBorder = null;
  44921. this.effectBorderInstanced = null;
  44922. }
  44923. Lines2DRenderCache.prototype.render = function (instanceInfo, context) {
  44924. // Do nothing if the shader is still loading/preparing
  44925. if (!this.effectsReady) {
  44926. if ((this.effectFill && (!this.effectFill.isReady() || (this.effectFillInstanced && !this.effectFillInstanced.isReady()))) ||
  44927. (this.effectBorder && (!this.effectBorder.isReady() || (this.effectBorderInstanced && !this.effectBorderInstanced.isReady())))) {
  44928. return false;
  44929. }
  44930. this.effectsReady = true;
  44931. }
  44932. var canvas = instanceInfo.owner.owner;
  44933. var engine = canvas.engine;
  44934. var depthFunction = 0;
  44935. if (this.effectFill && this.effectBorder) {
  44936. depthFunction = engine.getDepthFunction();
  44937. engine.setDepthFunctionToLessOrEqual();
  44938. }
  44939. var curAlphaMode = engine.getAlphaMode();
  44940. if (this.effectFill) {
  44941. var partIndex = instanceInfo.partIndexFromId.get(BABYLON.Shape2D.SHAPE2D_FILLPARTID.toString());
  44942. var pid = context.groupInfoPartData[partIndex];
  44943. if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
  44944. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  44945. }
  44946. var effect = context.useInstancing ? this.effectFillInstanced : this.effectFill;
  44947. engine.enableEffect(effect);
  44948. engine.bindBuffersDirectly(this.fillVB, this.fillIB, [2], 2 * 4, effect);
  44949. if (context.useInstancing) {
  44950. if (!this.instancingFillAttributes) {
  44951. this.instancingFillAttributes = this.loadInstancingAttributes(BABYLON.Shape2D.SHAPE2D_FILLPARTID, effect);
  44952. }
  44953. var glBuffer = context.instancedBuffers ? context.instancedBuffers[partIndex] : pid._partBuffer;
  44954. var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
  44955. canvas._addDrawCallCount(1, context.renderMode);
  44956. engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingFillAttributes);
  44957. engine.draw(true, 0, this.fillIndicesCount, count);
  44958. engine.unbindInstanceAttributes();
  44959. }
  44960. else {
  44961. canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
  44962. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  44963. this.setupUniforms(effect, partIndex, pid._partData, i);
  44964. engine.draw(true, 0, this.fillIndicesCount);
  44965. }
  44966. }
  44967. }
  44968. if (this.effectBorder) {
  44969. var partIndex = instanceInfo.partIndexFromId.get(BABYLON.Shape2D.SHAPE2D_BORDERPARTID.toString());
  44970. var pid = context.groupInfoPartData[partIndex];
  44971. if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
  44972. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  44973. }
  44974. var effect = context.useInstancing ? this.effectBorderInstanced : this.effectBorder;
  44975. engine.enableEffect(effect);
  44976. engine.bindBuffersDirectly(this.borderVB, this.borderIB, [2], 2 * 4, effect);
  44977. if (context.useInstancing) {
  44978. if (!this.instancingBorderAttributes) {
  44979. this.instancingBorderAttributes = this.loadInstancingAttributes(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, effect);
  44980. }
  44981. var glBuffer = context.instancedBuffers ? context.instancedBuffers[partIndex] : pid._partBuffer;
  44982. var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
  44983. canvas._addDrawCallCount(1, context.renderMode);
  44984. engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingBorderAttributes);
  44985. engine.draw(true, 0, this.borderIndicesCount, count);
  44986. engine.unbindInstanceAttributes();
  44987. }
  44988. else {
  44989. canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
  44990. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  44991. this.setupUniforms(effect, partIndex, pid._partData, i);
  44992. engine.draw(true, 0, this.borderIndicesCount);
  44993. }
  44994. }
  44995. }
  44996. engine.setAlphaMode(curAlphaMode);
  44997. if (this.effectFill && this.effectBorder) {
  44998. engine.setDepthFunction(depthFunction);
  44999. }
  45000. return true;
  45001. };
  45002. Lines2DRenderCache.prototype.dispose = function () {
  45003. if (!_super.prototype.dispose.call(this)) {
  45004. return false;
  45005. }
  45006. if (this.fillVB) {
  45007. this._engine._releaseBuffer(this.fillVB);
  45008. this.fillVB = null;
  45009. }
  45010. if (this.fillIB) {
  45011. this._engine._releaseBuffer(this.fillIB);
  45012. this.fillIB = null;
  45013. }
  45014. if (this.effectFill) {
  45015. this._engine._releaseEffect(this.effectFill);
  45016. this.effectFill = null;
  45017. }
  45018. if (this.effectFillInstanced) {
  45019. this._engine._releaseEffect(this.effectFillInstanced);
  45020. this.effectFillInstanced = null;
  45021. }
  45022. if (this.borderVB) {
  45023. this._engine._releaseBuffer(this.borderVB);
  45024. this.borderVB = null;
  45025. }
  45026. if (this.borderIB) {
  45027. this._engine._releaseBuffer(this.borderIB);
  45028. this.borderIB = null;
  45029. }
  45030. if (this.effectBorder) {
  45031. this._engine._releaseEffect(this.effectBorder);
  45032. this.effectBorder = null;
  45033. }
  45034. if (this.effectBorderInstanced) {
  45035. this._engine._releaseEffect(this.effectBorderInstanced);
  45036. this.effectBorderInstanced = null;
  45037. }
  45038. return true;
  45039. };
  45040. return Lines2DRenderCache;
  45041. }(BABYLON.ModelRenderCache));
  45042. BABYLON.Lines2DRenderCache = Lines2DRenderCache;
  45043. var Lines2DInstanceData = (function (_super) {
  45044. __extends(Lines2DInstanceData, _super);
  45045. function Lines2DInstanceData(partId) {
  45046. _super.call(this, partId, 1);
  45047. }
  45048. Object.defineProperty(Lines2DInstanceData.prototype, "boundingMin", {
  45049. get: function () {
  45050. return null;
  45051. },
  45052. enumerable: true,
  45053. configurable: true
  45054. });
  45055. Object.defineProperty(Lines2DInstanceData.prototype, "boundingMax", {
  45056. get: function () {
  45057. return null;
  45058. },
  45059. enumerable: true,
  45060. configurable: true
  45061. });
  45062. __decorate([
  45063. BABYLON.instanceData(BABYLON.Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT)
  45064. ], Lines2DInstanceData.prototype, "boundingMin", null);
  45065. __decorate([
  45066. BABYLON.instanceData(BABYLON.Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT)
  45067. ], Lines2DInstanceData.prototype, "boundingMax", null);
  45068. return Lines2DInstanceData;
  45069. }(BABYLON.Shape2DInstanceData));
  45070. BABYLON.Lines2DInstanceData = Lines2DInstanceData;
  45071. var Lines2D = (function (_super) {
  45072. __extends(Lines2D, _super);
  45073. /**
  45074. * Create an 2D Lines Shape primitive. The defined lines may be opened or closed (see below)
  45075. * @param points an array that describe the points to use to draw the line, must contain at least two entries.
  45076. * @param settings a combination of settings, possible ones are
  45077. * - 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)
  45078. * - children: an array of direct children
  45079. * - id a text identifier, for information purpose
  45080. * - position: the X & Y positions relative to its parent. Alternatively the x and y properties can be set. Default is [0;0]
  45081. * - rotation: the initial rotation (in radian) of the primitive. default is 0
  45082. * - scale: the initial scale of the primitive. default is 1
  45083. * - opacity: set the overall opacity of the primitive, 1 to be opaque (default), less than 1 to be transparent.
  45084. * - origin: define the normalized origin point location, default [0.5;0.5]
  45085. * - 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.
  45086. * - 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.
  45087. * - 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.
  45088. * - 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.
  45089. * - 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)
  45090. * - 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)
  45091. * - borderThickness: the thickness of the drawn border, default is 1.
  45092. * - isVisible: true if the primitive must be visible, false for hidden. Default is true.
  45093. * - childrenFlatZOrder: if true all the children (direct and indirect) will share the same Z-Order. Use this when there's a lot of children which don't overlap. The drawing order IS NOT GUARANTED!
  45094. * - marginTop: top margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  45095. * - marginLeft: left margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  45096. * - marginRight: right margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  45097. * - marginBottom: bottom margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  45098. * - margin: top, left, right and bottom margin formatted as a single string (see PrimitiveThickness.fromString)
  45099. * - marginHAlignment: one value of the PrimitiveAlignment type's static properties
  45100. * - marginVAlignment: one value of the PrimitiveAlignment type's static properties
  45101. * - marginAlignment: a string defining the alignment, see PrimitiveAlignment.fromString
  45102. * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  45103. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  45104. * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  45105. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  45106. * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
  45107. */
  45108. function Lines2D(points, settings) {
  45109. if (!settings) {
  45110. settings = {};
  45111. }
  45112. _super.call(this, settings);
  45113. this._fillVB = null;
  45114. this._fillIB = null;
  45115. this._borderVB = null;
  45116. this._borderIB = null;
  45117. this._size = BABYLON.Size.Zero();
  45118. this._boundingMin = null;
  45119. this._boundingMax = null;
  45120. var fillThickness = (settings.fillThickness == null) ? 1 : settings.fillThickness;
  45121. var startCap = (settings.startCap == null) ? 0 : settings.startCap;
  45122. var endCap = (settings.endCap == null) ? 0 : settings.endCap;
  45123. var closed = (settings.closed == null) ? false : settings.closed;
  45124. this.points = points;
  45125. this.fillThickness = fillThickness;
  45126. this.startCap = startCap;
  45127. this.endCap = endCap;
  45128. this.closed = closed;
  45129. }
  45130. Object.defineProperty(Lines2D, "NoCap", {
  45131. /**
  45132. * No Cap to apply on the extremity
  45133. */
  45134. get: function () { return Lines2D._noCap; },
  45135. enumerable: true,
  45136. configurable: true
  45137. });
  45138. Object.defineProperty(Lines2D, "RoundCap", {
  45139. /**
  45140. * A round cap, will use the line thickness as diameter
  45141. */
  45142. get: function () { return Lines2D._roundCap; },
  45143. enumerable: true,
  45144. configurable: true
  45145. });
  45146. Object.defineProperty(Lines2D, "TriangleCap", {
  45147. /**
  45148. * Creates a triangle at the extremity.
  45149. */
  45150. get: function () { return Lines2D._triangleCap; },
  45151. enumerable: true,
  45152. configurable: true
  45153. });
  45154. Object.defineProperty(Lines2D, "SquareAnchorCap", {
  45155. /**
  45156. * Creates a Square anchor at the extremity, the square size is twice the thickness of the line
  45157. */
  45158. get: function () { return Lines2D._squareAnchorCap; },
  45159. enumerable: true,
  45160. configurable: true
  45161. });
  45162. Object.defineProperty(Lines2D, "RoundAnchorCap", {
  45163. /**
  45164. * Creates a round anchor at the extremity, the diameter is twice the thickness of the line
  45165. */
  45166. get: function () { return Lines2D._roundAnchorCap; },
  45167. enumerable: true,
  45168. configurable: true
  45169. });
  45170. Object.defineProperty(Lines2D, "DiamondAnchorCap", {
  45171. /**
  45172. * Creates a diamond anchor at the extremity.
  45173. */
  45174. get: function () { return Lines2D._diamondAnchorCap; },
  45175. enumerable: true,
  45176. configurable: true
  45177. });
  45178. Object.defineProperty(Lines2D, "ArrowCap", {
  45179. /**
  45180. * Creates an arrow anchor at the extremity. the arrow base size is twice the thickness of the line
  45181. */
  45182. get: function () { return Lines2D._arrowCap; },
  45183. enumerable: true,
  45184. configurable: true
  45185. });
  45186. Object.defineProperty(Lines2D.prototype, "points", {
  45187. get: function () {
  45188. return this._points;
  45189. },
  45190. set: function (value) {
  45191. this._points = value;
  45192. this._boundingBoxDirty();
  45193. },
  45194. enumerable: true,
  45195. configurable: true
  45196. });
  45197. Object.defineProperty(Lines2D.prototype, "fillThickness", {
  45198. get: function () {
  45199. return this._fillThickness;
  45200. },
  45201. set: function (value) {
  45202. this._fillThickness = value;
  45203. },
  45204. enumerable: true,
  45205. configurable: true
  45206. });
  45207. Object.defineProperty(Lines2D.prototype, "closed", {
  45208. get: function () {
  45209. return this._closed;
  45210. },
  45211. set: function (value) {
  45212. this._closed = value;
  45213. },
  45214. enumerable: true,
  45215. configurable: true
  45216. });
  45217. Object.defineProperty(Lines2D.prototype, "startCap", {
  45218. get: function () {
  45219. return this._startCap;
  45220. },
  45221. set: function (value) {
  45222. this._startCap = value;
  45223. },
  45224. enumerable: true,
  45225. configurable: true
  45226. });
  45227. Object.defineProperty(Lines2D.prototype, "endCap", {
  45228. get: function () {
  45229. return this._endCap;
  45230. },
  45231. set: function (value) {
  45232. this._endCap = value;
  45233. },
  45234. enumerable: true,
  45235. configurable: true
  45236. });
  45237. Lines2D.prototype.levelIntersect = function (intersectInfo) {
  45238. var _this = this;
  45239. if (this._contour == null) {
  45240. this._computeLines2D();
  45241. }
  45242. var pl = this.points.length;
  45243. var l = this.closed ? pl + 1 : pl;
  45244. var p = intersectInfo._localPickPosition;
  45245. this.transformPointWithOriginToRef(this._contour[0], null, Lines2D._prevA);
  45246. this.transformPointWithOriginToRef(this._contour[1], null, Lines2D._prevB);
  45247. for (var i = 1; i < l; i++) {
  45248. this.transformPointWithOriginToRef(this._contour[(i % pl) * 2 + 0], null, Lines2D._curA);
  45249. this.transformPointWithOriginToRef(this._contour[(i % pl) * 2 + 1], null, Lines2D._curB);
  45250. if (BABYLON.Vector2.PointInTriangle(p, Lines2D._prevA, Lines2D._prevB, Lines2D._curA)) {
  45251. return true;
  45252. }
  45253. if (BABYLON.Vector2.PointInTriangle(p, Lines2D._curA, Lines2D._prevB, Lines2D._curB)) {
  45254. return true;
  45255. }
  45256. Lines2D._prevA.x = Lines2D._curA.x;
  45257. Lines2D._prevA.y = Lines2D._curA.y;
  45258. Lines2D._prevB.x = Lines2D._curB.x;
  45259. Lines2D._prevB.y = Lines2D._curB.y;
  45260. }
  45261. var capIntersect = function (tri, points) {
  45262. var l = tri.length;
  45263. for (var i = 0; i < l; i += 3) {
  45264. Lines2D._curA.x = points[tri[i + 0] * 2 + 0];
  45265. Lines2D._curA.y = points[tri[i + 0] * 2 + 1];
  45266. _this.transformPointWithOriginToRef(Lines2D._curA, null, Lines2D._curB);
  45267. Lines2D._curA.x = points[tri[i + 1] * 2 + 0];
  45268. Lines2D._curA.y = points[tri[i + 1] * 2 + 1];
  45269. _this.transformPointWithOriginToRef(Lines2D._curA, null, Lines2D._prevA);
  45270. Lines2D._curA.x = points[tri[i + 2] * 2 + 0];
  45271. Lines2D._curA.y = points[tri[i + 2] * 2 + 1];
  45272. _this.transformPointWithOriginToRef(Lines2D._curA, null, Lines2D._prevB);
  45273. if (BABYLON.Vector2.PointInTriangle(p, Lines2D._prevA, Lines2D._prevB, Lines2D._curB)) {
  45274. return true;
  45275. }
  45276. }
  45277. return false;
  45278. };
  45279. if (this._startCapTriIndices) {
  45280. if (capIntersect(this._startCapTriIndices, this._startCapContour)) {
  45281. return true;
  45282. }
  45283. if (capIntersect(this._endCapTriIndices, this._endCapContour)) {
  45284. return true;
  45285. }
  45286. }
  45287. return false;
  45288. };
  45289. Object.defineProperty(Lines2D.prototype, "boundingMin", {
  45290. get: function () {
  45291. if (!this._boundingMin) {
  45292. this._computeLines2D();
  45293. }
  45294. return this._boundingMin;
  45295. },
  45296. enumerable: true,
  45297. configurable: true
  45298. });
  45299. Object.defineProperty(Lines2D.prototype, "boundingMax", {
  45300. get: function () {
  45301. if (!this._boundingMax) {
  45302. this._computeLines2D();
  45303. }
  45304. return this._boundingMax;
  45305. },
  45306. enumerable: true,
  45307. configurable: true
  45308. });
  45309. Lines2D.prototype.getUsedShaderCategories = function (dataPart) {
  45310. var res = _super.prototype.getUsedShaderCategories.call(this, dataPart);
  45311. // Remove the BORDER category, we don't use it in the VertexShader
  45312. var i = res.indexOf(BABYLON.Shape2D.SHAPE2D_CATEGORY_BORDER);
  45313. if (i !== -1) {
  45314. res.splice(i, 1);
  45315. }
  45316. return res;
  45317. };
  45318. Lines2D.prototype.updateLevelBoundingInfo = function () {
  45319. if (!this._boundingMin) {
  45320. this._computeLines2D();
  45321. }
  45322. BABYLON.BoundingInfo2D.CreateFromMinMaxToRef(this._boundingMin.x, this._boundingMax.x, this._boundingMin.y, this._boundingMax.y, this._levelBoundingInfo);
  45323. };
  45324. Lines2D.prototype.createModelRenderCache = function (modelKey) {
  45325. var renderCache = new Lines2DRenderCache(this.owner.engine, modelKey);
  45326. return renderCache;
  45327. };
  45328. ///////////////////////////////////////////////////////////////////////////////////
  45329. // Methods for Lines building
  45330. Lines2D.prototype._perp = function (v, res) {
  45331. res.x = v.y;
  45332. res.y = -v.x;
  45333. };
  45334. ;
  45335. Lines2D.prototype._direction = function (a, b, res) {
  45336. a.subtractToRef(b, res);
  45337. res.normalize();
  45338. };
  45339. Lines2D.prototype._computeMiter = function (tangent, miter, a, b) {
  45340. a.addToRef(b, tangent);
  45341. tangent.normalize();
  45342. miter.x = -tangent.y;
  45343. miter.y = tangent.x;
  45344. Lines2D._miterTps.x = -a.y;
  45345. Lines2D._miterTps.y = a.x;
  45346. return 1 / BABYLON.Vector2.Dot(miter, Lines2D._miterTps);
  45347. };
  45348. Lines2D.prototype._intersect = function (x1, y1, x2, y2, x3, y3, x4, y4) {
  45349. var d = (x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4);
  45350. if (d === 0)
  45351. return false;
  45352. var xi = ((x3 - x4) * (x1 * y2 - y1 * x2) - (x1 - x2) * (x3 * y4 - y3 * x4)) / d; // Intersection point is xi/yi, just in case...
  45353. //let yi = ((y3 - y4) * (x1 * y2 - y1 * x2) - (y1 - y2) * (x3 * y4 - y3 * x4)) / d; // That's why I left it commented
  45354. if (xi < Math.min(x1, x2) || xi > Math.max(x1, x2))
  45355. return false;
  45356. if (xi < Math.min(x3, x4) || xi > Math.max(x3, x4))
  45357. return false;
  45358. return true;
  45359. };
  45360. Lines2D.prototype._updateMinMax = function (array, offset) {
  45361. if (offset >= array.length) {
  45362. return;
  45363. }
  45364. this._boundingMin.x = Math.min(this._boundingMin.x, array[offset]);
  45365. this._boundingMax.x = Math.max(this._boundingMax.x, array[offset]);
  45366. this._boundingMin.y = Math.min(this._boundingMin.y, array[offset + 1]);
  45367. this._boundingMax.y = Math.max(this._boundingMax.y, array[offset + 1]);
  45368. };
  45369. Lines2D.prototype._store = function (array, contour, index, max, p, n, halfThickness, borderThickness, detectFlip) {
  45370. var borderMode = borderThickness != null && !isNaN(borderThickness);
  45371. var off = index * (borderMode ? 8 : 4);
  45372. // 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)
  45373. if (off >= array.length) {
  45374. return;
  45375. }
  45376. // Store start/end normal, we need it for the cap construction
  45377. if (index === 0) {
  45378. this._perp(n, Lines2D._startDir);
  45379. }
  45380. else if (index === max - 1) {
  45381. this._perp(n, Lines2D._endDir);
  45382. Lines2D._endDir.x *= -1;
  45383. Lines2D._endDir.y *= -1;
  45384. }
  45385. var swap = false;
  45386. array[off + 0] = p.x + n.x * halfThickness;
  45387. array[off + 1] = p.y + n.y * halfThickness;
  45388. array[off + 2] = p.x + n.x * -halfThickness;
  45389. array[off + 3] = p.y + n.y * -halfThickness;
  45390. this._updateMinMax(array, off);
  45391. this._updateMinMax(array, off + 2);
  45392. // If an index is given we check if the two segments formed between [index+0;detectFlip+0] and [index+2;detectFlip+2] intersect themselves.
  45393. // 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
  45394. if (detectFlip !== undefined) {
  45395. // Flip if intersect
  45396. var flipOff = detectFlip * (borderMode ? 8 : 4);
  45397. 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])) {
  45398. swap = true;
  45399. var tps = array[off + 0];
  45400. array[off + 0] = array[off + 2];
  45401. array[off + 2] = tps;
  45402. tps = array[off + 1];
  45403. array[off + 1] = array[off + 3];
  45404. array[off + 3] = tps;
  45405. }
  45406. }
  45407. if (borderMode) {
  45408. var t = halfThickness + borderThickness;
  45409. array[off + 4] = p.x + n.x * (swap ? -t : t);
  45410. array[off + 5] = p.y + n.y * (swap ? -t : t);
  45411. array[off + 6] = p.x + n.x * (swap ? t : -t);
  45412. array[off + 7] = p.y + n.y * (swap ? t : -t);
  45413. this._updateMinMax(array, off + 4);
  45414. this._updateMinMax(array, off + 6);
  45415. }
  45416. if (contour) {
  45417. off += borderMode ? 4 : 0;
  45418. contour.push(new BABYLON.Vector2(array[off + 0], array[off + 1]));
  45419. contour.push(new BABYLON.Vector2(array[off + 2], array[off + 3]));
  45420. }
  45421. };
  45422. Lines2D.prototype._getCapSize = function (type, border) {
  45423. if (border === void 0) { border = false; }
  45424. var sd = Lines2D._roundCapSubDiv;
  45425. // If no array given, we call this to get the size
  45426. var vbsize = 0, ibsize = 0;
  45427. switch (type) {
  45428. case Lines2D.NoCap:
  45429. {
  45430. // If the line is not close and we're computing border, we add the size to generate the edge border
  45431. if (!this.closed && border) {
  45432. vbsize = 4;
  45433. ibsize = 6;
  45434. }
  45435. else {
  45436. vbsize = ibsize = 0;
  45437. }
  45438. break;
  45439. }
  45440. case Lines2D.RoundCap:
  45441. {
  45442. if (border) {
  45443. vbsize = sd;
  45444. ibsize = (sd - 2) * 3;
  45445. }
  45446. else {
  45447. vbsize = (sd / 2) + 1;
  45448. ibsize = (sd / 2) * 3;
  45449. }
  45450. break;
  45451. }
  45452. case Lines2D.ArrowCap:
  45453. {
  45454. if (border) {
  45455. vbsize = 12;
  45456. ibsize = 24;
  45457. }
  45458. else {
  45459. vbsize = 3;
  45460. ibsize = 3;
  45461. }
  45462. break;
  45463. }
  45464. case Lines2D.TriangleCap:
  45465. {
  45466. if (border) {
  45467. vbsize = 6;
  45468. ibsize = 12;
  45469. }
  45470. else {
  45471. vbsize = 3;
  45472. ibsize = 3;
  45473. }
  45474. break;
  45475. }
  45476. case Lines2D.DiamondAnchorCap:
  45477. {
  45478. if (border) {
  45479. vbsize = 10;
  45480. ibsize = 24;
  45481. }
  45482. else {
  45483. vbsize = 5;
  45484. ibsize = 9;
  45485. }
  45486. break;
  45487. }
  45488. case Lines2D.SquareAnchorCap:
  45489. {
  45490. if (border) {
  45491. vbsize = 12;
  45492. ibsize = 30;
  45493. }
  45494. else {
  45495. vbsize = 4;
  45496. ibsize = 6;
  45497. }
  45498. break;
  45499. }
  45500. case Lines2D.RoundAnchorCap:
  45501. {
  45502. if (border) {
  45503. vbsize = sd * 2;
  45504. ibsize = (sd - 1) * 6;
  45505. }
  45506. else {
  45507. vbsize = sd + 1;
  45508. ibsize = (sd + 1) * 3;
  45509. }
  45510. break;
  45511. }
  45512. }
  45513. return { vbsize: vbsize * 2, ibsize: ibsize };
  45514. };
  45515. Lines2D.prototype._storeVertex = function (vb, baseOffset, index, basePos, rotation, vertex, contour) {
  45516. var c = Math.cos(rotation);
  45517. var s = Math.sin(rotation);
  45518. Lines2D._tpsV.x = (c * vertex.x) + (-s * vertex.y) + basePos.x;
  45519. Lines2D._tpsV.y = (s * vertex.x) + (c * vertex.y) + basePos.y;
  45520. var offset = baseOffset + (index * 2);
  45521. vb[offset + 0] = Lines2D._tpsV.x;
  45522. vb[offset + 1] = Lines2D._tpsV.y;
  45523. if (contour) {
  45524. contour.push(Lines2D._tpsV.x);
  45525. contour.push(Lines2D._tpsV.y);
  45526. }
  45527. this._updateMinMax(vb, offset);
  45528. return (baseOffset + index * 2) / 2;
  45529. };
  45530. Lines2D.prototype._storeIndex = function (ib, baseOffset, index, vertexIndex) {
  45531. ib[baseOffset + index] = vertexIndex;
  45532. };
  45533. Lines2D.prototype._buildCap = function (vb, vbi, ib, ibi, pos, thickness, borderThickness, type, capDir, contour) {
  45534. // 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
  45535. var sd = Lines2D._roundCapSubDiv;
  45536. var dir = new BABYLON.Vector2(1, 0);
  45537. var angle = Math.atan2(capDir.y, capDir.x) - Math.atan2(dir.y, dir.x);
  45538. var ht = thickness / 2;
  45539. var t = thickness;
  45540. var borderMode = borderThickness != null;
  45541. var bt = borderThickness;
  45542. switch (type) {
  45543. case Lines2D.NoCap:
  45544. if (borderMode && !this.closed) {
  45545. var vi = 0;
  45546. var ii = 0;
  45547. var v1 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, ht + bt), contour);
  45548. var v2 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(bt, ht + bt), contour);
  45549. var v3 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(bt, -(ht + bt)), contour);
  45550. var v4 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, -(ht + bt)), contour);
  45551. this._storeIndex(ib, ibi, ii++, v1);
  45552. this._storeIndex(ib, ibi, ii++, v2);
  45553. this._storeIndex(ib, ibi, ii++, v3);
  45554. this._storeIndex(ib, ibi, ii++, v1);
  45555. this._storeIndex(ib, ibi, ii++, v3);
  45556. this._storeIndex(ib, ibi, ii++, v4);
  45557. }
  45558. break;
  45559. case Lines2D.ArrowCap:
  45560. ht *= 2;
  45561. case Lines2D.TriangleCap:
  45562. {
  45563. if (borderMode) {
  45564. var f = type === Lines2D.TriangleCap ? bt : Math.sqrt(bt * bt * 2);
  45565. var v1 = this._storeVertex(vb, vbi, 0, pos, angle, new BABYLON.Vector2(0, ht), null);
  45566. var v2 = this._storeVertex(vb, vbi, 1, pos, angle, new BABYLON.Vector2(ht, 0), null);
  45567. var v3 = this._storeVertex(vb, vbi, 2, pos, angle, new BABYLON.Vector2(0, -ht), null);
  45568. var v4 = this._storeVertex(vb, vbi, 3, pos, angle, new BABYLON.Vector2(0, ht + f), contour);
  45569. var v5 = this._storeVertex(vb, vbi, 4, pos, angle, new BABYLON.Vector2(ht + f, 0), contour);
  45570. var v6 = this._storeVertex(vb, vbi, 5, pos, angle, new BABYLON.Vector2(0, -(ht + f)), contour);
  45571. var ii = 0;
  45572. this._storeIndex(ib, ibi, ii++, v1);
  45573. this._storeIndex(ib, ibi, ii++, v4);
  45574. this._storeIndex(ib, ibi, ii++, v5);
  45575. this._storeIndex(ib, ibi, ii++, v1);
  45576. this._storeIndex(ib, ibi, ii++, v5);
  45577. this._storeIndex(ib, ibi, ii++, v2);
  45578. this._storeIndex(ib, ibi, ii++, v6);
  45579. this._storeIndex(ib, ibi, ii++, v3);
  45580. this._storeIndex(ib, ibi, ii++, v2);
  45581. this._storeIndex(ib, ibi, ii++, v6);
  45582. this._storeIndex(ib, ibi, ii++, v2);
  45583. this._storeIndex(ib, ibi, ii++, v5);
  45584. if (type === Lines2D.ArrowCap) {
  45585. var rht = thickness / 2;
  45586. var v10 = this._storeVertex(vb, vbi, 9, pos, angle, new BABYLON.Vector2(0, -(rht + bt)), null);
  45587. var v12 = this._storeVertex(vb, vbi, 11, pos, angle, new BABYLON.Vector2(-bt, -(ht + f)), contour);
  45588. var v11 = this._storeVertex(vb, vbi, 10, pos, angle, new BABYLON.Vector2(-bt, -(rht + bt)), contour);
  45589. var v7 = this._storeVertex(vb, vbi, 6, pos, angle, new BABYLON.Vector2(0, rht + bt), null);
  45590. var v8 = this._storeVertex(vb, vbi, 7, pos, angle, new BABYLON.Vector2(-bt, rht + bt), contour);
  45591. var v9 = this._storeVertex(vb, vbi, 8, pos, angle, new BABYLON.Vector2(-bt, ht + f), contour);
  45592. this._storeIndex(ib, ibi, ii++, v7);
  45593. this._storeIndex(ib, ibi, ii++, v8);
  45594. this._storeIndex(ib, ibi, ii++, v9);
  45595. this._storeIndex(ib, ibi, ii++, v7);
  45596. this._storeIndex(ib, ibi, ii++, v9);
  45597. this._storeIndex(ib, ibi, ii++, v4);
  45598. this._storeIndex(ib, ibi, ii++, v10);
  45599. this._storeIndex(ib, ibi, ii++, v12);
  45600. this._storeIndex(ib, ibi, ii++, v11);
  45601. this._storeIndex(ib, ibi, ii++, v10);
  45602. this._storeIndex(ib, ibi, ii++, v6);
  45603. this._storeIndex(ib, ibi, ii++, v12);
  45604. }
  45605. }
  45606. else {
  45607. var v1 = this._storeVertex(vb, vbi, 0, pos, angle, new BABYLON.Vector2(0, ht), contour);
  45608. var v2 = this._storeVertex(vb, vbi, 1, pos, angle, new BABYLON.Vector2(ht, 0), contour);
  45609. var v3 = this._storeVertex(vb, vbi, 2, pos, angle, new BABYLON.Vector2(0, -ht), contour);
  45610. this._storeIndex(ib, ibi, 0, v1);
  45611. this._storeIndex(ib, ibi, 1, v2);
  45612. this._storeIndex(ib, ibi, 2, v3);
  45613. }
  45614. break;
  45615. }
  45616. case Lines2D.RoundCap:
  45617. {
  45618. if (borderMode) {
  45619. var curA = -Math.PI / 2;
  45620. var incA = Math.PI / (sd / 2 - 1);
  45621. var ii = 0;
  45622. for (var i = 0; i < (sd / 2); i++) {
  45623. var v1 = this._storeVertex(vb, vbi, i * 2 + 0, pos, angle, new BABYLON.Vector2(Math.cos(curA) * ht, Math.sin(curA) * ht), null);
  45624. 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);
  45625. if (i > 0) {
  45626. this._storeIndex(ib, ibi, ii++, v1 - 2);
  45627. this._storeIndex(ib, ibi, ii++, v2 - 2);
  45628. this._storeIndex(ib, ibi, ii++, v2);
  45629. this._storeIndex(ib, ibi, ii++, v1 - 2);
  45630. this._storeIndex(ib, ibi, ii++, v2);
  45631. this._storeIndex(ib, ibi, ii++, v1);
  45632. }
  45633. curA += incA;
  45634. }
  45635. }
  45636. else {
  45637. var c = this._storeVertex(vb, vbi, 0, pos, angle, new BABYLON.Vector2(0, 0), null);
  45638. var curA = -Math.PI / 2;
  45639. var incA = Math.PI / (sd / 2 - 1);
  45640. this._storeVertex(vb, vbi, 1, pos, angle, new BABYLON.Vector2(Math.cos(curA) * ht, Math.sin(curA) * ht), null);
  45641. curA += incA;
  45642. for (var i = 1; i < (sd / 2); i++) {
  45643. var v2 = this._storeVertex(vb, vbi, i + 1, pos, angle, new BABYLON.Vector2(Math.cos(curA) * ht, Math.sin(curA) * ht), contour);
  45644. this._storeIndex(ib, ibi, i * 3 + 0, c);
  45645. this._storeIndex(ib, ibi, i * 3 + 1, v2 - 1);
  45646. this._storeIndex(ib, ibi, i * 3 + 2, v2);
  45647. curA += incA;
  45648. }
  45649. }
  45650. break;
  45651. }
  45652. case Lines2D.SquareAnchorCap:
  45653. {
  45654. var vi = 0;
  45655. var c = borderMode ? null : contour;
  45656. var v1 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, t), c);
  45657. var v2 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(t * 2, t), c);
  45658. var v3 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(t * 2, -t), c);
  45659. var v4 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, -t), c);
  45660. if (borderMode) {
  45661. var v5 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, ht + bt), null);
  45662. var v6 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(-bt, ht + bt), contour);
  45663. var v7 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(-bt, t + bt), contour);
  45664. var v8 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(t * 2 + bt, t + bt), contour);
  45665. var v9 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(t * 2 + bt, -(t + bt)), contour);
  45666. var v10 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(-bt, -(t + bt)), contour);
  45667. var v11 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(-bt, -(ht + bt)), contour);
  45668. var v12 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, -(ht + bt)), null);
  45669. var ii = 0;
  45670. this._storeIndex(ib, ibi, ii++, v6);
  45671. this._storeIndex(ib, ibi, ii++, v1);
  45672. this._storeIndex(ib, ibi, ii++, v5);
  45673. this._storeIndex(ib, ibi, ii++, v6);
  45674. this._storeIndex(ib, ibi, ii++, v7);
  45675. this._storeIndex(ib, ibi, ii++, v1);
  45676. this._storeIndex(ib, ibi, ii++, v1);
  45677. this._storeIndex(ib, ibi, ii++, v7);
  45678. this._storeIndex(ib, ibi, ii++, v8);
  45679. this._storeIndex(ib, ibi, ii++, v1);
  45680. this._storeIndex(ib, ibi, ii++, v8);
  45681. this._storeIndex(ib, ibi, ii++, v2);
  45682. this._storeIndex(ib, ibi, ii++, v2);
  45683. this._storeIndex(ib, ibi, ii++, v8);
  45684. this._storeIndex(ib, ibi, ii++, v9);
  45685. this._storeIndex(ib, ibi, ii++, v2);
  45686. this._storeIndex(ib, ibi, ii++, v9);
  45687. this._storeIndex(ib, ibi, ii++, v3);
  45688. this._storeIndex(ib, ibi, ii++, v3);
  45689. this._storeIndex(ib, ibi, ii++, v9);
  45690. this._storeIndex(ib, ibi, ii++, v10);
  45691. this._storeIndex(ib, ibi, ii++, v3);
  45692. this._storeIndex(ib, ibi, ii++, v10);
  45693. this._storeIndex(ib, ibi, ii++, v4);
  45694. this._storeIndex(ib, ibi, ii++, v10);
  45695. this._storeIndex(ib, ibi, ii++, v11);
  45696. this._storeIndex(ib, ibi, ii++, v4);
  45697. this._storeIndex(ib, ibi, ii++, v11);
  45698. this._storeIndex(ib, ibi, ii++, v12);
  45699. this._storeIndex(ib, ibi, ii++, v4);
  45700. }
  45701. else {
  45702. this._storeIndex(ib, ibi, 0, v1);
  45703. this._storeIndex(ib, ibi, 1, v2);
  45704. this._storeIndex(ib, ibi, 2, v3);
  45705. this._storeIndex(ib, ibi, 3, v1);
  45706. this._storeIndex(ib, ibi, 4, v3);
  45707. this._storeIndex(ib, ibi, 5, v4);
  45708. }
  45709. break;
  45710. }
  45711. case Lines2D.RoundAnchorCap:
  45712. {
  45713. var cpos = Math.sqrt(t * t - ht * ht);
  45714. var center = new BABYLON.Vector2(cpos, 0);
  45715. var curA = BABYLON.Tools.ToRadians(-150);
  45716. var incA = BABYLON.Tools.ToRadians(300) / (sd - 1);
  45717. if (borderMode) {
  45718. var ii = 0;
  45719. for (var i = 0; i < sd; i++) {
  45720. var v1 = this._storeVertex(vb, vbi, i * 2 + 0, pos, angle, new BABYLON.Vector2(cpos + Math.cos(curA) * t, Math.sin(curA) * t), null);
  45721. 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);
  45722. if (i > 0) {
  45723. this._storeIndex(ib, ibi, ii++, v1 - 2);
  45724. this._storeIndex(ib, ibi, ii++, v2 - 2);
  45725. this._storeIndex(ib, ibi, ii++, v2);
  45726. this._storeIndex(ib, ibi, ii++, v1 - 2);
  45727. this._storeIndex(ib, ibi, ii++, v2);
  45728. this._storeIndex(ib, ibi, ii++, v1);
  45729. }
  45730. curA += incA;
  45731. }
  45732. }
  45733. else {
  45734. var c = this._storeVertex(vb, vbi, 0, pos, angle, center, null);
  45735. this._storeVertex(vb, vbi, 1, pos, angle, new BABYLON.Vector2(cpos + Math.cos(curA) * t, Math.sin(curA) * t), null);
  45736. curA += incA;
  45737. for (var i = 1; i < sd; i++) {
  45738. var v2 = this._storeVertex(vb, vbi, i + 1, pos, angle, new BABYLON.Vector2(cpos + Math.cos(curA) * t, Math.sin(curA) * t), contour);
  45739. this._storeIndex(ib, ibi, i * 3 + 0, c);
  45740. this._storeIndex(ib, ibi, i * 3 + 1, v2 - 1);
  45741. this._storeIndex(ib, ibi, i * 3 + 2, v2);
  45742. curA += incA;
  45743. }
  45744. this._storeIndex(ib, ibi, sd * 3 + 0, c);
  45745. this._storeIndex(ib, ibi, sd * 3 + 1, c + 1);
  45746. this._storeIndex(ib, ibi, sd * 3 + 2, c + sd);
  45747. }
  45748. break;
  45749. }
  45750. case Lines2D.DiamondAnchorCap:
  45751. {
  45752. var vi = 0;
  45753. var c = borderMode ? null : contour;
  45754. var v1 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, ht), c);
  45755. var v2 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(ht, t), c);
  45756. var v3 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(ht * 3, 0), c);
  45757. var v4 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(ht, -t), c);
  45758. var v5 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, -ht), c);
  45759. if (borderMode) {
  45760. var f = Math.sqrt(bt * bt * 2);
  45761. var v6 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(-f, ht), contour);
  45762. var v7 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(ht, t + f), contour);
  45763. var v8 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(ht * 3 + f, 0), contour);
  45764. var v9 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(ht, -(t + f)), contour);
  45765. var v10 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(-f, -ht), contour);
  45766. var ii = 0;
  45767. this._storeIndex(ib, ibi, ii++, v6);
  45768. this._storeIndex(ib, ibi, ii++, v7);
  45769. this._storeIndex(ib, ibi, ii++, v1);
  45770. this._storeIndex(ib, ibi, ii++, v1);
  45771. this._storeIndex(ib, ibi, ii++, v7);
  45772. this._storeIndex(ib, ibi, ii++, v2);
  45773. this._storeIndex(ib, ibi, ii++, v2);
  45774. this._storeIndex(ib, ibi, ii++, v7);
  45775. this._storeIndex(ib, ibi, ii++, v8);
  45776. this._storeIndex(ib, ibi, ii++, v2);
  45777. this._storeIndex(ib, ibi, ii++, v8);
  45778. this._storeIndex(ib, ibi, ii++, v3);
  45779. this._storeIndex(ib, ibi, ii++, v3);
  45780. this._storeIndex(ib, ibi, ii++, v8);
  45781. this._storeIndex(ib, ibi, ii++, v9);
  45782. this._storeIndex(ib, ibi, ii++, v3);
  45783. this._storeIndex(ib, ibi, ii++, v9);
  45784. this._storeIndex(ib, ibi, ii++, v4);
  45785. this._storeIndex(ib, ibi, ii++, v4);
  45786. this._storeIndex(ib, ibi, ii++, v9);
  45787. this._storeIndex(ib, ibi, ii++, v10);
  45788. this._storeIndex(ib, ibi, ii++, v4);
  45789. this._storeIndex(ib, ibi, ii++, v10);
  45790. this._storeIndex(ib, ibi, ii++, v5);
  45791. }
  45792. else {
  45793. this._storeIndex(ib, ibi, 0, v1);
  45794. this._storeIndex(ib, ibi, 1, v2);
  45795. this._storeIndex(ib, ibi, 2, v3);
  45796. this._storeIndex(ib, ibi, 3, v1);
  45797. this._storeIndex(ib, ibi, 4, v3);
  45798. this._storeIndex(ib, ibi, 5, v5);
  45799. this._storeIndex(ib, ibi, 6, v5);
  45800. this._storeIndex(ib, ibi, 7, v3);
  45801. this._storeIndex(ib, ibi, 8, v4);
  45802. }
  45803. break;
  45804. }
  45805. }
  45806. return null;
  45807. };
  45808. Lines2D.prototype._buildLine = function (vb, contour, ht, bt) {
  45809. var lineA = BABYLON.Vector2.Zero();
  45810. var lineB = BABYLON.Vector2.Zero();
  45811. var tangent = BABYLON.Vector2.Zero();
  45812. var miter = BABYLON.Vector2.Zero();
  45813. var curNormal = null;
  45814. if (this.closed) {
  45815. this.points.push(this.points[0]);
  45816. }
  45817. var total = this.points.length;
  45818. for (var i = 1; i < total; i++) {
  45819. var last = this.points[i - 1];
  45820. var cur = this.points[i];
  45821. var next = (i < (this.points.length - 1)) ? this.points[i + 1] : null;
  45822. this._direction(cur, last, lineA);
  45823. if (!curNormal) {
  45824. curNormal = BABYLON.Vector2.Zero();
  45825. this._perp(lineA, curNormal);
  45826. }
  45827. if (i === 1) {
  45828. this._store(vb, contour, 0, total, this.points[0], curNormal, ht, bt);
  45829. }
  45830. if (!next) {
  45831. this._perp(lineA, curNormal);
  45832. this._store(vb, contour, i, total, this.points[i], curNormal, ht, bt, i - 1);
  45833. }
  45834. else {
  45835. this._direction(next, cur, lineB);
  45836. var miterLen = this._computeMiter(tangent, miter, lineA, lineB);
  45837. this._store(vb, contour, i, total, this.points[i], miter, miterLen * ht, miterLen * bt, i - 1);
  45838. }
  45839. }
  45840. if (this.points.length > 2 && this.closed) {
  45841. var last2 = this.points[total - 2];
  45842. var cur2 = this.points[0];
  45843. var next2 = this.points[1];
  45844. this._direction(cur2, last2, lineA);
  45845. this._direction(next2, cur2, lineB);
  45846. this._perp(lineA, curNormal);
  45847. var miterLen2 = this._computeMiter(tangent, miter, lineA, lineB);
  45848. this._store(vb, null, 0, total, this.points[0], miter, miterLen2 * ht, miterLen2 * bt, 1);
  45849. // Patch contour
  45850. if (contour) {
  45851. var off = (bt == null) ? 0 : 4;
  45852. contour[0].x = vb[off + 0];
  45853. contour[0].y = vb[off + 1];
  45854. contour[1].x = vb[off + 2];
  45855. contour[1].y = vb[off + 3];
  45856. }
  45857. }
  45858. // Remove the point we added at the beginning
  45859. if (this.closed) {
  45860. this.points.splice(total - 1);
  45861. }
  45862. };
  45863. // Methods for Lines building
  45864. ///////////////////////////////////////////////////////////////////////////////////
  45865. Lines2D.prototype.setupModelRenderCache = function (modelRenderCache) {
  45866. var renderCache = modelRenderCache;
  45867. var engine = this.owner.engine;
  45868. if (this._fillVB === null) {
  45869. this._computeLines2D();
  45870. }
  45871. // Need to create WebGL resources for fill part?
  45872. if (this.fill) {
  45873. renderCache.fillVB = engine.createVertexBuffer(this._fillVB);
  45874. renderCache.fillIB = engine.createIndexBuffer(this._fillIB);
  45875. renderCache.fillIndicesCount = this._fillIB.length;
  45876. // 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
  45877. var ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_FILLPARTID, ["position"], true);
  45878. if (ei) {
  45879. renderCache.effectFillInstanced = engine.createEffect("lines2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  45880. }
  45881. // Get the non instanced version
  45882. ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_FILLPARTID, ["position"], false);
  45883. renderCache.effectFill = engine.createEffect("lines2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  45884. }
  45885. // Need to create WebGL resources for border part?
  45886. if (this.border) {
  45887. renderCache.borderVB = engine.createVertexBuffer(this._borderVB);
  45888. renderCache.borderIB = engine.createIndexBuffer(this._borderIB);
  45889. renderCache.borderIndicesCount = this._borderIB.length;
  45890. // 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
  45891. var ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, ["position"], true);
  45892. if (ei) {
  45893. renderCache.effectBorderInstanced = engine.createEffect({ vertex: "lines2d", fragment: "lines2d" }, ei.attributes, ei.uniforms, [], ei.defines, null);
  45894. }
  45895. // Get the non instanced version
  45896. ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, ["position"], false);
  45897. renderCache.effectBorder = engine.createEffect({ vertex: "lines2d", fragment: "lines2d" }, ei.attributes, ei.uniforms, [], ei.defines, null);
  45898. }
  45899. this._fillVB = null;
  45900. this._fillIB = null;
  45901. this._borderVB = null;
  45902. this._borderIB = null;
  45903. return renderCache;
  45904. };
  45905. Lines2D.prototype._computeLines2D = function () {
  45906. // Init min/max because their being computed here
  45907. this._boundingMin = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  45908. this._boundingMax = new BABYLON.Vector2(Number.MIN_VALUE, Number.MIN_VALUE);
  45909. var contour = new Array();
  45910. var startCapContour = new Array();
  45911. var endCapContour = new Array();
  45912. // Need to create WebGL resources for fill part?
  45913. if (this.fill) {
  45914. var startCapInfo = this._getCapSize(this.startCap);
  45915. var endCapInfo = this._getCapSize(this.endCap);
  45916. var count = this.points.length;
  45917. var vbSize = (count * 2 * 2) + startCapInfo.vbsize + endCapInfo.vbsize;
  45918. this._fillVB = new Float32Array(vbSize);
  45919. var vb = this._fillVB;
  45920. var ht = this.fillThickness / 2;
  45921. var total = this.points.length;
  45922. this._buildLine(vb, this.border ? null : contour, ht);
  45923. var max = total * 2;
  45924. var triCount = (count - (this.closed ? 0 : 1)) * 2;
  45925. this._fillIB = new Float32Array(triCount * 3 + startCapInfo.ibsize + endCapInfo.ibsize);
  45926. var ib = this._fillIB;
  45927. for (var i = 0; i < triCount; i += 2) {
  45928. ib[i * 3 + 0] = i + 0;
  45929. ib[i * 3 + 1] = i + 1;
  45930. ib[i * 3 + 2] = (i + 2) % max;
  45931. ib[i * 3 + 3] = i + 1;
  45932. ib[i * 3 + 4] = (i + 3) % max;
  45933. ib[i * 3 + 5] = (i + 2) % max;
  45934. }
  45935. this._buildCap(vb, count * 2 * 2, ib, triCount * 3, this.points[0], this.fillThickness, null, this.startCap, Lines2D._startDir, this.border ? null : startCapContour);
  45936. 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);
  45937. }
  45938. // Need to create WebGL resources for border part?
  45939. if (this.border) {
  45940. var startCapInfo = this._getCapSize(this.startCap, true);
  45941. var endCapInfo = this._getCapSize(this.endCap, true);
  45942. var count = this.points.length;
  45943. var vbSize = (count * 2 * 2 * 2) + startCapInfo.vbsize + endCapInfo.vbsize;
  45944. this._borderVB = new Float32Array(vbSize);
  45945. var vb = this._borderVB;
  45946. var ht = this.fillThickness / 2;
  45947. var bt = this.borderThickness;
  45948. var total = this.points.length;
  45949. this._buildLine(vb, contour, ht, bt);
  45950. var max = total * 2 * 2;
  45951. var triCount = (count - (this.closed ? 0 : 1)) * 2 * 2;
  45952. this._borderIB = new Float32Array(triCount * 3 + startCapInfo.ibsize + endCapInfo.ibsize);
  45953. var ib = this._borderIB;
  45954. for (var i = 0; i < triCount; i += 4) {
  45955. ib[i * 3 + 0] = i + 0;
  45956. ib[i * 3 + 1] = i + 2;
  45957. ib[i * 3 + 2] = (i + 6) % max;
  45958. ib[i * 3 + 3] = i + 0;
  45959. ib[i * 3 + 4] = (i + 6) % max;
  45960. ib[i * 3 + 5] = (i + 4) % max;
  45961. ib[i * 3 + 6] = i + 3;
  45962. ib[i * 3 + 7] = i + 1;
  45963. ib[i * 3 + 8] = (i + 5) % max;
  45964. ib[i * 3 + 9] = i + 3;
  45965. ib[i * 3 + 10] = (i + 5) % max;
  45966. ib[i * 3 + 11] = (i + 7) % max;
  45967. }
  45968. this._buildCap(vb, count * 2 * 2 * 2, ib, triCount * 3, this.points[0], this.fillThickness, this.borderThickness, this.startCap, Lines2D._startDir, startCapContour);
  45969. 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);
  45970. }
  45971. this._contour = contour;
  45972. if (startCapContour.length > 0) {
  45973. var startCapTri = Earcut.earcut(startCapContour, null, 2);
  45974. this._startCapTriIndices = startCapTri;
  45975. this._startCapContour = startCapContour;
  45976. }
  45977. if (endCapContour.length > 0) {
  45978. var endCapTri = Earcut.earcut(endCapContour, null, 2);
  45979. this._endCapContour = endCapContour;
  45980. this._endCapTriIndices = endCapTri;
  45981. }
  45982. var bs = this._boundingMax.subtract(this._boundingMin);
  45983. this._size.width = bs.x;
  45984. this._size.height = bs.y;
  45985. };
  45986. Object.defineProperty(Lines2D.prototype, "size", {
  45987. get: function () {
  45988. if (this._size == null) {
  45989. this._computeLines2D();
  45990. }
  45991. return this._size;
  45992. },
  45993. enumerable: true,
  45994. configurable: true
  45995. });
  45996. Lines2D.prototype.createInstanceDataParts = function () {
  45997. var res = new Array();
  45998. if (this.border) {
  45999. res.push(new Lines2DInstanceData(BABYLON.Shape2D.SHAPE2D_BORDERPARTID));
  46000. }
  46001. if (this.fill) {
  46002. res.push(new Lines2DInstanceData(BABYLON.Shape2D.SHAPE2D_FILLPARTID));
  46003. }
  46004. return res;
  46005. };
  46006. Lines2D.prototype.refreshInstanceDataPart = function (part) {
  46007. if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
  46008. return false;
  46009. }
  46010. if (part.id === BABYLON.Shape2D.SHAPE2D_BORDERPARTID) {
  46011. var d = part;
  46012. if (this.border instanceof BABYLON.GradientColorBrush2D) {
  46013. d.boundingMin = this.boundingMin;
  46014. d.boundingMax = this.boundingMax;
  46015. }
  46016. }
  46017. else if (part.id === BABYLON.Shape2D.SHAPE2D_FILLPARTID) {
  46018. var d = part;
  46019. if (this.fill instanceof BABYLON.GradientColorBrush2D) {
  46020. d.boundingMin = this.boundingMin;
  46021. d.boundingMax = this.boundingMax;
  46022. }
  46023. }
  46024. return true;
  46025. };
  46026. Lines2D._prevA = BABYLON.Vector2.Zero();
  46027. Lines2D._prevB = BABYLON.Vector2.Zero();
  46028. Lines2D._curA = BABYLON.Vector2.Zero();
  46029. Lines2D._curB = BABYLON.Vector2.Zero();
  46030. Lines2D._miterTps = BABYLON.Vector2.Zero();
  46031. Lines2D._startDir = BABYLON.Vector2.Zero();
  46032. Lines2D._endDir = BABYLON.Vector2.Zero();
  46033. Lines2D._tpsV = BABYLON.Vector2.Zero();
  46034. Lines2D._noCap = 0;
  46035. Lines2D._roundCap = 1;
  46036. Lines2D._triangleCap = 2;
  46037. Lines2D._squareAnchorCap = 3;
  46038. Lines2D._roundAnchorCap = 4;
  46039. Lines2D._diamondAnchorCap = 5;
  46040. Lines2D._arrowCap = 6;
  46041. Lines2D._roundCapSubDiv = 36;
  46042. __decorate([
  46043. BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 1, function (pi) { return Lines2D.pointsProperty = pi; })
  46044. ], Lines2D.prototype, "points", null);
  46045. __decorate([
  46046. BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 2, function (pi) { return Lines2D.fillThicknessProperty = pi; })
  46047. ], Lines2D.prototype, "fillThickness", null);
  46048. __decorate([
  46049. BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 3, function (pi) { return Lines2D.closedProperty = pi; })
  46050. ], Lines2D.prototype, "closed", null);
  46051. __decorate([
  46052. BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 4, function (pi) { return Lines2D.startCapProperty = pi; })
  46053. ], Lines2D.prototype, "startCap", null);
  46054. __decorate([
  46055. BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 5, function (pi) { return Lines2D.endCapProperty = pi; })
  46056. ], Lines2D.prototype, "endCap", null);
  46057. Lines2D = __decorate([
  46058. BABYLON.className("Lines2D")
  46059. ], Lines2D);
  46060. return Lines2D;
  46061. }(BABYLON.Shape2D));
  46062. BABYLON.Lines2D = Lines2D;
  46063. })(BABYLON || (BABYLON = {}));
  46064. var BABYLON;
  46065. (function (BABYLON) {
  46066. // This class contains data that lifetime is bounding to the Babylon Engine object
  46067. var Canvas2DEngineBoundData = (function () {
  46068. function Canvas2DEngineBoundData() {
  46069. this._modelCache = new BABYLON.StringDictionary();
  46070. }
  46071. Canvas2DEngineBoundData.prototype.GetOrAddModelCache = function (key, factory) {
  46072. return this._modelCache.getOrAddWithFactory(key, factory);
  46073. };
  46074. Canvas2DEngineBoundData.prototype.DisposeModelRenderCache = function (modelRenderCache) {
  46075. if (!modelRenderCache.isDisposed) {
  46076. return false;
  46077. }
  46078. this._modelCache.remove(modelRenderCache.modelKey);
  46079. return true;
  46080. };
  46081. return Canvas2DEngineBoundData;
  46082. }());
  46083. BABYLON.Canvas2DEngineBoundData = Canvas2DEngineBoundData;
  46084. var Canvas2D = (function (_super) {
  46085. __extends(Canvas2D, _super);
  46086. function Canvas2D(scene, settings) {
  46087. var _this = this;
  46088. _super.call(this, settings);
  46089. /**
  46090. * 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.
  46091. * Beware that you have to take under consideration the origin in your calculations! Good luck!
  46092. */
  46093. this.worldSpaceToNodeLocal = function (worldPos) {
  46094. var node = _this._worldSpaceNode;
  46095. if (!node) {
  46096. return;
  46097. }
  46098. var mtx = node.getWorldMatrix().clone();
  46099. mtx.invert();
  46100. var v = BABYLON.Vector3.TransformCoordinates(worldPos, mtx);
  46101. var res = new BABYLON.Vector2(v.x, v.y);
  46102. var size = _this.actualSize;
  46103. res.x += size.width * 0.5; // res is centered, make it relative to bottom/left
  46104. res.y += size.height * 0.5;
  46105. return res;
  46106. };
  46107. /**
  46108. * 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
  46109. */
  46110. this.worldSpaceCacheChanged = function () {
  46111. var plane = _this.worldSpaceCanvasNode;
  46112. var vd = BABYLON.VertexData.ExtractFromMesh(plane); //new VertexData();
  46113. vd.uvs = new Float32Array(8);
  46114. var material = plane.material;
  46115. var tex = _this._renderableData._cacheTexture;
  46116. if (material.diffuseTexture !== tex) {
  46117. material.diffuseTexture = tex;
  46118. tex.hasAlpha = true;
  46119. }
  46120. var nodeuv = _this._renderableData._cacheNodeUVs;
  46121. for (var i = 0; i < 4; i++) {
  46122. vd.uvs[i * 2 + 0] = nodeuv[i].x;
  46123. vd.uvs[i * 2 + 1] = nodeuv[i].y;
  46124. }
  46125. vd.applyToMesh(plane);
  46126. };
  46127. this._notifDebugMode = false;
  46128. this._mapCounter = 0;
  46129. this._drawCallsOpaqueCounter = new BABYLON.PerfCounter();
  46130. this._drawCallsAlphaTestCounter = new BABYLON.PerfCounter();
  46131. this._drawCallsTransparentCounter = new BABYLON.PerfCounter();
  46132. this._groupRenderCounter = new BABYLON.PerfCounter();
  46133. this._updateTransparentDataCounter = new BABYLON.PerfCounter();
  46134. this._cachedGroupRenderCounter = new BABYLON.PerfCounter();
  46135. this._updateCachedStateCounter = new BABYLON.PerfCounter();
  46136. this._updateLayoutCounter = new BABYLON.PerfCounter();
  46137. this._updatePositioningCounter = new BABYLON.PerfCounter();
  46138. this._updateLocalTransformCounter = new BABYLON.PerfCounter();
  46139. this._updateGlobalTransformCounter = new BABYLON.PerfCounter();
  46140. this._boundingInfoRecomputeCounter = new BABYLON.PerfCounter();
  46141. this._profileInfoText = null;
  46142. BABYLON.Prim2DBase._isCanvasInit = false;
  46143. if (!settings) {
  46144. settings = {};
  46145. }
  46146. if (this._cachingStrategy !== Canvas2D.CACHESTRATEGY_TOPLEVELGROUPS) {
  46147. this._background = new BABYLON.Rectangle2D({ parent: this, id: "###CANVAS BACKGROUND###", size: settings.size }); //TODO CHECK when size is null
  46148. this._background.zOrder = 1.0;
  46149. this._background.isPickable = false;
  46150. this._background.origin = BABYLON.Vector2.Zero();
  46151. this._background.levelVisible = false;
  46152. if (settings.backgroundRoundRadius != null) {
  46153. this.backgroundRoundRadius = settings.backgroundRoundRadius;
  46154. }
  46155. if (settings.backgroundBorder != null) {
  46156. if (typeof (settings.backgroundBorder) === "string") {
  46157. this.backgroundBorder = Canvas2D.GetBrushFromString(settings.backgroundBorder);
  46158. }
  46159. else {
  46160. this.backgroundBorder = settings.backgroundBorder;
  46161. }
  46162. }
  46163. if (settings.backgroundBorderThickNess != null) {
  46164. this.backgroundBorderThickness = settings.backgroundBorderThickNess;
  46165. }
  46166. if (settings.backgroundFill != null) {
  46167. if (typeof (settings.backgroundFill) === "string") {
  46168. this.backgroundFill = Canvas2D.GetBrushFromString(settings.backgroundFill);
  46169. }
  46170. else {
  46171. this.backgroundFill = settings.backgroundFill;
  46172. }
  46173. }
  46174. this._background._patchHierarchy(this);
  46175. }
  46176. var engine = scene.getEngine();
  46177. this.__engineData = engine.getOrAddExternalDataWithFactory("__BJSCANVAS2D__", function (k) { return new Canvas2DEngineBoundData(); });
  46178. this._primPointerInfo = new BABYLON.PrimitivePointerInfo();
  46179. this._capturedPointers = new BABYLON.StringDictionary();
  46180. this._pickStartingPosition = BABYLON.Vector2.Zero();
  46181. this._hierarchyLevelMaxSiblingCount = 50;
  46182. this._hierarchyDepth = 0;
  46183. this._zOrder = 0;
  46184. this._zMax = 1;
  46185. this._scene = scene;
  46186. this._engine = engine;
  46187. this._renderingSize = new BABYLON.Size(0, 0);
  46188. this._trackedGroups = new Array();
  46189. this._maxAdaptiveWorldSpaceCanvasSize = null;
  46190. this._groupCacheMaps = new BABYLON.StringDictionary();
  46191. this._patchHierarchy(this);
  46192. var enableInteraction = (settings.enableInteraction == null) ? true : settings.enableInteraction;
  46193. this._fitRenderingDevice = !settings.size;
  46194. if (!settings.size) {
  46195. settings.size = new BABYLON.Size(engine.getRenderWidth(), engine.getRenderHeight());
  46196. }
  46197. // Register scene dispose to also dispose the canvas when it'll happens
  46198. scene.onDisposeObservable.add(function (d, s) {
  46199. _this.dispose();
  46200. });
  46201. if (this._isScreenSpace) {
  46202. this._afterRenderObserver = this._scene.onAfterRenderObservable.add(function (d, s) {
  46203. _this._engine.clear(null, false, true);
  46204. _this._render();
  46205. });
  46206. }
  46207. else {
  46208. this._beforeRenderObserver = this._scene.onBeforeRenderObservable.add(function (d, s) {
  46209. _this._render();
  46210. });
  46211. }
  46212. this._supprtInstancedArray = this._engine.getCaps().instancedArrays !== null;
  46213. //this._supprtInstancedArray = false; // TODO REMOVE!!!
  46214. this._setupInteraction(enableInteraction);
  46215. }
  46216. Object.defineProperty(Canvas2D.prototype, "drawCallsOpaqueCounter", {
  46217. get: function () {
  46218. return this._drawCallsOpaqueCounter;
  46219. },
  46220. enumerable: true,
  46221. configurable: true
  46222. });
  46223. Object.defineProperty(Canvas2D.prototype, "drawCallsAlphaTestCounter", {
  46224. get: function () {
  46225. return this._drawCallsAlphaTestCounter;
  46226. },
  46227. enumerable: true,
  46228. configurable: true
  46229. });
  46230. Object.defineProperty(Canvas2D.prototype, "drawCallsTransparentCounter", {
  46231. get: function () {
  46232. return this._drawCallsTransparentCounter;
  46233. },
  46234. enumerable: true,
  46235. configurable: true
  46236. });
  46237. Object.defineProperty(Canvas2D.prototype, "groupRenderCounter", {
  46238. get: function () {
  46239. return this._groupRenderCounter;
  46240. },
  46241. enumerable: true,
  46242. configurable: true
  46243. });
  46244. Object.defineProperty(Canvas2D.prototype, "updateTransparentDataCounter", {
  46245. get: function () {
  46246. return this._updateTransparentDataCounter;
  46247. },
  46248. enumerable: true,
  46249. configurable: true
  46250. });
  46251. Object.defineProperty(Canvas2D.prototype, "cachedGroupRenderCounter", {
  46252. get: function () {
  46253. return this._cachedGroupRenderCounter;
  46254. },
  46255. enumerable: true,
  46256. configurable: true
  46257. });
  46258. Object.defineProperty(Canvas2D.prototype, "updateCachedStateCounter", {
  46259. get: function () {
  46260. return this._updateCachedStateCounter;
  46261. },
  46262. enumerable: true,
  46263. configurable: true
  46264. });
  46265. Object.defineProperty(Canvas2D.prototype, "updateLayoutCounter", {
  46266. get: function () {
  46267. return this._updateLayoutCounter;
  46268. },
  46269. enumerable: true,
  46270. configurable: true
  46271. });
  46272. Object.defineProperty(Canvas2D.prototype, "updatePositioningCounter", {
  46273. get: function () {
  46274. return this._updatePositioningCounter;
  46275. },
  46276. enumerable: true,
  46277. configurable: true
  46278. });
  46279. Object.defineProperty(Canvas2D.prototype, "updateLocalTransformCounter", {
  46280. get: function () {
  46281. return this._updateLocalTransformCounter;
  46282. },
  46283. enumerable: true,
  46284. configurable: true
  46285. });
  46286. Object.defineProperty(Canvas2D.prototype, "updateGlobalTransformCounter", {
  46287. get: function () {
  46288. return this._updateGlobalTransformCounter;
  46289. },
  46290. enumerable: true,
  46291. configurable: true
  46292. });
  46293. Object.defineProperty(Canvas2D.prototype, "boundingInfoRecomputeCounter", {
  46294. get: function () {
  46295. return this._boundingInfoRecomputeCounter;
  46296. },
  46297. enumerable: true,
  46298. configurable: true
  46299. });
  46300. Canvas2D.prototype._canvasPreInit = function (settings) {
  46301. var cachingStrategy = (settings.cachingStrategy == null) ? Canvas2D.CACHESTRATEGY_DONTCACHE : settings.cachingStrategy;
  46302. this._cachingStrategy = cachingStrategy;
  46303. this._isScreenSpace = (settings.isScreenSpace == null) ? true : settings.isScreenSpace;
  46304. };
  46305. Canvas2D.prototype._setupInteraction = function (enable) {
  46306. var _this = this;
  46307. // No change detection
  46308. if (enable === this._interactionEnabled) {
  46309. return;
  46310. }
  46311. // Set the new state
  46312. this._interactionEnabled = enable;
  46313. // ScreenSpace mode
  46314. if (this._isScreenSpace) {
  46315. // Disable interaction
  46316. if (!enable) {
  46317. if (this._scenePrePointerObserver) {
  46318. this.scene.onPrePointerObservable.remove(this._scenePrePointerObserver);
  46319. this._scenePrePointerObserver = null;
  46320. }
  46321. return;
  46322. }
  46323. // Enable Interaction
  46324. // Register the observable
  46325. this._scenePrePointerObserver = this.scene.onPrePointerObservable.add(function (e, s) {
  46326. var hs = 1 / _this.engine.getHardwareScalingLevel();
  46327. var localPos = e.localPosition.multiplyByFloats(hs, hs);
  46328. _this._handlePointerEventForInteraction(e, localPos, s);
  46329. });
  46330. }
  46331. else {
  46332. var scene = this.scene;
  46333. if (enable) {
  46334. scene.constantlyUpdateMeshUnderPointer = true;
  46335. this._scenePointerObserver = scene.onPointerObservable.add(function (e, s) {
  46336. if (e.pickInfo.hit && e.pickInfo.pickedMesh === _this._worldSpaceNode && _this.worldSpaceToNodeLocal) {
  46337. var localPos = _this.worldSpaceToNodeLocal(e.pickInfo.pickedPoint);
  46338. _this._handlePointerEventForInteraction(e, localPos, s);
  46339. }
  46340. });
  46341. }
  46342. else {
  46343. if (this._scenePointerObserver) {
  46344. this.scene.onPointerObservable.remove(this._scenePointerObserver);
  46345. this._scenePointerObserver = null;
  46346. }
  46347. }
  46348. }
  46349. };
  46350. /**
  46351. * Internal method, you should use the Prim2DBase version instead
  46352. */
  46353. Canvas2D.prototype._setPointerCapture = function (pointerId, primitive) {
  46354. if (this.isPointerCaptured(pointerId)) {
  46355. return false;
  46356. }
  46357. // Try to capture the pointer on the HTML side
  46358. try {
  46359. this.engine.getRenderingCanvas().setPointerCapture(pointerId);
  46360. }
  46361. catch (e) {
  46362. }
  46363. this._primPointerInfo.updateRelatedTarget(primitive, BABYLON.Vector2.Zero());
  46364. this._bubbleNotifyPrimPointerObserver(primitive, BABYLON.PrimitivePointerInfo.PointerGotCapture, null);
  46365. this._capturedPointers.add(pointerId.toString(), primitive);
  46366. return true;
  46367. };
  46368. /**
  46369. * Internal method, you should use the Prim2DBase version instead
  46370. */
  46371. Canvas2D.prototype._releasePointerCapture = function (pointerId, primitive) {
  46372. if (this._capturedPointers.get(pointerId.toString()) !== primitive) {
  46373. return false;
  46374. }
  46375. // Try to release the pointer on the HTML side
  46376. try {
  46377. this.engine.getRenderingCanvas().releasePointerCapture(pointerId);
  46378. }
  46379. catch (e) {
  46380. }
  46381. this._primPointerInfo.updateRelatedTarget(primitive, BABYLON.Vector2.Zero());
  46382. this._bubbleNotifyPrimPointerObserver(primitive, BABYLON.PrimitivePointerInfo.PointerLostCapture, null);
  46383. this._capturedPointers.remove(pointerId.toString());
  46384. return true;
  46385. };
  46386. /**
  46387. * Determine if the given pointer is captured or not
  46388. * @param pointerId the Id of the pointer
  46389. * @return true if it's captured, false otherwise
  46390. */
  46391. Canvas2D.prototype.isPointerCaptured = function (pointerId) {
  46392. return this._capturedPointers.contains(pointerId.toString());
  46393. };
  46394. Canvas2D.prototype.getCapturedPrimitive = function (pointerId) {
  46395. // Avoid unnecessary lookup
  46396. if (this._capturedPointers.count === 0) {
  46397. return null;
  46398. }
  46399. return this._capturedPointers.get(pointerId.toString());
  46400. };
  46401. Canvas2D.prototype._handlePointerEventForInteraction = function (eventData, localPosition, eventState) {
  46402. // Dispose check
  46403. if (this.isDisposed) {
  46404. return;
  46405. }
  46406. // Update the this._primPointerInfo structure we'll send to observers using the PointerEvent data
  46407. this._updatePointerInfo(eventData, localPosition);
  46408. var capturedPrim = this.getCapturedPrimitive(this._primPointerInfo.pointerId);
  46409. // 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.
  46410. // 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.
  46411. this._updateIntersectionList(this._primPointerInfo.canvasPointerPos, capturedPrim !== null);
  46412. // 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
  46413. this._updateOverStatus();
  46414. // Check if we have nothing to raise
  46415. if (!this._actualOverPrimitive && !capturedPrim) {
  46416. return;
  46417. }
  46418. // Update the relatedTarget info with the over primitive or the captured one (if any)
  46419. var targetPrim = capturedPrim || this._actualOverPrimitive.prim;
  46420. var targetPointerPos = capturedPrim ? this._primPointerInfo.canvasPointerPos.subtract(new BABYLON.Vector2(targetPrim.globalTransform.m[12], targetPrim.globalTransform.m[13])) : this._actualOverPrimitive.intersectionLocation;
  46421. this._primPointerInfo.updateRelatedTarget(targetPrim, targetPointerPos);
  46422. // Analyze the pointer event type and fire proper events on the primitive
  46423. if (eventData.type === BABYLON.PointerEventTypes.POINTERWHEEL) {
  46424. this._bubbleNotifyPrimPointerObserver(targetPrim, BABYLON.PrimitivePointerInfo.PointerMouseWheel, eventData.event);
  46425. }
  46426. else if (eventData.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  46427. this._bubbleNotifyPrimPointerObserver(targetPrim, BABYLON.PrimitivePointerInfo.PointerMove, eventData.event);
  46428. }
  46429. else if (eventData.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  46430. this._bubbleNotifyPrimPointerObserver(targetPrim, BABYLON.PrimitivePointerInfo.PointerDown, eventData.event);
  46431. }
  46432. else if (eventData.type === BABYLON.PointerEventTypes.POINTERUP) {
  46433. this._bubbleNotifyPrimPointerObserver(targetPrim, BABYLON.PrimitivePointerInfo.PointerUp, eventData.event);
  46434. }
  46435. };
  46436. Canvas2D.prototype._updatePointerInfo = function (eventData, localPosition) {
  46437. var pii = this._primPointerInfo;
  46438. if (!pii.canvasPointerPos) {
  46439. pii.canvasPointerPos = BABYLON.Vector2.Zero();
  46440. }
  46441. var camera = this._scene.cameraToUseForPointers || this._scene.activeCamera;
  46442. var engine = this._scene.getEngine();
  46443. if (this._isScreenSpace) {
  46444. var cameraViewport = camera.viewport;
  46445. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  46446. // Moving coordinates to local viewport world
  46447. var x = localPosition.x - viewport.x;
  46448. var y = localPosition.y - viewport.y;
  46449. pii.canvasPointerPos.x = x - this.actualPosition.x;
  46450. pii.canvasPointerPos.y = engine.getRenderHeight() - y - this.actualPosition.y;
  46451. }
  46452. else {
  46453. pii.canvasPointerPos.x = localPosition.x;
  46454. pii.canvasPointerPos.y = localPosition.y;
  46455. }
  46456. pii.mouseWheelDelta = 0;
  46457. if (eventData.type === BABYLON.PointerEventTypes.POINTERWHEEL) {
  46458. var event = eventData.event;
  46459. if (event.wheelDelta) {
  46460. pii.mouseWheelDelta = event.wheelDelta / (BABYLON.PrimitivePointerInfo.MouseWheelPrecision * 40);
  46461. }
  46462. else if (event.detail) {
  46463. pii.mouseWheelDelta = -event.detail / BABYLON.PrimitivePointerInfo.MouseWheelPrecision;
  46464. }
  46465. }
  46466. else {
  46467. var pe = eventData.event;
  46468. pii.ctrlKey = pe.ctrlKey;
  46469. pii.altKey = pe.altKey;
  46470. pii.shiftKey = pe.shiftKey;
  46471. pii.metaKey = pe.metaKey;
  46472. pii.button = pe.button;
  46473. pii.buttons = pe.buttons;
  46474. pii.pointerId = pe.pointerId;
  46475. pii.width = pe.width;
  46476. pii.height = pe.height;
  46477. pii.presssure = pe.pressure;
  46478. pii.tilt.x = pe.tiltX;
  46479. pii.tilt.y = pe.tiltY;
  46480. pii.isCaptured = this.getCapturedPrimitive(pe.pointerId) !== null;
  46481. }
  46482. };
  46483. Canvas2D.prototype._updateIntersectionList = function (mouseLocalPos, isCapture) {
  46484. if (this.scene.getRenderId() === this._intersectionRenderId) {
  46485. return;
  46486. }
  46487. // 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
  46488. if (!this._globalTransform) {
  46489. this.updateCachedStates(true);
  46490. }
  46491. var ii = Canvas2D._interInfo;
  46492. ii.pickPosition.x = mouseLocalPos.x;
  46493. ii.pickPosition.y = mouseLocalPos.y;
  46494. ii.findFirstOnly = false;
  46495. // Fast rejection: test if the mouse pointer is outside the canvas's bounding Info
  46496. if (!isCapture && !this.boundingInfo.doesIntersect(ii.pickPosition)) {
  46497. this._previousIntersectionList = this._actualIntersectionList;
  46498. this._actualIntersectionList = null;
  46499. this._previousOverPrimitive = this._actualOverPrimitive;
  46500. this._actualOverPrimitive = null;
  46501. return;
  46502. }
  46503. this.intersect(ii);
  46504. this._previousIntersectionList = this._actualIntersectionList;
  46505. this._actualIntersectionList = ii.intersectedPrimitives;
  46506. this._previousOverPrimitive = this._actualOverPrimitive;
  46507. this._actualOverPrimitive = ii.topMostIntersectedPrimitive;
  46508. this._intersectionRenderId = this.scene.getRenderId();
  46509. };
  46510. // Based on the previousIntersectionList and the actualInstersectionList we can determined which primitives are being hover state or loosing it
  46511. Canvas2D.prototype._updateOverStatus = function () {
  46512. if ((this.scene.getRenderId() === this._hoverStatusRenderId) || !this._previousIntersectionList || !this._actualIntersectionList) {
  46513. return;
  46514. }
  46515. // Detect a change of over
  46516. var prevPrim = this._previousOverPrimitive ? this._previousOverPrimitive.prim : null;
  46517. var actualPrim = this._actualOverPrimitive ? this._actualOverPrimitive.prim : null;
  46518. if (prevPrim !== actualPrim) {
  46519. // Detect if the current pointer is captured, only fire event if they belong to the capture primitive
  46520. var capturedPrim = this.getCapturedPrimitive(this._primPointerInfo.pointerId);
  46521. // Notify the previous "over" prim that the pointer is no longer over it
  46522. if ((capturedPrim && capturedPrim === prevPrim) || (!capturedPrim && prevPrim)) {
  46523. this._primPointerInfo.updateRelatedTarget(prevPrim, this._previousOverPrimitive.intersectionLocation);
  46524. this._bubbleNotifyPrimPointerObserver(prevPrim, BABYLON.PrimitivePointerInfo.PointerOut, null);
  46525. }
  46526. // Notify the new "over" prim that the pointer is over it
  46527. if ((capturedPrim && capturedPrim === actualPrim) || (!capturedPrim && actualPrim)) {
  46528. this._primPointerInfo.updateRelatedTarget(actualPrim, this._actualOverPrimitive.intersectionLocation);
  46529. this._bubbleNotifyPrimPointerObserver(actualPrim, BABYLON.PrimitivePointerInfo.PointerOver, null);
  46530. }
  46531. }
  46532. this._hoverStatusRenderId = this.scene.getRenderId();
  46533. };
  46534. Canvas2D.prototype._updatePrimPointerPos = function (prim) {
  46535. if (this._primPointerInfo.isCaptured) {
  46536. this._primPointerInfo.primitivePointerPos = this._primPointerInfo.relatedTargetPointerPos;
  46537. }
  46538. else {
  46539. for (var _i = 0, _a = this._actualIntersectionList; _i < _a.length; _i++) {
  46540. var pii = _a[_i];
  46541. if (pii.prim === prim) {
  46542. this._primPointerInfo.primitivePointerPos = pii.intersectionLocation;
  46543. return;
  46544. }
  46545. }
  46546. }
  46547. };
  46548. Canvas2D.prototype._debugExecObserver = function (prim, mask) {
  46549. if (!this._notifDebugMode) {
  46550. return;
  46551. }
  46552. var debug = "";
  46553. for (var i = 0; i < prim.hierarchyDepth; i++) {
  46554. debug += " ";
  46555. }
  46556. var pii = this._primPointerInfo;
  46557. 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();
  46558. console.log(debug);
  46559. };
  46560. Canvas2D.prototype._bubbleNotifyPrimPointerObserver = function (prim, mask, eventData) {
  46561. var ppi = this._primPointerInfo;
  46562. // In case of PointerOver/Out we will first notify the parent with PointerEnter/Leave
  46563. if ((mask & (BABYLON.PrimitivePointerInfo.PointerOver | BABYLON.PrimitivePointerInfo.PointerOut)) !== 0) {
  46564. this._notifParents(prim, mask);
  46565. }
  46566. var bubbleCancelled = false;
  46567. var cur = prim;
  46568. while (cur) {
  46569. // Only trigger the observers if the primitive is intersected (except for out)
  46570. if (!bubbleCancelled) {
  46571. this._updatePrimPointerPos(cur);
  46572. // Exec the observers
  46573. this._debugExecObserver(cur, mask);
  46574. cur._pointerEventObservable.notifyObservers(ppi, mask);
  46575. this._triggerActionManager(cur, ppi, mask, eventData);
  46576. // Bubble canceled? If we're not executing PointerOver or PointerOut, quit immediately
  46577. // If it's PointerOver/Out we have to trigger PointerEnter/Leave no matter what
  46578. if (ppi.cancelBubble) {
  46579. if ((mask & (BABYLON.PrimitivePointerInfo.PointerOver | BABYLON.PrimitivePointerInfo.PointerOut)) === 0) {
  46580. return;
  46581. }
  46582. // We're dealing with PointerOver/Out, let's keep looping to fire PointerEnter/Leave, but not Over/Out anymore
  46583. bubbleCancelled = true;
  46584. }
  46585. }
  46586. // If bubble is cancel we didn't update the Primitive Pointer Pos yet, let's do it
  46587. if (bubbleCancelled) {
  46588. this._updatePrimPointerPos(cur);
  46589. }
  46590. // Trigger a PointerEnter corresponding to the PointerOver
  46591. if (mask === BABYLON.PrimitivePointerInfo.PointerOver) {
  46592. this._debugExecObserver(cur, BABYLON.PrimitivePointerInfo.PointerEnter);
  46593. cur._pointerEventObservable.notifyObservers(ppi, BABYLON.PrimitivePointerInfo.PointerEnter);
  46594. }
  46595. else if (mask === BABYLON.PrimitivePointerInfo.PointerOut) {
  46596. this._debugExecObserver(cur, BABYLON.PrimitivePointerInfo.PointerLeave);
  46597. cur._pointerEventObservable.notifyObservers(ppi, BABYLON.PrimitivePointerInfo.PointerLeave);
  46598. }
  46599. // Loop to the parent
  46600. cur = cur.parent;
  46601. }
  46602. };
  46603. Canvas2D.prototype._triggerActionManager = function (prim, ppi, mask, eventData) {
  46604. var _this = this;
  46605. // 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
  46606. if (!this._globalTransform) {
  46607. this.updateCachedStates(true);
  46608. }
  46609. // Process Trigger related to PointerDown
  46610. if ((mask & BABYLON.PrimitivePointerInfo.PointerDown) !== 0) {
  46611. // On pointer down, record the current position and time to be able to trick PickTrigger and LongPressTrigger
  46612. this._pickStartingPosition = ppi.primitivePointerPos.clone();
  46613. this._pickStartingTime = new Date().getTime();
  46614. this._pickedDownPrim = null;
  46615. if (prim.actionManager) {
  46616. this._pickedDownPrim = prim;
  46617. if (prim.actionManager.hasPickTriggers) {
  46618. var actionEvent = BABYLON.ActionEvent.CreateNewFromPrimitive(prim, ppi.primitivePointerPos, eventData);
  46619. switch (eventData.button) {
  46620. case 0:
  46621. prim.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, actionEvent);
  46622. break;
  46623. case 1:
  46624. prim.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, actionEvent);
  46625. break;
  46626. case 2:
  46627. prim.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, actionEvent);
  46628. break;
  46629. }
  46630. prim.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, actionEvent);
  46631. }
  46632. if (prim.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  46633. window.setTimeout(function () {
  46634. var ppi = _this._primPointerInfo;
  46635. var capturedPrim = _this.getCapturedPrimitive(ppi.pointerId);
  46636. _this._updateIntersectionList(ppi.canvasPointerPos, capturedPrim !== null);
  46637. var ii = new BABYLON.IntersectInfo2D();
  46638. ii.pickPosition = ppi.canvasPointerPos.clone();
  46639. ii.findFirstOnly = false;
  46640. _this.intersect(ii);
  46641. if (ii.isPrimIntersected(prim) !== null) {
  46642. if (prim.actionManager) {
  46643. 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)) {
  46644. _this._pickStartingTime = 0;
  46645. prim.actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNewFromPrimitive(prim, ppi.primitivePointerPos, eventData));
  46646. }
  46647. }
  46648. }
  46649. }, BABYLON.ActionManager.LongPressDelay);
  46650. }
  46651. }
  46652. }
  46653. else if ((mask & BABYLON.PrimitivePointerInfo.PointerUp) !== 0) {
  46654. this._pickStartingTime = 0;
  46655. var actionEvent = BABYLON.ActionEvent.CreateNewFromPrimitive(prim, ppi.primitivePointerPos, eventData);
  46656. if (prim.actionManager) {
  46657. // OnPickUpTrigger
  46658. prim.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, actionEvent);
  46659. // OnPickTrigger
  46660. if (Math.abs(this._pickStartingPosition.x - ppi.canvasPointerPos.x) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(this._pickStartingPosition.y - ppi.canvasPointerPos.y) < BABYLON.ActionManager.DragMovementThreshold) {
  46661. prim.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, actionEvent);
  46662. }
  46663. }
  46664. // OnPickOutTrigger
  46665. if (this._pickedDownPrim && this._pickedDownPrim.actionManager && (this._pickedDownPrim !== prim)) {
  46666. this._pickedDownPrim.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, actionEvent);
  46667. }
  46668. }
  46669. else if ((mask & BABYLON.PrimitivePointerInfo.PointerOver) !== 0) {
  46670. if (prim.actionManager) {
  46671. var actionEvent = BABYLON.ActionEvent.CreateNewFromPrimitive(prim, ppi.primitivePointerPos, eventData);
  46672. prim.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, actionEvent);
  46673. }
  46674. }
  46675. else if ((mask & BABYLON.PrimitivePointerInfo.PointerOut) !== 0) {
  46676. if (prim.actionManager) {
  46677. var actionEvent = BABYLON.ActionEvent.CreateNewFromPrimitive(prim, ppi.primitivePointerPos, eventData);
  46678. prim.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, actionEvent);
  46679. }
  46680. }
  46681. };
  46682. Canvas2D.prototype._notifParents = function (prim, mask) {
  46683. var pii = this._primPointerInfo;
  46684. var curPrim = this;
  46685. while (curPrim) {
  46686. this._updatePrimPointerPos(curPrim);
  46687. // Fire the proper notification
  46688. if (mask === BABYLON.PrimitivePointerInfo.PointerOver) {
  46689. this._debugExecObserver(curPrim, BABYLON.PrimitivePointerInfo.PointerEnter);
  46690. curPrim._pointerEventObservable.notifyObservers(pii, BABYLON.PrimitivePointerInfo.PointerEnter);
  46691. }
  46692. else if (mask === BABYLON.PrimitivePointerInfo.PointerOut) {
  46693. this._debugExecObserver(curPrim, BABYLON.PrimitivePointerInfo.PointerLeave);
  46694. curPrim._pointerEventObservable.notifyObservers(pii, BABYLON.PrimitivePointerInfo.PointerLeave);
  46695. }
  46696. curPrim = curPrim.parent;
  46697. }
  46698. };
  46699. /**
  46700. * Don't forget to call the dispose method when you're done with the Canvas instance.
  46701. * But don't worry, if you dispose its scene, the canvas will be automatically disposed too.
  46702. */
  46703. Canvas2D.prototype.dispose = function () {
  46704. if (!_super.prototype.dispose.call(this)) {
  46705. return false;
  46706. }
  46707. if (this._profilingCanvas) {
  46708. this._profilingCanvas.dispose();
  46709. this._profilingCanvas = null;
  46710. }
  46711. if (this.interactionEnabled) {
  46712. this._setupInteraction(false);
  46713. }
  46714. if (this._beforeRenderObserver) {
  46715. this._scene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  46716. this._beforeRenderObserver = null;
  46717. }
  46718. if (this._afterRenderObserver) {
  46719. this._scene.onAfterRenderObservable.remove(this._afterRenderObserver);
  46720. this._afterRenderObserver = null;
  46721. }
  46722. if (this._groupCacheMaps) {
  46723. this._groupCacheMaps.forEach(function (k, m) { return m.forEach(function (e) { return e.dispose(); }); });
  46724. this._groupCacheMaps = null;
  46725. }
  46726. };
  46727. Object.defineProperty(Canvas2D.prototype, "scene", {
  46728. /**
  46729. * Accessor to the Scene that owns the Canvas
  46730. * @returns The instance of the Scene object
  46731. */
  46732. get: function () {
  46733. return this._scene;
  46734. },
  46735. enumerable: true,
  46736. configurable: true
  46737. });
  46738. Object.defineProperty(Canvas2D.prototype, "engine", {
  46739. /**
  46740. * Accessor to the Engine that drives the Scene used by this Canvas
  46741. * @returns The instance of the Engine object
  46742. */
  46743. get: function () {
  46744. return this._engine;
  46745. },
  46746. enumerable: true,
  46747. configurable: true
  46748. });
  46749. Object.defineProperty(Canvas2D.prototype, "cachingStrategy", {
  46750. /**
  46751. * Accessor of the Caching Strategy used by this Canvas.
  46752. * See Canvas2D.CACHESTRATEGY_xxxx static members for more information
  46753. * @returns the value corresponding to the used strategy.
  46754. */
  46755. get: function () {
  46756. return this._cachingStrategy;
  46757. },
  46758. enumerable: true,
  46759. configurable: true
  46760. });
  46761. Object.defineProperty(Canvas2D.prototype, "isScreenSpace", {
  46762. /**
  46763. * Return true if the Canvas is a Screen Space one, false if it's a World Space one.
  46764. * @returns {}
  46765. */
  46766. get: function () {
  46767. return this._isScreenSpace;
  46768. },
  46769. enumerable: true,
  46770. configurable: true
  46771. });
  46772. Object.defineProperty(Canvas2D.prototype, "worldSpaceCanvasNode", {
  46773. /**
  46774. * Only valid for World Space Canvas, returns the scene node that displays the canvas
  46775. */
  46776. get: function () {
  46777. return this._worldSpaceNode;
  46778. },
  46779. set: function (val) {
  46780. this._worldSpaceNode = val;
  46781. },
  46782. enumerable: true,
  46783. configurable: true
  46784. });
  46785. Object.defineProperty(Canvas2D.prototype, "supportInstancedArray", {
  46786. /**
  46787. * Check if the WebGL Instanced Array extension is supported or not
  46788. */
  46789. get: function () {
  46790. return this._supprtInstancedArray;
  46791. },
  46792. enumerable: true,
  46793. configurable: true
  46794. });
  46795. Object.defineProperty(Canvas2D.prototype, "backgroundFill", {
  46796. /**
  46797. * Property that defines the fill object used to draw the background of the Canvas.
  46798. * Note that Canvas with a Caching Strategy of
  46799. * @returns If the background is not set, null will be returned, otherwise a valid fill object is returned.
  46800. */
  46801. get: function () {
  46802. if (!this._background || !this._background.isVisible) {
  46803. return null;
  46804. }
  46805. return this._background.fill;
  46806. },
  46807. set: function (value) {
  46808. this.checkBackgroundAvailability();
  46809. if (value === this._background.fill) {
  46810. return;
  46811. }
  46812. this._background.fill = value;
  46813. this._background.levelVisible = true;
  46814. },
  46815. enumerable: true,
  46816. configurable: true
  46817. });
  46818. Object.defineProperty(Canvas2D.prototype, "backgroundBorder", {
  46819. /**
  46820. * Property that defines the border object used to draw the background of the Canvas.
  46821. * @returns If the background is not set, null will be returned, otherwise a valid border object is returned.
  46822. */
  46823. get: function () {
  46824. if (!this._background || !this._background.isVisible) {
  46825. return null;
  46826. }
  46827. return this._background.border;
  46828. },
  46829. set: function (value) {
  46830. this.checkBackgroundAvailability();
  46831. if (value === this._background.border) {
  46832. return;
  46833. }
  46834. this._background.border = value;
  46835. this._background.levelVisible = true;
  46836. },
  46837. enumerable: true,
  46838. configurable: true
  46839. });
  46840. Object.defineProperty(Canvas2D.prototype, "backgroundBorderThickness", {
  46841. /**
  46842. * Property that defines the thickness of the border object used to draw the background of the Canvas.
  46843. * @returns If the background is not set, null will be returned, otherwise a valid number matching the thickness is returned.
  46844. */
  46845. get: function () {
  46846. if (!this._background || !this._background.isVisible) {
  46847. return null;
  46848. }
  46849. return this._background.borderThickness;
  46850. },
  46851. set: function (value) {
  46852. this.checkBackgroundAvailability();
  46853. if (value === this._background.borderThickness) {
  46854. return;
  46855. }
  46856. this._background.borderThickness = value;
  46857. },
  46858. enumerable: true,
  46859. configurable: true
  46860. });
  46861. Object.defineProperty(Canvas2D.prototype, "backgroundRoundRadius", {
  46862. /**
  46863. * You can set the roundRadius of the background
  46864. * @returns The current roundRadius
  46865. */
  46866. get: function () {
  46867. if (!this._background || !this._background.isVisible) {
  46868. return null;
  46869. }
  46870. return this._background.roundRadius;
  46871. },
  46872. set: function (value) {
  46873. this.checkBackgroundAvailability();
  46874. if (value === this._background.roundRadius) {
  46875. return;
  46876. }
  46877. this._background.roundRadius = value;
  46878. this._background.levelVisible = true;
  46879. },
  46880. enumerable: true,
  46881. configurable: true
  46882. });
  46883. Object.defineProperty(Canvas2D.prototype, "interactionEnabled", {
  46884. /**
  46885. * Enable/Disable interaction for this Canvas
  46886. * When enabled the Prim2DBase.pointerEventObservable property will notified when appropriate events occur
  46887. */
  46888. get: function () {
  46889. return this._interactionEnabled;
  46890. },
  46891. set: function (enable) {
  46892. this._setupInteraction(enable);
  46893. },
  46894. enumerable: true,
  46895. configurable: true
  46896. });
  46897. Object.defineProperty(Canvas2D.prototype, "_engineData", {
  46898. /**
  46899. * Access the babylon.js' engine bound data, do not invoke this method, it's for internal purpose only
  46900. * @returns {}
  46901. */
  46902. get: function () {
  46903. return this.__engineData;
  46904. },
  46905. enumerable: true,
  46906. configurable: true
  46907. });
  46908. Canvas2D.prototype.createCanvasProfileInfoCanvas = function () {
  46909. if (this._profilingCanvas) {
  46910. return this._profilingCanvas;
  46911. }
  46912. var canvas = new ScreenSpaceCanvas2D(this.scene, {
  46913. id: "ProfileInfoCanvas", cachingStrategy: Canvas2D.CACHESTRATEGY_DONTCACHE, children: [
  46914. new BABYLON.Rectangle2D({
  46915. id: "ProfileBorder", border: "#FFFFFFFF", borderThickness: 2, roundRadius: 5, fill: "#C04040C0", marginAlignment: "h: left, v: top", margin: "10", padding: "10", children: [
  46916. new BABYLON.Text2D("Stats", { id: "ProfileInfoText", marginAlignment: "h: left, v: top", fontName: "10pt Lucida Console" })
  46917. ]
  46918. })
  46919. ]
  46920. });
  46921. this._profileInfoText = canvas.findById("ProfileInfoText");
  46922. this._profilingCanvas = canvas;
  46923. return canvas;
  46924. };
  46925. Canvas2D.prototype.checkBackgroundAvailability = function () {
  46926. if (this._cachingStrategy === Canvas2D.CACHESTRATEGY_TOPLEVELGROUPS) {
  46927. throw Error("Can't use Canvas Background with the caching strategy TOPLEVELGROUPS");
  46928. }
  46929. };
  46930. Canvas2D.prototype._initPerfMetrics = function () {
  46931. this._drawCallsOpaqueCounter.fetchNewFrame();
  46932. this._drawCallsAlphaTestCounter.fetchNewFrame();
  46933. this._drawCallsTransparentCounter.fetchNewFrame();
  46934. this._groupRenderCounter.fetchNewFrame();
  46935. this._updateTransparentDataCounter.fetchNewFrame();
  46936. this._cachedGroupRenderCounter.fetchNewFrame();
  46937. this._updateCachedStateCounter.fetchNewFrame();
  46938. this._updateLayoutCounter.fetchNewFrame();
  46939. this._updatePositioningCounter.fetchNewFrame();
  46940. this._updateLocalTransformCounter.fetchNewFrame();
  46941. this._updateGlobalTransformCounter.fetchNewFrame();
  46942. this._boundingInfoRecomputeCounter.fetchNewFrame();
  46943. };
  46944. Canvas2D.prototype._fetchPerfMetrics = function () {
  46945. this._drawCallsOpaqueCounter.addCount(0, true);
  46946. this._drawCallsAlphaTestCounter.addCount(0, true);
  46947. this._drawCallsTransparentCounter.addCount(0, true);
  46948. this._groupRenderCounter.addCount(0, true);
  46949. this._updateTransparentDataCounter.addCount(0, true);
  46950. this._cachedGroupRenderCounter.addCount(0, true);
  46951. this._updateCachedStateCounter.addCount(0, true);
  46952. this._updateLayoutCounter.addCount(0, true);
  46953. this._updatePositioningCounter.addCount(0, true);
  46954. this._updateLocalTransformCounter.addCount(0, true);
  46955. this._updateGlobalTransformCounter.addCount(0, true);
  46956. this._boundingInfoRecomputeCounter.addCount(0, true);
  46957. };
  46958. Canvas2D.prototype._updateProfileCanvas = function () {
  46959. if (this._profileInfoText == null) {
  46960. return;
  46961. }
  46962. var format = function (v) { return (Math.round(v * 100) / 100).toString(); };
  46963. var p = "Draw Calls:\n" +
  46964. (" - Opaque: " + format(this.drawCallsOpaqueCounter.current) + ", (avg:" + format(this.drawCallsOpaqueCounter.lastSecAverage) + ", t:" + format(this.drawCallsOpaqueCounter.total) + ")\n") +
  46965. (" - AlphaTest: " + format(this.drawCallsAlphaTestCounter.current) + ", (avg:" + format(this.drawCallsAlphaTestCounter.lastSecAverage) + ", t:" + format(this.drawCallsAlphaTestCounter.total) + ")\n") +
  46966. (" - Transparent: " + format(this.drawCallsTransparentCounter.current) + ", (avg:" + format(this.drawCallsTransparentCounter.lastSecAverage) + ", t:" + format(this.drawCallsTransparentCounter.total) + ")\n") +
  46967. ("Group Render: " + this.groupRenderCounter.current + ", (avg:" + format(this.groupRenderCounter.lastSecAverage) + ", t:" + format(this.groupRenderCounter.total) + ")\n") +
  46968. ("Update Transparent Data: " + this.updateTransparentDataCounter.current + ", (avg:" + format(this.updateTransparentDataCounter.lastSecAverage) + ", t:" + format(this.updateTransparentDataCounter.total) + ")\n") +
  46969. ("Cached Group Render: " + this.cachedGroupRenderCounter.current + ", (avg:" + format(this.cachedGroupRenderCounter.lastSecAverage) + ", t:" + format(this.cachedGroupRenderCounter.total) + ")\n") +
  46970. ("Update Cached States: " + this.updateCachedStateCounter.current + ", (avg:" + format(this.updateCachedStateCounter.lastSecAverage) + ", t:" + format(this.updateCachedStateCounter.total) + ")\n") +
  46971. (" - Update Layout: " + this.updateLayoutCounter.current + ", (avg:" + format(this.updateLayoutCounter.lastSecAverage) + ", t:" + format(this.updateLayoutCounter.total) + ")\n") +
  46972. (" - Update Positioning: " + this.updatePositioningCounter.current + ", (avg:" + format(this.updatePositioningCounter.lastSecAverage) + ", t:" + format(this.updatePositioningCounter.total) + ")\n") +
  46973. (" - Update Local Trans: " + this.updateLocalTransformCounter.current + ", (avg:" + format(this.updateLocalTransformCounter.lastSecAverage) + ", t:" + format(this.updateLocalTransformCounter.total) + ")\n") +
  46974. (" - Update Global Trans: " + this.updateGlobalTransformCounter.current + ", (avg:" + format(this.updateGlobalTransformCounter.lastSecAverage) + ", t:" + format(this.updateGlobalTransformCounter.total) + ")\n") +
  46975. (" - BoundingInfo Recompute: " + this.boundingInfoRecomputeCounter.current + ", (avg:" + format(this.boundingInfoRecomputeCounter.lastSecAverage) + ", t:" + format(this.boundingInfoRecomputeCounter.total) + ")\n");
  46976. this._profileInfoText.text = p;
  46977. };
  46978. Canvas2D.prototype._addDrawCallCount = function (count, renderMode) {
  46979. switch (renderMode) {
  46980. case BABYLON.Render2DContext.RenderModeOpaque:
  46981. this._drawCallsOpaqueCounter.addCount(count, false);
  46982. return;
  46983. case BABYLON.Render2DContext.RenderModeAlphaTest:
  46984. this._drawCallsAlphaTestCounter.addCount(count, false);
  46985. return;
  46986. case BABYLON.Render2DContext.RenderModeTransparent:
  46987. this._drawCallsTransparentCounter.addCount(count, false);
  46988. return;
  46989. }
  46990. };
  46991. Canvas2D.prototype._addGroupRenderCount = function (count) {
  46992. this._groupRenderCounter.addCount(count, false);
  46993. };
  46994. Canvas2D.prototype._addUpdateTransparentDataCount = function (count) {
  46995. this._updateTransparentDataCounter.addCount(count, false);
  46996. };
  46997. Canvas2D.prototype.addCachedGroupRenderCounter = function (count) {
  46998. this._cachedGroupRenderCounter.addCount(count, false);
  46999. };
  47000. Canvas2D.prototype.addUpdateCachedStateCounter = function (count) {
  47001. this._updateCachedStateCounter.addCount(count, false);
  47002. };
  47003. Canvas2D.prototype.addUpdateLayoutCounter = function (count) {
  47004. this._updateLayoutCounter.addCount(count, false);
  47005. };
  47006. Canvas2D.prototype.addUpdatePositioningCounter = function (count) {
  47007. this._updatePositioningCounter.addCount(count, false);
  47008. };
  47009. Canvas2D.prototype.addupdateLocalTransformCounter = function (count) {
  47010. this._updateLocalTransformCounter.addCount(count, false);
  47011. };
  47012. Canvas2D.prototype.addUpdateGlobalTransformCounter = function (count) {
  47013. this._updateGlobalTransformCounter.addCount(count, false);
  47014. };
  47015. Canvas2D.prototype.onPrimBecomesDirty = function () {
  47016. this._addPrimToDirtyList(this);
  47017. };
  47018. Canvas2D.prototype._updateTrackedNodes = function () {
  47019. var cam = this.scene.cameraToUseForPointers || this.scene.activeCamera;
  47020. cam.getViewMatrix().multiplyToRef(cam.getProjectionMatrix(), Canvas2D._m);
  47021. var rh = this.engine.getRenderHeight();
  47022. var v = cam.viewport.toGlobal(this.engine.getRenderWidth(), rh);
  47023. for (var _i = 0, _a = this._trackedGroups; _i < _a.length; _i++) {
  47024. var group = _a[_i];
  47025. if (group.isDisposed || !group.isVisible) {
  47026. continue;
  47027. }
  47028. var node = group.trackedNode;
  47029. var worldMtx = node.getWorldMatrix();
  47030. var proj = BABYLON.Vector3.Project(Canvas2D._v, worldMtx, Canvas2D._m, v);
  47031. group.x = Math.round(proj.x);
  47032. group.y = Math.round(rh - proj.y);
  47033. }
  47034. };
  47035. /**
  47036. * Call this method change you want to have layout related data computed and up to date (layout area, primitive area, local/global transformation matrices)
  47037. */
  47038. Canvas2D.prototype.updateCanvasLayout = function (forceRecompute) {
  47039. this._updateCanvasState(forceRecompute);
  47040. };
  47041. Canvas2D.prototype._updateAdaptiveSizeWorldCanvas = function () {
  47042. if (this._globalTransformStep < 2) {
  47043. return;
  47044. }
  47045. var n = this.worldSpaceCanvasNode;
  47046. var bi = n.getBoundingInfo().boundingBox;
  47047. var v = bi.vectorsWorld;
  47048. var cam = this.scene.cameraToUseForPointers || this.scene.activeCamera;
  47049. cam.getViewMatrix().multiplyToRef(cam.getProjectionMatrix(), Canvas2D._m);
  47050. var vp = cam.viewport.toGlobal(this.engine.getRenderWidth(), this.engine.getRenderHeight());
  47051. var projPoints = new Array(4);
  47052. for (var i = 0; i < 4; i++) {
  47053. projPoints[i] = BABYLON.Vector3.Project(v[i], Canvas2D._mI, Canvas2D._m, vp);
  47054. }
  47055. var left = projPoints[3].subtract(projPoints[0]).length();
  47056. var top = projPoints[3].subtract(projPoints[1]).length();
  47057. var right = projPoints[1].subtract(projPoints[2]).length();
  47058. var bottom = projPoints[2].subtract(projPoints[0]).length();
  47059. var w = Math.round(Math.max(top, bottom));
  47060. var h = Math.round(Math.max(right, left));
  47061. var isW = w > h;
  47062. // Basically if it's under 256 we use 256, otherwise we take the biggest power of 2
  47063. var edge = Math.max(w, h);
  47064. if (edge < 256) {
  47065. edge = 256;
  47066. }
  47067. else {
  47068. edge = Math.pow(2, Math.ceil(Math.log(edge) / Math.log(2)));
  47069. }
  47070. // Clip values if needed
  47071. edge = Math.min(edge, this._maxAdaptiveWorldSpaceCanvasSize);
  47072. var newScale = edge / ((isW) ? this.size.width : this.size.height);
  47073. if (newScale !== this.scale) {
  47074. var scale = newScale;
  47075. // console.log(`New adaptive scale for Canvas ${this.id}, w: ${w}, h: ${h}, scale: ${scale}, edge: ${edge}, isW: ${isW}`);
  47076. this._setRenderingScale(scale);
  47077. }
  47078. };
  47079. Canvas2D.prototype._updateCanvasState = function (forceRecompute) {
  47080. // Check if the update has already been made for this render Frame
  47081. if (!forceRecompute && this.scene.getRenderId() === this._updateRenderId) {
  47082. return;
  47083. }
  47084. // Detect a change of rendering size
  47085. var renderingSizeChanged = false;
  47086. var newWidth = this.engine.getRenderWidth();
  47087. if (newWidth !== this._renderingSize.width) {
  47088. renderingSizeChanged = true;
  47089. }
  47090. this._renderingSize.width = newWidth;
  47091. var newHeight = this.engine.getRenderHeight();
  47092. if (newHeight !== this._renderingSize.height) {
  47093. renderingSizeChanged = true;
  47094. }
  47095. this._renderingSize.height = newHeight;
  47096. // If the canvas fit the rendering size and it changed, update
  47097. if (renderingSizeChanged && this._fitRenderingDevice) {
  47098. this.size = this._renderingSize;
  47099. if (this._background) {
  47100. this._background.size = this.size;
  47101. }
  47102. // Dirty the Layout at the Canvas level to recompute as the size changed
  47103. this._setLayoutDirty();
  47104. }
  47105. var context = new BABYLON.PrepareRender2DContext();
  47106. ++this._globalTransformProcessStep;
  47107. this.updateCachedStates(false);
  47108. this._prepareGroupRender(context);
  47109. this._updateRenderId = this.scene.getRenderId();
  47110. };
  47111. /**
  47112. * Method that renders the Canvas, you should not invoke
  47113. */
  47114. Canvas2D.prototype._render = function () {
  47115. this._initPerfMetrics();
  47116. this._updateTrackedNodes();
  47117. this._updateCanvasState(false);
  47118. if (!this._isScreenSpace) {
  47119. this._updateAdaptiveSizeWorldCanvas();
  47120. }
  47121. this._updateCanvasState(false);
  47122. if (this._primPointerInfo.canvasPointerPos) {
  47123. this._updateIntersectionList(this._primPointerInfo.canvasPointerPos, false);
  47124. this._updateOverStatus(); // TODO this._primPointerInfo may not be up to date!
  47125. }
  47126. this.engine.setState(false);
  47127. this._groupRender();
  47128. if (!this._isScreenSpace) {
  47129. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagWorldCacheChanged)) {
  47130. this.worldSpaceCacheChanged();
  47131. this._clearFlags(BABYLON.SmartPropertyPrim.flagWorldCacheChanged);
  47132. }
  47133. }
  47134. // If the canvas is cached at canvas level, we must manually render the sprite that will display its content
  47135. if (this._cachingStrategy === Canvas2D.CACHESTRATEGY_CANVAS && this._cachedCanvasGroup) {
  47136. this._cachedCanvasGroup._renderCachedCanvas();
  47137. }
  47138. this._fetchPerfMetrics();
  47139. this._updateProfileCanvas();
  47140. };
  47141. /**
  47142. * Internal method that allocate a cache for the given group.
  47143. * Caching is made using a collection of MapTexture where many groups have their bitmap cache stored inside.
  47144. * @param group The group to allocate the cache of.
  47145. * @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.
  47146. */
  47147. Canvas2D.prototype._allocateGroupCache = function (group, parent, minSize, useMipMap, anisotropicLevel) {
  47148. if (useMipMap === void 0) { useMipMap = false; }
  47149. if (anisotropicLevel === void 0) { anisotropicLevel = 1; }
  47150. var key = (useMipMap ? "MipMap" : "NoMipMap") + "_" + anisotropicLevel;
  47151. // Determine size
  47152. var size = group.actualSize;
  47153. size = new BABYLON.Size(Math.ceil(size.width), Math.ceil(size.height));
  47154. if (minSize) {
  47155. size.width = Math.max(minSize.width, size.width);
  47156. size.height = Math.max(minSize.height, size.height);
  47157. }
  47158. var mapArray = this._groupCacheMaps.getOrAddWithFactory(key, function () { return new Array(); });
  47159. // Try to find a spot in one of the cached texture
  47160. var res = null;
  47161. var map;
  47162. for (var _i = 0, mapArray_1 = mapArray; _i < mapArray_1.length; _i++) {
  47163. var _map = mapArray_1[_i];
  47164. map = _map;
  47165. var node = map.allocateRect(size);
  47166. if (node) {
  47167. res = { node: node, texture: map };
  47168. break;
  47169. }
  47170. }
  47171. // Couldn't find a map that could fit the rect, create a new map for it
  47172. if (!res) {
  47173. var mapSize = new BABYLON.Size(Canvas2D._groupTextureCacheSize, Canvas2D._groupTextureCacheSize);
  47174. // Check if the predefined size would fit, other create a custom size using the nearest bigger power of 2
  47175. if (size.width > mapSize.width || size.height > mapSize.height) {
  47176. mapSize.width = Math.pow(2, Math.ceil(Math.log(size.width) / Math.log(2)));
  47177. mapSize.height = Math.pow(2, Math.ceil(Math.log(size.height) / Math.log(2)));
  47178. }
  47179. var id = "groupsMapChache" + this._mapCounter + "forCanvas" + this.id;
  47180. map = new BABYLON.MapTexture(id, this._scene, mapSize, useMipMap ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : BABYLON.Texture.BILINEAR_SAMPLINGMODE, useMipMap);
  47181. map.anisotropicFilteringLevel = 4;
  47182. mapArray.splice(0, 0, map);
  47183. var node = map.allocateRect(size);
  47184. res = { node: node, texture: map };
  47185. }
  47186. // Check if we have to create a Sprite that will display the content of the Canvas which is cached.
  47187. // Don't do it in case of the group being a worldspace canvas (because its texture is bound to a WorldSpaceCanvas node)
  47188. if (group !== this || this._isScreenSpace) {
  47189. var node = res.node;
  47190. // 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
  47191. if (this._cachingStrategy === Canvas2D.CACHESTRATEGY_CANVAS) {
  47192. this._cachedCanvasGroup = BABYLON.Group2D._createCachedCanvasGroup(this);
  47193. var sprite = new BABYLON.Sprite2D(map, { parent: this._cachedCanvasGroup, id: "__cachedCanvasSprite__", spriteSize: node.contentSize, spriteLocation: node.pos });
  47194. sprite.zOrder = 1;
  47195. sprite.origin = BABYLON.Vector2.Zero();
  47196. }
  47197. else {
  47198. 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 });
  47199. sprite.origin = group.origin.clone();
  47200. res.sprite = sprite;
  47201. }
  47202. }
  47203. return res;
  47204. };
  47205. /**
  47206. * Internal method used to register a Scene Node to track position for the given group
  47207. * Do not invoke this method, for internal purpose only.
  47208. * @param group the group to track its associated Scene Node
  47209. */
  47210. Canvas2D.prototype._registerTrackedNode = function (group) {
  47211. if (group._isFlagSet(BABYLON.SmartPropertyPrim.flagTrackedGroup)) {
  47212. return;
  47213. }
  47214. this._trackedGroups.push(group);
  47215. group._setFlags(BABYLON.SmartPropertyPrim.flagTrackedGroup);
  47216. };
  47217. /**
  47218. * Internal method used to unregister a tracked Scene Node
  47219. * Do not invoke this method, it's for internal purpose only.
  47220. * @param group the group to unregister its tracked Scene Node from.
  47221. */
  47222. Canvas2D.prototype._unregisterTrackedNode = function (group) {
  47223. if (!group._isFlagSet(BABYLON.SmartPropertyPrim.flagTrackedGroup)) {
  47224. return;
  47225. }
  47226. var i = this._trackedGroups.indexOf(group);
  47227. if (i !== -1) {
  47228. this._trackedGroups.splice(i, 1);
  47229. }
  47230. group._clearFlags(BABYLON.SmartPropertyPrim.flagTrackedGroup);
  47231. };
  47232. /**
  47233. * Get a Solid Color Brush instance matching the given color.
  47234. * @param color The color to retrieve
  47235. * @return A shared instance of the SolidColorBrush2D class that use the given color
  47236. */
  47237. Canvas2D.GetSolidColorBrush = function (color) {
  47238. return Canvas2D._solidColorBrushes.getOrAddWithFactory(color.toHexString(), function () { return new BABYLON.SolidColorBrush2D(color.clone(), true); });
  47239. };
  47240. /**
  47241. * Get a Solid Color Brush instance matching the given color expressed as a CSS formatted hexadecimal value.
  47242. * @param color The color to retrieve
  47243. * @return A shared instance of the SolidColorBrush2D class that uses the given color
  47244. */
  47245. Canvas2D.GetSolidColorBrushFromHex = function (hexValue) {
  47246. return Canvas2D._solidColorBrushes.getOrAddWithFactory(hexValue, function () { return new BABYLON.SolidColorBrush2D(BABYLON.Color4.FromHexString(hexValue), true); });
  47247. };
  47248. /**
  47249. * Get a Gradient Color Brush
  47250. * @param color1 starting color
  47251. * @param color2 engine color
  47252. * @param translation translation vector to apply. default is [0;0]
  47253. * @param rotation rotation in radian to apply to the brush, initial direction is top to bottom. rotation is counter clockwise. default is 0.
  47254. * @param scale scaling factor to apply. default is 1.
  47255. */
  47256. Canvas2D.GetGradientColorBrush = function (color1, color2, translation, rotation, scale) {
  47257. if (translation === void 0) { translation = BABYLON.Vector2.Zero(); }
  47258. if (rotation === void 0) { rotation = 0; }
  47259. if (scale === void 0) { scale = 1; }
  47260. return Canvas2D._gradientColorBrushes.getOrAddWithFactory(BABYLON.GradientColorBrush2D.BuildKey(color1, color2, translation, rotation, scale), function () { return new BABYLON.GradientColorBrush2D(color1, color2, translation, rotation, scale, true); });
  47261. };
  47262. /**
  47263. * Create a solid or gradient brush from a string value.
  47264. * @param brushString should be either
  47265. * - "solid: #RRGGBBAA" or "#RRGGBBAA"
  47266. * - "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.
  47267. */
  47268. Canvas2D.GetBrushFromString = function (brushString) {
  47269. // Note: yes, I hate/don't know RegEx.. Feel free to add your contribution to the cause!
  47270. brushString = brushString.trim();
  47271. var split = brushString.split(",");
  47272. // Solid, formatted as: "[solid:]#FF808080"
  47273. if (split.length === 1) {
  47274. var value = null;
  47275. if (brushString.indexOf("solid:") === 0) {
  47276. value = brushString.substr(6).trim();
  47277. }
  47278. else if (brushString.indexOf("#") === 0) {
  47279. value = brushString;
  47280. }
  47281. else {
  47282. return null;
  47283. }
  47284. return Canvas2D.GetSolidColorBrushFromHex(value);
  47285. }
  47286. else {
  47287. if (split[0].indexOf("gradient:") === 0) {
  47288. split[0] = split[0].substr(9).trim();
  47289. }
  47290. try {
  47291. var start = BABYLON.Color4.FromHexString(split[0].trim());
  47292. var end = BABYLON.Color4.FromHexString(split[1].trim());
  47293. var t = BABYLON.Vector2.Zero();
  47294. if (split.length > 2) {
  47295. var v = split[2].trim();
  47296. if (v.charAt(0) !== "[" || v.charAt(v.length - 1) !== "]") {
  47297. return null;
  47298. }
  47299. var sep = v.indexOf(":");
  47300. var x = parseFloat(v.substr(1, sep));
  47301. var y = parseFloat(v.substr(sep + 1, v.length - (sep + 1)));
  47302. t = new BABYLON.Vector2(x, y);
  47303. }
  47304. var r = 0;
  47305. if (split.length > 3) {
  47306. r = BABYLON.Tools.ToRadians(parseFloat(split[3].trim()));
  47307. }
  47308. var s = 1;
  47309. if (split.length > 4) {
  47310. s = parseFloat(split[4].trim());
  47311. }
  47312. return Canvas2D.GetGradientColorBrush(start, end, t, r, s);
  47313. }
  47314. catch (e) {
  47315. return null;
  47316. }
  47317. }
  47318. };
  47319. /**
  47320. * 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.
  47321. * This strategy doesn't allow primitives added directly as children of the Canvas.
  47322. * 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.
  47323. */
  47324. Canvas2D.CACHESTRATEGY_TOPLEVELGROUPS = 1;
  47325. /**
  47326. * In this strategy each group will have its own cache bitmap (except if a given group explicitly defines the DONTCACHEOVERRIDE or CACHEINPARENTGROUP behaviors).
  47327. * 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.
  47328. * When using this strategy, group instances can rely on the DONTCACHEOVERRIDE or CACHEINPARENTGROUP behaviors to minimize the amount of cached bitmaps.
  47329. * 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.
  47330. */
  47331. Canvas2D.CACHESTRATEGY_ALLGROUPS = 2;
  47332. /**
  47333. * 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).
  47334. */
  47335. Canvas2D.CACHESTRATEGY_CANVAS = 3;
  47336. /**
  47337. * This strategy is used to recompose/redraw the canvas entirely at each viewport render.
  47338. * 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).
  47339. * Note that you can't use this strategy for WorldSpace Canvas, they need at least a top level group caching.
  47340. */
  47341. Canvas2D.CACHESTRATEGY_DONTCACHE = 4;
  47342. Canvas2D._zMinDelta = 1 / (Math.pow(2, 24) - 1);
  47343. Canvas2D._interInfo = new BABYLON.IntersectInfo2D();
  47344. Canvas2D._v = BABYLON.Vector3.Zero(); // Must stay zero
  47345. Canvas2D._m = BABYLON.Matrix.Identity();
  47346. Canvas2D._mI = BABYLON.Matrix.Identity(); // Must stay identity
  47347. /**
  47348. * Define the default size used for both the width and height of a MapTexture to allocate.
  47349. * Note that some MapTexture might be bigger than this size if the first node to allocate is bigger in width or height
  47350. */
  47351. Canvas2D._groupTextureCacheSize = 1024;
  47352. Canvas2D._solidColorBrushes = new BABYLON.StringDictionary();
  47353. Canvas2D._gradientColorBrushes = new BABYLON.StringDictionary();
  47354. Canvas2D = __decorate([
  47355. BABYLON.className("Canvas2D")
  47356. ], Canvas2D);
  47357. return Canvas2D;
  47358. }(BABYLON.Group2D));
  47359. BABYLON.Canvas2D = Canvas2D;
  47360. var WorldSpaceCanvas2D = (function (_super) {
  47361. __extends(WorldSpaceCanvas2D, _super);
  47362. /**
  47363. * 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.
  47364. * 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.
  47365. * @param scene the Scene that owns the Canvas
  47366. * @param size the dimension of the Canvas in World Space
  47367. * @param settings a combination of settings, possible ones are
  47368. * - children: an array of direct children primitives
  47369. * - id: a text identifier, for information purpose only, default is null.
  47370. * - worldPosition the position of the Canvas in World Space, default is [0,0,0]
  47371. * - worldRotation the rotation of the Canvas in World Space, default is Quaternion.Identity()
  47372. * - sideOrientation: Unexpected behavior occur if the value is different from Mesh.DEFAULTSIDE right now, so please use this one, which is the default.
  47373. * - cachingStrategy Must be CACHESTRATEGY_CANVAS for now, which is the default.
  47374. * - 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).
  47375. * - isVisible: true if the canvas must be visible, false for hidden. Default is true.
  47376. * - backgroundRoundRadius: the round radius of the background, either backgroundFill or backgroundBorder must be specified.
  47377. * - 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.
  47378. * - 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.
  47379. * - backgroundBorderThickness: if a backgroundBorder is specified, its thickness can be set using this property
  47380. * - 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.
  47381. * - 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.
  47382. * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  47383. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  47384. * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  47385. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  47386. * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
  47387. */
  47388. function WorldSpaceCanvas2D(scene, size, settings) {
  47389. BABYLON.Prim2DBase._isCanvasInit = true;
  47390. var s = settings;
  47391. s.isScreenSpace = false;
  47392. s.size = size.clone();
  47393. settings.cachingStrategy = (settings.cachingStrategy == null) ? Canvas2D.CACHESTRATEGY_CANVAS : settings.cachingStrategy;
  47394. if (settings.cachingStrategy !== Canvas2D.CACHESTRATEGY_CANVAS) {
  47395. throw new Error("Right now only the CACHESTRATEGY_CANVAS cache Strategy is supported for WorldSpace Canvas. More will come soon!");
  47396. }
  47397. _super.call(this, scene, settings);
  47398. BABYLON.Prim2DBase._isCanvasInit = false;
  47399. this._renderableData._useMipMap = true;
  47400. this._renderableData._anisotropicLevel = 8;
  47401. //if (cachingStrategy === Canvas2D.CACHESTRATEGY_DONTCACHE) {
  47402. // throw new Error("CACHESTRATEGY_DONTCACHE cache Strategy can't be used for WorldSpace Canvas");
  47403. //}
  47404. var createWorldSpaceNode = !settings || (settings.customWorldSpaceNode == null);
  47405. var id = settings ? settings.id || null : null;
  47406. // Set the max size of texture allowed for the adaptive render of the world space canvas cached bitmap
  47407. var capMaxTextSize = this.engine.getCaps().maxRenderTextureSize;
  47408. var defaultTextSize = (Math.min(capMaxTextSize, 1024)); // Default is 4K if allowed otherwise the max allowed
  47409. if (settings.maxAdaptiveCanvasSize == null) {
  47410. this._maxAdaptiveWorldSpaceCanvasSize = defaultTextSize;
  47411. }
  47412. else {
  47413. // We still clip the given value with the max allowed, the user may not be aware of these limitations
  47414. this._maxAdaptiveWorldSpaceCanvasSize = Math.min(settings.maxAdaptiveCanvasSize, capMaxTextSize);
  47415. }
  47416. if (createWorldSpaceNode) {
  47417. var plane = new BABYLON.WorldSpaceCanvas2DNode(id, scene, this);
  47418. var vertexData = BABYLON.VertexData.CreatePlane({
  47419. width: size.width,
  47420. height: size.height,
  47421. sideOrientation: settings && settings.sideOrientation || BABYLON.Mesh.DEFAULTSIDE
  47422. });
  47423. var mtl = new BABYLON.StandardMaterial(id + "_Material", scene);
  47424. this.applyCachedTexture(vertexData, mtl);
  47425. vertexData.applyToMesh(plane, true);
  47426. mtl.specularColor = new BABYLON.Color3(0, 0, 0);
  47427. mtl.disableLighting = true;
  47428. mtl.useAlphaFromDiffuseTexture = true;
  47429. plane.position = settings && settings.worldPosition || BABYLON.Vector3.Zero();
  47430. plane.rotationQuaternion = settings && settings.worldRotation || BABYLON.Quaternion.Identity();
  47431. plane.material = mtl;
  47432. this._worldSpaceNode = plane;
  47433. }
  47434. else {
  47435. this._worldSpaceNode = settings.customWorldSpaceNode;
  47436. this.applyCachedTexture(null, null);
  47437. }
  47438. }
  47439. WorldSpaceCanvas2D = __decorate([
  47440. BABYLON.className("WorldSpaceCanvas2D")
  47441. ], WorldSpaceCanvas2D);
  47442. return WorldSpaceCanvas2D;
  47443. }(Canvas2D));
  47444. BABYLON.WorldSpaceCanvas2D = WorldSpaceCanvas2D;
  47445. var ScreenSpaceCanvas2D = (function (_super) {
  47446. __extends(ScreenSpaceCanvas2D, _super);
  47447. /**
  47448. * 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.
  47449. * 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.
  47450. * All caching strategies will be available.
  47451. * 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]
  47452. * @param scene the Scene that owns the Canvas
  47453. * @param settings a combination of settings, possible ones are
  47454. * - children: an array of direct children primitives
  47455. * - id: a text identifier, for information purpose only
  47456. * - x: the position along the x axis (horizontal), relative to the left edge of the viewport. you can alternatively use the position setting.
  47457. * - y: the position along the y axis (vertically), relative to the bottom edge of the viewport. you can alternatively use the position setting.
  47458. * - 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]
  47459. * - width: the width of the Canvas. you can alternatively use the size setting.
  47460. * - height: the height of the Canvas. you can alternatively use the size setting.
  47461. * - 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
  47462. * - cachingStrategy: either CACHESTRATEGY_TOPLEVELGROUPS, CACHESTRATEGY_ALLGROUPS, CACHESTRATEGY_CANVAS, CACHESTRATEGY_DONTCACHE. Please refer to their respective documentation for more information. Default is Canvas2D.CACHESTRATEGY_DONTCACHE
  47463. * - 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.
  47464. * - isVisible: true if the canvas must be visible, false for hidden. Default is true.
  47465. * - backgroundRoundRadius: the round radius of the background, either backgroundFill or backgroundBorder must be specified.
  47466. * - 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.
  47467. * - 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.
  47468. * - backgroundBorderThickness: if a backgroundBorder is specified, its thickness can be set using this property
  47469. * - 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.
  47470. * - paddingTop: top padding, can be a number (will be pixels) or a string (see BABYLON.PrimitiveThickness.fromString)
  47471. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see BABYLON.PrimitiveThickness.fromString)
  47472. * - paddingRight: right padding, can be a number (will be pixels) or a string (see BABYLON.PrimitiveThickness.fromString)
  47473. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see BABYLON.PrimitiveThickness.fromString)
  47474. * - padding: top, left, right and bottom padding formatted as a single string (see BABYLON.PrimitiveThickness.fromString)
  47475. */
  47476. function ScreenSpaceCanvas2D(scene, settings) {
  47477. BABYLON.Prim2DBase._isCanvasInit = true;
  47478. _super.call(this, scene, settings);
  47479. }
  47480. ScreenSpaceCanvas2D = __decorate([
  47481. BABYLON.className("ScreenSpaceCanvas2D")
  47482. ], ScreenSpaceCanvas2D);
  47483. return ScreenSpaceCanvas2D;
  47484. }(Canvas2D));
  47485. BABYLON.ScreenSpaceCanvas2D = ScreenSpaceCanvas2D;
  47486. })(BABYLON || (BABYLON = {}));
  47487. var BABYLON;
  47488. (function (BABYLON) {
  47489. /**
  47490. * This is the class that is used to display a World Space Canvas into a 3D scene
  47491. */
  47492. var WorldSpaceCanvas2DNode = (function (_super) {
  47493. __extends(WorldSpaceCanvas2DNode, _super);
  47494. function WorldSpaceCanvas2DNode(name, scene, canvas) {
  47495. _super.call(this, name, scene);
  47496. this._canvas = canvas;
  47497. }
  47498. WorldSpaceCanvas2DNode.prototype.dispose = function () {
  47499. _super.prototype.dispose.call(this);
  47500. if (this._canvas) {
  47501. this._canvas.dispose();
  47502. this._canvas = null;
  47503. }
  47504. };
  47505. return WorldSpaceCanvas2DNode;
  47506. }(BABYLON.Mesh));
  47507. BABYLON.WorldSpaceCanvas2DNode = WorldSpaceCanvas2DNode;
  47508. })(BABYLON || (BABYLON = {}));
  47509. var BABYLON;
  47510. (function (BABYLON) {
  47511. var LayoutEngineBase = (function () {
  47512. function LayoutEngineBase() {
  47513. this.layoutDirtyOnPropertyChangedMask = 0;
  47514. }
  47515. LayoutEngineBase.prototype.updateLayout = function (prim) {
  47516. };
  47517. Object.defineProperty(LayoutEngineBase.prototype, "isChildPositionAllowed", {
  47518. get: function () {
  47519. return false;
  47520. },
  47521. enumerable: true,
  47522. configurable: true
  47523. });
  47524. LayoutEngineBase.prototype.isLocked = function () {
  47525. return this._isLocked;
  47526. };
  47527. LayoutEngineBase.prototype.lock = function () {
  47528. if (this._isLocked) {
  47529. return false;
  47530. }
  47531. this._isLocked = true;
  47532. return true;
  47533. };
  47534. LayoutEngineBase = __decorate([
  47535. BABYLON.className("LayoutEngineBase")
  47536. ], LayoutEngineBase);
  47537. return LayoutEngineBase;
  47538. }());
  47539. BABYLON.LayoutEngineBase = LayoutEngineBase;
  47540. var CanvasLayoutEngine = (function (_super) {
  47541. __extends(CanvasLayoutEngine, _super);
  47542. function CanvasLayoutEngine() {
  47543. _super.apply(this, arguments);
  47544. }
  47545. // A very simple (no) layout computing...
  47546. // The Canvas and its direct children gets the Canvas' size as Layout Area
  47547. // Indirect children have their Layout Area to the actualSize (margin area) of their parent
  47548. CanvasLayoutEngine.prototype.updateLayout = function (prim) {
  47549. // If this prim is layoutDiry we update its layoutArea and also the one of its direct children
  47550. if (prim._isFlagSet(BABYLON.SmartPropertyPrim.flagLayoutDirty)) {
  47551. for (var _i = 0, _a = prim.children; _i < _a.length; _i++) {
  47552. var child = _a[_i];
  47553. this._doUpdate(child);
  47554. }
  47555. prim._clearFlags(BABYLON.SmartPropertyPrim.flagLayoutDirty);
  47556. }
  47557. };
  47558. CanvasLayoutEngine.prototype._doUpdate = function (prim) {
  47559. // Canvas ?
  47560. if (prim instanceof BABYLON.Canvas2D) {
  47561. prim.layoutArea = prim.actualSize;
  47562. }
  47563. else if (prim.parent instanceof BABYLON.Canvas2D) {
  47564. prim.layoutArea = prim.owner.actualSize;
  47565. }
  47566. else {
  47567. prim.layoutArea = prim.parent.contentArea;
  47568. }
  47569. };
  47570. Object.defineProperty(CanvasLayoutEngine.prototype, "isChildPositionAllowed", {
  47571. get: function () {
  47572. return true;
  47573. },
  47574. enumerable: true,
  47575. configurable: true
  47576. });
  47577. CanvasLayoutEngine.Singleton = new CanvasLayoutEngine();
  47578. CanvasLayoutEngine = __decorate([
  47579. BABYLON.className("CanvasLayoutEngine")
  47580. ], CanvasLayoutEngine);
  47581. return CanvasLayoutEngine;
  47582. }(LayoutEngineBase));
  47583. BABYLON.CanvasLayoutEngine = CanvasLayoutEngine;
  47584. var StackPanelLayoutEngine = (function (_super) {
  47585. __extends(StackPanelLayoutEngine, _super);
  47586. function StackPanelLayoutEngine() {
  47587. _super.call(this);
  47588. this._isHorizontal = true;
  47589. this.layoutDirtyOnPropertyChangedMask = BABYLON.Prim2DBase.sizeProperty.flagId;
  47590. }
  47591. Object.defineProperty(StackPanelLayoutEngine, "Horizontal", {
  47592. get: function () {
  47593. if (!StackPanelLayoutEngine._horizontal) {
  47594. StackPanelLayoutEngine._horizontal = new StackPanelLayoutEngine();
  47595. StackPanelLayoutEngine._horizontal.isHorizontal = true;
  47596. StackPanelLayoutEngine._horizontal.lock();
  47597. }
  47598. return StackPanelLayoutEngine._horizontal;
  47599. },
  47600. enumerable: true,
  47601. configurable: true
  47602. });
  47603. Object.defineProperty(StackPanelLayoutEngine, "Vertical", {
  47604. get: function () {
  47605. if (!StackPanelLayoutEngine._vertical) {
  47606. StackPanelLayoutEngine._vertical = new StackPanelLayoutEngine();
  47607. StackPanelLayoutEngine._vertical.isHorizontal = false;
  47608. StackPanelLayoutEngine._vertical.lock();
  47609. }
  47610. return StackPanelLayoutEngine._vertical;
  47611. },
  47612. enumerable: true,
  47613. configurable: true
  47614. });
  47615. Object.defineProperty(StackPanelLayoutEngine.prototype, "isHorizontal", {
  47616. get: function () {
  47617. return this._isHorizontal;
  47618. },
  47619. set: function (val) {
  47620. if (this.isLocked()) {
  47621. return;
  47622. }
  47623. this._isHorizontal = val;
  47624. },
  47625. enumerable: true,
  47626. configurable: true
  47627. });
  47628. StackPanelLayoutEngine.prototype.updateLayout = function (prim) {
  47629. if (prim._isFlagSet(BABYLON.SmartPropertyPrim.flagLayoutDirty)) {
  47630. var x = 0;
  47631. var y = 0;
  47632. var h = this.isHorizontal;
  47633. var max = 0;
  47634. for (var _i = 0, _a = prim.children; _i < _a.length; _i++) {
  47635. var child = _a[_i];
  47636. var layoutArea = child.layoutArea;
  47637. child.margin.computeArea(child.actualSize, layoutArea);
  47638. max = Math.max(max, h ? layoutArea.height : layoutArea.width);
  47639. }
  47640. for (var _b = 0, _c = prim.children; _b < _c.length; _b++) {
  47641. var child = _c[_b];
  47642. child.layoutAreaPos = new BABYLON.Vector2(x, y);
  47643. var layoutArea = child.layoutArea;
  47644. if (h) {
  47645. x += layoutArea.width;
  47646. child.layoutArea = new BABYLON.Size(layoutArea.width, max);
  47647. }
  47648. else {
  47649. y += layoutArea.height;
  47650. child.layoutArea = new BABYLON.Size(max, layoutArea.height);
  47651. }
  47652. }
  47653. prim._clearFlags(BABYLON.SmartPropertyPrim.flagLayoutDirty);
  47654. }
  47655. };
  47656. Object.defineProperty(StackPanelLayoutEngine.prototype, "isChildPositionAllowed", {
  47657. get: function () {
  47658. return false;
  47659. },
  47660. enumerable: true,
  47661. configurable: true
  47662. });
  47663. StackPanelLayoutEngine._horizontal = null;
  47664. StackPanelLayoutEngine._vertical = null;
  47665. StackPanelLayoutEngine = __decorate([
  47666. BABYLON.className("StackPanelLayoutEngine")
  47667. ], StackPanelLayoutEngine);
  47668. return StackPanelLayoutEngine;
  47669. }(LayoutEngineBase));
  47670. BABYLON.StackPanelLayoutEngine = StackPanelLayoutEngine;
  47671. })(BABYLON || (BABYLON = {}));
  47672. var BABYLON;
  47673. (function (BABYLON) {
  47674. var ShaderMaterial = (function (_super) {
  47675. __extends(ShaderMaterial, _super);
  47676. function ShaderMaterial(name, scene, shaderPath, options) {
  47677. _super.call(this, name, scene);
  47678. this._textures = {};
  47679. this._textureArrays = {};
  47680. this._floats = {};
  47681. this._floatsArrays = {};
  47682. this._colors3 = {};
  47683. this._colors4 = {};
  47684. this._vectors2 = {};
  47685. this._vectors3 = {};
  47686. this._vectors4 = {};
  47687. this._matrices = {};
  47688. this._matrices3x3 = {};
  47689. this._matrices2x2 = {};
  47690. this._cachedWorldViewMatrix = new BABYLON.Matrix();
  47691. this._shaderPath = shaderPath;
  47692. options.needAlphaBlending = options.needAlphaBlending || false;
  47693. options.needAlphaTesting = options.needAlphaTesting || false;
  47694. options.attributes = options.attributes || ["position", "normal", "uv"];
  47695. options.uniforms = options.uniforms || ["worldViewProjection"];
  47696. options.samplers = options.samplers || [];
  47697. options.defines = options.defines || [];
  47698. this._options = options;
  47699. }
  47700. ShaderMaterial.prototype.needAlphaBlending = function () {
  47701. return this._options.needAlphaBlending;
  47702. };
  47703. ShaderMaterial.prototype.needAlphaTesting = function () {
  47704. return this._options.needAlphaTesting;
  47705. };
  47706. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  47707. if (this._options.uniforms.indexOf(uniformName) === -1) {
  47708. this._options.uniforms.push(uniformName);
  47709. }
  47710. };
  47711. ShaderMaterial.prototype.setTexture = function (name, texture) {
  47712. if (this._options.samplers.indexOf(name) === -1) {
  47713. this._options.samplers.push(name);
  47714. }
  47715. this._textures[name] = texture;
  47716. return this;
  47717. };
  47718. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  47719. if (this._options.samplers.indexOf(name) === -1) {
  47720. this._options.samplers.push(name);
  47721. }
  47722. this._checkUniform(name);
  47723. this._textureArrays[name] = textures;
  47724. return this;
  47725. };
  47726. ShaderMaterial.prototype.setFloat = function (name, value) {
  47727. this._checkUniform(name);
  47728. this._floats[name] = value;
  47729. return this;
  47730. };
  47731. ShaderMaterial.prototype.setFloats = function (name, value) {
  47732. this._checkUniform(name);
  47733. this._floatsArrays[name] = value;
  47734. return this;
  47735. };
  47736. ShaderMaterial.prototype.setColor3 = function (name, value) {
  47737. this._checkUniform(name);
  47738. this._colors3[name] = value;
  47739. return this;
  47740. };
  47741. ShaderMaterial.prototype.setColor4 = function (name, value) {
  47742. this._checkUniform(name);
  47743. this._colors4[name] = value;
  47744. return this;
  47745. };
  47746. ShaderMaterial.prototype.setVector2 = function (name, value) {
  47747. this._checkUniform(name);
  47748. this._vectors2[name] = value;
  47749. return this;
  47750. };
  47751. ShaderMaterial.prototype.setVector3 = function (name, value) {
  47752. this._checkUniform(name);
  47753. this._vectors3[name] = value;
  47754. return this;
  47755. };
  47756. ShaderMaterial.prototype.setVector4 = function (name, value) {
  47757. this._checkUniform(name);
  47758. this._vectors4[name] = value;
  47759. return this;
  47760. };
  47761. ShaderMaterial.prototype.setMatrix = function (name, value) {
  47762. this._checkUniform(name);
  47763. this._matrices[name] = value;
  47764. return this;
  47765. };
  47766. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  47767. this._checkUniform(name);
  47768. this._matrices3x3[name] = value;
  47769. return this;
  47770. };
  47771. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  47772. this._checkUniform(name);
  47773. this._matrices2x2[name] = value;
  47774. return this;
  47775. };
  47776. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  47777. var scene = this.getScene();
  47778. var engine = scene.getEngine();
  47779. if (!this.checkReadyOnEveryCall) {
  47780. if (this._renderId === scene.getRenderId()) {
  47781. return true;
  47782. }
  47783. }
  47784. // Instances
  47785. var defines = [];
  47786. var fallbacks = new BABYLON.EffectFallbacks();
  47787. if (useInstances) {
  47788. defines.push("#define INSTANCES");
  47789. }
  47790. for (var index = 0; index < this._options.defines.length; index++) {
  47791. defines.push(this._options.defines[index]);
  47792. }
  47793. // Bones
  47794. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  47795. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  47796. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  47797. fallbacks.addCPUSkinningFallback(0, mesh);
  47798. }
  47799. // Alpha test
  47800. if (engine.getAlphaTesting()) {
  47801. defines.push("#define ALPHATEST");
  47802. }
  47803. var previousEffect = this._effect;
  47804. var join = defines.join("\n");
  47805. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, join, fallbacks, this.onCompiled, this.onError);
  47806. if (!this._effect.isReady()) {
  47807. return false;
  47808. }
  47809. if (previousEffect !== this._effect) {
  47810. scene.resetCachedMaterial();
  47811. }
  47812. this._renderId = scene.getRenderId();
  47813. return true;
  47814. };
  47815. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  47816. var scene = this.getScene();
  47817. if (this._options.uniforms.indexOf("world") !== -1) {
  47818. this._effect.setMatrix("world", world);
  47819. }
  47820. if (this._options.uniforms.indexOf("worldView") !== -1) {
  47821. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  47822. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  47823. }
  47824. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  47825. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  47826. }
  47827. };
  47828. ShaderMaterial.prototype.bind = function (world, mesh) {
  47829. // Std values
  47830. this.bindOnlyWorldMatrix(world);
  47831. if (this.getScene().getCachedMaterial() !== this) {
  47832. if (this._options.uniforms.indexOf("view") !== -1) {
  47833. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  47834. }
  47835. if (this._options.uniforms.indexOf("projection") !== -1) {
  47836. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  47837. }
  47838. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  47839. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  47840. }
  47841. // Bones
  47842. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  47843. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  47844. }
  47845. var name;
  47846. // Texture
  47847. for (name in this._textures) {
  47848. this._effect.setTexture(name, this._textures[name]);
  47849. }
  47850. // Texture arrays
  47851. for (name in this._textureArrays) {
  47852. this._effect.setTextureArray(name, this._textureArrays[name]);
  47853. }
  47854. // Float
  47855. for (name in this._floats) {
  47856. this._effect.setFloat(name, this._floats[name]);
  47857. }
  47858. // Float s
  47859. for (name in this._floatsArrays) {
  47860. this._effect.setArray(name, this._floatsArrays[name]);
  47861. }
  47862. // Color3
  47863. for (name in this._colors3) {
  47864. this._effect.setColor3(name, this._colors3[name]);
  47865. }
  47866. // Color4
  47867. for (name in this._colors4) {
  47868. var color = this._colors4[name];
  47869. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  47870. }
  47871. // Vector2
  47872. for (name in this._vectors2) {
  47873. this._effect.setVector2(name, this._vectors2[name]);
  47874. }
  47875. // Vector3
  47876. for (name in this._vectors3) {
  47877. this._effect.setVector3(name, this._vectors3[name]);
  47878. }
  47879. // Vector4
  47880. for (name in this._vectors4) {
  47881. this._effect.setVector4(name, this._vectors4[name]);
  47882. }
  47883. // Matrix
  47884. for (name in this._matrices) {
  47885. this._effect.setMatrix(name, this._matrices[name]);
  47886. }
  47887. // Matrix 3x3
  47888. for (name in this._matrices3x3) {
  47889. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  47890. }
  47891. // Matrix 2x2
  47892. for (name in this._matrices2x2) {
  47893. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  47894. }
  47895. }
  47896. _super.prototype.bind.call(this, world, mesh);
  47897. };
  47898. ShaderMaterial.prototype.clone = function (name) {
  47899. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  47900. return newShaderMaterial;
  47901. };
  47902. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  47903. if (forceDisposeTextures) {
  47904. var name;
  47905. for (name in this._textures) {
  47906. this._textures[name].dispose();
  47907. }
  47908. for (name in this._textureArrays) {
  47909. var array = this._textureArrays[name];
  47910. for (var index = 0; index < array.length; index++) {
  47911. array[index].dispose();
  47912. }
  47913. }
  47914. }
  47915. this._textures = {};
  47916. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  47917. };
  47918. ShaderMaterial.prototype.serialize = function () {
  47919. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  47920. serializationObject.customType = "BABYLON.ShaderMaterial";
  47921. serializationObject.options = this._options;
  47922. serializationObject.shaderPath = this._shaderPath;
  47923. var name;
  47924. // Texture
  47925. serializationObject.textures = {};
  47926. for (name in this._textures) {
  47927. serializationObject.textures[name] = this._textures[name].serialize();
  47928. }
  47929. // Texture arrays
  47930. serializationObject.textureArrays = {};
  47931. for (name in this._textureArrays) {
  47932. serializationObject.textureArrays[name] = [];
  47933. var array = this._textureArrays[name];
  47934. for (var index = 0; index < array.length; index++) {
  47935. serializationObject.textureArrays[name].push(array[index].serialize());
  47936. }
  47937. }
  47938. // Float
  47939. serializationObject.floats = {};
  47940. for (name in this._floats) {
  47941. serializationObject.floats[name] = this._floats[name];
  47942. }
  47943. // Float s
  47944. serializationObject.floatArrays = {};
  47945. for (name in this._floatsArrays) {
  47946. serializationObject.floatArrays[name] = this._floatsArrays[name];
  47947. }
  47948. // Color3
  47949. serializationObject.colors3 = {};
  47950. for (name in this._colors3) {
  47951. serializationObject.colors3[name] = this._colors3[name].asArray();
  47952. }
  47953. // Color4
  47954. serializationObject.colors4 = {};
  47955. for (name in this._colors4) {
  47956. serializationObject.colors4[name] = this._colors4[name].asArray();
  47957. }
  47958. // Vector2
  47959. serializationObject.vectors2 = {};
  47960. for (name in this._vectors2) {
  47961. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  47962. }
  47963. // Vector3
  47964. serializationObject.vectors3 = {};
  47965. for (name in this._vectors3) {
  47966. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  47967. }
  47968. // Vector4
  47969. serializationObject.vectors4 = {};
  47970. for (name in this._vectors4) {
  47971. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  47972. }
  47973. // Matrix
  47974. serializationObject.matrices = {};
  47975. for (name in this._matrices) {
  47976. serializationObject.matrices[name] = this._matrices[name].asArray();
  47977. }
  47978. // Matrix 3x3
  47979. serializationObject.matrices3x3 = {};
  47980. for (name in this._matrices3x3) {
  47981. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  47982. }
  47983. // Matrix 2x2
  47984. serializationObject.matrices2x2 = {};
  47985. for (name in this._matrices2x2) {
  47986. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  47987. }
  47988. return serializationObject;
  47989. };
  47990. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  47991. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  47992. var name;
  47993. // Texture
  47994. for (name in source.textures) {
  47995. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  47996. }
  47997. // Texture arrays
  47998. for (name in source.textureArrays) {
  47999. var array = source.textureArrays[name];
  48000. var textureArray = new Array();
  48001. for (var index = 0; index < array.length; index++) {
  48002. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  48003. }
  48004. material.setTextureArray(name, textureArray);
  48005. }
  48006. // Float
  48007. for (name in source.floats) {
  48008. material.setFloat(name, source.floats[name]);
  48009. }
  48010. // Float s
  48011. for (name in source.floatsArrays) {
  48012. material.setFloats(name, source.floatsArrays[name]);
  48013. }
  48014. // Color3
  48015. for (name in source.colors3) {
  48016. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  48017. }
  48018. // Color4
  48019. for (name in source.colors4) {
  48020. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  48021. }
  48022. // Vector2
  48023. for (name in source.vectors2) {
  48024. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  48025. }
  48026. // Vector3
  48027. for (name in source.vectors3) {
  48028. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  48029. }
  48030. // Vector4
  48031. for (name in source.vectors4) {
  48032. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  48033. }
  48034. // Matrix
  48035. for (name in source.matrices) {
  48036. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  48037. }
  48038. // Matrix 3x3
  48039. for (name in source.matrices3x3) {
  48040. material.setMatrix3x3(name, source.matrices3x3[name]);
  48041. }
  48042. // Matrix 2x2
  48043. for (name in source.matrices2x2) {
  48044. material.setMatrix2x2(name, source.matrices2x2[name]);
  48045. }
  48046. return material;
  48047. };
  48048. return ShaderMaterial;
  48049. }(BABYLON.Material));
  48050. BABYLON.ShaderMaterial = ShaderMaterial;
  48051. })(BABYLON || (BABYLON = {}));
  48052. var BABYLON;
  48053. (function (BABYLON) {
  48054. var Internals;
  48055. (function (Internals) {
  48056. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  48057. // All values and structures referenced from:
  48058. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  48059. var DDS_MAGIC = 0x20534444;
  48060. 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;
  48061. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  48062. 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;
  48063. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  48064. function FourCCToInt32(value) {
  48065. return value.charCodeAt(0) +
  48066. (value.charCodeAt(1) << 8) +
  48067. (value.charCodeAt(2) << 16) +
  48068. (value.charCodeAt(3) << 24);
  48069. }
  48070. function Int32ToFourCC(value) {
  48071. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  48072. }
  48073. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  48074. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  48075. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  48076. var headerLengthInt = 31; // The header length in 32 bit ints
  48077. // Offsets into the header array
  48078. var off_magic = 0;
  48079. var off_size = 1;
  48080. var off_flags = 2;
  48081. var off_height = 3;
  48082. var off_width = 4;
  48083. var off_mipmapCount = 7;
  48084. var off_pfFlags = 20;
  48085. var off_pfFourCC = 21;
  48086. var off_RGBbpp = 22;
  48087. var off_RMask = 23;
  48088. var off_GMask = 24;
  48089. var off_BMask = 25;
  48090. var off_AMask = 26;
  48091. var off_caps1 = 27;
  48092. var off_caps2 = 28;
  48093. ;
  48094. var DDSTools = (function () {
  48095. function DDSTools() {
  48096. }
  48097. DDSTools.GetDDSInfo = function (arrayBuffer) {
  48098. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  48099. var mipmapCount = 1;
  48100. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  48101. mipmapCount = Math.max(1, header[off_mipmapCount]);
  48102. }
  48103. return {
  48104. width: header[off_width],
  48105. height: header[off_height],
  48106. mipmapCount: mipmapCount,
  48107. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  48108. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  48109. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  48110. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  48111. };
  48112. };
  48113. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  48114. var byteArray = new Uint8Array(dataLength);
  48115. var srcData = new Uint8Array(arrayBuffer);
  48116. var index = 0;
  48117. for (var y = height - 1; y >= 0; y--) {
  48118. for (var x = 0; x < width; x++) {
  48119. var srcPos = dataOffset + (x + y * width) * 4;
  48120. byteArray[index + 2] = srcData[srcPos];
  48121. byteArray[index + 1] = srcData[srcPos + 1];
  48122. byteArray[index] = srcData[srcPos + 2];
  48123. byteArray[index + 3] = srcData[srcPos + 3];
  48124. index += 4;
  48125. }
  48126. }
  48127. return byteArray;
  48128. };
  48129. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  48130. var byteArray = new Uint8Array(dataLength);
  48131. var srcData = new Uint8Array(arrayBuffer);
  48132. var index = 0;
  48133. for (var y = height - 1; y >= 0; y--) {
  48134. for (var x = 0; x < width; x++) {
  48135. var srcPos = dataOffset + (x + y * width) * 3;
  48136. byteArray[index + 2] = srcData[srcPos];
  48137. byteArray[index + 1] = srcData[srcPos + 1];
  48138. byteArray[index] = srcData[srcPos + 2];
  48139. index += 3;
  48140. }
  48141. }
  48142. return byteArray;
  48143. };
  48144. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  48145. var byteArray = new Uint8Array(dataLength);
  48146. var srcData = new Uint8Array(arrayBuffer);
  48147. var index = 0;
  48148. for (var y = height - 1; y >= 0; y--) {
  48149. for (var x = 0; x < width; x++) {
  48150. var srcPos = dataOffset + (x + y * width);
  48151. byteArray[index] = srcData[srcPos];
  48152. index++;
  48153. }
  48154. }
  48155. return byteArray;
  48156. };
  48157. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  48158. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  48159. if (header[off_magic] != DDS_MAGIC) {
  48160. BABYLON.Tools.Error("Invalid magic number in DDS header");
  48161. return;
  48162. }
  48163. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  48164. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  48165. return;
  48166. }
  48167. if (info.isFourCC) {
  48168. fourCC = header[off_pfFourCC];
  48169. switch (fourCC) {
  48170. case FOURCC_DXT1:
  48171. blockBytes = 8;
  48172. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  48173. break;
  48174. case FOURCC_DXT3:
  48175. blockBytes = 16;
  48176. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  48177. break;
  48178. case FOURCC_DXT5:
  48179. blockBytes = 16;
  48180. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  48181. break;
  48182. default:
  48183. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  48184. return;
  48185. }
  48186. }
  48187. mipmapCount = 1;
  48188. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  48189. mipmapCount = Math.max(1, header[off_mipmapCount]);
  48190. }
  48191. var bpp = header[off_RGBbpp];
  48192. for (var face = 0; face < faces; face++) {
  48193. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  48194. width = header[off_width];
  48195. height = header[off_height];
  48196. dataOffset = header[off_size] + 4;
  48197. for (i = 0; i < mipmapCount; ++i) {
  48198. if (info.isRGB) {
  48199. if (bpp === 24) {
  48200. dataLength = width * height * 3;
  48201. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  48202. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  48203. }
  48204. else {
  48205. dataLength = width * height * 4;
  48206. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  48207. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  48208. }
  48209. }
  48210. else if (info.isLuminance) {
  48211. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  48212. var unpaddedRowSize = width;
  48213. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  48214. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  48215. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  48216. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  48217. }
  48218. else {
  48219. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  48220. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  48221. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  48222. }
  48223. dataOffset += dataLength;
  48224. width *= 0.5;
  48225. height *= 0.5;
  48226. width = Math.max(1.0, width);
  48227. height = Math.max(1.0, height);
  48228. }
  48229. }
  48230. };
  48231. return DDSTools;
  48232. }());
  48233. Internals.DDSTools = DDSTools;
  48234. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  48235. })(BABYLON || (BABYLON = {}));
  48236. var BABYLON;
  48237. (function (BABYLON) {
  48238. var CannonJSPlugin = (function () {
  48239. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  48240. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  48241. if (iterations === void 0) { iterations = 10; }
  48242. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  48243. this.name = "CannonJSPlugin";
  48244. this._physicsMaterials = [];
  48245. this._fixedTimeStep = 1 / 60;
  48246. //See https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  48247. this._currentCollisionGroup = 2;
  48248. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  48249. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  48250. this._tmpPosition = BABYLON.Vector3.Zero();
  48251. this._tmpQuaternion = new BABYLON.Quaternion();
  48252. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  48253. this._tmpDeltaRotation = new BABYLON.Quaternion();
  48254. this._tmpUnityRotation = new BABYLON.Quaternion();
  48255. if (!this.isSupported()) {
  48256. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  48257. return;
  48258. }
  48259. this.world = new CANNON.World();
  48260. this.world.broadphase = new CANNON.NaiveBroadphase();
  48261. this.world.solver.iterations = iterations;
  48262. }
  48263. CannonJSPlugin.prototype.setGravity = function (gravity) {
  48264. this.world.gravity.copy(gravity);
  48265. };
  48266. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  48267. this._fixedTimeStep = timeStep;
  48268. };
  48269. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  48270. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta * 1000 : 0, 3);
  48271. };
  48272. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  48273. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  48274. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  48275. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  48276. };
  48277. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  48278. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  48279. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  48280. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  48281. };
  48282. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  48283. //parent-child relationship. Does this impostor has a parent impostor?
  48284. if (impostor.parent) {
  48285. if (impostor.physicsBody) {
  48286. this.removePhysicsBody(impostor);
  48287. //TODO is that needed?
  48288. impostor.forceUpdate();
  48289. }
  48290. return;
  48291. }
  48292. //should a new body be created for this impostor?
  48293. if (impostor.isBodyInitRequired()) {
  48294. var shape = this._createShape(impostor);
  48295. //unregister events, if body is being changed
  48296. var oldBody = impostor.physicsBody;
  48297. if (oldBody) {
  48298. this.removePhysicsBody(impostor);
  48299. }
  48300. //create the body and material
  48301. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  48302. var bodyCreationObject = {
  48303. mass: impostor.getParam("mass"),
  48304. material: material
  48305. };
  48306. // A simple extend, in case native options were used.
  48307. var nativeOptions = impostor.getParam("nativeOptions");
  48308. for (var key in nativeOptions) {
  48309. if (nativeOptions.hasOwnProperty(key)) {
  48310. bodyCreationObject[key] = nativeOptions[key];
  48311. }
  48312. }
  48313. impostor.physicsBody = new CANNON.Body(bodyCreationObject);
  48314. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  48315. this.world.addEventListener("preStep", impostor.beforeStep);
  48316. this.world.addEventListener("postStep", impostor.afterStep);
  48317. impostor.physicsBody.addShape(shape);
  48318. this.world.add(impostor.physicsBody);
  48319. //try to keep the body moving in the right direction by taking old properties.
  48320. //Should be tested!
  48321. if (oldBody) {
  48322. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  48323. impostor.physicsBody[param].copy(oldBody[param]);
  48324. });
  48325. }
  48326. this._processChildMeshes(impostor);
  48327. }
  48328. //now update the body's transformation
  48329. this._updatePhysicsBodyTransformation(impostor);
  48330. };
  48331. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  48332. var _this = this;
  48333. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes() : [];
  48334. if (meshChildren.length) {
  48335. var processMesh = function (localPosition, mesh) {
  48336. var childImpostor = mesh.getPhysicsImpostor();
  48337. if (childImpostor) {
  48338. var parent = childImpostor.parent;
  48339. if (parent !== mainImpostor) {
  48340. var localPosition = mesh.position;
  48341. if (childImpostor.physicsBody) {
  48342. _this.removePhysicsBody(childImpostor);
  48343. childImpostor.physicsBody = null;
  48344. }
  48345. childImpostor.parent = mainImpostor;
  48346. childImpostor.resetUpdateFlags();
  48347. mainImpostor.physicsBody.addShape(_this._createShape(childImpostor), new CANNON.Vec3(localPosition.x, localPosition.y, localPosition.z));
  48348. //Add the mass of the children.
  48349. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  48350. }
  48351. }
  48352. mesh.getChildMeshes().forEach(processMesh.bind(_this, mesh.position));
  48353. };
  48354. meshChildren.forEach(processMesh.bind(this, BABYLON.Vector3.Zero()));
  48355. }
  48356. };
  48357. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  48358. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  48359. this.world.removeEventListener("preStep", impostor.beforeStep);
  48360. this.world.removeEventListener("postStep", impostor.afterStep);
  48361. this.world.remove(impostor.physicsBody);
  48362. };
  48363. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  48364. var mainBody = impostorJoint.mainImpostor.physicsBody;
  48365. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  48366. if (!mainBody || !connectedBody) {
  48367. return;
  48368. }
  48369. var constraint;
  48370. var jointData = impostorJoint.joint.jointData;
  48371. //TODO - https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  48372. var constraintData = {
  48373. pivotA: jointData.mainPivot ? new CANNON.Vec3().copy(jointData.mainPivot) : null,
  48374. pivotB: jointData.connectedPivot ? new CANNON.Vec3().copy(jointData.connectedPivot) : null,
  48375. axisA: jointData.mainAxis ? new CANNON.Vec3().copy(jointData.mainAxis) : null,
  48376. axisB: jointData.connectedAxis ? new CANNON.Vec3().copy(jointData.connectedAxis) : null,
  48377. maxForce: jointData.nativeParams.maxForce,
  48378. collideConnected: !!jointData.collision
  48379. };
  48380. //Not needed, Cannon has a collideConnected flag
  48381. /*if (!jointData.collision) {
  48382. //add 1st body to a collision group of its own, if it is not in 1
  48383. if (mainBody.collisionFilterGroup === 1) {
  48384. mainBody.collisionFilterGroup = this._currentCollisionGroup;
  48385. this._currentCollisionGroup <<= 1;
  48386. }
  48387. if (connectedBody.collisionFilterGroup === 1) {
  48388. connectedBody.collisionFilterGroup = this._currentCollisionGroup;
  48389. this._currentCollisionGroup <<= 1;
  48390. }
  48391. //add their mask to the collisionFilterMask of each other:
  48392. connectedBody.collisionFilterMask = connectedBody.collisionFilterMask | ~mainBody.collisionFilterGroup;
  48393. mainBody.collisionFilterMask = mainBody.collisionFilterMask | ~connectedBody.collisionFilterGroup;
  48394. }*/
  48395. switch (impostorJoint.joint.type) {
  48396. case BABYLON.PhysicsJoint.HingeJoint:
  48397. case BABYLON.PhysicsJoint.Hinge2Joint:
  48398. constraint = new CANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  48399. break;
  48400. case BABYLON.PhysicsJoint.DistanceJoint:
  48401. constraint = new CANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  48402. break;
  48403. case BABYLON.PhysicsJoint.SpringJoint:
  48404. var springData = jointData;
  48405. constraint = new CANNON.Spring(mainBody, connectedBody, {
  48406. restLength: springData.length,
  48407. stiffness: springData.stiffness,
  48408. damping: springData.damping,
  48409. localAnchorA: constraintData.pivotA,
  48410. localAnchorB: constraintData.pivotB
  48411. });
  48412. break;
  48413. case BABYLON.PhysicsJoint.LockJoint:
  48414. constraint = new CANNON.LockConstraint(mainBody, connectedBody, constraintData);
  48415. break;
  48416. case BABYLON.PhysicsJoint.PointToPointJoint:
  48417. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  48418. default:
  48419. constraint = new CANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  48420. break;
  48421. }
  48422. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  48423. constraint.collideConnected = !!jointData.collision;
  48424. impostorJoint.joint.physicsJoint = constraint;
  48425. //don't add spring as constraint, as it is not one.
  48426. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  48427. this.world.addConstraint(constraint);
  48428. }
  48429. else {
  48430. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  48431. constraint.applyForce();
  48432. });
  48433. }
  48434. };
  48435. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  48436. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  48437. };
  48438. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  48439. var index;
  48440. var mat;
  48441. for (index = 0; index < this._physicsMaterials.length; index++) {
  48442. mat = this._physicsMaterials[index];
  48443. if (mat.friction === friction && mat.restitution === restitution) {
  48444. return mat;
  48445. }
  48446. }
  48447. var currentMat = new CANNON.Material(name);
  48448. currentMat.friction = friction;
  48449. currentMat.restitution = restitution;
  48450. this._physicsMaterials.push(currentMat);
  48451. return currentMat;
  48452. };
  48453. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  48454. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  48455. };
  48456. CannonJSPlugin.prototype._createShape = function (impostor) {
  48457. var object = impostor.object;
  48458. var returnValue;
  48459. var extendSize = impostor.getObjectExtendSize();
  48460. switch (impostor.type) {
  48461. case BABYLON.PhysicsEngine.SphereImpostor:
  48462. var radiusX = extendSize.x;
  48463. var radiusY = extendSize.y;
  48464. var radiusZ = extendSize.z;
  48465. returnValue = new CANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  48466. break;
  48467. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  48468. case BABYLON.PhysicsImpostor.CylinderImpostor:
  48469. returnValue = new CANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  48470. break;
  48471. case BABYLON.PhysicsImpostor.BoxImpostor:
  48472. var box = extendSize.scale(0.5);
  48473. returnValue = new CANNON.Box(new CANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  48474. break;
  48475. case BABYLON.PhysicsImpostor.PlaneImpostor:
  48476. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  48477. returnValue = new CANNON.Plane();
  48478. break;
  48479. case BABYLON.PhysicsImpostor.MeshImpostor:
  48480. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  48481. var rawFaces = object.getIndices ? object.getIndices() : [];
  48482. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  48483. returnValue = new CANNON.Trimesh(rawVerts, rawFaces);
  48484. break;
  48485. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  48486. returnValue = this._createHeightmap(object);
  48487. break;
  48488. case BABYLON.PhysicsImpostor.ParticleImpostor:
  48489. returnValue = new CANNON.Particle();
  48490. break;
  48491. }
  48492. return returnValue;
  48493. };
  48494. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  48495. var pos = object.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  48496. var matrix = [];
  48497. //For now pointDepth will not be used and will be automatically calculated.
  48498. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  48499. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  48500. var dim = Math.min(object.getBoundingInfo().boundingBox.extendSize.x, object.getBoundingInfo().boundingBox.extendSize.z);
  48501. var elementSize = dim * 2 / arraySize;
  48502. var minY = object.getBoundingInfo().boundingBox.extendSize.y;
  48503. for (var i = 0; i < pos.length; i = i + 3) {
  48504. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  48505. var z = Math.round(((pos[i + 2]) / elementSize - arraySize / 2) * -1);
  48506. var y = pos[i + 1] + minY;
  48507. if (!matrix[x]) {
  48508. matrix[x] = [];
  48509. }
  48510. if (!matrix[x][z]) {
  48511. matrix[x][z] = y;
  48512. }
  48513. matrix[x][z] = Math.max(y, matrix[x][z]);
  48514. }
  48515. for (var x = 0; x <= arraySize; ++x) {
  48516. if (!matrix[x]) {
  48517. var loc = 1;
  48518. while (!matrix[(x + loc) % arraySize]) {
  48519. loc++;
  48520. }
  48521. matrix[x] = matrix[(x + loc) % arraySize].slice();
  48522. }
  48523. for (var z = 0; z <= arraySize; ++z) {
  48524. if (!matrix[x][z]) {
  48525. var loc = 1;
  48526. var newValue;
  48527. while (newValue === undefined) {
  48528. newValue = matrix[x][(z + loc++) % arraySize];
  48529. }
  48530. matrix[x][z] = newValue;
  48531. }
  48532. }
  48533. }
  48534. var shape = new CANNON.Heightfield(matrix, {
  48535. elementSize: elementSize
  48536. });
  48537. //For future reference, needed for body transformation
  48538. shape.minY = minY;
  48539. return shape;
  48540. };
  48541. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  48542. var object = impostor.object;
  48543. //make sure it is updated...
  48544. object.computeWorldMatrix && object.computeWorldMatrix(true);
  48545. // The delta between the mesh position and the mesh bounding box center
  48546. var center = impostor.getObjectCenter();
  48547. var extendSize = impostor.getObjectExtendSize();
  48548. this._tmpDeltaPosition.copyFrom(object.position.subtract(center));
  48549. this._tmpPosition.copyFrom(center);
  48550. var quaternion = object.rotationQuaternion;
  48551. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  48552. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  48553. //-90 DEG in X, precalculated
  48554. quaternion = quaternion.multiply(this._minus90X);
  48555. //Invert! (Precalculated, 90 deg in X)
  48556. //No need to clone. this will never change.
  48557. impostor.setDeltaRotation(this._plus90X);
  48558. }
  48559. //If it is a heightfield, if should be centered.
  48560. if (impostor.type === BABYLON.PhysicsEngine.HeightmapImpostor) {
  48561. var mesh = object;
  48562. //calculate the correct body position:
  48563. var rotationQuaternion = mesh.rotationQuaternion;
  48564. mesh.rotationQuaternion = this._tmpUnityRotation;
  48565. mesh.computeWorldMatrix(true);
  48566. //get original center with no rotation
  48567. var c = center.clone();
  48568. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  48569. //rotation is back
  48570. mesh.rotationQuaternion = rotationQuaternion;
  48571. //calculate the new center using a pivot (since Cannon.js doesn't center height maps)
  48572. var p = BABYLON.Matrix.Translation(mesh.getBoundingInfo().boundingBox.extendSize.x, 0, -mesh.getBoundingInfo().boundingBox.extendSize.z);
  48573. mesh.setPivotMatrix(p);
  48574. mesh.computeWorldMatrix(true);
  48575. //calculate the translation
  48576. var translation = mesh.getBoundingInfo().boundingBox.center.subtract(center).subtract(mesh.position).negate();
  48577. this._tmpPosition.copyFromFloats(translation.x, translation.y - mesh.getBoundingInfo().boundingBox.extendSize.y, translation.z);
  48578. //add it inverted to the delta
  48579. this._tmpDeltaPosition.copyFrom(mesh.getBoundingInfo().boundingBox.center.subtract(c));
  48580. this._tmpDeltaPosition.y += mesh.getBoundingInfo().boundingBox.extendSize.y;
  48581. mesh.setPivotMatrix(oldPivot);
  48582. mesh.computeWorldMatrix(true);
  48583. }
  48584. else if (impostor.type === BABYLON.PhysicsEngine.MeshImpostor) {
  48585. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  48586. this._tmpPosition.copyFrom(object.position);
  48587. }
  48588. impostor.setDeltaPosition(this._tmpDeltaPosition);
  48589. //Now update the impostor object
  48590. impostor.physicsBody.position.copy(this._tmpPosition);
  48591. impostor.physicsBody.quaternion.copy(quaternion);
  48592. };
  48593. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  48594. impostor.object.position.copyFrom(impostor.physicsBody.position);
  48595. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  48596. };
  48597. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  48598. impostor.physicsBody.position.copy(newPosition);
  48599. impostor.physicsBody.quaternion.copy(newRotation);
  48600. };
  48601. CannonJSPlugin.prototype.isSupported = function () {
  48602. return window.CANNON !== undefined;
  48603. };
  48604. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  48605. impostor.physicsBody.velocity.copy(velocity);
  48606. };
  48607. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  48608. impostor.physicsBody.angularVelocity.copy(velocity);
  48609. };
  48610. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  48611. var v = impostor.physicsBody.velocity;
  48612. if (!v)
  48613. return null;
  48614. return new BABYLON.Vector3(v.x, v.y, v.z);
  48615. };
  48616. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  48617. var v = impostor.physicsBody.angularVelocity;
  48618. if (!v)
  48619. return null;
  48620. return new BABYLON.Vector3(v.x, v.y, v.z);
  48621. };
  48622. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  48623. impostor.physicsBody.mass = mass;
  48624. impostor.physicsBody.updateMassProperties();
  48625. };
  48626. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  48627. impostor.physicsBody.sleep();
  48628. };
  48629. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  48630. impostor.physicsBody.wakeUp();
  48631. };
  48632. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  48633. joint.physicsJoint.distance = maxDistance;
  48634. };
  48635. CannonJSPlugin.prototype.enableMotor = function (joint, motorIndex) {
  48636. if (!motorIndex) {
  48637. joint.physicsJoint.enableMotor();
  48638. }
  48639. };
  48640. CannonJSPlugin.prototype.disableMotor = function (joint, motorIndex) {
  48641. if (!motorIndex) {
  48642. joint.physicsJoint.disableMotor();
  48643. }
  48644. };
  48645. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  48646. if (!motorIndex) {
  48647. joint.physicsJoint.enableMotor();
  48648. joint.physicsJoint.setMotorSpeed(speed);
  48649. if (maxForce) {
  48650. this.setLimit(joint, maxForce);
  48651. }
  48652. }
  48653. };
  48654. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  48655. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  48656. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  48657. };
  48658. CannonJSPlugin.prototype.dispose = function () {
  48659. //nothing to do, actually.
  48660. };
  48661. return CannonJSPlugin;
  48662. }());
  48663. BABYLON.CannonJSPlugin = CannonJSPlugin;
  48664. })(BABYLON || (BABYLON = {}));
  48665. var BABYLON;
  48666. (function (BABYLON) {
  48667. var OimoJSPlugin = (function () {
  48668. function OimoJSPlugin(iterations) {
  48669. this.name = "OimoJSPlugin";
  48670. this._tmpImpostorsArray = [];
  48671. this._tmpPositionVector = BABYLON.Vector3.Zero();
  48672. this.world = new OIMO.World(1 / 60, 2, iterations, true);
  48673. this.world.clear();
  48674. //making sure no stats are calculated
  48675. this.world.isNoStat = true;
  48676. }
  48677. OimoJSPlugin.prototype.setGravity = function (gravity) {
  48678. this.world.gravity.copy(gravity);
  48679. };
  48680. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  48681. this.world.timeStep = timeStep;
  48682. };
  48683. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  48684. var _this = this;
  48685. impostors.forEach(function (impostor) {
  48686. impostor.beforeStep();
  48687. });
  48688. this.world.step();
  48689. impostors.forEach(function (impostor) {
  48690. impostor.afterStep();
  48691. //update the ordered impostors array
  48692. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  48693. });
  48694. //check for collisions
  48695. var contact = this.world.contacts;
  48696. while (contact !== null) {
  48697. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  48698. contact = contact.next;
  48699. continue;
  48700. }
  48701. //is this body colliding with any other? get the impostor
  48702. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  48703. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  48704. if (!mainImpostor || !collidingImpostor) {
  48705. contact = contact.next;
  48706. continue;
  48707. }
  48708. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  48709. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  48710. contact = contact.next;
  48711. }
  48712. };
  48713. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  48714. var mass = impostor.physicsBody.massInfo.mass;
  48715. impostor.physicsBody.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  48716. };
  48717. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  48718. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  48719. this.applyImpulse(impostor, force, contactPoint);
  48720. };
  48721. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  48722. var _this = this;
  48723. //parent-child relationship. Does this impostor has a parent impostor?
  48724. if (impostor.parent) {
  48725. if (impostor.physicsBody) {
  48726. this.removePhysicsBody(impostor);
  48727. //TODO is that needed?
  48728. impostor.forceUpdate();
  48729. }
  48730. return;
  48731. }
  48732. if (impostor.isBodyInitRequired()) {
  48733. var bodyConfig = {
  48734. name: impostor.uniqueId,
  48735. //Oimo must have mass, also for static objects.
  48736. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  48737. size: [],
  48738. type: [],
  48739. pos: [],
  48740. rot: [],
  48741. move: impostor.getParam("mass") !== 0,
  48742. //Supporting older versions of Oimo
  48743. world: this.world
  48744. };
  48745. var impostors = [impostor];
  48746. function addToArray(parent) {
  48747. if (!parent.getChildMeshes)
  48748. return;
  48749. parent.getChildMeshes().forEach(function (m) {
  48750. if (m.physicsImpostor) {
  48751. impostors.push(m.physicsImpostor);
  48752. m.physicsImpostor._init();
  48753. }
  48754. });
  48755. }
  48756. addToArray(impostor.object);
  48757. function checkWithEpsilon(value) {
  48758. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  48759. }
  48760. impostors.forEach(function (i) {
  48761. //get the correct bounding box
  48762. var oldQuaternion = i.object.rotationQuaternion;
  48763. var rot = new OIMO.Euler().setFromQuaternion({
  48764. x: impostor.object.rotationQuaternion.x,
  48765. y: impostor.object.rotationQuaternion.y,
  48766. z: impostor.object.rotationQuaternion.z,
  48767. s: impostor.object.rotationQuaternion.w
  48768. });
  48769. var extendSize = i.getObjectExtendSize();
  48770. if (i === impostor) {
  48771. var center = impostor.getObjectCenter();
  48772. impostor.object.position.subtractToRef(center, _this._tmpPositionVector);
  48773. //Can also use Array.prototype.push.apply
  48774. bodyConfig.pos.push(center.x);
  48775. bodyConfig.pos.push(center.y);
  48776. bodyConfig.pos.push(center.z);
  48777. //tmp solution
  48778. bodyConfig.rot.push(rot.x / (OIMO.degtorad || OIMO.TO_RAD));
  48779. bodyConfig.rot.push(rot.y / (OIMO.degtorad || OIMO.TO_RAD));
  48780. bodyConfig.rot.push(rot.z / (OIMO.degtorad || OIMO.TO_RAD));
  48781. }
  48782. else {
  48783. bodyConfig.pos.push(i.object.position.x);
  48784. bodyConfig.pos.push(i.object.position.y);
  48785. bodyConfig.pos.push(i.object.position.z);
  48786. //tmp solution until https://github.com/lo-th/Oimo.js/pull/37 is merged
  48787. bodyConfig.rot.push(0);
  48788. bodyConfig.rot.push(0);
  48789. bodyConfig.rot.push(0);
  48790. }
  48791. // register mesh
  48792. switch (i.type) {
  48793. case BABYLON.PhysicsImpostor.ParticleImpostor:
  48794. BABYLON.Tools.Warn("No Particle support in Oimo.js. using SphereImpostor instead");
  48795. case BABYLON.PhysicsImpostor.SphereImpostor:
  48796. var radiusX = extendSize.x;
  48797. var radiusY = extendSize.y;
  48798. var radiusZ = extendSize.z;
  48799. var size = Math.max(checkWithEpsilon(radiusX), checkWithEpsilon(radiusY), checkWithEpsilon(radiusZ)) / 2;
  48800. bodyConfig.type.push('sphere');
  48801. //due to the way oimo works with compounds, add 3 times
  48802. bodyConfig.size.push(size);
  48803. bodyConfig.size.push(size);
  48804. bodyConfig.size.push(size);
  48805. break;
  48806. case BABYLON.PhysicsImpostor.CylinderImpostor:
  48807. var sizeX = checkWithEpsilon(extendSize.x) / 2;
  48808. var sizeY = checkWithEpsilon(extendSize.y);
  48809. bodyConfig.type.push('cylinder');
  48810. bodyConfig.size.push(sizeX);
  48811. bodyConfig.size.push(sizeY);
  48812. //due to the way oimo works with compounds, add one more value.
  48813. bodyConfig.size.push(sizeY);
  48814. break;
  48815. case BABYLON.PhysicsImpostor.PlaneImpostor:
  48816. case BABYLON.PhysicsImpostor.BoxImpostor:
  48817. default:
  48818. var sizeX = checkWithEpsilon(extendSize.x);
  48819. var sizeY = checkWithEpsilon(extendSize.y);
  48820. var sizeZ = checkWithEpsilon(extendSize.z);
  48821. bodyConfig.type.push('box');
  48822. bodyConfig.size.push(sizeX);
  48823. bodyConfig.size.push(sizeY);
  48824. bodyConfig.size.push(sizeZ);
  48825. break;
  48826. }
  48827. //actually not needed, but hey...
  48828. i.object.rotationQuaternion = oldQuaternion;
  48829. });
  48830. impostor.physicsBody = new OIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  48831. }
  48832. else {
  48833. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  48834. }
  48835. impostor.setDeltaPosition(this._tmpPositionVector);
  48836. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  48837. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  48838. };
  48839. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  48840. //impostor.physicsBody.dispose();
  48841. //Same as : (older oimo versions)
  48842. this.world.removeRigidBody(impostor.physicsBody);
  48843. };
  48844. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  48845. var mainBody = impostorJoint.mainImpostor.physicsBody;
  48846. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  48847. if (!mainBody || !connectedBody) {
  48848. return;
  48849. }
  48850. var jointData = impostorJoint.joint.jointData;
  48851. var options = jointData.nativeParams || {};
  48852. var type;
  48853. var nativeJointData = {
  48854. body1: mainBody,
  48855. body2: connectedBody,
  48856. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  48857. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  48858. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  48859. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  48860. min: options.min,
  48861. max: options.max,
  48862. collision: options.collision || jointData.collision,
  48863. spring: options.spring,
  48864. //supporting older version of Oimo
  48865. world: this.world
  48866. };
  48867. switch (impostorJoint.joint.type) {
  48868. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  48869. type = "jointBall";
  48870. break;
  48871. case BABYLON.PhysicsJoint.SpringJoint:
  48872. BABYLON.Tools.Warn("Oimo.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  48873. var springData = jointData;
  48874. nativeJointData.min = springData.length || nativeJointData.min;
  48875. //Max should also be set, just make sure it is at least min
  48876. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  48877. case BABYLON.PhysicsJoint.DistanceJoint:
  48878. type = "jointDistance";
  48879. nativeJointData.max = jointData.maxDistance;
  48880. break;
  48881. case BABYLON.PhysicsJoint.PrismaticJoint:
  48882. type = "jointPrisme";
  48883. break;
  48884. case BABYLON.PhysicsJoint.SliderJoint:
  48885. type = "jointSlide";
  48886. break;
  48887. case BABYLON.PhysicsJoint.WheelJoint:
  48888. type = "jointWheel";
  48889. break;
  48890. case BABYLON.PhysicsJoint.HingeJoint:
  48891. default:
  48892. type = "jointHinge";
  48893. break;
  48894. }
  48895. nativeJointData.type = type;
  48896. impostorJoint.joint.physicsJoint = new OIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  48897. };
  48898. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  48899. //Bug in Oimo prevents us from disposing a joint in the playground
  48900. //joint.joint.physicsJoint.dispose();
  48901. //So we will bruteforce it!
  48902. try {
  48903. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  48904. }
  48905. catch (e) {
  48906. BABYLON.Tools.Warn(e);
  48907. }
  48908. };
  48909. OimoJSPlugin.prototype.isSupported = function () {
  48910. return OIMO !== undefined;
  48911. };
  48912. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  48913. if (!impostor.physicsBody.sleeping) {
  48914. //TODO check that
  48915. if (impostor.physicsBody.shapes.next) {
  48916. var parentShape = this._getLastShape(impostor.physicsBody);
  48917. impostor.object.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  48918. impostor.object.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  48919. impostor.object.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  48920. }
  48921. else {
  48922. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  48923. }
  48924. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  48925. impostor.object.rotationQuaternion.normalize();
  48926. }
  48927. };
  48928. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  48929. var body = impostor.physicsBody;
  48930. body.position.init(newPosition.x * OIMO.INV_SCALE, newPosition.y * OIMO.INV_SCALE, newPosition.z * OIMO.INV_SCALE);
  48931. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  48932. body.syncShapes();
  48933. body.awake();
  48934. };
  48935. OimoJSPlugin.prototype._getLastShape = function (body) {
  48936. var lastShape = body.shapes;
  48937. while (lastShape.next) {
  48938. lastShape = lastShape.next;
  48939. }
  48940. return lastShape;
  48941. };
  48942. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  48943. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  48944. };
  48945. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  48946. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  48947. };
  48948. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  48949. var v = impostor.physicsBody.linearVelocity;
  48950. if (!v)
  48951. return null;
  48952. return new BABYLON.Vector3(v.x, v.y, v.z);
  48953. };
  48954. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  48955. var v = impostor.physicsBody.angularVelocity;
  48956. if (!v)
  48957. return null;
  48958. return new BABYLON.Vector3(v.x, v.y, v.z);
  48959. };
  48960. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  48961. var staticBody = mass === 0;
  48962. //this will actually set the body's density and not its mass.
  48963. //But this is how oimo treats the mass variable.
  48964. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  48965. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  48966. };
  48967. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  48968. impostor.physicsBody.sleep();
  48969. };
  48970. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  48971. impostor.physicsBody.awake();
  48972. };
  48973. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  48974. joint.physicsJoint.limitMotoe.upperLimit = maxDistance;
  48975. if (minDistance !== void 0) {
  48976. joint.physicsJoint.limitMotoe.lowerLimit = minDistance;
  48977. }
  48978. };
  48979. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  48980. //TODO separate rotational and transational motors.
  48981. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  48982. if (motor) {
  48983. motor.setMotor(speed, maxForce);
  48984. }
  48985. };
  48986. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  48987. //TODO separate rotational and transational motors.
  48988. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  48989. if (motor) {
  48990. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  48991. }
  48992. };
  48993. OimoJSPlugin.prototype.dispose = function () {
  48994. this.world.clear();
  48995. };
  48996. return OimoJSPlugin;
  48997. }());
  48998. BABYLON.OimoJSPlugin = OimoJSPlugin;
  48999. })(BABYLON || (BABYLON = {}));
  49000. var BABYLON;
  49001. (function (BABYLON) {
  49002. var DisplayPassPostProcess = (function (_super) {
  49003. __extends(DisplayPassPostProcess, _super);
  49004. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  49005. _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable);
  49006. }
  49007. return DisplayPassPostProcess;
  49008. }(BABYLON.PostProcess));
  49009. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  49010. })(BABYLON || (BABYLON = {}));
  49011. var BABYLON;
  49012. (function (BABYLON) {
  49013. var SimplificationSettings = (function () {
  49014. function SimplificationSettings(quality, distance, optimizeMesh) {
  49015. this.quality = quality;
  49016. this.distance = distance;
  49017. this.optimizeMesh = optimizeMesh;
  49018. }
  49019. return SimplificationSettings;
  49020. }());
  49021. BABYLON.SimplificationSettings = SimplificationSettings;
  49022. var SimplificationQueue = (function () {
  49023. function SimplificationQueue() {
  49024. this.running = false;
  49025. this._simplificationArray = [];
  49026. }
  49027. SimplificationQueue.prototype.addTask = function (task) {
  49028. this._simplificationArray.push(task);
  49029. };
  49030. SimplificationQueue.prototype.executeNext = function () {
  49031. var task = this._simplificationArray.pop();
  49032. if (task) {
  49033. this.running = true;
  49034. this.runSimplification(task);
  49035. }
  49036. else {
  49037. this.running = false;
  49038. }
  49039. };
  49040. SimplificationQueue.prototype.runSimplification = function (task) {
  49041. var _this = this;
  49042. if (task.parallelProcessing) {
  49043. //parallel simplifier
  49044. task.settings.forEach(function (setting) {
  49045. var simplifier = _this.getSimplifier(task);
  49046. simplifier.simplify(setting, function (newMesh) {
  49047. task.mesh.addLODLevel(setting.distance, newMesh);
  49048. newMesh.isVisible = true;
  49049. //check if it is the last
  49050. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  49051. //all done, run the success callback.
  49052. task.successCallback();
  49053. }
  49054. _this.executeNext();
  49055. });
  49056. });
  49057. }
  49058. else {
  49059. //single simplifier.
  49060. var simplifier = this.getSimplifier(task);
  49061. var runDecimation = function (setting, callback) {
  49062. simplifier.simplify(setting, function (newMesh) {
  49063. task.mesh.addLODLevel(setting.distance, newMesh);
  49064. newMesh.isVisible = true;
  49065. //run the next quality level
  49066. callback();
  49067. });
  49068. };
  49069. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  49070. runDecimation(task.settings[loop.index], function () {
  49071. loop.executeNext();
  49072. });
  49073. }, function () {
  49074. //execution ended, run the success callback.
  49075. if (task.successCallback) {
  49076. task.successCallback();
  49077. }
  49078. _this.executeNext();
  49079. });
  49080. }
  49081. };
  49082. SimplificationQueue.prototype.getSimplifier = function (task) {
  49083. switch (task.simplificationType) {
  49084. case SimplificationType.QUADRATIC:
  49085. default:
  49086. return new QuadraticErrorSimplification(task.mesh);
  49087. }
  49088. };
  49089. return SimplificationQueue;
  49090. }());
  49091. BABYLON.SimplificationQueue = SimplificationQueue;
  49092. /**
  49093. * The implemented types of simplification.
  49094. * At the moment only Quadratic Error Decimation is implemented.
  49095. */
  49096. (function (SimplificationType) {
  49097. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  49098. })(BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  49099. var SimplificationType = BABYLON.SimplificationType;
  49100. var DecimationTriangle = (function () {
  49101. function DecimationTriangle(vertices) {
  49102. this.vertices = vertices;
  49103. this.error = new Array(4);
  49104. this.deleted = false;
  49105. this.isDirty = false;
  49106. this.deletePending = false;
  49107. this.borderFactor = 0;
  49108. }
  49109. return DecimationTriangle;
  49110. }());
  49111. BABYLON.DecimationTriangle = DecimationTriangle;
  49112. var DecimationVertex = (function () {
  49113. function DecimationVertex(position, id) {
  49114. this.position = position;
  49115. this.id = id;
  49116. this.isBorder = true;
  49117. this.q = new QuadraticMatrix();
  49118. this.triangleCount = 0;
  49119. this.triangleStart = 0;
  49120. this.originalOffsets = [];
  49121. }
  49122. DecimationVertex.prototype.updatePosition = function (newPosition) {
  49123. this.position.copyFrom(newPosition);
  49124. };
  49125. return DecimationVertex;
  49126. }());
  49127. BABYLON.DecimationVertex = DecimationVertex;
  49128. var QuadraticMatrix = (function () {
  49129. function QuadraticMatrix(data) {
  49130. this.data = new Array(10);
  49131. for (var i = 0; i < 10; ++i) {
  49132. if (data && data[i]) {
  49133. this.data[i] = data[i];
  49134. }
  49135. else {
  49136. this.data[i] = 0;
  49137. }
  49138. }
  49139. }
  49140. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  49141. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  49142. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  49143. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  49144. return det;
  49145. };
  49146. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  49147. for (var i = 0; i < 10; ++i) {
  49148. this.data[i] += matrix.data[i];
  49149. }
  49150. };
  49151. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  49152. for (var i = 0; i < 10; ++i) {
  49153. this.data[i] += data[i];
  49154. }
  49155. };
  49156. QuadraticMatrix.prototype.add = function (matrix) {
  49157. var m = new QuadraticMatrix();
  49158. for (var i = 0; i < 10; ++i) {
  49159. m.data[i] = this.data[i] + matrix.data[i];
  49160. }
  49161. return m;
  49162. };
  49163. QuadraticMatrix.FromData = function (a, b, c, d) {
  49164. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  49165. };
  49166. //returning an array to avoid garbage collection
  49167. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  49168. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  49169. };
  49170. return QuadraticMatrix;
  49171. }());
  49172. BABYLON.QuadraticMatrix = QuadraticMatrix;
  49173. var Reference = (function () {
  49174. function Reference(vertexId, triangleId) {
  49175. this.vertexId = vertexId;
  49176. this.triangleId = triangleId;
  49177. }
  49178. return Reference;
  49179. }());
  49180. BABYLON.Reference = Reference;
  49181. /**
  49182. * An implementation of the Quadratic Error simplification algorithm.
  49183. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  49184. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  49185. * @author RaananW
  49186. */
  49187. var QuadraticErrorSimplification = (function () {
  49188. function QuadraticErrorSimplification(_mesh) {
  49189. this._mesh = _mesh;
  49190. this.initialized = false;
  49191. this.syncIterations = 5000;
  49192. this.aggressiveness = 7;
  49193. this.decimationIterations = 100;
  49194. this.boundingBoxEpsilon = BABYLON.Epsilon;
  49195. }
  49196. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  49197. var _this = this;
  49198. this.initDecimatedMesh();
  49199. //iterating through the submeshes array, one after the other.
  49200. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  49201. _this.initWithMesh(loop.index, function () {
  49202. _this.runDecimation(settings, loop.index, function () {
  49203. loop.executeNext();
  49204. });
  49205. }, settings.optimizeMesh);
  49206. }, function () {
  49207. setTimeout(function () {
  49208. successCallback(_this._reconstructedMesh);
  49209. }, 0);
  49210. });
  49211. };
  49212. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  49213. var _this = this;
  49214. var gCount = 0;
  49215. triangle.vertices.forEach(function (vertex) {
  49216. var count = 0;
  49217. var vPos = vertex.position;
  49218. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  49219. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  49220. ++count;
  49221. if (bbox.maximum.y === vPos.y || vPos.y === bbox.minimum.y)
  49222. ++count;
  49223. if (bbox.maximum.z === vPos.z || vPos.z === bbox.minimum.z)
  49224. ++count;
  49225. if (count > 1) {
  49226. ++gCount;
  49227. }
  49228. ;
  49229. });
  49230. if (gCount > 1) {
  49231. console.log(triangle, gCount);
  49232. }
  49233. return gCount > 1;
  49234. };
  49235. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  49236. var _this = this;
  49237. var targetCount = ~~(this.triangles.length * settings.quality);
  49238. var deletedTriangles = 0;
  49239. var triangleCount = this.triangles.length;
  49240. var iterationFunction = function (iteration, callback) {
  49241. setTimeout(function () {
  49242. if (iteration % 5 === 0) {
  49243. _this.updateMesh(iteration === 0);
  49244. }
  49245. for (var i = 0; i < _this.triangles.length; ++i) {
  49246. _this.triangles[i].isDirty = false;
  49247. }
  49248. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  49249. var trianglesIterator = function (i) {
  49250. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  49251. var t = _this.triangles[tIdx];
  49252. if (!t)
  49253. return;
  49254. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  49255. return;
  49256. }
  49257. for (var j = 0; j < 3; ++j) {
  49258. if (t.error[j] < threshold) {
  49259. var deleted0 = [];
  49260. var deleted1 = [];
  49261. var v0 = t.vertices[j];
  49262. var v1 = t.vertices[(j + 1) % 3];
  49263. if (v0.isBorder || v1.isBorder)
  49264. continue;
  49265. var p = BABYLON.Vector3.Zero();
  49266. var n = BABYLON.Vector3.Zero();
  49267. var uv = BABYLON.Vector2.Zero();
  49268. var color = new BABYLON.Color4(0, 0, 0, 1);
  49269. _this.calculateError(v0, v1, p, n, uv, color);
  49270. var delTr = [];
  49271. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  49272. continue;
  49273. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  49274. continue;
  49275. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  49276. continue;
  49277. var uniqueArray = [];
  49278. delTr.forEach(function (deletedT) {
  49279. if (uniqueArray.indexOf(deletedT) === -1) {
  49280. deletedT.deletePending = true;
  49281. uniqueArray.push(deletedT);
  49282. }
  49283. });
  49284. if (uniqueArray.length % 2 !== 0) {
  49285. continue;
  49286. }
  49287. v0.q = v1.q.add(v0.q);
  49288. v0.updatePosition(p);
  49289. var tStart = _this.references.length;
  49290. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  49291. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  49292. var tCount = _this.references.length - tStart;
  49293. if (tCount <= v0.triangleCount) {
  49294. if (tCount) {
  49295. for (var c = 0; c < tCount; c++) {
  49296. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  49297. }
  49298. }
  49299. }
  49300. else {
  49301. v0.triangleStart = tStart;
  49302. }
  49303. v0.triangleCount = tCount;
  49304. break;
  49305. }
  49306. }
  49307. };
  49308. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  49309. }, 0);
  49310. };
  49311. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  49312. if (triangleCount - deletedTriangles <= targetCount)
  49313. loop.breakLoop();
  49314. else {
  49315. iterationFunction(loop.index, function () {
  49316. loop.executeNext();
  49317. });
  49318. }
  49319. }, function () {
  49320. setTimeout(function () {
  49321. //reconstruct this part of the mesh
  49322. _this.reconstructMesh(submeshIndex);
  49323. successCallback();
  49324. }, 0);
  49325. });
  49326. };
  49327. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  49328. var _this = this;
  49329. this.vertices = [];
  49330. this.triangles = [];
  49331. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  49332. var indices = this._mesh.getIndices();
  49333. var submesh = this._mesh.subMeshes[submeshIndex];
  49334. var findInVertices = function (positionToSearch) {
  49335. if (optimizeMesh) {
  49336. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  49337. if (_this.vertices[ii].position.equals(positionToSearch)) {
  49338. return _this.vertices[ii];
  49339. }
  49340. }
  49341. }
  49342. return null;
  49343. };
  49344. var vertexReferences = [];
  49345. var vertexInit = function (i) {
  49346. var offset = i + submesh.verticesStart;
  49347. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  49348. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  49349. vertex.originalOffsets.push(offset);
  49350. if (vertex.id === _this.vertices.length) {
  49351. _this.vertices.push(vertex);
  49352. }
  49353. vertexReferences.push(vertex.id);
  49354. };
  49355. //var totalVertices = mesh.getTotalVertices();
  49356. var totalVertices = submesh.verticesCount;
  49357. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  49358. var indicesInit = function (i) {
  49359. var offset = (submesh.indexStart / 3) + i;
  49360. var pos = (offset * 3);
  49361. var i0 = indices[pos + 0];
  49362. var i1 = indices[pos + 1];
  49363. var i2 = indices[pos + 2];
  49364. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  49365. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  49366. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  49367. var triangle = new DecimationTriangle([v0, v1, v2]);
  49368. triangle.originalOffset = pos;
  49369. _this.triangles.push(triangle);
  49370. };
  49371. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  49372. _this.init(callback);
  49373. });
  49374. });
  49375. };
  49376. QuadraticErrorSimplification.prototype.init = function (callback) {
  49377. var _this = this;
  49378. var triangleInit1 = function (i) {
  49379. var t = _this.triangles[i];
  49380. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  49381. for (var j = 0; j < 3; j++) {
  49382. 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))));
  49383. }
  49384. };
  49385. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  49386. var triangleInit2 = function (i) {
  49387. var t = _this.triangles[i];
  49388. for (var j = 0; j < 3; ++j) {
  49389. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  49390. }
  49391. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  49392. };
  49393. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  49394. _this.initialized = true;
  49395. callback();
  49396. });
  49397. });
  49398. };
  49399. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  49400. var newTriangles = [];
  49401. var i;
  49402. for (i = 0; i < this.vertices.length; ++i) {
  49403. this.vertices[i].triangleCount = 0;
  49404. }
  49405. var t;
  49406. var j;
  49407. for (i = 0; i < this.triangles.length; ++i) {
  49408. if (!this.triangles[i].deleted) {
  49409. t = this.triangles[i];
  49410. for (j = 0; j < 3; ++j) {
  49411. t.vertices[j].triangleCount = 1;
  49412. }
  49413. newTriangles.push(t);
  49414. }
  49415. }
  49416. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  49417. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  49418. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  49419. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  49420. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  49421. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  49422. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  49423. var vertexCount = 0;
  49424. for (i = 0; i < this.vertices.length; ++i) {
  49425. var vertex = this.vertices[i];
  49426. vertex.id = vertexCount;
  49427. if (vertex.triangleCount) {
  49428. vertex.originalOffsets.forEach(function (originalOffset) {
  49429. newPositionData.push(vertex.position.x);
  49430. newPositionData.push(vertex.position.y);
  49431. newPositionData.push(vertex.position.z);
  49432. newNormalData.push(normalData[originalOffset * 3]);
  49433. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  49434. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  49435. if (uvs && uvs.length) {
  49436. newUVsData.push(uvs[(originalOffset * 2)]);
  49437. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  49438. }
  49439. else if (colorsData && colorsData.length) {
  49440. newColorsData.push(colorsData[(originalOffset * 4)]);
  49441. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  49442. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  49443. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  49444. }
  49445. ++vertexCount;
  49446. });
  49447. }
  49448. }
  49449. var startingIndex = this._reconstructedMesh.getTotalIndices();
  49450. var startingVertex = this._reconstructedMesh.getTotalVertices();
  49451. var submeshesArray = this._reconstructedMesh.subMeshes;
  49452. this._reconstructedMesh.subMeshes = [];
  49453. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  49454. var originalIndices = this._mesh.getIndices();
  49455. for (i = 0; i < newTriangles.length; ++i) {
  49456. t = newTriangles[i]; //now get the new referencing point for each vertex
  49457. [0, 1, 2].forEach(function (idx) {
  49458. var id = originalIndices[t.originalOffset + idx];
  49459. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  49460. if (offset < 0)
  49461. offset = 0;
  49462. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  49463. });
  49464. }
  49465. //overwriting the old vertex buffers and indices.
  49466. this._reconstructedMesh.setIndices(newIndicesArray);
  49467. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  49468. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  49469. if (newUVsData.length > 0)
  49470. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  49471. if (newColorsData.length > 0)
  49472. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  49473. //create submesh
  49474. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  49475. if (submeshIndex > 0) {
  49476. this._reconstructedMesh.subMeshes = [];
  49477. submeshesArray.forEach(function (submesh) {
  49478. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  49479. });
  49480. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  49481. }
  49482. };
  49483. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  49484. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  49485. this._reconstructedMesh.material = this._mesh.material;
  49486. this._reconstructedMesh.parent = this._mesh.parent;
  49487. this._reconstructedMesh.isVisible = false;
  49488. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  49489. };
  49490. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  49491. for (var i = 0; i < vertex1.triangleCount; ++i) {
  49492. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  49493. if (t.deleted)
  49494. continue;
  49495. var s = this.references[vertex1.triangleStart + i].vertexId;
  49496. var v1 = t.vertices[(s + 1) % 3];
  49497. var v2 = t.vertices[(s + 2) % 3];
  49498. if ((v1 === vertex2 || v2 === vertex2) /* && !this.isTriangleOnBoundingBox(t)*/) {
  49499. deletedArray[i] = true;
  49500. delTr.push(t);
  49501. continue;
  49502. }
  49503. var d1 = v1.position.subtract(point);
  49504. d1 = d1.normalize();
  49505. var d2 = v2.position.subtract(point);
  49506. d2 = d2.normalize();
  49507. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  49508. return true;
  49509. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  49510. deletedArray[i] = false;
  49511. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  49512. return true;
  49513. }
  49514. return false;
  49515. };
  49516. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  49517. var newDeleted = deletedTriangles;
  49518. for (var i = 0; i < vertex.triangleCount; ++i) {
  49519. var ref = this.references[vertex.triangleStart + i];
  49520. var t = this.triangles[ref.triangleId];
  49521. if (t.deleted)
  49522. continue;
  49523. if (deletedArray[i] && t.deletePending) {
  49524. t.deleted = true;
  49525. newDeleted++;
  49526. continue;
  49527. }
  49528. t.vertices[ref.vertexId] = origVertex;
  49529. t.isDirty = true;
  49530. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  49531. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  49532. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  49533. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  49534. this.references.push(ref);
  49535. }
  49536. return newDeleted;
  49537. };
  49538. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  49539. for (var i = 0; i < this.vertices.length; ++i) {
  49540. var vCount = [];
  49541. var vId = [];
  49542. var v = this.vertices[i];
  49543. var j;
  49544. for (j = 0; j < v.triangleCount; ++j) {
  49545. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  49546. for (var ii = 0; ii < 3; ii++) {
  49547. var ofs = 0;
  49548. var vv = triangle.vertices[ii];
  49549. while (ofs < vCount.length) {
  49550. if (vId[ofs] === vv.id)
  49551. break;
  49552. ++ofs;
  49553. }
  49554. if (ofs === vCount.length) {
  49555. vCount.push(1);
  49556. vId.push(vv.id);
  49557. }
  49558. else {
  49559. vCount[ofs]++;
  49560. }
  49561. }
  49562. }
  49563. for (j = 0; j < vCount.length; ++j) {
  49564. if (vCount[j] === 1) {
  49565. this.vertices[vId[j]].isBorder = true;
  49566. }
  49567. else {
  49568. this.vertices[vId[j]].isBorder = false;
  49569. }
  49570. }
  49571. }
  49572. };
  49573. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  49574. if (identifyBorders === void 0) { identifyBorders = false; }
  49575. var i;
  49576. if (!identifyBorders) {
  49577. var newTrianglesVector = [];
  49578. for (i = 0; i < this.triangles.length; ++i) {
  49579. if (!this.triangles[i].deleted) {
  49580. newTrianglesVector.push(this.triangles[i]);
  49581. }
  49582. }
  49583. this.triangles = newTrianglesVector;
  49584. }
  49585. for (i = 0; i < this.vertices.length; ++i) {
  49586. this.vertices[i].triangleCount = 0;
  49587. this.vertices[i].triangleStart = 0;
  49588. }
  49589. var t;
  49590. var j;
  49591. var v;
  49592. for (i = 0; i < this.triangles.length; ++i) {
  49593. t = this.triangles[i];
  49594. for (j = 0; j < 3; ++j) {
  49595. v = t.vertices[j];
  49596. v.triangleCount++;
  49597. }
  49598. }
  49599. var tStart = 0;
  49600. for (i = 0; i < this.vertices.length; ++i) {
  49601. this.vertices[i].triangleStart = tStart;
  49602. tStart += this.vertices[i].triangleCount;
  49603. this.vertices[i].triangleCount = 0;
  49604. }
  49605. var newReferences = new Array(this.triangles.length * 3);
  49606. for (i = 0; i < this.triangles.length; ++i) {
  49607. t = this.triangles[i];
  49608. for (j = 0; j < 3; ++j) {
  49609. v = t.vertices[j];
  49610. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  49611. v.triangleCount++;
  49612. }
  49613. }
  49614. this.references = newReferences;
  49615. if (identifyBorders) {
  49616. this.identifyBorder();
  49617. }
  49618. };
  49619. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  49620. var x = point.x;
  49621. var y = point.y;
  49622. var z = point.z;
  49623. 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
  49624. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  49625. };
  49626. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  49627. var q = vertex1.q.add(vertex2.q);
  49628. var border = vertex1.isBorder && vertex2.isBorder;
  49629. var error = 0;
  49630. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  49631. if (qDet !== 0 && !border) {
  49632. if (!pointResult) {
  49633. pointResult = BABYLON.Vector3.Zero();
  49634. }
  49635. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  49636. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  49637. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  49638. error = this.vertexError(q, pointResult);
  49639. }
  49640. else {
  49641. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  49642. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  49643. var error1 = this.vertexError(q, vertex1.position);
  49644. var error2 = this.vertexError(q, vertex2.position);
  49645. var error3 = this.vertexError(q, p3);
  49646. error = Math.min(error1, error2, error3);
  49647. if (error === error1) {
  49648. if (pointResult) {
  49649. pointResult.copyFrom(vertex1.position);
  49650. }
  49651. }
  49652. else if (error === error2) {
  49653. if (pointResult) {
  49654. pointResult.copyFrom(vertex2.position);
  49655. }
  49656. }
  49657. else {
  49658. if (pointResult) {
  49659. pointResult.copyFrom(p3);
  49660. }
  49661. }
  49662. }
  49663. return error;
  49664. };
  49665. return QuadraticErrorSimplification;
  49666. }());
  49667. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  49668. })(BABYLON || (BABYLON = {}));
  49669. var BABYLON;
  49670. (function (BABYLON) {
  49671. var serializedGeometries = [];
  49672. var serializeGeometry = function (geometry, serializationGeometries) {
  49673. if (serializedGeometries[geometry.id]) {
  49674. return;
  49675. }
  49676. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  49677. serializationGeometries.boxes.push(geometry.serialize());
  49678. }
  49679. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  49680. serializationGeometries.spheres.push(geometry.serialize());
  49681. }
  49682. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  49683. serializationGeometries.cylinders.push(geometry.serialize());
  49684. }
  49685. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  49686. serializationGeometries.toruses.push(geometry.serialize());
  49687. }
  49688. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  49689. serializationGeometries.grounds.push(geometry.serialize());
  49690. }
  49691. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  49692. serializationGeometries.planes.push(geometry.serialize());
  49693. }
  49694. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  49695. serializationGeometries.torusKnots.push(geometry.serialize());
  49696. }
  49697. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  49698. throw new Error("Unknown primitive type");
  49699. }
  49700. else {
  49701. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  49702. }
  49703. serializedGeometries[geometry.id] = true;
  49704. };
  49705. var serializeMesh = function (mesh, serializationScene) {
  49706. var serializationObject = {};
  49707. serializationObject.name = mesh.name;
  49708. serializationObject.id = mesh.id;
  49709. if (BABYLON.Tags.HasTags(mesh)) {
  49710. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  49711. }
  49712. serializationObject.position = mesh.position.asArray();
  49713. if (mesh.rotationQuaternion) {
  49714. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  49715. }
  49716. else if (mesh.rotation) {
  49717. serializationObject.rotation = mesh.rotation.asArray();
  49718. }
  49719. serializationObject.scaling = mesh.scaling.asArray();
  49720. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  49721. serializationObject.isEnabled = mesh.isEnabled();
  49722. serializationObject.isVisible = mesh.isVisible;
  49723. serializationObject.infiniteDistance = mesh.infiniteDistance;
  49724. serializationObject.pickable = mesh.isPickable;
  49725. serializationObject.receiveShadows = mesh.receiveShadows;
  49726. serializationObject.billboardMode = mesh.billboardMode;
  49727. serializationObject.visibility = mesh.visibility;
  49728. serializationObject.checkCollisions = mesh.checkCollisions;
  49729. // Parent
  49730. if (mesh.parent) {
  49731. serializationObject.parentId = mesh.parent.id;
  49732. }
  49733. // Geometry
  49734. var geometry = mesh._geometry;
  49735. if (geometry) {
  49736. var geometryId = geometry.id;
  49737. serializationObject.geometryId = geometryId;
  49738. if (!mesh.getScene().getGeometryByID(geometryId)) {
  49739. // 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
  49740. serializeGeometry(geometry, serializationScene.geometries);
  49741. }
  49742. // SubMeshes
  49743. serializationObject.subMeshes = [];
  49744. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  49745. var subMesh = mesh.subMeshes[subIndex];
  49746. serializationObject.subMeshes.push({
  49747. materialIndex: subMesh.materialIndex,
  49748. verticesStart: subMesh.verticesStart,
  49749. verticesCount: subMesh.verticesCount,
  49750. indexStart: subMesh.indexStart,
  49751. indexCount: subMesh.indexCount
  49752. });
  49753. }
  49754. }
  49755. // Material
  49756. if (mesh.material) {
  49757. serializationObject.materialId = mesh.material.id;
  49758. }
  49759. else {
  49760. mesh.material = null;
  49761. }
  49762. // Skeleton
  49763. if (mesh.skeleton) {
  49764. serializationObject.skeletonId = mesh.skeleton.id;
  49765. }
  49766. // Physics
  49767. //TODO implement correct serialization for physics impostors.
  49768. if (mesh.getPhysicsImpostor()) {
  49769. serializationObject.physicsMass = mesh.getPhysicsMass();
  49770. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  49771. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  49772. serializationObject.physicsImpostor = mesh.getPhysicsImpostor().type;
  49773. }
  49774. // Instances
  49775. serializationObject.instances = [];
  49776. for (var index = 0; index < mesh.instances.length; index++) {
  49777. var instance = mesh.instances[index];
  49778. var serializationInstance = {
  49779. name: instance.name,
  49780. position: instance.position.asArray(),
  49781. scaling: instance.scaling.asArray()
  49782. };
  49783. if (instance.rotationQuaternion) {
  49784. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  49785. }
  49786. else if (instance.rotation) {
  49787. serializationInstance.rotation = instance.rotation.asArray();
  49788. }
  49789. serializationObject.instances.push(serializationInstance);
  49790. // Animations
  49791. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  49792. serializationInstance.ranges = instance.serializeAnimationRanges();
  49793. }
  49794. // Animations
  49795. BABYLON.Animation.AppendSerializedAnimations(mesh, serializationObject);
  49796. serializationObject.ranges = mesh.serializeAnimationRanges();
  49797. // Layer mask
  49798. serializationObject.layerMask = mesh.layerMask;
  49799. // Action Manager
  49800. if (mesh.actionManager) {
  49801. serializationObject.actions = mesh.actionManager.serialize(mesh.name);
  49802. }
  49803. return serializationObject;
  49804. };
  49805. var finalizeSingleMesh = function (mesh, serializationObject) {
  49806. //only works if the mesh is already loaded
  49807. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  49808. //serialize material
  49809. if (mesh.material) {
  49810. if (mesh.material instanceof BABYLON.StandardMaterial) {
  49811. serializationObject.materials = serializationObject.materials || [];
  49812. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  49813. serializationObject.materials.push(mesh.material.serialize());
  49814. }
  49815. }
  49816. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  49817. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  49818. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  49819. serializationObject.multiMaterials.push(mesh.material.serialize());
  49820. }
  49821. }
  49822. }
  49823. //serialize geometry
  49824. var geometry = mesh._geometry;
  49825. if (geometry) {
  49826. if (!serializationObject.geometries) {
  49827. serializationObject.geometries = {};
  49828. serializationObject.geometries.boxes = [];
  49829. serializationObject.geometries.spheres = [];
  49830. serializationObject.geometries.cylinders = [];
  49831. serializationObject.geometries.toruses = [];
  49832. serializationObject.geometries.grounds = [];
  49833. serializationObject.geometries.planes = [];
  49834. serializationObject.geometries.torusKnots = [];
  49835. serializationObject.geometries.vertexData = [];
  49836. }
  49837. serializeGeometry(geometry, serializationObject.geometries);
  49838. }
  49839. // Skeletons
  49840. if (mesh.skeleton) {
  49841. serializationObject.skeletons = serializationObject.skeletons || [];
  49842. serializationObject.skeletons.push(mesh.skeleton.serialize());
  49843. }
  49844. //serialize the actual mesh
  49845. serializationObject.meshes = serializationObject.meshes || [];
  49846. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  49847. }
  49848. };
  49849. var SceneSerializer = (function () {
  49850. function SceneSerializer() {
  49851. }
  49852. SceneSerializer.ClearCache = function () {
  49853. serializedGeometries = [];
  49854. };
  49855. SceneSerializer.Serialize = function (scene) {
  49856. var serializationObject = {};
  49857. // Scene
  49858. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  49859. serializationObject.autoClear = scene.autoClear;
  49860. serializationObject.clearColor = scene.clearColor.asArray();
  49861. serializationObject.ambientColor = scene.ambientColor.asArray();
  49862. serializationObject.gravity = scene.gravity.asArray();
  49863. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  49864. serializationObject.workerCollisions = scene.workerCollisions;
  49865. // Fog
  49866. if (scene.fogMode && scene.fogMode !== 0) {
  49867. serializationObject.fogMode = scene.fogMode;
  49868. serializationObject.fogColor = scene.fogColor.asArray();
  49869. serializationObject.fogStart = scene.fogStart;
  49870. serializationObject.fogEnd = scene.fogEnd;
  49871. serializationObject.fogDensity = scene.fogDensity;
  49872. }
  49873. //Physics
  49874. if (scene.isPhysicsEnabled()) {
  49875. serializationObject.physicsEnabled = true;
  49876. serializationObject.physicsGravity = scene.getPhysicsEngine().gravity.asArray();
  49877. serializationObject.physicsEngine = scene.getPhysicsEngine().getPhysicsPluginName();
  49878. }
  49879. // Lights
  49880. serializationObject.lights = [];
  49881. var index;
  49882. var light;
  49883. for (index = 0; index < scene.lights.length; index++) {
  49884. light = scene.lights[index];
  49885. serializationObject.lights.push(light.serialize());
  49886. }
  49887. // Cameras
  49888. serializationObject.cameras = [];
  49889. for (index = 0; index < scene.cameras.length; index++) {
  49890. var camera = scene.cameras[index];
  49891. serializationObject.cameras.push(camera.serialize());
  49892. }
  49893. if (scene.activeCamera) {
  49894. serializationObject.activeCameraID = scene.activeCamera.id;
  49895. }
  49896. // Animations
  49897. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  49898. // Materials
  49899. serializationObject.materials = [];
  49900. serializationObject.multiMaterials = [];
  49901. var material;
  49902. for (index = 0; index < scene.materials.length; index++) {
  49903. material = scene.materials[index];
  49904. serializationObject.materials.push(material.serialize());
  49905. }
  49906. // MultiMaterials
  49907. serializationObject.multiMaterials = [];
  49908. for (index = 0; index < scene.multiMaterials.length; index++) {
  49909. var multiMaterial = scene.multiMaterials[index];
  49910. serializationObject.multiMaterials.push(multiMaterial.serialize());
  49911. }
  49912. // Skeletons
  49913. serializationObject.skeletons = [];
  49914. for (index = 0; index < scene.skeletons.length; index++) {
  49915. serializationObject.skeletons.push(scene.skeletons[index].serialize());
  49916. }
  49917. // Geometries
  49918. serializationObject.geometries = {};
  49919. serializationObject.geometries.boxes = [];
  49920. serializationObject.geometries.spheres = [];
  49921. serializationObject.geometries.cylinders = [];
  49922. serializationObject.geometries.toruses = [];
  49923. serializationObject.geometries.grounds = [];
  49924. serializationObject.geometries.planes = [];
  49925. serializationObject.geometries.torusKnots = [];
  49926. serializationObject.geometries.vertexData = [];
  49927. serializedGeometries = [];
  49928. var geometries = scene.getGeometries();
  49929. for (index = 0; index < geometries.length; index++) {
  49930. var geometry = geometries[index];
  49931. if (geometry.isReady()) {
  49932. serializeGeometry(geometry, serializationObject.geometries);
  49933. }
  49934. }
  49935. // Meshes
  49936. serializationObject.meshes = [];
  49937. for (index = 0; index < scene.meshes.length; index++) {
  49938. var abstractMesh = scene.meshes[index];
  49939. if (abstractMesh instanceof BABYLON.Mesh) {
  49940. var mesh = abstractMesh;
  49941. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  49942. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  49943. }
  49944. }
  49945. }
  49946. // Particles Systems
  49947. serializationObject.particleSystems = [];
  49948. for (index = 0; index < scene.particleSystems.length; index++) {
  49949. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  49950. }
  49951. // Lens flares
  49952. serializationObject.lensFlareSystems = [];
  49953. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  49954. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  49955. }
  49956. // Shadows
  49957. serializationObject.shadowGenerators = [];
  49958. for (index = 0; index < scene.lights.length; index++) {
  49959. light = scene.lights[index];
  49960. var shadowGenerator = light.getShadowGenerator();
  49961. // Only support serialization for official generator so far.
  49962. if (shadowGenerator && shadowGenerator instanceof BABYLON.ShadowGenerator) {
  49963. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  49964. }
  49965. }
  49966. // Action Manager
  49967. if (scene.actionManager) {
  49968. serializationObject.actions = scene.actionManager.serialize("scene");
  49969. }
  49970. // Audio
  49971. serializationObject.sounds = [];
  49972. for (index = 0; index < scene.soundTracks.length; index++) {
  49973. var soundtrack = scene.soundTracks[index];
  49974. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  49975. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  49976. }
  49977. }
  49978. return serializationObject;
  49979. };
  49980. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  49981. if (withParents === void 0) { withParents = false; }
  49982. if (withChildren === void 0) { withChildren = false; }
  49983. var serializationObject = {};
  49984. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  49985. if (withParents || withChildren) {
  49986. //deliberate for loop! not for each, appended should be processed as well.
  49987. for (var i = 0; i < toSerialize.length; ++i) {
  49988. if (withChildren) {
  49989. toSerialize[i].getDescendants().forEach(function (node) {
  49990. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  49991. toSerialize.push(node);
  49992. }
  49993. });
  49994. }
  49995. //make sure the array doesn't contain the object already
  49996. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  49997. toSerialize.push(toSerialize[i].parent);
  49998. }
  49999. }
  50000. }
  50001. toSerialize.forEach(function (mesh) {
  50002. finalizeSingleMesh(mesh, serializationObject);
  50003. });
  50004. return serializationObject;
  50005. };
  50006. return SceneSerializer;
  50007. }());
  50008. BABYLON.SceneSerializer = SceneSerializer;
  50009. })(BABYLON || (BABYLON = {}));
  50010. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  50011. // Huge respect for a such great lib.
  50012. // Earcut license:
  50013. // Copyright (c) 2016, Mapbox
  50014. //
  50015. // Permission to use, copy, modify, and/or distribute this software for any purpose
  50016. // with or without fee is hereby granted, provided that the above copyright notice
  50017. // and this permission notice appear in all copies.
  50018. //
  50019. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  50020. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  50021. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  50022. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  50023. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  50024. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  50025. // THIS SOFTWARE.
  50026. var Earcut;
  50027. (function (Earcut) {
  50028. /**
  50029. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  50030. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  50031. * @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).
  50032. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  50033. */
  50034. function earcut(data, holeIndices, dim) {
  50035. dim = dim || 2;
  50036. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = [];
  50037. if (!outerNode)
  50038. return triangles;
  50039. var minX, minY, maxX, maxY, x, y, size;
  50040. if (hasHoles)
  50041. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  50042. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  50043. if (data.length > 80 * dim) {
  50044. minX = maxX = data[0];
  50045. minY = maxY = data[1];
  50046. for (var i = dim; i < outerLen; i += dim) {
  50047. x = data[i];
  50048. y = data[i + 1];
  50049. if (x < minX)
  50050. minX = x;
  50051. if (y < minY)
  50052. minY = y;
  50053. if (x > maxX)
  50054. maxX = x;
  50055. if (y > maxY)
  50056. maxY = y;
  50057. }
  50058. // minX, minY and size are later used to transform coords into integers for z-order calculation
  50059. size = Math.max(maxX - minX, maxY - minY);
  50060. }
  50061. earcutLinked(outerNode, triangles, dim, minX, minY, size, undefined);
  50062. return triangles;
  50063. }
  50064. Earcut.earcut = earcut;
  50065. // create a circular doubly linked list from polygon points in the specified winding order
  50066. function linkedList(data, start, end, dim, clockwise) {
  50067. var i, last;
  50068. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  50069. for (i = start; i < end; i += dim)
  50070. last = insertNode(i, data[i], data[i + 1], last);
  50071. }
  50072. else {
  50073. for (i = end - dim; i >= start; i -= dim)
  50074. last = insertNode(i, data[i], data[i + 1], last);
  50075. }
  50076. if (last && equals(last, last.next)) {
  50077. removeNode(last);
  50078. last = last.next;
  50079. }
  50080. return last;
  50081. }
  50082. // eliminate colinear or duplicate points
  50083. function filterPoints(start, end) {
  50084. if (!start)
  50085. return start;
  50086. if (!end)
  50087. end = start;
  50088. var p = start, again;
  50089. do {
  50090. again = false;
  50091. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  50092. removeNode(p);
  50093. p = end = p.prev;
  50094. if (p === p.next)
  50095. return null;
  50096. again = true;
  50097. }
  50098. else {
  50099. p = p.next;
  50100. }
  50101. } while (again || p !== end);
  50102. return end;
  50103. }
  50104. // main ear slicing loop which triangulates a polygon (given as a linked list)
  50105. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  50106. if (!ear)
  50107. return;
  50108. // interlink polygon nodes in z-order
  50109. if (!pass && size)
  50110. indexCurve(ear, minX, minY, size);
  50111. var stop = ear, prev, next;
  50112. // iterate through ears, slicing them one by one
  50113. while (ear.prev !== ear.next) {
  50114. prev = ear.prev;
  50115. next = ear.next;
  50116. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  50117. // cut off the triangle
  50118. triangles.push(prev.i / dim);
  50119. triangles.push(ear.i / dim);
  50120. triangles.push(next.i / dim);
  50121. removeNode(ear);
  50122. // skipping the next vertice leads to less sliver triangles
  50123. ear = next.next;
  50124. stop = next.next;
  50125. continue;
  50126. }
  50127. ear = next;
  50128. // if we looped through the whole remaining polygon and can't find any more ears
  50129. if (ear === stop) {
  50130. // try filtering points and slicing again
  50131. if (!pass) {
  50132. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  50133. }
  50134. else if (pass === 1) {
  50135. ear = cureLocalIntersections(ear, triangles, dim);
  50136. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  50137. }
  50138. else if (pass === 2) {
  50139. splitEarcut(ear, triangles, dim, minX, minY, size);
  50140. }
  50141. break;
  50142. }
  50143. }
  50144. }
  50145. // check whether a polygon node forms a valid ear with adjacent nodes
  50146. function isEar(ear) {
  50147. var a = ear.prev, b = ear, c = ear.next;
  50148. if (area(a, b, c) >= 0)
  50149. return false; // reflex, can't be an ear
  50150. // now make sure we don't have other points inside the potential ear
  50151. var p = ear.next.next;
  50152. while (p !== ear.prev) {
  50153. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  50154. area(p.prev, p, p.next) >= 0)
  50155. return false;
  50156. p = p.next;
  50157. }
  50158. return true;
  50159. }
  50160. function isEarHashed(ear, minX, minY, size) {
  50161. var a = ear.prev, b = ear, c = ear.next;
  50162. if (area(a, b, c) >= 0)
  50163. return false; // reflex, can't be an ear
  50164. // triangle bbox; min & max are calculated like this for speed
  50165. 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);
  50166. // z-order range for the current triangle bbox;
  50167. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  50168. // first look for points inside the triangle in increasing z-order
  50169. var p = ear.nextZ;
  50170. while (p && p.z <= maxZ) {
  50171. if (p !== ear.prev &&
  50172. p !== ear.next &&
  50173. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  50174. area(p.prev, p, p.next) >= 0)
  50175. return false;
  50176. p = p.nextZ;
  50177. }
  50178. // then look for points in decreasing z-order
  50179. p = ear.prevZ;
  50180. while (p && p.z >= minZ) {
  50181. if (p !== ear.prev &&
  50182. p !== ear.next &&
  50183. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  50184. area(p.prev, p, p.next) >= 0)
  50185. return false;
  50186. p = p.prevZ;
  50187. }
  50188. return true;
  50189. }
  50190. // go through all polygon nodes and cure small local self-intersections
  50191. function cureLocalIntersections(start, triangles, dim) {
  50192. var p = start;
  50193. do {
  50194. var a = p.prev, b = p.next.next;
  50195. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  50196. triangles.push(a.i / dim);
  50197. triangles.push(p.i / dim);
  50198. triangles.push(b.i / dim);
  50199. // remove two nodes involved
  50200. removeNode(p);
  50201. removeNode(p.next);
  50202. p = start = b;
  50203. }
  50204. p = p.next;
  50205. } while (p !== start);
  50206. return p;
  50207. }
  50208. // try splitting polygon into two and triangulate them independently
  50209. function splitEarcut(start, triangles, dim, minX, minY, size) {
  50210. // look for a valid diagonal that divides the polygon into two
  50211. var a = start;
  50212. do {
  50213. var b = a.next.next;
  50214. while (b !== a.prev) {
  50215. if (a.i !== b.i && isValidDiagonal(a, b)) {
  50216. // split the polygon in two by the diagonal
  50217. var c = splitPolygon(a, b);
  50218. // filter colinear points around the cuts
  50219. a = filterPoints(a, a.next);
  50220. c = filterPoints(c, c.next);
  50221. // run earcut on each half
  50222. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  50223. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  50224. return;
  50225. }
  50226. b = b.next;
  50227. }
  50228. a = a.next;
  50229. } while (a !== start);
  50230. }
  50231. // link every hole into the outer loop, producing a single-ring polygon without holes
  50232. function eliminateHoles(data, holeIndices, outerNode, dim) {
  50233. var queue = [], i, len, start, end, list;
  50234. for (i = 0, len = holeIndices.length; i < len; i++) {
  50235. start = holeIndices[i] * dim;
  50236. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  50237. list = linkedList(data, start, end, dim, false);
  50238. if (list === list.next)
  50239. list.steiner = true;
  50240. queue.push(getLeftmost(list));
  50241. }
  50242. queue.sort(compareX);
  50243. // process holes from left to right
  50244. for (i = 0; i < queue.length; i++) {
  50245. eliminateHole(queue[i], outerNode);
  50246. outerNode = filterPoints(outerNode, outerNode.next);
  50247. }
  50248. return outerNode;
  50249. }
  50250. function compareX(a, b) {
  50251. return a.x - b.x;
  50252. }
  50253. // find a bridge between vertices that connects hole with an outer ring and and link it
  50254. function eliminateHole(hole, outerNode) {
  50255. outerNode = findHoleBridge(hole, outerNode);
  50256. if (outerNode) {
  50257. var b = splitPolygon(outerNode, hole);
  50258. filterPoints(b, b.next);
  50259. }
  50260. }
  50261. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  50262. function findHoleBridge(hole, outerNode) {
  50263. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  50264. // find a segment intersected by a ray from the hole's leftmost point to the left;
  50265. // segment's endpoint with lesser x will be potential connection point
  50266. do {
  50267. if (hy <= p.y && hy >= p.next.y) {
  50268. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  50269. if (x <= hx && x > qx) {
  50270. qx = x;
  50271. if (x === hx) {
  50272. if (hy === p.y)
  50273. return p;
  50274. if (hy === p.next.y)
  50275. return p.next;
  50276. }
  50277. m = p.x < p.next.x ? p : p.next;
  50278. }
  50279. }
  50280. p = p.next;
  50281. } while (p !== outerNode);
  50282. if (!m)
  50283. return null;
  50284. if (hx === qx)
  50285. return m.prev; // hole touches outer segment; pick lower endpoint
  50286. // look for points inside the triangle of hole point, segment intersection and endpoint;
  50287. // if there are no points found, we have a valid connection;
  50288. // otherwise choose the point of the minimum angle with the ray as connection point
  50289. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  50290. p = m.next;
  50291. while (p !== stop) {
  50292. if (hx >= p.x &&
  50293. p.x >= mx &&
  50294. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  50295. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  50296. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  50297. m = p;
  50298. tanMin = tan;
  50299. }
  50300. }
  50301. p = p.next;
  50302. }
  50303. return m;
  50304. }
  50305. // interlink polygon nodes in z-order
  50306. function indexCurve(start, minX, minY, size) {
  50307. var p = start;
  50308. do {
  50309. if (p.z === null)
  50310. p.z = zOrder(p.x, p.y, minX, minY, size);
  50311. p.prevZ = p.prev;
  50312. p.nextZ = p.next;
  50313. p = p.next;
  50314. } while (p !== start);
  50315. p.prevZ.nextZ = null;
  50316. p.prevZ = null;
  50317. sortLinked(p);
  50318. }
  50319. // Simon Tatham's linked list merge sort algorithm
  50320. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  50321. function sortLinked(list) {
  50322. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  50323. do {
  50324. p = list;
  50325. list = null;
  50326. tail = null;
  50327. numMerges = 0;
  50328. while (p) {
  50329. numMerges++;
  50330. q = p;
  50331. pSize = 0;
  50332. for (i = 0; i < inSize; i++) {
  50333. pSize++;
  50334. q = q.nextZ;
  50335. if (!q)
  50336. break;
  50337. }
  50338. qSize = inSize;
  50339. while (pSize > 0 || (qSize > 0 && q)) {
  50340. if (pSize === 0) {
  50341. e = q;
  50342. q = q.nextZ;
  50343. qSize--;
  50344. }
  50345. else if (qSize === 0 || !q) {
  50346. e = p;
  50347. p = p.nextZ;
  50348. pSize--;
  50349. }
  50350. else if (p.z <= q.z) {
  50351. e = p;
  50352. p = p.nextZ;
  50353. pSize--;
  50354. }
  50355. else {
  50356. e = q;
  50357. q = q.nextZ;
  50358. qSize--;
  50359. }
  50360. if (tail)
  50361. tail.nextZ = e;
  50362. else
  50363. list = e;
  50364. e.prevZ = tail;
  50365. tail = e;
  50366. }
  50367. p = q;
  50368. }
  50369. tail.nextZ = null;
  50370. inSize *= 2;
  50371. } while (numMerges > 1);
  50372. return list;
  50373. }
  50374. // z-order of a point given coords and size of the data bounding box
  50375. function zOrder(x, y, minX, minY, size) {
  50376. // coords are transformed into non-negative 15-bit integer range
  50377. x = 32767 * (x - minX) / size;
  50378. y = 32767 * (y - minY) / size;
  50379. x = (x | (x << 8)) & 0x00FF00FF;
  50380. x = (x | (x << 4)) & 0x0F0F0F0F;
  50381. x = (x | (x << 2)) & 0x33333333;
  50382. x = (x | (x << 1)) & 0x55555555;
  50383. y = (y | (y << 8)) & 0x00FF00FF;
  50384. y = (y | (y << 4)) & 0x0F0F0F0F;
  50385. y = (y | (y << 2)) & 0x33333333;
  50386. y = (y | (y << 1)) & 0x55555555;
  50387. return x | (y << 1);
  50388. }
  50389. // find the leftmost node of a polygon ring
  50390. function getLeftmost(start) {
  50391. var p = start, leftmost = start;
  50392. do {
  50393. if (p.x < leftmost.x)
  50394. leftmost = p;
  50395. p = p.next;
  50396. } while (p !== start);
  50397. return leftmost;
  50398. }
  50399. // check if a point lies within a convex triangle
  50400. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  50401. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  50402. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  50403. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  50404. }
  50405. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  50406. function isValidDiagonal(a, b) {
  50407. return a.next.i !== b.i &&
  50408. a.prev.i !== b.i &&
  50409. !intersectsPolygon(a, b) &&
  50410. locallyInside(a, b) &&
  50411. locallyInside(b, a) &&
  50412. middleInside(a, b);
  50413. }
  50414. // signed area of a triangle
  50415. function area(p, q, r) {
  50416. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  50417. }
  50418. // check if two points are equal
  50419. function equals(p1, p2) {
  50420. return p1.x === p2.x && p1.y === p2.y;
  50421. }
  50422. // check if two segments intersect
  50423. function intersects(p1, q1, p2, q2) {
  50424. if ((equals(p1, q1) && equals(p2, q2)) ||
  50425. (equals(p1, q2) && equals(p2, q1)))
  50426. return true;
  50427. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  50428. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  50429. }
  50430. // check if a polygon diagonal intersects any polygon segments
  50431. function intersectsPolygon(a, b) {
  50432. var p = a;
  50433. do {
  50434. if (p.i !== a.i &&
  50435. p.next.i !== a.i &&
  50436. p.i !== b.i &&
  50437. p.next.i !== b.i &&
  50438. intersects(p, p.next, a, b))
  50439. return true;
  50440. p = p.next;
  50441. } while (p !== a);
  50442. return false;
  50443. }
  50444. // check if a polygon diagonal is locally inside the polygon
  50445. function locallyInside(a, b) {
  50446. return area(a.prev, a, a.next) < 0
  50447. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  50448. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  50449. }
  50450. // check if the middle point of a polygon diagonal is inside the polygon
  50451. function middleInside(a, b) {
  50452. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  50453. do {
  50454. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  50455. inside = !inside;
  50456. p = p.next;
  50457. } while (p !== a);
  50458. return inside;
  50459. }
  50460. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  50461. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  50462. function splitPolygon(a, b) {
  50463. 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;
  50464. a.next = b;
  50465. b.prev = a;
  50466. a2.next = an;
  50467. an.prev = a2;
  50468. b2.next = a2;
  50469. a2.prev = b2;
  50470. bp.next = b2;
  50471. b2.prev = bp;
  50472. return b2;
  50473. }
  50474. // create a node and optionally link it with previous one (in a circular doubly linked list)
  50475. function insertNode(i, x, y, last) {
  50476. var p = new Node(i, x, y);
  50477. if (!last) {
  50478. p.prev = p;
  50479. p.next = p;
  50480. }
  50481. else {
  50482. p.next = last.next;
  50483. p.prev = last;
  50484. last.next.prev = p;
  50485. last.next = p;
  50486. }
  50487. return p;
  50488. }
  50489. function removeNode(p) {
  50490. p.next.prev = p.prev;
  50491. p.prev.next = p.next;
  50492. if (p.prevZ)
  50493. p.prevZ.nextZ = p.nextZ;
  50494. if (p.nextZ)
  50495. p.nextZ.prevZ = p.prevZ;
  50496. }
  50497. function Node(i, x, y) {
  50498. // vertice index in coordinates array
  50499. this.i = i;
  50500. // vertex coordinates
  50501. this.x = x;
  50502. this.y = y;
  50503. // previous and next vertice nodes in a polygon ring
  50504. this.prev = null;
  50505. this.next = null;
  50506. // z-order curve value
  50507. this.z = null;
  50508. // previous and next nodes in z-order
  50509. this.prevZ = null;
  50510. this.nextZ = null;
  50511. // indicates whether this is a steiner point
  50512. this.steiner = false;
  50513. }
  50514. /**
  50515. * return a percentage difference between the polygon area and its triangulation area;
  50516. * used to verify correctness of triangulation
  50517. */
  50518. function deviation(data, holeIndices, dim, triangles) {
  50519. var hasHoles = holeIndices && holeIndices.length;
  50520. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  50521. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  50522. if (hasHoles) {
  50523. for (var i = 0, len = holeIndices.length; i < len; i++) {
  50524. var start = holeIndices[i] * dim;
  50525. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  50526. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  50527. }
  50528. }
  50529. var trianglesArea = 0;
  50530. for (i = 0; i < triangles.length; i += 3) {
  50531. var a = triangles[i] * dim;
  50532. var b = triangles[i + 1] * dim;
  50533. var c = triangles[i + 2] * dim;
  50534. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  50535. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  50536. }
  50537. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  50538. }
  50539. Earcut.deviation = deviation;
  50540. ;
  50541. function signedArea(data, start, end, dim) {
  50542. var sum = 0;
  50543. for (var i = start, j = end - dim; i < end; i += dim) {
  50544. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  50545. j = i;
  50546. }
  50547. return sum;
  50548. }
  50549. /**
  50550. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  50551. */
  50552. function flatten(data) {
  50553. var dim = data[0][0].length, result = { vertices: [], holes: [], dimensions: dim }, holeIndex = 0;
  50554. for (var i = 0; i < data.length; i++) {
  50555. for (var j = 0; j < data[i].length; j++) {
  50556. for (var d = 0; d < dim; d++)
  50557. result.vertices.push(data[i][j][d]);
  50558. }
  50559. if (i > 0) {
  50560. holeIndex += data[i - 1].length;
  50561. result.holes.push(holeIndex);
  50562. }
  50563. }
  50564. return result;
  50565. }
  50566. Earcut.flatten = flatten;
  50567. ;
  50568. })(Earcut || (Earcut = {}));
  50569. var BABYLON;
  50570. (function (BABYLON) {
  50571. // Unique ID when we import meshes from Babylon to CSG
  50572. var currentCSGMeshId = 0;
  50573. // # class Vertex
  50574. // Represents a vertex of a polygon. Use your own vertex class instead of this
  50575. // one to provide additional features like texture coordinates and vertex
  50576. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  50577. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  50578. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  50579. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  50580. // is not used anywhere else.
  50581. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  50582. var Vertex = (function () {
  50583. function Vertex(pos, normal, uv) {
  50584. this.pos = pos;
  50585. this.normal = normal;
  50586. this.uv = uv;
  50587. }
  50588. Vertex.prototype.clone = function () {
  50589. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  50590. };
  50591. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  50592. // orientation of a polygon is flipped.
  50593. Vertex.prototype.flip = function () {
  50594. this.normal = this.normal.scale(-1);
  50595. };
  50596. // Create a new vertex between this vertex and `other` by linearly
  50597. // interpolating all properties using a parameter of `t`. Subclasses should
  50598. // override this to interpolate additional properties.
  50599. Vertex.prototype.interpolate = function (other, t) {
  50600. 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));
  50601. };
  50602. return Vertex;
  50603. }());
  50604. // # class Plane
  50605. // Represents a plane in 3D space.
  50606. var Plane = (function () {
  50607. function Plane(normal, w) {
  50608. this.normal = normal;
  50609. this.w = w;
  50610. }
  50611. Plane.FromPoints = function (a, b, c) {
  50612. var v0 = c.subtract(a);
  50613. var v1 = b.subtract(a);
  50614. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  50615. return null;
  50616. }
  50617. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  50618. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  50619. };
  50620. Plane.prototype.clone = function () {
  50621. return new Plane(this.normal.clone(), this.w);
  50622. };
  50623. Plane.prototype.flip = function () {
  50624. this.normal.scaleInPlace(-1);
  50625. this.w = -this.w;
  50626. };
  50627. // Split `polygon` by this plane if needed, then put the polygon or polygon
  50628. // fragments in the appropriate lists. Coplanar polygons go into either
  50629. // `coplanarFront` or `coplanarBack` depending on their orientation with
  50630. // respect to this plane. Polygons in front or in back of this plane go into
  50631. // either `front` or `back`.
  50632. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  50633. var COPLANAR = 0;
  50634. var FRONT = 1;
  50635. var BACK = 2;
  50636. var SPANNING = 3;
  50637. // Classify each point as well as the entire polygon into one of the above
  50638. // four classes.
  50639. var polygonType = 0;
  50640. var types = [];
  50641. var i;
  50642. var t;
  50643. for (i = 0; i < polygon.vertices.length; i++) {
  50644. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  50645. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  50646. polygonType |= type;
  50647. types.push(type);
  50648. }
  50649. // Put the polygon in the correct list, splitting it when necessary.
  50650. switch (polygonType) {
  50651. case COPLANAR:
  50652. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  50653. break;
  50654. case FRONT:
  50655. front.push(polygon);
  50656. break;
  50657. case BACK:
  50658. back.push(polygon);
  50659. break;
  50660. case SPANNING:
  50661. var f = [], b = [];
  50662. for (i = 0; i < polygon.vertices.length; i++) {
  50663. var j = (i + 1) % polygon.vertices.length;
  50664. var ti = types[i], tj = types[j];
  50665. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  50666. if (ti !== BACK)
  50667. f.push(vi);
  50668. if (ti !== FRONT)
  50669. b.push(ti !== BACK ? vi.clone() : vi);
  50670. if ((ti | tj) === SPANNING) {
  50671. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  50672. var v = vi.interpolate(vj, t);
  50673. f.push(v);
  50674. b.push(v.clone());
  50675. }
  50676. }
  50677. var poly;
  50678. if (f.length >= 3) {
  50679. poly = new Polygon(f, polygon.shared);
  50680. if (poly.plane)
  50681. front.push(poly);
  50682. }
  50683. if (b.length >= 3) {
  50684. poly = new Polygon(b, polygon.shared);
  50685. if (poly.plane)
  50686. back.push(poly);
  50687. }
  50688. break;
  50689. }
  50690. };
  50691. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  50692. // point is on the plane.
  50693. Plane.EPSILON = 1e-5;
  50694. return Plane;
  50695. }());
  50696. // # class Polygon
  50697. // Represents a convex polygon. The vertices used to initialize a polygon must
  50698. // be coplanar and form a convex loop.
  50699. //
  50700. // Each convex polygon has a `shared` property, which is shared between all
  50701. // polygons that are clones of each other or were split from the same polygon.
  50702. // This can be used to define per-polygon properties (such as surface color).
  50703. var Polygon = (function () {
  50704. function Polygon(vertices, shared) {
  50705. this.vertices = vertices;
  50706. this.shared = shared;
  50707. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  50708. }
  50709. Polygon.prototype.clone = function () {
  50710. var vertices = this.vertices.map(function (v) { return v.clone(); });
  50711. return new Polygon(vertices, this.shared);
  50712. };
  50713. Polygon.prototype.flip = function () {
  50714. this.vertices.reverse().map(function (v) { v.flip(); });
  50715. this.plane.flip();
  50716. };
  50717. return Polygon;
  50718. }());
  50719. // # class Node
  50720. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  50721. // by picking a polygon to split along. That polygon (and all other coplanar
  50722. // polygons) are added directly to that node and the other polygons are added to
  50723. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  50724. // no distinction between internal and leaf nodes.
  50725. var Node = (function () {
  50726. function Node(polygons) {
  50727. this.plane = null;
  50728. this.front = null;
  50729. this.back = null;
  50730. this.polygons = [];
  50731. if (polygons) {
  50732. this.build(polygons);
  50733. }
  50734. }
  50735. Node.prototype.clone = function () {
  50736. var node = new Node();
  50737. node.plane = this.plane && this.plane.clone();
  50738. node.front = this.front && this.front.clone();
  50739. node.back = this.back && this.back.clone();
  50740. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  50741. return node;
  50742. };
  50743. // Convert solid space to empty space and empty space to solid space.
  50744. Node.prototype.invert = function () {
  50745. for (var i = 0; i < this.polygons.length; i++) {
  50746. this.polygons[i].flip();
  50747. }
  50748. if (this.plane) {
  50749. this.plane.flip();
  50750. }
  50751. if (this.front) {
  50752. this.front.invert();
  50753. }
  50754. if (this.back) {
  50755. this.back.invert();
  50756. }
  50757. var temp = this.front;
  50758. this.front = this.back;
  50759. this.back = temp;
  50760. };
  50761. // Recursively remove all polygons in `polygons` that are inside this BSP
  50762. // tree.
  50763. Node.prototype.clipPolygons = function (polygons) {
  50764. if (!this.plane)
  50765. return polygons.slice();
  50766. var front = [], back = [];
  50767. for (var i = 0; i < polygons.length; i++) {
  50768. this.plane.splitPolygon(polygons[i], front, back, front, back);
  50769. }
  50770. if (this.front) {
  50771. front = this.front.clipPolygons(front);
  50772. }
  50773. if (this.back) {
  50774. back = this.back.clipPolygons(back);
  50775. }
  50776. else {
  50777. back = [];
  50778. }
  50779. return front.concat(back);
  50780. };
  50781. // Remove all polygons in this BSP tree that are inside the other BSP tree
  50782. // `bsp`.
  50783. Node.prototype.clipTo = function (bsp) {
  50784. this.polygons = bsp.clipPolygons(this.polygons);
  50785. if (this.front)
  50786. this.front.clipTo(bsp);
  50787. if (this.back)
  50788. this.back.clipTo(bsp);
  50789. };
  50790. // Return a list of all polygons in this BSP tree.
  50791. Node.prototype.allPolygons = function () {
  50792. var polygons = this.polygons.slice();
  50793. if (this.front)
  50794. polygons = polygons.concat(this.front.allPolygons());
  50795. if (this.back)
  50796. polygons = polygons.concat(this.back.allPolygons());
  50797. return polygons;
  50798. };
  50799. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  50800. // new polygons are filtered down to the bottom of the tree and become new
  50801. // nodes there. Each set of polygons is partitioned using the first polygon
  50802. // (no heuristic is used to pick a good split).
  50803. Node.prototype.build = function (polygons) {
  50804. if (!polygons.length)
  50805. return;
  50806. if (!this.plane)
  50807. this.plane = polygons[0].plane.clone();
  50808. var front = [], back = [];
  50809. for (var i = 0; i < polygons.length; i++) {
  50810. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  50811. }
  50812. if (front.length) {
  50813. if (!this.front)
  50814. this.front = new Node();
  50815. this.front.build(front);
  50816. }
  50817. if (back.length) {
  50818. if (!this.back)
  50819. this.back = new Node();
  50820. this.back.build(back);
  50821. }
  50822. };
  50823. return Node;
  50824. }());
  50825. var CSG = (function () {
  50826. function CSG() {
  50827. this.polygons = new Array();
  50828. }
  50829. // Convert BABYLON.Mesh to BABYLON.CSG
  50830. CSG.FromMesh = function (mesh) {
  50831. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  50832. var matrix, meshPosition, meshRotation, meshRotationQuaternion, meshScaling;
  50833. if (mesh instanceof BABYLON.Mesh) {
  50834. mesh.computeWorldMatrix(true);
  50835. matrix = mesh.getWorldMatrix();
  50836. meshPosition = mesh.position.clone();
  50837. meshRotation = mesh.rotation.clone();
  50838. if (mesh.rotationQuaternion) {
  50839. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  50840. }
  50841. meshScaling = mesh.scaling.clone();
  50842. }
  50843. else {
  50844. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  50845. }
  50846. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  50847. var subMeshes = mesh.subMeshes;
  50848. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  50849. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  50850. vertices = [];
  50851. for (var j = 0; j < 3; j++) {
  50852. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  50853. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  50854. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  50855. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  50856. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  50857. vertex = new Vertex(position, normal, uv);
  50858. vertices.push(vertex);
  50859. }
  50860. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  50861. // To handle the case of degenerated triangle
  50862. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  50863. if (polygon.plane)
  50864. polygons.push(polygon);
  50865. }
  50866. }
  50867. var csg = CSG.FromPolygons(polygons);
  50868. csg.matrix = matrix;
  50869. csg.position = meshPosition;
  50870. csg.rotation = meshRotation;
  50871. csg.scaling = meshScaling;
  50872. csg.rotationQuaternion = meshRotationQuaternion;
  50873. currentCSGMeshId++;
  50874. return csg;
  50875. };
  50876. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  50877. CSG.FromPolygons = function (polygons) {
  50878. var csg = new CSG();
  50879. csg.polygons = polygons;
  50880. return csg;
  50881. };
  50882. CSG.prototype.clone = function () {
  50883. var csg = new CSG();
  50884. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  50885. csg.copyTransformAttributes(this);
  50886. return csg;
  50887. };
  50888. CSG.prototype.toPolygons = function () {
  50889. return this.polygons;
  50890. };
  50891. CSG.prototype.union = function (csg) {
  50892. var a = new Node(this.clone().polygons);
  50893. var b = new Node(csg.clone().polygons);
  50894. a.clipTo(b);
  50895. b.clipTo(a);
  50896. b.invert();
  50897. b.clipTo(a);
  50898. b.invert();
  50899. a.build(b.allPolygons());
  50900. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  50901. };
  50902. CSG.prototype.unionInPlace = function (csg) {
  50903. var a = new Node(this.polygons);
  50904. var b = new Node(csg.polygons);
  50905. a.clipTo(b);
  50906. b.clipTo(a);
  50907. b.invert();
  50908. b.clipTo(a);
  50909. b.invert();
  50910. a.build(b.allPolygons());
  50911. this.polygons = a.allPolygons();
  50912. };
  50913. CSG.prototype.subtract = function (csg) {
  50914. var a = new Node(this.clone().polygons);
  50915. var b = new Node(csg.clone().polygons);
  50916. a.invert();
  50917. a.clipTo(b);
  50918. b.clipTo(a);
  50919. b.invert();
  50920. b.clipTo(a);
  50921. b.invert();
  50922. a.build(b.allPolygons());
  50923. a.invert();
  50924. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  50925. };
  50926. CSG.prototype.subtractInPlace = function (csg) {
  50927. var a = new Node(this.polygons);
  50928. var b = new Node(csg.polygons);
  50929. a.invert();
  50930. a.clipTo(b);
  50931. b.clipTo(a);
  50932. b.invert();
  50933. b.clipTo(a);
  50934. b.invert();
  50935. a.build(b.allPolygons());
  50936. a.invert();
  50937. this.polygons = a.allPolygons();
  50938. };
  50939. CSG.prototype.intersect = function (csg) {
  50940. var a = new Node(this.clone().polygons);
  50941. var b = new Node(csg.clone().polygons);
  50942. a.invert();
  50943. b.clipTo(a);
  50944. b.invert();
  50945. a.clipTo(b);
  50946. b.clipTo(a);
  50947. a.build(b.allPolygons());
  50948. a.invert();
  50949. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  50950. };
  50951. CSG.prototype.intersectInPlace = function (csg) {
  50952. var a = new Node(this.polygons);
  50953. var b = new Node(csg.polygons);
  50954. a.invert();
  50955. b.clipTo(a);
  50956. b.invert();
  50957. a.clipTo(b);
  50958. b.clipTo(a);
  50959. a.build(b.allPolygons());
  50960. a.invert();
  50961. this.polygons = a.allPolygons();
  50962. };
  50963. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  50964. // not modified.
  50965. CSG.prototype.inverse = function () {
  50966. var csg = this.clone();
  50967. csg.inverseInPlace();
  50968. return csg;
  50969. };
  50970. CSG.prototype.inverseInPlace = function () {
  50971. this.polygons.map(function (p) { p.flip(); });
  50972. };
  50973. // This is used to keep meshes transformations so they can be restored
  50974. // when we build back a Babylon Mesh
  50975. // NB : All CSG operations are performed in world coordinates
  50976. CSG.prototype.copyTransformAttributes = function (csg) {
  50977. this.matrix = csg.matrix;
  50978. this.position = csg.position;
  50979. this.rotation = csg.rotation;
  50980. this.scaling = csg.scaling;
  50981. this.rotationQuaternion = csg.rotationQuaternion;
  50982. return this;
  50983. };
  50984. // Build Raw mesh from CSG
  50985. // Coordinates here are in world space
  50986. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  50987. var matrix = this.matrix.clone();
  50988. matrix.invert();
  50989. 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;
  50990. if (keepSubMeshes) {
  50991. // Sort Polygons, since subMeshes are indices range
  50992. polygons.sort(function (a, b) {
  50993. if (a.shared.meshId === b.shared.meshId) {
  50994. return a.shared.subMeshId - b.shared.subMeshId;
  50995. }
  50996. else {
  50997. return a.shared.meshId - b.shared.meshId;
  50998. }
  50999. });
  51000. }
  51001. for (var i = 0, il = polygons.length; i < il; i++) {
  51002. polygon = polygons[i];
  51003. // Building SubMeshes
  51004. if (!subMesh_dict[polygon.shared.meshId]) {
  51005. subMesh_dict[polygon.shared.meshId] = {};
  51006. }
  51007. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  51008. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  51009. indexStart: +Infinity,
  51010. indexEnd: -Infinity,
  51011. materialIndex: polygon.shared.materialIndex
  51012. };
  51013. }
  51014. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  51015. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  51016. polygonIndices[0] = 0;
  51017. polygonIndices[1] = j - 1;
  51018. polygonIndices[2] = j;
  51019. for (var k = 0; k < 3; k++) {
  51020. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  51021. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  51022. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  51023. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  51024. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  51025. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  51026. // Check if 2 points can be merged
  51027. if (!(typeof vertex_idx !== 'undefined' &&
  51028. normals[vertex_idx * 3] === localNormal.x &&
  51029. normals[vertex_idx * 3 + 1] === localNormal.y &&
  51030. normals[vertex_idx * 3 + 2] === localNormal.z &&
  51031. uvs[vertex_idx * 2] === uv.x &&
  51032. uvs[vertex_idx * 2 + 1] === uv.y)) {
  51033. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  51034. uvs.push(uv.x, uv.y);
  51035. normals.push(normal.x, normal.y, normal.z);
  51036. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  51037. }
  51038. indices.push(vertex_idx);
  51039. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  51040. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  51041. currentIndex++;
  51042. }
  51043. }
  51044. }
  51045. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  51046. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  51047. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  51048. mesh.setIndices(indices);
  51049. if (keepSubMeshes) {
  51050. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  51051. var materialIndexOffset = 0, materialMaxIndex;
  51052. mesh.subMeshes = new Array();
  51053. for (var m in subMesh_dict) {
  51054. materialMaxIndex = -1;
  51055. for (var sm in subMesh_dict[m]) {
  51056. subMesh_obj = subMesh_dict[m][sm];
  51057. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  51058. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  51059. }
  51060. materialIndexOffset += ++materialMaxIndex;
  51061. }
  51062. }
  51063. return mesh;
  51064. };
  51065. // Build Mesh from CSG taking material and transforms into account
  51066. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  51067. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  51068. mesh.material = material;
  51069. mesh.position.copyFrom(this.position);
  51070. mesh.rotation.copyFrom(this.rotation);
  51071. if (this.rotationQuaternion) {
  51072. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  51073. }
  51074. mesh.scaling.copyFrom(this.scaling);
  51075. mesh.computeWorldMatrix(true);
  51076. return mesh;
  51077. };
  51078. return CSG;
  51079. }());
  51080. BABYLON.CSG = CSG;
  51081. })(BABYLON || (BABYLON = {}));
  51082. var BABYLON;
  51083. (function (BABYLON) {
  51084. var VRDistortionCorrectionPostProcess = (function (_super) {
  51085. __extends(VRDistortionCorrectionPostProcess, _super);
  51086. //ANY
  51087. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  51088. var _this = this;
  51089. _super.call(this, name, "vrDistortionCorrection", [
  51090. 'LensCenter',
  51091. 'Scale',
  51092. 'ScaleIn',
  51093. 'HmdWarpParam'
  51094. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
  51095. this._isRightEye = isRightEye;
  51096. this._distortionFactors = vrMetrics.distortionK;
  51097. this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  51098. this._lensCenterOffset = vrMetrics.lensCenterOffset;
  51099. this.onSizeChangedObservable.add(function () {
  51100. _this.aspectRatio = _this.width * .5 / _this.height;
  51101. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  51102. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  51103. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  51104. });
  51105. this.onApplyObservable.add(function (effect) {
  51106. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  51107. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  51108. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  51109. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  51110. });
  51111. }
  51112. return VRDistortionCorrectionPostProcess;
  51113. }(BABYLON.PostProcess));
  51114. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  51115. })(BABYLON || (BABYLON = {}));
  51116. // Mainly based on these 2 articles :
  51117. // 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
  51118. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  51119. var BABYLON;
  51120. (function (BABYLON) {
  51121. (function (JoystickAxis) {
  51122. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  51123. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  51124. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  51125. })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  51126. var JoystickAxis = BABYLON.JoystickAxis;
  51127. var VirtualJoystick = (function () {
  51128. function VirtualJoystick(leftJoystick) {
  51129. var _this = this;
  51130. if (leftJoystick) {
  51131. this._leftJoystick = true;
  51132. }
  51133. else {
  51134. this._leftJoystick = false;
  51135. }
  51136. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  51137. VirtualJoystick._globalJoystickIndex++;
  51138. // By default left & right arrow keys are moving the X
  51139. // and up & down keys are moving the Y
  51140. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  51141. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  51142. this.reverseLeftRight = false;
  51143. this.reverseUpDown = false;
  51144. // collections of pointers
  51145. this._touches = new BABYLON.StringDictionary();
  51146. this.deltaPosition = BABYLON.Vector3.Zero();
  51147. this._joystickSensibility = 25;
  51148. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  51149. this._rotationSpeed = 25;
  51150. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  51151. this._rotateOnAxisRelativeToMesh = false;
  51152. this._onResize = function (evt) {
  51153. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  51154. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  51155. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  51156. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  51157. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  51158. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  51159. };
  51160. // injecting a canvas element on top of the canvas 3D game
  51161. if (!VirtualJoystick.vjCanvas) {
  51162. window.addEventListener("resize", this._onResize, false);
  51163. VirtualJoystick.vjCanvas = document.createElement("canvas");
  51164. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  51165. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  51166. VirtualJoystick.vjCanvas.width = window.innerWidth;
  51167. VirtualJoystick.vjCanvas.height = window.innerHeight;
  51168. VirtualJoystick.vjCanvas.style.width = "100%";
  51169. VirtualJoystick.vjCanvas.style.height = "100%";
  51170. VirtualJoystick.vjCanvas.style.position = "absolute";
  51171. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  51172. VirtualJoystick.vjCanvas.style.top = "0px";
  51173. VirtualJoystick.vjCanvas.style.left = "0px";
  51174. VirtualJoystick.vjCanvas.style.zIndex = "5";
  51175. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  51176. // Support for jQuery PEP polyfill
  51177. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  51178. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  51179. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  51180. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  51181. document.body.appendChild(VirtualJoystick.vjCanvas);
  51182. }
  51183. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  51184. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  51185. this.pressed = false;
  51186. // default joystick color
  51187. this._joystickColor = "cyan";
  51188. this._joystickPointerID = -1;
  51189. // current joystick position
  51190. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  51191. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  51192. // origin joystick position
  51193. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  51194. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  51195. this._onPointerDownHandlerRef = function (evt) {
  51196. _this._onPointerDown(evt);
  51197. };
  51198. this._onPointerMoveHandlerRef = function (evt) {
  51199. _this._onPointerMove(evt);
  51200. };
  51201. this._onPointerOutHandlerRef = function (evt) {
  51202. _this._onPointerUp(evt);
  51203. };
  51204. this._onPointerUpHandlerRef = function (evt) {
  51205. _this._onPointerUp(evt);
  51206. };
  51207. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  51208. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  51209. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  51210. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  51211. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  51212. evt.preventDefault(); // Disables system menu
  51213. }, false);
  51214. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  51215. }
  51216. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  51217. this._joystickSensibility = newJoystickSensibility;
  51218. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  51219. };
  51220. VirtualJoystick.prototype._onPointerDown = function (e) {
  51221. var positionOnScreenCondition;
  51222. e.preventDefault();
  51223. if (this._leftJoystick === true) {
  51224. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  51225. }
  51226. else {
  51227. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  51228. }
  51229. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  51230. // First contact will be dedicated to the virtual joystick
  51231. this._joystickPointerID = e.pointerId;
  51232. this._joystickPointerStartPos.x = e.clientX;
  51233. this._joystickPointerStartPos.y = e.clientY;
  51234. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  51235. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  51236. this._deltaJoystickVector.x = 0;
  51237. this._deltaJoystickVector.y = 0;
  51238. this.pressed = true;
  51239. this._touches.add(e.pointerId.toString(), e);
  51240. }
  51241. else {
  51242. // You can only trigger the action buttons with a joystick declared
  51243. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  51244. this._action();
  51245. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  51246. }
  51247. }
  51248. };
  51249. VirtualJoystick.prototype._onPointerMove = function (e) {
  51250. // If the current pointer is the one associated to the joystick (first touch contact)
  51251. if (this._joystickPointerID == e.pointerId) {
  51252. this._joystickPointerPos.x = e.clientX;
  51253. this._joystickPointerPos.y = e.clientY;
  51254. this._deltaJoystickVector = this._joystickPointerPos.clone();
  51255. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  51256. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  51257. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  51258. switch (this._axisTargetedByLeftAndRight) {
  51259. case JoystickAxis.X:
  51260. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  51261. break;
  51262. case JoystickAxis.Y:
  51263. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  51264. break;
  51265. case JoystickAxis.Z:
  51266. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  51267. break;
  51268. }
  51269. var directionUpDown = this.reverseUpDown ? 1 : -1;
  51270. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  51271. switch (this._axisTargetedByUpAndDown) {
  51272. case JoystickAxis.X:
  51273. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  51274. break;
  51275. case JoystickAxis.Y:
  51276. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  51277. break;
  51278. case JoystickAxis.Z:
  51279. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  51280. break;
  51281. }
  51282. }
  51283. else {
  51284. var data = this._touches.get(e.pointerId.toString());
  51285. if (data) {
  51286. data.x = e.clientX;
  51287. data.y = e.clientY;
  51288. }
  51289. }
  51290. };
  51291. VirtualJoystick.prototype._onPointerUp = function (e) {
  51292. if (this._joystickPointerID == e.pointerId) {
  51293. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 63, this._joystickPointerStartPos.y - 63, 126, 126);
  51294. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 41, this._joystickPreviousPointerPos.y - 41, 82, 82);
  51295. this._joystickPointerID = -1;
  51296. this.pressed = false;
  51297. }
  51298. else {
  51299. var touch = this._touches.get(e.pointerId.toString());
  51300. if (touch) {
  51301. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  51302. }
  51303. }
  51304. this._deltaJoystickVector.x = 0;
  51305. this._deltaJoystickVector.y = 0;
  51306. this._touches.remove(e.pointerId.toString());
  51307. };
  51308. /**
  51309. * Change the color of the virtual joystick
  51310. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  51311. */
  51312. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  51313. this._joystickColor = newColor;
  51314. };
  51315. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  51316. this._action = action;
  51317. };
  51318. // Define which axis you'd like to control for left & right
  51319. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  51320. switch (axis) {
  51321. case JoystickAxis.X:
  51322. case JoystickAxis.Y:
  51323. case JoystickAxis.Z:
  51324. this._axisTargetedByLeftAndRight = axis;
  51325. break;
  51326. default:
  51327. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  51328. break;
  51329. }
  51330. };
  51331. // Define which axis you'd like to control for up & down
  51332. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  51333. switch (axis) {
  51334. case JoystickAxis.X:
  51335. case JoystickAxis.Y:
  51336. case JoystickAxis.Z:
  51337. this._axisTargetedByUpAndDown = axis;
  51338. break;
  51339. default:
  51340. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  51341. break;
  51342. }
  51343. };
  51344. VirtualJoystick.prototype._clearCanvas = function () {
  51345. if (this._leftJoystick) {
  51346. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  51347. }
  51348. else {
  51349. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  51350. }
  51351. };
  51352. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  51353. var _this = this;
  51354. if (this.pressed) {
  51355. this._touches.forEach(function (touch) {
  51356. if (touch.pointerId === _this._joystickPointerID) {
  51357. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 63, _this._joystickPointerStartPos.y - 63, 126, 126);
  51358. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 41, _this._joystickPreviousPointerPos.y - 41, 82, 82);
  51359. VirtualJoystick.vjCanvasContext.beginPath();
  51360. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  51361. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  51362. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  51363. VirtualJoystick.vjCanvasContext.stroke();
  51364. VirtualJoystick.vjCanvasContext.closePath();
  51365. VirtualJoystick.vjCanvasContext.beginPath();
  51366. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  51367. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  51368. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  51369. VirtualJoystick.vjCanvasContext.stroke();
  51370. VirtualJoystick.vjCanvasContext.closePath();
  51371. VirtualJoystick.vjCanvasContext.beginPath();
  51372. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  51373. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  51374. VirtualJoystick.vjCanvasContext.stroke();
  51375. VirtualJoystick.vjCanvasContext.closePath();
  51376. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  51377. }
  51378. else {
  51379. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  51380. VirtualJoystick.vjCanvasContext.beginPath();
  51381. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  51382. VirtualJoystick.vjCanvasContext.beginPath();
  51383. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  51384. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  51385. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  51386. VirtualJoystick.vjCanvasContext.stroke();
  51387. VirtualJoystick.vjCanvasContext.closePath();
  51388. touch.prevX = touch.x;
  51389. touch.prevY = touch.y;
  51390. }
  51391. ;
  51392. });
  51393. }
  51394. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  51395. };
  51396. VirtualJoystick.prototype.releaseCanvas = function () {
  51397. if (VirtualJoystick.vjCanvas) {
  51398. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  51399. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  51400. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  51401. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  51402. window.removeEventListener("resize", this._onResize);
  51403. document.body.removeChild(VirtualJoystick.vjCanvas);
  51404. VirtualJoystick.vjCanvas = null;
  51405. }
  51406. };
  51407. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  51408. VirtualJoystick._globalJoystickIndex = 0;
  51409. return VirtualJoystick;
  51410. }());
  51411. BABYLON.VirtualJoystick = VirtualJoystick;
  51412. })(BABYLON || (BABYLON = {}));
  51413. var BABYLON;
  51414. (function (BABYLON) {
  51415. // We're mainly based on the logic defined into the FreeCamera code
  51416. var VirtualJoysticksCamera = (function (_super) {
  51417. __extends(VirtualJoysticksCamera, _super);
  51418. function VirtualJoysticksCamera(name, position, scene) {
  51419. _super.call(this, name, position, scene);
  51420. this.inputs.addVirtualJoystick();
  51421. }
  51422. return VirtualJoysticksCamera;
  51423. }(BABYLON.FreeCamera));
  51424. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  51425. })(BABYLON || (BABYLON = {}));
  51426. var BABYLON;
  51427. (function (BABYLON) {
  51428. var FreeCameraVirtualJoystickInput = (function () {
  51429. function FreeCameraVirtualJoystickInput() {
  51430. }
  51431. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  51432. return this._leftjoystick;
  51433. };
  51434. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  51435. return this._rightjoystick;
  51436. };
  51437. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  51438. if (this._leftjoystick) {
  51439. var camera = this.camera;
  51440. var speed = camera._computeLocalCameraSpeed() * 50;
  51441. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  51442. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  51443. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  51444. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  51445. if (!this._leftjoystick.pressed) {
  51446. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  51447. }
  51448. if (!this._rightjoystick.pressed) {
  51449. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  51450. }
  51451. }
  51452. };
  51453. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  51454. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  51455. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  51456. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  51457. this._leftjoystick.setJoystickSensibility(0.15);
  51458. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  51459. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  51460. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  51461. this._rightjoystick.reverseUpDown = true;
  51462. this._rightjoystick.setJoystickSensibility(0.05);
  51463. this._rightjoystick.setJoystickColor("yellow");
  51464. };
  51465. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  51466. this._leftjoystick.releaseCanvas();
  51467. this._rightjoystick.releaseCanvas();
  51468. };
  51469. FreeCameraVirtualJoystickInput.prototype.getTypeName = function () {
  51470. return "FreeCameraVirtualJoystickInput";
  51471. };
  51472. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  51473. return "virtualJoystick";
  51474. };
  51475. return FreeCameraVirtualJoystickInput;
  51476. }());
  51477. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  51478. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  51479. })(BABYLON || (BABYLON = {}));
  51480. var BABYLON;
  51481. (function (BABYLON) {
  51482. var AnaglyphPostProcess = (function (_super) {
  51483. __extends(AnaglyphPostProcess, _super);
  51484. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  51485. var _this = this;
  51486. _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable);
  51487. this._passedProcess = rigCameras[0]._rigPostProcess;
  51488. this.onApplyObservable.add(function (effect) {
  51489. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  51490. });
  51491. }
  51492. return AnaglyphPostProcess;
  51493. }(BABYLON.PostProcess));
  51494. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  51495. })(BABYLON || (BABYLON = {}));
  51496. var BABYLON;
  51497. (function (BABYLON) {
  51498. var OutlineRenderer = (function () {
  51499. function OutlineRenderer(scene) {
  51500. this._scene = scene;
  51501. }
  51502. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  51503. var _this = this;
  51504. if (useOverlay === void 0) { useOverlay = false; }
  51505. var scene = this._scene;
  51506. var engine = this._scene.getEngine();
  51507. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  51508. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  51509. return;
  51510. }
  51511. var mesh = subMesh.getRenderingMesh();
  51512. var material = subMesh.getMaterial();
  51513. engine.enableEffect(this._effect);
  51514. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  51515. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  51516. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  51517. // Bones
  51518. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  51519. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  51520. }
  51521. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  51522. // Alpha test
  51523. if (material && material.needAlphaTesting()) {
  51524. var alphaTexture = material.getAlphaTestTexture();
  51525. this._effect.setTexture("diffuseSampler", alphaTexture);
  51526. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  51527. }
  51528. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  51529. };
  51530. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  51531. var defines = [];
  51532. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  51533. var mesh = subMesh.getMesh();
  51534. var material = subMesh.getMaterial();
  51535. // Alpha test
  51536. if (material && material.needAlphaTesting()) {
  51537. defines.push("#define ALPHATEST");
  51538. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  51539. attribs.push(BABYLON.VertexBuffer.UVKind);
  51540. defines.push("#define UV1");
  51541. }
  51542. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  51543. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  51544. defines.push("#define UV2");
  51545. }
  51546. }
  51547. // Bones
  51548. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  51549. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  51550. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  51551. if (mesh.numBoneInfluencers > 4) {
  51552. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  51553. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  51554. }
  51555. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  51556. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  51557. }
  51558. else {
  51559. defines.push("#define NUM_BONE_INFLUENCERS 0");
  51560. }
  51561. // Instances
  51562. if (useInstances) {
  51563. defines.push("#define INSTANCES");
  51564. attribs.push("world0");
  51565. attribs.push("world1");
  51566. attribs.push("world2");
  51567. attribs.push("world3");
  51568. }
  51569. // Get correct effect
  51570. var join = defines.join("\n");
  51571. if (this._cachedDefines !== join) {
  51572. this._cachedDefines = join;
  51573. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  51574. }
  51575. return this._effect.isReady();
  51576. };
  51577. return OutlineRenderer;
  51578. }());
  51579. BABYLON.OutlineRenderer = OutlineRenderer;
  51580. })(BABYLON || (BABYLON = {}));
  51581. var BABYLON;
  51582. (function (BABYLON) {
  51583. var MeshAssetTask = (function () {
  51584. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  51585. this.name = name;
  51586. this.meshesNames = meshesNames;
  51587. this.rootUrl = rootUrl;
  51588. this.sceneFilename = sceneFilename;
  51589. this.isCompleted = false;
  51590. }
  51591. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  51592. var _this = this;
  51593. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  51594. _this.loadedMeshes = meshes;
  51595. _this.loadedParticleSystems = particleSystems;
  51596. _this.loadedSkeletons = skeletons;
  51597. _this.isCompleted = true;
  51598. if (_this.onSuccess) {
  51599. _this.onSuccess(_this);
  51600. }
  51601. onSuccess();
  51602. }, null, function () {
  51603. if (_this.onError) {
  51604. _this.onError(_this);
  51605. }
  51606. onError();
  51607. });
  51608. };
  51609. return MeshAssetTask;
  51610. }());
  51611. BABYLON.MeshAssetTask = MeshAssetTask;
  51612. var TextFileAssetTask = (function () {
  51613. function TextFileAssetTask(name, url) {
  51614. this.name = name;
  51615. this.url = url;
  51616. this.isCompleted = false;
  51617. }
  51618. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  51619. var _this = this;
  51620. BABYLON.Tools.LoadFile(this.url, function (data) {
  51621. _this.text = data;
  51622. _this.isCompleted = true;
  51623. if (_this.onSuccess) {
  51624. _this.onSuccess(_this);
  51625. }
  51626. onSuccess();
  51627. }, null, scene.database, false, function () {
  51628. if (_this.onError) {
  51629. _this.onError(_this);
  51630. }
  51631. onError();
  51632. });
  51633. };
  51634. return TextFileAssetTask;
  51635. }());
  51636. BABYLON.TextFileAssetTask = TextFileAssetTask;
  51637. var BinaryFileAssetTask = (function () {
  51638. function BinaryFileAssetTask(name, url) {
  51639. this.name = name;
  51640. this.url = url;
  51641. this.isCompleted = false;
  51642. }
  51643. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  51644. var _this = this;
  51645. BABYLON.Tools.LoadFile(this.url, function (data) {
  51646. _this.data = data;
  51647. _this.isCompleted = true;
  51648. if (_this.onSuccess) {
  51649. _this.onSuccess(_this);
  51650. }
  51651. onSuccess();
  51652. }, null, scene.database, true, function () {
  51653. if (_this.onError) {
  51654. _this.onError(_this);
  51655. }
  51656. onError();
  51657. });
  51658. };
  51659. return BinaryFileAssetTask;
  51660. }());
  51661. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  51662. var ImageAssetTask = (function () {
  51663. function ImageAssetTask(name, url) {
  51664. this.name = name;
  51665. this.url = url;
  51666. this.isCompleted = false;
  51667. }
  51668. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  51669. var _this = this;
  51670. var img = new Image();
  51671. img.onload = function () {
  51672. _this.image = img;
  51673. _this.isCompleted = true;
  51674. if (_this.onSuccess) {
  51675. _this.onSuccess(_this);
  51676. }
  51677. onSuccess();
  51678. };
  51679. img.onerror = function () {
  51680. if (_this.onError) {
  51681. _this.onError(_this);
  51682. }
  51683. onError();
  51684. };
  51685. img.src = this.url;
  51686. };
  51687. return ImageAssetTask;
  51688. }());
  51689. BABYLON.ImageAssetTask = ImageAssetTask;
  51690. var TextureAssetTask = (function () {
  51691. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  51692. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  51693. this.name = name;
  51694. this.url = url;
  51695. this.noMipmap = noMipmap;
  51696. this.invertY = invertY;
  51697. this.samplingMode = samplingMode;
  51698. this.isCompleted = false;
  51699. }
  51700. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  51701. var _this = this;
  51702. var onload = function () {
  51703. _this.isCompleted = true;
  51704. if (_this.onSuccess) {
  51705. _this.onSuccess(_this);
  51706. }
  51707. onSuccess();
  51708. };
  51709. var onerror = function () {
  51710. if (_this.onError) {
  51711. _this.onError(_this);
  51712. }
  51713. onError();
  51714. };
  51715. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  51716. };
  51717. return TextureAssetTask;
  51718. }());
  51719. BABYLON.TextureAssetTask = TextureAssetTask;
  51720. var AssetsManager = (function () {
  51721. function AssetsManager(scene) {
  51722. this._tasks = new Array();
  51723. this._waitingTasksCount = 0;
  51724. this.useDefaultLoadingScreen = true;
  51725. this._scene = scene;
  51726. }
  51727. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  51728. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  51729. this._tasks.push(task);
  51730. return task;
  51731. };
  51732. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  51733. var task = new TextFileAssetTask(taskName, url);
  51734. this._tasks.push(task);
  51735. return task;
  51736. };
  51737. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  51738. var task = new BinaryFileAssetTask(taskName, url);
  51739. this._tasks.push(task);
  51740. return task;
  51741. };
  51742. AssetsManager.prototype.addImageTask = function (taskName, url) {
  51743. var task = new ImageAssetTask(taskName, url);
  51744. this._tasks.push(task);
  51745. return task;
  51746. };
  51747. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  51748. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  51749. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  51750. this._tasks.push(task);
  51751. return task;
  51752. };
  51753. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  51754. this._waitingTasksCount--;
  51755. if (this._waitingTasksCount === 0) {
  51756. if (this.onFinish) {
  51757. this.onFinish(this._tasks);
  51758. }
  51759. this._scene.getEngine().hideLoadingUI();
  51760. }
  51761. };
  51762. AssetsManager.prototype._runTask = function (task) {
  51763. var _this = this;
  51764. task.run(this._scene, function () {
  51765. if (_this.onTaskSuccess) {
  51766. _this.onTaskSuccess(task);
  51767. }
  51768. _this._decreaseWaitingTasksCount();
  51769. }, function () {
  51770. if (_this.onTaskError) {
  51771. _this.onTaskError(task);
  51772. }
  51773. _this._decreaseWaitingTasksCount();
  51774. });
  51775. };
  51776. AssetsManager.prototype.reset = function () {
  51777. this._tasks = new Array();
  51778. return this;
  51779. };
  51780. AssetsManager.prototype.load = function () {
  51781. this._waitingTasksCount = this._tasks.length;
  51782. if (this._waitingTasksCount === 0) {
  51783. if (this.onFinish) {
  51784. this.onFinish(this._tasks);
  51785. }
  51786. return this;
  51787. }
  51788. if (this.useDefaultLoadingScreen) {
  51789. this._scene.getEngine().displayLoadingUI();
  51790. }
  51791. for (var index = 0; index < this._tasks.length; index++) {
  51792. var task = this._tasks[index];
  51793. this._runTask(task);
  51794. }
  51795. return this;
  51796. };
  51797. return AssetsManager;
  51798. }());
  51799. BABYLON.AssetsManager = AssetsManager;
  51800. })(BABYLON || (BABYLON = {}));
  51801. var BABYLON;
  51802. (function (BABYLON) {
  51803. var VRCameraMetrics = (function () {
  51804. function VRCameraMetrics() {
  51805. this.compensateDistortion = true;
  51806. }
  51807. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  51808. get: function () {
  51809. return this.hResolution / (2 * this.vResolution);
  51810. },
  51811. enumerable: true,
  51812. configurable: true
  51813. });
  51814. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  51815. get: function () {
  51816. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  51817. },
  51818. enumerable: true,
  51819. configurable: true
  51820. });
  51821. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  51822. get: function () {
  51823. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  51824. var h = (4 * meters) / this.hScreenSize;
  51825. return BABYLON.Matrix.Translation(h, 0, 0);
  51826. },
  51827. enumerable: true,
  51828. configurable: true
  51829. });
  51830. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  51831. get: function () {
  51832. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  51833. var h = (4 * meters) / this.hScreenSize;
  51834. return BABYLON.Matrix.Translation(-h, 0, 0);
  51835. },
  51836. enumerable: true,
  51837. configurable: true
  51838. });
  51839. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  51840. get: function () {
  51841. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  51842. },
  51843. enumerable: true,
  51844. configurable: true
  51845. });
  51846. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  51847. get: function () {
  51848. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  51849. },
  51850. enumerable: true,
  51851. configurable: true
  51852. });
  51853. VRCameraMetrics.GetDefault = function () {
  51854. var result = new VRCameraMetrics();
  51855. result.hResolution = 1280;
  51856. result.vResolution = 800;
  51857. result.hScreenSize = 0.149759993;
  51858. result.vScreenSize = 0.0935999975;
  51859. result.vScreenCenter = 0.0467999987,
  51860. result.eyeToScreenDistance = 0.0410000011;
  51861. result.lensSeparationDistance = 0.0635000020;
  51862. result.interpupillaryDistance = 0.0640000030;
  51863. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  51864. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  51865. result.postProcessScaleFactor = 1.714605507808412;
  51866. result.lensCenterOffset = 0.151976421;
  51867. return result;
  51868. };
  51869. return VRCameraMetrics;
  51870. }());
  51871. BABYLON.VRCameraMetrics = VRCameraMetrics;
  51872. })(BABYLON || (BABYLON = {}));
  51873. var BABYLON;
  51874. (function (BABYLON) {
  51875. var WebVRFreeCamera = (function (_super) {
  51876. __extends(WebVRFreeCamera, _super);
  51877. function WebVRFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  51878. if (compensateDistortion === void 0) { compensateDistortion = true; }
  51879. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  51880. _super.call(this, name, position, scene);
  51881. this._hmdDevice = null;
  51882. this._sensorDevice = null;
  51883. this._cacheState = null;
  51884. this._vrEnabled = false;
  51885. vrCameraMetrics.compensateDistortion = compensateDistortion;
  51886. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  51887. this._getWebVRDevices = this._getWebVRDevices.bind(this);
  51888. this.rotationQuaternion = new BABYLON.Quaternion();
  51889. this._quaternionCache = new BABYLON.Quaternion();
  51890. }
  51891. WebVRFreeCamera.prototype._getWebVRDevices = function (devices) {
  51892. var size = devices.length;
  51893. var i = 0;
  51894. // Reset devices.
  51895. this._sensorDevice = null;
  51896. this._hmdDevice = null;
  51897. // Search for a HmdDevice.
  51898. while (i < size && this._hmdDevice === null) {
  51899. if (devices[i] instanceof HMDVRDevice) {
  51900. this._hmdDevice = devices[i];
  51901. }
  51902. i++;
  51903. }
  51904. i = 0;
  51905. while (i < size && this._sensorDevice === null) {
  51906. if (devices[i] instanceof PositionSensorVRDevice && (!this._hmdDevice || devices[i].hardwareUnitId === this._hmdDevice.hardwareUnitId)) {
  51907. this._sensorDevice = devices[i];
  51908. }
  51909. i++;
  51910. }
  51911. this._vrEnabled = this._sensorDevice && this._hmdDevice ? true : false;
  51912. };
  51913. WebVRFreeCamera.prototype._checkInputs = function () {
  51914. if (this._vrEnabled) {
  51915. this._cacheState = this._sensorDevice.getState();
  51916. this.rotationQuaternion.copyFrom(this._cacheState.orientation);
  51917. //Flip in XY plane
  51918. this.rotationQuaternion.z *= -1;
  51919. this.rotationQuaternion.w *= -1;
  51920. if (this._initialQuaternion) {
  51921. this._quaternionCache.copyFrom(this.rotationQuaternion);
  51922. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  51923. }
  51924. }
  51925. _super.prototype._checkInputs.call(this);
  51926. };
  51927. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  51928. _super.prototype.attachControl.call(this, element, noPreventDefault);
  51929. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  51930. if (navigator.getVRDevices) {
  51931. navigator.getVRDevices().then(this._getWebVRDevices);
  51932. }
  51933. else if (navigator.mozGetVRDevices) {
  51934. navigator.mozGetVRDevices(this._getWebVRDevices);
  51935. }
  51936. };
  51937. WebVRFreeCamera.prototype.detachControl = function (element) {
  51938. _super.prototype.detachControl.call(this, element);
  51939. this._vrEnabled = false;
  51940. };
  51941. WebVRFreeCamera.prototype.requestVRFullscreen = function (requestPointerlock) {
  51942. if (!this._hmdDevice)
  51943. return;
  51944. this.getEngine().switchFullscreen(requestPointerlock, { vrDisplay: this._hmdDevice });
  51945. };
  51946. WebVRFreeCamera.prototype.getTypeName = function () {
  51947. return "WebVRFreeCamera";
  51948. };
  51949. WebVRFreeCamera.prototype.resetToCurrentRotation = function (axis) {
  51950. var _this = this;
  51951. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  51952. //can only work if this camera has a rotation quaternion already.
  51953. if (!this.rotationQuaternion)
  51954. return;
  51955. if (!this._initialQuaternion) {
  51956. this._initialQuaternion = new BABYLON.Quaternion();
  51957. }
  51958. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  51959. ['x', 'y', 'z'].forEach(function (axisName) {
  51960. if (!axis[axisName]) {
  51961. _this._initialQuaternion[axisName] = 0;
  51962. }
  51963. else {
  51964. _this._initialQuaternion[axisName] *= -1;
  51965. }
  51966. });
  51967. this._initialQuaternion.normalize();
  51968. };
  51969. return WebVRFreeCamera;
  51970. }(BABYLON.FreeCamera));
  51971. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  51972. })(BABYLON || (BABYLON = {}));
  51973. var BABYLON;
  51974. (function (BABYLON) {
  51975. // Standard optimizations
  51976. var SceneOptimization = (function () {
  51977. function SceneOptimization(priority) {
  51978. if (priority === void 0) { priority = 0; }
  51979. this.priority = priority;
  51980. this.apply = function (scene) {
  51981. return true; // Return true if everything that can be done was applied
  51982. };
  51983. }
  51984. return SceneOptimization;
  51985. }());
  51986. BABYLON.SceneOptimization = SceneOptimization;
  51987. var TextureOptimization = (function (_super) {
  51988. __extends(TextureOptimization, _super);
  51989. function TextureOptimization(priority, maximumSize) {
  51990. var _this = this;
  51991. if (priority === void 0) { priority = 0; }
  51992. if (maximumSize === void 0) { maximumSize = 1024; }
  51993. _super.call(this, priority);
  51994. this.priority = priority;
  51995. this.maximumSize = maximumSize;
  51996. this.apply = function (scene) {
  51997. var allDone = true;
  51998. for (var index = 0; index < scene.textures.length; index++) {
  51999. var texture = scene.textures[index];
  52000. if (!texture.canRescale) {
  52001. continue;
  52002. }
  52003. var currentSize = texture.getSize();
  52004. var maxDimension = Math.max(currentSize.width, currentSize.height);
  52005. if (maxDimension > _this.maximumSize) {
  52006. texture.scale(0.5);
  52007. allDone = false;
  52008. }
  52009. }
  52010. return allDone;
  52011. };
  52012. }
  52013. return TextureOptimization;
  52014. }(SceneOptimization));
  52015. BABYLON.TextureOptimization = TextureOptimization;
  52016. var HardwareScalingOptimization = (function (_super) {
  52017. __extends(HardwareScalingOptimization, _super);
  52018. function HardwareScalingOptimization(priority, maximumScale) {
  52019. var _this = this;
  52020. if (priority === void 0) { priority = 0; }
  52021. if (maximumScale === void 0) { maximumScale = 2; }
  52022. _super.call(this, priority);
  52023. this.priority = priority;
  52024. this.maximumScale = maximumScale;
  52025. this._currentScale = 1;
  52026. this.apply = function (scene) {
  52027. _this._currentScale++;
  52028. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  52029. return _this._currentScale >= _this.maximumScale;
  52030. };
  52031. }
  52032. return HardwareScalingOptimization;
  52033. }(SceneOptimization));
  52034. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  52035. var ShadowsOptimization = (function (_super) {
  52036. __extends(ShadowsOptimization, _super);
  52037. function ShadowsOptimization() {
  52038. _super.apply(this, arguments);
  52039. this.apply = function (scene) {
  52040. scene.shadowsEnabled = false;
  52041. return true;
  52042. };
  52043. }
  52044. return ShadowsOptimization;
  52045. }(SceneOptimization));
  52046. BABYLON.ShadowsOptimization = ShadowsOptimization;
  52047. var PostProcessesOptimization = (function (_super) {
  52048. __extends(PostProcessesOptimization, _super);
  52049. function PostProcessesOptimization() {
  52050. _super.apply(this, arguments);
  52051. this.apply = function (scene) {
  52052. scene.postProcessesEnabled = false;
  52053. return true;
  52054. };
  52055. }
  52056. return PostProcessesOptimization;
  52057. }(SceneOptimization));
  52058. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  52059. var LensFlaresOptimization = (function (_super) {
  52060. __extends(LensFlaresOptimization, _super);
  52061. function LensFlaresOptimization() {
  52062. _super.apply(this, arguments);
  52063. this.apply = function (scene) {
  52064. scene.lensFlaresEnabled = false;
  52065. return true;
  52066. };
  52067. }
  52068. return LensFlaresOptimization;
  52069. }(SceneOptimization));
  52070. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  52071. var ParticlesOptimization = (function (_super) {
  52072. __extends(ParticlesOptimization, _super);
  52073. function ParticlesOptimization() {
  52074. _super.apply(this, arguments);
  52075. this.apply = function (scene) {
  52076. scene.particlesEnabled = false;
  52077. return true;
  52078. };
  52079. }
  52080. return ParticlesOptimization;
  52081. }(SceneOptimization));
  52082. BABYLON.ParticlesOptimization = ParticlesOptimization;
  52083. var RenderTargetsOptimization = (function (_super) {
  52084. __extends(RenderTargetsOptimization, _super);
  52085. function RenderTargetsOptimization() {
  52086. _super.apply(this, arguments);
  52087. this.apply = function (scene) {
  52088. scene.renderTargetsEnabled = false;
  52089. return true;
  52090. };
  52091. }
  52092. return RenderTargetsOptimization;
  52093. }(SceneOptimization));
  52094. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  52095. var MergeMeshesOptimization = (function (_super) {
  52096. __extends(MergeMeshesOptimization, _super);
  52097. function MergeMeshesOptimization() {
  52098. var _this = this;
  52099. _super.apply(this, arguments);
  52100. this._canBeMerged = function (abstractMesh) {
  52101. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  52102. return false;
  52103. }
  52104. var mesh = abstractMesh;
  52105. if (!mesh.isVisible || !mesh.isEnabled()) {
  52106. return false;
  52107. }
  52108. if (mesh.instances.length > 0) {
  52109. return false;
  52110. }
  52111. if (mesh.skeleton || mesh.hasLODLevels) {
  52112. return false;
  52113. }
  52114. if (mesh.parent) {
  52115. return false;
  52116. }
  52117. return true;
  52118. };
  52119. this.apply = function (scene, updateSelectionTree) {
  52120. var globalPool = scene.meshes.slice(0);
  52121. var globalLength = globalPool.length;
  52122. for (var index = 0; index < globalLength; index++) {
  52123. var currentPool = new Array();
  52124. var current = globalPool[index];
  52125. // Checks
  52126. if (!_this._canBeMerged(current)) {
  52127. continue;
  52128. }
  52129. currentPool.push(current);
  52130. // Find compatible meshes
  52131. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  52132. var otherMesh = globalPool[subIndex];
  52133. if (!_this._canBeMerged(otherMesh)) {
  52134. continue;
  52135. }
  52136. if (otherMesh.material !== current.material) {
  52137. continue;
  52138. }
  52139. if (otherMesh.checkCollisions !== current.checkCollisions) {
  52140. continue;
  52141. }
  52142. currentPool.push(otherMesh);
  52143. globalLength--;
  52144. globalPool.splice(subIndex, 1);
  52145. subIndex--;
  52146. }
  52147. if (currentPool.length < 2) {
  52148. continue;
  52149. }
  52150. // Merge meshes
  52151. BABYLON.Mesh.MergeMeshes(currentPool);
  52152. }
  52153. if (updateSelectionTree != undefined) {
  52154. if (updateSelectionTree) {
  52155. scene.createOrUpdateSelectionOctree();
  52156. }
  52157. }
  52158. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  52159. scene.createOrUpdateSelectionOctree();
  52160. }
  52161. return true;
  52162. };
  52163. }
  52164. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  52165. get: function () {
  52166. return MergeMeshesOptimization._UpdateSelectionTree;
  52167. },
  52168. set: function (value) {
  52169. MergeMeshesOptimization._UpdateSelectionTree = value;
  52170. },
  52171. enumerable: true,
  52172. configurable: true
  52173. });
  52174. MergeMeshesOptimization._UpdateSelectionTree = false;
  52175. return MergeMeshesOptimization;
  52176. }(SceneOptimization));
  52177. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  52178. // Options
  52179. var SceneOptimizerOptions = (function () {
  52180. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  52181. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  52182. if (trackerDuration === void 0) { trackerDuration = 2000; }
  52183. this.targetFrameRate = targetFrameRate;
  52184. this.trackerDuration = trackerDuration;
  52185. this.optimizations = new Array();
  52186. }
  52187. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  52188. var result = new SceneOptimizerOptions(targetFrameRate);
  52189. var priority = 0;
  52190. result.optimizations.push(new MergeMeshesOptimization(priority));
  52191. result.optimizations.push(new ShadowsOptimization(priority));
  52192. result.optimizations.push(new LensFlaresOptimization(priority));
  52193. // Next priority
  52194. priority++;
  52195. result.optimizations.push(new PostProcessesOptimization(priority));
  52196. result.optimizations.push(new ParticlesOptimization(priority));
  52197. // Next priority
  52198. priority++;
  52199. result.optimizations.push(new TextureOptimization(priority, 1024));
  52200. return result;
  52201. };
  52202. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  52203. var result = new SceneOptimizerOptions(targetFrameRate);
  52204. var priority = 0;
  52205. result.optimizations.push(new MergeMeshesOptimization(priority));
  52206. result.optimizations.push(new ShadowsOptimization(priority));
  52207. result.optimizations.push(new LensFlaresOptimization(priority));
  52208. // Next priority
  52209. priority++;
  52210. result.optimizations.push(new PostProcessesOptimization(priority));
  52211. result.optimizations.push(new ParticlesOptimization(priority));
  52212. // Next priority
  52213. priority++;
  52214. result.optimizations.push(new TextureOptimization(priority, 512));
  52215. // Next priority
  52216. priority++;
  52217. result.optimizations.push(new RenderTargetsOptimization(priority));
  52218. // Next priority
  52219. priority++;
  52220. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  52221. return result;
  52222. };
  52223. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  52224. var result = new SceneOptimizerOptions(targetFrameRate);
  52225. var priority = 0;
  52226. result.optimizations.push(new MergeMeshesOptimization(priority));
  52227. result.optimizations.push(new ShadowsOptimization(priority));
  52228. result.optimizations.push(new LensFlaresOptimization(priority));
  52229. // Next priority
  52230. priority++;
  52231. result.optimizations.push(new PostProcessesOptimization(priority));
  52232. result.optimizations.push(new ParticlesOptimization(priority));
  52233. // Next priority
  52234. priority++;
  52235. result.optimizations.push(new TextureOptimization(priority, 256));
  52236. // Next priority
  52237. priority++;
  52238. result.optimizations.push(new RenderTargetsOptimization(priority));
  52239. // Next priority
  52240. priority++;
  52241. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  52242. return result;
  52243. };
  52244. return SceneOptimizerOptions;
  52245. }());
  52246. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  52247. // Scene optimizer tool
  52248. var SceneOptimizer = (function () {
  52249. function SceneOptimizer() {
  52250. }
  52251. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  52252. // TODO: add an epsilon
  52253. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  52254. if (onSuccess) {
  52255. onSuccess();
  52256. }
  52257. return;
  52258. }
  52259. // Apply current level of optimizations
  52260. var allDone = true;
  52261. var noOptimizationApplied = true;
  52262. for (var index = 0; index < options.optimizations.length; index++) {
  52263. var optimization = options.optimizations[index];
  52264. if (optimization.priority === currentPriorityLevel) {
  52265. noOptimizationApplied = false;
  52266. allDone = allDone && optimization.apply(scene);
  52267. }
  52268. }
  52269. // If no optimization was applied, this is a failure :(
  52270. if (noOptimizationApplied) {
  52271. if (onFailure) {
  52272. onFailure();
  52273. }
  52274. return;
  52275. }
  52276. // If all optimizations were done, move to next level
  52277. if (allDone) {
  52278. currentPriorityLevel++;
  52279. }
  52280. // Let's the system running for a specific amount of time before checking FPS
  52281. scene.executeWhenReady(function () {
  52282. setTimeout(function () {
  52283. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  52284. }, options.trackerDuration);
  52285. });
  52286. };
  52287. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  52288. if (!options) {
  52289. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  52290. }
  52291. // Let's the system running for a specific amount of time before checking FPS
  52292. scene.executeWhenReady(function () {
  52293. setTimeout(function () {
  52294. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  52295. }, options.trackerDuration);
  52296. });
  52297. };
  52298. return SceneOptimizer;
  52299. }());
  52300. BABYLON.SceneOptimizer = SceneOptimizer;
  52301. })(BABYLON || (BABYLON = {}));
  52302. var BABYLON;
  52303. (function (BABYLON) {
  52304. var Internals;
  52305. (function (Internals) {
  52306. var MeshLODLevel = (function () {
  52307. function MeshLODLevel(distance, mesh) {
  52308. this.distance = distance;
  52309. this.mesh = mesh;
  52310. }
  52311. return MeshLODLevel;
  52312. }());
  52313. Internals.MeshLODLevel = MeshLODLevel;
  52314. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  52315. })(BABYLON || (BABYLON = {}));
  52316. var BABYLON;
  52317. (function (BABYLON) {
  52318. var RawTexture = (function (_super) {
  52319. __extends(RawTexture, _super);
  52320. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  52321. if (generateMipMaps === void 0) { generateMipMaps = true; }
  52322. if (invertY === void 0) { invertY = false; }
  52323. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  52324. _super.call(this, null, scene, !generateMipMaps, invertY);
  52325. this.format = format;
  52326. this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  52327. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  52328. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  52329. }
  52330. RawTexture.prototype.update = function (data) {
  52331. this.getScene().getEngine().updateRawTexture(this._texture, data, this.format, this._invertY);
  52332. };
  52333. // Statics
  52334. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  52335. if (generateMipMaps === void 0) { generateMipMaps = true; }
  52336. if (invertY === void 0) { invertY = false; }
  52337. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  52338. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  52339. };
  52340. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  52341. if (generateMipMaps === void 0) { generateMipMaps = true; }
  52342. if (invertY === void 0) { invertY = false; }
  52343. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  52344. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  52345. };
  52346. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  52347. if (generateMipMaps === void 0) { generateMipMaps = true; }
  52348. if (invertY === void 0) { invertY = false; }
  52349. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  52350. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  52351. };
  52352. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  52353. if (generateMipMaps === void 0) { generateMipMaps = true; }
  52354. if (invertY === void 0) { invertY = false; }
  52355. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  52356. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  52357. };
  52358. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  52359. if (generateMipMaps === void 0) { generateMipMaps = true; }
  52360. if (invertY === void 0) { invertY = false; }
  52361. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  52362. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  52363. };
  52364. return RawTexture;
  52365. }(BABYLON.Texture));
  52366. BABYLON.RawTexture = RawTexture;
  52367. })(BABYLON || (BABYLON = {}));
  52368. var BABYLON;
  52369. (function (BABYLON) {
  52370. var IndexedVector2 = (function (_super) {
  52371. __extends(IndexedVector2, _super);
  52372. function IndexedVector2(original, index) {
  52373. _super.call(this, original.x, original.y);
  52374. this.index = index;
  52375. }
  52376. return IndexedVector2;
  52377. }(BABYLON.Vector2));
  52378. var PolygonPoints = (function () {
  52379. function PolygonPoints() {
  52380. this.elements = new Array();
  52381. }
  52382. PolygonPoints.prototype.add = function (originalPoints) {
  52383. var _this = this;
  52384. var result = new Array();
  52385. originalPoints.forEach(function (point) {
  52386. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  52387. var newPoint = new IndexedVector2(point, _this.elements.length);
  52388. result.push(newPoint);
  52389. _this.elements.push(newPoint);
  52390. }
  52391. });
  52392. return result;
  52393. };
  52394. PolygonPoints.prototype.computeBounds = function () {
  52395. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  52396. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  52397. this.elements.forEach(function (point) {
  52398. // x
  52399. if (point.x < lmin.x) {
  52400. lmin.x = point.x;
  52401. }
  52402. else if (point.x > lmax.x) {
  52403. lmax.x = point.x;
  52404. }
  52405. // y
  52406. if (point.y < lmin.y) {
  52407. lmin.y = point.y;
  52408. }
  52409. else if (point.y > lmax.y) {
  52410. lmax.y = point.y;
  52411. }
  52412. });
  52413. return {
  52414. min: lmin,
  52415. max: lmax,
  52416. width: lmax.x - lmin.x,
  52417. height: lmax.y - lmin.y
  52418. };
  52419. };
  52420. return PolygonPoints;
  52421. }());
  52422. var Polygon = (function () {
  52423. function Polygon() {
  52424. }
  52425. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  52426. return [
  52427. new BABYLON.Vector2(xmin, ymin),
  52428. new BABYLON.Vector2(xmax, ymin),
  52429. new BABYLON.Vector2(xmax, ymax),
  52430. new BABYLON.Vector2(xmin, ymax)
  52431. ];
  52432. };
  52433. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  52434. if (cx === void 0) { cx = 0; }
  52435. if (cy === void 0) { cy = 0; }
  52436. if (numberOfSides === void 0) { numberOfSides = 32; }
  52437. var result = new Array();
  52438. var angle = 0;
  52439. var increment = (Math.PI * 2) / numberOfSides;
  52440. for (var i = 0; i < numberOfSides; i++) {
  52441. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  52442. angle -= increment;
  52443. }
  52444. return result;
  52445. };
  52446. Polygon.Parse = function (input) {
  52447. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  52448. var i, result = [];
  52449. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  52450. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  52451. }
  52452. return result;
  52453. };
  52454. Polygon.StartingAt = function (x, y) {
  52455. return BABYLON.Path2.StartingAt(x, y);
  52456. };
  52457. return Polygon;
  52458. }());
  52459. BABYLON.Polygon = Polygon;
  52460. var PolygonMeshBuilder = (function () {
  52461. function PolygonMeshBuilder(name, contours, scene) {
  52462. this._points = new PolygonPoints();
  52463. this._outlinepoints = new PolygonPoints();
  52464. this._holes = [];
  52465. this._epoints = new Array();
  52466. this._eholes = new Array();
  52467. this._name = name;
  52468. this._scene = scene;
  52469. var points;
  52470. if (contours instanceof BABYLON.Path2) {
  52471. points = contours.getPoints();
  52472. }
  52473. else {
  52474. points = contours;
  52475. }
  52476. this._addToepoint(points);
  52477. this._points.add(points);
  52478. this._outlinepoints.add(points);
  52479. }
  52480. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  52481. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  52482. var p = points_1[_i];
  52483. this._epoints.push(p.x, p.y);
  52484. }
  52485. };
  52486. PolygonMeshBuilder.prototype.addHole = function (hole) {
  52487. this._points.add(hole);
  52488. var holepoints = new PolygonPoints();
  52489. holepoints.add(hole);
  52490. this._holes.push(holepoints);
  52491. this._eholes.push(this._epoints.length / 2);
  52492. this._addToepoint(hole);
  52493. return this;
  52494. };
  52495. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  52496. var _this = this;
  52497. if (updatable === void 0) { updatable = false; }
  52498. var result = new BABYLON.Mesh(this._name, this._scene);
  52499. var normals = [];
  52500. var positions = [];
  52501. var uvs = [];
  52502. var bounds = this._points.computeBounds();
  52503. this._points.elements.forEach(function (p) {
  52504. normals.push(0, 1.0, 0);
  52505. positions.push(p.x, 0, p.y);
  52506. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  52507. });
  52508. var indices = [];
  52509. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  52510. for (var i = 0; i < res.length; i++) {
  52511. indices.push(res[i]);
  52512. }
  52513. if (depth > 0) {
  52514. var positionscount = (positions.length / 3); //get the current pointcount
  52515. this._points.elements.forEach(function (p) {
  52516. normals.push(0, -1.0, 0);
  52517. positions.push(p.x, -depth, p.y);
  52518. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  52519. });
  52520. var totalCount = indices.length;
  52521. for (var i = 0; i < totalCount; i += 3) {
  52522. var i0 = indices[i + 0];
  52523. var i1 = indices[i + 1];
  52524. var i2 = indices[i + 2];
  52525. indices.push(i2 + positionscount);
  52526. indices.push(i1 + positionscount);
  52527. indices.push(i0 + positionscount);
  52528. }
  52529. //Add the sides
  52530. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  52531. this._holes.forEach(function (hole) {
  52532. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  52533. });
  52534. }
  52535. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  52536. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  52537. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  52538. result.setIndices(indices);
  52539. return result;
  52540. };
  52541. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  52542. var StartIndex = positions.length / 3;
  52543. var ulength = 0;
  52544. for (var i = 0; i < points.elements.length; i++) {
  52545. var p = points.elements[i];
  52546. var p1;
  52547. if ((i + 1) > points.elements.length - 1) {
  52548. p1 = points.elements[0];
  52549. }
  52550. else {
  52551. p1 = points.elements[i + 1];
  52552. }
  52553. positions.push(p.x, 0, p.y);
  52554. positions.push(p.x, -depth, p.y);
  52555. positions.push(p1.x, 0, p1.y);
  52556. positions.push(p1.x, -depth, p1.y);
  52557. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  52558. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  52559. var v3 = v2.subtract(v1);
  52560. var v4 = new BABYLON.Vector3(0, 1, 0);
  52561. var vn = BABYLON.Vector3.Cross(v3, v4);
  52562. vn = vn.normalize();
  52563. uvs.push(ulength / bounds.width, 0);
  52564. uvs.push(ulength / bounds.width, 1);
  52565. ulength += v3.length();
  52566. uvs.push((ulength / bounds.width), 0);
  52567. uvs.push((ulength / bounds.width), 1);
  52568. if (!flip) {
  52569. normals.push(-vn.x, -vn.y, -vn.z);
  52570. normals.push(-vn.x, -vn.y, -vn.z);
  52571. normals.push(-vn.x, -vn.y, -vn.z);
  52572. normals.push(-vn.x, -vn.y, -vn.z);
  52573. indices.push(StartIndex);
  52574. indices.push(StartIndex + 1);
  52575. indices.push(StartIndex + 2);
  52576. indices.push(StartIndex + 1);
  52577. indices.push(StartIndex + 3);
  52578. indices.push(StartIndex + 2);
  52579. }
  52580. else {
  52581. normals.push(vn.x, vn.y, vn.z);
  52582. normals.push(vn.x, vn.y, vn.z);
  52583. normals.push(vn.x, vn.y, vn.z);
  52584. normals.push(vn.x, vn.y, vn.z);
  52585. indices.push(StartIndex);
  52586. indices.push(StartIndex + 2);
  52587. indices.push(StartIndex + 1);
  52588. indices.push(StartIndex + 1);
  52589. indices.push(StartIndex + 2);
  52590. indices.push(StartIndex + 3);
  52591. }
  52592. StartIndex += 4;
  52593. }
  52594. ;
  52595. };
  52596. return PolygonMeshBuilder;
  52597. }());
  52598. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  52599. })(BABYLON || (BABYLON = {}));
  52600. var BABYLON;
  52601. (function (BABYLON) {
  52602. var Octree = (function () {
  52603. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  52604. if (maxDepth === void 0) { maxDepth = 2; }
  52605. this.maxDepth = maxDepth;
  52606. this.dynamicContent = new Array();
  52607. this._maxBlockCapacity = maxBlockCapacity || 64;
  52608. this._selectionContent = new BABYLON.SmartArray(1024);
  52609. this._creationFunc = creationFunc;
  52610. }
  52611. // Methods
  52612. Octree.prototype.update = function (worldMin, worldMax, entries) {
  52613. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  52614. };
  52615. Octree.prototype.addMesh = function (entry) {
  52616. for (var index = 0; index < this.blocks.length; index++) {
  52617. var block = this.blocks[index];
  52618. block.addEntry(entry);
  52619. }
  52620. };
  52621. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  52622. this._selectionContent.reset();
  52623. for (var index = 0; index < this.blocks.length; index++) {
  52624. var block = this.blocks[index];
  52625. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  52626. }
  52627. if (allowDuplicate) {
  52628. this._selectionContent.concat(this.dynamicContent);
  52629. }
  52630. else {
  52631. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  52632. }
  52633. return this._selectionContent;
  52634. };
  52635. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  52636. this._selectionContent.reset();
  52637. for (var index = 0; index < this.blocks.length; index++) {
  52638. var block = this.blocks[index];
  52639. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  52640. }
  52641. if (allowDuplicate) {
  52642. this._selectionContent.concat(this.dynamicContent);
  52643. }
  52644. else {
  52645. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  52646. }
  52647. return this._selectionContent;
  52648. };
  52649. Octree.prototype.intersectsRay = function (ray) {
  52650. this._selectionContent.reset();
  52651. for (var index = 0; index < this.blocks.length; index++) {
  52652. var block = this.blocks[index];
  52653. block.intersectsRay(ray, this._selectionContent);
  52654. }
  52655. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  52656. return this._selectionContent;
  52657. };
  52658. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  52659. target.blocks = new Array();
  52660. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  52661. // Segmenting space
  52662. for (var x = 0; x < 2; x++) {
  52663. for (var y = 0; y < 2; y++) {
  52664. for (var z = 0; z < 2; z++) {
  52665. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  52666. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  52667. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  52668. block.addEntries(entries);
  52669. target.blocks.push(block);
  52670. }
  52671. }
  52672. }
  52673. };
  52674. Octree.CreationFuncForMeshes = function (entry, block) {
  52675. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  52676. block.entries.push(entry);
  52677. }
  52678. };
  52679. Octree.CreationFuncForSubMeshes = function (entry, block) {
  52680. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  52681. block.entries.push(entry);
  52682. }
  52683. };
  52684. return Octree;
  52685. }());
  52686. BABYLON.Octree = Octree;
  52687. })(BABYLON || (BABYLON = {}));
  52688. var BABYLON;
  52689. (function (BABYLON) {
  52690. var OctreeBlock = (function () {
  52691. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  52692. this.entries = new Array();
  52693. this._boundingVectors = new Array();
  52694. this._capacity = capacity;
  52695. this._depth = depth;
  52696. this._maxDepth = maxDepth;
  52697. this._creationFunc = creationFunc;
  52698. this._minPoint = minPoint;
  52699. this._maxPoint = maxPoint;
  52700. this._boundingVectors.push(minPoint.clone());
  52701. this._boundingVectors.push(maxPoint.clone());
  52702. this._boundingVectors.push(minPoint.clone());
  52703. this._boundingVectors[2].x = maxPoint.x;
  52704. this._boundingVectors.push(minPoint.clone());
  52705. this._boundingVectors[3].y = maxPoint.y;
  52706. this._boundingVectors.push(minPoint.clone());
  52707. this._boundingVectors[4].z = maxPoint.z;
  52708. this._boundingVectors.push(maxPoint.clone());
  52709. this._boundingVectors[5].z = minPoint.z;
  52710. this._boundingVectors.push(maxPoint.clone());
  52711. this._boundingVectors[6].x = minPoint.x;
  52712. this._boundingVectors.push(maxPoint.clone());
  52713. this._boundingVectors[7].y = minPoint.y;
  52714. }
  52715. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  52716. // Property
  52717. get: function () {
  52718. return this._capacity;
  52719. },
  52720. enumerable: true,
  52721. configurable: true
  52722. });
  52723. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  52724. get: function () {
  52725. return this._minPoint;
  52726. },
  52727. enumerable: true,
  52728. configurable: true
  52729. });
  52730. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  52731. get: function () {
  52732. return this._maxPoint;
  52733. },
  52734. enumerable: true,
  52735. configurable: true
  52736. });
  52737. // Methods
  52738. OctreeBlock.prototype.addEntry = function (entry) {
  52739. if (this.blocks) {
  52740. for (var index = 0; index < this.blocks.length; index++) {
  52741. var block = this.blocks[index];
  52742. block.addEntry(entry);
  52743. }
  52744. return;
  52745. }
  52746. this._creationFunc(entry, this);
  52747. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  52748. this.createInnerBlocks();
  52749. }
  52750. };
  52751. OctreeBlock.prototype.addEntries = function (entries) {
  52752. for (var index = 0; index < entries.length; index++) {
  52753. var mesh = entries[index];
  52754. this.addEntry(mesh);
  52755. }
  52756. };
  52757. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  52758. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  52759. if (this.blocks) {
  52760. for (var index = 0; index < this.blocks.length; index++) {
  52761. var block = this.blocks[index];
  52762. block.select(frustumPlanes, selection, allowDuplicate);
  52763. }
  52764. return;
  52765. }
  52766. if (allowDuplicate) {
  52767. selection.concat(this.entries);
  52768. }
  52769. else {
  52770. selection.concatWithNoDuplicate(this.entries);
  52771. }
  52772. }
  52773. };
  52774. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  52775. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  52776. if (this.blocks) {
  52777. for (var index = 0; index < this.blocks.length; index++) {
  52778. var block = this.blocks[index];
  52779. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  52780. }
  52781. return;
  52782. }
  52783. if (allowDuplicate) {
  52784. selection.concat(this.entries);
  52785. }
  52786. else {
  52787. selection.concatWithNoDuplicate(this.entries);
  52788. }
  52789. }
  52790. };
  52791. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  52792. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  52793. if (this.blocks) {
  52794. for (var index = 0; index < this.blocks.length; index++) {
  52795. var block = this.blocks[index];
  52796. block.intersectsRay(ray, selection);
  52797. }
  52798. return;
  52799. }
  52800. selection.concatWithNoDuplicate(this.entries);
  52801. }
  52802. };
  52803. OctreeBlock.prototype.createInnerBlocks = function () {
  52804. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  52805. };
  52806. return OctreeBlock;
  52807. }());
  52808. BABYLON.OctreeBlock = OctreeBlock;
  52809. })(BABYLON || (BABYLON = {}));
  52810. var BABYLON;
  52811. (function (BABYLON) {
  52812. var BlurPostProcess = (function (_super) {
  52813. __extends(BlurPostProcess, _super);
  52814. function BlurPostProcess(name, direction, blurWidth, options, camera, samplingMode, engine, reusable) {
  52815. var _this = this;
  52816. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  52817. _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable);
  52818. this.direction = direction;
  52819. this.blurWidth = blurWidth;
  52820. this.onApplyObservable.add(function (effect) {
  52821. effect.setFloat2("screenSize", _this.width, _this.height);
  52822. effect.setVector2("direction", _this.direction);
  52823. effect.setFloat("blurWidth", _this.blurWidth);
  52824. });
  52825. }
  52826. return BlurPostProcess;
  52827. }(BABYLON.PostProcess));
  52828. BABYLON.BlurPostProcess = BlurPostProcess;
  52829. })(BABYLON || (BABYLON = {}));
  52830. var BABYLON;
  52831. (function (BABYLON) {
  52832. var RefractionPostProcess = (function (_super) {
  52833. __extends(RefractionPostProcess, _super);
  52834. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  52835. var _this = this;
  52836. _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable);
  52837. this.color = color;
  52838. this.depth = depth;
  52839. this.colorLevel = colorLevel;
  52840. this.onActivateObservable.add(function (cam) {
  52841. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  52842. });
  52843. this.onApplyObservable.add(function (effect) {
  52844. effect.setColor3("baseColor", _this.color);
  52845. effect.setFloat("depth", _this.depth);
  52846. effect.setFloat("colorLevel", _this.colorLevel);
  52847. effect.setTexture("refractionSampler", _this._refRexture);
  52848. });
  52849. }
  52850. // Methods
  52851. RefractionPostProcess.prototype.dispose = function (camera) {
  52852. if (this._refRexture) {
  52853. this._refRexture.dispose();
  52854. }
  52855. _super.prototype.dispose.call(this, camera);
  52856. };
  52857. return RefractionPostProcess;
  52858. }(BABYLON.PostProcess));
  52859. BABYLON.RefractionPostProcess = RefractionPostProcess;
  52860. })(BABYLON || (BABYLON = {}));
  52861. var BABYLON;
  52862. (function (BABYLON) {
  52863. var BlackAndWhitePostProcess = (function (_super) {
  52864. __extends(BlackAndWhitePostProcess, _super);
  52865. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  52866. _super.call(this, name, "blackAndWhite", null, null, options, camera, samplingMode, engine, reusable);
  52867. }
  52868. return BlackAndWhitePostProcess;
  52869. }(BABYLON.PostProcess));
  52870. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  52871. })(BABYLON || (BABYLON = {}));
  52872. var BABYLON;
  52873. (function (BABYLON) {
  52874. var ConvolutionPostProcess = (function (_super) {
  52875. __extends(ConvolutionPostProcess, _super);
  52876. function ConvolutionPostProcess(name, kernel, options, camera, samplingMode, engine, reusable) {
  52877. var _this = this;
  52878. _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable);
  52879. this.kernel = kernel;
  52880. this.onApply = function (effect) {
  52881. effect.setFloat2("screenSize", _this.width, _this.height);
  52882. effect.setArray("kernel", _this.kernel);
  52883. };
  52884. }
  52885. // Statics
  52886. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  52887. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  52888. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  52889. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  52890. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  52891. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  52892. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  52893. return ConvolutionPostProcess;
  52894. }(BABYLON.PostProcess));
  52895. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  52896. })(BABYLON || (BABYLON = {}));
  52897. var BABYLON;
  52898. (function (BABYLON) {
  52899. var FilterPostProcess = (function (_super) {
  52900. __extends(FilterPostProcess, _super);
  52901. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  52902. var _this = this;
  52903. _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable);
  52904. this.kernelMatrix = kernelMatrix;
  52905. this.onApply = function (effect) {
  52906. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  52907. };
  52908. }
  52909. return FilterPostProcess;
  52910. }(BABYLON.PostProcess));
  52911. BABYLON.FilterPostProcess = FilterPostProcess;
  52912. })(BABYLON || (BABYLON = {}));
  52913. var BABYLON;
  52914. (function (BABYLON) {
  52915. var FxaaPostProcess = (function (_super) {
  52916. __extends(FxaaPostProcess, _super);
  52917. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable) {
  52918. var _this = this;
  52919. _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode, engine, reusable);
  52920. this.onSizeChangedObservable.add(function () {
  52921. _this.texelWidth = 1.0 / _this.width;
  52922. _this.texelHeight = 1.0 / _this.height;
  52923. });
  52924. this.onApplyObservable.add(function (effect) {
  52925. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  52926. });
  52927. }
  52928. return FxaaPostProcess;
  52929. }(BABYLON.PostProcess));
  52930. BABYLON.FxaaPostProcess = FxaaPostProcess;
  52931. })(BABYLON || (BABYLON = {}));
  52932. var BABYLON;
  52933. (function (BABYLON) {
  52934. var StereoscopicInterlacePostProcess = (function (_super) {
  52935. __extends(StereoscopicInterlacePostProcess, _super);
  52936. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  52937. var _this = this;
  52938. _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined);
  52939. this._passedProcess = rigCameras[0]._rigPostProcess;
  52940. this._stepSize = new BABYLON.Vector2(1 / this.width, 1 / this.height);
  52941. this.onSizeChangedObservable.add(function () {
  52942. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  52943. });
  52944. this.onApplyObservable.add(function (effect) {
  52945. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  52946. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  52947. });
  52948. }
  52949. return StereoscopicInterlacePostProcess;
  52950. }(BABYLON.PostProcess));
  52951. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  52952. })(BABYLON || (BABYLON = {}));
  52953. var BABYLON;
  52954. (function (BABYLON) {
  52955. var LensFlare = (function () {
  52956. function LensFlare(size, position, color, imgUrl, system) {
  52957. this.size = size;
  52958. this.position = position;
  52959. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  52960. this.dispose = function () {
  52961. if (this.texture) {
  52962. this.texture.dispose();
  52963. }
  52964. // Remove from scene
  52965. var index = this._system.lensFlares.indexOf(this);
  52966. this._system.lensFlares.splice(index, 1);
  52967. };
  52968. this.color = color || new BABYLON.Color3(1, 1, 1);
  52969. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  52970. this._system = system;
  52971. system.lensFlares.push(this);
  52972. }
  52973. return LensFlare;
  52974. }());
  52975. BABYLON.LensFlare = LensFlare;
  52976. })(BABYLON || (BABYLON = {}));
  52977. var BABYLON;
  52978. (function (BABYLON) {
  52979. var LensFlareSystem = (function () {
  52980. function LensFlareSystem(name, emitter, scene) {
  52981. this.name = name;
  52982. this.lensFlares = new Array();
  52983. this.borderLimit = 300;
  52984. this.layerMask = 0x0FFFFFFF;
  52985. this._vertexBuffers = {};
  52986. this._isEnabled = true;
  52987. this._scene = scene;
  52988. this._emitter = emitter;
  52989. this.id = name;
  52990. scene.lensFlareSystems.push(this);
  52991. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  52992. var engine = scene.getEngine();
  52993. // VBO
  52994. var vertices = [];
  52995. vertices.push(1, 1);
  52996. vertices.push(-1, 1);
  52997. vertices.push(-1, -1);
  52998. vertices.push(1, -1);
  52999. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  53000. // Indices
  53001. var indices = [];
  53002. indices.push(0);
  53003. indices.push(1);
  53004. indices.push(2);
  53005. indices.push(0);
  53006. indices.push(2);
  53007. indices.push(3);
  53008. this._indexBuffer = engine.createIndexBuffer(indices);
  53009. // Effects
  53010. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  53011. }
  53012. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  53013. get: function () {
  53014. return this._isEnabled;
  53015. },
  53016. set: function (value) {
  53017. this._isEnabled = value;
  53018. },
  53019. enumerable: true,
  53020. configurable: true
  53021. });
  53022. LensFlareSystem.prototype.getScene = function () {
  53023. return this._scene;
  53024. };
  53025. LensFlareSystem.prototype.getEmitter = function () {
  53026. return this._emitter;
  53027. };
  53028. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  53029. this._emitter = newEmitter;
  53030. };
  53031. LensFlareSystem.prototype.getEmitterPosition = function () {
  53032. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  53033. };
  53034. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  53035. var position = this.getEmitterPosition();
  53036. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  53037. this._positionX = position.x;
  53038. this._positionY = position.y;
  53039. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  53040. if (position.z > 0) {
  53041. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  53042. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  53043. return true;
  53044. }
  53045. }
  53046. return false;
  53047. };
  53048. LensFlareSystem.prototype._isVisible = function () {
  53049. if (!this._isEnabled) {
  53050. return false;
  53051. }
  53052. var emitterPosition = this.getEmitterPosition();
  53053. var direction = emitterPosition.subtract(this._scene.activeCamera.position);
  53054. var distance = direction.length();
  53055. direction.normalize();
  53056. var ray = new BABYLON.Ray(this._scene.activeCamera.position, direction);
  53057. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  53058. return !pickInfo.hit || pickInfo.distance > distance;
  53059. };
  53060. LensFlareSystem.prototype.render = function () {
  53061. if (!this._effect.isReady())
  53062. return false;
  53063. var engine = this._scene.getEngine();
  53064. var viewport = this._scene.activeCamera.viewport;
  53065. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  53066. // Position
  53067. if (!this.computeEffectivePosition(globalViewport)) {
  53068. return false;
  53069. }
  53070. // Visibility
  53071. if (!this._isVisible()) {
  53072. return false;
  53073. }
  53074. // Intensity
  53075. var awayX;
  53076. var awayY;
  53077. if (this._positionX < this.borderLimit + globalViewport.x) {
  53078. awayX = this.borderLimit + globalViewport.x - this._positionX;
  53079. }
  53080. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  53081. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  53082. }
  53083. else {
  53084. awayX = 0;
  53085. }
  53086. if (this._positionY < this.borderLimit + globalViewport.y) {
  53087. awayY = this.borderLimit + globalViewport.y - this._positionY;
  53088. }
  53089. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  53090. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  53091. }
  53092. else {
  53093. awayY = 0;
  53094. }
  53095. var away = (awayX > awayY) ? awayX : awayY;
  53096. if (away > this.borderLimit) {
  53097. away = this.borderLimit;
  53098. }
  53099. var intensity = 1.0 - (away / this.borderLimit);
  53100. if (intensity < 0) {
  53101. return false;
  53102. }
  53103. if (intensity > 1.0) {
  53104. intensity = 1.0;
  53105. }
  53106. // Position
  53107. var centerX = globalViewport.x + globalViewport.width / 2;
  53108. var centerY = globalViewport.y + globalViewport.height / 2;
  53109. var distX = centerX - this._positionX;
  53110. var distY = centerY - this._positionY;
  53111. // Effects
  53112. engine.enableEffect(this._effect);
  53113. engine.setState(false);
  53114. engine.setDepthBuffer(false);
  53115. // VBOs
  53116. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  53117. // Flares
  53118. for (var index = 0; index < this.lensFlares.length; index++) {
  53119. var flare = this.lensFlares[index];
  53120. engine.setAlphaMode(flare.alphaMode);
  53121. var x = centerX - (distX * flare.position);
  53122. var y = centerY - (distY * flare.position);
  53123. var cw = flare.size;
  53124. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  53125. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  53126. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  53127. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  53128. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  53129. // Texture
  53130. this._effect.setTexture("textureSampler", flare.texture);
  53131. // Color
  53132. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  53133. // Draw order
  53134. engine.draw(true, 0, 6);
  53135. }
  53136. engine.setDepthBuffer(true);
  53137. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  53138. return true;
  53139. };
  53140. LensFlareSystem.prototype.dispose = function () {
  53141. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  53142. if (vertexBuffer) {
  53143. vertexBuffer.dispose();
  53144. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  53145. }
  53146. if (this._indexBuffer) {
  53147. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  53148. this._indexBuffer = null;
  53149. }
  53150. while (this.lensFlares.length) {
  53151. this.lensFlares[0].dispose();
  53152. }
  53153. // Remove from scene
  53154. var index = this._scene.lensFlareSystems.indexOf(this);
  53155. this._scene.lensFlareSystems.splice(index, 1);
  53156. };
  53157. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  53158. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  53159. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  53160. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  53161. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  53162. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  53163. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  53164. var parsedFlare = parsedLensFlareSystem.flares[index];
  53165. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  53166. }
  53167. return lensFlareSystem;
  53168. };
  53169. LensFlareSystem.prototype.serialize = function () {
  53170. var serializationObject = {};
  53171. serializationObject.id = this.id;
  53172. serializationObject.name = this.name;
  53173. serializationObject.emitterId = this.getEmitter().id;
  53174. serializationObject.borderLimit = this.borderLimit;
  53175. serializationObject.flares = [];
  53176. for (var index = 0; index < this.lensFlares.length; index++) {
  53177. var flare = this.lensFlares[index];
  53178. serializationObject.flares.push({
  53179. size: flare.size,
  53180. position: flare.position,
  53181. color: flare.color.asArray(),
  53182. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  53183. });
  53184. }
  53185. return serializationObject;
  53186. };
  53187. return LensFlareSystem;
  53188. }());
  53189. BABYLON.LensFlareSystem = LensFlareSystem;
  53190. })(BABYLON || (BABYLON = {}));
  53191. var BABYLON;
  53192. (function (BABYLON) {
  53193. // We're mainly based on the logic defined into the FreeCamera code
  53194. var DeviceOrientationCamera = (function (_super) {
  53195. __extends(DeviceOrientationCamera, _super);
  53196. function DeviceOrientationCamera(name, position, scene) {
  53197. _super.call(this, name, position, scene);
  53198. this.inputs.addDeviceOrientation();
  53199. }
  53200. DeviceOrientationCamera.prototype.getTypeName = function () {
  53201. return "DeviceOrientationCamera";
  53202. };
  53203. DeviceOrientationCamera.prototype._checkInputs = function () {
  53204. _super.prototype._checkInputs.call(this);
  53205. if (this._initialQuaternion) {
  53206. this._quaternionCache.copyFrom(this.rotationQuaternion);
  53207. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  53208. }
  53209. };
  53210. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  53211. var _this = this;
  53212. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  53213. //can only work if this camera has a rotation quaternion already.
  53214. if (!this.rotationQuaternion)
  53215. return;
  53216. if (!this._initialQuaternion) {
  53217. this._initialQuaternion = new BABYLON.Quaternion();
  53218. }
  53219. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  53220. ['x', 'y', 'z'].forEach(function (axisName) {
  53221. if (!axis[axisName]) {
  53222. _this._initialQuaternion[axisName] = 0;
  53223. }
  53224. else {
  53225. _this._initialQuaternion[axisName] *= -1;
  53226. }
  53227. });
  53228. this._initialQuaternion.normalize();
  53229. };
  53230. return DeviceOrientationCamera;
  53231. }(BABYLON.FreeCamera));
  53232. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  53233. })(BABYLON || (BABYLON = {}));
  53234. var BABYLON;
  53235. (function (BABYLON) {
  53236. var VRDeviceOrientationFreeCamera = (function (_super) {
  53237. __extends(VRDeviceOrientationFreeCamera, _super);
  53238. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  53239. if (compensateDistortion === void 0) { compensateDistortion = true; }
  53240. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  53241. _super.call(this, name, position, scene);
  53242. vrCameraMetrics.compensateDistortion = compensateDistortion;
  53243. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  53244. }
  53245. VRDeviceOrientationFreeCamera.prototype.getTypeName = function () {
  53246. return "VRDeviceOrientationFreeCamera";
  53247. };
  53248. return VRDeviceOrientationFreeCamera;
  53249. }(BABYLON.DeviceOrientationCamera));
  53250. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  53251. var VRDeviceOrientationArcRotateCamera = (function (_super) {
  53252. __extends(VRDeviceOrientationArcRotateCamera, _super);
  53253. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion) {
  53254. if (compensateDistortion === void 0) { compensateDistortion = true; }
  53255. _super.call(this, name, alpha, beta, radius, target, scene);
  53256. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  53257. metrics.compensateDistortion = compensateDistortion;
  53258. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
  53259. this.inputs.addVRDeviceOrientation();
  53260. }
  53261. VRDeviceOrientationArcRotateCamera.prototype.getTypeName = function () {
  53262. return "VRDeviceOrientationArcRotateCamera";
  53263. };
  53264. return VRDeviceOrientationArcRotateCamera;
  53265. }(BABYLON.ArcRotateCamera));
  53266. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  53267. })(BABYLON || (BABYLON = {}));
  53268. var BABYLON;
  53269. (function (BABYLON) {
  53270. // We're mainly based on the logic defined into the FreeCamera code
  53271. var UniversalCamera = (function (_super) {
  53272. __extends(UniversalCamera, _super);
  53273. //-- end properties for backward compatibility for inputs
  53274. function UniversalCamera(name, position, scene) {
  53275. _super.call(this, name, position, scene);
  53276. this.inputs.addGamepad();
  53277. }
  53278. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  53279. //-- Begin properties for backward compatibility for inputs
  53280. get: function () {
  53281. var gamepad = this.inputs.attached["gamepad"];
  53282. if (gamepad)
  53283. return gamepad.gamepadAngularSensibility;
  53284. },
  53285. set: function (value) {
  53286. var gamepad = this.inputs.attached["gamepad"];
  53287. if (gamepad)
  53288. gamepad.gamepadAngularSensibility = value;
  53289. },
  53290. enumerable: true,
  53291. configurable: true
  53292. });
  53293. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  53294. get: function () {
  53295. var gamepad = this.inputs.attached["gamepad"];
  53296. if (gamepad)
  53297. return gamepad.gamepadMoveSensibility;
  53298. },
  53299. set: function (value) {
  53300. var gamepad = this.inputs.attached["gamepad"];
  53301. if (gamepad)
  53302. gamepad.gamepadMoveSensibility = value;
  53303. },
  53304. enumerable: true,
  53305. configurable: true
  53306. });
  53307. UniversalCamera.prototype.getTypeName = function () {
  53308. return "UniversalCamera";
  53309. };
  53310. return UniversalCamera;
  53311. }(BABYLON.TouchCamera));
  53312. BABYLON.UniversalCamera = UniversalCamera;
  53313. })(BABYLON || (BABYLON = {}));
  53314. var BABYLON;
  53315. (function (BABYLON) {
  53316. var Gamepads = (function () {
  53317. function Gamepads(ongamedpadconnected) {
  53318. var _this = this;
  53319. this.babylonGamepads = [];
  53320. this.oneGamepadConnected = false;
  53321. this.isMonitoring = false;
  53322. this.gamepadEventSupported = 'GamepadEvent' in window;
  53323. this.gamepadSupportAvailable = (navigator.getGamepads ||
  53324. !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  53325. this._callbackGamepadConnected = ongamedpadconnected;
  53326. if (this.gamepadSupportAvailable) {
  53327. // Checking if the gamepad connected event is supported (like in Firefox)
  53328. if (this.gamepadEventSupported) {
  53329. this._onGamepadConnectedEvent = function (evt) {
  53330. _this._onGamepadConnected(evt);
  53331. };
  53332. this._onGamepadDisonnectedEvent = function (evt) {
  53333. _this._onGamepadDisconnected(evt);
  53334. };
  53335. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  53336. window.addEventListener('gamepaddisconnected', this._onGamepadDisonnectedEvent, false);
  53337. }
  53338. else {
  53339. this._startMonitoringGamepads();
  53340. }
  53341. }
  53342. }
  53343. Gamepads.prototype.dispose = function () {
  53344. if (Gamepads.gamepadDOMInfo) {
  53345. document.body.removeChild(Gamepads.gamepadDOMInfo);
  53346. }
  53347. if (this._onGamepadConnectedEvent) {
  53348. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  53349. window.removeEventListener('gamepaddisconnected', this._onGamepadDisonnectedEvent, false);
  53350. this._onGamepadConnectedEvent = null;
  53351. this._onGamepadDisonnectedEvent = null;
  53352. }
  53353. };
  53354. Gamepads.prototype._onGamepadConnected = function (evt) {
  53355. var newGamepad = this._addNewGamepad(evt.gamepad);
  53356. if (this._callbackGamepadConnected)
  53357. this._callbackGamepadConnected(newGamepad);
  53358. this._startMonitoringGamepads();
  53359. };
  53360. Gamepads.prototype._addNewGamepad = function (gamepad) {
  53361. if (!this.oneGamepadConnected) {
  53362. this.oneGamepadConnected = true;
  53363. if (Gamepads.gamepadDOMInfo) {
  53364. document.body.removeChild(Gamepads.gamepadDOMInfo);
  53365. Gamepads.gamepadDOMInfo = null;
  53366. }
  53367. }
  53368. var newGamepad;
  53369. if (gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  53370. newGamepad = new Xbox360Pad(gamepad.id, gamepad.index, gamepad);
  53371. }
  53372. else {
  53373. newGamepad = new GenericPad(gamepad.id, gamepad.index, gamepad);
  53374. }
  53375. this.babylonGamepads.push(newGamepad);
  53376. return newGamepad;
  53377. };
  53378. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  53379. // Remove the gamepad from the list of gamepads to monitor.
  53380. for (var i in this.babylonGamepads) {
  53381. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  53382. this.babylonGamepads.splice(+i, 1);
  53383. break;
  53384. }
  53385. }
  53386. // If no gamepads are left, stop the polling loop.
  53387. if (this.babylonGamepads.length == 0) {
  53388. this._stopMonitoringGamepads();
  53389. }
  53390. };
  53391. Gamepads.prototype._startMonitoringGamepads = function () {
  53392. if (!this.isMonitoring) {
  53393. this.isMonitoring = true;
  53394. this._checkGamepadsStatus();
  53395. }
  53396. };
  53397. Gamepads.prototype._stopMonitoringGamepads = function () {
  53398. this.isMonitoring = false;
  53399. };
  53400. Gamepads.prototype._checkGamepadsStatus = function () {
  53401. var _this = this;
  53402. // updating gamepad objects
  53403. this._updateGamepadObjects();
  53404. for (var i in this.babylonGamepads) {
  53405. this.babylonGamepads[i].update();
  53406. }
  53407. if (this.isMonitoring) {
  53408. if (window.requestAnimationFrame) {
  53409. window.requestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  53410. }
  53411. else if (window.mozRequestAnimationFrame) {
  53412. window.mozRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  53413. }
  53414. else if (window.webkitRequestAnimationFrame) {
  53415. window.webkitRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  53416. }
  53417. }
  53418. };
  53419. // This function is called only on Chrome, which does not yet support
  53420. // connection/disconnection events, but requires you to monitor
  53421. // an array for changes.
  53422. Gamepads.prototype._updateGamepadObjects = function () {
  53423. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  53424. for (var i = 0; i < gamepads.length; i++) {
  53425. if (gamepads[i]) {
  53426. if (!(gamepads[i].index in this.babylonGamepads)) {
  53427. var newGamepad = this._addNewGamepad(gamepads[i]);
  53428. if (this._callbackGamepadConnected) {
  53429. this._callbackGamepadConnected(newGamepad);
  53430. }
  53431. }
  53432. else {
  53433. this.babylonGamepads[i].browserGamepad = gamepads[i];
  53434. }
  53435. }
  53436. }
  53437. };
  53438. return Gamepads;
  53439. }());
  53440. BABYLON.Gamepads = Gamepads;
  53441. var StickValues = (function () {
  53442. function StickValues(x, y) {
  53443. this.x = x;
  53444. this.y = y;
  53445. }
  53446. return StickValues;
  53447. }());
  53448. BABYLON.StickValues = StickValues;
  53449. var Gamepad = (function () {
  53450. function Gamepad(id, index, browserGamepad) {
  53451. this.id = id;
  53452. this.index = index;
  53453. this.browserGamepad = browserGamepad;
  53454. if (this.browserGamepad.axes.length >= 2) {
  53455. this._leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  53456. }
  53457. if (this.browserGamepad.axes.length >= 4) {
  53458. this._rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  53459. }
  53460. }
  53461. Gamepad.prototype.onleftstickchanged = function (callback) {
  53462. this._onleftstickchanged = callback;
  53463. };
  53464. Gamepad.prototype.onrightstickchanged = function (callback) {
  53465. this._onrightstickchanged = callback;
  53466. };
  53467. Object.defineProperty(Gamepad.prototype, "leftStick", {
  53468. get: function () {
  53469. return this._leftStick;
  53470. },
  53471. set: function (newValues) {
  53472. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  53473. this._onleftstickchanged(newValues);
  53474. }
  53475. this._leftStick = newValues;
  53476. },
  53477. enumerable: true,
  53478. configurable: true
  53479. });
  53480. Object.defineProperty(Gamepad.prototype, "rightStick", {
  53481. get: function () {
  53482. return this._rightStick;
  53483. },
  53484. set: function (newValues) {
  53485. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  53486. this._onrightstickchanged(newValues);
  53487. }
  53488. this._rightStick = newValues;
  53489. },
  53490. enumerable: true,
  53491. configurable: true
  53492. });
  53493. Gamepad.prototype.update = function () {
  53494. if (this._leftStick) {
  53495. this.leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  53496. }
  53497. if (this._rightStick) {
  53498. this.rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  53499. }
  53500. };
  53501. return Gamepad;
  53502. }());
  53503. BABYLON.Gamepad = Gamepad;
  53504. var GenericPad = (function (_super) {
  53505. __extends(GenericPad, _super);
  53506. function GenericPad(id, index, gamepad) {
  53507. _super.call(this, id, index, gamepad);
  53508. this.id = id;
  53509. this.index = index;
  53510. this.gamepad = gamepad;
  53511. this._buttons = new Array(gamepad.buttons.length);
  53512. }
  53513. GenericPad.prototype.onbuttondown = function (callback) {
  53514. this._onbuttondown = callback;
  53515. };
  53516. GenericPad.prototype.onbuttonup = function (callback) {
  53517. this._onbuttonup = callback;
  53518. };
  53519. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  53520. if (newValue !== currentValue) {
  53521. if (this._onbuttondown && newValue === 1) {
  53522. this._onbuttondown(buttonIndex);
  53523. }
  53524. if (this._onbuttonup && newValue === 0) {
  53525. this._onbuttonup(buttonIndex);
  53526. }
  53527. }
  53528. return newValue;
  53529. };
  53530. GenericPad.prototype.update = function () {
  53531. _super.prototype.update.call(this);
  53532. for (var index = 0; index < this._buttons.length; index++) {
  53533. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  53534. }
  53535. };
  53536. return GenericPad;
  53537. }(Gamepad));
  53538. BABYLON.GenericPad = GenericPad;
  53539. (function (Xbox360Button) {
  53540. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  53541. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  53542. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  53543. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  53544. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  53545. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  53546. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  53547. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  53548. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  53549. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  53550. })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  53551. var Xbox360Button = BABYLON.Xbox360Button;
  53552. (function (Xbox360Dpad) {
  53553. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  53554. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  53555. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  53556. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  53557. })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  53558. var Xbox360Dpad = BABYLON.Xbox360Dpad;
  53559. var Xbox360Pad = (function (_super) {
  53560. __extends(Xbox360Pad, _super);
  53561. function Xbox360Pad() {
  53562. _super.apply(this, arguments);
  53563. this._leftTrigger = 0;
  53564. this._rightTrigger = 0;
  53565. this._buttonA = 0;
  53566. this._buttonB = 0;
  53567. this._buttonX = 0;
  53568. this._buttonY = 0;
  53569. this._buttonBack = 0;
  53570. this._buttonStart = 0;
  53571. this._buttonLB = 0;
  53572. this._buttonRB = 0;
  53573. this._buttonLeftStick = 0;
  53574. this._buttonRightStick = 0;
  53575. this._dPadUp = 0;
  53576. this._dPadDown = 0;
  53577. this._dPadLeft = 0;
  53578. this._dPadRight = 0;
  53579. }
  53580. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  53581. this._onlefttriggerchanged = callback;
  53582. };
  53583. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  53584. this._onrighttriggerchanged = callback;
  53585. };
  53586. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  53587. get: function () {
  53588. return this._leftTrigger;
  53589. },
  53590. set: function (newValue) {
  53591. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  53592. this._onlefttriggerchanged(newValue);
  53593. }
  53594. this._leftTrigger = newValue;
  53595. },
  53596. enumerable: true,
  53597. configurable: true
  53598. });
  53599. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  53600. get: function () {
  53601. return this._rightTrigger;
  53602. },
  53603. set: function (newValue) {
  53604. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  53605. this._onrighttriggerchanged(newValue);
  53606. }
  53607. this._rightTrigger = newValue;
  53608. },
  53609. enumerable: true,
  53610. configurable: true
  53611. });
  53612. Xbox360Pad.prototype.onbuttondown = function (callback) {
  53613. this._onbuttondown = callback;
  53614. };
  53615. Xbox360Pad.prototype.onbuttonup = function (callback) {
  53616. this._onbuttonup = callback;
  53617. };
  53618. Xbox360Pad.prototype.ondpaddown = function (callback) {
  53619. this._ondpaddown = callback;
  53620. };
  53621. Xbox360Pad.prototype.ondpadup = function (callback) {
  53622. this._ondpadup = callback;
  53623. };
  53624. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  53625. if (newValue !== currentValue) {
  53626. if (this._onbuttondown && newValue === 1) {
  53627. this._onbuttondown(buttonType);
  53628. }
  53629. if (this._onbuttonup && newValue === 0) {
  53630. this._onbuttonup(buttonType);
  53631. }
  53632. }
  53633. return newValue;
  53634. };
  53635. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  53636. if (newValue !== currentValue) {
  53637. if (this._ondpaddown && newValue === 1) {
  53638. this._ondpaddown(buttonType);
  53639. }
  53640. if (this._ondpadup && newValue === 0) {
  53641. this._ondpadup(buttonType);
  53642. }
  53643. }
  53644. return newValue;
  53645. };
  53646. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  53647. get: function () {
  53648. return this._buttonA;
  53649. },
  53650. set: function (value) {
  53651. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  53652. },
  53653. enumerable: true,
  53654. configurable: true
  53655. });
  53656. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  53657. get: function () {
  53658. return this._buttonB;
  53659. },
  53660. set: function (value) {
  53661. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  53662. },
  53663. enumerable: true,
  53664. configurable: true
  53665. });
  53666. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  53667. get: function () {
  53668. return this._buttonX;
  53669. },
  53670. set: function (value) {
  53671. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  53672. },
  53673. enumerable: true,
  53674. configurable: true
  53675. });
  53676. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  53677. get: function () {
  53678. return this._buttonY;
  53679. },
  53680. set: function (value) {
  53681. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  53682. },
  53683. enumerable: true,
  53684. configurable: true
  53685. });
  53686. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  53687. get: function () {
  53688. return this._buttonStart;
  53689. },
  53690. set: function (value) {
  53691. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  53692. },
  53693. enumerable: true,
  53694. configurable: true
  53695. });
  53696. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  53697. get: function () {
  53698. return this._buttonBack;
  53699. },
  53700. set: function (value) {
  53701. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  53702. },
  53703. enumerable: true,
  53704. configurable: true
  53705. });
  53706. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  53707. get: function () {
  53708. return this._buttonLB;
  53709. },
  53710. set: function (value) {
  53711. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  53712. },
  53713. enumerable: true,
  53714. configurable: true
  53715. });
  53716. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  53717. get: function () {
  53718. return this._buttonRB;
  53719. },
  53720. set: function (value) {
  53721. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  53722. },
  53723. enumerable: true,
  53724. configurable: true
  53725. });
  53726. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  53727. get: function () {
  53728. return this._buttonLeftStick;
  53729. },
  53730. set: function (value) {
  53731. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  53732. },
  53733. enumerable: true,
  53734. configurable: true
  53735. });
  53736. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  53737. get: function () {
  53738. return this._buttonRightStick;
  53739. },
  53740. set: function (value) {
  53741. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  53742. },
  53743. enumerable: true,
  53744. configurable: true
  53745. });
  53746. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  53747. get: function () {
  53748. return this._dPadUp;
  53749. },
  53750. set: function (value) {
  53751. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  53752. },
  53753. enumerable: true,
  53754. configurable: true
  53755. });
  53756. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  53757. get: function () {
  53758. return this._dPadDown;
  53759. },
  53760. set: function (value) {
  53761. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  53762. },
  53763. enumerable: true,
  53764. configurable: true
  53765. });
  53766. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  53767. get: function () {
  53768. return this._dPadLeft;
  53769. },
  53770. set: function (value) {
  53771. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  53772. },
  53773. enumerable: true,
  53774. configurable: true
  53775. });
  53776. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  53777. get: function () {
  53778. return this._dPadRight;
  53779. },
  53780. set: function (value) {
  53781. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  53782. },
  53783. enumerable: true,
  53784. configurable: true
  53785. });
  53786. Xbox360Pad.prototype.update = function () {
  53787. _super.prototype.update.call(this);
  53788. this.buttonA = this.browserGamepad.buttons[0].value;
  53789. this.buttonB = this.browserGamepad.buttons[1].value;
  53790. this.buttonX = this.browserGamepad.buttons[2].value;
  53791. this.buttonY = this.browserGamepad.buttons[3].value;
  53792. this.buttonLB = this.browserGamepad.buttons[4].value;
  53793. this.buttonRB = this.browserGamepad.buttons[5].value;
  53794. this.leftTrigger = this.browserGamepad.buttons[6].value;
  53795. this.rightTrigger = this.browserGamepad.buttons[7].value;
  53796. this.buttonBack = this.browserGamepad.buttons[8].value;
  53797. this.buttonStart = this.browserGamepad.buttons[9].value;
  53798. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  53799. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  53800. this.dPadUp = this.browserGamepad.buttons[12].value;
  53801. this.dPadDown = this.browserGamepad.buttons[13].value;
  53802. this.dPadLeft = this.browserGamepad.buttons[14].value;
  53803. this.dPadRight = this.browserGamepad.buttons[15].value;
  53804. };
  53805. return Xbox360Pad;
  53806. }(Gamepad));
  53807. BABYLON.Xbox360Pad = Xbox360Pad;
  53808. })(BABYLON || (BABYLON = {}));
  53809. var BABYLON;
  53810. (function (BABYLON) {
  53811. // We're mainly based on the logic defined into the FreeCamera code
  53812. var GamepadCamera = (function (_super) {
  53813. __extends(GamepadCamera, _super);
  53814. //-- end properties for backward compatibility for inputs
  53815. function GamepadCamera(name, position, scene) {
  53816. BABYLON.Tools.Warn("Deprecated. Please use Universal Camera instead.");
  53817. _super.call(this, name, position, scene);
  53818. }
  53819. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  53820. //-- Begin properties for backward compatibility for inputs
  53821. get: function () {
  53822. var gamepad = this.inputs.attached["gamepad"];
  53823. if (gamepad)
  53824. return gamepad.gamepadAngularSensibility;
  53825. },
  53826. set: function (value) {
  53827. var gamepad = this.inputs.attached["gamepad"];
  53828. if (gamepad)
  53829. gamepad.gamepadAngularSensibility = value;
  53830. },
  53831. enumerable: true,
  53832. configurable: true
  53833. });
  53834. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  53835. get: function () {
  53836. var gamepad = this.inputs.attached["gamepad"];
  53837. if (gamepad)
  53838. return gamepad.gamepadMoveSensibility;
  53839. },
  53840. set: function (value) {
  53841. var gamepad = this.inputs.attached["gamepad"];
  53842. if (gamepad)
  53843. gamepad.gamepadMoveSensibility = value;
  53844. },
  53845. enumerable: true,
  53846. configurable: true
  53847. });
  53848. GamepadCamera.prototype.getTypeName = function () {
  53849. return "GamepadCamera";
  53850. };
  53851. return GamepadCamera;
  53852. }(BABYLON.UniversalCamera));
  53853. BABYLON.GamepadCamera = GamepadCamera;
  53854. })(BABYLON || (BABYLON = {}));
  53855. var BABYLON;
  53856. (function (BABYLON) {
  53857. var Analyser = (function () {
  53858. function Analyser(scene) {
  53859. this.SMOOTHING = 0.75;
  53860. this.FFT_SIZE = 512;
  53861. this.BARGRAPHAMPLITUDE = 256;
  53862. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  53863. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  53864. this._scene = scene;
  53865. this._audioEngine = BABYLON.Engine.audioEngine;
  53866. if (this._audioEngine.canUseWebAudio) {
  53867. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  53868. this._webAudioAnalyser.minDecibels = -140;
  53869. this._webAudioAnalyser.maxDecibels = 0;
  53870. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  53871. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  53872. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  53873. }
  53874. }
  53875. Analyser.prototype.getFrequencyBinCount = function () {
  53876. if (this._audioEngine.canUseWebAudio) {
  53877. return this._webAudioAnalyser.frequencyBinCount;
  53878. }
  53879. else {
  53880. return 0;
  53881. }
  53882. };
  53883. Analyser.prototype.getByteFrequencyData = function () {
  53884. if (this._audioEngine.canUseWebAudio) {
  53885. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  53886. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  53887. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  53888. }
  53889. return this._byteFreqs;
  53890. };
  53891. Analyser.prototype.getByteTimeDomainData = function () {
  53892. if (this._audioEngine.canUseWebAudio) {
  53893. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  53894. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  53895. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  53896. }
  53897. return this._byteTime;
  53898. };
  53899. Analyser.prototype.getFloatFrequencyData = function () {
  53900. if (this._audioEngine.canUseWebAudio) {
  53901. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  53902. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  53903. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  53904. }
  53905. return this._floatFreqs;
  53906. };
  53907. Analyser.prototype.drawDebugCanvas = function () {
  53908. var _this = this;
  53909. if (this._audioEngine.canUseWebAudio) {
  53910. if (!this._debugCanvas) {
  53911. this._debugCanvas = document.createElement("canvas");
  53912. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  53913. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  53914. this._debugCanvas.style.position = "absolute";
  53915. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  53916. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  53917. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  53918. document.body.appendChild(this._debugCanvas);
  53919. this._registerFunc = function () {
  53920. _this.drawDebugCanvas();
  53921. };
  53922. this._scene.registerBeforeRender(this._registerFunc);
  53923. }
  53924. if (this._registerFunc) {
  53925. var workingArray = this.getByteFrequencyData();
  53926. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  53927. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  53928. // Draw the frequency domain chart.
  53929. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  53930. var value = workingArray[i];
  53931. var percent = value / this.BARGRAPHAMPLITUDE;
  53932. var height = this.DEBUGCANVASSIZE.height * percent;
  53933. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  53934. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  53935. var hue = i / this.getFrequencyBinCount() * 360;
  53936. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  53937. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  53938. }
  53939. }
  53940. }
  53941. };
  53942. Analyser.prototype.stopDebugCanvas = function () {
  53943. if (this._debugCanvas) {
  53944. this._scene.unregisterBeforeRender(this._registerFunc);
  53945. this._registerFunc = null;
  53946. document.body.removeChild(this._debugCanvas);
  53947. this._debugCanvas = null;
  53948. this._debugCanvasContext = null;
  53949. }
  53950. };
  53951. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  53952. if (this._audioEngine.canUseWebAudio) {
  53953. inputAudioNode.connect(this._webAudioAnalyser);
  53954. this._webAudioAnalyser.connect(outputAudioNode);
  53955. }
  53956. };
  53957. Analyser.prototype.dispose = function () {
  53958. if (this._audioEngine.canUseWebAudio) {
  53959. this._webAudioAnalyser.disconnect();
  53960. }
  53961. };
  53962. return Analyser;
  53963. }());
  53964. BABYLON.Analyser = Analyser;
  53965. })(BABYLON || (BABYLON = {}));
  53966. var BABYLON;
  53967. (function (BABYLON) {
  53968. var DepthRenderer = (function () {
  53969. function DepthRenderer(scene, type) {
  53970. var _this = this;
  53971. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  53972. this._viewMatrix = BABYLON.Matrix.Zero();
  53973. this._projectionMatrix = BABYLON.Matrix.Zero();
  53974. this._transformMatrix = BABYLON.Matrix.Zero();
  53975. this._worldViewProjection = BABYLON.Matrix.Zero();
  53976. this._scene = scene;
  53977. var engine = scene.getEngine();
  53978. // Render target
  53979. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  53980. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53981. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53982. this._depthMap.refreshRate = 1;
  53983. this._depthMap.renderParticles = false;
  53984. this._depthMap.renderList = null;
  53985. // set default depth value to 1.0 (far away)
  53986. this._depthMap.onClearObservable.add(function (engine) {
  53987. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  53988. });
  53989. // Custom render function
  53990. var renderSubMesh = function (subMesh) {
  53991. var mesh = subMesh.getRenderingMesh();
  53992. var scene = _this._scene;
  53993. var engine = scene.getEngine();
  53994. // Culling
  53995. engine.setState(subMesh.getMaterial().backFaceCulling);
  53996. // Managing instances
  53997. var batch = mesh._getInstancesRenderList(subMesh._id);
  53998. if (batch.mustReturn) {
  53999. return;
  54000. }
  54001. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  54002. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  54003. engine.enableEffect(_this._effect);
  54004. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  54005. var material = subMesh.getMaterial();
  54006. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  54007. _this._effect.setFloat("far", scene.activeCamera.maxZ);
  54008. // Alpha test
  54009. if (material && material.needAlphaTesting()) {
  54010. var alphaTexture = material.getAlphaTestTexture();
  54011. _this._effect.setTexture("diffuseSampler", alphaTexture);
  54012. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  54013. }
  54014. // Bones
  54015. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  54016. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  54017. }
  54018. // Draw
  54019. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  54020. }
  54021. };
  54022. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  54023. var index;
  54024. for (index = 0; index < opaqueSubMeshes.length; index++) {
  54025. renderSubMesh(opaqueSubMeshes.data[index]);
  54026. }
  54027. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  54028. renderSubMesh(alphaTestSubMeshes.data[index]);
  54029. }
  54030. };
  54031. }
  54032. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  54033. var material = subMesh.getMaterial();
  54034. if (material.disableDepthWrite) {
  54035. return false;
  54036. }
  54037. var defines = [];
  54038. var attribs = [BABYLON.VertexBuffer.PositionKind];
  54039. var mesh = subMesh.getMesh();
  54040. var scene = mesh.getScene();
  54041. // Alpha test
  54042. if (material && material.needAlphaTesting()) {
  54043. defines.push("#define ALPHATEST");
  54044. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  54045. attribs.push(BABYLON.VertexBuffer.UVKind);
  54046. defines.push("#define UV1");
  54047. }
  54048. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  54049. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  54050. defines.push("#define UV2");
  54051. }
  54052. }
  54053. // Bones
  54054. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  54055. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  54056. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  54057. if (mesh.numBoneInfluencers > 4) {
  54058. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  54059. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  54060. }
  54061. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  54062. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  54063. }
  54064. else {
  54065. defines.push("#define NUM_BONE_INFLUENCERS 0");
  54066. }
  54067. // Instances
  54068. if (useInstances) {
  54069. defines.push("#define INSTANCES");
  54070. attribs.push("world0");
  54071. attribs.push("world1");
  54072. attribs.push("world2");
  54073. attribs.push("world3");
  54074. }
  54075. // Get correct effect
  54076. var join = defines.join("\n");
  54077. if (this._cachedDefines !== join) {
  54078. this._cachedDefines = join;
  54079. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler"], join);
  54080. }
  54081. return this._effect.isReady();
  54082. };
  54083. DepthRenderer.prototype.getDepthMap = function () {
  54084. return this._depthMap;
  54085. };
  54086. // Methods
  54087. DepthRenderer.prototype.dispose = function () {
  54088. this._depthMap.dispose();
  54089. };
  54090. return DepthRenderer;
  54091. }());
  54092. BABYLON.DepthRenderer = DepthRenderer;
  54093. })(BABYLON || (BABYLON = {}));
  54094. var BABYLON;
  54095. (function (BABYLON) {
  54096. var SSAORenderingPipeline = (function (_super) {
  54097. __extends(SSAORenderingPipeline, _super);
  54098. /**
  54099. * @constructor
  54100. * @param {string} name - The rendering pipeline name
  54101. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  54102. * @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 }
  54103. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  54104. */
  54105. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  54106. var _this = this;
  54107. _super.call(this, scene.getEngine(), name);
  54108. // Members
  54109. /**
  54110. * The PassPostProcess id in the pipeline that contains the original scene color
  54111. * @type {string}
  54112. */
  54113. this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  54114. /**
  54115. * The SSAO PostProcess id in the pipeline
  54116. * @type {string}
  54117. */
  54118. this.SSAORenderEffect = "SSAORenderEffect";
  54119. /**
  54120. * The horizontal blur PostProcess id in the pipeline
  54121. * @type {string}
  54122. */
  54123. this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  54124. /**
  54125. * The vertical blur PostProcess id in the pipeline
  54126. * @type {string}
  54127. */
  54128. this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  54129. /**
  54130. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  54131. * @type {string}
  54132. */
  54133. this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  54134. /**
  54135. * The output strength of the SSAO post-process. Default value is 1.0.
  54136. * @type {number}
  54137. */
  54138. this.totalStrength = 1.0;
  54139. /**
  54140. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  54141. * @type {number}
  54142. */
  54143. this.radius = 0.0001;
  54144. /**
  54145. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  54146. * Must not be equal to fallOff and superior to fallOff.
  54147. * Default value is 0.975
  54148. * @type {number}
  54149. */
  54150. this.area = 0.0075;
  54151. /**
  54152. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  54153. * Must not be equal to area and inferior to area.
  54154. * Default value is 0.0
  54155. * @type {number}
  54156. */
  54157. this.fallOff = 0.000001;
  54158. /**
  54159. * The base color of the SSAO post-process
  54160. * The final result is "base + ssao" between [0, 1]
  54161. * @type {number}
  54162. */
  54163. this.base = 0.5;
  54164. this._firstUpdate = true;
  54165. this._scene = scene;
  54166. // Set up assets
  54167. this._createRandomTexture();
  54168. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  54169. var ssaoRatio = ratio.ssaoRatio || ratio;
  54170. var combineRatio = ratio.combineRatio || ratio;
  54171. this._ratio = {
  54172. ssaoRatio: ssaoRatio,
  54173. combineRatio: combineRatio
  54174. };
  54175. this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  54176. this._createSSAOPostProcess(ssaoRatio);
  54177. this._createBlurPostProcess(ssaoRatio);
  54178. this._createSSAOCombinePostProcess(combineRatio);
  54179. // Set up pipeline
  54180. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  54181. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  54182. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  54183. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  54184. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  54185. // Finish
  54186. scene.postProcessRenderPipelineManager.addPipeline(this);
  54187. if (cameras)
  54188. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  54189. }
  54190. // Public Methods
  54191. /**
  54192. * Returns the horizontal blur PostProcess
  54193. * @return {BABYLON.BlurPostProcess} The horizontal blur post-process
  54194. */
  54195. SSAORenderingPipeline.prototype.getBlurHPostProcess = function () {
  54196. BABYLON.Tools.Error("SSAORenderinPipeline.getBlurHPostProcess() is deprecated, no more blur post-process exists");
  54197. return null;
  54198. };
  54199. /**
  54200. * Returns the vertical blur PostProcess
  54201. * @return {BABYLON.BlurPostProcess} The vertical blur post-process
  54202. */
  54203. SSAORenderingPipeline.prototype.getBlurVPostProcess = function () {
  54204. BABYLON.Tools.Error("SSAORenderinPipeline.getBlurVPostProcess() is deprecated, no more blur post-process exists");
  54205. return null;
  54206. };
  54207. /**
  54208. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  54209. */
  54210. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  54211. if (disableDepthRender === void 0) { disableDepthRender = false; }
  54212. for (var i = 0; i < this._scene.cameras.length; i++) {
  54213. var camera = this._scene.cameras[i];
  54214. this._originalColorPostProcess.dispose(camera);
  54215. this._ssaoPostProcess.dispose(camera);
  54216. this._blurHPostProcess.dispose(camera);
  54217. this._blurVPostProcess.dispose(camera);
  54218. this._ssaoCombinePostProcess.dispose(camera);
  54219. }
  54220. this._randomTexture.dispose();
  54221. if (disableDepthRender)
  54222. this._scene.disableDepthRenderer();
  54223. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  54224. };
  54225. // Private Methods
  54226. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  54227. var _this = this;
  54228. /*
  54229. var samplerOffsets = [
  54230. -8.0, -6.0, -4.0, -2.0,
  54231. 0.0,
  54232. 2.0, 4.0, 6.0, 8.0
  54233. ];
  54234. */
  54235. var samples = 16;
  54236. var samplerOffsets = [];
  54237. for (var i = -8; i < 8; i++) {
  54238. samplerOffsets.push(i * 2);
  54239. }
  54240. 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");
  54241. this._blurHPostProcess.onApply = function (effect) {
  54242. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width);
  54243. effect.setTexture("depthSampler", _this._depthTexture);
  54244. if (_this._firstUpdate) {
  54245. effect.setArray("samplerOffsets", samplerOffsets);
  54246. }
  54247. };
  54248. 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");
  54249. this._blurVPostProcess.onApply = function (effect) {
  54250. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height);
  54251. effect.setTexture("depthSampler", _this._depthTexture);
  54252. if (_this._firstUpdate) {
  54253. effect.setArray("samplerOffsets", samplerOffsets);
  54254. _this._firstUpdate = false;
  54255. }
  54256. };
  54257. };
  54258. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  54259. var _this = this;
  54260. var numSamples = 16;
  54261. var sampleSphere = [
  54262. 0.5381, 0.1856, -0.4319,
  54263. 0.1379, 0.2486, 0.4430,
  54264. 0.3371, 0.5679, -0.0057,
  54265. -0.6999, -0.0451, -0.0019,
  54266. 0.0689, -0.1598, -0.8547,
  54267. 0.0560, 0.0069, -0.1843,
  54268. -0.0146, 0.1402, 0.0762,
  54269. 0.0100, -0.1924, -0.0344,
  54270. -0.3577, -0.5301, -0.4358,
  54271. -0.3169, 0.1063, 0.0158,
  54272. 0.0103, -0.5869, 0.0046,
  54273. -0.0897, -0.4940, 0.3287,
  54274. 0.7119, -0.0154, -0.0918,
  54275. -0.0533, 0.0596, -0.5411,
  54276. 0.0352, -0.0631, 0.5460,
  54277. -0.4776, 0.2847, -0.0271
  54278. ];
  54279. var samplesFactor = 1.0 / numSamples;
  54280. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  54281. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  54282. "area", "fallOff", "base", "range", "viewport"
  54283. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  54284. var viewport = new BABYLON.Vector2(0, 0);
  54285. this._ssaoPostProcess.onApply = function (effect) {
  54286. if (_this._firstUpdate) {
  54287. effect.setArray3("sampleSphere", sampleSphere);
  54288. effect.setFloat("samplesFactor", samplesFactor);
  54289. effect.setFloat("randTextureTiles", 4.0);
  54290. }
  54291. effect.setFloat("totalStrength", _this.totalStrength);
  54292. effect.setFloat("radius", _this.radius);
  54293. effect.setFloat("area", _this.area);
  54294. effect.setFloat("fallOff", _this.fallOff);
  54295. effect.setFloat("base", _this.base);
  54296. effect.setTexture("textureSampler", _this._depthTexture);
  54297. effect.setTexture("randomSampler", _this._randomTexture);
  54298. };
  54299. };
  54300. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  54301. var _this = this;
  54302. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  54303. this._ssaoCombinePostProcess.onApply = function (effect) {
  54304. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  54305. };
  54306. };
  54307. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  54308. var size = 512;
  54309. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  54310. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  54311. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  54312. var context = this._randomTexture.getContext();
  54313. var rand = function (min, max) {
  54314. return Math.random() * (max - min) + min;
  54315. };
  54316. var randVector = BABYLON.Vector3.Zero();
  54317. for (var x = 0; x < size; x++) {
  54318. for (var y = 0; y < size; y++) {
  54319. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  54320. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  54321. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  54322. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  54323. context.fillRect(x, y, 1, 1);
  54324. }
  54325. }
  54326. this._randomTexture.update(false);
  54327. };
  54328. __decorate([
  54329. BABYLON.serialize()
  54330. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  54331. __decorate([
  54332. BABYLON.serialize()
  54333. ], SSAORenderingPipeline.prototype, "radius", void 0);
  54334. __decorate([
  54335. BABYLON.serialize()
  54336. ], SSAORenderingPipeline.prototype, "area", void 0);
  54337. __decorate([
  54338. BABYLON.serialize()
  54339. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  54340. __decorate([
  54341. BABYLON.serialize()
  54342. ], SSAORenderingPipeline.prototype, "base", void 0);
  54343. __decorate([
  54344. BABYLON.serialize()
  54345. ], SSAORenderingPipeline.prototype, "_ratio", void 0);
  54346. return SSAORenderingPipeline;
  54347. }(BABYLON.PostProcessRenderPipeline));
  54348. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  54349. })(BABYLON || (BABYLON = {}));
  54350. var BABYLON;
  54351. (function (BABYLON) {
  54352. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  54353. var VolumetricLightScatteringPostProcess = (function (_super) {
  54354. __extends(VolumetricLightScatteringPostProcess, _super);
  54355. /**
  54356. * @constructor
  54357. * @param {string} name - The post-process name
  54358. * @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)
  54359. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  54360. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  54361. * @param {number} samples - The post-process quality, default 100
  54362. * @param {number} samplingMode - The post-process filtering mode
  54363. * @param {BABYLON.Engine} engine - The babylon engine
  54364. * @param {boolean} reusable - If the post-process is reusable
  54365. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  54366. */
  54367. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  54368. var _this = this;
  54369. if (samples === void 0) { samples = 100; }
  54370. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  54371. _super.call(this, name, "volumetricLightScattering", ["decay", "exposure", "weight", "meshPositionOnScreen", "density"], ["lightScatteringSampler"], ratio.postProcessRatio || ratio, camera, samplingMode, engine, reusable, "#define NUM_SAMPLES " + samples);
  54372. this._screenCoordinates = BABYLON.Vector2.Zero();
  54373. /**
  54374. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  54375. * @type {Vector3}
  54376. */
  54377. this.customMeshPosition = BABYLON.Vector3.Zero();
  54378. /**
  54379. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  54380. * @type {boolean}
  54381. */
  54382. this.useCustomMeshPosition = false;
  54383. /**
  54384. * If the post-process should inverse the light scattering direction
  54385. * @type {boolean}
  54386. */
  54387. this.invert = true;
  54388. /**
  54389. * Array containing the excluded meshes not rendered in the internal pass
  54390. */
  54391. this.excludedMeshes = new Array();
  54392. /**
  54393. * Controls the overall intensity of the post-process
  54394. * @type {number}
  54395. */
  54396. this.exposure = 0.3;
  54397. /**
  54398. * Dissipates each sample's contribution in range [0, 1]
  54399. * @type {number}
  54400. */
  54401. this.decay = 0.96815;
  54402. /**
  54403. * Controls the overall intensity of each sample
  54404. * @type {number}
  54405. */
  54406. this.weight = 0.58767;
  54407. /**
  54408. * Controls the density of each sample
  54409. * @type {number}
  54410. */
  54411. this.density = 0.926;
  54412. scene = (camera === null) ? scene : camera.getScene(); // parameter "scene" can be null.
  54413. var engine = scene.getEngine();
  54414. this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  54415. // Configure mesh
  54416. this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  54417. // Configure
  54418. this._createPass(scene, ratio.passRatio || ratio);
  54419. this.onActivate = function (camera) {
  54420. if (!_this.isSupported) {
  54421. _this.dispose(camera);
  54422. }
  54423. _this.onActivate = null;
  54424. };
  54425. this.onApplyObservable.add(function (effect) {
  54426. _this._updateMeshScreenCoordinates(scene);
  54427. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  54428. effect.setFloat("exposure", _this.exposure);
  54429. effect.setFloat("decay", _this.decay);
  54430. effect.setFloat("weight", _this.weight);
  54431. effect.setFloat("density", _this.density);
  54432. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  54433. });
  54434. }
  54435. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  54436. get: function () {
  54437. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  54438. return false;
  54439. },
  54440. set: function (useDiffuseColor) {
  54441. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  54442. },
  54443. enumerable: true,
  54444. configurable: true
  54445. });
  54446. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  54447. var mesh = subMesh.getMesh();
  54448. // Render this.mesh as default
  54449. if (mesh === this.mesh) {
  54450. return mesh.material.isReady(mesh);
  54451. }
  54452. var defines = [];
  54453. var attribs = [BABYLON.VertexBuffer.PositionKind];
  54454. var material = subMesh.getMaterial();
  54455. var needUV = false;
  54456. // Alpha test
  54457. if (material) {
  54458. if (material.needAlphaTesting()) {
  54459. defines.push("#define ALPHATEST");
  54460. }
  54461. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  54462. attribs.push(BABYLON.VertexBuffer.UVKind);
  54463. defines.push("#define UV1");
  54464. }
  54465. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  54466. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  54467. defines.push("#define UV2");
  54468. }
  54469. }
  54470. // Bones
  54471. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  54472. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  54473. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  54474. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  54475. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  54476. }
  54477. else {
  54478. defines.push("#define NUM_BONE_INFLUENCERS 0");
  54479. }
  54480. // Instances
  54481. if (useInstances) {
  54482. defines.push("#define INSTANCES");
  54483. attribs.push("world0");
  54484. attribs.push("world1");
  54485. attribs.push("world2");
  54486. attribs.push("world3");
  54487. }
  54488. // Get correct effect
  54489. var join = defines.join("\n");
  54490. if (this._cachedDefines !== join) {
  54491. this._cachedDefines = join;
  54492. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  54493. }
  54494. return this._volumetricLightScatteringPass.isReady();
  54495. };
  54496. /**
  54497. * Sets the new light position for light scattering effect
  54498. * @param {BABYLON.Vector3} The new custom light position
  54499. */
  54500. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  54501. this.customMeshPosition = position;
  54502. };
  54503. /**
  54504. * Returns the light position for light scattering effect
  54505. * @return {BABYLON.Vector3} The custom light position
  54506. */
  54507. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  54508. return this.customMeshPosition;
  54509. };
  54510. /**
  54511. * Disposes the internal assets and detaches the post-process from the camera
  54512. */
  54513. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  54514. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  54515. if (rttIndex !== -1) {
  54516. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  54517. }
  54518. this._volumetricLightScatteringRTT.dispose();
  54519. _super.prototype.dispose.call(this, camera);
  54520. };
  54521. /**
  54522. * Returns the render target texture used by the post-process
  54523. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  54524. */
  54525. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  54526. return this._volumetricLightScatteringRTT;
  54527. };
  54528. // Private methods
  54529. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  54530. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  54531. return true;
  54532. }
  54533. return false;
  54534. };
  54535. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  54536. var _this = this;
  54537. var engine = scene.getEngine();
  54538. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  54539. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54540. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54541. this._volumetricLightScatteringRTT.renderList = null;
  54542. this._volumetricLightScatteringRTT.renderParticles = false;
  54543. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  54544. // Custom render function for submeshes
  54545. var renderSubMesh = function (subMesh) {
  54546. var mesh = subMesh.getRenderingMesh();
  54547. if (_this._meshExcluded(mesh)) {
  54548. return;
  54549. }
  54550. var scene = mesh.getScene();
  54551. var engine = scene.getEngine();
  54552. // Culling
  54553. engine.setState(subMesh.getMaterial().backFaceCulling);
  54554. // Managing instances
  54555. var batch = mesh._getInstancesRenderList(subMesh._id);
  54556. if (batch.mustReturn) {
  54557. return;
  54558. }
  54559. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  54560. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  54561. var effect = _this._volumetricLightScatteringPass;
  54562. if (mesh === _this.mesh) {
  54563. effect = subMesh.getMaterial().getEffect();
  54564. }
  54565. engine.enableEffect(effect);
  54566. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  54567. if (mesh === _this.mesh) {
  54568. subMesh.getMaterial().bind(mesh.getWorldMatrix(), mesh);
  54569. }
  54570. else {
  54571. var material = subMesh.getMaterial();
  54572. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  54573. // Alpha test
  54574. if (material && material.needAlphaTesting()) {
  54575. var alphaTexture = material.getAlphaTestTexture();
  54576. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  54577. if (alphaTexture) {
  54578. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  54579. }
  54580. }
  54581. // Bones
  54582. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  54583. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  54584. }
  54585. }
  54586. // Draw
  54587. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  54588. }
  54589. };
  54590. // Render target texture callbacks
  54591. var savedSceneClearColor;
  54592. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  54593. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  54594. savedSceneClearColor = scene.clearColor;
  54595. scene.clearColor = sceneClearColor;
  54596. });
  54597. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  54598. scene.clearColor = savedSceneClearColor;
  54599. });
  54600. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  54601. var engine = scene.getEngine();
  54602. var index;
  54603. for (index = 0; index < opaqueSubMeshes.length; index++) {
  54604. renderSubMesh(opaqueSubMeshes.data[index]);
  54605. }
  54606. engine.setAlphaTesting(true);
  54607. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  54608. renderSubMesh(alphaTestSubMeshes.data[index]);
  54609. }
  54610. engine.setAlphaTesting(false);
  54611. if (transparentSubMeshes.length) {
  54612. // Sort sub meshes
  54613. for (index = 0; index < transparentSubMeshes.length; index++) {
  54614. var submesh = transparentSubMeshes.data[index];
  54615. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  54616. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  54617. }
  54618. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  54619. sortedArray.sort(function (a, b) {
  54620. // Alpha index first
  54621. if (a._alphaIndex > b._alphaIndex) {
  54622. return 1;
  54623. }
  54624. if (a._alphaIndex < b._alphaIndex) {
  54625. return -1;
  54626. }
  54627. // Then distance to camera
  54628. if (a._distanceToCamera < b._distanceToCamera) {
  54629. return 1;
  54630. }
  54631. if (a._distanceToCamera > b._distanceToCamera) {
  54632. return -1;
  54633. }
  54634. return 0;
  54635. });
  54636. // Render sub meshes
  54637. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  54638. for (index = 0; index < sortedArray.length; index++) {
  54639. renderSubMesh(sortedArray[index]);
  54640. }
  54641. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  54642. }
  54643. };
  54644. };
  54645. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  54646. var transform = scene.getTransformMatrix();
  54647. var meshPosition;
  54648. if (this.useCustomMeshPosition) {
  54649. meshPosition = this.customMeshPosition;
  54650. }
  54651. else if (this.attachedNode) {
  54652. meshPosition = this.attachedNode.position;
  54653. }
  54654. else {
  54655. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  54656. }
  54657. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  54658. this._screenCoordinates.x = pos.x / this._viewPort.width;
  54659. this._screenCoordinates.y = pos.y / this._viewPort.height;
  54660. if (this.invert)
  54661. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  54662. };
  54663. // Static methods
  54664. /**
  54665. * Creates a default mesh for the Volumeric Light Scattering post-process
  54666. * @param {string} The mesh name
  54667. * @param {BABYLON.Scene} The scene where to create the mesh
  54668. * @return {BABYLON.Mesh} the default mesh
  54669. */
  54670. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  54671. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  54672. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  54673. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  54674. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  54675. mesh.material = material;
  54676. return mesh;
  54677. };
  54678. __decorate([
  54679. BABYLON.serializeAsVector3()
  54680. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  54681. __decorate([
  54682. BABYLON.serialize()
  54683. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  54684. __decorate([
  54685. BABYLON.serialize()
  54686. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  54687. __decorate([
  54688. BABYLON.serializeAsMeshReference()
  54689. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  54690. __decorate([
  54691. BABYLON.serialize()
  54692. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  54693. __decorate([
  54694. BABYLON.serialize()
  54695. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  54696. __decorate([
  54697. BABYLON.serialize()
  54698. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  54699. __decorate([
  54700. BABYLON.serialize()
  54701. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  54702. __decorate([
  54703. BABYLON.serialize()
  54704. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  54705. return VolumetricLightScatteringPostProcess;
  54706. }(BABYLON.PostProcess));
  54707. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  54708. })(BABYLON || (BABYLON = {}));
  54709. // BABYLON.JS Chromatic Aberration GLSL Shader
  54710. // Author: Olivier Guyot
  54711. // Separates very slightly R, G and B colors on the edges of the screen
  54712. // Inspired by Francois Tarlier & Martins Upitis
  54713. var BABYLON;
  54714. (function (BABYLON) {
  54715. var LensRenderingPipeline = (function (_super) {
  54716. __extends(LensRenderingPipeline, _super);
  54717. /**
  54718. * @constructor
  54719. *
  54720. * Effect parameters are as follow:
  54721. * {
  54722. * chromatic_aberration: number; // from 0 to x (1 for realism)
  54723. * edge_blur: number; // from 0 to x (1 for realism)
  54724. * distortion: number; // from 0 to x (1 for realism)
  54725. * grain_amount: number; // from 0 to 1
  54726. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  54727. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  54728. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  54729. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  54730. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  54731. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  54732. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  54733. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  54734. * }
  54735. * Note: if an effect parameter is unset, effect is disabled
  54736. *
  54737. * @param {string} name - The rendering pipeline name
  54738. * @param {object} parameters - An object containing all parameters (see above)
  54739. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  54740. * @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)
  54741. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  54742. */
  54743. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  54744. var _this = this;
  54745. if (ratio === void 0) { ratio = 1.0; }
  54746. _super.call(this, scene.getEngine(), name);
  54747. // Lens effects can be of the following:
  54748. // - chromatic aberration (slight shift of RGB colors)
  54749. // - blur on the edge of the lens
  54750. // - lens distortion
  54751. // - depth-of-field blur & highlights enhancing
  54752. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  54753. // - grain effect (noise or custom texture)
  54754. // Two additional texture samplers are needed:
  54755. // - depth map (for depth-of-field)
  54756. // - grain texture
  54757. /**
  54758. * The chromatic aberration PostProcess id in the pipeline
  54759. * @type {string}
  54760. */
  54761. this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  54762. /**
  54763. * The highlights enhancing PostProcess id in the pipeline
  54764. * @type {string}
  54765. */
  54766. this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  54767. /**
  54768. * The depth-of-field PostProcess id in the pipeline
  54769. * @type {string}
  54770. */
  54771. this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  54772. this._scene = scene;
  54773. // Fetch texture samplers
  54774. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  54775. if (parameters.grain_texture) {
  54776. this._grainTexture = parameters.grain_texture;
  54777. }
  54778. else {
  54779. this._createGrainTexture();
  54780. }
  54781. // save parameters
  54782. this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  54783. this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  54784. this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  54785. this._distortion = parameters.distortion ? parameters.distortion : 0;
  54786. this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  54787. this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  54788. this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  54789. this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  54790. this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  54791. this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  54792. this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  54793. // Create effects
  54794. this._createChromaticAberrationPostProcess(ratio);
  54795. this._createHighlightsPostProcess(ratio);
  54796. this._createDepthOfFieldPostProcess(ratio / 4);
  54797. // Set up pipeline
  54798. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  54799. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  54800. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  54801. if (this._highlightsGain === -1) {
  54802. this._disableEffect(this.HighlightsEnhancingEffect, null);
  54803. }
  54804. // Finish
  54805. scene.postProcessRenderPipelineManager.addPipeline(this);
  54806. if (cameras) {
  54807. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  54808. }
  54809. }
  54810. // public methods (self explanatory)
  54811. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  54812. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  54813. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  54814. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  54815. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  54816. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  54817. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  54818. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  54819. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  54820. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  54821. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  54822. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  54823. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  54824. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  54825. };
  54826. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  54827. this._highlightsPostProcess.updateEffect();
  54828. };
  54829. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  54830. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  54831. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  54832. this._highlightsGain = amount;
  54833. };
  54834. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  54835. if (this._highlightsGain === -1) {
  54836. this._highlightsGain = 1.0;
  54837. }
  54838. this._highlightsThreshold = amount;
  54839. };
  54840. LensRenderingPipeline.prototype.disableHighlights = function () {
  54841. this._highlightsGain = -1;
  54842. };
  54843. /**
  54844. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  54845. */
  54846. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  54847. if (disableDepthRender === void 0) { disableDepthRender = false; }
  54848. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  54849. this._chromaticAberrationPostProcess = undefined;
  54850. this._highlightsPostProcess = undefined;
  54851. this._depthOfFieldPostProcess = undefined;
  54852. this._grainTexture.dispose();
  54853. if (disableDepthRender)
  54854. this._scene.disableDepthRenderer();
  54855. };
  54856. // colors shifting and distortion
  54857. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  54858. var _this = this;
  54859. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  54860. [], // samplers
  54861. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  54862. this._chromaticAberrationPostProcess.onApply = function (effect) {
  54863. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  54864. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  54865. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  54866. };
  54867. };
  54868. // highlights enhancing
  54869. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  54870. var _this = this;
  54871. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  54872. [], // samplers
  54873. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  54874. this._highlightsPostProcess.onApply = function (effect) {
  54875. effect.setFloat('gain', _this._highlightsGain);
  54876. effect.setFloat('threshold', _this._highlightsThreshold);
  54877. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  54878. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  54879. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  54880. };
  54881. };
  54882. // colors shifting and distortion
  54883. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  54884. var _this = this;
  54885. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  54886. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  54887. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  54888. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  54889. this._depthOfFieldPostProcess.onApply = function (effect) {
  54890. effect.setTexture("depthSampler", _this._depthTexture);
  54891. effect.setTexture("grainSampler", _this._grainTexture);
  54892. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  54893. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  54894. effect.setFloat('grain_amount', _this._grainAmount);
  54895. effect.setBool('blur_noise', _this._blurNoise);
  54896. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  54897. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  54898. effect.setFloat('distortion', _this._distortion);
  54899. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  54900. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  54901. effect.setFloat('aperture', _this._dofAperture);
  54902. effect.setFloat('darken', _this._dofDarken);
  54903. effect.setFloat('edge_blur', _this._edgeBlur);
  54904. effect.setBool('highlights', (_this._highlightsGain !== -1));
  54905. effect.setFloat('near', _this._scene.activeCamera.minZ);
  54906. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  54907. };
  54908. };
  54909. // creates a black and white random noise texture, 512x512
  54910. LensRenderingPipeline.prototype._createGrainTexture = function () {
  54911. var size = 512;
  54912. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  54913. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  54914. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  54915. var context = this._grainTexture.getContext();
  54916. var rand = function (min, max) {
  54917. return Math.random() * (max - min) + min;
  54918. };
  54919. var value;
  54920. for (var x = 0; x < size; x++) {
  54921. for (var y = 0; y < size; y++) {
  54922. value = Math.floor(rand(0.42, 0.58) * 255);
  54923. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  54924. context.fillRect(x, y, 1, 1);
  54925. }
  54926. }
  54927. this._grainTexture.update(false);
  54928. };
  54929. return LensRenderingPipeline;
  54930. }(BABYLON.PostProcessRenderPipeline));
  54931. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  54932. })(BABYLON || (BABYLON = {}));
  54933. //
  54934. // This post-process allows the modification of rendered colors by using
  54935. // a 'look-up table' (LUT). This effect is also called Color Grading.
  54936. //
  54937. // The object needs to be provided an url to a texture containing the color
  54938. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  54939. // Use an image editing software to tweak the LUT to match your needs.
  54940. //
  54941. // For an example of a color LUT, see here:
  54942. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  54943. // For explanations on color grading, see here:
  54944. // http://udn.epicgames.com/Three/ColorGrading.html
  54945. //
  54946. var BABYLON;
  54947. (function (BABYLON) {
  54948. var ColorCorrectionPostProcess = (function (_super) {
  54949. __extends(ColorCorrectionPostProcess, _super);
  54950. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  54951. var _this = this;
  54952. _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable);
  54953. this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  54954. this._colorTableTexture.anisotropicFilteringLevel = 1;
  54955. this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54956. this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54957. this.onApply = function (effect) {
  54958. effect.setTexture("colorTable", _this._colorTableTexture);
  54959. };
  54960. }
  54961. return ColorCorrectionPostProcess;
  54962. }(BABYLON.PostProcess));
  54963. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  54964. })(BABYLON || (BABYLON = {}));
  54965. var BABYLON;
  54966. (function (BABYLON) {
  54967. var AnaglyphFreeCamera = (function (_super) {
  54968. __extends(AnaglyphFreeCamera, _super);
  54969. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  54970. _super.call(this, name, position, scene);
  54971. this.interaxialDistance = interaxialDistance;
  54972. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  54973. }
  54974. AnaglyphFreeCamera.prototype.getTypeName = function () {
  54975. return "AnaglyphFreeCamera";
  54976. };
  54977. return AnaglyphFreeCamera;
  54978. }(BABYLON.FreeCamera));
  54979. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  54980. var AnaglyphArcRotateCamera = (function (_super) {
  54981. __extends(AnaglyphArcRotateCamera, _super);
  54982. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  54983. _super.call(this, name, alpha, beta, radius, target, scene);
  54984. this.interaxialDistance = interaxialDistance;
  54985. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  54986. }
  54987. AnaglyphArcRotateCamera.prototype.getTypeName = function () {
  54988. return "AnaglyphArcRotateCamera";
  54989. };
  54990. return AnaglyphArcRotateCamera;
  54991. }(BABYLON.ArcRotateCamera));
  54992. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  54993. var AnaglyphGamepadCamera = (function (_super) {
  54994. __extends(AnaglyphGamepadCamera, _super);
  54995. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  54996. _super.call(this, name, position, scene);
  54997. this.interaxialDistance = interaxialDistance;
  54998. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  54999. }
  55000. AnaglyphGamepadCamera.prototype.getTypeName = function () {
  55001. return "AnaglyphGamepadCamera";
  55002. };
  55003. return AnaglyphGamepadCamera;
  55004. }(BABYLON.GamepadCamera));
  55005. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  55006. var AnaglyphUniversalCamera = (function (_super) {
  55007. __extends(AnaglyphUniversalCamera, _super);
  55008. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  55009. _super.call(this, name, position, scene);
  55010. this.interaxialDistance = interaxialDistance;
  55011. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  55012. }
  55013. AnaglyphUniversalCamera.prototype.getTypeName = function () {
  55014. return "AnaglyphUniversalCamera";
  55015. };
  55016. return AnaglyphUniversalCamera;
  55017. }(BABYLON.UniversalCamera));
  55018. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  55019. var StereoscopicFreeCamera = (function (_super) {
  55020. __extends(StereoscopicFreeCamera, _super);
  55021. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  55022. _super.call(this, name, position, scene);
  55023. this.interaxialDistance = interaxialDistance;
  55024. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  55025. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  55026. }
  55027. StereoscopicFreeCamera.prototype.getTypeName = function () {
  55028. return "StereoscopicFreeCamera";
  55029. };
  55030. return StereoscopicFreeCamera;
  55031. }(BABYLON.FreeCamera));
  55032. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  55033. var StereoscopicArcRotateCamera = (function (_super) {
  55034. __extends(StereoscopicArcRotateCamera, _super);
  55035. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  55036. _super.call(this, name, alpha, beta, radius, target, scene);
  55037. this.interaxialDistance = interaxialDistance;
  55038. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  55039. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  55040. }
  55041. StereoscopicArcRotateCamera.prototype.getTypeName = function () {
  55042. return "StereoscopicArcRotateCamera";
  55043. };
  55044. return StereoscopicArcRotateCamera;
  55045. }(BABYLON.ArcRotateCamera));
  55046. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  55047. var StereoscopicGamepadCamera = (function (_super) {
  55048. __extends(StereoscopicGamepadCamera, _super);
  55049. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  55050. _super.call(this, name, position, scene);
  55051. this.interaxialDistance = interaxialDistance;
  55052. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  55053. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  55054. }
  55055. StereoscopicGamepadCamera.prototype.getTypeName = function () {
  55056. return "StereoscopicGamepadCamera";
  55057. };
  55058. return StereoscopicGamepadCamera;
  55059. }(BABYLON.GamepadCamera));
  55060. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  55061. var StereoscopicUniversalCamera = (function (_super) {
  55062. __extends(StereoscopicUniversalCamera, _super);
  55063. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  55064. _super.call(this, name, position, scene);
  55065. this.interaxialDistance = interaxialDistance;
  55066. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  55067. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  55068. }
  55069. StereoscopicUniversalCamera.prototype.getTypeName = function () {
  55070. return "StereoscopicUniversalCamera";
  55071. };
  55072. return StereoscopicUniversalCamera;
  55073. }(BABYLON.UniversalCamera));
  55074. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  55075. })(BABYLON || (BABYLON = {}));
  55076. var BABYLON;
  55077. (function (BABYLON) {
  55078. var HDRRenderingPipeline = (function (_super) {
  55079. __extends(HDRRenderingPipeline, _super);
  55080. /**
  55081. * @constructor
  55082. * @param {string} name - The rendering pipeline name
  55083. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  55084. * @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)
  55085. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  55086. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  55087. */
  55088. function HDRRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  55089. var _this = this;
  55090. if (originalPostProcess === void 0) { originalPostProcess = null; }
  55091. _super.call(this, scene.getEngine(), name);
  55092. /**
  55093. * Public members
  55094. */
  55095. // Gaussian Blur
  55096. /**
  55097. * Gaussian blur coefficient
  55098. * @type {number}
  55099. */
  55100. this.gaussCoeff = 0.3;
  55101. /**
  55102. * Gaussian blur mean
  55103. * @type {number}
  55104. */
  55105. this.gaussMean = 1.0;
  55106. /**
  55107. * Gaussian blur standard deviation
  55108. * @type {number}
  55109. */
  55110. this.gaussStandDev = 0.8;
  55111. /**
  55112. * Gaussian blur multiplier. Multiplies the blur effect
  55113. * @type {number}
  55114. */
  55115. this.gaussMultiplier = 4.0;
  55116. // HDR
  55117. /**
  55118. * Exposure, controls the overall intensity of the pipeline
  55119. * @type {number}
  55120. */
  55121. this.exposure = 1.0;
  55122. /**
  55123. * Minimum luminance that the post-process can output. Luminance is >= 0
  55124. * @type {number}
  55125. */
  55126. this.minimumLuminance = 1.0;
  55127. /**
  55128. * Maximum luminance that the post-process can output. Must be suprerior to minimumLuminance
  55129. * @type {number}
  55130. */
  55131. this.maximumLuminance = 1e20;
  55132. /**
  55133. * Increase rate for luminance: eye adaptation speed to dark
  55134. * @type {number}
  55135. */
  55136. this.luminanceIncreaserate = 0.5;
  55137. /**
  55138. * Decrease rate for luminance: eye adaptation speed to bright
  55139. * @type {number}
  55140. */
  55141. this.luminanceDecreaseRate = 0.5;
  55142. // Bright pass
  55143. /**
  55144. * Minimum luminance needed to compute HDR
  55145. * @type {number}
  55146. */
  55147. this.brightThreshold = 0.8;
  55148. this._needUpdate = true;
  55149. this._scene = scene;
  55150. // Bright pass
  55151. this._createBrightPassPostProcess(scene, ratio);
  55152. // Down sample X4
  55153. this._createDownSampleX4PostProcess(scene, ratio);
  55154. // Create gaussian blur post-processes
  55155. this._createGaussianBlurPostProcess(scene, ratio);
  55156. // Texture adder
  55157. this._createTextureAdderPostProcess(scene, ratio);
  55158. // Luminance generator
  55159. this._createLuminanceGeneratorPostProcess(scene);
  55160. // HDR
  55161. this._createHDRPostProcess(scene, ratio);
  55162. // Pass postprocess
  55163. if (originalPostProcess === null) {
  55164. this._originalPostProcess = new BABYLON.PassPostProcess("hdr", ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  55165. }
  55166. else {
  55167. this._originalPostProcess = originalPostProcess;
  55168. }
  55169. // Configure pipeline
  55170. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this._originalPostProcess; }, true));
  55171. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this._brightPassPostProcess; }, true));
  55172. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this._downSampleX4PostProcess; }, true));
  55173. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurH", function () { return _this._guassianBlurHPostProcess; }, true));
  55174. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurV", function () { return _this._guassianBlurVPostProcess; }, true));
  55175. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this._textureAdderPostProcess; }, true));
  55176. var addDownSamplerPostProcess = function (id) {
  55177. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampler" + id, function () { return _this._downSamplePostProcesses[id]; }, true));
  55178. };
  55179. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  55180. addDownSamplerPostProcess(i);
  55181. }
  55182. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this._hdrPostProcess; }, true));
  55183. // Finish
  55184. scene.postProcessRenderPipelineManager.addPipeline(this);
  55185. if (cameras !== null) {
  55186. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  55187. }
  55188. this.update();
  55189. }
  55190. /**
  55191. * Tells the pipeline to update its post-processes
  55192. */
  55193. HDRRenderingPipeline.prototype.update = function () {
  55194. this._needUpdate = true;
  55195. };
  55196. /**
  55197. * Returns the current calculated luminance
  55198. */
  55199. HDRRenderingPipeline.prototype.getCurrentLuminance = function () {
  55200. return this._hdrCurrentLuminance;
  55201. };
  55202. /**
  55203. * Returns the currently drawn luminance
  55204. */
  55205. HDRRenderingPipeline.prototype.getOutputLuminance = function () {
  55206. return this._hdrOutputLuminance;
  55207. };
  55208. /**
  55209. * Releases the rendering pipeline and its internal effects. Detaches pipeline from cameras
  55210. */
  55211. HDRRenderingPipeline.prototype.dispose = function () {
  55212. this._originalPostProcess = undefined;
  55213. this._brightPassPostProcess = undefined;
  55214. this._downSampleX4PostProcess = undefined;
  55215. this._guassianBlurHPostProcess = undefined;
  55216. this._guassianBlurVPostProcess = undefined;
  55217. this._textureAdderPostProcess = undefined;
  55218. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  55219. this._downSamplePostProcesses[i] = undefined;
  55220. }
  55221. this._hdrPostProcess = undefined;
  55222. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  55223. };
  55224. /**
  55225. * Creates the HDR post-process and computes the luminance adaptation
  55226. */
  55227. HDRRenderingPipeline.prototype._createHDRPostProcess = function (scene, ratio) {
  55228. var _this = this;
  55229. var hdrLastLuminance = 0.0;
  55230. this._hdrOutputLuminance = -1.0;
  55231. this._hdrCurrentLuminance = 1.0;
  55232. this._hdrPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["exposure", "avgLuminance"], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define HDR");
  55233. this._hdrPostProcess.onApply = function (effect) {
  55234. if (_this._hdrOutputLuminance < 0.0) {
  55235. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  55236. }
  55237. else {
  55238. var dt = (hdrLastLuminance - (hdrLastLuminance + scene.getEngine().getDeltaTime())) / 1000.0;
  55239. if (_this._hdrCurrentLuminance < _this._hdrOutputLuminance + _this.luminanceDecreaseRate * dt) {
  55240. _this._hdrOutputLuminance += _this.luminanceDecreaseRate * dt;
  55241. }
  55242. else if (_this._hdrCurrentLuminance > _this._hdrOutputLuminance - _this.luminanceIncreaserate * dt) {
  55243. _this._hdrOutputLuminance -= _this.luminanceIncreaserate * dt;
  55244. }
  55245. else {
  55246. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  55247. }
  55248. }
  55249. _this._hdrOutputLuminance = BABYLON.MathTools.Clamp(_this._hdrOutputLuminance, _this.minimumLuminance, _this.maximumLuminance);
  55250. hdrLastLuminance += scene.getEngine().getDeltaTime();
  55251. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  55252. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  55253. effect.setFloat("exposure", _this.exposure);
  55254. effect.setFloat("avgLuminance", _this._hdrOutputLuminance);
  55255. _this._needUpdate = false;
  55256. };
  55257. };
  55258. /**
  55259. * Texture Adder post-process
  55260. */
  55261. HDRRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  55262. var _this = this;
  55263. this._textureAdderPostProcess = new BABYLON.PostProcess("hdr", "hdr", [], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define TEXTURE_ADDER");
  55264. this._textureAdderPostProcess.onApply = function (effect) {
  55265. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  55266. };
  55267. };
  55268. /**
  55269. * Down sample X4 post-process
  55270. */
  55271. HDRRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  55272. var _this = this;
  55273. var downSampleX4Offsets = new Array(32);
  55274. this._downSampleX4PostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets"], [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define DOWN_SAMPLE_X4");
  55275. this._downSampleX4PostProcess.onApply = function (effect) {
  55276. if (_this._needUpdate) {
  55277. var id = 0;
  55278. for (var i = -2; i < 2; i++) {
  55279. for (var j = -2; j < 2; j++) {
  55280. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this._downSampleX4PostProcess.width);
  55281. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this._downSampleX4PostProcess.height);
  55282. id += 2;
  55283. }
  55284. }
  55285. }
  55286. effect.setArray2("dsOffsets", downSampleX4Offsets);
  55287. };
  55288. };
  55289. /**
  55290. * Bright pass post-process
  55291. */
  55292. HDRRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  55293. var _this = this;
  55294. var brightOffsets = new Array(8);
  55295. var brightPassCallback = function (effect) {
  55296. if (_this._needUpdate) {
  55297. var sU = (1.0 / _this._brightPassPostProcess.width);
  55298. var sV = (1.0 / _this._brightPassPostProcess.height);
  55299. brightOffsets[0] = -0.5 * sU;
  55300. brightOffsets[1] = 0.5 * sV;
  55301. brightOffsets[2] = 0.5 * sU;
  55302. brightOffsets[3] = 0.5 * sV;
  55303. brightOffsets[4] = -0.5 * sU;
  55304. brightOffsets[5] = -0.5 * sV;
  55305. brightOffsets[6] = 0.5 * sU;
  55306. brightOffsets[7] = -0.5 * sV;
  55307. }
  55308. effect.setArray2("dsOffsets", brightOffsets);
  55309. effect.setFloat("brightThreshold", _this.brightThreshold);
  55310. };
  55311. this._brightPassPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "brightThreshold"], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define BRIGHT_PASS");
  55312. this._brightPassPostProcess.onApply = brightPassCallback;
  55313. };
  55314. /**
  55315. * Luminance generator. Creates the luminance post-process and down sample post-processes
  55316. */
  55317. HDRRenderingPipeline.prototype._createLuminanceGeneratorPostProcess = function (scene) {
  55318. var _this = this;
  55319. var lumSteps = HDRRenderingPipeline.LUM_STEPS;
  55320. var luminanceOffsets = new Array(8);
  55321. var downSampleOffsets = new Array(18);
  55322. var halfDestPixelSize;
  55323. this._downSamplePostProcesses = new Array(lumSteps);
  55324. // Utils for luminance
  55325. var luminanceUpdateSourceOffsets = function (width, height) {
  55326. var sU = (1.0 / width);
  55327. var sV = (1.0 / height);
  55328. luminanceOffsets[0] = -0.5 * sU;
  55329. luminanceOffsets[1] = 0.5 * sV;
  55330. luminanceOffsets[2] = 0.5 * sU;
  55331. luminanceOffsets[3] = 0.5 * sV;
  55332. luminanceOffsets[4] = -0.5 * sU;
  55333. luminanceOffsets[5] = -0.5 * sV;
  55334. luminanceOffsets[6] = 0.5 * sU;
  55335. luminanceOffsets[7] = -0.5 * sV;
  55336. };
  55337. var luminanceUpdateDestOffsets = function (width, height) {
  55338. var id = 0;
  55339. for (var x = -1; x < 2; x++) {
  55340. for (var y = -1; y < 2; y++) {
  55341. downSampleOffsets[id] = (x) / width;
  55342. downSampleOffsets[id + 1] = (y) / height;
  55343. id += 2;
  55344. }
  55345. }
  55346. };
  55347. // Luminance callback
  55348. var luminanceCallback = function (effect) {
  55349. if (_this._needUpdate) {
  55350. luminanceUpdateSourceOffsets(_this._textureAdderPostProcess.width, _this._textureAdderPostProcess.height);
  55351. }
  55352. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  55353. effect.setArray2("lumOffsets", luminanceOffsets);
  55354. };
  55355. // Down sample callbacks
  55356. var downSampleCallback = function (indice) {
  55357. var i = indice;
  55358. return function (effect) {
  55359. luminanceUpdateSourceOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  55360. luminanceUpdateDestOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  55361. halfDestPixelSize = 0.5 / _this._downSamplePostProcesses[i].width;
  55362. effect.setTextureFromPostProcess("textureSampler", _this._downSamplePostProcesses[i + 1]);
  55363. effect.setFloat("halfDestPixelSize", halfDestPixelSize);
  55364. effect.setArray2("dsOffsets", downSampleOffsets);
  55365. };
  55366. };
  55367. var downSampleAfterRenderCallback = function (effect) {
  55368. // Unpack result
  55369. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  55370. 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);
  55371. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  55372. };
  55373. // Create luminance post-process
  55374. var ratio = { width: Math.pow(3, lumSteps - 1), height: Math.pow(3, lumSteps - 1) };
  55375. 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);
  55376. this._downSamplePostProcesses[lumSteps - 1].onApply = luminanceCallback;
  55377. // Create down sample post-processes
  55378. for (var i = lumSteps - 2; i >= 0; i--) {
  55379. var length = Math.pow(3, i);
  55380. ratio = { width: length, height: length };
  55381. var defines = "#define DOWN_SAMPLE\n";
  55382. if (i === 0) {
  55383. defines += "#define FINAL_DOWN_SAMPLE\n"; // To pack the result
  55384. }
  55385. this._downSamplePostProcesses[i] = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "halfDestPixelSize"], [], ratio, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, scene.getEngine(), false, defines, BABYLON.Engine.TEXTURETYPE_FLOAT);
  55386. this._downSamplePostProcesses[i].onApply = downSampleCallback(i);
  55387. if (i === 0) {
  55388. this._downSamplePostProcesses[i].onAfterRender = downSampleAfterRenderCallback;
  55389. }
  55390. }
  55391. };
  55392. /**
  55393. * Gaussian blur post-processes. Horizontal and Vertical
  55394. */
  55395. HDRRenderingPipeline.prototype._createGaussianBlurPostProcess = function (scene, ratio) {
  55396. var _this = this;
  55397. var blurOffsetsW = new Array(9);
  55398. var blurOffsetsH = new Array(9);
  55399. var blurWeights = new Array(9);
  55400. var uniforms = ["blurOffsets", "blurWeights", "multiplier"];
  55401. // Utils for gaussian blur
  55402. var calculateBlurOffsets = function (height) {
  55403. var lastOutputDimensions = {
  55404. width: scene.getEngine().getRenderWidth(),
  55405. height: scene.getEngine().getRenderHeight()
  55406. };
  55407. for (var i = 0; i < 9; i++) {
  55408. var value = (i - 4.0) * (1.0 / (height === true ? lastOutputDimensions.height : lastOutputDimensions.width));
  55409. if (height) {
  55410. blurOffsetsH[i] = value;
  55411. }
  55412. else {
  55413. blurOffsetsW[i] = value;
  55414. }
  55415. }
  55416. };
  55417. var calculateWeights = function () {
  55418. var x = 0.0;
  55419. for (var i = 0; i < 9; i++) {
  55420. x = (i - 4.0) / 4.0;
  55421. 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));
  55422. }
  55423. };
  55424. // Callback
  55425. var gaussianBlurCallback = function (height) {
  55426. return function (effect) {
  55427. if (_this._needUpdate) {
  55428. calculateWeights();
  55429. calculateBlurOffsets(height);
  55430. }
  55431. effect.setArray("blurOffsets", height ? blurOffsetsH : blurOffsetsW);
  55432. effect.setArray("blurWeights", blurWeights);
  55433. effect.setFloat("multiplier", _this.gaussMultiplier);
  55434. };
  55435. };
  55436. // Create horizontal gaussian blur post-processes
  55437. this._guassianBlurHPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_H");
  55438. this._guassianBlurHPostProcess.onApply = gaussianBlurCallback(false);
  55439. // Create vertical gaussian blur post-process
  55440. this._guassianBlurVPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_V");
  55441. this._guassianBlurVPostProcess.onApply = gaussianBlurCallback(true);
  55442. };
  55443. // Luminance generator
  55444. HDRRenderingPipeline.LUM_STEPS = 6;
  55445. return HDRRenderingPipeline;
  55446. }(BABYLON.PostProcessRenderPipeline));
  55447. BABYLON.HDRRenderingPipeline = HDRRenderingPipeline;
  55448. })(BABYLON || (BABYLON = {}));
  55449. var BABYLON;
  55450. (function (BABYLON) {
  55451. var FaceAdjacencies = (function () {
  55452. function FaceAdjacencies() {
  55453. this.edges = new Array();
  55454. this.edgesConnectedCount = 0;
  55455. }
  55456. return FaceAdjacencies;
  55457. }());
  55458. var EdgesRenderer = (function () {
  55459. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  55460. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  55461. if (epsilon === void 0) { epsilon = 0.95; }
  55462. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  55463. this.edgesWidthScalerForOrthographic = 1000.0;
  55464. this.edgesWidthScalerForPerspective = 50.0;
  55465. this._linesPositions = new Array();
  55466. this._linesNormals = new Array();
  55467. this._linesIndices = new Array();
  55468. this._buffers = {};
  55469. this._checkVerticesInsteadOfIndices = false;
  55470. this._source = source;
  55471. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  55472. this._epsilon = epsilon;
  55473. this._prepareRessources();
  55474. this._generateEdgesLines();
  55475. }
  55476. EdgesRenderer.prototype._prepareRessources = function () {
  55477. if (this._lineShader) {
  55478. return;
  55479. }
  55480. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  55481. attributes: ["position", "normal"],
  55482. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  55483. });
  55484. this._lineShader.disableDepthWrite = true;
  55485. this._lineShader.backFaceCulling = false;
  55486. };
  55487. EdgesRenderer.prototype.dispose = function () {
  55488. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  55489. if (buffer) {
  55490. buffer.dispose();
  55491. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  55492. }
  55493. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  55494. if (buffer) {
  55495. buffer.dispose();
  55496. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  55497. }
  55498. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  55499. this._lineShader.dispose();
  55500. };
  55501. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  55502. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  55503. return 0;
  55504. }
  55505. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  55506. return 1;
  55507. }
  55508. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  55509. return 2;
  55510. }
  55511. return -1;
  55512. };
  55513. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  55514. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  55515. return 0;
  55516. }
  55517. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  55518. return 1;
  55519. }
  55520. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  55521. return 2;
  55522. }
  55523. return -1;
  55524. };
  55525. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  55526. var needToCreateLine;
  55527. if (edge === undefined) {
  55528. needToCreateLine = true;
  55529. }
  55530. else {
  55531. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  55532. needToCreateLine = dotProduct < this._epsilon;
  55533. }
  55534. if (needToCreateLine) {
  55535. var offset = this._linesPositions.length / 3;
  55536. var normal = p0.subtract(p1);
  55537. normal.normalize();
  55538. // Positions
  55539. this._linesPositions.push(p0.x);
  55540. this._linesPositions.push(p0.y);
  55541. this._linesPositions.push(p0.z);
  55542. this._linesPositions.push(p0.x);
  55543. this._linesPositions.push(p0.y);
  55544. this._linesPositions.push(p0.z);
  55545. this._linesPositions.push(p1.x);
  55546. this._linesPositions.push(p1.y);
  55547. this._linesPositions.push(p1.z);
  55548. this._linesPositions.push(p1.x);
  55549. this._linesPositions.push(p1.y);
  55550. this._linesPositions.push(p1.z);
  55551. // Normals
  55552. this._linesNormals.push(p1.x);
  55553. this._linesNormals.push(p1.y);
  55554. this._linesNormals.push(p1.z);
  55555. this._linesNormals.push(-1);
  55556. this._linesNormals.push(p1.x);
  55557. this._linesNormals.push(p1.y);
  55558. this._linesNormals.push(p1.z);
  55559. this._linesNormals.push(1);
  55560. this._linesNormals.push(p0.x);
  55561. this._linesNormals.push(p0.y);
  55562. this._linesNormals.push(p0.z);
  55563. this._linesNormals.push(-1);
  55564. this._linesNormals.push(p0.x);
  55565. this._linesNormals.push(p0.y);
  55566. this._linesNormals.push(p0.z);
  55567. this._linesNormals.push(1);
  55568. // Indices
  55569. this._linesIndices.push(offset);
  55570. this._linesIndices.push(offset + 1);
  55571. this._linesIndices.push(offset + 2);
  55572. this._linesIndices.push(offset);
  55573. this._linesIndices.push(offset + 2);
  55574. this._linesIndices.push(offset + 3);
  55575. }
  55576. };
  55577. EdgesRenderer.prototype._generateEdgesLines = function () {
  55578. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  55579. var indices = this._source.getIndices();
  55580. // First let's find adjacencies
  55581. var adjacencies = new Array();
  55582. var faceNormals = new Array();
  55583. var index;
  55584. var faceAdjacencies;
  55585. // Prepare faces
  55586. for (index = 0; index < indices.length; index += 3) {
  55587. faceAdjacencies = new FaceAdjacencies();
  55588. var p0Index = indices[index];
  55589. var p1Index = indices[index + 1];
  55590. var p2Index = indices[index + 2];
  55591. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  55592. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  55593. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  55594. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  55595. faceNormal.normalize();
  55596. faceNormals.push(faceNormal);
  55597. adjacencies.push(faceAdjacencies);
  55598. }
  55599. // Scan
  55600. for (index = 0; index < adjacencies.length; index++) {
  55601. faceAdjacencies = adjacencies[index];
  55602. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  55603. var otherFaceAdjacencies = adjacencies[otherIndex];
  55604. if (faceAdjacencies.edgesConnectedCount === 3) {
  55605. break;
  55606. }
  55607. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  55608. continue;
  55609. }
  55610. var otherP0 = indices[otherIndex * 3];
  55611. var otherP1 = indices[otherIndex * 3 + 1];
  55612. var otherP2 = indices[otherIndex * 3 + 2];
  55613. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  55614. var otherEdgeIndex;
  55615. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  55616. continue;
  55617. }
  55618. switch (edgeIndex) {
  55619. case 0:
  55620. if (this._checkVerticesInsteadOfIndices) {
  55621. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  55622. }
  55623. else {
  55624. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  55625. }
  55626. break;
  55627. case 1:
  55628. if (this._checkVerticesInsteadOfIndices) {
  55629. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  55630. }
  55631. else {
  55632. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  55633. }
  55634. break;
  55635. case 2:
  55636. if (this._checkVerticesInsteadOfIndices) {
  55637. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  55638. }
  55639. else {
  55640. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  55641. }
  55642. break;
  55643. }
  55644. if (otherEdgeIndex === -1) {
  55645. continue;
  55646. }
  55647. faceAdjacencies.edges[edgeIndex] = otherIndex;
  55648. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  55649. faceAdjacencies.edgesConnectedCount++;
  55650. otherFaceAdjacencies.edgesConnectedCount++;
  55651. if (faceAdjacencies.edgesConnectedCount === 3) {
  55652. break;
  55653. }
  55654. }
  55655. }
  55656. }
  55657. // Create lines
  55658. for (index = 0; index < adjacencies.length; index++) {
  55659. // 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
  55660. var current = adjacencies[index];
  55661. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  55662. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  55663. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  55664. }
  55665. // Merge into a single mesh
  55666. var engine = this._source.getScene().getEngine();
  55667. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  55668. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  55669. this._ib = engine.createIndexBuffer(this._linesIndices);
  55670. this._indicesCount = this._linesIndices.length;
  55671. };
  55672. EdgesRenderer.prototype.render = function () {
  55673. if (!this._lineShader.isReady()) {
  55674. return;
  55675. }
  55676. var scene = this._source.getScene();
  55677. var engine = scene.getEngine();
  55678. this._lineShader._preBind();
  55679. // VBOs
  55680. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  55681. scene.resetCachedMaterial();
  55682. this._lineShader.setColor4("color", this._source.edgesColor);
  55683. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  55684. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  55685. }
  55686. else {
  55687. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  55688. }
  55689. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  55690. this._lineShader.bind(this._source.getWorldMatrix());
  55691. // Draw order
  55692. engine.draw(true, 0, this._indicesCount);
  55693. this._lineShader.unbind();
  55694. engine.setDepthWrite(true);
  55695. };
  55696. return EdgesRenderer;
  55697. }());
  55698. BABYLON.EdgesRenderer = EdgesRenderer;
  55699. })(BABYLON || (BABYLON = {}));
  55700. var BABYLON;
  55701. (function (BABYLON) {
  55702. (function (TonemappingOperator) {
  55703. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  55704. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  55705. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  55706. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  55707. })(BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  55708. var TonemappingOperator = BABYLON.TonemappingOperator;
  55709. ;
  55710. var TonemapPostProcess = (function (_super) {
  55711. __extends(TonemapPostProcess, _super);
  55712. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  55713. var _this = this;
  55714. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  55715. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  55716. _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, defines, textureFormat);
  55717. this._operator = _operator;
  55718. this.exposureAdjustment = exposureAdjustment;
  55719. var defines = "#define ";
  55720. if (this._operator === TonemappingOperator.Hable)
  55721. defines += "HABLE_TONEMAPPING";
  55722. else if (this._operator === TonemappingOperator.Reinhard)
  55723. defines += "REINHARD_TONEMAPPING";
  55724. else if (this._operator === TonemappingOperator.HejiDawson)
  55725. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  55726. else if (this._operator === TonemappingOperator.Photographic)
  55727. defines += "PHOTOGRAPHIC_TONEMAPPING";
  55728. //sadly a second call to create the effect.
  55729. this.updateEffect(defines);
  55730. this.onApply = function (effect) {
  55731. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  55732. };
  55733. }
  55734. return TonemapPostProcess;
  55735. }(BABYLON.PostProcess));
  55736. BABYLON.TonemapPostProcess = TonemapPostProcess;
  55737. })(BABYLON || (BABYLON = {}));
  55738. var BABYLON;
  55739. (function (BABYLON) {
  55740. var ReflectionProbe = (function () {
  55741. function ReflectionProbe(name, size, scene, generateMipMaps) {
  55742. var _this = this;
  55743. if (generateMipMaps === void 0) { generateMipMaps = true; }
  55744. this.name = name;
  55745. this._viewMatrix = BABYLON.Matrix.Identity();
  55746. this._target = BABYLON.Vector3.Zero();
  55747. this._add = BABYLON.Vector3.Zero();
  55748. this.invertYAxis = false;
  55749. this.position = BABYLON.Vector3.Zero();
  55750. this._scene = scene;
  55751. this._scene.reflectionProbes.push(this);
  55752. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  55753. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  55754. switch (faceIndex) {
  55755. case 0:
  55756. _this._add.copyFromFloats(1, 0, 0);
  55757. break;
  55758. case 1:
  55759. _this._add.copyFromFloats(-1, 0, 0);
  55760. break;
  55761. case 2:
  55762. _this._add.copyFromFloats(0, _this.invertYAxis ? 1 : -1, 0);
  55763. break;
  55764. case 3:
  55765. _this._add.copyFromFloats(0, _this.invertYAxis ? -1 : 1, 0);
  55766. break;
  55767. case 4:
  55768. _this._add.copyFromFloats(0, 0, 1);
  55769. break;
  55770. case 5:
  55771. _this._add.copyFromFloats(0, 0, -1);
  55772. break;
  55773. }
  55774. if (_this._attachedMesh) {
  55775. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  55776. }
  55777. _this.position.addToRef(_this._add, _this._target);
  55778. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  55779. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  55780. });
  55781. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  55782. scene.updateTransformMatrix(true);
  55783. });
  55784. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  55785. }
  55786. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  55787. get: function () {
  55788. return this._renderTargetTexture.refreshRate;
  55789. },
  55790. set: function (value) {
  55791. this._renderTargetTexture.refreshRate = value;
  55792. },
  55793. enumerable: true,
  55794. configurable: true
  55795. });
  55796. ReflectionProbe.prototype.getScene = function () {
  55797. return this._scene;
  55798. };
  55799. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  55800. get: function () {
  55801. return this._renderTargetTexture;
  55802. },
  55803. enumerable: true,
  55804. configurable: true
  55805. });
  55806. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  55807. get: function () {
  55808. return this._renderTargetTexture.renderList;
  55809. },
  55810. enumerable: true,
  55811. configurable: true
  55812. });
  55813. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  55814. this._attachedMesh = mesh;
  55815. };
  55816. ReflectionProbe.prototype.dispose = function () {
  55817. var index = this._scene.reflectionProbes.indexOf(this);
  55818. if (index !== -1) {
  55819. // Remove from the scene if found
  55820. this._scene.reflectionProbes.splice(index, 1);
  55821. }
  55822. if (this._renderTargetTexture) {
  55823. this._renderTargetTexture.dispose();
  55824. this._renderTargetTexture = null;
  55825. }
  55826. };
  55827. return ReflectionProbe;
  55828. }());
  55829. BABYLON.ReflectionProbe = ReflectionProbe;
  55830. })(BABYLON || (BABYLON = {}));
  55831. var BABYLON;
  55832. (function (BABYLON) {
  55833. var SolidParticle = (function () {
  55834. function SolidParticle(particleIndex, positionIndex, model, shapeId, idxInShape) {
  55835. this.color = new BABYLON.Color4(1, 1, 1, 1); // color
  55836. this.position = BABYLON.Vector3.Zero(); // position
  55837. this.rotation = BABYLON.Vector3.Zero(); // rotation
  55838. this.scaling = new BABYLON.Vector3(1, 1, 1); // scaling
  55839. this.uvs = new BABYLON.Vector4(0, 0, 1, 1); // uvs
  55840. this.velocity = BABYLON.Vector3.Zero(); // velocity
  55841. this.alive = true; // alive
  55842. this.isVisible = true; // visibility
  55843. this.idx = particleIndex;
  55844. this._pos = positionIndex;
  55845. this._model = model;
  55846. this.shapeId = shapeId;
  55847. this.idxInShape = idxInShape;
  55848. }
  55849. Object.defineProperty(SolidParticle.prototype, "scale", {
  55850. //legacy support, changed scale to scaling
  55851. get: function () {
  55852. return this.scaling;
  55853. },
  55854. set: function (scale) {
  55855. this.scaling = scale;
  55856. },
  55857. enumerable: true,
  55858. configurable: true
  55859. });
  55860. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  55861. //legacy support, changed quaternion to rotationQuaternion
  55862. get: function () {
  55863. return this.rotationQuaternion;
  55864. },
  55865. set: function (q) {
  55866. this.rotationQuaternion = q;
  55867. },
  55868. enumerable: true,
  55869. configurable: true
  55870. });
  55871. return SolidParticle;
  55872. }());
  55873. BABYLON.SolidParticle = SolidParticle;
  55874. var ModelShape = (function () {
  55875. function ModelShape(id, shape, shapeUV, posFunction, vtxFunction) {
  55876. this.shapeID = id;
  55877. this._shape = shape;
  55878. this._shapeUV = shapeUV;
  55879. this._positionFunction = posFunction;
  55880. this._vertexFunction = vtxFunction;
  55881. }
  55882. return ModelShape;
  55883. }());
  55884. BABYLON.ModelShape = ModelShape;
  55885. })(BABYLON || (BABYLON = {}));
  55886. var BABYLON;
  55887. (function (BABYLON) {
  55888. /**
  55889. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  55890. */
  55891. var SolidParticleSystem = (function () {
  55892. /**
  55893. * Creates a SPS (Solid Particle System) object.
  55894. * `name` (String) is the SPS name, this will be the underlying mesh name.
  55895. * `scene` (Scene) is the scene in which the SPS is added.
  55896. * `updatable` (default true) : if the SPS must be updatable or immutable.
  55897. * `isPickable` (default false) : if the solid particles must be pickable.
  55898. */
  55899. function SolidParticleSystem(name, scene, options) {
  55900. // public members
  55901. /**
  55902. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  55903. * Example : var p = SPS.particles[i];
  55904. */
  55905. this.particles = new Array();
  55906. /**
  55907. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  55908. */
  55909. this.nbParticles = 0;
  55910. /**
  55911. * If the particles must ever face the camera (default false). Useful for planar particles.
  55912. */
  55913. this.billboard = false;
  55914. /**
  55915. * This a counter ofr your own usage. It's not set by any SPS functions.
  55916. */
  55917. this.counter = 0;
  55918. /**
  55919. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  55920. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  55921. */
  55922. this.vars = {};
  55923. this._positions = new Array();
  55924. this._indices = new Array();
  55925. this._normals = new Array();
  55926. this._colors = new Array();
  55927. this._uvs = new Array();
  55928. this._index = 0; // indices index
  55929. this._updatable = true;
  55930. this._pickable = false;
  55931. this._isVisibilityBoxLocked = false;
  55932. this._alwaysVisible = false;
  55933. this._shapeCounter = 0;
  55934. this._copy = new BABYLON.SolidParticle(null, null, null, null, null);
  55935. this._color = new BABYLON.Color4(0, 0, 0, 0);
  55936. this._computeParticleColor = true;
  55937. this._computeParticleTexture = true;
  55938. this._computeParticleRotation = true;
  55939. this._computeParticleVertex = false;
  55940. this._computeBoundingBox = false;
  55941. this._cam_axisZ = BABYLON.Vector3.Zero();
  55942. this._cam_axisY = BABYLON.Vector3.Zero();
  55943. this._cam_axisX = BABYLON.Vector3.Zero();
  55944. this._axisX = BABYLON.Axis.X;
  55945. this._axisY = BABYLON.Axis.Y;
  55946. this._axisZ = BABYLON.Axis.Z;
  55947. this._camDir = BABYLON.Vector3.Zero();
  55948. this._rotMatrix = new BABYLON.Matrix();
  55949. this._invertMatrix = new BABYLON.Matrix();
  55950. this._rotated = BABYLON.Vector3.Zero();
  55951. this._quaternion = new BABYLON.Quaternion();
  55952. this._vertex = BABYLON.Vector3.Zero();
  55953. this._normal = BABYLON.Vector3.Zero();
  55954. this._yaw = 0.0;
  55955. this._pitch = 0.0;
  55956. this._roll = 0.0;
  55957. this._halfroll = 0.0;
  55958. this._halfpitch = 0.0;
  55959. this._halfyaw = 0.0;
  55960. this._sinRoll = 0.0;
  55961. this._cosRoll = 0.0;
  55962. this._sinPitch = 0.0;
  55963. this._cosPitch = 0.0;
  55964. this._sinYaw = 0.0;
  55965. this._cosYaw = 0.0;
  55966. this._w = 0.0;
  55967. this._minimum = BABYLON.Tmp.Vector3[0];
  55968. this._maximum = BABYLON.Tmp.Vector3[1];
  55969. this.name = name;
  55970. this._scene = scene;
  55971. this._camera = scene.activeCamera;
  55972. this._pickable = options ? options.isPickable : false;
  55973. if (options && options.updatable) {
  55974. this._updatable = options.updatable;
  55975. }
  55976. else {
  55977. this._updatable = true;
  55978. }
  55979. if (this._pickable) {
  55980. this.pickedParticles = [];
  55981. }
  55982. }
  55983. /**
  55984. * Builds the SPS underlying mesh. Returns a standard Mesh.
  55985. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  55986. */
  55987. SolidParticleSystem.prototype.buildMesh = function () {
  55988. if (this.nbParticles === 0) {
  55989. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  55990. this.addShape(triangle, 1);
  55991. triangle.dispose();
  55992. }
  55993. this._positions32 = new Float32Array(this._positions);
  55994. this._uvs32 = new Float32Array(this._uvs);
  55995. this._colors32 = new Float32Array(this._colors);
  55996. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals);
  55997. this._normals32 = new Float32Array(this._normals);
  55998. this._fixedNormal32 = new Float32Array(this._normals);
  55999. var vertexData = new BABYLON.VertexData();
  56000. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  56001. vertexData.indices = this._indices;
  56002. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  56003. if (this._uvs32) {
  56004. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  56005. ;
  56006. }
  56007. if (this._colors32) {
  56008. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  56009. }
  56010. var mesh = new BABYLON.Mesh(this.name, this._scene);
  56011. vertexData.applyToMesh(mesh, this._updatable);
  56012. this.mesh = mesh;
  56013. this.mesh.isPickable = this._pickable;
  56014. // free memory
  56015. this._positions = null;
  56016. this._normals = null;
  56017. this._uvs = null;
  56018. this._colors = null;
  56019. if (!this._updatable) {
  56020. this.particles.length = 0;
  56021. }
  56022. return mesh;
  56023. };
  56024. /**
  56025. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  56026. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  56027. * Thus the particles generated from `digest()` have their property `position` set yet.
  56028. * `mesh` ( Mesh ) is the mesh to be digested
  56029. * `facetNb` (optional integer, default 1) is the number of mesh facets per particle, this parameter is overriden by the parameter `number` if any
  56030. * `delta` (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  56031. * `number` (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  56032. */
  56033. SolidParticleSystem.prototype.digest = function (mesh, options) {
  56034. var size = (options && options.facetNb) || 1;
  56035. var number = (options && options.number);
  56036. var delta = (options && options.delta) || 0;
  56037. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  56038. var meshInd = mesh.getIndices();
  56039. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  56040. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  56041. var f = 0; // facet counter
  56042. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  56043. // compute size from number
  56044. if (number) {
  56045. number = (number > totalFacets) ? totalFacets : number;
  56046. size = Math.round(totalFacets / number);
  56047. delta = 0;
  56048. }
  56049. else {
  56050. size = (size > totalFacets) ? totalFacets : size;
  56051. }
  56052. var facetPos = []; // submesh positions
  56053. var facetInd = []; // submesh indices
  56054. var facetUV = []; // submesh UV
  56055. var facetCol = []; // submesh colors
  56056. var barycenter = BABYLON.Tmp.Vector3[0];
  56057. var rand;
  56058. var sizeO = size;
  56059. while (f < totalFacets) {
  56060. size = sizeO + Math.floor((1 + delta) * Math.random());
  56061. if (f > totalFacets - size) {
  56062. size = totalFacets - f;
  56063. }
  56064. // reset temp arrays
  56065. facetPos.length = 0;
  56066. facetInd.length = 0;
  56067. facetUV.length = 0;
  56068. facetCol.length = 0;
  56069. // iterate over "size" facets
  56070. var fi = 0;
  56071. for (var j = f * 3; j < (f + size) * 3; j++) {
  56072. facetInd.push(fi);
  56073. var i = meshInd[j];
  56074. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  56075. if (meshUV) {
  56076. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  56077. }
  56078. if (meshCol) {
  56079. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  56080. }
  56081. fi++;
  56082. }
  56083. // create a model shape for each single particle
  56084. var idx = this.nbParticles;
  56085. var shape = this._posToShape(facetPos);
  56086. var shapeUV = this._uvsToShapeUV(facetUV);
  56087. // compute the barycenter of the shape
  56088. var v;
  56089. for (v = 0; v < shape.length; v++) {
  56090. barycenter.addInPlace(shape[v]);
  56091. }
  56092. barycenter.scaleInPlace(1 / shape.length);
  56093. // shift the shape from its barycenter to the origin
  56094. for (v = 0; v < shape.length; v++) {
  56095. shape[v].subtractInPlace(barycenter);
  56096. }
  56097. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, null, null);
  56098. // add the particle in the SPS
  56099. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, idx, 0, null);
  56100. this._addParticle(idx, this._positions.length, modelShape, this._shapeCounter, 0);
  56101. // initialize the particle position
  56102. this.particles[this.nbParticles].position.addInPlace(barycenter);
  56103. this._index += shape.length;
  56104. idx++;
  56105. this.nbParticles++;
  56106. this._shapeCounter++;
  56107. f += size;
  56108. }
  56109. return this;
  56110. };
  56111. //reset copy
  56112. SolidParticleSystem.prototype._resetCopy = function () {
  56113. this._copy.position.x = 0;
  56114. this._copy.position.y = 0;
  56115. this._copy.position.z = 0;
  56116. this._copy.rotation.x = 0;
  56117. this._copy.rotation.y = 0;
  56118. this._copy.rotation.z = 0;
  56119. this._copy.rotationQuaternion = null;
  56120. this._copy.scaling.x = 1;
  56121. this._copy.scaling.y = 1;
  56122. this._copy.scaling.z = 1;
  56123. this._copy.uvs.x = 0;
  56124. this._copy.uvs.y = 0;
  56125. this._copy.uvs.z = 1;
  56126. this._copy.uvs.w = 1;
  56127. this._copy.color = null;
  56128. };
  56129. // _meshBuilder : inserts the shape model in the global SPS mesh
  56130. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, idx, idxInShape, options) {
  56131. var i;
  56132. var u = 0;
  56133. var c = 0;
  56134. this._resetCopy();
  56135. if (options && options.positionFunction) {
  56136. options.positionFunction(this._copy, idx, idxInShape);
  56137. }
  56138. if (this._copy.rotationQuaternion) {
  56139. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  56140. }
  56141. else {
  56142. this._yaw = this._copy.rotation.y;
  56143. this._pitch = this._copy.rotation.x;
  56144. this._roll = this._copy.rotation.z;
  56145. this._quaternionRotationYPR();
  56146. }
  56147. this._quaternionToRotationMatrix();
  56148. for (i = 0; i < shape.length; i++) {
  56149. this._vertex.x = shape[i].x;
  56150. this._vertex.y = shape[i].y;
  56151. this._vertex.z = shape[i].z;
  56152. if (options && options.vertexFunction) {
  56153. options.vertexFunction(this._copy, this._vertex, i);
  56154. }
  56155. this._vertex.x *= this._copy.scaling.x;
  56156. this._vertex.y *= this._copy.scaling.y;
  56157. this._vertex.z *= this._copy.scaling.z;
  56158. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  56159. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  56160. if (meshUV) {
  56161. 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);
  56162. u += 2;
  56163. }
  56164. if (this._copy.color) {
  56165. this._color = this._copy.color;
  56166. }
  56167. else if (meshCol && meshCol[c] !== undefined) {
  56168. this._color.r = meshCol[c];
  56169. this._color.g = meshCol[c + 1];
  56170. this._color.b = meshCol[c + 2];
  56171. this._color.a = meshCol[c + 3];
  56172. }
  56173. else {
  56174. this._color.r = 1;
  56175. this._color.g = 1;
  56176. this._color.b = 1;
  56177. this._color.a = 1;
  56178. }
  56179. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  56180. c += 4;
  56181. }
  56182. for (i = 0; i < meshInd.length; i++) {
  56183. indices.push(p + meshInd[i]);
  56184. }
  56185. if (this._pickable) {
  56186. var nbfaces = meshInd.length / 3;
  56187. for (i = 0; i < nbfaces; i++) {
  56188. this.pickedParticles.push({ idx: idx, faceId: i });
  56189. }
  56190. }
  56191. };
  56192. // returns a shape array from positions array
  56193. SolidParticleSystem.prototype._posToShape = function (positions) {
  56194. var shape = [];
  56195. for (var i = 0; i < positions.length; i += 3) {
  56196. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  56197. }
  56198. return shape;
  56199. };
  56200. // returns a shapeUV array from a Vector4 uvs
  56201. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  56202. var shapeUV = [];
  56203. if (uvs) {
  56204. for (var i = 0; i < uvs.length; i++)
  56205. shapeUV.push(uvs[i]);
  56206. }
  56207. return shapeUV;
  56208. };
  56209. // adds a new particle object in the particles array
  56210. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, model, shapeId, idxInShape) {
  56211. this.particles.push(new BABYLON.SolidParticle(idx, idxpos, model, shapeId, idxInShape));
  56212. };
  56213. /**
  56214. * Adds some particles to the SPS from the model shape. Returns the shape id.
  56215. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  56216. * `mesh` is any Mesh object that will be used as a model for the solid particles.
  56217. * `nb` (positive integer) the number of particles to be created from this model
  56218. * `positionFunction` is an optional javascript function to called for each particle on SPS creation.
  56219. * `vertexFunction` is an optional javascript function to called for each vertex of each particle on SPS creation
  56220. */
  56221. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  56222. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  56223. var meshInd = mesh.getIndices();
  56224. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  56225. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  56226. var shape = this._posToShape(meshPos);
  56227. var shapeUV = this._uvsToShapeUV(meshUV);
  56228. var posfunc = options ? options.positionFunction : null;
  56229. var vtxfunc = options ? options.vertexFunction : null;
  56230. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, posfunc, vtxfunc);
  56231. // particles
  56232. var idx = this.nbParticles;
  56233. for (var i = 0; i < nb; i++) {
  56234. this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, idx, i, options);
  56235. if (this._updatable) {
  56236. this._addParticle(idx, this._positions.length, modelShape, this._shapeCounter, i);
  56237. }
  56238. this._index += shape.length;
  56239. idx++;
  56240. }
  56241. this.nbParticles += nb;
  56242. this._shapeCounter++;
  56243. return this._shapeCounter - 1;
  56244. };
  56245. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  56246. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  56247. this._resetCopy();
  56248. if (particle._model._positionFunction) {
  56249. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  56250. }
  56251. if (this._copy.rotationQuaternion) {
  56252. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  56253. }
  56254. else {
  56255. this._yaw = this._copy.rotation.y;
  56256. this._pitch = this._copy.rotation.x;
  56257. this._roll = this._copy.rotation.z;
  56258. this._quaternionRotationYPR();
  56259. }
  56260. this._quaternionToRotationMatrix();
  56261. this._shape = particle._model._shape;
  56262. for (var pt = 0; pt < this._shape.length; pt++) {
  56263. this._vertex.x = this._shape[pt].x;
  56264. this._vertex.y = this._shape[pt].y;
  56265. this._vertex.z = this._shape[pt].z;
  56266. if (particle._model._vertexFunction) {
  56267. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  56268. }
  56269. this._vertex.x *= this._copy.scaling.x;
  56270. this._vertex.y *= this._copy.scaling.y;
  56271. this._vertex.z *= this._copy.scaling.z;
  56272. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  56273. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  56274. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  56275. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  56276. }
  56277. particle.position.x = 0;
  56278. particle.position.y = 0;
  56279. particle.position.z = 0;
  56280. particle.rotation.x = 0;
  56281. particle.rotation.y = 0;
  56282. particle.rotation.z = 0;
  56283. particle.rotationQuaternion = null;
  56284. particle.scaling.x = 1;
  56285. particle.scaling.y = 1;
  56286. particle.scaling.z = 1;
  56287. };
  56288. /**
  56289. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  56290. */
  56291. SolidParticleSystem.prototype.rebuildMesh = function () {
  56292. for (var p = 0; p < this.particles.length; p++) {
  56293. this._rebuildParticle(this.particles[p]);
  56294. }
  56295. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  56296. };
  56297. /**
  56298. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  56299. * This method calls `updateParticle()` for each particle of the SPS.
  56300. * For an animated SPS, it is usually called within the render loop.
  56301. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  56302. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  56303. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  56304. */
  56305. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  56306. if (start === void 0) { start = 0; }
  56307. if (end === void 0) { end = this.nbParticles - 1; }
  56308. if (update === void 0) { update = true; }
  56309. if (!this._updatable) {
  56310. return;
  56311. }
  56312. // custom beforeUpdate
  56313. this.beforeUpdateParticles(start, end, update);
  56314. this._cam_axisX.x = 1.0;
  56315. this._cam_axisX.y = 0.0;
  56316. this._cam_axisX.z = 0.0;
  56317. this._cam_axisY.x = 0.0;
  56318. this._cam_axisY.y = 1.0;
  56319. this._cam_axisY.z = 0.0;
  56320. this._cam_axisZ.x = 0.0;
  56321. this._cam_axisZ.y = 0.0;
  56322. this._cam_axisZ.z = 1.0;
  56323. // if the particles will always face the camera
  56324. if (this.billboard) {
  56325. // compute the camera position and un-rotate it by the current mesh rotation
  56326. this._yaw = this.mesh.rotation.y;
  56327. this._pitch = this.mesh.rotation.x;
  56328. this._roll = this.mesh.rotation.z;
  56329. this._quaternionRotationYPR();
  56330. this._quaternionToRotationMatrix();
  56331. this._rotMatrix.invertToRef(this._invertMatrix);
  56332. this._camera._currentTarget.subtractToRef(this._camera.globalPosition, this._camDir);
  56333. BABYLON.Vector3.TransformCoordinatesToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  56334. this._cam_axisZ.normalize();
  56335. // set two orthogonal vectors (_cam_axisX and and _cam_axisY) to the rotated camDir axis (_cam_axisZ)
  56336. BABYLON.Vector3.CrossToRef(this._cam_axisZ, this._axisX, this._cam_axisY);
  56337. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  56338. this._cam_axisY.normalize();
  56339. this._cam_axisX.normalize();
  56340. }
  56341. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  56342. var idx = 0;
  56343. var index = 0;
  56344. var colidx = 0;
  56345. var colorIndex = 0;
  56346. var uvidx = 0;
  56347. var uvIndex = 0;
  56348. var pt = 0;
  56349. if (this._computeBoundingBox) {
  56350. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  56351. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  56352. }
  56353. // particle loop
  56354. end = (end > this.nbParticles - 1) ? this.nbParticles - 1 : end;
  56355. for (var p = start; p <= end; p++) {
  56356. this._particle = this.particles[p];
  56357. this._shape = this._particle._model._shape;
  56358. this._shapeUV = this._particle._model._shapeUV;
  56359. // call to custom user function to update the particle properties
  56360. this.updateParticle(this._particle);
  56361. if (this._particle.isVisible) {
  56362. // particle rotation matrix
  56363. if (this.billboard) {
  56364. this._particle.rotation.x = 0.0;
  56365. this._particle.rotation.y = 0.0;
  56366. }
  56367. if (this._computeParticleRotation || this.billboard) {
  56368. if (this._particle.rotationQuaternion) {
  56369. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  56370. }
  56371. else {
  56372. this._yaw = this._particle.rotation.y;
  56373. this._pitch = this._particle.rotation.x;
  56374. this._roll = this._particle.rotation.z;
  56375. this._quaternionRotationYPR();
  56376. }
  56377. this._quaternionToRotationMatrix();
  56378. }
  56379. // particle vertex loop
  56380. for (pt = 0; pt < this._shape.length; pt++) {
  56381. idx = index + pt * 3;
  56382. colidx = colorIndex + pt * 4;
  56383. uvidx = uvIndex + pt * 2;
  56384. this._vertex.x = this._shape[pt].x;
  56385. this._vertex.y = this._shape[pt].y;
  56386. this._vertex.z = this._shape[pt].z;
  56387. if (this._computeParticleVertex) {
  56388. this.updateParticleVertex(this._particle, this._vertex, pt);
  56389. }
  56390. // positions
  56391. this._vertex.x *= this._particle.scaling.x;
  56392. this._vertex.y *= this._particle.scaling.y;
  56393. this._vertex.z *= this._particle.scaling.z;
  56394. 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];
  56395. 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;
  56396. 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;
  56397. 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;
  56398. 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;
  56399. 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;
  56400. 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;
  56401. if (this._computeBoundingBox) {
  56402. if (this._positions32[idx] < this._minimum.x) {
  56403. this._minimum.x = this._positions32[idx];
  56404. }
  56405. if (this._positions32[idx] > this._maximum.x) {
  56406. this._maximum.x = this._positions32[idx];
  56407. }
  56408. if (this._positions32[idx + 1] < this._minimum.y) {
  56409. this._minimum.y = this._positions32[idx + 1];
  56410. }
  56411. if (this._positions32[idx + 1] > this._maximum.y) {
  56412. this._maximum.y = this._positions32[idx + 1];
  56413. }
  56414. if (this._positions32[idx + 2] < this._minimum.z) {
  56415. this._minimum.z = this._positions32[idx + 2];
  56416. }
  56417. if (this._positions32[idx + 2] > this._maximum.z) {
  56418. this._maximum.z = this._positions32[idx + 2];
  56419. }
  56420. }
  56421. // normals : if the particles can't be morphed then just rotate the normals, what if much more faster than ComputeNormals()
  56422. if (!this._computeParticleVertex) {
  56423. this._normal.x = this._fixedNormal32[idx];
  56424. this._normal.y = this._fixedNormal32[idx + 1];
  56425. this._normal.z = this._fixedNormal32[idx + 2];
  56426. 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];
  56427. 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;
  56428. 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;
  56429. 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;
  56430. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  56431. 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;
  56432. 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;
  56433. }
  56434. if (this._computeParticleColor) {
  56435. this._colors32[colidx] = this._particle.color.r;
  56436. this._colors32[colidx + 1] = this._particle.color.g;
  56437. this._colors32[colidx + 2] = this._particle.color.b;
  56438. this._colors32[colidx + 3] = this._particle.color.a;
  56439. }
  56440. if (this._computeParticleTexture) {
  56441. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  56442. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  56443. }
  56444. }
  56445. }
  56446. else {
  56447. for (pt = 0; pt < this._shape.length; pt++) {
  56448. idx = index + pt * 3;
  56449. colidx = colorIndex + pt * 4;
  56450. uvidx = uvIndex + pt * 2;
  56451. this._positions32[idx] = this._camera.position.x;
  56452. this._positions32[idx + 1] = this._camera.position.y;
  56453. this._positions32[idx + 2] = this._camera.position.z;
  56454. this._normals32[idx] = 0.0;
  56455. this._normals32[idx + 1] = 0.0;
  56456. this._normals32[idx + 2] = 0.0;
  56457. if (this._computeParticleColor) {
  56458. this._colors32[colidx] = this._particle.color.r;
  56459. this._colors32[colidx + 1] = this._particle.color.g;
  56460. this._colors32[colidx + 2] = this._particle.color.b;
  56461. this._colors32[colidx + 3] = this._particle.color.a;
  56462. }
  56463. if (this._computeParticleTexture) {
  56464. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  56465. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  56466. }
  56467. }
  56468. }
  56469. // increment indexes for the next particle
  56470. index = idx + 3;
  56471. colorIndex = colidx + 4;
  56472. uvIndex = uvidx + 2;
  56473. }
  56474. // if the VBO must be updated
  56475. if (update) {
  56476. if (this._computeParticleColor) {
  56477. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  56478. }
  56479. if (this._computeParticleTexture) {
  56480. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  56481. }
  56482. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  56483. if (!this.mesh.areNormalsFrozen) {
  56484. if (this._computeParticleVertex) {
  56485. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  56486. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals32);
  56487. for (var i = 0; i < this._normals32.length; i++) {
  56488. this._fixedNormal32[i] = this._normals32[i];
  56489. }
  56490. }
  56491. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  56492. }
  56493. }
  56494. if (this._computeBoundingBox) {
  56495. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  56496. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  56497. }
  56498. this.afterUpdateParticles(start, end, update);
  56499. };
  56500. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  56501. this._halfroll = this._roll * 0.5;
  56502. this._halfpitch = this._pitch * 0.5;
  56503. this._halfyaw = this._yaw * 0.5;
  56504. this._sinRoll = Math.sin(this._halfroll);
  56505. this._cosRoll = Math.cos(this._halfroll);
  56506. this._sinPitch = Math.sin(this._halfpitch);
  56507. this._cosPitch = Math.cos(this._halfpitch);
  56508. this._sinYaw = Math.sin(this._halfyaw);
  56509. this._cosYaw = Math.cos(this._halfyaw);
  56510. this._quaternion.x = (this._cosYaw * this._sinPitch * this._cosRoll) + (this._sinYaw * this._cosPitch * this._sinRoll);
  56511. this._quaternion.y = (this._sinYaw * this._cosPitch * this._cosRoll) - (this._cosYaw * this._sinPitch * this._sinRoll);
  56512. this._quaternion.z = (this._cosYaw * this._cosPitch * this._sinRoll) - (this._sinYaw * this._sinPitch * this._cosRoll);
  56513. this._quaternion.w = (this._cosYaw * this._cosPitch * this._cosRoll) + (this._sinYaw * this._sinPitch * this._sinRoll);
  56514. };
  56515. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  56516. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  56517. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  56518. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  56519. this._rotMatrix.m[3] = 0;
  56520. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  56521. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  56522. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  56523. this._rotMatrix.m[7] = 0;
  56524. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  56525. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  56526. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  56527. this._rotMatrix.m[11] = 0;
  56528. this._rotMatrix.m[12] = 0;
  56529. this._rotMatrix.m[13] = 0;
  56530. this._rotMatrix.m[14] = 0;
  56531. this._rotMatrix.m[15] = 1.0;
  56532. };
  56533. /**
  56534. * Disposes the SPS
  56535. */
  56536. SolidParticleSystem.prototype.dispose = function () {
  56537. this.mesh.dispose();
  56538. this.vars = null;
  56539. // drop references to internal big arrays for the GC
  56540. this._positions = null;
  56541. this._indices = null;
  56542. this._normals = null;
  56543. this._uvs = null;
  56544. this._colors = null;
  56545. this._positions32 = null;
  56546. this._normals32 = null;
  56547. this._fixedNormal32 = null;
  56548. this._uvs32 = null;
  56549. this._colors32 = null;
  56550. this.pickedParticles = null;
  56551. };
  56552. /**
  56553. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  56554. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  56555. */
  56556. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  56557. if (!this._isVisibilityBoxLocked) {
  56558. this.mesh.refreshBoundingInfo();
  56559. }
  56560. };
  56561. /**
  56562. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  56563. * @param size the size (float) of the visibility box
  56564. * note : this doesn't lock the SPS mesh bounding box.
  56565. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  56566. */
  56567. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  56568. var vis = size / 2;
  56569. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  56570. };
  56571. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  56572. // getter and setter
  56573. get: function () {
  56574. return this._alwaysVisible;
  56575. },
  56576. /**
  56577. * Sets the SPS as always visible or not
  56578. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  56579. */
  56580. set: function (val) {
  56581. this._alwaysVisible = val;
  56582. this.mesh.alwaysSelectAsActiveMesh = val;
  56583. },
  56584. enumerable: true,
  56585. configurable: true
  56586. });
  56587. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  56588. get: function () {
  56589. return this._isVisibilityBoxLocked;
  56590. },
  56591. /**
  56592. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  56593. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  56594. */
  56595. set: function (val) {
  56596. this._isVisibilityBoxLocked = val;
  56597. this.mesh.getBoundingInfo().isLocked = val;
  56598. },
  56599. enumerable: true,
  56600. configurable: true
  56601. });
  56602. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  56603. // getters
  56604. get: function () {
  56605. return this._computeParticleRotation;
  56606. },
  56607. // Optimizer setters
  56608. /**
  56609. * Tells to `setParticles()` to compute the particle rotations or not.
  56610. * Default value : true. The SPS is faster when it's set to false.
  56611. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  56612. */
  56613. set: function (val) {
  56614. this._computeParticleRotation = val;
  56615. },
  56616. enumerable: true,
  56617. configurable: true
  56618. });
  56619. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  56620. get: function () {
  56621. return this._computeParticleColor;
  56622. },
  56623. /**
  56624. * Tells to `setParticles()` to compute the particle colors or not.
  56625. * Default value : true. The SPS is faster when it's set to false.
  56626. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  56627. */
  56628. set: function (val) {
  56629. this._computeParticleColor = val;
  56630. },
  56631. enumerable: true,
  56632. configurable: true
  56633. });
  56634. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  56635. get: function () {
  56636. return this._computeParticleTexture;
  56637. },
  56638. /**
  56639. * Tells to `setParticles()` to compute the particle textures or not.
  56640. * Default value : true. The SPS is faster when it's set to false.
  56641. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  56642. */
  56643. set: function (val) {
  56644. this._computeParticleTexture = val;
  56645. },
  56646. enumerable: true,
  56647. configurable: true
  56648. });
  56649. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  56650. get: function () {
  56651. return this._computeParticleVertex;
  56652. },
  56653. /**
  56654. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  56655. * Default value : false. The SPS is faster when it's set to false.
  56656. * Note : the particle custom vertex positions aren't stored values.
  56657. */
  56658. set: function (val) {
  56659. this._computeParticleVertex = val;
  56660. },
  56661. enumerable: true,
  56662. configurable: true
  56663. });
  56664. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  56665. get: function () {
  56666. return this._computeBoundingBox;
  56667. },
  56668. /**
  56669. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  56670. */
  56671. set: function (val) {
  56672. this._computeBoundingBox = val;
  56673. },
  56674. enumerable: true,
  56675. configurable: true
  56676. });
  56677. // =======================================================================
  56678. // Particle behavior logic
  56679. // these following methods may be overwritten by the user to fit his needs
  56680. /**
  56681. * This function does nothing. It may be overwritten to set all the particle first values.
  56682. * The SPS doesn't call this function, you may have to call it by your own.
  56683. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  56684. */
  56685. SolidParticleSystem.prototype.initParticles = function () {
  56686. };
  56687. /**
  56688. * This function does nothing. It may be overwritten to recycle a particle.
  56689. * The SPS doesn't call this function, you may have to call it by your own.
  56690. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  56691. */
  56692. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  56693. return particle;
  56694. };
  56695. /**
  56696. * Updates a particle : this function should be overwritten by the user.
  56697. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  56698. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  56699. * ex : just set a particle position or velocity and recycle conditions
  56700. */
  56701. SolidParticleSystem.prototype.updateParticle = function (particle) {
  56702. return particle;
  56703. };
  56704. /**
  56705. * Updates a vertex of a particle : it can be overwritten by the user.
  56706. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  56707. * @param particle the current particle
  56708. * @param vertex the current index of the current particle
  56709. * @param pt the index of the current vertex in the particle shape
  56710. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  56711. * ex : just set a vertex particle position
  56712. */
  56713. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  56714. return vertex;
  56715. };
  56716. /**
  56717. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  56718. * This does nothing and may be overwritten by the user.
  56719. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  56720. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  56721. * @param update the boolean update value actually passed to setParticles()
  56722. */
  56723. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  56724. };
  56725. /**
  56726. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  56727. * This will be passed three parameters.
  56728. * This does nothing and may be overwritten by the user.
  56729. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  56730. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  56731. * @param update the boolean update value actually passed to setParticles()
  56732. */
  56733. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  56734. };
  56735. return SolidParticleSystem;
  56736. }());
  56737. BABYLON.SolidParticleSystem = SolidParticleSystem;
  56738. })(BABYLON || (BABYLON = {}));
  56739. var BABYLON;
  56740. (function (BABYLON) {
  56741. var Internals;
  56742. (function (Internals) {
  56743. var FileFaceOrientation = (function () {
  56744. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  56745. this.name = name;
  56746. this.worldAxisForNormal = worldAxisForNormal;
  56747. this.worldAxisForFileX = worldAxisForFileX;
  56748. this.worldAxisForFileY = worldAxisForFileY;
  56749. }
  56750. return FileFaceOrientation;
  56751. }());
  56752. ;
  56753. /**
  56754. * Helper class dealing with the extraction of spherical polynomial dataArray
  56755. * from a cube map.
  56756. */
  56757. var CubeMapToSphericalPolynomialTools = (function () {
  56758. function CubeMapToSphericalPolynomialTools() {
  56759. }
  56760. /**
  56761. * Converts a cubemap to the according Spherical Polynomial data.
  56762. * This extracts the first 3 orders only as they are the only one used in the lighting.
  56763. *
  56764. * @param cubeInfo The Cube map to extract the information from.
  56765. * @return The Spherical Polynomial data.
  56766. */
  56767. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  56768. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  56769. var totalSolidAngle = 0.0;
  56770. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  56771. var du = 2.0 / cubeInfo.size;
  56772. var dv = du;
  56773. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  56774. var minUV = du * 0.5 - 1.0;
  56775. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  56776. var fileFace = this.FileFaces[faceIndex];
  56777. var dataArray = cubeInfo[fileFace.name];
  56778. var v = minUV;
  56779. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  56780. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  56781. // Because SP is still linear, so summation is fine in that basis.
  56782. for (var y = 0; y < cubeInfo.size; y++) {
  56783. var u = minUV;
  56784. for (var x = 0; x < cubeInfo.size; x++) {
  56785. // World direction (not normalised)
  56786. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  56787. worldDirection.normalize();
  56788. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  56789. if (1) {
  56790. var r = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0];
  56791. var g = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1];
  56792. var b = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2];
  56793. var color = new BABYLON.Color3(r, g, b);
  56794. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  56795. }
  56796. else {
  56797. if (faceIndex == 0) {
  56798. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  56799. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  56800. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  56801. }
  56802. else if (faceIndex == 1) {
  56803. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  56804. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  56805. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  56806. }
  56807. else if (faceIndex == 2) {
  56808. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  56809. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  56810. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  56811. }
  56812. else if (faceIndex == 3) {
  56813. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  56814. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  56815. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  56816. }
  56817. else if (faceIndex == 4) {
  56818. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  56819. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  56820. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  56821. }
  56822. else if (faceIndex == 5) {
  56823. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  56824. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  56825. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  56826. }
  56827. 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]);
  56828. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  56829. }
  56830. totalSolidAngle += deltaSolidAngle;
  56831. u += du;
  56832. }
  56833. v += dv;
  56834. }
  56835. }
  56836. var correctSolidAngle = 4.0 * Math.PI; // Solid angle for entire sphere is 4*pi
  56837. var correction = correctSolidAngle / totalSolidAngle;
  56838. sphericalHarmonics.scale(correction);
  56839. // Additionally scale by pi -- audit needed
  56840. sphericalHarmonics.scale(1.0 / Math.PI);
  56841. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  56842. };
  56843. CubeMapToSphericalPolynomialTools.FileFaces = [
  56844. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  56845. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  56846. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  56847. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  56848. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  56849. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  56850. ];
  56851. return CubeMapToSphericalPolynomialTools;
  56852. }());
  56853. Internals.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  56854. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  56855. })(BABYLON || (BABYLON = {}));
  56856. var BABYLON;
  56857. (function (BABYLON) {
  56858. var Internals;
  56859. (function (Internals) {
  56860. /**
  56861. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  56862. */
  56863. var PanoramaToCubeMapTools = (function () {
  56864. function PanoramaToCubeMapTools() {
  56865. }
  56866. /**
  56867. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  56868. *
  56869. * @param float32Array The source data.
  56870. * @param inputWidth The width of the input panorama.
  56871. * @param inputhHeight The height of the input panorama.
  56872. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  56873. * @return The cubemap data
  56874. */
  56875. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  56876. if (!float32Array) {
  56877. throw "ConvertPanoramaToCubemap: input cannot be null";
  56878. }
  56879. if (float32Array.length != inputWidth * inputHeight * 3) {
  56880. throw "ConvertPanoramaToCubemap: input size is wrong";
  56881. }
  56882. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  56883. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  56884. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  56885. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  56886. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  56887. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  56888. return {
  56889. front: textureFront,
  56890. back: textureBack,
  56891. left: textureLeft,
  56892. right: textureRight,
  56893. up: textureUp,
  56894. down: textureDown,
  56895. size: size
  56896. };
  56897. };
  56898. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  56899. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  56900. var textureArray = new Float32Array(buffer);
  56901. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  56902. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  56903. var dy = 1 / texSize;
  56904. var fy = 0;
  56905. for (var y = 0; y < texSize; y++) {
  56906. var xv1 = faceData[0];
  56907. var xv2 = faceData[2];
  56908. for (var x = 0; x < texSize; x++) {
  56909. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  56910. v.normalize();
  56911. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  56912. // 3 channels per pixels
  56913. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  56914. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  56915. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  56916. xv1 = xv1.add(rotDX1);
  56917. xv2 = xv2.add(rotDX2);
  56918. }
  56919. fy += dy;
  56920. }
  56921. return textureArray;
  56922. };
  56923. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  56924. var theta = Math.atan2(vDir.z, vDir.x);
  56925. var phi = Math.acos(vDir.y);
  56926. while (theta < -Math.PI)
  56927. theta += 2 * Math.PI;
  56928. while (theta > Math.PI)
  56929. theta -= 2 * Math.PI;
  56930. var dx = theta / Math.PI;
  56931. var dy = phi / Math.PI;
  56932. // recenter.
  56933. dx = dx * 0.5 + 0.5;
  56934. var px = Math.round(dx * inputWidth);
  56935. if (px < 0)
  56936. px = 0;
  56937. else if (px >= inputWidth)
  56938. px = inputWidth - 1;
  56939. var py = Math.round(dy * inputHeight);
  56940. if (py < 0)
  56941. py = 0;
  56942. else if (py >= inputHeight)
  56943. py = inputHeight - 1;
  56944. var inputY = (inputHeight - py - 1);
  56945. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  56946. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  56947. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  56948. return {
  56949. r: r,
  56950. g: g,
  56951. b: b
  56952. };
  56953. };
  56954. PanoramaToCubeMapTools.FACE_FRONT = [
  56955. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  56956. new BABYLON.Vector3(1.0, -1.0, -1.0),
  56957. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  56958. new BABYLON.Vector3(1.0, 1.0, -1.0)
  56959. ];
  56960. PanoramaToCubeMapTools.FACE_BACK = [
  56961. new BABYLON.Vector3(1.0, -1.0, 1.0),
  56962. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  56963. new BABYLON.Vector3(1.0, 1.0, 1.0),
  56964. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  56965. ];
  56966. PanoramaToCubeMapTools.FACE_RIGHT = [
  56967. new BABYLON.Vector3(1.0, -1.0, -1.0),
  56968. new BABYLON.Vector3(1.0, -1.0, 1.0),
  56969. new BABYLON.Vector3(1.0, 1.0, -1.0),
  56970. new BABYLON.Vector3(1.0, 1.0, 1.0)
  56971. ];
  56972. PanoramaToCubeMapTools.FACE_LEFT = [
  56973. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  56974. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  56975. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  56976. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  56977. ];
  56978. PanoramaToCubeMapTools.FACE_DOWN = [
  56979. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  56980. new BABYLON.Vector3(1.0, 1.0, -1.0),
  56981. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  56982. new BABYLON.Vector3(1.0, 1.0, 1.0)
  56983. ];
  56984. PanoramaToCubeMapTools.FACE_UP = [
  56985. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  56986. new BABYLON.Vector3(1.0, -1.0, 1.0),
  56987. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  56988. new BABYLON.Vector3(1.0, -1.0, -1.0)
  56989. ];
  56990. return PanoramaToCubeMapTools;
  56991. }());
  56992. Internals.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  56993. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  56994. })(BABYLON || (BABYLON = {}));
  56995. var BABYLON;
  56996. (function (BABYLON) {
  56997. var Internals;
  56998. (function (Internals) {
  56999. ;
  57000. /**
  57001. * This groups tools to convert HDR texture to native colors array.
  57002. */
  57003. var HDRTools = (function () {
  57004. function HDRTools() {
  57005. }
  57006. HDRTools.Ldexp = function (mantissa, exponent) {
  57007. if (exponent > 1023) {
  57008. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  57009. }
  57010. if (exponent < -1074) {
  57011. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  57012. }
  57013. return mantissa * Math.pow(2, exponent);
  57014. };
  57015. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  57016. if (exponent > 0) {
  57017. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  57018. float32array[index + 0] = red * exponent;
  57019. float32array[index + 1] = green * exponent;
  57020. float32array[index + 2] = blue * exponent;
  57021. }
  57022. else {
  57023. float32array[index + 0] = 0;
  57024. float32array[index + 1] = 0;
  57025. float32array[index + 2] = 0;
  57026. }
  57027. };
  57028. HDRTools.readStringLine = function (uint8array, startIndex) {
  57029. var line = "";
  57030. var character = "";
  57031. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  57032. character = String.fromCharCode(uint8array[i]);
  57033. if (character == "\n") {
  57034. break;
  57035. }
  57036. line += character;
  57037. }
  57038. return line;
  57039. };
  57040. /**
  57041. * Reads header information from an RGBE texture stored in a native array.
  57042. * More information on this format are available here:
  57043. * https://en.wikipedia.org/wiki/RGBE_image_format
  57044. *
  57045. * @param uint8array The binary file stored in native array.
  57046. * @return The header information.
  57047. */
  57048. HDRTools.RGBE_ReadHeader = function (uint8array) {
  57049. var height = 0;
  57050. var width = 0;
  57051. var line = this.readStringLine(uint8array, 0);
  57052. if (line[0] != '#' || line[1] != '?') {
  57053. throw "Bad HDR Format.";
  57054. }
  57055. var endOfHeader = false;
  57056. var findFormat = false;
  57057. var lineIndex = 0;
  57058. do {
  57059. lineIndex += (line.length + 1);
  57060. line = this.readStringLine(uint8array, lineIndex);
  57061. if (line == "FORMAT=32-bit_rle_rgbe") {
  57062. findFormat = true;
  57063. }
  57064. else if (line.length == 0) {
  57065. endOfHeader = true;
  57066. }
  57067. } while (!endOfHeader);
  57068. if (!findFormat) {
  57069. throw "HDR Bad header format, unsupported FORMAT";
  57070. }
  57071. lineIndex += (line.length + 1);
  57072. line = this.readStringLine(uint8array, lineIndex);
  57073. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  57074. var match = sizeRegexp.exec(line);
  57075. // TODO. Support +Y and -X if needed.
  57076. if (match.length < 3) {
  57077. throw "HDR Bad header format, no size";
  57078. }
  57079. width = parseInt(match[2]);
  57080. height = parseInt(match[1]);
  57081. if (width < 8 || width > 0x7fff) {
  57082. throw "HDR Bad header format, unsupported size";
  57083. }
  57084. lineIndex += (line.length + 1);
  57085. return {
  57086. height: height,
  57087. width: width,
  57088. dataPosition: lineIndex
  57089. };
  57090. };
  57091. /**
  57092. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  57093. * This RGBE texture needs to store the information as a panorama.
  57094. *
  57095. * More information on this format are available here:
  57096. * https://en.wikipedia.org/wiki/RGBE_image_format
  57097. *
  57098. * @param buffer The binary file stored in an array buffer.
  57099. * @param size The expected size of the extracted cubemap.
  57100. * @return The Cube Map information.
  57101. */
  57102. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  57103. var uint8array = new Uint8Array(buffer);
  57104. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  57105. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  57106. var cubeMapData = Internals.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  57107. return cubeMapData;
  57108. };
  57109. /**
  57110. * Returns the pixels data extracted from an RGBE texture.
  57111. * This pixels will be stored left to right up to down in the R G B order in one array.
  57112. *
  57113. * More information on this format are available here:
  57114. * https://en.wikipedia.org/wiki/RGBE_image_format
  57115. *
  57116. * @param uint8array The binary file stored in an array buffer.
  57117. * @param hdrInfo The header information of the file.
  57118. * @return The pixels data in RGB right to left up to down order.
  57119. */
  57120. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  57121. // Keep for multi format supports.
  57122. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  57123. };
  57124. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  57125. var num_scanlines = hdrInfo.height;
  57126. var scanline_width = hdrInfo.width;
  57127. var a, b, c, d, count;
  57128. var dataIndex = hdrInfo.dataPosition;
  57129. var index = 0, endIndex = 0, i = 0;
  57130. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  57131. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  57132. // 3 channels of 4 bytes per pixel in float.
  57133. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  57134. var resultArray = new Float32Array(resultBuffer);
  57135. // read in each successive scanline
  57136. while (num_scanlines > 0) {
  57137. a = uint8array[dataIndex++];
  57138. b = uint8array[dataIndex++];
  57139. c = uint8array[dataIndex++];
  57140. d = uint8array[dataIndex++];
  57141. if (a != 2 || b != 2 || (c & 0x80)) {
  57142. // this file is not run length encoded
  57143. throw "HDR Bad header format, not RLE";
  57144. }
  57145. if (((c << 8) | d) != scanline_width) {
  57146. throw "HDR Bad header format, wrong scan line width";
  57147. }
  57148. index = 0;
  57149. // read each of the four channels for the scanline into the buffer
  57150. for (i = 0; i < 4; i++) {
  57151. endIndex = (i + 1) * scanline_width;
  57152. while (index < endIndex) {
  57153. a = uint8array[dataIndex++];
  57154. b = uint8array[dataIndex++];
  57155. if (a > 128) {
  57156. // a run of the same value
  57157. count = a - 128;
  57158. if ((count == 0) || (count > endIndex - index)) {
  57159. throw "HDR Bad Format, bad scanline data (run)";
  57160. }
  57161. while (count-- > 0) {
  57162. scanLineArray[index++] = b;
  57163. }
  57164. }
  57165. else {
  57166. // a non-run
  57167. count = a;
  57168. if ((count == 0) || (count > endIndex - index)) {
  57169. throw "HDR Bad Format, bad scanline data (non-run)";
  57170. }
  57171. scanLineArray[index++] = b;
  57172. if (--count > 0) {
  57173. for (var j = 0; j < count; j++) {
  57174. scanLineArray[index++] = uint8array[dataIndex++];
  57175. }
  57176. }
  57177. }
  57178. }
  57179. }
  57180. // now convert data from buffer into floats
  57181. for (i = 0; i < scanline_width; i++) {
  57182. a = scanLineArray[i];
  57183. b = scanLineArray[i + scanline_width];
  57184. c = scanLineArray[i + 2 * scanline_width];
  57185. d = scanLineArray[i + 3 * scanline_width];
  57186. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  57187. }
  57188. num_scanlines--;
  57189. }
  57190. return resultArray;
  57191. };
  57192. return HDRTools;
  57193. }());
  57194. Internals.HDRTools = HDRTools;
  57195. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  57196. })(BABYLON || (BABYLON = {}));
  57197. //_______________________________________________________________
  57198. // Extracted from CubeMapGen:
  57199. // https://code.google.com/archive/p/cubemapgen/
  57200. //
  57201. // Following https://seblagarde.wordpress.com/2012/06/10/amd-cubemapgen-for-physically-based-rendering/
  57202. //_______________________________________________________________
  57203. var BABYLON;
  57204. (function (BABYLON) {
  57205. var Internals;
  57206. (function (Internals) {
  57207. /**
  57208. * The bounding box information used during the conversion process.
  57209. */
  57210. var CMGBoundinBox = (function () {
  57211. function CMGBoundinBox() {
  57212. this.min = new BABYLON.Vector3(0, 0, 0);
  57213. this.max = new BABYLON.Vector3(0, 0, 0);
  57214. this.clear();
  57215. }
  57216. CMGBoundinBox.prototype.clear = function () {
  57217. this.min.x = CMGBoundinBox.MAX;
  57218. this.min.y = CMGBoundinBox.MAX;
  57219. this.min.z = CMGBoundinBox.MAX;
  57220. this.max.x = CMGBoundinBox.MIN;
  57221. this.max.y = CMGBoundinBox.MIN;
  57222. this.max.z = CMGBoundinBox.MIN;
  57223. };
  57224. CMGBoundinBox.prototype.augment = function (x, y, z) {
  57225. this.min.x = Math.min(this.min.x, x);
  57226. this.min.y = Math.min(this.min.y, y);
  57227. this.min.z = Math.min(this.min.z, z);
  57228. this.max.x = Math.max(this.max.x, x);
  57229. this.max.y = Math.max(this.max.y, y);
  57230. this.max.z = Math.max(this.max.z, z);
  57231. };
  57232. CMGBoundinBox.prototype.clampMin = function (x, y, z) {
  57233. this.min.x = Math.max(this.min.x, x);
  57234. this.min.y = Math.max(this.min.y, y);
  57235. this.min.z = Math.max(this.min.z, z);
  57236. };
  57237. CMGBoundinBox.prototype.clampMax = function (x, y, z) {
  57238. this.max.x = Math.min(this.max.x, x);
  57239. this.max.y = Math.min(this.max.y, y);
  57240. this.max.z = Math.min(this.max.z, z);
  57241. };
  57242. CMGBoundinBox.prototype.empty = function () {
  57243. if ((this.min.x > this.max.y) ||
  57244. (this.min.y > this.max.y) ||
  57245. (this.min.z > this.max.y)) {
  57246. return true;
  57247. }
  57248. else {
  57249. return false;
  57250. }
  57251. };
  57252. CMGBoundinBox.MAX = Number.MAX_VALUE;
  57253. CMGBoundinBox.MIN = Number.MIN_VALUE;
  57254. return CMGBoundinBox;
  57255. }());
  57256. /**
  57257. * Helper class to PreProcess a cubemap in order to generate mipmap according to the level of blur
  57258. * required by the glossinees of a material.
  57259. *
  57260. * This only supports the cosine drop power as well as Warp fixup generation method.
  57261. *
  57262. * This is using the process from CubeMapGen described here:
  57263. * https://seblagarde.wordpress.com/2012/06/10/amd-cubemapgen-for-physically-based-rendering/
  57264. */
  57265. var PMREMGenerator = (function () {
  57266. /**
  57267. * Constructor of the generator.
  57268. *
  57269. * @param input The different faces data from the original cubemap in the order X+ X- Y+ Y- Z+ Z-
  57270. * @param inputSize The size of the cubemap faces
  57271. * @param outputSize The size of the output cubemap faces
  57272. * @param maxNumMipLevels The max number of mip map to generate (0 means all)
  57273. * @param numChannels The number of channels stored in the cubemap (3 for RBGE for instance)
  57274. * @param isFloat Specifies if the input texture is in float or int (hdr is usually in float)
  57275. * @param specularPower The max specular level of the desired cubemap
  57276. * @param cosinePowerDropPerMip The amount of drop the specular power will follow on each mip
  57277. * @param excludeBase Specifies wether to process the level 0 (original level) or not
  57278. * @param fixup Specifies wether to apply the edge fixup algorythm or not
  57279. */
  57280. function PMREMGenerator(input, inputSize, outputSize, maxNumMipLevels, numChannels, isFloat, specularPower, cosinePowerDropPerMip, excludeBase, fixup) {
  57281. this.input = input;
  57282. this.inputSize = inputSize;
  57283. this.outputSize = outputSize;
  57284. this.maxNumMipLevels = maxNumMipLevels;
  57285. this.numChannels = numChannels;
  57286. this.isFloat = isFloat;
  57287. this.specularPower = specularPower;
  57288. this.cosinePowerDropPerMip = cosinePowerDropPerMip;
  57289. this.excludeBase = excludeBase;
  57290. this.fixup = fixup;
  57291. this._outputSurface = [];
  57292. this._numMipLevels = 0;
  57293. }
  57294. /**
  57295. * Launches the filter process and return the result.
  57296. *
  57297. * @return the filter cubemap in the form mip0 [faces1..6] .. mipN [faces1..6]
  57298. */
  57299. PMREMGenerator.prototype.filterCubeMap = function () {
  57300. // Init cubemap processor
  57301. this.init();
  57302. // Filters the cubemap
  57303. this.filterCubeMapMipChain();
  57304. // Returns the filtered mips.
  57305. return this._outputSurface;
  57306. };
  57307. PMREMGenerator.prototype.init = function () {
  57308. var i;
  57309. var j;
  57310. var mipLevelSize;
  57311. //if nax num mip levels is set to 0, set it to generate the entire mip chain
  57312. if (this.maxNumMipLevels == 0) {
  57313. this.maxNumMipLevels = PMREMGenerator.CP_MAX_MIPLEVELS;
  57314. }
  57315. //first miplevel size
  57316. mipLevelSize = this.outputSize;
  57317. //Iterate over mip chain, and init ArrayBufferView for mip-chain
  57318. for (j = 0; j < this.maxNumMipLevels; j++) {
  57319. this._outputSurface.length++;
  57320. this._outputSurface[j] = [];
  57321. //Iterate over faces for output images
  57322. for (i = 0; i < 6; i++) {
  57323. this._outputSurface[j].length++;
  57324. // Initializes a new array for the output.
  57325. if (this.isFloat) {
  57326. this._outputSurface[j][i] = new Float32Array(mipLevelSize * mipLevelSize * this.numChannels);
  57327. }
  57328. else {
  57329. this._outputSurface[j][i] = new Uint32Array(mipLevelSize * mipLevelSize * this.numChannels);
  57330. }
  57331. }
  57332. //next mip level is half size
  57333. mipLevelSize >>= 1;
  57334. this._numMipLevels++;
  57335. //terminate if mip chain becomes too small
  57336. if (mipLevelSize == 0) {
  57337. this.maxNumMipLevels = j;
  57338. return;
  57339. }
  57340. }
  57341. };
  57342. //--------------------------------------------------------------------------------------
  57343. //Cube map filtering and mip chain generation.
  57344. // the cube map filtereing is specified using a number of parameters:
  57345. // Filtering per miplevel is specified using 2D cone angle (in degrees) that
  57346. // indicates the region of the hemisphere to filter over for each tap.
  57347. //
  57348. // Note that the top mip level is also a filtered version of the original input images
  57349. // as well in order to create mip chains for diffuse environment illumination.
  57350. // The cone angle for the top level is specified by a_BaseAngle. This can be used to
  57351. // generate mipchains used to store the resutls of preintegration across the hemisphere.
  57352. //
  57353. // Then the mip angle used to genreate the next level of the mip chain from the first level
  57354. // is a_InitialMipAngle
  57355. //
  57356. // The angle for the subsequent levels of the mip chain are specified by their parents
  57357. // filtering angle and a per-level scale and bias
  57358. // newAngle = oldAngle * a_MipAnglePerLevelScale;
  57359. //
  57360. //--------------------------------------------------------------------------------------
  57361. PMREMGenerator.prototype.filterCubeMapMipChain = function () {
  57362. // First, take count of the lighting model to modify SpecularPower
  57363. // 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;
  57364. // var refSpecularPower = this.specularPower; // Only Phong BRDF yet. This explains the line below using this.specularpower.
  57365. //Cone angle start (for generating subsequent mip levels)
  57366. var currentSpecularPower = this.specularPower;
  57367. //Build filter lookup tables based on the source miplevel size
  57368. this.precomputeFilterLookupTables(this.inputSize);
  57369. // Note that we need to filter the first level before generating mipmap
  57370. // So LevelIndex == 0 is base filtering hen LevelIndex > 0 is mipmap generation
  57371. for (var levelIndex = 0; levelIndex < this._numMipLevels; levelIndex++) {
  57372. // TODO : Write a function to copy and scale the base mipmap in output
  57373. // I am just lazy here and just put a high specular power value, and do some if.
  57374. if (this.excludeBase && (levelIndex == 0)) {
  57375. // 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).
  57376. currentSpecularPower = 100000.0;
  57377. }
  57378. // Special case for cosine power mipmap chain. For quality requirement, we always process the current mipmap from the top mipmap
  57379. var srcCubeImage = this.input;
  57380. var dstCubeImage = this._outputSurface[levelIndex];
  57381. var dstSize = this.outputSize >> levelIndex;
  57382. // Compute required angle.
  57383. var angle = this.getBaseFilterAngle(currentSpecularPower);
  57384. // filter cube surfaces
  57385. this.filterCubeSurfaces(srcCubeImage, this.inputSize, dstCubeImage, dstSize, angle, currentSpecularPower);
  57386. // fix seams
  57387. if (this.fixup) {
  57388. this.fixupCubeEdges(dstCubeImage, dstSize);
  57389. }
  57390. // Decrease the specular power to generate the mipmap chain
  57391. // TODO : Use another method for Exclude (see first comment at start of the function
  57392. if (this.excludeBase && (levelIndex == 0)) {
  57393. currentSpecularPower = this.specularPower;
  57394. }
  57395. currentSpecularPower *= this.cosinePowerDropPerMip;
  57396. }
  57397. };
  57398. //--------------------------------------------------------------------------------------
  57399. // This function return the BaseFilterAngle require by PMREMGenerator to its FilterExtends
  57400. // It allow to optimize the texel to access base on the specular power.
  57401. //--------------------------------------------------------------------------------------
  57402. PMREMGenerator.prototype.getBaseFilterAngle = function (cosinePower) {
  57403. // We want to find the alpha such that:
  57404. // cos(alpha)^cosinePower = epsilon
  57405. // That's: acos(epsilon^(1/cosinePower))
  57406. var threshold = 0.000001; // Empirical threshold (Work perfectly, didn't check for a more big number, may get some performance and still god approximation)
  57407. var angle = 180.0;
  57408. angle = Math.acos(Math.pow(threshold, 1.0 / cosinePower));
  57409. angle *= 180.0 / Math.PI; // Convert to degree
  57410. angle *= 2.0; // * 2.0f because PMREMGenerator divide by 2 later
  57411. return angle;
  57412. };
  57413. //--------------------------------------------------------------------------------------
  57414. //Builds the following lookup tables prior to filtering:
  57415. // -normalizer cube map
  57416. // -tap weight lookup table
  57417. //
  57418. //--------------------------------------------------------------------------------------
  57419. PMREMGenerator.prototype.precomputeFilterLookupTables = function (srcCubeMapWidth) {
  57420. var srcTexelAngle;
  57421. var iCubeFace;
  57422. //clear pre-existing normalizer cube map
  57423. this._normCubeMap = [];
  57424. //Normalized vectors per cubeface and per-texel solid angle
  57425. this.buildNormalizerSolidAngleCubemap(srcCubeMapWidth);
  57426. };
  57427. //--------------------------------------------------------------------------------------
  57428. //Builds a normalizer cubemap, with the texels solid angle stored in the fourth component
  57429. //
  57430. //Takes in a cube face size, and an array of 6 surfaces to write the cube faces into
  57431. //
  57432. //Note that this normalizer cube map stores the vectors in unbiased -1 to 1 range.
  57433. // if _bx2 style scaled and biased vectors are needed, uncomment the SCALE and BIAS
  57434. // below
  57435. //--------------------------------------------------------------------------------------
  57436. PMREMGenerator.prototype.buildNormalizerSolidAngleCubemap = function (size) {
  57437. var iCubeFace;
  57438. var u;
  57439. var v;
  57440. //iterate over cube faces
  57441. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  57442. //First three channels for norm cube, and last channel for solid angle
  57443. this._normCubeMap.push(new Float32Array(size * size * 4));
  57444. //fast texture walk, build normalizer cube map
  57445. var facesData = this.input[iCubeFace];
  57446. for (v = 0; v < size; v++) {
  57447. for (u = 0; u < size; u++) {
  57448. var vect = this.texelCoordToVect(iCubeFace, u, v, size, this.fixup);
  57449. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 0] = vect.x;
  57450. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 1] = vect.y;
  57451. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 2] = vect.z;
  57452. var solidAngle = this.texelCoordSolidAngle(iCubeFace, u, v, size);
  57453. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 4] = solidAngle;
  57454. }
  57455. }
  57456. }
  57457. };
  57458. //--------------------------------------------------------------------------------------
  57459. // Convert cubemap face texel coordinates and face idx to 3D vector
  57460. // note the U and V coords are integer coords and range from 0 to size-1
  57461. // this routine can be used to generate a normalizer cube map
  57462. //--------------------------------------------------------------------------------------
  57463. // SL BEGIN
  57464. PMREMGenerator.prototype.texelCoordToVect = function (faceIdx, u, v, size, fixup) {
  57465. var nvcU;
  57466. var nvcV;
  57467. var tempVec;
  57468. // Change from original AMD code
  57469. // transform from [0..res - 1] to [- (1 - 1 / res) .. (1 - 1 / res)]
  57470. // + 0.5f is for texel center addressing
  57471. nvcU = (2.0 * (u + 0.5) / size) - 1.0;
  57472. nvcV = (2.0 * (v + 0.5) / size) - 1.0;
  57473. // warp fixup
  57474. if (fixup && size > 1) {
  57475. // Code from Nvtt : http://code.google.com/p/nvidia-texture-tools/source/browse/trunk/src/nvtt/CubeSurface.cpp
  57476. var a = Math.pow(size, 2.0) / Math.pow(size - 1, 3.0);
  57477. nvcU = a * Math.pow(nvcU, 3) + nvcU;
  57478. nvcV = a * Math.pow(nvcV, 3) + nvcV;
  57479. }
  57480. // Get current vector
  57481. // generate x,y,z vector (xform 2d NVC coord to 3D vector)
  57482. // U contribution
  57483. var UVec = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_UDIR];
  57484. PMREMGenerator._vectorTemp.x = UVec[0] * nvcU;
  57485. PMREMGenerator._vectorTemp.y = UVec[1] * nvcU;
  57486. PMREMGenerator._vectorTemp.z = UVec[2] * nvcU;
  57487. // V contribution and Sum
  57488. var VVec = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_VDIR];
  57489. PMREMGenerator._vectorTemp.x += VVec[0] * nvcV;
  57490. PMREMGenerator._vectorTemp.y += VVec[1] * nvcV;
  57491. PMREMGenerator._vectorTemp.z += VVec[2] * nvcV;
  57492. //add face axis
  57493. var faceAxis = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_FACEAXIS];
  57494. PMREMGenerator._vectorTemp.x += faceAxis[0];
  57495. PMREMGenerator._vectorTemp.y += faceAxis[1];
  57496. PMREMGenerator._vectorTemp.z += faceAxis[2];
  57497. //normalize vector
  57498. PMREMGenerator._vectorTemp.normalize();
  57499. return PMREMGenerator._vectorTemp;
  57500. };
  57501. //--------------------------------------------------------------------------------------
  57502. // Convert 3D vector to cubemap face texel coordinates and face idx
  57503. // note the U and V coords are integer coords and range from 0 to size-1
  57504. // this routine can be used to generate a normalizer cube map
  57505. //
  57506. // returns face IDX and texel coords
  57507. //--------------------------------------------------------------------------------------
  57508. // SL BEGIN
  57509. /*
  57510. Mapping Texture Coordinates to Cube Map Faces
  57511. Because there are multiple faces, the mapping of texture coordinates to positions on cube map faces
  57512. is more complicated than the other texturing targets. The EXT_texture_cube_map extension is purposefully
  57513. designed to be consistent with DirectX 7's cube map arrangement. This is also consistent with the cube
  57514. map arrangement in Pixar's RenderMan package.
  57515. For cube map texturing, the (s,t,r) texture coordinates are treated as a direction vector (rx,ry,rz)
  57516. emanating from the center of a cube. (The q coordinate can be ignored since it merely scales the vector
  57517. without affecting the direction.) At texture application time, the interpolated per-fragment (s,t,r)
  57518. selects one of the cube map face's 2D mipmap sets based on the largest magnitude coordinate direction
  57519. the major axis direction). The target column in the table below explains how the major axis direction
  57520. maps to the 2D image of a particular cube map target.
  57521. major axis
  57522. direction target sc tc ma
  57523. ---------- --------------------------------- --- --- ---
  57524. +rx GL_TEXTURE_CUBE_MAP_POSITIVE_X_EXT -rz -ry rx
  57525. -rx GL_TEXTURE_CUBE_MAP_NEGATIVE_X_EXT +rz -ry rx
  57526. +ry GL_TEXTURE_CUBE_MAP_POSITIVE_Y_EXT +rx +rz ry
  57527. -ry GL_TEXTURE_CUBE_MAP_NEGATIVE_Y_EXT +rx -rz ry
  57528. +rz GL_TEXTURE_CUBE_MAP_POSITIVE_Z_EXT +rx -ry rz
  57529. -rz GL_TEXTURE_CUBE_MAP_NEGATIVE_Z_EXT -rx -ry rz
  57530. Using the sc, tc, and ma determined by the major axis direction as specified in the table above,
  57531. an updated (s,t) is calculated as follows
  57532. s = ( sc/|ma| + 1 ) / 2
  57533. t = ( tc/|ma| + 1 ) / 2
  57534. If |ma| is zero or very nearly zero, the results of the above two equations need not be defined
  57535. (though the result may not lead to GL interruption or termination). Once the cube map face's 2D mipmap
  57536. set and (s,t) is determined, texture fetching and filtering proceeds like standard OpenGL 2D texturing.
  57537. */
  57538. // Note this method return U and V in range from 0 to size-1
  57539. // SL END
  57540. // Store the information in vector3 for convenience (faceindex, u, v)
  57541. PMREMGenerator.prototype.vectToTexelCoord = function (x, y, z, size) {
  57542. var maxCoord;
  57543. var faceIdx;
  57544. //absolute value 3
  57545. var absX = Math.abs(x);
  57546. var absY = Math.abs(y);
  57547. var absZ = Math.abs(z);
  57548. if (absX >= absY && absX >= absZ) {
  57549. maxCoord = absX;
  57550. if (x >= 0) {
  57551. faceIdx = PMREMGenerator.CP_FACE_X_POS;
  57552. }
  57553. else {
  57554. faceIdx = PMREMGenerator.CP_FACE_X_NEG;
  57555. }
  57556. }
  57557. else if (absY >= absX && absY >= absZ) {
  57558. maxCoord = absY;
  57559. if (y >= 0) {
  57560. faceIdx = PMREMGenerator.CP_FACE_Y_POS;
  57561. }
  57562. else {
  57563. faceIdx = PMREMGenerator.CP_FACE_Y_NEG;
  57564. }
  57565. }
  57566. else {
  57567. maxCoord = absZ;
  57568. if (z >= 0) {
  57569. faceIdx = PMREMGenerator.CP_FACE_Z_POS;
  57570. }
  57571. else {
  57572. faceIdx = PMREMGenerator.CP_FACE_Z_NEG;
  57573. }
  57574. }
  57575. //divide through by max coord so face vector lies on cube face
  57576. var scale = 1 / maxCoord;
  57577. x *= scale;
  57578. y *= scale;
  57579. z *= scale;
  57580. var temp = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_UDIR];
  57581. var nvcU = temp[0] * x + temp[1] * y + temp[2] * z;
  57582. temp = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_VDIR];
  57583. var nvcV = temp[0] * x + temp[1] * y + temp[2] * z;
  57584. // Modify original AMD code to return value from 0 to Size - 1
  57585. var u = Math.floor((size - 1) * 0.5 * (nvcU + 1.0));
  57586. var v = Math.floor((size - 1) * 0.5 * (nvcV + 1.0));
  57587. PMREMGenerator._vectorTemp.x = faceIdx;
  57588. PMREMGenerator._vectorTemp.y = u;
  57589. PMREMGenerator._vectorTemp.z = v;
  57590. return PMREMGenerator._vectorTemp;
  57591. };
  57592. //--------------------------------------------------------------------------------------
  57593. //Original code from Ignacio CastaÒo
  57594. // This formula is from Manne ÷hrstrˆm's thesis.
  57595. // Take two coordiantes in the range [-1, 1] that define a portion of a
  57596. // cube face and return the area of the projection of that portion on the
  57597. // surface of the sphere.
  57598. //--------------------------------------------------------------------------------------
  57599. PMREMGenerator.prototype.areaElement = function (x, y) {
  57600. return Math.atan2(x * y, Math.sqrt(x * x + y * y + 1));
  57601. };
  57602. PMREMGenerator.prototype.texelCoordSolidAngle = function (faceIdx, u, v, size) {
  57603. // transform from [0..res - 1] to [- (1 - 1 / res) .. (1 - 1 / res)]
  57604. // (+ 0.5f is for texel center addressing)
  57605. u = (2.0 * (u + 0.5) / size) - 1.0;
  57606. v = (2.0 * (v + 0.5) / size) - 1.0;
  57607. // Shift from a demi texel, mean 1.0f / a_Size with U and V in [-1..1]
  57608. var invResolution = 1.0 / size;
  57609. // U and V are the -1..1 texture coordinate on the current face.
  57610. // Get projected area for this texel
  57611. var x0 = u - invResolution;
  57612. var y0 = v - invResolution;
  57613. var x1 = u + invResolution;
  57614. var y1 = v + invResolution;
  57615. var solidAngle = this.areaElement(x0, y0) - this.areaElement(x0, y1) - this.areaElement(x1, y0) + this.areaElement(x1, y1);
  57616. return solidAngle;
  57617. };
  57618. //--------------------------------------------------------------------------------------
  57619. //The key to the speed of these filtering routines is to quickly define a per-face
  57620. // bounding box of pixels which enclose all the taps in the filter kernel efficiently.
  57621. // Later these pixels are selectively processed based on their dot products to see if
  57622. // they reside within the filtering cone.
  57623. //
  57624. //This is done by computing the smallest per-texel angle to get a conservative estimate
  57625. // of the number of texels needed to be covered in width and height order to filter the
  57626. // region. the bounding box for the center taps face is defined first, and if the
  57627. // filtereing region bleeds onto the other faces, bounding boxes for the other faces are
  57628. // defined next
  57629. //--------------------------------------------------------------------------------------
  57630. PMREMGenerator.prototype.filterCubeSurfaces = function (srcCubeMap, srcSize, dstCubeMap, dstSize, filterConeAngle, specularPower) {
  57631. // note that pixels within these regions may be rejected
  57632. // based on the anlge
  57633. var iCubeFace;
  57634. var u;
  57635. var v;
  57636. // bounding box per face to specify region to process
  57637. var filterExtents = [];
  57638. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  57639. filterExtents.push(new CMGBoundinBox());
  57640. }
  57641. // min angle a src texel can cover (in degrees)
  57642. var srcTexelAngle = (180.0 / (Math.PI) * Math.atan2(1.0, srcSize));
  57643. // angle about center tap to define filter cone
  57644. // filter angle is 1/2 the cone angle
  57645. var filterAngle = filterConeAngle / 2.0;
  57646. //ensure filter angle is larger than a texel
  57647. if (filterAngle < srcTexelAngle) {
  57648. filterAngle = srcTexelAngle;
  57649. }
  57650. //ensure filter cone is always smaller than the hemisphere
  57651. if (filterAngle > 90.0) {
  57652. filterAngle = 90.0;
  57653. }
  57654. // the maximum number of texels in 1D the filter cone angle will cover
  57655. // used to determine bounding box size for filter extents
  57656. var filterSize = Math.ceil(filterAngle / srcTexelAngle);
  57657. // ensure conservative region always covers at least one texel
  57658. if (filterSize < 1) {
  57659. filterSize = 1;
  57660. }
  57661. // dotProdThresh threshold based on cone angle to determine whether or not taps
  57662. // reside within the cone angle
  57663. var dotProdThresh = Math.cos((Math.PI / 180.0) * filterAngle);
  57664. // process required faces
  57665. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  57666. //iterate over dst cube map face texel
  57667. for (v = 0; v < dstSize; v++) {
  57668. for (u = 0; u < dstSize; u++) {
  57669. //get center tap direction
  57670. var centerTapDir = this.texelCoordToVect(iCubeFace, u, v, dstSize, this.fixup).clone();
  57671. //clear old per-face filter extents
  57672. this.clearFilterExtents(filterExtents);
  57673. //define per-face filter extents
  57674. this.determineFilterExtents(centerTapDir, srcSize, filterSize, filterExtents);
  57675. //perform filtering of src faces using filter extents
  57676. var vect = this.processFilterExtents(centerTapDir, dotProdThresh, filterExtents, srcCubeMap, srcSize, specularPower);
  57677. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 0] = vect.x;
  57678. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 1] = vect.y;
  57679. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 2] = vect.z;
  57680. }
  57681. }
  57682. }
  57683. };
  57684. //--------------------------------------------------------------------------------------
  57685. //Clear filter extents for the 6 cube map faces
  57686. //--------------------------------------------------------------------------------------
  57687. PMREMGenerator.prototype.clearFilterExtents = function (filterExtents) {
  57688. for (var iCubeFaces = 0; iCubeFaces < 6; iCubeFaces++) {
  57689. filterExtents[iCubeFaces].clear();
  57690. }
  57691. };
  57692. //--------------------------------------------------------------------------------------
  57693. //Define per-face bounding box filter extents
  57694. //
  57695. // These define conservative texel regions in each of the faces the filter can possibly
  57696. // process. When the pixels in the regions are actually processed, the dot product
  57697. // between the tap vector and the center tap vector is used to determine the weight of
  57698. // the tap and whether or not the tap is within the cone.
  57699. //
  57700. //--------------------------------------------------------------------------------------
  57701. PMREMGenerator.prototype.determineFilterExtents = function (centerTapDir, srcSize, bboxSize, filterExtents) {
  57702. //neighboring face and bleed over amount, and width of BBOX for
  57703. // left, right, top, and bottom edges of this face
  57704. var bleedOverAmount = [0, 0, 0, 0];
  57705. var bleedOverBBoxMin = [0, 0, 0, 0];
  57706. var bleedOverBBoxMax = [0, 0, 0, 0];
  57707. var neighborFace;
  57708. var neighborEdge;
  57709. var oppositeFaceIdx;
  57710. //get face idx, and u, v info from center tap dir
  57711. var result = this.vectToTexelCoord(centerTapDir.x, centerTapDir.y, centerTapDir.z, srcSize);
  57712. var faceIdx = result.x;
  57713. var u = result.y;
  57714. var v = result.z;
  57715. //define bbox size within face
  57716. filterExtents[faceIdx].augment(u - bboxSize, v - bboxSize, 0);
  57717. filterExtents[faceIdx].augment(u + bboxSize, v + bboxSize, 0);
  57718. filterExtents[faceIdx].clampMin(0, 0, 0);
  57719. filterExtents[faceIdx].clampMax(srcSize - 1, srcSize - 1, 0);
  57720. //u and v extent in face corresponding to center tap
  57721. var minU = filterExtents[faceIdx].min.x;
  57722. var minV = filterExtents[faceIdx].min.y;
  57723. var maxU = filterExtents[faceIdx].max.x;
  57724. var maxV = filterExtents[faceIdx].max.y;
  57725. //bleed over amounts for face across u=0 edge (left)
  57726. bleedOverAmount[0] = (bboxSize - u);
  57727. bleedOverBBoxMin[0] = minV;
  57728. bleedOverBBoxMax[0] = maxV;
  57729. //bleed over amounts for face across u=1 edge (right)
  57730. bleedOverAmount[1] = (u + bboxSize) - (srcSize - 1);
  57731. bleedOverBBoxMin[1] = minV;
  57732. bleedOverBBoxMax[1] = maxV;
  57733. //bleed over to face across v=0 edge (up)
  57734. bleedOverAmount[2] = (bboxSize - v);
  57735. bleedOverBBoxMin[2] = minU;
  57736. bleedOverBBoxMax[2] = maxU;
  57737. //bleed over to face across v=1 edge (down)
  57738. bleedOverAmount[3] = (v + bboxSize) - (srcSize - 1);
  57739. bleedOverBBoxMin[3] = minU;
  57740. bleedOverBBoxMax[3] = maxU;
  57741. //compute bleed over regions in neighboring faces
  57742. for (var i = 0; i < 4; i++) {
  57743. if (bleedOverAmount[i] > 0) {
  57744. neighborFace = PMREMGenerator._sgCubeNgh[faceIdx][i][0];
  57745. neighborEdge = PMREMGenerator._sgCubeNgh[faceIdx][i][1];
  57746. //For certain types of edge abutments, the bleedOverBBoxMin, and bleedOverBBoxMax need to
  57747. // be flipped: the cases are
  57748. // if a left edge mates with a left or bottom edge on the neighbor
  57749. // if a top edge mates with a top or right edge on the neighbor
  57750. // if a right edge mates with a right or top edge on the neighbor
  57751. // if a bottom edge mates with a bottom or left edge on the neighbor
  57752. //Seeing as the edges are enumerated as follows
  57753. // left =0
  57754. // right =1
  57755. // top =2
  57756. // bottom =3
  57757. //
  57758. // so if the edge enums are the same, or the sum of the enums == 3,
  57759. // the bbox needs to be flipped
  57760. if ((i == neighborEdge) || ((i + neighborEdge) == 3)) {
  57761. bleedOverBBoxMin[i] = (srcSize - 1) - bleedOverBBoxMin[i];
  57762. bleedOverBBoxMax[i] = (srcSize - 1) - bleedOverBBoxMax[i];
  57763. }
  57764. //The way the bounding box is extended onto the neighboring face
  57765. // depends on which edge of neighboring face abuts with this one
  57766. switch (PMREMGenerator._sgCubeNgh[faceIdx][i][1]) {
  57767. case PMREMGenerator.CP_EDGE_LEFT:
  57768. filterExtents[neighborFace].augment(0, bleedOverBBoxMin[i], 0);
  57769. filterExtents[neighborFace].augment(bleedOverAmount[i], bleedOverBBoxMax[i], 0);
  57770. break;
  57771. case PMREMGenerator.CP_EDGE_RIGHT:
  57772. filterExtents[neighborFace].augment((srcSize - 1), bleedOverBBoxMin[i], 0);
  57773. filterExtents[neighborFace].augment((srcSize - 1) - bleedOverAmount[i], bleedOverBBoxMax[i], 0);
  57774. break;
  57775. case PMREMGenerator.CP_EDGE_TOP:
  57776. filterExtents[neighborFace].augment(bleedOverBBoxMin[i], 0, 0);
  57777. filterExtents[neighborFace].augment(bleedOverBBoxMax[i], bleedOverAmount[i], 0);
  57778. break;
  57779. case PMREMGenerator.CP_EDGE_BOTTOM:
  57780. filterExtents[neighborFace].augment(bleedOverBBoxMin[i], (srcSize - 1), 0);
  57781. filterExtents[neighborFace].augment(bleedOverBBoxMax[i], (srcSize - 1) - bleedOverAmount[i], 0);
  57782. break;
  57783. }
  57784. //clamp filter extents in non-center tap faces to remain within surface
  57785. filterExtents[neighborFace].clampMin(0, 0, 0);
  57786. filterExtents[neighborFace].clampMax(srcSize - 1, srcSize - 1, 0);
  57787. }
  57788. //If the bleed over amount bleeds past the adjacent face onto the opposite face
  57789. // from the center tap face, then process the opposite face entirely for now.
  57790. //Note that the cases in which this happens, what usually happens is that
  57791. // more than one edge bleeds onto the opposite face, and the bounding box
  57792. // encompasses the entire cube map face.
  57793. if (bleedOverAmount[i] > srcSize) {
  57794. //determine opposite face
  57795. switch (faceIdx) {
  57796. case PMREMGenerator.CP_FACE_X_POS:
  57797. oppositeFaceIdx = PMREMGenerator.CP_FACE_X_NEG;
  57798. break;
  57799. case PMREMGenerator.CP_FACE_X_NEG:
  57800. oppositeFaceIdx = PMREMGenerator.CP_FACE_X_POS;
  57801. break;
  57802. case PMREMGenerator.CP_FACE_Y_POS:
  57803. oppositeFaceIdx = PMREMGenerator.CP_FACE_Y_NEG;
  57804. break;
  57805. case PMREMGenerator.CP_FACE_Y_NEG:
  57806. oppositeFaceIdx = PMREMGenerator.CP_FACE_Y_POS;
  57807. break;
  57808. case PMREMGenerator.CP_FACE_Z_POS:
  57809. oppositeFaceIdx = PMREMGenerator.CP_FACE_Z_NEG;
  57810. break;
  57811. case PMREMGenerator.CP_FACE_Z_NEG:
  57812. oppositeFaceIdx = PMREMGenerator.CP_FACE_Z_POS;
  57813. break;
  57814. default:
  57815. break;
  57816. }
  57817. //just encompass entire face for now
  57818. filterExtents[oppositeFaceIdx].augment(0, 0, 0);
  57819. filterExtents[oppositeFaceIdx].augment((srcSize - 1), (srcSize - 1), 0);
  57820. }
  57821. }
  57822. };
  57823. //--------------------------------------------------------------------------------------
  57824. //ProcessFilterExtents
  57825. // Process bounding box in each cube face
  57826. //
  57827. //--------------------------------------------------------------------------------------
  57828. PMREMGenerator.prototype.processFilterExtents = function (centerTapDir, dotProdThresh, filterExtents, srcCubeMap, srcSize, specularPower) {
  57829. //accumulators are 64-bit floats in order to have the precision needed
  57830. // over a summation of a large number of pixels
  57831. var dstAccum = [0, 0, 0, 0];
  57832. var weightAccum = 0;
  57833. var k = 0;
  57834. var nSrcChannels = this.numChannels;
  57835. // norm cube map and srcCubeMap have same face width
  57836. var faceWidth = srcSize;
  57837. //amount to add to pointer to move to next scanline in images
  57838. var normCubePitch = faceWidth * 4; // 4 channels in normCubeMap.
  57839. var srcCubePitch = faceWidth * this.numChannels; // numChannels correponds to the cubemap number of channel
  57840. var IsPhongBRDF = 1; // Only works in Phong BRDF yet.
  57841. //(a_LightingModel == CP_LIGHTINGMODEL_PHONG_BRDF || a_LightingModel == CP_LIGHTINGMODEL_BLINN_BRDF) ? 1 : 0; // This value will be added to the specular power
  57842. // iterate over cubefaces
  57843. for (var iFaceIdx = 0; iFaceIdx < 6; iFaceIdx++) {
  57844. //if bbox is non empty
  57845. if (!filterExtents[iFaceIdx].empty()) {
  57846. var uStart = filterExtents[iFaceIdx].min.x;
  57847. var vStart = filterExtents[iFaceIdx].min.y;
  57848. var uEnd = filterExtents[iFaceIdx].max.x;
  57849. var vEnd = filterExtents[iFaceIdx].max.y;
  57850. var startIndexNormCubeMap = (4 * ((vStart * faceWidth) + uStart));
  57851. var startIndexSrcCubeMap = (this.numChannels * ((vStart * faceWidth) + uStart));
  57852. //note that <= is used to ensure filter extents always encompass at least one pixel if bbox is non empty
  57853. for (var v = vStart; v <= vEnd; v++) {
  57854. var normCubeRowWalk = 0;
  57855. var srcCubeRowWalk = 0;
  57856. for (var u = uStart; u <= uEnd; u++) {
  57857. //pointer to direction in cube map associated with texel
  57858. var texelVectX = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 0];
  57859. var texelVectY = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 1];
  57860. var texelVectZ = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 2];
  57861. //check dot product to see if texel is within cone
  57862. var tapDotProd = texelVectX * centerTapDir.x +
  57863. texelVectY * centerTapDir.y +
  57864. texelVectZ * centerTapDir.z;
  57865. if (tapDotProd >= dotProdThresh && tapDotProd > 0.0) {
  57866. //solid angle stored in 4th channel of normalizer/solid angle cube map
  57867. var weight = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 3];
  57868. // Here we decide if we use a Phong/Blinn or a Phong/Blinn BRDF.
  57869. // Phong/Blinn BRDF is just the Phong/Blinn model multiply by the cosine of the lambert law
  57870. // so just adding one to specularpower do the trick.
  57871. weight *= Math.pow(tapDotProd, (specularPower + IsPhongBRDF));
  57872. //iterate over channels
  57873. for (k = 0; k < nSrcChannels; k++) {
  57874. dstAccum[k] += weight * srcCubeMap[iFaceIdx][startIndexSrcCubeMap + srcCubeRowWalk];
  57875. srcCubeRowWalk++;
  57876. }
  57877. weightAccum += weight; //accumulate weight
  57878. }
  57879. else {
  57880. //step across source pixel
  57881. srcCubeRowWalk += nSrcChannels;
  57882. }
  57883. normCubeRowWalk += 4; // 4 channels per norm cube map.
  57884. }
  57885. startIndexNormCubeMap += normCubePitch;
  57886. startIndexSrcCubeMap += srcCubePitch;
  57887. }
  57888. }
  57889. }
  57890. //divide through by weights if weight is non zero
  57891. if (weightAccum != 0.0) {
  57892. PMREMGenerator._vectorTemp.x = (dstAccum[0] / weightAccum);
  57893. PMREMGenerator._vectorTemp.y = (dstAccum[1] / weightAccum);
  57894. PMREMGenerator._vectorTemp.z = (dstAccum[2] / weightAccum);
  57895. if (this.numChannels > 3) {
  57896. PMREMGenerator._vectorTemp.w = (dstAccum[3] / weightAccum);
  57897. }
  57898. }
  57899. else {
  57900. // otherwise sample nearest
  57901. // get face idx and u, v texel coordinate in face
  57902. var coord = this.vectToTexelCoord(centerTapDir.x, centerTapDir.y, centerTapDir.z, srcSize).clone();
  57903. PMREMGenerator._vectorTemp.x = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 0];
  57904. PMREMGenerator._vectorTemp.y = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 1];
  57905. PMREMGenerator._vectorTemp.z = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 2];
  57906. if (this.numChannels > 3) {
  57907. PMREMGenerator._vectorTemp.z = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 3];
  57908. }
  57909. }
  57910. return PMREMGenerator._vectorTemp;
  57911. };
  57912. //--------------------------------------------------------------------------------------
  57913. // Fixup cube edges
  57914. //
  57915. // average texels on cube map faces across the edges
  57916. // WARP/BENT Method Only.
  57917. //--------------------------------------------------------------------------------------
  57918. PMREMGenerator.prototype.fixupCubeEdges = function (cubeMap, cubeMapSize) {
  57919. var k;
  57920. var j;
  57921. var i;
  57922. var iFace;
  57923. var iCorner = 0;
  57924. var cornerNumPtrs = [0, 0, 0, 0, 0, 0, 0, 0]; //indexed by corner and face idx
  57925. var faceCornerStartIndicies = [[], [], [], []]; //corner pointers for face keeping track of the face they belong to.
  57926. // note that if functionality to filter across the three texels for each corner, then
  57927. //indexed by corner and face idx. the array contains the face the start points belongs to.
  57928. var cornerPtr = [
  57929. [[], [], []],
  57930. [[], [], []],
  57931. [[], [], []],
  57932. [[], [], []],
  57933. [[], [], []],
  57934. [[], [], []],
  57935. [[], [], []],
  57936. [[], [], []]
  57937. ];
  57938. //if there is no fixup, or fixup width = 0, do nothing
  57939. if (cubeMapSize < 1) {
  57940. return;
  57941. }
  57942. //special case 1x1 cubemap, average face colors
  57943. if (cubeMapSize == 1) {
  57944. //iterate over channels
  57945. for (k = 0; k < this.numChannels; k++) {
  57946. var accum = 0.0;
  57947. //iterate over faces to accumulate face colors
  57948. for (iFace = 0; iFace < 6; iFace++) {
  57949. accum += cubeMap[iFace][k];
  57950. }
  57951. //compute average over 6 face colors
  57952. accum /= 6.0;
  57953. //iterate over faces to distribute face colors
  57954. for (iFace = 0; iFace < 6; iFace++) {
  57955. cubeMap[iFace][k] = accum;
  57956. }
  57957. }
  57958. return;
  57959. }
  57960. //iterate over faces to collect list of corner texel pointers
  57961. for (iFace = 0; iFace < 6; iFace++) {
  57962. //the 4 corner pointers for this face
  57963. faceCornerStartIndicies[0] = [iFace, 0];
  57964. faceCornerStartIndicies[1] = [iFace, ((cubeMapSize - 1) * this.numChannels)];
  57965. faceCornerStartIndicies[2] = [iFace, ((cubeMapSize) * (cubeMapSize - 1) * this.numChannels)];
  57966. faceCornerStartIndicies[3] = [iFace, ((((cubeMapSize) * (cubeMapSize - 1)) + (cubeMapSize - 1)) * this.numChannels)];
  57967. //iterate over face corners to collect cube corner pointers
  57968. for (iCorner = 0; iCorner < 4; iCorner++) {
  57969. var corner = PMREMGenerator._sgCubeCornerList[iFace][iCorner];
  57970. cornerPtr[corner][cornerNumPtrs[corner]] = faceCornerStartIndicies[iCorner];
  57971. cornerNumPtrs[corner]++;
  57972. }
  57973. }
  57974. //iterate over corners to average across corner tap values
  57975. for (iCorner = 0; iCorner < 8; iCorner++) {
  57976. for (k = 0; k < this.numChannels; k++) {
  57977. var cornerTapAccum = 0.0;
  57978. //iterate over corner texels and average results
  57979. for (i = 0; i < 3; i++) {
  57980. cornerTapAccum += cubeMap[cornerPtr[iCorner][i][0]][cornerPtr[iCorner][i][1] + k]; // Get in the cube map face the start point + channel.
  57981. }
  57982. //divide by 3 to compute average of corner tap values
  57983. cornerTapAccum *= (1.0 / 3.0);
  57984. //iterate over corner texels and average results
  57985. for (i = 0; i < 3; i++) {
  57986. cubeMap[cornerPtr[iCorner][i][0]][cornerPtr[iCorner][i][1] + k] = cornerTapAccum;
  57987. }
  57988. }
  57989. }
  57990. //iterate over the twelve edges of the cube to average across edges
  57991. for (i = 0; i < 12; i++) {
  57992. var face = PMREMGenerator._sgCubeEdgeList[i][0];
  57993. var edge = PMREMGenerator._sgCubeEdgeList[i][1];
  57994. var neighborFace = PMREMGenerator._sgCubeNgh[face][edge][0];
  57995. var neighborEdge = PMREMGenerator._sgCubeNgh[face][edge][1];
  57996. var edgeStartIndex = 0; // a_CubeMap[face].m_ImgData;
  57997. var neighborEdgeStartIndex = 0; // a_CubeMap[neighborFace].m_ImgData;
  57998. var edgeWalk = 0;
  57999. var neighborEdgeWalk = 0;
  58000. //Determine walking pointers based on edge type
  58001. // e.g. CP_EDGE_LEFT, CP_EDGE_RIGHT, CP_EDGE_TOP, CP_EDGE_BOTTOM
  58002. switch (edge) {
  58003. case PMREMGenerator.CP_EDGE_LEFT:
  58004. // no change to faceEdgeStartPtr
  58005. edgeWalk = this.numChannels * cubeMapSize;
  58006. break;
  58007. case PMREMGenerator.CP_EDGE_RIGHT:
  58008. edgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  58009. edgeWalk = this.numChannels * cubeMapSize;
  58010. break;
  58011. case PMREMGenerator.CP_EDGE_TOP:
  58012. // no change to faceEdgeStartPtr
  58013. edgeWalk = this.numChannels;
  58014. break;
  58015. case PMREMGenerator.CP_EDGE_BOTTOM:
  58016. edgeStartIndex += (cubeMapSize) * (cubeMapSize - 1) * this.numChannels;
  58017. edgeWalk = this.numChannels;
  58018. break;
  58019. }
  58020. //For certain types of edge abutments, the neighbor edge walk needs to
  58021. // be flipped: the cases are
  58022. // if a left edge mates with a left or bottom edge on the neighbor
  58023. // if a top edge mates with a top or right edge on the neighbor
  58024. // if a right edge mates with a right or top edge on the neighbor
  58025. // if a bottom edge mates with a bottom or left edge on the neighbor
  58026. //Seeing as the edges are enumerated as follows
  58027. // left =0
  58028. // right =1
  58029. // top =2
  58030. // bottom =3
  58031. //
  58032. //If the edge enums are the same, or the sum of the enums == 3,
  58033. // the neighbor edge walk needs to be flipped
  58034. if ((edge == neighborEdge) || ((edge + neighborEdge) == 3)) {
  58035. switch (neighborEdge) {
  58036. case PMREMGenerator.CP_EDGE_LEFT:
  58037. neighborEdgeStartIndex += (cubeMapSize - 1) * (cubeMapSize) * this.numChannels;
  58038. neighborEdgeWalk = -(this.numChannels * cubeMapSize);
  58039. break;
  58040. case PMREMGenerator.CP_EDGE_RIGHT:
  58041. neighborEdgeStartIndex += ((cubeMapSize - 1) * (cubeMapSize) + (cubeMapSize - 1)) * this.numChannels;
  58042. neighborEdgeWalk = -(this.numChannels * cubeMapSize);
  58043. break;
  58044. case PMREMGenerator.CP_EDGE_TOP:
  58045. neighborEdgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  58046. neighborEdgeWalk = -this.numChannels;
  58047. break;
  58048. case PMREMGenerator.CP_EDGE_BOTTOM:
  58049. neighborEdgeStartIndex += ((cubeMapSize - 1) * (cubeMapSize) + (cubeMapSize - 1)) * this.numChannels;
  58050. neighborEdgeWalk = -this.numChannels;
  58051. break;
  58052. }
  58053. }
  58054. else {
  58055. //swapped direction neighbor edge walk
  58056. switch (neighborEdge) {
  58057. case PMREMGenerator.CP_EDGE_LEFT:
  58058. //no change to neighborEdgeStartPtr for this case since it points
  58059. // to the upper left corner already
  58060. neighborEdgeWalk = this.numChannels * cubeMapSize;
  58061. break;
  58062. case PMREMGenerator.CP_EDGE_RIGHT:
  58063. neighborEdgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  58064. neighborEdgeWalk = this.numChannels * cubeMapSize;
  58065. break;
  58066. case PMREMGenerator.CP_EDGE_TOP:
  58067. //no change to neighborEdgeStartPtr for this case since it points
  58068. // to the upper left corner already
  58069. neighborEdgeWalk = this.numChannels;
  58070. break;
  58071. case PMREMGenerator.CP_EDGE_BOTTOM:
  58072. neighborEdgeStartIndex += (cubeMapSize) * (cubeMapSize - 1) * this.numChannels;
  58073. neighborEdgeWalk = this.numChannels;
  58074. break;
  58075. }
  58076. }
  58077. //Perform edge walk, to average across the 12 edges and smoothly propagate change to
  58078. //nearby neighborhood
  58079. //step ahead one texel on edge
  58080. edgeStartIndex += edgeWalk;
  58081. neighborEdgeStartIndex += neighborEdgeWalk;
  58082. // note that this loop does not process the corner texels, since they have already been
  58083. // averaged across faces across earlier
  58084. for (j = 1; j < (cubeMapSize - 1); j++) {
  58085. //for each set of taps along edge, average them
  58086. // and rewrite the results into the edges
  58087. for (k = 0; k < this.numChannels; k++) {
  58088. var edgeTap = cubeMap[face][edgeStartIndex + k];
  58089. var neighborEdgeTap = cubeMap[neighborFace][neighborEdgeStartIndex + k];
  58090. //compute average of tap intensity values
  58091. var avgTap = 0.5 * (edgeTap + neighborEdgeTap);
  58092. //propagate average of taps to edge taps
  58093. cubeMap[face][edgeStartIndex + k] = avgTap;
  58094. cubeMap[neighborFace][neighborEdgeStartIndex + k] = avgTap;
  58095. }
  58096. edgeStartIndex += edgeWalk;
  58097. neighborEdgeStartIndex += neighborEdgeWalk;
  58098. }
  58099. }
  58100. };
  58101. PMREMGenerator.CP_MAX_MIPLEVELS = 16;
  58102. PMREMGenerator.CP_UDIR = 0;
  58103. PMREMGenerator.CP_VDIR = 1;
  58104. PMREMGenerator.CP_FACEAXIS = 2;
  58105. //used to index cube faces
  58106. PMREMGenerator.CP_FACE_X_POS = 0;
  58107. PMREMGenerator.CP_FACE_X_NEG = 1;
  58108. PMREMGenerator.CP_FACE_Y_POS = 2;
  58109. PMREMGenerator.CP_FACE_Y_NEG = 3;
  58110. PMREMGenerator.CP_FACE_Z_POS = 4;
  58111. PMREMGenerator.CP_FACE_Z_NEG = 5;
  58112. //used to index image edges
  58113. // NOTE.. the actual number corresponding to the edge is important
  58114. // do not change these, or the code will break
  58115. //
  58116. // CP_EDGE_LEFT is u = 0
  58117. // CP_EDGE_RIGHT is u = width-1
  58118. // CP_EDGE_TOP is v = 0
  58119. // CP_EDGE_BOTTOM is v = height-1
  58120. PMREMGenerator.CP_EDGE_LEFT = 0;
  58121. PMREMGenerator.CP_EDGE_RIGHT = 1;
  58122. PMREMGenerator.CP_EDGE_TOP = 2;
  58123. PMREMGenerator.CP_EDGE_BOTTOM = 3;
  58124. //corners of CUBE map (P or N specifys if it corresponds to the
  58125. // positive or negative direction each of X, Y, and Z
  58126. PMREMGenerator.CP_CORNER_NNN = 0;
  58127. PMREMGenerator.CP_CORNER_NNP = 1;
  58128. PMREMGenerator.CP_CORNER_NPN = 2;
  58129. PMREMGenerator.CP_CORNER_NPP = 3;
  58130. PMREMGenerator.CP_CORNER_PNN = 4;
  58131. PMREMGenerator.CP_CORNER_PNP = 5;
  58132. PMREMGenerator.CP_CORNER_PPN = 6;
  58133. PMREMGenerator.CP_CORNER_PPP = 7;
  58134. PMREMGenerator._vectorTemp = new BABYLON.Vector4(0, 0, 0, 0);
  58135. //3x2 matrices that map cube map indexing vectors in 3d
  58136. // (after face selection and divide through by the
  58137. // _ABSOLUTE VALUE_ of the max coord)
  58138. // into NVC space
  58139. //Note this currently assumes the D3D cube face ordering and orientation
  58140. PMREMGenerator._sgFace2DMapping = [
  58141. //XPOS face
  58142. [[0, 0, -1],
  58143. [0, -1, 0],
  58144. [1, 0, 0]],
  58145. //XNEG face
  58146. [[0, 0, 1],
  58147. [0, -1, 0],
  58148. [-1, 0, 0]],
  58149. //YPOS face
  58150. [[1, 0, 0],
  58151. [0, 0, 1],
  58152. [0, 1, 0]],
  58153. //YNEG face
  58154. [[1, 0, 0],
  58155. [0, 0, -1],
  58156. [0, -1, 0]],
  58157. //ZPOS face
  58158. [[1, 0, 0],
  58159. [0, -1, 0],
  58160. [0, 0, 1]],
  58161. //ZNEG face
  58162. [[-1, 0, 0],
  58163. [0, -1, 0],
  58164. [0, 0, -1]],
  58165. ];
  58166. //------------------------------------------------------------------------------
  58167. // D3D cube map face specification
  58168. // mapping from 3D x,y,z cube map lookup coordinates
  58169. // to 2D within face u,v coordinates
  58170. //
  58171. // --------------------> U direction
  58172. // | (within-face texture space)
  58173. // | _____
  58174. // | | |
  58175. // | | +Y |
  58176. // | _____|_____|_____ _____
  58177. // | | | | | |
  58178. // | | -X | +Z | +X | -Z |
  58179. // | |_____|_____|_____|_____|
  58180. // | | |
  58181. // | | -Y |
  58182. // | |_____|
  58183. // |
  58184. // v V direction
  58185. // (within-face texture space)
  58186. //------------------------------------------------------------------------------
  58187. //Information about neighbors and how texture coorrdinates change across faces
  58188. // in ORDER of left, right, top, bottom (e.g. edges corresponding to u=0,
  58189. // u=1, v=0, v=1 in the 2D coordinate system of the particular face.
  58190. //Note this currently assumes the D3D cube face ordering and orientation
  58191. PMREMGenerator._sgCubeNgh = [
  58192. //XPOS face
  58193. [[PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_RIGHT],
  58194. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_LEFT],
  58195. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_RIGHT],
  58196. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_RIGHT]],
  58197. //XNEG face
  58198. [[PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  58199. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_LEFT],
  58200. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_LEFT],
  58201. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_LEFT]],
  58202. //YPOS face
  58203. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_TOP],
  58204. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_TOP],
  58205. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_TOP],
  58206. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_TOP]],
  58207. //YNEG face
  58208. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_BOTTOM],
  58209. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  58210. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  58211. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_BOTTOM]],
  58212. //ZPOS face
  58213. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  58214. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_LEFT],
  58215. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  58216. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_TOP]],
  58217. //ZNEG face
  58218. [[PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_RIGHT],
  58219. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_LEFT],
  58220. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_TOP],
  58221. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_BOTTOM]]
  58222. ];
  58223. //The 12 edges of the cubemap, (entries are used to index into the neighbor table)
  58224. // this table is used to average over the edges.
  58225. PMREMGenerator._sgCubeEdgeList = [
  58226. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_LEFT],
  58227. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_RIGHT],
  58228. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_TOP],
  58229. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  58230. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_LEFT],
  58231. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  58232. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_TOP],
  58233. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_BOTTOM],
  58234. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_TOP],
  58235. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  58236. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_TOP],
  58237. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_BOTTOM]
  58238. ];
  58239. //Information about which of the 8 cube corners are correspond to the
  58240. // the 4 corners in each cube face
  58241. // the order is upper left, upper right, lower left, lower right
  58242. PMREMGenerator._sgCubeCornerList = [
  58243. [PMREMGenerator.CP_CORNER_PPP, PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_PNP, PMREMGenerator.CP_CORNER_PNN],
  58244. [PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_NNN, PMREMGenerator.CP_CORNER_NNP],
  58245. [PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_PPP],
  58246. [PMREMGenerator.CP_CORNER_NNP, PMREMGenerator.CP_CORNER_PNP, PMREMGenerator.CP_CORNER_NNN, PMREMGenerator.CP_CORNER_PNN],
  58247. [PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_PPP, PMREMGenerator.CP_CORNER_NNP, PMREMGenerator.CP_CORNER_PNP],
  58248. [PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_PNN, PMREMGenerator.CP_CORNER_NNN] // ZNEG face
  58249. ];
  58250. return PMREMGenerator;
  58251. }());
  58252. Internals.PMREMGenerator = PMREMGenerator;
  58253. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  58254. })(BABYLON || (BABYLON = {}));
  58255. var BABYLON;
  58256. (function (BABYLON) {
  58257. /**
  58258. * This represents a texture coming from an HDR input.
  58259. *
  58260. * The only supported format is currently panorama picture stored in RGBE format.
  58261. * Example of such files can be found on HDRLib: http://hdrlib.com/
  58262. */
  58263. var HDRCubeTexture = (function (_super) {
  58264. __extends(HDRCubeTexture, _super);
  58265. /**
  58266. * Instantiates an HDRTexture from the following parameters.
  58267. *
  58268. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  58269. * @param scene The scene the texture will be used in
  58270. * @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.
  58271. * @param noMipmap Forces to not generate the mipmap if true
  58272. * @param generateHarmonics Specifies wether you want to extract the polynomial harmonics during the generation process
  58273. * @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)
  58274. * @param usePMREMGenerator Specifies wether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  58275. */
  58276. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  58277. if (noMipmap === void 0) { noMipmap = false; }
  58278. if (generateHarmonics === void 0) { generateHarmonics = true; }
  58279. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  58280. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  58281. _super.call(this, scene);
  58282. this._useInGammaSpace = false;
  58283. this._generateHarmonics = true;
  58284. this._isBABYLONPreprocessed = false;
  58285. /**
  58286. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  58287. */
  58288. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  58289. /**
  58290. * The spherical polynomial data extracted from the texture.
  58291. */
  58292. this.sphericalPolynomial = null;
  58293. /**
  58294. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  58295. * This is usefull at run time to apply the good shader.
  58296. */
  58297. this.isPMREM = false;
  58298. if (!url) {
  58299. return;
  58300. }
  58301. this.name = url;
  58302. this.url = url;
  58303. this.hasAlpha = false;
  58304. this.isCube = true;
  58305. this._textureMatrix = BABYLON.Matrix.Identity();
  58306. if (size) {
  58307. this._isBABYLONPreprocessed = false;
  58308. this._noMipmap = noMipmap;
  58309. this._size = size;
  58310. this._useInGammaSpace = useInGammaSpace;
  58311. this._usePMREMGenerator = usePMREMGenerator &&
  58312. scene.getEngine().getCaps().textureLOD &&
  58313. this.getScene().getEngine().getCaps().textureFloat &&
  58314. !this._useInGammaSpace;
  58315. }
  58316. else {
  58317. this._isBABYLONPreprocessed = true;
  58318. this._noMipmap = false;
  58319. this._useInGammaSpace = false;
  58320. this._usePMREMGenerator = scene.getEngine().getCaps().textureLOD &&
  58321. this.getScene().getEngine().getCaps().textureFloat &&
  58322. !this._useInGammaSpace;
  58323. }
  58324. this.isPMREM = this._usePMREMGenerator;
  58325. this._texture = this._getFromCache(url, this._noMipmap);
  58326. if (!this._texture) {
  58327. if (!scene.useDelayedTextureLoading) {
  58328. this.loadTexture();
  58329. }
  58330. else {
  58331. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  58332. }
  58333. }
  58334. }
  58335. /**
  58336. * Occurs when the file is a preprocessed .babylon.hdr file.
  58337. */
  58338. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  58339. var _this = this;
  58340. var mipLevels = 0;
  58341. var floatArrayView = null;
  58342. var mipmapGenerator = (!this._useInGammaSpace && this.getScene().getEngine().getCaps().textureFloat) ? function (data) {
  58343. var mips = [];
  58344. var startIndex = 30;
  58345. for (var level = 0; level < mipLevels; level++) {
  58346. mips.push([]);
  58347. // Fill each pixel of the mip level.
  58348. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  58349. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  58350. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  58351. mips[level].push(faceData);
  58352. startIndex += faceSize;
  58353. }
  58354. }
  58355. return mips;
  58356. } : null;
  58357. var callback = function (buffer) {
  58358. // Create Native Array Views
  58359. var intArrayView = new Int32Array(buffer);
  58360. floatArrayView = new Float32Array(buffer);
  58361. // Fill header.
  58362. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  58363. _this._size = intArrayView[1]; // CubeMap max mip face size.
  58364. // Update Texture Information.
  58365. _this.getScene().getEngine().updateTextureSize(_this._texture, _this._size, _this._size);
  58366. // Fill polynomial information.
  58367. _this.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  58368. _this.sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  58369. _this.sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  58370. _this.sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  58371. _this.sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  58372. _this.sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  58373. _this.sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  58374. _this.sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  58375. _this.sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  58376. _this.sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  58377. // Fill pixel data.
  58378. mipLevels = intArrayView[29]; // Number of mip levels.
  58379. var startIndex = 30;
  58380. var data = [];
  58381. var faceSize = Math.pow(_this._size, 2) * 3;
  58382. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  58383. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  58384. startIndex += faceSize;
  58385. }
  58386. var results = [];
  58387. var byteArray = null;
  58388. // Push each faces.
  58389. for (var k = 0; k < 6; k++) {
  58390. var dataFace = null;
  58391. // If special cases.
  58392. if (!mipmapGenerator) {
  58393. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y... if no mipmapgenerator...
  58394. dataFace = data[j];
  58395. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  58396. // 3 channels of 1 bytes per pixel in bytes.
  58397. var byteBuffer = new ArrayBuffer(faceSize);
  58398. byteArray = new Uint8Array(byteBuffer);
  58399. }
  58400. for (var i = 0; i < _this._size * _this._size; i++) {
  58401. // Put in gamma space if requested.
  58402. if (_this._useInGammaSpace) {
  58403. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  58404. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  58405. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  58406. }
  58407. // Convert to int texture for fallback.
  58408. if (byteArray) {
  58409. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  58410. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  58411. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  58412. // May use luminance instead if the result is not accurate.
  58413. var max = Math.max(Math.max(r, g), b);
  58414. if (max > 255) {
  58415. var scale = 255 / max;
  58416. r *= scale;
  58417. g *= scale;
  58418. b *= scale;
  58419. }
  58420. byteArray[(i * 3) + 0] = r;
  58421. byteArray[(i * 3) + 1] = g;
  58422. byteArray[(i * 3) + 2] = b;
  58423. }
  58424. }
  58425. }
  58426. else {
  58427. dataFace = data[k];
  58428. }
  58429. // Fill the array accordingly.
  58430. if (byteArray) {
  58431. results.push(byteArray);
  58432. }
  58433. else {
  58434. results.push(dataFace);
  58435. }
  58436. }
  58437. return results;
  58438. };
  58439. 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);
  58440. };
  58441. /**
  58442. * Occurs when the file is raw .hdr file.
  58443. */
  58444. HDRCubeTexture.prototype.loadHDRTexture = function () {
  58445. var _this = this;
  58446. var callback = function (buffer) {
  58447. // Extract the raw linear data.
  58448. var data = BABYLON.Internals.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  58449. // Generate harmonics if needed.
  58450. if (_this._generateHarmonics) {
  58451. _this.sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  58452. }
  58453. var results = [];
  58454. var byteArray = null;
  58455. // Push each faces.
  58456. for (var j = 0; j < 6; j++) {
  58457. // Create uintarray fallback.
  58458. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  58459. // 3 channels of 1 bytes per pixel in bytes.
  58460. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  58461. byteArray = new Uint8Array(byteBuffer);
  58462. }
  58463. var dataFace = data[HDRCubeTexture._facesMapping[j]];
  58464. // If special cases.
  58465. if (_this._useInGammaSpace || byteArray) {
  58466. for (var i = 0; i < _this._size * _this._size; i++) {
  58467. // Put in gamma space if requested.
  58468. if (_this._useInGammaSpace) {
  58469. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  58470. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  58471. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  58472. }
  58473. // Convert to int texture for fallback.
  58474. if (byteArray) {
  58475. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  58476. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  58477. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  58478. // May use luminance instead if the result is not accurate.
  58479. var max = Math.max(Math.max(r, g), b);
  58480. if (max > 255) {
  58481. var scale = 255 / max;
  58482. r *= scale;
  58483. g *= scale;
  58484. b *= scale;
  58485. }
  58486. byteArray[(i * 3) + 0] = r;
  58487. byteArray[(i * 3) + 1] = g;
  58488. byteArray[(i * 3) + 2] = b;
  58489. }
  58490. }
  58491. }
  58492. if (byteArray) {
  58493. results.push(byteArray);
  58494. }
  58495. else {
  58496. results.push(dataFace);
  58497. }
  58498. }
  58499. return results;
  58500. };
  58501. var mipmapGenerator = null;
  58502. if (!this._noMipmap &&
  58503. this._usePMREMGenerator) {
  58504. mipmapGenerator = function (data) {
  58505. // Custom setup of the generator matching with the PBR shader values.
  58506. var generator = new BABYLON.Internals.PMREMGenerator(data, _this._size, _this._size, 0, 3, _this.getScene().getEngine().getCaps().textureFloat, 2048, 0.25, false, true);
  58507. return generator.filterCubeMap();
  58508. };
  58509. }
  58510. 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);
  58511. };
  58512. /**
  58513. * Starts the loading process of the texture.
  58514. */
  58515. HDRCubeTexture.prototype.loadTexture = function () {
  58516. if (this._isBABYLONPreprocessed) {
  58517. this.loadBabylonTexture();
  58518. }
  58519. else {
  58520. this.loadHDRTexture();
  58521. }
  58522. };
  58523. HDRCubeTexture.prototype.clone = function () {
  58524. var size = this._isBABYLONPreprocessed ? null : this._size;
  58525. var newTexture = new HDRCubeTexture(this.url, this.getScene(), size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  58526. // Base texture
  58527. newTexture.level = this.level;
  58528. newTexture.wrapU = this.wrapU;
  58529. newTexture.wrapV = this.wrapV;
  58530. newTexture.coordinatesIndex = this.coordinatesIndex;
  58531. newTexture.coordinatesMode = this.coordinatesMode;
  58532. return newTexture;
  58533. };
  58534. // Methods
  58535. HDRCubeTexture.prototype.delayLoad = function () {
  58536. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  58537. return;
  58538. }
  58539. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  58540. this._texture = this._getFromCache(this.url, this._noMipmap);
  58541. if (!this._texture) {
  58542. this.loadTexture();
  58543. }
  58544. };
  58545. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  58546. return this._textureMatrix;
  58547. };
  58548. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  58549. var texture = null;
  58550. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  58551. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  58552. texture = new BABYLON.HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, texture.generateHarmonics, texture.useInGammaSpace, texture.usePMREMGenerator);
  58553. texture.name = parsedTexture.name;
  58554. texture.hasAlpha = parsedTexture.hasAlpha;
  58555. texture.level = parsedTexture.level;
  58556. texture.coordinatesMode = parsedTexture.coordinatesMode;
  58557. }
  58558. return texture;
  58559. };
  58560. HDRCubeTexture.prototype.serialize = function () {
  58561. if (!this.name) {
  58562. return null;
  58563. }
  58564. var serializationObject = {};
  58565. serializationObject.name = this.name;
  58566. serializationObject.hasAlpha = this.hasAlpha;
  58567. serializationObject.isCube = true;
  58568. serializationObject.level = this.level;
  58569. serializationObject.size = this._size;
  58570. serializationObject.coordinatesMode = this.coordinatesMode;
  58571. serializationObject.useInGammaSpace = this._useInGammaSpace;
  58572. serializationObject.generateHarmonics = this._generateHarmonics;
  58573. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  58574. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  58575. serializationObject.customType = "BABYLON.HDRCubeTexture";
  58576. return serializationObject;
  58577. };
  58578. /**
  58579. * Saves as a file the data contained in the texture in a binary format.
  58580. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  58581. * as the spherical used in the lighting.
  58582. * @param url The HDR file url.
  58583. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  58584. * @param onError Method called if any error happens during download.
  58585. * @return The packed binary data.
  58586. */
  58587. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  58588. if (onError === void 0) { onError = null; }
  58589. var callback = function (buffer) {
  58590. var data = new Blob([buffer], { type: 'application/octet-stream' });
  58591. // Returns a URL you can use as a href.
  58592. var objUrl = window.URL.createObjectURL(data);
  58593. // Simulates a link to it and click to dowload.
  58594. var a = document.createElement("a");
  58595. document.body.appendChild(a);
  58596. a.style.display = "none";
  58597. a.href = objUrl;
  58598. a.download = "envmap.babylon.hdr";
  58599. a.click();
  58600. };
  58601. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  58602. };
  58603. /**
  58604. * Serializes the data contained in the texture in a binary format.
  58605. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  58606. * as the spherical used in the lighting.
  58607. * @param url The HDR file url.
  58608. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  58609. * @param onError Method called if any error happens during download.
  58610. * @return The packed binary data.
  58611. */
  58612. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  58613. if (onError === void 0) { onError = null; }
  58614. // Needs the url tho create the texture.
  58615. if (!url) {
  58616. return null;
  58617. }
  58618. // Check Power of two size.
  58619. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  58620. return null;
  58621. }
  58622. var getDataCallback = function (dataBuffer) {
  58623. // Extract the raw linear data.
  58624. var cubeData = BABYLON.Internals.HDRTools.GetCubeMapTextureData(dataBuffer, size);
  58625. // Generate harmonics if needed.
  58626. var sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(cubeData);
  58627. // Generate seamless faces
  58628. var mipGeneratorArray = [];
  58629. // Data are known to be in +X +Y +Z -X -Y -Z
  58630. // mipmmapGenerator data is expected to be order in +X -X +Y -Y +Z -Z
  58631. mipGeneratorArray.push(cubeData.right); // +X
  58632. mipGeneratorArray.push(cubeData.left); // -X
  58633. mipGeneratorArray.push(cubeData.up); // +Y
  58634. mipGeneratorArray.push(cubeData.down); // -Y
  58635. mipGeneratorArray.push(cubeData.front); // +Z
  58636. mipGeneratorArray.push(cubeData.back); // -Z
  58637. // Custom setup of the generator matching with the PBR shader values.
  58638. var generator = new BABYLON.Internals.PMREMGenerator(mipGeneratorArray, size, size, 0, 3, true, 2048, 0.25, false, true);
  58639. var mippedData = generator.filterCubeMap();
  58640. // Compute required byte length.
  58641. var byteLength = 1 * 4; // Raw Data Version int32.
  58642. byteLength += 4; // CubeMap max mip face size int32.
  58643. byteLength += (9 * 3 * 4); // Spherical polynomial byte length 9 Vector 3 of floats.
  58644. // Add data size.
  58645. byteLength += 4; // Number of mip levels int32.
  58646. for (var level = 0; level < mippedData.length; level++) {
  58647. var mipSize = size >> level;
  58648. byteLength += (6 * mipSize * mipSize * 3 * 4); // 6 faces of size squared rgb float pixels.
  58649. }
  58650. // Prepare binary structure.
  58651. var buffer = new ArrayBuffer(byteLength);
  58652. var intArrayView = new Int32Array(buffer);
  58653. var floatArrayView = new Float32Array(buffer);
  58654. // Fill header.
  58655. intArrayView[0] = 1; // Version 1.
  58656. intArrayView[1] = size; // CubeMap max mip face size.
  58657. // Fill polynomial information.
  58658. sphericalPolynomial.x.toArray(floatArrayView, 2);
  58659. sphericalPolynomial.y.toArray(floatArrayView, 5);
  58660. sphericalPolynomial.z.toArray(floatArrayView, 8);
  58661. sphericalPolynomial.xx.toArray(floatArrayView, 11);
  58662. sphericalPolynomial.yy.toArray(floatArrayView, 14);
  58663. sphericalPolynomial.zz.toArray(floatArrayView, 17);
  58664. sphericalPolynomial.xy.toArray(floatArrayView, 20);
  58665. sphericalPolynomial.yz.toArray(floatArrayView, 23);
  58666. sphericalPolynomial.zx.toArray(floatArrayView, 26);
  58667. // Fill pixel data.
  58668. intArrayView[29] = mippedData.length; // Number of mip levels.
  58669. var startIndex = 30;
  58670. for (var level = 0; level < mippedData.length; level++) {
  58671. // Fill each pixel of the mip level.
  58672. var faceSize = Math.pow(size >> level, 2) * 3;
  58673. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  58674. floatArrayView.set(mippedData[level][faceIndex], startIndex);
  58675. startIndex += faceSize;
  58676. }
  58677. }
  58678. // Callback.
  58679. callback(buffer);
  58680. };
  58681. // Download and process.
  58682. BABYLON.Tools.LoadFile(url, function (data) {
  58683. getDataCallback(data);
  58684. }, null, null, true, onError);
  58685. };
  58686. HDRCubeTexture._facesMapping = [
  58687. "right",
  58688. "up",
  58689. "front",
  58690. "left",
  58691. "down",
  58692. "back"
  58693. ];
  58694. return HDRCubeTexture;
  58695. }(BABYLON.BaseTexture));
  58696. BABYLON.HDRCubeTexture = HDRCubeTexture;
  58697. })(BABYLON || (BABYLON = {}));
  58698. var BABYLON;
  58699. (function (BABYLON) {
  58700. var Debug;
  58701. (function (Debug) {
  58702. /**
  58703. * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
  58704. */
  58705. var SkeletonViewer = (function () {
  58706. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  58707. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  58708. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  58709. this.skeleton = skeleton;
  58710. this.mesh = mesh;
  58711. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  58712. this.renderingGroupId = renderingGroupId;
  58713. this.color = BABYLON.Color3.White();
  58714. this._debugLines = [];
  58715. this._isEnabled = false;
  58716. this._scene = scene;
  58717. this.update();
  58718. this._renderFunction = this.update.bind(this);
  58719. }
  58720. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  58721. get: function () {
  58722. return this._isEnabled;
  58723. },
  58724. set: function (value) {
  58725. if (this._isEnabled === value) {
  58726. return;
  58727. }
  58728. this._isEnabled = value;
  58729. if (value) {
  58730. this._scene.registerBeforeRender(this._renderFunction);
  58731. }
  58732. else {
  58733. this._scene.unregisterBeforeRender(this._renderFunction);
  58734. }
  58735. },
  58736. enumerable: true,
  58737. configurable: true
  58738. });
  58739. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  58740. if (x === void 0) { x = 0; }
  58741. if (y === void 0) { y = 0; }
  58742. if (z === void 0) { z = 0; }
  58743. var tmat = BABYLON.Tmp.Matrix[0];
  58744. var parentBone = bone.getParent();
  58745. tmat.copyFrom(bone.getLocalMatrix());
  58746. if (x !== 0 || y !== 0 || z !== 0) {
  58747. var tmat2 = BABYLON.Tmp.Matrix[1];
  58748. BABYLON.Matrix.IdentityToRef(tmat2);
  58749. tmat2.m[12] = x;
  58750. tmat2.m[13] = y;
  58751. tmat2.m[14] = z;
  58752. tmat2.multiplyToRef(tmat, tmat);
  58753. }
  58754. if (parentBone) {
  58755. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  58756. }
  58757. tmat.multiplyToRef(meshMat, tmat);
  58758. position.x = tmat.m[12];
  58759. position.y = tmat.m[13];
  58760. position.z = tmat.m[14];
  58761. };
  58762. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  58763. var len = bones.length;
  58764. for (var i = 0; i < len; i++) {
  58765. var bone = bones[i];
  58766. var points = this._debugLines[i];
  58767. if (!points) {
  58768. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  58769. this._debugLines[i] = points;
  58770. }
  58771. this._getBonePosition(points[0], bone, meshMat);
  58772. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  58773. }
  58774. };
  58775. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  58776. var len = bones.length;
  58777. var boneNum = 0;
  58778. for (var i = len - 1; i >= 0; i--) {
  58779. var childBone = bones[i];
  58780. var parentBone = childBone.getParent();
  58781. if (!parentBone) {
  58782. continue;
  58783. }
  58784. var points = this._debugLines[boneNum];
  58785. if (!points) {
  58786. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  58787. this._debugLines[boneNum] = points;
  58788. }
  58789. this._getBonePosition(points[0], childBone, meshMat);
  58790. this._getBonePosition(points[1], parentBone, meshMat);
  58791. boneNum++;
  58792. }
  58793. };
  58794. SkeletonViewer.prototype.update = function () {
  58795. if (this.autoUpdateBonesMatrices) {
  58796. this._updateBoneMatrix(this.skeleton.bones[0]);
  58797. }
  58798. if (this.skeleton.bones[0].length === undefined) {
  58799. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  58800. }
  58801. else {
  58802. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  58803. }
  58804. if (!this._debugMesh) {
  58805. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true }, this._scene);
  58806. this._debugMesh.renderingGroupId = this.renderingGroupId;
  58807. }
  58808. else {
  58809. BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  58810. }
  58811. this._debugMesh.color = this.color;
  58812. };
  58813. SkeletonViewer.prototype._updateBoneMatrix = function (bone) {
  58814. if (bone.getParent()) {
  58815. bone.getLocalMatrix().multiplyToRef(bone.getParent().getAbsoluteTransform(), bone.getAbsoluteTransform());
  58816. }
  58817. var children = bone.children;
  58818. var len = children.length;
  58819. for (var i = 0; i < len; i++) {
  58820. this._updateBoneMatrix(children[i]);
  58821. }
  58822. };
  58823. SkeletonViewer.prototype.dispose = function () {
  58824. if (this._debugMesh) {
  58825. this.isEnabled = false;
  58826. this._debugMesh.dispose();
  58827. this._debugMesh = null;
  58828. }
  58829. };
  58830. return SkeletonViewer;
  58831. }());
  58832. Debug.SkeletonViewer = SkeletonViewer;
  58833. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  58834. })(BABYLON || (BABYLON = {}));
  58835. var BABYLON;
  58836. (function (BABYLON) {
  58837. /**
  58838. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  58839. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  58840. * 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;
  58841. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  58842. */
  58843. var ColorCurves = (function () {
  58844. function ColorCurves() {
  58845. this._dirty = true;
  58846. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  58847. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  58848. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  58849. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  58850. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  58851. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  58852. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  58853. this._globalHue = 30;
  58854. this._globalDensity = 0;
  58855. this._globalSaturation = 0;
  58856. this._globalExposure = 0;
  58857. this._highlightsHue = 30;
  58858. this._highlightsDensity = 0;
  58859. this._highlightsSaturation = 0;
  58860. this._highlightsExposure = 0;
  58861. this._midtonesHue = 30;
  58862. this._midtonesDensity = 0;
  58863. this._midtonesSaturation = 0;
  58864. this._midtonesExposure = 0;
  58865. this._shadowsHue = 30;
  58866. this._shadowsDensity = 0;
  58867. this._shadowsSaturation = 0;
  58868. this._shadowsExposure = 0;
  58869. }
  58870. Object.defineProperty(ColorCurves.prototype, "GlobalHue", {
  58871. /**
  58872. * Gets the global Hue value.
  58873. * 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).
  58874. */
  58875. get: function () {
  58876. return this._globalHue;
  58877. },
  58878. /**
  58879. * Sets the global Hue value.
  58880. * 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).
  58881. */
  58882. set: function (value) {
  58883. this._globalHue = value;
  58884. this._dirty = true;
  58885. },
  58886. enumerable: true,
  58887. configurable: true
  58888. });
  58889. Object.defineProperty(ColorCurves.prototype, "GlobalDensity", {
  58890. /**
  58891. * Gets the global Density value.
  58892. * 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.
  58893. * Values less than zero provide a filter of opposite hue.
  58894. */
  58895. get: function () {
  58896. return this._globalDensity;
  58897. },
  58898. /**
  58899. * Sets the global Density value.
  58900. * 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.
  58901. * Values less than zero provide a filter of opposite hue.
  58902. */
  58903. set: function (value) {
  58904. this._globalDensity = value;
  58905. this._dirty = true;
  58906. },
  58907. enumerable: true,
  58908. configurable: true
  58909. });
  58910. Object.defineProperty(ColorCurves.prototype, "GlobalSaturation", {
  58911. /**
  58912. * Gets the global Saturation value.
  58913. * 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.
  58914. */
  58915. get: function () {
  58916. return this._globalSaturation;
  58917. },
  58918. /**
  58919. * Sets the global Saturation value.
  58920. * 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.
  58921. */
  58922. set: function (value) {
  58923. this._globalSaturation = value;
  58924. this._dirty = true;
  58925. },
  58926. enumerable: true,
  58927. configurable: true
  58928. });
  58929. Object.defineProperty(ColorCurves.prototype, "HighlightsHue", {
  58930. /**
  58931. * Gets the highlights Hue value.
  58932. * 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).
  58933. */
  58934. get: function () {
  58935. return this._highlightsHue;
  58936. },
  58937. /**
  58938. * Sets the highlights Hue value.
  58939. * 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).
  58940. */
  58941. set: function (value) {
  58942. this._highlightsHue = value;
  58943. this._dirty = true;
  58944. },
  58945. enumerable: true,
  58946. configurable: true
  58947. });
  58948. Object.defineProperty(ColorCurves.prototype, "HighlightsDensity", {
  58949. /**
  58950. * Gets the highlights Density value.
  58951. * 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.
  58952. * Values less than zero provide a filter of opposite hue.
  58953. */
  58954. get: function () {
  58955. return this._highlightsDensity;
  58956. },
  58957. /**
  58958. * Sets the highlights Density value.
  58959. * 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.
  58960. * Values less than zero provide a filter of opposite hue.
  58961. */
  58962. set: function (value) {
  58963. this._highlightsDensity = value;
  58964. this._dirty = true;
  58965. },
  58966. enumerable: true,
  58967. configurable: true
  58968. });
  58969. Object.defineProperty(ColorCurves.prototype, "HighlightsSaturation", {
  58970. /**
  58971. * Gets the highlights Saturation value.
  58972. * 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.
  58973. */
  58974. get: function () {
  58975. return this._highlightsSaturation;
  58976. },
  58977. /**
  58978. * Sets the highlights Saturation value.
  58979. * 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.
  58980. */
  58981. set: function (value) {
  58982. this._highlightsSaturation = value;
  58983. this._dirty = true;
  58984. },
  58985. enumerable: true,
  58986. configurable: true
  58987. });
  58988. Object.defineProperty(ColorCurves.prototype, "HighlightsExposure", {
  58989. /**
  58990. * Gets the highlights Exposure value.
  58991. * 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.
  58992. */
  58993. get: function () {
  58994. return this._highlightsExposure;
  58995. },
  58996. /**
  58997. * Sets the highlights Exposure value.
  58998. * 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.
  58999. */
  59000. set: function (value) {
  59001. this._highlightsExposure = value;
  59002. this._dirty = true;
  59003. },
  59004. enumerable: true,
  59005. configurable: true
  59006. });
  59007. Object.defineProperty(ColorCurves.prototype, "MidtonesHue", {
  59008. /**
  59009. * Gets the midtones Hue value.
  59010. * 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).
  59011. */
  59012. get: function () {
  59013. return this._midtonesHue;
  59014. },
  59015. /**
  59016. * Sets the midtones Hue value.
  59017. * 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).
  59018. */
  59019. set: function (value) {
  59020. this._midtonesHue = value;
  59021. this._dirty = true;
  59022. },
  59023. enumerable: true,
  59024. configurable: true
  59025. });
  59026. Object.defineProperty(ColorCurves.prototype, "MidtonesDensity", {
  59027. /**
  59028. * Gets the midtones Density value.
  59029. * 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.
  59030. * Values less than zero provide a filter of opposite hue.
  59031. */
  59032. get: function () {
  59033. return this._midtonesDensity;
  59034. },
  59035. /**
  59036. * Sets the midtones Density value.
  59037. * 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.
  59038. * Values less than zero provide a filter of opposite hue.
  59039. */
  59040. set: function (value) {
  59041. this._midtonesDensity = value;
  59042. this._dirty = true;
  59043. },
  59044. enumerable: true,
  59045. configurable: true
  59046. });
  59047. Object.defineProperty(ColorCurves.prototype, "MidtonesSaturation", {
  59048. /**
  59049. * Gets the midtones Saturation value.
  59050. * 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.
  59051. */
  59052. get: function () {
  59053. return this._midtonesSaturation;
  59054. },
  59055. /**
  59056. * Sets the midtones Saturation value.
  59057. * 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.
  59058. */
  59059. set: function (value) {
  59060. this._midtonesSaturation = value;
  59061. this._dirty = true;
  59062. },
  59063. enumerable: true,
  59064. configurable: true
  59065. });
  59066. Object.defineProperty(ColorCurves.prototype, "MidtonesExposure", {
  59067. /**
  59068. * Gets the midtones Exposure value.
  59069. * 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.
  59070. */
  59071. get: function () {
  59072. return this._midtonesExposure;
  59073. },
  59074. /**
  59075. * Sets the midtones Exposure value.
  59076. * 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.
  59077. */
  59078. set: function (value) {
  59079. this._midtonesExposure = value;
  59080. this._dirty = true;
  59081. },
  59082. enumerable: true,
  59083. configurable: true
  59084. });
  59085. Object.defineProperty(ColorCurves.prototype, "ShadowsHue", {
  59086. /**
  59087. * Gets the shadows Hue value.
  59088. * 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).
  59089. */
  59090. get: function () {
  59091. return this._shadowsHue;
  59092. },
  59093. /**
  59094. * Sets the shadows Hue value.
  59095. * 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).
  59096. */
  59097. set: function (value) {
  59098. this._shadowsHue = value;
  59099. this._dirty = true;
  59100. },
  59101. enumerable: true,
  59102. configurable: true
  59103. });
  59104. Object.defineProperty(ColorCurves.prototype, "ShadowsDensity", {
  59105. /**
  59106. * Gets the shadows Density value.
  59107. * 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.
  59108. * Values less than zero provide a filter of opposite hue.
  59109. */
  59110. get: function () {
  59111. return this._shadowsDensity;
  59112. },
  59113. /**
  59114. * Sets the shadows Density value.
  59115. * 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.
  59116. * Values less than zero provide a filter of opposite hue.
  59117. */
  59118. set: function (value) {
  59119. this._shadowsDensity = value;
  59120. this._dirty = true;
  59121. },
  59122. enumerable: true,
  59123. configurable: true
  59124. });
  59125. Object.defineProperty(ColorCurves.prototype, "ShadowsSaturation", {
  59126. /**
  59127. * Gets the shadows Saturation value.
  59128. * 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.
  59129. */
  59130. get: function () {
  59131. return this._shadowsSaturation;
  59132. },
  59133. /**
  59134. * Sets the shadows Saturation value.
  59135. * 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.
  59136. */
  59137. set: function (value) {
  59138. this._shadowsSaturation = value;
  59139. this._dirty = true;
  59140. },
  59141. enumerable: true,
  59142. configurable: true
  59143. });
  59144. Object.defineProperty(ColorCurves.prototype, "ShadowsExposure", {
  59145. /**
  59146. * Gets the shadows Exposure value.
  59147. * 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.
  59148. */
  59149. get: function () {
  59150. return this._shadowsExposure;
  59151. },
  59152. /**
  59153. * Sets the shadows Exposure value.
  59154. * 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.
  59155. */
  59156. set: function (value) {
  59157. this._shadowsExposure = value;
  59158. this._dirty = true;
  59159. },
  59160. enumerable: true,
  59161. configurable: true
  59162. });
  59163. /**
  59164. * Binds the color curves to the shader.
  59165. * @param colorCurves The color curve to bind
  59166. * @param effect The effect to bind to
  59167. */
  59168. ColorCurves.Bind = function (colorCurves, effect) {
  59169. if (colorCurves._dirty) {
  59170. colorCurves._dirty = false;
  59171. // Fill in global info.
  59172. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  59173. // Compute highlights info.
  59174. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  59175. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  59176. // Compute midtones info.
  59177. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  59178. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  59179. // Compute shadows info.
  59180. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  59181. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  59182. // Compute deltas (neutral is midtones).
  59183. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  59184. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  59185. }
  59186. effect.setFloat4("vCameraColorCurvePositive", colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  59187. effect.setFloat4("vCameraColorCurveNeutral", colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  59188. effect.setFloat4("vCameraColorCurveNegative", colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  59189. };
  59190. /**
  59191. * Prepare the list of uniforms associated with the ColorCurves effects.
  59192. * @param uniformsList The list of uniforms used in the effect
  59193. */
  59194. ColorCurves.PrepareUniforms = function (uniformsList) {
  59195. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  59196. };
  59197. /**
  59198. * Returns color grading data based on a hue, density, saturation and exposure value.
  59199. * @param filterHue The hue of the color filter.
  59200. * @param filterDensity The density of the color filter.
  59201. * @param saturation The saturation.
  59202. * @param exposure The exposure.
  59203. * @param result The result data container.
  59204. */
  59205. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  59206. if (hue == null) {
  59207. return;
  59208. }
  59209. hue = ColorCurves.clamp(hue, 0, 360);
  59210. density = ColorCurves.clamp(density, -100, 100);
  59211. saturation = ColorCurves.clamp(saturation, -100, 100);
  59212. exposure = ColorCurves.clamp(exposure, -100, 100);
  59213. // Remap the slider/config filter density with non-linear mapping and also scale by half
  59214. // so that the maximum filter density is only 50% control. This provides fine control
  59215. // for small values and reasonable range.
  59216. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  59217. density *= 0.5;
  59218. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  59219. if (density < 0) {
  59220. density *= -1;
  59221. hue = (hue + 180) % 360;
  59222. }
  59223. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  59224. result.scaleToRef(2, result);
  59225. result.a = 1 + 0.01 * saturation;
  59226. };
  59227. /**
  59228. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  59229. * @param value The input slider value in range [-100,100].
  59230. * @returns Adjusted value.
  59231. */
  59232. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  59233. value /= 100;
  59234. var x = Math.abs(value);
  59235. x = Math.pow(x, 2);
  59236. if (value < 0) {
  59237. x *= -1;
  59238. }
  59239. x *= 100;
  59240. return x;
  59241. };
  59242. /**
  59243. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  59244. * @param hue The hue (H) input.
  59245. * @param saturation The saturation (S) input.
  59246. * @param brightness The brightness (B) input.
  59247. * @result An RGBA color represented as Vector4.
  59248. */
  59249. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  59250. var h = ColorCurves.clamp(hue, 0, 360);
  59251. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  59252. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  59253. if (s === 0) {
  59254. result.r = v;
  59255. result.g = v;
  59256. result.b = v;
  59257. }
  59258. else {
  59259. // sector 0 to 5
  59260. h /= 60;
  59261. var i = Math.floor(h);
  59262. // fractional part of h
  59263. var f = h - i;
  59264. var p = v * (1 - s);
  59265. var q = v * (1 - s * f);
  59266. var t = v * (1 - s * (1 - f));
  59267. switch (i) {
  59268. case 0:
  59269. result.r = v;
  59270. result.g = t;
  59271. result.b = p;
  59272. break;
  59273. case 1:
  59274. result.r = q;
  59275. result.g = v;
  59276. result.b = p;
  59277. break;
  59278. case 2:
  59279. result.r = p;
  59280. result.g = v;
  59281. result.b = t;
  59282. break;
  59283. case 3:
  59284. result.r = p;
  59285. result.g = q;
  59286. result.b = v;
  59287. break;
  59288. case 4:
  59289. result.r = t;
  59290. result.g = p;
  59291. result.b = v;
  59292. break;
  59293. default:
  59294. result.r = v;
  59295. result.g = p;
  59296. result.b = q;
  59297. break;
  59298. }
  59299. }
  59300. result.a = 1;
  59301. };
  59302. /**
  59303. * Returns a value clamped between min and max
  59304. * @param value The value to clamp
  59305. * @param min The minimum of value
  59306. * @param max The maximum of value
  59307. * @returns The clamped value.
  59308. */
  59309. ColorCurves.clamp = function (value, min, max) {
  59310. return Math.min(Math.max(value, min), max);
  59311. };
  59312. /**
  59313. * Clones the current color curve instance.
  59314. * @return The cloned curves
  59315. */
  59316. ColorCurves.prototype.clone = function () {
  59317. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  59318. };
  59319. /**
  59320. * Serializes the current color curve instance to a json representation.
  59321. * @return a JSON representation
  59322. */
  59323. ColorCurves.prototype.serialize = function () {
  59324. return BABYLON.SerializationHelper.Serialize(this);
  59325. };
  59326. /**
  59327. * Parses the color curve from a json representation.
  59328. * @param source the JSON source to parse
  59329. * @return The parsed curves
  59330. */
  59331. ColorCurves.Parse = function (source) {
  59332. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  59333. };
  59334. __decorate([
  59335. BABYLON.serialize()
  59336. ], ColorCurves.prototype, "_globalHue", void 0);
  59337. __decorate([
  59338. BABYLON.serialize()
  59339. ], ColorCurves.prototype, "_globalDensity", void 0);
  59340. __decorate([
  59341. BABYLON.serialize()
  59342. ], ColorCurves.prototype, "_globalSaturation", void 0);
  59343. __decorate([
  59344. BABYLON.serialize()
  59345. ], ColorCurves.prototype, "_globalExposure", void 0);
  59346. __decorate([
  59347. BABYLON.serialize()
  59348. ], ColorCurves.prototype, "_highlightsHue", void 0);
  59349. __decorate([
  59350. BABYLON.serialize()
  59351. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  59352. __decorate([
  59353. BABYLON.serialize()
  59354. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  59355. __decorate([
  59356. BABYLON.serialize()
  59357. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  59358. __decorate([
  59359. BABYLON.serialize()
  59360. ], ColorCurves.prototype, "_midtonesHue", void 0);
  59361. __decorate([
  59362. BABYLON.serialize()
  59363. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  59364. __decorate([
  59365. BABYLON.serialize()
  59366. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  59367. __decorate([
  59368. BABYLON.serialize()
  59369. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  59370. return ColorCurves;
  59371. }());
  59372. BABYLON.ColorCurves = ColorCurves;
  59373. })(BABYLON || (BABYLON = {}));
  59374. var BABYLON;
  59375. (function (BABYLON) {
  59376. /**
  59377. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  59378. * It can help converting any input color in a desired output one. This can then be used to create effects
  59379. * from sepia, black and white to sixties or futuristic rendering...
  59380. *
  59381. * The only supported format is currently 3dl.
  59382. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  59383. */
  59384. var ColorGradingTexture = (function (_super) {
  59385. __extends(ColorGradingTexture, _super);
  59386. /**
  59387. * Instantiates a ColorGradingTexture from the following parameters.
  59388. *
  59389. * @param url The location of the color gradind data (currently only supporting 3dl)
  59390. * @param scene The scene the texture will be used in
  59391. */
  59392. function ColorGradingTexture(url, scene) {
  59393. _super.call(this, scene);
  59394. if (!url) {
  59395. return;
  59396. }
  59397. this._textureMatrix = BABYLON.Matrix.Identity();
  59398. this.name = url;
  59399. this.url = url;
  59400. this.hasAlpha = false;
  59401. this.isCube = false;
  59402. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59403. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59404. this.anisotropicFilteringLevel = 1;
  59405. this._texture = this._getFromCache(url, true);
  59406. if (!this._texture) {
  59407. if (!scene.useDelayedTextureLoading) {
  59408. this.loadTexture();
  59409. }
  59410. else {
  59411. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  59412. }
  59413. }
  59414. }
  59415. /**
  59416. * Returns the texture matrix used in most of the material.
  59417. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  59418. */
  59419. ColorGradingTexture.prototype.getTextureMatrix = function () {
  59420. return this._textureMatrix;
  59421. };
  59422. /**
  59423. * Occurs when the file being loaded is a .3dl LUT file.
  59424. */
  59425. ColorGradingTexture.prototype.load3dlTexture = function () {
  59426. var _this = this;
  59427. var mipLevels = 0;
  59428. var floatArrayView = null;
  59429. var texture = this.getScene().getEngine().createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  59430. this._texture = texture;
  59431. var callback = function (text) {
  59432. var data;
  59433. var tempData;
  59434. var line;
  59435. var lines = text.split('\n');
  59436. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  59437. var maxColor = 0;
  59438. for (var i = 0; i < lines.length; i++) {
  59439. line = lines[i];
  59440. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  59441. continue;
  59442. if (line.indexOf('#') === 0)
  59443. continue;
  59444. var words = line.split(" ");
  59445. if (size === 0) {
  59446. // Number of space + one
  59447. size = words.length;
  59448. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  59449. tempData = new Float32Array(size * size * size * 4);
  59450. continue;
  59451. }
  59452. if (size != 0) {
  59453. var r = Math.max(parseInt(words[0]), 0);
  59454. var g = Math.max(parseInt(words[1]), 0);
  59455. var b = Math.max(parseInt(words[2]), 0);
  59456. maxColor = Math.max(r, maxColor);
  59457. maxColor = Math.max(g, maxColor);
  59458. maxColor = Math.max(b, maxColor);
  59459. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  59460. tempData[pixelStorageIndex + 0] = r;
  59461. tempData[pixelStorageIndex + 1] = g;
  59462. tempData[pixelStorageIndex + 2] = b;
  59463. tempData[pixelStorageIndex + 3] = 0;
  59464. pixelIndexSlice++;
  59465. if (pixelIndexSlice % size == 0) {
  59466. pixelIndexH++;
  59467. pixelIndexSlice = 0;
  59468. if (pixelIndexH % size == 0) {
  59469. pixelIndexW++;
  59470. pixelIndexH = 0;
  59471. }
  59472. }
  59473. }
  59474. }
  59475. for (var i = 0; i < tempData.length; i++) {
  59476. var value = tempData[i];
  59477. data[i] = (value / maxColor * 255);
  59478. }
  59479. _this.getScene().getEngine().updateTextureSize(texture, size * size, size);
  59480. _this.getScene().getEngine().updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  59481. };
  59482. BABYLON.Tools.LoadFile(this.url, callback);
  59483. return this._texture;
  59484. };
  59485. /**
  59486. * Starts the loading process of the texture.
  59487. */
  59488. ColorGradingTexture.prototype.loadTexture = function () {
  59489. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  59490. this.load3dlTexture();
  59491. }
  59492. };
  59493. /**
  59494. * Clones the color gradind texture.
  59495. */
  59496. ColorGradingTexture.prototype.clone = function () {
  59497. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  59498. // Base texture
  59499. newTexture.level = this.level;
  59500. return newTexture;
  59501. };
  59502. /**
  59503. * Called during delayed load for textures.
  59504. */
  59505. ColorGradingTexture.prototype.delayLoad = function () {
  59506. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  59507. return;
  59508. }
  59509. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  59510. this._texture = this._getFromCache(this.url, true);
  59511. if (!this._texture) {
  59512. this.loadTexture();
  59513. }
  59514. };
  59515. /**
  59516. * Binds the color grading to the shader.
  59517. * @param colorGrading The texture to bind
  59518. * @param effect The effect to bind to
  59519. */
  59520. ColorGradingTexture.Bind = function (colorGrading, effect) {
  59521. effect.setTexture("cameraColorGrading2DSampler", colorGrading);
  59522. var x = colorGrading.level; // Texture Level
  59523. var y = colorGrading.getSize().height; // Texture Size example with 8
  59524. var z = y - 1.0; // SizeMinusOne 8 - 1
  59525. var w = 1 / y; // Space of 1 slice 1 / 8
  59526. effect.setFloat4("vCameraColorGradingInfos", x, y, z, w);
  59527. var slicePixelSizeU = w / y; // Space of 1 pixel in U direction, e.g. 1/64
  59528. var slicePixelSizeV = w; // Space of 1 pixel in V direction, e.g. 1/8 // Space of 1 pixel in V direction, e.g. 1/8
  59529. var x2 = z * slicePixelSizeU; // Extent of lookup range in U for a single slice so that range corresponds to (size-1) texels, for example 7/64
  59530. var y2 = z / y; // Extent of lookup range in V for a single slice so that range corresponds to (size-1) texels, for example 7/8
  59531. var z2 = 0.5 * slicePixelSizeU; // Offset of lookup range in U to align sample position with texel centre, for example 0.5/64
  59532. var w2 = 0.5 * slicePixelSizeV; // Offset of lookup range in V to align sample position with texel centre, for example 0.5/8
  59533. effect.setFloat4("vCameraColorGradingScaleOffset", x2, y2, z2, w2);
  59534. };
  59535. /**
  59536. * Prepare the list of uniforms associated with the ColorGrading effects.
  59537. * @param uniformsList The list of uniforms used in the effect
  59538. * @param samplersList The list of samplers used in the effect
  59539. */
  59540. ColorGradingTexture.PrepareUniformsAndSamplers = function (uniformsList, samplersList) {
  59541. uniformsList.push("vCameraColorGradingInfos", "vCameraColorGradingScaleOffset");
  59542. samplersList.push("cameraColorGrading2DSampler");
  59543. };
  59544. /**
  59545. * Parses a color grading texture serialized by Babylon.
  59546. * @param parsedTexture The texture information being parsedTexture
  59547. * @param scene The scene to load the texture in
  59548. * @param rootUrl The root url of the data assets to load
  59549. * @return A color gradind texture
  59550. */
  59551. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  59552. var texture = null;
  59553. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  59554. texture = new BABYLON.ColorGradingTexture(parsedTexture.name, scene);
  59555. texture.name = parsedTexture.name;
  59556. texture.level = parsedTexture.level;
  59557. }
  59558. return texture;
  59559. };
  59560. /**
  59561. * Serializes the LUT texture to json format.
  59562. */
  59563. ColorGradingTexture.prototype.serialize = function () {
  59564. if (!this.name) {
  59565. return null;
  59566. }
  59567. var serializationObject = {};
  59568. serializationObject.name = this.name;
  59569. serializationObject.level = this.level;
  59570. serializationObject.customType = "BABYLON.ColorGradingTexture";
  59571. return serializationObject;
  59572. };
  59573. /**
  59574. * Empty line regex stored for GC.
  59575. */
  59576. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  59577. return ColorGradingTexture;
  59578. }(BABYLON.BaseTexture));
  59579. BABYLON.ColorGradingTexture = ColorGradingTexture;
  59580. })(BABYLON || (BABYLON = {}));
  59581. var BABYLON;
  59582. (function (BABYLON) {
  59583. var PBRMaterialDefines = (function (_super) {
  59584. __extends(PBRMaterialDefines, _super);
  59585. function PBRMaterialDefines() {
  59586. _super.call(this);
  59587. this.ALBEDO = false;
  59588. this.AMBIENT = false;
  59589. this.OPACITY = false;
  59590. this.OPACITYRGB = false;
  59591. this.REFLECTION = false;
  59592. this.EMISSIVE = false;
  59593. this.REFLECTIVITY = false;
  59594. this.BUMP = false;
  59595. this.PARALLAX = false;
  59596. this.PARALLAXOCCLUSION = false;
  59597. this.SPECULAROVERALPHA = false;
  59598. this.CLIPPLANE = false;
  59599. this.ALPHATEST = false;
  59600. this.ALPHAFROMALBEDO = false;
  59601. this.POINTSIZE = false;
  59602. this.FOG = false;
  59603. this.SPECULARTERM = false;
  59604. this.OPACITYFRESNEL = false;
  59605. this.EMISSIVEFRESNEL = false;
  59606. this.FRESNEL = false;
  59607. this.NORMAL = false;
  59608. this.UV1 = false;
  59609. this.UV2 = false;
  59610. this.VERTEXCOLOR = false;
  59611. this.VERTEXALPHA = false;
  59612. this.NUM_BONE_INFLUENCERS = 0;
  59613. this.BonesPerMesh = 0;
  59614. this.INSTANCES = false;
  59615. this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  59616. this.MICROSURFACEAUTOMATIC = false;
  59617. this.EMISSIVEASILLUMINATION = false;
  59618. this.LINKEMISSIVEWITHALBEDO = false;
  59619. this.LIGHTMAP = false;
  59620. this.USELIGHTMAPASSHADOWMAP = false;
  59621. this.REFLECTIONMAP_3D = false;
  59622. this.REFLECTIONMAP_SPHERICAL = false;
  59623. this.REFLECTIONMAP_PLANAR = false;
  59624. this.REFLECTIONMAP_CUBIC = false;
  59625. this.REFLECTIONMAP_PROJECTION = false;
  59626. this.REFLECTIONMAP_SKYBOX = false;
  59627. this.REFLECTIONMAP_EXPLICIT = false;
  59628. this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  59629. this.INVERTCUBICMAP = false;
  59630. this.LOGARITHMICDEPTH = false;
  59631. this.CAMERATONEMAP = false;
  59632. this.CAMERACONTRAST = false;
  59633. this.CAMERACOLORGRADING = false;
  59634. this.CAMERACOLORCURVES = false;
  59635. this.OVERLOADEDVALUES = false;
  59636. this.OVERLOADEDSHADOWVALUES = false;
  59637. this.USESPHERICALFROMREFLECTIONMAP = false;
  59638. this.REFRACTION = false;
  59639. this.REFRACTIONMAP_3D = false;
  59640. this.LINKREFRACTIONTOTRANSPARENCY = false;
  59641. this.REFRACTIONMAPINLINEARSPACE = false;
  59642. this.LODBASEDMICROSFURACE = false;
  59643. this.USEPHYSICALLIGHTFALLOFF = false;
  59644. this.RADIANCEOVERALPHA = false;
  59645. this.USEPMREMREFLECTION = false;
  59646. this.USEPMREMREFRACTION = false;
  59647. this.OPENGLNORMALMAP = false;
  59648. this.INVERTNORMALMAPX = false;
  59649. this.INVERTNORMALMAPY = false;
  59650. this.SHADOWFULLFLOAT = false;
  59651. this.rebuild();
  59652. }
  59653. return PBRMaterialDefines;
  59654. }(BABYLON.MaterialDefines));
  59655. /**
  59656. * The Physically based material of BJS.
  59657. *
  59658. * This offers the main features of a standard PBR material.
  59659. * For more information, please refer to the documentation :
  59660. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  59661. */
  59662. var PBRMaterial = (function (_super) {
  59663. __extends(PBRMaterial, _super);
  59664. /**
  59665. * Instantiates a new PBRMaterial instance.
  59666. *
  59667. * @param name The material name
  59668. * @param scene The scene the material will be use in.
  59669. */
  59670. function PBRMaterial(name, scene) {
  59671. var _this = this;
  59672. _super.call(this, name, scene);
  59673. /**
  59674. * Intensity of the direct lights e.g. the four lights available in your scene.
  59675. * This impacts both the direct diffuse and specular highlights.
  59676. */
  59677. this.directIntensity = 1.0;
  59678. /**
  59679. * Intensity of the emissive part of the material.
  59680. * This helps controlling the emissive effect without modifying the emissive color.
  59681. */
  59682. this.emissiveIntensity = 1.0;
  59683. /**
  59684. * Intensity of the environment e.g. how much the environment will light the object
  59685. * either through harmonics for rough material or through the refelction for shiny ones.
  59686. */
  59687. this.environmentIntensity = 1.0;
  59688. /**
  59689. * This is a special control allowing the reduction of the specular highlights coming from the
  59690. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  59691. */
  59692. this.specularIntensity = 1.0;
  59693. this._lightingInfos = new BABYLON.Vector4(this.directIntensity, this.emissiveIntensity, this.environmentIntensity, this.specularIntensity);
  59694. /**
  59695. * Debug Control allowing disabling the bump map on this material.
  59696. */
  59697. this.disableBumpMap = false;
  59698. /**
  59699. * Debug Control helping enforcing or dropping the darkness of shadows.
  59700. * 1.0 means the shadows have their normal darkness, 0.0 means the shadows are not visible.
  59701. */
  59702. this.overloadedShadowIntensity = 1.0;
  59703. /**
  59704. * Debug Control helping dropping the shading effect coming from the diffuse lighting.
  59705. * 1.0 means the shade have their normal impact, 0.0 means no shading at all.
  59706. */
  59707. this.overloadedShadeIntensity = 1.0;
  59708. this._overloadedShadowInfos = new BABYLON.Vector4(this.overloadedShadowIntensity, this.overloadedShadeIntensity, 0.0, 0.0);
  59709. /**
  59710. * The camera exposure used on this material.
  59711. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  59712. * This corresponds to a photographic exposure.
  59713. */
  59714. this.cameraExposure = 1.0;
  59715. /**
  59716. * The camera contrast used on this material.
  59717. * This property is here and not in the camera to allow controlling contrast without full screen post process.
  59718. */
  59719. this.cameraContrast = 1.0;
  59720. /**
  59721. * Color Grading 2D Lookup Texture.
  59722. * This allows special effects like sepia, black and white to sixties rendering style.
  59723. */
  59724. this.cameraColorGradingTexture = null;
  59725. /**
  59726. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  59727. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  59728. * 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;
  59729. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  59730. */
  59731. this.cameraColorCurves = null;
  59732. this._cameraInfos = new BABYLON.Vector4(1.0, 1.0, 0.0, 0.0);
  59733. this._microsurfaceTextureLods = new BABYLON.Vector2(0.0, 0.0);
  59734. /**
  59735. * Debug Control allowing to overload the ambient color.
  59736. * This as to be use with the overloadedAmbientIntensity parameter.
  59737. */
  59738. this.overloadedAmbient = BABYLON.Color3.White();
  59739. /**
  59740. * Debug Control indicating how much the overloaded ambient color is used against the default one.
  59741. */
  59742. this.overloadedAmbientIntensity = 0.0;
  59743. /**
  59744. * Debug Control allowing to overload the albedo color.
  59745. * This as to be use with the overloadedAlbedoIntensity parameter.
  59746. */
  59747. this.overloadedAlbedo = BABYLON.Color3.White();
  59748. /**
  59749. * Debug Control indicating how much the overloaded albedo color is used against the default one.
  59750. */
  59751. this.overloadedAlbedoIntensity = 0.0;
  59752. /**
  59753. * Debug Control allowing to overload the reflectivity color.
  59754. * This as to be use with the overloadedReflectivityIntensity parameter.
  59755. */
  59756. this.overloadedReflectivity = new BABYLON.Color3(0.3, 0.3, 0.3);
  59757. /**
  59758. * Debug Control indicating how much the overloaded reflectivity color is used against the default one.
  59759. */
  59760. this.overloadedReflectivityIntensity = 0.0;
  59761. /**
  59762. * Debug Control allowing to overload the emissive color.
  59763. * This as to be use with the overloadedEmissiveIntensity parameter.
  59764. */
  59765. this.overloadedEmissive = BABYLON.Color3.White();
  59766. /**
  59767. * Debug Control indicating how much the overloaded emissive color is used against the default one.
  59768. */
  59769. this.overloadedEmissiveIntensity = 0.0;
  59770. this._overloadedIntensity = new BABYLON.Vector4(this.overloadedAmbientIntensity, this.overloadedAlbedoIntensity, this.overloadedReflectivityIntensity, this.overloadedEmissiveIntensity);
  59771. /**
  59772. * Debug Control allowing to overload the reflection color.
  59773. * This as to be use with the overloadedReflectionIntensity parameter.
  59774. */
  59775. this.overloadedReflection = BABYLON.Color3.White();
  59776. /**
  59777. * Debug Control indicating how much the overloaded reflection color is used against the default one.
  59778. */
  59779. this.overloadedReflectionIntensity = 0.0;
  59780. /**
  59781. * Debug Control allowing to overload the microsurface.
  59782. * This as to be use with the overloadedMicroSurfaceIntensity parameter.
  59783. */
  59784. this.overloadedMicroSurface = 0.0;
  59785. /**
  59786. * Debug Control indicating how much the overloaded microsurface is used against the default one.
  59787. */
  59788. this.overloadedMicroSurfaceIntensity = 0.0;
  59789. this._overloadedMicroSurface = new BABYLON.Vector3(this.overloadedMicroSurface, this.overloadedMicroSurfaceIntensity, this.overloadedReflectionIntensity);
  59790. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  59791. /**
  59792. * AKA Diffuse Color in other nomenclature.
  59793. */
  59794. this.albedoColor = new BABYLON.Color3(1, 1, 1);
  59795. /**
  59796. * AKA Specular Color in other nomenclature.
  59797. */
  59798. this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  59799. this.reflectionColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  59800. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  59801. /**
  59802. * AKA Glossiness in other nomenclature.
  59803. */
  59804. this.microSurface = 0.9;
  59805. /**
  59806. * source material index of refraction (IOR)' / 'destination material IOR.
  59807. */
  59808. this.indexOfRefraction = 0.66;
  59809. /**
  59810. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  59811. */
  59812. this.invertRefractionY = false;
  59813. /**
  59814. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  59815. * Materials half opaque for instance using refraction could benefit from this control.
  59816. */
  59817. this.linkRefractionWithTransparency = false;
  59818. /**
  59819. * The emissive and albedo are linked to never be more than one (Energy conservation).
  59820. */
  59821. this.linkEmissiveWithAlbedo = false;
  59822. this.useLightmapAsShadowmap = false;
  59823. /**
  59824. * In this mode, the emissive informtaion will always be added to the lighting once.
  59825. * A light for instance can be thought as emissive.
  59826. */
  59827. this.useEmissiveAsIllumination = false;
  59828. /**
  59829. * Secifies that the alpha is coming form the albedo channel alpha channel.
  59830. */
  59831. this.useAlphaFromAlbedoTexture = false;
  59832. /**
  59833. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  59834. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  59835. */
  59836. this.useSpecularOverAlpha = true;
  59837. /**
  59838. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  59839. */
  59840. this.useMicroSurfaceFromReflectivityMapAlpha = false;
  59841. /**
  59842. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  59843. * The material will try to infer what glossiness each pixel should be.
  59844. */
  59845. this.useAutoMicroSurfaceFromReflectivityMap = false;
  59846. /**
  59847. * Allows to work with scalar in linear mode. This is definitely a matter of preferences and tools used during
  59848. * the creation of the material.
  59849. */
  59850. this.useScalarInLinearSpace = false;
  59851. /**
  59852. * BJS is using an harcoded light falloff based on a manually sets up range.
  59853. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  59854. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  59855. */
  59856. this.usePhysicalLightFalloff = true;
  59857. /**
  59858. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  59859. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  59860. */
  59861. this.useRadianceOverAlpha = true;
  59862. /**
  59863. * Allows using the bump map in parallax mode.
  59864. */
  59865. this.useParallax = false;
  59866. /**
  59867. * Allows using the bump map in parallax occlusion mode.
  59868. */
  59869. this.useParallaxOcclusion = false;
  59870. /**
  59871. * Controls the scale bias of the parallax mode.
  59872. */
  59873. this.parallaxScaleBias = 0.05;
  59874. /**
  59875. * If sets to true, disables all the lights affecting the material.
  59876. */
  59877. this.disableLighting = false;
  59878. /**
  59879. * Number of Simultaneous lights allowed on the material.
  59880. */
  59881. this.maxSimultaneousLights = 4;
  59882. /**
  59883. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  59884. */
  59885. this.invertNormalMapX = false;
  59886. /**
  59887. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  59888. */
  59889. this.invertNormalMapY = false;
  59890. this._renderTargets = new BABYLON.SmartArray(16);
  59891. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  59892. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  59893. this._tempColor = new BABYLON.Color3();
  59894. this._defines = new PBRMaterialDefines();
  59895. this._cachedDefines = new PBRMaterialDefines();
  59896. this._myScene = null;
  59897. this._myShadowGenerator = null;
  59898. this._cachedDefines.BonesPerMesh = -1;
  59899. this.getRenderTargetTextures = function () {
  59900. _this._renderTargets.reset();
  59901. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  59902. _this._renderTargets.push(_this.reflectionTexture);
  59903. }
  59904. if (_this.refractionTexture && _this.refractionTexture.isRenderTarget) {
  59905. _this._renderTargets.push(_this.refractionTexture);
  59906. }
  59907. return _this._renderTargets;
  59908. };
  59909. }
  59910. Object.defineProperty(PBRMaterial.prototype, "useLogarithmicDepth", {
  59911. get: function () {
  59912. return this._useLogarithmicDepth;
  59913. },
  59914. set: function (value) {
  59915. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  59916. },
  59917. enumerable: true,
  59918. configurable: true
  59919. });
  59920. PBRMaterial.prototype.needAlphaBlending = function () {
  59921. if (this.linkRefractionWithTransparency) {
  59922. return false;
  59923. }
  59924. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  59925. };
  59926. PBRMaterial.prototype.needAlphaTesting = function () {
  59927. if (this.linkRefractionWithTransparency) {
  59928. return false;
  59929. }
  59930. return this.albedoTexture != null && this.albedoTexture.hasAlpha;
  59931. };
  59932. PBRMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  59933. return this.albedoTexture != null && this.albedoTexture.hasAlpha && this.useAlphaFromAlbedoTexture;
  59934. };
  59935. PBRMaterial.prototype.getAlphaTestTexture = function () {
  59936. return this.albedoTexture;
  59937. };
  59938. PBRMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  59939. if (!mesh) {
  59940. return true;
  59941. }
  59942. if (this._defines.INSTANCES !== useInstances) {
  59943. return false;
  59944. }
  59945. if (mesh._materialDefines && mesh._materialDefines.isEqual(this._defines)) {
  59946. return true;
  59947. }
  59948. return false;
  59949. };
  59950. PBRMaterial.prototype.convertColorToLinearSpaceToRef = function (color, ref) {
  59951. PBRMaterial.convertColorToLinearSpaceToRef(color, ref, this.useScalarInLinearSpace);
  59952. };
  59953. PBRMaterial.convertColorToLinearSpaceToRef = function (color, ref, useScalarInLinear) {
  59954. if (!useScalarInLinear) {
  59955. color.toLinearSpaceToRef(ref);
  59956. }
  59957. else {
  59958. ref.r = color.r;
  59959. ref.g = color.g;
  59960. ref.b = color.b;
  59961. }
  59962. };
  59963. PBRMaterial.BindLights = function (scene, mesh, effect, defines, useScalarInLinearSpace, maxSimultaneousLights, usePhysicalLightFalloff) {
  59964. var lightIndex = 0;
  59965. var depthValuesAlreadySet = false;
  59966. for (var index = 0; index < scene.lights.length; index++) {
  59967. var light = scene.lights[index];
  59968. if (!light.isEnabled()) {
  59969. continue;
  59970. }
  59971. if (!light.canAffectMesh(mesh)) {
  59972. continue;
  59973. }
  59974. BABYLON.MaterialHelper.BindLightProperties(light, effect, lightIndex);
  59975. // GAMMA CORRECTION.
  59976. this.convertColorToLinearSpaceToRef(light.diffuse, PBRMaterial._scaledAlbedo, useScalarInLinearSpace);
  59977. PBRMaterial._scaledAlbedo.scaleToRef(light.intensity, PBRMaterial._scaledAlbedo);
  59978. effect.setColor4("vLightDiffuse" + lightIndex, PBRMaterial._scaledAlbedo, usePhysicalLightFalloff ? light.radius : light.range);
  59979. if (defines["SPECULARTERM"]) {
  59980. this.convertColorToLinearSpaceToRef(light.specular, PBRMaterial._scaledReflectivity, useScalarInLinearSpace);
  59981. PBRMaterial._scaledReflectivity.scaleToRef(light.intensity, PBRMaterial._scaledReflectivity);
  59982. effect.setColor3("vLightSpecular" + lightIndex, PBRMaterial._scaledReflectivity);
  59983. }
  59984. // Shadows
  59985. if (scene.shadowsEnabled) {
  59986. depthValuesAlreadySet = BABYLON.MaterialHelper.BindLightShadow(light, scene, mesh, lightIndex, effect, depthValuesAlreadySet);
  59987. }
  59988. lightIndex++;
  59989. if (lightIndex === maxSimultaneousLights)
  59990. break;
  59991. }
  59992. };
  59993. PBRMaterial.prototype.isReady = function (mesh, useInstances) {
  59994. if (this.checkReadyOnlyOnce) {
  59995. if (this._wasPreviouslyReady) {
  59996. return true;
  59997. }
  59998. }
  59999. var scene = this.getScene();
  60000. if (!this.checkReadyOnEveryCall) {
  60001. if (this._renderId === scene.getRenderId()) {
  60002. if (this._checkCache(scene, mesh, useInstances)) {
  60003. return true;
  60004. }
  60005. }
  60006. }
  60007. var engine = scene.getEngine();
  60008. var needNormals = false;
  60009. var needUVs = false;
  60010. this._defines.reset();
  60011. if (scene.texturesEnabled) {
  60012. // Textures
  60013. if (scene.texturesEnabled) {
  60014. if (scene.getEngine().getCaps().textureLOD) {
  60015. this._defines.LODBASEDMICROSFURACE = true;
  60016. }
  60017. if (this.albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  60018. if (!this.albedoTexture.isReady()) {
  60019. return false;
  60020. }
  60021. else {
  60022. needUVs = true;
  60023. this._defines.ALBEDO = true;
  60024. }
  60025. }
  60026. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  60027. if (!this.ambientTexture.isReady()) {
  60028. return false;
  60029. }
  60030. else {
  60031. needUVs = true;
  60032. this._defines.AMBIENT = true;
  60033. }
  60034. }
  60035. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  60036. if (!this.opacityTexture.isReady()) {
  60037. return false;
  60038. }
  60039. else {
  60040. needUVs = true;
  60041. this._defines.OPACITY = true;
  60042. if (this.opacityTexture.getAlphaFromRGB) {
  60043. this._defines.OPACITYRGB = true;
  60044. }
  60045. }
  60046. }
  60047. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  60048. if (!this.reflectionTexture.isReady()) {
  60049. return false;
  60050. }
  60051. else {
  60052. needNormals = true;
  60053. this._defines.REFLECTION = true;
  60054. if (this.reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  60055. this._defines.INVERTCUBICMAP = true;
  60056. }
  60057. this._defines.REFLECTIONMAP_3D = this.reflectionTexture.isCube;
  60058. switch (this.reflectionTexture.coordinatesMode) {
  60059. case BABYLON.Texture.CUBIC_MODE:
  60060. case BABYLON.Texture.INVCUBIC_MODE:
  60061. this._defines.REFLECTIONMAP_CUBIC = true;
  60062. break;
  60063. case BABYLON.Texture.EXPLICIT_MODE:
  60064. this._defines.REFLECTIONMAP_EXPLICIT = true;
  60065. break;
  60066. case BABYLON.Texture.PLANAR_MODE:
  60067. this._defines.REFLECTIONMAP_PLANAR = true;
  60068. break;
  60069. case BABYLON.Texture.PROJECTION_MODE:
  60070. this._defines.REFLECTIONMAP_PROJECTION = true;
  60071. break;
  60072. case BABYLON.Texture.SKYBOX_MODE:
  60073. this._defines.REFLECTIONMAP_SKYBOX = true;
  60074. break;
  60075. case BABYLON.Texture.SPHERICAL_MODE:
  60076. this._defines.REFLECTIONMAP_SPHERICAL = true;
  60077. break;
  60078. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  60079. this._defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  60080. break;
  60081. }
  60082. if (this.reflectionTexture instanceof BABYLON.HDRCubeTexture && this.reflectionTexture) {
  60083. this._defines.USESPHERICALFROMREFLECTIONMAP = true;
  60084. needNormals = true;
  60085. if (this.reflectionTexture.isPMREM) {
  60086. this._defines.USEPMREMREFLECTION = true;
  60087. }
  60088. }
  60089. }
  60090. }
  60091. if (this.lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  60092. if (!this.lightmapTexture.isReady()) {
  60093. return false;
  60094. }
  60095. else {
  60096. needUVs = true;
  60097. this._defines.LIGHTMAP = true;
  60098. this._defines.USELIGHTMAPASSHADOWMAP = this.useLightmapAsShadowmap;
  60099. }
  60100. }
  60101. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  60102. if (!this.emissiveTexture.isReady()) {
  60103. return false;
  60104. }
  60105. else {
  60106. needUVs = true;
  60107. this._defines.EMISSIVE = true;
  60108. }
  60109. }
  60110. if (this.reflectivityTexture && BABYLON.StandardMaterial.SpecularTextureEnabled) {
  60111. if (!this.reflectivityTexture.isReady()) {
  60112. return false;
  60113. }
  60114. else {
  60115. needUVs = true;
  60116. this._defines.REFLECTIVITY = true;
  60117. this._defines.MICROSURFACEFROMREFLECTIVITYMAP = this.useMicroSurfaceFromReflectivityMapAlpha;
  60118. this._defines.MICROSURFACEAUTOMATIC = this.useAutoMicroSurfaceFromReflectivityMap;
  60119. }
  60120. }
  60121. }
  60122. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this.disableBumpMap) {
  60123. if (!this.bumpTexture.isReady()) {
  60124. return false;
  60125. }
  60126. else {
  60127. needUVs = true;
  60128. this._defines.BUMP = true;
  60129. if (this.useParallax) {
  60130. this._defines.PARALLAX = true;
  60131. if (this.useParallaxOcclusion) {
  60132. this._defines.PARALLAXOCCLUSION = true;
  60133. }
  60134. }
  60135. if (this.invertNormalMapX) {
  60136. this._defines.INVERTNORMALMAPX = true;
  60137. }
  60138. if (this.invertNormalMapY) {
  60139. this._defines.INVERTNORMALMAPY = true;
  60140. }
  60141. }
  60142. }
  60143. if (this.refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  60144. if (!this.refractionTexture.isReady()) {
  60145. return false;
  60146. }
  60147. else {
  60148. needUVs = true;
  60149. this._defines.REFRACTION = true;
  60150. this._defines.REFRACTIONMAP_3D = this.refractionTexture.isCube;
  60151. if (this.linkRefractionWithTransparency) {
  60152. this._defines.LINKREFRACTIONTOTRANSPARENCY = true;
  60153. }
  60154. if (this.refractionTexture instanceof BABYLON.HDRCubeTexture) {
  60155. this._defines.REFRACTIONMAPINLINEARSPACE = true;
  60156. if (this.refractionTexture.isPMREM) {
  60157. this._defines.USEPMREMREFRACTION = true;
  60158. }
  60159. }
  60160. }
  60161. }
  60162. if (this.cameraColorGradingTexture && BABYLON.StandardMaterial.ColorGradingTextureEnabled) {
  60163. if (!this.cameraColorGradingTexture.isReady()) {
  60164. return false;
  60165. }
  60166. else {
  60167. this._defines.CAMERACOLORGRADING = true;
  60168. }
  60169. }
  60170. }
  60171. // Effect
  60172. if (scene.clipPlane) {
  60173. this._defines.CLIPPLANE = true;
  60174. }
  60175. if (engine.getAlphaTesting()) {
  60176. this._defines.ALPHATEST = true;
  60177. }
  60178. if (this._shouldUseAlphaFromAlbedoTexture()) {
  60179. this._defines.ALPHAFROMALBEDO = true;
  60180. }
  60181. if (this.useEmissiveAsIllumination) {
  60182. this._defines.EMISSIVEASILLUMINATION = true;
  60183. }
  60184. if (this.linkEmissiveWithAlbedo) {
  60185. this._defines.LINKEMISSIVEWITHALBEDO = true;
  60186. }
  60187. if (this.useLogarithmicDepth) {
  60188. this._defines.LOGARITHMICDEPTH = true;
  60189. }
  60190. if (this.cameraContrast != 1) {
  60191. this._defines.CAMERACONTRAST = true;
  60192. }
  60193. if (this.cameraExposure != 1) {
  60194. this._defines.CAMERATONEMAP = true;
  60195. }
  60196. if (this.cameraColorCurves) {
  60197. this._defines.CAMERACOLORCURVES = true;
  60198. }
  60199. if (this.overloadedShadeIntensity != 1 ||
  60200. this.overloadedShadowIntensity != 1) {
  60201. this._defines.OVERLOADEDSHADOWVALUES = true;
  60202. }
  60203. if (this.overloadedMicroSurfaceIntensity > 0 ||
  60204. this.overloadedEmissiveIntensity > 0 ||
  60205. this.overloadedReflectivityIntensity > 0 ||
  60206. this.overloadedAlbedoIntensity > 0 ||
  60207. this.overloadedAmbientIntensity > 0 ||
  60208. this.overloadedReflectionIntensity > 0) {
  60209. this._defines.OVERLOADEDVALUES = true;
  60210. }
  60211. // Point size
  60212. if (this.pointsCloud || scene.forcePointsCloud) {
  60213. this._defines.POINTSIZE = true;
  60214. }
  60215. // Fog
  60216. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  60217. this._defines.FOG = true;
  60218. }
  60219. if (scene.lightsEnabled && !this.disableLighting) {
  60220. needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, this._defines, this.maxSimultaneousLights) || needNormals;
  60221. }
  60222. if (BABYLON.StandardMaterial.FresnelEnabled) {
  60223. // Fresnel
  60224. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  60225. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  60226. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  60227. this._defines.OPACITYFRESNEL = true;
  60228. }
  60229. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  60230. this._defines.EMISSIVEFRESNEL = true;
  60231. }
  60232. needNormals = true;
  60233. this._defines.FRESNEL = true;
  60234. }
  60235. }
  60236. if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
  60237. this._defines.SPECULAROVERALPHA = true;
  60238. }
  60239. if (this.usePhysicalLightFalloff) {
  60240. this._defines.USEPHYSICALLIGHTFALLOFF = true;
  60241. }
  60242. if (this.useRadianceOverAlpha) {
  60243. this._defines.RADIANCEOVERALPHA = true;
  60244. }
  60245. // Attribs
  60246. if (mesh) {
  60247. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  60248. this._defines.NORMAL = true;
  60249. }
  60250. if (needUVs) {
  60251. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  60252. this._defines.UV1 = true;
  60253. }
  60254. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  60255. this._defines.UV2 = true;
  60256. }
  60257. }
  60258. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  60259. this._defines.VERTEXCOLOR = true;
  60260. if (mesh.hasVertexAlpha) {
  60261. this._defines.VERTEXALPHA = true;
  60262. }
  60263. }
  60264. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  60265. this._defines.NUM_BONE_INFLUENCERS = mesh.numBoneInfluencers;
  60266. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  60267. }
  60268. // Instances
  60269. if (useInstances) {
  60270. this._defines.INSTANCES = true;
  60271. }
  60272. }
  60273. // Get correct effect
  60274. if (!this._defines.isEqual(this._cachedDefines)) {
  60275. this._defines.cloneTo(this._cachedDefines);
  60276. scene.resetCachedMaterial();
  60277. // Fallbacks
  60278. var fallbacks = new BABYLON.EffectFallbacks();
  60279. if (this._defines.REFLECTION) {
  60280. fallbacks.addFallback(0, "REFLECTION");
  60281. }
  60282. if (this._defines.REFRACTION) {
  60283. fallbacks.addFallback(0, "REFRACTION");
  60284. }
  60285. if (this._defines.REFLECTIVITY) {
  60286. fallbacks.addFallback(0, "REFLECTIVITY");
  60287. }
  60288. if (this._defines.BUMP) {
  60289. fallbacks.addFallback(0, "BUMP");
  60290. }
  60291. if (this._defines.PARALLAX) {
  60292. fallbacks.addFallback(1, "PARALLAX");
  60293. }
  60294. if (this._defines.PARALLAXOCCLUSION) {
  60295. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  60296. }
  60297. if (this._defines.SPECULAROVERALPHA) {
  60298. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  60299. }
  60300. if (this._defines.FOG) {
  60301. fallbacks.addFallback(1, "FOG");
  60302. }
  60303. if (this._defines.POINTSIZE) {
  60304. fallbacks.addFallback(0, "POINTSIZE");
  60305. }
  60306. if (this._defines.LOGARITHMICDEPTH) {
  60307. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  60308. }
  60309. BABYLON.MaterialHelper.HandleFallbacksForShadows(this._defines, fallbacks, this.maxSimultaneousLights);
  60310. if (this._defines.SPECULARTERM) {
  60311. fallbacks.addFallback(0, "SPECULARTERM");
  60312. }
  60313. if (this._defines.OPACITYFRESNEL) {
  60314. fallbacks.addFallback(1, "OPACITYFRESNEL");
  60315. }
  60316. if (this._defines.EMISSIVEFRESNEL) {
  60317. fallbacks.addFallback(2, "EMISSIVEFRESNEL");
  60318. }
  60319. if (this._defines.FRESNEL) {
  60320. fallbacks.addFallback(3, "FRESNEL");
  60321. }
  60322. if (this._defines.NUM_BONE_INFLUENCERS > 0) {
  60323. fallbacks.addCPUSkinningFallback(0, mesh);
  60324. }
  60325. //Attributes
  60326. var attribs = [BABYLON.VertexBuffer.PositionKind];
  60327. if (this._defines.NORMAL) {
  60328. attribs.push(BABYLON.VertexBuffer.NormalKind);
  60329. }
  60330. if (this._defines.UV1) {
  60331. attribs.push(BABYLON.VertexBuffer.UVKind);
  60332. }
  60333. if (this._defines.UV2) {
  60334. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  60335. }
  60336. if (this._defines.VERTEXCOLOR) {
  60337. attribs.push(BABYLON.VertexBuffer.ColorKind);
  60338. }
  60339. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, this._defines, fallbacks);
  60340. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, this._defines);
  60341. // Legacy browser patch
  60342. var shaderName = "pbr";
  60343. if (!scene.getEngine().getCaps().standardDerivatives) {
  60344. shaderName = "legacypbr";
  60345. }
  60346. var join = this._defines.toString();
  60347. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  60348. "vFogInfos", "vFogColor", "pointSize",
  60349. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vReflectivityInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  60350. "mBones",
  60351. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  60352. "depthValues",
  60353. "opacityParts", "emissiveLeftColor", "emissiveRightColor",
  60354. "vLightingIntensity", "vOverloadedShadowIntensity", "vOverloadedIntensity", "vOverloadedAlbedo", "vOverloadedReflection", "vOverloadedReflectivity", "vOverloadedEmissive", "vOverloadedMicroSurface",
  60355. "logarithmicDepthConstant",
  60356. "vSphericalX", "vSphericalY", "vSphericalZ",
  60357. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  60358. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  60359. "vMicrosurfaceTextureLods",
  60360. "vCameraInfos"
  60361. ];
  60362. var samplers = ["albedoSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "reflectivitySampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  60363. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  60364. BABYLON.ColorGradingTexture.PrepareUniformsAndSamplers(uniforms, samplers);
  60365. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList(uniforms, samplers, this._defines, this.maxSimultaneousLights);
  60366. this._effect = scene.getEngine().createEffect(shaderName, attribs, uniforms, samplers, join, fallbacks, this.onCompiled, this.onError, { maxSimultaneousLights: this.maxSimultaneousLights });
  60367. }
  60368. if (!this._effect.isReady()) {
  60369. return false;
  60370. }
  60371. this._renderId = scene.getRenderId();
  60372. this._wasPreviouslyReady = true;
  60373. if (mesh) {
  60374. if (!mesh._materialDefines) {
  60375. mesh._materialDefines = new PBRMaterialDefines();
  60376. }
  60377. this._defines.cloneTo(mesh._materialDefines);
  60378. }
  60379. return true;
  60380. };
  60381. PBRMaterial.prototype.unbind = function () {
  60382. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  60383. this._effect.setTexture("reflection2DSampler", null);
  60384. }
  60385. if (this.refractionTexture && this.refractionTexture.isRenderTarget) {
  60386. this._effect.setTexture("refraction2DSampler", null);
  60387. }
  60388. _super.prototype.unbind.call(this);
  60389. };
  60390. PBRMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  60391. this._effect.setMatrix("world", world);
  60392. };
  60393. PBRMaterial.prototype.bind = function (world, mesh) {
  60394. this._myScene = this.getScene();
  60395. // Matrices
  60396. this.bindOnlyWorldMatrix(world);
  60397. // Bones
  60398. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  60399. if (this._myScene.getCachedMaterial() !== this) {
  60400. this._effect.setMatrix("viewProjection", this._myScene.getTransformMatrix());
  60401. if (BABYLON.StandardMaterial.FresnelEnabled) {
  60402. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  60403. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  60404. }
  60405. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  60406. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  60407. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  60408. }
  60409. }
  60410. // Textures
  60411. if (this._myScene.texturesEnabled) {
  60412. if (this.albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  60413. this._effect.setTexture("albedoSampler", this.albedoTexture);
  60414. this._effect.setFloat2("vAlbedoInfos", this.albedoTexture.coordinatesIndex, this.albedoTexture.level);
  60415. this._effect.setMatrix("albedoMatrix", this.albedoTexture.getTextureMatrix());
  60416. }
  60417. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  60418. this._effect.setTexture("ambientSampler", this.ambientTexture);
  60419. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  60420. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  60421. }
  60422. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  60423. this._effect.setTexture("opacitySampler", this.opacityTexture);
  60424. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  60425. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  60426. }
  60427. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  60428. this._microsurfaceTextureLods.x = Math.round(Math.log(this.reflectionTexture.getSize().width) * Math.LOG2E);
  60429. if (this.reflectionTexture.isCube) {
  60430. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  60431. }
  60432. else {
  60433. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  60434. }
  60435. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  60436. this._effect.setFloat2("vReflectionInfos", this.reflectionTexture.level, 0);
  60437. if (this._defines.USESPHERICALFROMREFLECTIONMAP) {
  60438. this._effect.setFloat3("vSphericalX", this.reflectionTexture.sphericalPolynomial.x.x, this.reflectionTexture.sphericalPolynomial.x.y, this.reflectionTexture.sphericalPolynomial.x.z);
  60439. this._effect.setFloat3("vSphericalY", this.reflectionTexture.sphericalPolynomial.y.x, this.reflectionTexture.sphericalPolynomial.y.y, this.reflectionTexture.sphericalPolynomial.y.z);
  60440. this._effect.setFloat3("vSphericalZ", this.reflectionTexture.sphericalPolynomial.z.x, this.reflectionTexture.sphericalPolynomial.z.y, this.reflectionTexture.sphericalPolynomial.z.z);
  60441. this._effect.setFloat3("vSphericalXX", this.reflectionTexture.sphericalPolynomial.xx.x, this.reflectionTexture.sphericalPolynomial.xx.y, this.reflectionTexture.sphericalPolynomial.xx.z);
  60442. this._effect.setFloat3("vSphericalYY", this.reflectionTexture.sphericalPolynomial.yy.x, this.reflectionTexture.sphericalPolynomial.yy.y, this.reflectionTexture.sphericalPolynomial.yy.z);
  60443. this._effect.setFloat3("vSphericalZZ", this.reflectionTexture.sphericalPolynomial.zz.x, this.reflectionTexture.sphericalPolynomial.zz.y, this.reflectionTexture.sphericalPolynomial.zz.z);
  60444. this._effect.setFloat3("vSphericalXY", this.reflectionTexture.sphericalPolynomial.xy.x, this.reflectionTexture.sphericalPolynomial.xy.y, this.reflectionTexture.sphericalPolynomial.xy.z);
  60445. this._effect.setFloat3("vSphericalYZ", this.reflectionTexture.sphericalPolynomial.yz.x, this.reflectionTexture.sphericalPolynomial.yz.y, this.reflectionTexture.sphericalPolynomial.yz.z);
  60446. this._effect.setFloat3("vSphericalZX", this.reflectionTexture.sphericalPolynomial.zx.x, this.reflectionTexture.sphericalPolynomial.zx.y, this.reflectionTexture.sphericalPolynomial.zx.z);
  60447. }
  60448. }
  60449. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  60450. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  60451. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  60452. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  60453. }
  60454. if (this.lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  60455. this._effect.setTexture("lightmapSampler", this.lightmapTexture);
  60456. this._effect.setFloat2("vLightmapInfos", this.lightmapTexture.coordinatesIndex, this.lightmapTexture.level);
  60457. this._effect.setMatrix("lightmapMatrix", this.lightmapTexture.getTextureMatrix());
  60458. }
  60459. if (this.reflectivityTexture && BABYLON.StandardMaterial.SpecularTextureEnabled) {
  60460. this._effect.setTexture("reflectivitySampler", this.reflectivityTexture);
  60461. this._effect.setFloat2("vReflectivityInfos", this.reflectivityTexture.coordinatesIndex, this.reflectivityTexture.level);
  60462. this._effect.setMatrix("reflectivityMatrix", this.reflectivityTexture.getTextureMatrix());
  60463. }
  60464. if (this.bumpTexture && this._myScene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this.disableBumpMap) {
  60465. this._effect.setTexture("bumpSampler", this.bumpTexture);
  60466. this._effect.setFloat3("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level, this.parallaxScaleBias);
  60467. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  60468. }
  60469. if (this.refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  60470. this._microsurfaceTextureLods.y = Math.round(Math.log(this.refractionTexture.getSize().width) * Math.LOG2E);
  60471. var depth = 1.0;
  60472. if (this.refractionTexture.isCube) {
  60473. this._effect.setTexture("refractionCubeSampler", this.refractionTexture);
  60474. }
  60475. else {
  60476. this._effect.setTexture("refraction2DSampler", this.refractionTexture);
  60477. this._effect.setMatrix("refractionMatrix", this.refractionTexture.getReflectionTextureMatrix());
  60478. if (this.refractionTexture.depth) {
  60479. depth = this.refractionTexture.depth;
  60480. }
  60481. }
  60482. this._effect.setFloat4("vRefractionInfos", this.refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  60483. }
  60484. if ((this.reflectionTexture || this.refractionTexture)) {
  60485. this._effect.setFloat2("vMicrosurfaceTextureLods", this._microsurfaceTextureLods.x, this._microsurfaceTextureLods.y);
  60486. }
  60487. if (this.cameraColorGradingTexture && BABYLON.StandardMaterial.ColorGradingTextureEnabled) {
  60488. BABYLON.ColorGradingTexture.Bind(this.cameraColorGradingTexture, this._effect);
  60489. }
  60490. }
  60491. // Clip plane
  60492. BABYLON.MaterialHelper.BindClipPlane(this._effect, this._myScene);
  60493. // Point size
  60494. if (this.pointsCloud) {
  60495. this._effect.setFloat("pointSize", this.pointSize);
  60496. }
  60497. // Colors
  60498. this._myScene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  60499. // GAMMA CORRECTION.
  60500. this.convertColorToLinearSpaceToRef(this.reflectivityColor, PBRMaterial._scaledReflectivity);
  60501. this._effect.setVector3("vEyePosition", this._myScene._mirroredCameraPosition ? this._myScene._mirroredCameraPosition : this._myScene.activeCamera.position);
  60502. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  60503. this._effect.setColor4("vReflectivityColor", PBRMaterial._scaledReflectivity, this.microSurface);
  60504. // GAMMA CORRECTION.
  60505. this.convertColorToLinearSpaceToRef(this.emissiveColor, PBRMaterial._scaledEmissive);
  60506. this._effect.setColor3("vEmissiveColor", PBRMaterial._scaledEmissive);
  60507. // GAMMA CORRECTION.
  60508. this.convertColorToLinearSpaceToRef(this.reflectionColor, PBRMaterial._scaledReflection);
  60509. this._effect.setColor3("vReflectionColor", PBRMaterial._scaledReflection);
  60510. }
  60511. if (this._myScene.getCachedMaterial() !== this || !this.isFrozen) {
  60512. // GAMMA CORRECTION.
  60513. this.convertColorToLinearSpaceToRef(this.albedoColor, PBRMaterial._scaledAlbedo);
  60514. this._effect.setColor4("vAlbedoColor", PBRMaterial._scaledAlbedo, this.alpha * mesh.visibility);
  60515. // Lights
  60516. if (this._myScene.lightsEnabled && !this.disableLighting) {
  60517. PBRMaterial.BindLights(this._myScene, mesh, this._effect, this._defines, this.useScalarInLinearSpace, this.maxSimultaneousLights, this.usePhysicalLightFalloff);
  60518. }
  60519. // View
  60520. if (this._myScene.fogEnabled && mesh.applyFog && this._myScene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  60521. this._effect.setMatrix("view", this._myScene.getViewMatrix());
  60522. }
  60523. // Fog
  60524. BABYLON.MaterialHelper.BindFogParameters(this._myScene, mesh, this._effect);
  60525. this._lightingInfos.x = this.directIntensity;
  60526. this._lightingInfos.y = this.emissiveIntensity;
  60527. this._lightingInfos.z = this.environmentIntensity;
  60528. this._lightingInfos.w = this.specularIntensity;
  60529. this._effect.setVector4("vLightingIntensity", this._lightingInfos);
  60530. this._overloadedShadowInfos.x = this.overloadedShadowIntensity;
  60531. this._overloadedShadowInfos.y = this.overloadedShadeIntensity;
  60532. this._effect.setVector4("vOverloadedShadowIntensity", this._overloadedShadowInfos);
  60533. this._cameraInfos.x = this.cameraExposure;
  60534. this._cameraInfos.y = this.cameraContrast;
  60535. this._effect.setVector4("vCameraInfos", this._cameraInfos);
  60536. if (this.cameraColorCurves) {
  60537. BABYLON.ColorCurves.Bind(this.cameraColorCurves, this._effect);
  60538. }
  60539. this._overloadedIntensity.x = this.overloadedAmbientIntensity;
  60540. this._overloadedIntensity.y = this.overloadedAlbedoIntensity;
  60541. this._overloadedIntensity.z = this.overloadedReflectivityIntensity;
  60542. this._overloadedIntensity.w = this.overloadedEmissiveIntensity;
  60543. this._effect.setVector4("vOverloadedIntensity", this._overloadedIntensity);
  60544. this.convertColorToLinearSpaceToRef(this.overloadedAmbient, this._tempColor);
  60545. this._effect.setColor3("vOverloadedAmbient", this._tempColor);
  60546. this.convertColorToLinearSpaceToRef(this.overloadedAlbedo, this._tempColor);
  60547. this._effect.setColor3("vOverloadedAlbedo", this._tempColor);
  60548. this.convertColorToLinearSpaceToRef(this.overloadedReflectivity, this._tempColor);
  60549. this._effect.setColor3("vOverloadedReflectivity", this._tempColor);
  60550. this.convertColorToLinearSpaceToRef(this.overloadedEmissive, this._tempColor);
  60551. this._effect.setColor3("vOverloadedEmissive", this._tempColor);
  60552. this.convertColorToLinearSpaceToRef(this.overloadedReflection, this._tempColor);
  60553. this._effect.setColor3("vOverloadedReflection", this._tempColor);
  60554. this._overloadedMicroSurface.x = this.overloadedMicroSurface;
  60555. this._overloadedMicroSurface.y = this.overloadedMicroSurfaceIntensity;
  60556. this._overloadedMicroSurface.z = this.overloadedReflectionIntensity;
  60557. this._effect.setVector3("vOverloadedMicroSurface", this._overloadedMicroSurface);
  60558. // Log. depth
  60559. BABYLON.MaterialHelper.BindLogDepth(this._defines, this._effect, this._myScene);
  60560. }
  60561. _super.prototype.bind.call(this, world, mesh);
  60562. this._myScene = null;
  60563. };
  60564. PBRMaterial.prototype.getAnimatables = function () {
  60565. var results = [];
  60566. if (this.albedoTexture && this.albedoTexture.animations && this.albedoTexture.animations.length > 0) {
  60567. results.push(this.albedoTexture);
  60568. }
  60569. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  60570. results.push(this.ambientTexture);
  60571. }
  60572. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  60573. results.push(this.opacityTexture);
  60574. }
  60575. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  60576. results.push(this.reflectionTexture);
  60577. }
  60578. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  60579. results.push(this.emissiveTexture);
  60580. }
  60581. if (this.reflectivityTexture && this.reflectivityTexture.animations && this.reflectivityTexture.animations.length > 0) {
  60582. results.push(this.reflectivityTexture);
  60583. }
  60584. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  60585. results.push(this.bumpTexture);
  60586. }
  60587. if (this.lightmapTexture && this.lightmapTexture.animations && this.lightmapTexture.animations.length > 0) {
  60588. results.push(this.lightmapTexture);
  60589. }
  60590. if (this.refractionTexture && this.refractionTexture.animations && this.refractionTexture.animations.length > 0) {
  60591. results.push(this.refractionTexture);
  60592. }
  60593. if (this.cameraColorGradingTexture && this.cameraColorGradingTexture.animations && this.cameraColorGradingTexture.animations.length > 0) {
  60594. results.push(this.cameraColorGradingTexture);
  60595. }
  60596. return results;
  60597. };
  60598. PBRMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  60599. if (forceDisposeTextures) {
  60600. if (this.albedoTexture) {
  60601. this.albedoTexture.dispose();
  60602. }
  60603. if (this.ambientTexture) {
  60604. this.ambientTexture.dispose();
  60605. }
  60606. if (this.opacityTexture) {
  60607. this.opacityTexture.dispose();
  60608. }
  60609. if (this.reflectionTexture) {
  60610. this.reflectionTexture.dispose();
  60611. }
  60612. if (this.emissiveTexture) {
  60613. this.emissiveTexture.dispose();
  60614. }
  60615. if (this.reflectivityTexture) {
  60616. this.reflectivityTexture.dispose();
  60617. }
  60618. if (this.bumpTexture) {
  60619. this.bumpTexture.dispose();
  60620. }
  60621. if (this.lightmapTexture) {
  60622. this.lightmapTexture.dispose();
  60623. }
  60624. if (this.refractionTexture) {
  60625. this.refractionTexture.dispose();
  60626. }
  60627. if (this.cameraColorGradingTexture) {
  60628. this.cameraColorGradingTexture.dispose();
  60629. }
  60630. }
  60631. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  60632. };
  60633. PBRMaterial.prototype.clone = function (name) {
  60634. var _this = this;
  60635. return BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  60636. };
  60637. PBRMaterial.prototype.serialize = function () {
  60638. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  60639. serializationObject.customType = "BABYLON.PBRMaterial";
  60640. return serializationObject;
  60641. };
  60642. // Statics
  60643. PBRMaterial.Parse = function (source, scene, rootUrl) {
  60644. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  60645. };
  60646. PBRMaterial._scaledAlbedo = new BABYLON.Color3();
  60647. PBRMaterial._scaledReflectivity = new BABYLON.Color3();
  60648. PBRMaterial._scaledEmissive = new BABYLON.Color3();
  60649. PBRMaterial._scaledReflection = new BABYLON.Color3();
  60650. __decorate([
  60651. BABYLON.serialize()
  60652. ], PBRMaterial.prototype, "directIntensity", void 0);
  60653. __decorate([
  60654. BABYLON.serialize()
  60655. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  60656. __decorate([
  60657. BABYLON.serialize()
  60658. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  60659. __decorate([
  60660. BABYLON.serialize()
  60661. ], PBRMaterial.prototype, "specularIntensity", void 0);
  60662. __decorate([
  60663. BABYLON.serialize()
  60664. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  60665. __decorate([
  60666. BABYLON.serialize()
  60667. ], PBRMaterial.prototype, "overloadedShadowIntensity", void 0);
  60668. __decorate([
  60669. BABYLON.serialize()
  60670. ], PBRMaterial.prototype, "overloadedShadeIntensity", void 0);
  60671. __decorate([
  60672. BABYLON.serialize()
  60673. ], PBRMaterial.prototype, "cameraExposure", void 0);
  60674. __decorate([
  60675. BABYLON.serialize()
  60676. ], PBRMaterial.prototype, "cameraContrast", void 0);
  60677. __decorate([
  60678. BABYLON.serializeAsTexture()
  60679. ], PBRMaterial.prototype, "cameraColorGradingTexture", void 0);
  60680. __decorate([
  60681. BABYLON.serializeAsColorCurves()
  60682. ], PBRMaterial.prototype, "cameraColorCurves", void 0);
  60683. __decorate([
  60684. BABYLON.serializeAsColor3()
  60685. ], PBRMaterial.prototype, "overloadedAmbient", void 0);
  60686. __decorate([
  60687. BABYLON.serialize()
  60688. ], PBRMaterial.prototype, "overloadedAmbientIntensity", void 0);
  60689. __decorate([
  60690. BABYLON.serializeAsColor3()
  60691. ], PBRMaterial.prototype, "overloadedAlbedo", void 0);
  60692. __decorate([
  60693. BABYLON.serialize()
  60694. ], PBRMaterial.prototype, "overloadedAlbedoIntensity", void 0);
  60695. __decorate([
  60696. BABYLON.serializeAsColor3()
  60697. ], PBRMaterial.prototype, "overloadedReflectivity", void 0);
  60698. __decorate([
  60699. BABYLON.serialize()
  60700. ], PBRMaterial.prototype, "overloadedReflectivityIntensity", void 0);
  60701. __decorate([
  60702. BABYLON.serializeAsColor3()
  60703. ], PBRMaterial.prototype, "overloadedEmissive", void 0);
  60704. __decorate([
  60705. BABYLON.serialize()
  60706. ], PBRMaterial.prototype, "overloadedEmissiveIntensity", void 0);
  60707. __decorate([
  60708. BABYLON.serializeAsColor3()
  60709. ], PBRMaterial.prototype, "overloadedReflection", void 0);
  60710. __decorate([
  60711. BABYLON.serialize()
  60712. ], PBRMaterial.prototype, "overloadedReflectionIntensity", void 0);
  60713. __decorate([
  60714. BABYLON.serialize()
  60715. ], PBRMaterial.prototype, "overloadedMicroSurface", void 0);
  60716. __decorate([
  60717. BABYLON.serialize()
  60718. ], PBRMaterial.prototype, "overloadedMicroSurfaceIntensity", void 0);
  60719. __decorate([
  60720. BABYLON.serializeAsTexture()
  60721. ], PBRMaterial.prototype, "albedoTexture", void 0);
  60722. __decorate([
  60723. BABYLON.serializeAsTexture()
  60724. ], PBRMaterial.prototype, "ambientTexture", void 0);
  60725. __decorate([
  60726. BABYLON.serializeAsTexture()
  60727. ], PBRMaterial.prototype, "opacityTexture", void 0);
  60728. __decorate([
  60729. BABYLON.serializeAsTexture()
  60730. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  60731. __decorate([
  60732. BABYLON.serializeAsTexture()
  60733. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  60734. __decorate([
  60735. BABYLON.serializeAsTexture()
  60736. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  60737. __decorate([
  60738. BABYLON.serializeAsTexture()
  60739. ], PBRMaterial.prototype, "bumpTexture", void 0);
  60740. __decorate([
  60741. BABYLON.serializeAsTexture()
  60742. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  60743. __decorate([
  60744. BABYLON.serializeAsTexture()
  60745. ], PBRMaterial.prototype, "refractionTexture", void 0);
  60746. __decorate([
  60747. BABYLON.serializeAsColor3("ambient")
  60748. ], PBRMaterial.prototype, "ambientColor", void 0);
  60749. __decorate([
  60750. BABYLON.serializeAsColor3("albedo")
  60751. ], PBRMaterial.prototype, "albedoColor", void 0);
  60752. __decorate([
  60753. BABYLON.serializeAsColor3("reflectivity")
  60754. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  60755. __decorate([
  60756. BABYLON.serializeAsColor3("reflection")
  60757. ], PBRMaterial.prototype, "reflectionColor", void 0);
  60758. __decorate([
  60759. BABYLON.serializeAsColor3("emissive")
  60760. ], PBRMaterial.prototype, "emissiveColor", void 0);
  60761. __decorate([
  60762. BABYLON.serialize()
  60763. ], PBRMaterial.prototype, "microSurface", void 0);
  60764. __decorate([
  60765. BABYLON.serialize()
  60766. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  60767. __decorate([
  60768. BABYLON.serialize()
  60769. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  60770. __decorate([
  60771. BABYLON.serializeAsFresnelParameters()
  60772. ], PBRMaterial.prototype, "opacityFresnelParameters", void 0);
  60773. __decorate([
  60774. BABYLON.serializeAsFresnelParameters()
  60775. ], PBRMaterial.prototype, "emissiveFresnelParameters", void 0);
  60776. __decorate([
  60777. BABYLON.serialize()
  60778. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  60779. __decorate([
  60780. BABYLON.serialize()
  60781. ], PBRMaterial.prototype, "linkEmissiveWithAlbedo", void 0);
  60782. __decorate([
  60783. BABYLON.serialize()
  60784. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  60785. __decorate([
  60786. BABYLON.serialize()
  60787. ], PBRMaterial.prototype, "useEmissiveAsIllumination", void 0);
  60788. __decorate([
  60789. BABYLON.serialize()
  60790. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  60791. __decorate([
  60792. BABYLON.serialize()
  60793. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  60794. __decorate([
  60795. BABYLON.serialize()
  60796. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  60797. __decorate([
  60798. BABYLON.serialize()
  60799. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  60800. __decorate([
  60801. BABYLON.serialize()
  60802. ], PBRMaterial.prototype, "useScalarInLinearSpace", void 0);
  60803. __decorate([
  60804. BABYLON.serialize()
  60805. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  60806. __decorate([
  60807. BABYLON.serialize()
  60808. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  60809. __decorate([
  60810. BABYLON.serialize()
  60811. ], PBRMaterial.prototype, "useParallax", void 0);
  60812. __decorate([
  60813. BABYLON.serialize()
  60814. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  60815. __decorate([
  60816. BABYLON.serialize()
  60817. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  60818. __decorate([
  60819. BABYLON.serialize()
  60820. ], PBRMaterial.prototype, "disableLighting", void 0);
  60821. __decorate([
  60822. BABYLON.serialize()
  60823. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  60824. __decorate([
  60825. BABYLON.serialize()
  60826. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  60827. __decorate([
  60828. BABYLON.serialize()
  60829. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  60830. __decorate([
  60831. BABYLON.serialize()
  60832. ], PBRMaterial.prototype, "useLogarithmicDepth", null);
  60833. return PBRMaterial;
  60834. }(BABYLON.Material));
  60835. BABYLON.PBRMaterial = PBRMaterial;
  60836. })(BABYLON || (BABYLON = {}));
  60837. BABYLON.Effect.ShadersStore={"anaglyphPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D leftSampler;\nvoid main(void)\n{\nvec4 leftFrag=texture2D(leftSampler,vUV);\nleftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);\nvec4 rightFrag=texture2D(textureSampler,vUV);\nrightFrag=vec4(rightFrag.r,1.0,1.0,1.0);\ngl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);\n}","blackAndWhitePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\nfloat luminance=dot(texture2D(textureSampler,vUV).rgb,vec3(0.3,0.59,0.11));\ngl_FragColor=vec4(luminance,luminance,luminance,1.0);\n}","blurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\nvoid main(void)\n{\nfloat weights[7];\nweights[0]=0.05;\nweights[1]=0.1;\nweights[2]=0.2;\nweights[3]=0.3;\nweights[4]=0.2;\nweights[5]=0.1;\nweights[6]=0.05;\nvec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);\nvec2 texelStep=texelSize*direction*blurWidth;\nvec2 start=vUV-3.0*texelStep;\nvec4 baseColor=vec4(0.,0.,0.,0.);\nvec2 texelOffset=vec2(0.,0.);\nfor (int i=0; i<7; i++)\n{\nbaseColor+=texture2D(textureSampler,start+texelOffset)*weights[i];\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\n}","chromaticAberrationPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float chromatic_aberration;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec2 centered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nfloat radius2=centered_screen_pos.x*centered_screen_pos.x\n+centered_screen_pos.y*centered_screen_pos.y;\nfloat radius=sqrt(radius2);\nvec4 original=texture2D(textureSampler,vUV);\nif (chromatic_aberration>0.0) {\n\nvec3 ref_indices=vec3(-0.3,0.0,0.3);\nfloat ref_shiftX=chromatic_aberration*radius*17.0/screen_width;\nfloat ref_shiftY=chromatic_aberration*radius*17.0/screen_height;\n\nvec2 ref_coords_r=vec2(vUV.x+ref_indices.r*ref_shiftX,vUV.y+ref_indices.r*ref_shiftY*0.5);\nvec2 ref_coords_g=vec2(vUV.x+ref_indices.g*ref_shiftX,vUV.y+ref_indices.g*ref_shiftY*0.5);\nvec2 ref_coords_b=vec2(vUV.x+ref_indices.b*ref_shiftX,vUV.y+ref_indices.b*ref_shiftY*0.5);\noriginal.r=texture2D(textureSampler,ref_coords_r).r;\noriginal.g=texture2D(textureSampler,ref_coords_g).g;\noriginal.b=texture2D(textureSampler,ref_coords_b).b;\n}\ngl_FragColor=original;\n}","colorPixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","colorVertexShader":"\nattribute vec3 position;\n\nuniform mat4 worldViewProjection;\nvoid main(void) {\ngl_Position=worldViewProjection*vec4(position,1.0);\n}","colorCorrectionPixelShader":"\nuniform sampler2D textureSampler; \nuniform sampler2D colorTable; \n\nvarying vec2 vUV;\n\nconst float SLICE_COUNT=16.0; \n\nvec4 sampleAs3DTexture(sampler2D texture,vec3 uv,float width) {\nfloat sliceSize=1.0/width; \nfloat slicePixelSize=sliceSize/width; \nfloat sliceInnerSize=slicePixelSize*(width-1.0); \nfloat zSlice0=min(floor(uv.z*width),width-1.0);\nfloat zSlice1=min(zSlice0+1.0,width-1.0);\nfloat xOffset=slicePixelSize*0.5+uv.x*sliceInnerSize;\nfloat s0=xOffset+(zSlice0*sliceSize);\nfloat s1=xOffset+(zSlice1*sliceSize);\nvec4 slice0Color=texture2D(texture,vec2(s0,uv.y));\nvec4 slice1Color=texture2D(texture,vec2(s1,uv.y));\nfloat zOffset=mod(uv.z*width,1.0);\nvec4 result=mix(slice0Color,slice1Color,zOffset);\nreturn result;\n}\nvoid main(void)\n{\nvec4 screen_color=texture2D(textureSampler,vUV);\ngl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);\n}","convolutionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform float kernel[9];\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 colorSum =\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];\nfloat kernelWeight =\nkernel[0] +\nkernel[1] +\nkernel[2] +\nkernel[3] +\nkernel[4] +\nkernel[5] +\nkernel[6] +\nkernel[7] +\nkernel[8];\nif (kernelWeight<=0.0) {\nkernelWeight=1.0;\n}\ngl_FragColor=vec4((colorSum/kernelWeight).rgb,1);\n}","defaultPixelShader":"#ifdef BUMP\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n\n#define RECIPROCAL_PI2 0.15915494\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<helperFunctions>\n\n#include<lightFragmentDeclaration>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform sampler2D diffuseSampler;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform sampler2D ambientSampler;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform vec2 vLightmapInfos;\nuniform sampler2D lightmapSampler;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\nuniform mat4 refractionMatrix;\n#endif\n#ifdef REFRACTIONFRESNEL\nuniform vec4 refractionLeftColor;\nuniform vec4 refractionRightColor;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform sampler2D specularSampler;\n#endif\n\n#include<fresnelFunction>\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvarying vec3 vDirectionW;\n#endif\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#endif\n#include<reflectionFunction>\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n#endif\n#ifdef CAMERACOLORGRADING\n#include<colorGradingDefinition> \n#include<colorGrading>\n#endif\n#ifdef CAMERACOLORCURVES\n#include<colorCurvesDefinition>\n#include<colorCurves>\n#endif\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\n#ifdef DIFFUSE\nvec2 diffuseUV=vDiffuseUV;\n#endif\n#include<bumpFragment>\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,diffuseUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#ifdef ALPHAFROMDIFFUSE\nalpha*=baseColor.a;\n#endif\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV).rgb*vAmbientInfos.y;\n#endif\n\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nvec4 specularMapColor=texture2D(specularSampler,vSpecularUV);\nspecularColor=specularMapColor.rgb;\n#ifdef GLOSSINESS\nglossiness=glossiness*specularMapColor.a;\n#endif\n#endif\n#else\nfloat glossiness=0.;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\nfloat shadow=1.;\n#include<lightFragment>[0..maxSimultaneousLights]\n\nvec3 refractionColor=vec3(0.,0.,0.);\n#ifdef REFRACTION\nvec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y));\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0)\n{\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb*vRefractionInfos.x;\n}\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\nrefractionColor=texture2D(refraction2DSampler,refractionCoords).rgb*vRefractionInfos.x;\n#endif\n#endif\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_3D\n#ifdef ROUGHNESS\nfloat bias=vReflectionInfos.y;\n#ifdef SPECULARTERM\n#ifdef SPECULAR\n#ifdef GLOSSINESS\nbias*=(1.0-specularMapColor.a);\n#endif\n#endif\n#endif\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias).rgb*vReflectionInfos.x;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb*vReflectionInfos.x;\n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb*vReflectionInfos.x;\n#endif\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\n#ifdef REFLECTIONFRESNELFROMSPECULAR\n#ifdef SPECULARTERM\nreflectionColor*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n#endif\n#ifdef REFRACTIONFRESNEL\nfloat refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);\nrefractionColor*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\n#ifdef LINKEMISSIVEWITHDIFFUSE\nvec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#endif\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n#ifdef REFLECTIONOVERALPHA\nalpha=clamp(alpha+dot(reflectionColor,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 color=vec4(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+emissiveColor+refractionColor,0.0,1.0),alpha);\n#else\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+refractionColor,alpha);\n#endif\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV).rgb*vLightmapInfos.y;\n#ifdef USELIGHTMAPASSHADOWMAP\ncolor.rgb*=lightmapColor;\n#else\ncolor.rgb+=lightmapColor;\n#endif\n#endif\n#include<logDepthFragment>\n#include<fogFragment>\n#ifdef CAMERACOLORGRADING\ncolor=colorGrades(color);\n#endif\n#ifdef CAMERACOLORCURVES\ncolor.rgb=applyColorCurves(color.rgb);\n#endif\ngl_FragColor=color;\n}","defaultVertexShader":"\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#include<pointCloudVertexDeclaration>\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<shadowsVertexDeclaration>[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=position;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef DIFFUSE\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef AMBIENT\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef OPACITY\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef EMISSIVE\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef LIGHTMAP\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef BUMP\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n#include<pointCloudVertex>\n#include<logDepthVertex>\n}","depthPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nuniform float far;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\nfloat depth=(gl_FragCoord.z/gl_FragCoord.w)/far;\ngl_FragColor=vec4(depth,depth*depth,0.0,1.0);\n}","depthVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","depthBoxBlurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nvoid main(void)\n{\nvec4 colorDepth=vec4(0.0);\nfor (int x=-OFFSET; x<=OFFSET; x++)\nfor (int y=-OFFSET; y<=OFFSET; y++)\ncolorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);\ngl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));\n}","depthOfFieldPixelShader":"\n\n\n\n\nuniform sampler2D textureSampler;\nuniform sampler2D highlightsSampler;\nuniform sampler2D depthSampler;\nuniform sampler2D grainSampler;\n\nuniform float grain_amount;\nuniform bool blur_noise;\nuniform float screen_width;\nuniform float screen_height;\nuniform float distortion;\nuniform bool dof_enabled;\n\nuniform float screen_distance; \nuniform float aperture;\nuniform float darken;\nuniform float edge_blur;\nuniform bool highlights;\n\nuniform float near;\nuniform float far;\n\nvarying vec2 vUV;\n\n#define PI 3.14159265\n#define TWOPI 6.28318530\n#define inverse_focal_length 0.1 \n\nvec2 centered_screen_pos;\nvec2 distorted_coords;\nfloat radius2;\nfloat radius;\n\nvec2 rand(vec2 co)\n{\nfloat noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));\nfloat noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));\nreturn clamp(vec2(noise1,noise2),0.0,1.0);\n}\n\nvec2 getDistortedCoords(vec2 coords) {\nif (distortion == 0.0) { return coords; }\nvec2 direction=1.0*normalize(centered_screen_pos);\nvec2 dist_coords=vec2(0.5,0.5);\ndist_coords.x=0.5+direction.x*radius2*1.0;\ndist_coords.y=0.5+direction.y*radius2*1.0;\nfloat dist_amount=clamp(distortion*0.23,0.0,1.0);\ndist_coords=mix(coords,dist_coords,dist_amount);\nreturn dist_coords;\n}\n\nfloat sampleScreen(inout vec4 color,const in vec2 offset,const in float weight) {\n\nvec2 coords=distorted_coords;\nfloat angle=rand(coords*100.0).x*TWOPI;\ncoords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));\ncolor+=texture2D(textureSampler,coords)*weight;\nreturn weight;\n}\n\nfloat getBlurLevel(float size) {\nreturn min(3.0,ceil(size/1.0));\n}\n\nvec4 getBlurColor(float size) {\nvec4 col=texture2D(textureSampler,distorted_coords);\nif (size == 0.0) { return col; }\n\n\nfloat blur_level=getBlurLevel(size);\nfloat w=(size/screen_width);\nfloat h=(size/screen_height);\nfloat total_weight=1.0;\nvec2 sample_coords;\ntotal_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);\ntotal_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);\ntotal_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);\ntotal_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);\ntotal_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);\ntotal_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);\ntotal_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);\ntotal_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);\ntotal_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);\nif (blur_level>1.0) {\ntotal_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);\ntotal_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);\ntotal_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);\ntotal_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);\ntotal_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);\ntotal_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);\ntotal_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);\ntotal_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);\ntotal_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);\n}\nif (blur_level>2.0) {\ntotal_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);\ntotal_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);\ntotal_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);\ntotal_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);\ntotal_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);\ntotal_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);\ntotal_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);\ntotal_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);\ntotal_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);\n}\ncol/=total_weight; \n\nif (darken>0.0) {\ncol.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);\n}\n\n\n\n\nreturn col;\n}\nvoid main(void)\n{\n\ncentered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nradius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;\nradius=sqrt(radius2);\ndistorted_coords=getDistortedCoords(vUV); \nvec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); \nfloat depth=texture2D(depthSampler,distorted_coords).r; \nfloat distance=near+(far-near)*depth; \nvec4 color=texture2D(textureSampler,vUV); \n\n\nfloat coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));\n\nif (dof_enabled == false || coc<0.07) { coc=0.0; }\n\nfloat edge_blur_amount=0.0;\nif (edge_blur>0.0) {\nedge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;\n}\n\nfloat blur_amount=max(edge_blur_amount,coc);\n\nif (blur_amount == 0.0) {\ngl_FragColor=texture2D(textureSampler,distorted_coords);\n}\nelse {\n\ngl_FragColor=getBlurColor(blur_amount*1.7);\n\nif (highlights) {\ngl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;\n}\nif (blur_noise) {\n\nvec2 noise=rand(distorted_coords)*0.01*blur_amount;\nvec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);\ngl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;\n}\n}\n\nif (grain_amount>0.0) {\nvec4 grain_color=texture2D(grainSampler,texels_coords*0.003);\ngl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;\n}\n}\n","displayPassPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D passSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(passSampler,vUV);\n}","ellipse2dPixelShader":"varying vec4 vColor;\nvoid main(void) {\ngl_FragColor=vColor;\n}","ellipse2dVertexShader":"\n#ifdef Instanced\n#define att attribute\n#else\n#define att uniform\n#endif\nattribute float index;\natt vec2 zBias;\natt vec4 transformX;\natt vec4 transformY;\natt float opacity;\n#ifdef Border\natt float borderThickness;\n#endif\n#ifdef FillSolid\natt vec4 fillSolidColor;\n#endif\n#ifdef BorderSolid\natt vec4 borderSolidColor;\n#endif\n#ifdef FillGradient\natt vec4 fillGradientColor1;\natt vec4 fillGradientColor2;\natt vec4 fillGradientTY;\n#endif\n#ifdef BorderGradient\natt vec4 borderGradientColor1;\natt vec4 borderGradientColor2;\natt vec4 borderGradientTY;\n#endif\n\natt vec3 properties;\n#define TWOPI 6.28318530\n\nvarying vec2 vUV;\nvarying vec4 vColor;\nvoid main(void) {\nvec2 pos2;\n#ifdef Border\nfloat w=properties.x;\nfloat h=properties.y;\nfloat ms=properties.z;\nvec2 borderOffset=vec2(1.0,1.0);\nfloat segi=index;\nif (index<ms) {\nborderOffset=vec2(1.0-(borderThickness*2.0/w),1.0-(borderThickness*2.0/h));\n}\nelse {\nsegi-=ms;\n}\nfloat angle=TWOPI*segi/ms;\npos2.x=(cos(angle)/2.0)+0.5;\npos2.y=(sin(angle)/2.0)+0.5;\npos2.x=((pos2.x-0.5)*borderOffset.x)+0.5;\npos2.y=((pos2.y-0.5)*borderOffset.y)+0.5;\n#else\nif (index == 0.0) {\npos2=vec2(0.5,0.5);\n}\nelse {\nfloat ms=properties.z;\nfloat angle=TWOPI*(index-1.0)/ms;\npos2.x=(cos(angle)/2.0)+0.5;\npos2.y=(sin(angle)/2.0)+0.5;\n}\n#endif\n#ifdef FillSolid\nvColor=fillSolidColor;\n#endif\n#ifdef BorderSolid\nvColor=borderSolidColor;\n#endif\n#ifdef FillGradient\nfloat v=dot(vec4(pos2.xy,1,1),fillGradientTY);\nvColor=mix(fillGradientColor2,fillGradientColor1,v); \n#endif\n#ifdef BorderGradient\nfloat v=dot(vec4(pos2.xy,1,1),borderGradientTY);\nvColor=mix(borderGradientColor2,borderGradientColor1,v); \n#endif\nvColor.a*=opacity;\nvec4 pos;\npos.xy=pos2.xy*properties.xy;\npos.z=1.0;\npos.w=1.0;\ngl_Position=vec4(dot(pos,transformX),dot(pos,transformY),zBias.x,1);\n}","filterPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform mat4 kernelMatrix;\nvoid main(void)\n{\nvec3 baseColor=texture2D(textureSampler,vUV).rgb;\nvec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;\ngl_FragColor=vec4(updatedColor,1.0);\n}","fxaaPixelShader":"#define FXAA_REDUCE_MIN (1.0/128.0)\n#define FXAA_REDUCE_MUL (1.0/8.0)\n#define FXAA_SPAN_MAX 8.0\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 texelSize;\nvoid main(){\nvec2 localTexelSize=texelSize;\nvec4 rgbNW=texture2D(textureSampler,(vUV+vec2(-1.0,-1.0)*localTexelSize));\nvec4 rgbNE=texture2D(textureSampler,(vUV+vec2(1.0,-1.0)*localTexelSize));\nvec4 rgbSW=texture2D(textureSampler,(vUV+vec2(-1.0,1.0)*localTexelSize));\nvec4 rgbSE=texture2D(textureSampler,(vUV+vec2(1.0,1.0)*localTexelSize));\nvec4 rgbM=texture2D(textureSampler,vUV);\nvec4 luma=vec4(0.299,0.587,0.114,1.0);\nfloat lumaNW=dot(rgbNW,luma);\nfloat lumaNE=dot(rgbNE,luma);\nfloat lumaSW=dot(rgbSW,luma);\nfloat lumaSE=dot(rgbSE,luma);\nfloat lumaM=dot(rgbM,luma);\nfloat lumaMin=min(lumaM,min(min(lumaNW,lumaNE),min(lumaSW,lumaSE)));\nfloat lumaMax=max(lumaM,max(max(lumaNW,lumaNE),max(lumaSW,lumaSE)));\nvec2 dir=vec2(-((lumaNW+lumaNE)-(lumaSW+lumaSE)),((lumaNW+lumaSW)-(lumaNE+lumaSE)));\nfloat dirReduce=max(\n(lumaNW+lumaNE+lumaSW+lumaSE)*(0.25*FXAA_REDUCE_MUL),\nFXAA_REDUCE_MIN);\nfloat rcpDirMin=1.0/(min(abs(dir.x),abs(dir.y))+dirReduce);\ndir=min(vec2(FXAA_SPAN_MAX,FXAA_SPAN_MAX),\nmax(vec2(-FXAA_SPAN_MAX,-FXAA_SPAN_MAX),\ndir*rcpDirMin))*localTexelSize;\nvec4 rgbA=0.5*(\ntexture2D(textureSampler,vUV+dir*(1.0/3.0-0.5)) +\ntexture2D(textureSampler,vUV+dir*(2.0/3.0-0.5)));\nvec4 rgbB=rgbA*0.5+0.25*(\ntexture2D(textureSampler,vUV+dir*-0.5) +\ntexture2D(textureSampler,vUV+dir*0.5));\nfloat lumaB=dot(rgbB,luma);\nif ((lumaB<lumaMin) || (lumaB>lumaMax)) {\ngl_FragColor=rgbA;\n}\nelse {\ngl_FragColor=rgbB;\n}\n}","hdrPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(GAUSSIAN_BLUR_H) || defined(GAUSSIAN_BLUR_V)\nuniform float blurOffsets[9];\nuniform float blurWeights[9];\nuniform float multiplier;\nvoid main(void) {\nvec4 color=vec4(0.0,0.0,0.0,0.0);\nfor (int i=0; i<9; i++) {\n#ifdef GAUSSIAN_BLUR_H\ncolor+=(texture2D(textureSampler,vUV+vec2(blurOffsets[i]*multiplier,0.0))*blurWeights[i]);\n#else\ncolor+=(texture2D(textureSampler,vUV+vec2(0.0,blurOffsets[i]*multiplier))*blurWeights[i]);\n#endif\n}\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nvoid main() {\nvec4 sum=texture2D(textureSampler,vUV)+texture2D(otherSampler,vUV);\nsum.a=clamp(sum.a,0.0,1.0);\ngl_FragColor=sum;\n}\n#endif\n#if defined(LUMINANCE_GENERATOR)\nuniform vec2 lumOffsets[4];\nvoid main() {\nfloat average=0.0;\nvec4 color=vec4(0.0,0.0,0.0,0.0);\nfloat maximum=-1e20;\nfor (int i=0; i<4; i++) {\ncolor=texture2D(textureSampler,vUV+lumOffsets[i]);\nfloat GreyValue=length(color.rgb);\nmaximum=max(maximum,GreyValue);\naverage+=(0.25*log(1e-5+GreyValue));\n}\naverage=exp(average);\ngl_FragColor=vec4(average,maximum,0.0,1.0);\n}\n#endif\n#if defined(DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];\nuniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLE\nvec4 pack(float value) {\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(value*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvoid main() {\nvec4 color=vec4(0.0,0.0,0.0,0.0);\nfloat average=0.0;\nfor (int i=0; i<9; i++) {\ncolor=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);\naverage+=color.r;\n}\naverage/=9.0;\n#ifndef FINAL_DOWN_SAMPLE\ngl_FragColor=vec4(average,average,0.0,1.0);\n#else\ngl_FragColor=pack(average);\n#endif\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main() {\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main() {\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(HDR)\nuniform sampler2D otherSampler;\nuniform float exposure;\nuniform float avgLuminance;\nvoid main() {\nvec4 color=texture2D(textureSampler,vUV)+texture2D(otherSampler,vUV);\nvec4 adjustedColor=color/avgLuminance*exposure;\ncolor=adjustedColor;\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n","layerPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=baseColor*color;\n}","layerVertexShader":"\nattribute vec2 position;\n\nuniform vec2 scale;\nuniform vec2 offset;\nuniform mat4 textureMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvec2 shiftedPosition=position*scale+offset;\nvUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));\ngl_Position=vec4(shiftedPosition,0.0,1.0);\n}","legacydefaultPixelShader":"#define MAP_PROJECTION 4.\n\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\n\nvarying vec3 vPositionW;\nvarying vec3 vNormalW;\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<lightFragmentDeclaration>[0..3]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform sampler2D diffuseSampler;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform sampler2D ambientSampler;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef REFLECTION\nvarying vec3 vReflectionUVW;\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\nuniform vec2 vReflectionInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform sampler2D emissiveSampler;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform sampler2D specularSampler;\n#endif\n\n#include<fresnelFunction>\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n#include<clipPlaneFragmentDeclaration>\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n\nvec3 normalW=normalize(vNormalW);\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV).rgb*vAmbientInfos.y;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\nfloat glossiness=0.;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\nglossiness=vSpecularColor.a;\n#endif\nfloat shadow=1.;\n#include<lightFragment>[0..3]\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb*vReflectionInfos.x;\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb*vReflectionInfos.x;\n#endif\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n\nfloat alpha=vDiffuseColor.a;\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef SPECULARTERM\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nspecularColor=texture2D(specularSampler,vSpecularUV).rgb*vSpecularInfos.y;\n#endif\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor,alpha);\n#include<fogFragment>\ngl_FragColor=color;\n}","legacydefaultVertexShader":"\nattribute vec3 position;\nattribute vec3 normal;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\nuniform mat4 world;\nuniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform vec2 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n\nvarying vec3 vPositionW;\nvarying vec3 vNormalW;\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<shadowsVertexDeclaration>[0..maxSimultaneousLights]\n#ifdef REFLECTION\nuniform vec3 vEyePosition;\nvarying vec3 vReflectionUVW;\nuniform mat4 reflectionMatrix;\nvec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#ifdef REFLECTIONMAP_SPHERICAL\nvec3 coords=vec3(view*vec4(worldNormal,0.0));\nreturn vec3(reflectionMatrix*vec4(coords,1.0));\n#endif\n#ifdef REFLECTIONMAP_PLANAR\nvec3 viewDir=worldPos.xyz-vEyePosition;\nvec3 coords=normalize(reflect(viewDir,worldNormal));\nreturn vec3(reflectionMatrix*vec4(coords,1));\n#endif\n#ifdef REFLECTIONMAP_CUBIC\nvec3 viewDir=worldPos.xyz-vEyePosition;\nvec3 coords=reflect(viewDir,worldNormal);\n#ifdef INVERTCUBICMAP\ncoords.y=1.0-coords.y;\n#endif\nreturn vec3(reflectionMatrix*vec4(coords,0));\n#endif\n#ifdef REFLECTIONMAP_PROJECTION\nreturn vec3(reflectionMatrix*(view*worldPos));\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nreturn position;\n#endif\n#ifdef REFLECTIONMAP_EXPLICIT\nreturn vec3(0,0,0);\n#endif\n}\n#endif\nvoid main(void) {\nmat4 finalWorld=world;\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef DIFFUSE\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef AMBIENT\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef OPACITY\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef REFLECTION\nvReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),vNormalW);\n#endif\n#ifdef EMISSIVE\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef BUMP\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n}","legacypbrPixelShader":"precision mediump float;\n\n#define RECIPROCAL_PI2 0.15915494\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vAlbedoColor;\nuniform vec3 vReflectionColor;\n\nuniform vec4 vLightingIntensity;\nuniform vec4 vCameraInfos;\n#ifdef OVERLOADEDVALUES\nuniform vec4 vOverloadedIntensity;\nuniform vec3 vOverloadedAmbient;\nuniform vec3 vOverloadedAlbedo;\nuniform vec3 vOverloadedReflectivity;\nuniform vec3 vOverloadedEmissive;\nuniform vec3 vOverloadedReflection;\nuniform vec3 vOverloadedMicroSurface;\n#endif\n#ifdef OVERLOADEDSHADOWVALUES\nuniform vec4 vOverloadedShadowIntensity;\n#endif\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<lightFragmentDeclaration>[0..maxSimultaneousLights]\n\n#ifdef ALBEDO\nvarying vec2 vAlbedoUV;\nuniform sampler2D albedoSampler;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform sampler2D ambientSampler;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform vec2 vLightmapInfos;\nuniform sampler2D lightmapSampler;\n#endif\n#if defined(REFLECTIVITY)\nvarying vec2 vReflectivityUV;\nuniform vec2 vReflectivityInfos;\nuniform sampler2D reflectivitySampler;\n#endif\n#include<clipPlaneFragmentDeclaration>\n#ifdef CAMERACOLORGRADING\nuniform sampler2D cameraColorGrading2DSampler;\nuniform vec4 vCameraColorGradingInfos;\nuniform vec4 vCameraColorGradingScaleOffset;\n#endif\n\n#include<pbrFunctions>\n#include<harmonicsFunctions>\n#include<pbrLightFunctions>\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 surfaceAlbedo=vec4(1.,1.,1.,1.);\nvec3 surfaceAlbedoContribution=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nsurfaceAlbedo=texture2D(albedoSampler,vAlbedoUV);\nsurfaceAlbedo=vec4(toLinearSpace(surfaceAlbedo.rgb),surfaceAlbedo.a);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#ifdef ALPHAFROMALBEDO\nalpha*=surfaceAlbedo.a;\n#endif\nsurfaceAlbedo.rgb*=vAlbedoInfos.y;\n#else\n\nsurfaceAlbedo.rgb=surfaceAlbedoContribution;\nsurfaceAlbedoContribution=vec3(1.,1.,1.);\n#endif\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n#ifdef OVERLOADEDVALUES\nsurfaceAlbedo.rgb=mix(surfaceAlbedo.rgb,vOverloadedAlbedo,vOverloadedIntensity.y);\n#endif\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\n\nvec3 ambientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nambientColor=texture2D(ambientSampler,vAmbientUV).rgb*vAmbientInfos.y;\n#ifdef OVERLOADEDVALUES\nambientColor.rgb=mix(ambientColor.rgb,vOverloadedAmbient,vOverloadedIntensity.x);\n#endif\n#endif\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef OVERLOADEDVALUES\nsurfaceReflectivityColor.rgb=mix(surfaceReflectivityColor.rgb,vOverloadedReflectivity,vOverloadedIntensity.z);\n#endif\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV);\nsurfaceReflectivityColor=surfaceReflectivityColorMap.rgb;\nsurfaceReflectivityColor=toLinearSpace(surfaceReflectivityColor);\n#ifdef OVERLOADEDVALUES\nsurfaceReflectivityColor=mix(surfaceReflectivityColor,vOverloadedReflectivity,vOverloadedIntensity.z);\n#endif\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface=surfaceReflectivityColorMap.a;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#endif\n#endif\n#ifdef OVERLOADEDVALUES\nmicroSurface=mix(microSurface,vOverloadedMicroSurface.x,vOverloadedMicroSurface.y);\n#endif\n\nfloat NdotV=max(0.00000000001,dot(normalW,viewDirectionW));\n\nmicroSurface=clamp(microSurface,0.,1.)*0.98;\n\nfloat roughness=clamp(1.-microSurface,0.000001,1.0);\n\nvec3 lightDiffuseContribution=vec3(0.,0.,0.);\n#ifdef OVERLOADEDSHADOWVALUES\nvec3 shadowedOnlyLightDiffuseContribution=vec3(1.,1.,1.);\n#endif\n#ifdef SPECULARTERM\nvec3 lightSpecularContribution= vec3(0.,0.,0.);\n#endif\nfloat notShadowLevel=1.; \nfloat NdotL=-1.;\nlightingInfo info;\n#include<pbrLightFunctionsCall>[0..maxSimultaneousLights]\n#ifdef SPECULARTERM\nlightSpecularContribution*=vLightingIntensity.w;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n\nvec3 environmentRadiance=vReflectionColor.rgb;\nvec3 environmentIrradiance=vReflectionColor.rgb;\n#ifdef OVERLOADEDVALUES\nenvironmentIrradiance=mix(environmentIrradiance,vOverloadedReflection,vOverloadedMicroSurface.z);\nenvironmentRadiance=mix(environmentRadiance,vOverloadedReflection,vOverloadedMicroSurface.z);\n#endif\nenvironmentRadiance*=vLightingIntensity.z;\nenvironmentIrradiance*=vLightingIntensity.z;\n\nvec3 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0);\nvec3 specularEnvironmentReflectance=FresnelSchlickEnvironmentGGX(clamp(NdotV,0.,1.),specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\nenvironmentRadiance*=specularEnvironmentReflectance;\n\nvec3 surfaceEmissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV).rgb;\nsurfaceEmissiveColor=toLinearSpace(emissiveColorTex.rgb)*surfaceEmissiveColor*vEmissiveInfos.y;\n#endif\n#ifdef OVERLOADEDVALUES\nsurfaceEmissiveColor=mix(surfaceEmissiveColor,vOverloadedEmissive,vOverloadedIntensity.w);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=max(lightDiffuseContribution*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#ifdef OVERLOADEDSHADOWVALUES\nshadowedOnlyLightDiffuseContribution=max(shadowedOnlyLightDiffuseContribution*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#endif\n#else\n#ifdef LINKEMISSIVEWITHALBEDO\nvec3 finalDiffuse=max((lightDiffuseContribution+surfaceEmissiveColor)*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#ifdef OVERLOADEDSHADOWVALUES\nshadowedOnlyLightDiffuseContribution=max((shadowedOnlyLightDiffuseContribution+surfaceEmissiveColor)*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#endif\n#else\nvec3 finalDiffuse=max(lightDiffuseContribution*surfaceAlbedoContribution+surfaceEmissiveColor+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#ifdef OVERLOADEDSHADOWVALUES\nshadowedOnlyLightDiffuseContribution=max(shadowedOnlyLightDiffuseContribution*surfaceAlbedoContribution+surfaceEmissiveColor+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#endif\n#endif\n#endif\n#ifdef OVERLOADEDSHADOWVALUES\nfinalDiffuse=mix(finalDiffuse,shadowedOnlyLightDiffuseContribution,(1.0-vOverloadedShadowIntensity.y));\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=lightSpecularContribution*surfaceReflectivityColor;\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+getLuminance(finalSpecular),0.,1.);\n#endif\n#ifdef RADIANCEOVERALPHA\nalpha=clamp(alpha+getLuminance(environmentRadiance),0.,1.);\n#endif\n\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 finalColor=vec4(finalDiffuse*ambientColor*vLightingIntensity.x+surfaceAlbedo.rgb*environmentIrradiance+finalSpecular*vLightingIntensity.x+environmentRadiance+surfaceEmissiveColor*vLightingIntensity.y,alpha);\n#else\nvec4 finalColor=vec4(finalDiffuse*ambientColor*vLightingIntensity.x+surfaceAlbedo.rgb*environmentIrradiance+finalSpecular*vLightingIntensity.x+environmentRadiance,alpha);\n#endif\nfinalColor=max(finalColor,0.0);\n#ifdef CAMERATONEMAP\nfinalColor.rgb=toneMaps(finalColor.rgb);\n#endif\nfinalColor.rgb=toGammaSpace(finalColor.rgb);\n#ifdef CAMERACONTRAST\nfinalColor=contrasts(finalColor);\n#endif\nfinalColor.rgb=clamp(finalColor.rgb,0.,1.);\n#ifdef CAMERACOLORGRADING\nfinalColor=colorGrades(finalColor,cameraColorGrading2DSampler,vCameraColorGradingInfos,vCameraColorGradingScaleOffset);\n#endif\ngl_FragColor=finalColor;\n}","legacypbrVertexShader":"precision mediump float;\n\nattribute vec3 position;\nattribute vec3 normal;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\nuniform mat4 world;\nuniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef ALBEDO\nvarying vec2 vAlbedoUV;\nuniform mat4 albedoMatrix;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#if defined(REFLECTIVITY)\nvarying vec2 vReflectivityUV;\nuniform vec2 vReflectivityInfos;\nuniform mat4 reflectivityMatrix;\n#endif\n\nvarying vec3 vPositionW;\nvarying vec3 vNormalW;\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<clipPlaneVertexDeclaration>\nvoid main(void) {\nmat4 finalWorld=world;\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef ALBEDO\nif (vAlbedoInfos.x == 0.)\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef AMBIENT\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef OPACITY\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef EMISSIVE\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(REFLECTIVITY)\nif (vReflectivityInfos.x == 0.)\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<clipPlaneVertex>\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n}","lensFlarePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\ngl_FragColor=baseColor*color;\n}","lensFlareVertexShader":"\nattribute vec2 position;\n\nuniform mat4 viewportMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=position*madd+madd;\ngl_Position=viewportMatrix*vec4(position,0.0,1.0);\n}","lensHighlightsPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float gain;\nuniform float threshold;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\n\nvec4 highlightColor(vec4 color) {\nvec4 highlight=color;\nfloat luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));\nfloat lum_threshold;\nif (threshold>1.0) { lum_threshold=0.94+0.01*threshold; }\nelse { lum_threshold=0.5+0.44*threshold; }\nluminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);\nhighlight*=luminance*gain;\nhighlight.a=1.0;\nreturn highlight;\n}\nvoid main(void)\n{\nvec4 original=texture2D(textureSampler,vUV);\n\nif (gain == -1.0) {\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nreturn;\n}\nfloat w=2.0/screen_width;\nfloat h=2.0/screen_height;\nfloat weight=1.0;\n\nvec4 blurred=vec4(0.0,0.0,0.0,0.0);\n#ifdef PENTAGON\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h)));\n#else\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h)));\n#endif\nblurred/=39.0;\ngl_FragColor=blurred;\n\n}","linePixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","lineVertexShader":"\nattribute vec3 position;\nattribute vec4 normal;\n\nuniform mat4 worldViewProjection;\nuniform float width;\nuniform float aspectRatio;\nvoid main(void) {\nvec4 viewPosition=worldViewProjection*vec4(position,1.0);\nvec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);\nvec2 currentScreen=viewPosition.xy/viewPosition.w;\nvec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;\ncurrentScreen.x*=aspectRatio;\nnextScreen.x*=aspectRatio;\nvec2 dir=normalize(nextScreen-currentScreen);\nvec2 normalDir=vec2(-dir.y,dir.x);\nnormalDir*=width/2.0;\nnormalDir.x/=aspectRatio;\nvec4 offset=vec4(normalDir*normal.w,0.0,0.0);\ngl_Position=viewPosition+offset;\n}","lines2dPixelShader":"varying vec4 vColor;\nvoid main(void) {\ngl_FragColor=vColor;\n}","lines2dVertexShader":"\n#ifdef Instanced\n#define att attribute\n#else\n#define att uniform\n#endif\nattribute vec2 position;\natt vec2 zBias;\natt vec4 transformX;\natt vec4 transformY;\natt float opacity;\n#ifdef FillSolid\natt vec4 fillSolidColor;\n#endif\n#ifdef BorderSolid\natt vec4 borderSolidColor;\n#endif\n#ifdef FillGradient\natt vec2 boundingMin;\natt vec2 boundingMax;\natt vec4 fillGradientColor1;\natt vec4 fillGradientColor2;\natt vec4 fillGradientTY;\n#endif\n#ifdef BorderGradient\natt vec4 borderGradientColor1;\natt vec4 borderGradientColor2;\natt vec4 borderGradientTY;\n#endif\n#define TWOPI 6.28318530\n\nvarying vec2 vUV;\nvarying vec4 vColor;\nvoid main(void) {\n#ifdef FillSolid\nvColor=fillSolidColor;\n#endif\n#ifdef BorderSolid\nvColor=borderSolidColor;\n#endif\n#ifdef FillGradient\nfloat v=dot(vec4((position.xy-boundingMin)/(boundingMax-boundingMin),1,1),fillGradientTY);\nvColor=mix(fillGradientColor2,fillGradientColor1,v); \n#endif\n#ifdef BorderGradient\nfloat v=dot(vec4((position.xy-boundingMin)/(boundingMax-boundingMin),1,1),borderGradientTY);\nvColor=mix(borderGradientColor2,borderGradientColor1,v); \n#endif\nvColor.a*=opacity;\nvec4 pos;\npos.xy=position.xy;\npos.z=1.0;\npos.w=1.0;\ngl_Position=vec4(dot(pos,transformX),dot(pos,transformY),zBias.x,1);\n}","outlinePixelShader":"uniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void) {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragColor=color;\n}","outlineVertexShader":"\nattribute vec3 position;\nattribute vec3 normal;\n#include<bonesDeclaration>\n\nuniform float offset;\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\nvec3 offsetPosition=position+normal*offset;\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(offsetPosition,1.0);\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}\n","particlesPixelShader":"\nvarying vec2 vUV;\nvarying vec4 vColor;\nuniform vec4 textureMask;\nuniform sampler2D diffuseSampler;\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\nvoid main(void) {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif\nvec4 baseColor=texture2D(diffuseSampler,vUV);\ngl_FragColor=(baseColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;\n}","particlesVertexShader":"\nattribute vec3 position;\nattribute vec4 color;\nattribute vec4 options;\n\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nvarying float fClipDistance;\n#endif\nvoid main(void) { \nvec3 viewPos=(view*vec4(position,1.0)).xyz; \nvec3 cornerPos;\nfloat size=options.y;\nfloat angle=options.x;\nvec2 offset=options.zw;\ncornerPos=vec3(offset.x-0.5,offset.y-0.5,0.)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \nvColor=color;\nvUV=offset;\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*vec4(viewPos,1.0);\nfClipDistance=dot(worldPos,vClipPlane);\n#endif\n}","passPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\n}","pbrPixelShader":"#ifdef BUMP\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LODBASEDMICROSFURACE\n#extension GL_EXT_shader_texture_lod : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nprecision highp float;\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\n\nuniform vec4 vLightingIntensity;\nuniform vec4 vCameraInfos;\n#ifdef OVERLOADEDVALUES\nuniform vec4 vOverloadedIntensity;\nuniform vec3 vOverloadedAmbient;\nuniform vec3 vOverloadedAlbedo;\nuniform vec3 vOverloadedReflectivity;\nuniform vec3 vOverloadedEmissive;\nuniform vec3 vOverloadedReflection;\nuniform vec3 vOverloadedMicroSurface;\n#endif\n#ifdef OVERLOADEDSHADOWVALUES\nuniform vec4 vOverloadedShadowIntensity;\n#endif\n#if defined(REFLECTION) || defined(REFRACTION)\nuniform vec2 vMicrosurfaceTextureLods;\n#endif\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<lightFragmentDeclaration>[0..maxSimultaneousLights]\n\n#ifdef ALBEDO\nvarying vec2 vAlbedoUV;\nuniform sampler2D albedoSampler;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform sampler2D ambientSampler;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform vec2 vLightmapInfos;\nuniform sampler2D lightmapSampler;\n#endif\n#if defined(REFLECTIVITY)\nvarying vec2 vReflectivityUV;\nuniform vec2 vReflectivityInfos;\nuniform sampler2D reflectivitySampler;\n#endif\n\n#include<fresnelFunction>\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\nuniform mat4 refractionMatrix;\n#endif\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvarying vec3 vDirectionW;\n#endif\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#ifdef CAMERACOLORGRADING\n#include<colorGradingDefinition>\n#endif\n#ifdef CAMERACOLORCURVES\n#include<colorCurvesDefinition>\n#endif\n\n#include<pbrShadowFunctions>\n#include<pbrFunctions>\n#ifdef CAMERACOLORGRADING\n#include<colorGrading>\n#endif\n#ifdef CAMERACOLORCURVES\n#include<colorCurves>\n#endif\n#include<harmonicsFunctions>\n#include<pbrLightFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 surfaceAlbedo=vec4(1.,1.,1.,1.);\nvec3 surfaceAlbedoContribution=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nsurfaceAlbedo=texture2D(albedoSampler,vAlbedoUV);\nsurfaceAlbedo=vec4(toLinearSpace(surfaceAlbedo.rgb),surfaceAlbedo.a);\n#ifndef LINKREFRACTIONTOTRANSPARENCY\n#ifdef ALPHATEST\nif (surfaceAlbedo.a<0.4)\ndiscard;\n#endif\n#endif\n#ifdef ALPHAFROMALBEDO\nalpha*=surfaceAlbedo.a;\n#endif\nsurfaceAlbedo.rgb*=vAlbedoInfos.y;\n#else\n\nsurfaceAlbedo.rgb=surfaceAlbedoContribution;\nsurfaceAlbedoContribution=vec3(1.,1.,1.);\n#endif\n#ifdef VERTEXCOLOR\nsurfaceAlbedo.rgb*=vColor.rgb;\n#endif\n#ifdef OVERLOADEDVALUES\nsurfaceAlbedo.rgb=mix(surfaceAlbedo.rgb,vOverloadedAlbedo,vOverloadedIntensity.y);\n#endif\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\n#include<bumpFragment>\n\nvec3 ambientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nambientColor=texture2D(ambientSampler,vAmbientUV).rgb*vAmbientInfos.y;\n#ifdef OVERLOADEDVALUES\nambientColor.rgb=mix(ambientColor.rgb,vOverloadedAmbient,vOverloadedIntensity.x);\n#endif\n#endif\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef OVERLOADEDVALUES\nsurfaceReflectivityColor.rgb=mix(surfaceReflectivityColor.rgb,vOverloadedReflectivity,vOverloadedIntensity.z);\n#endif\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV);\nsurfaceReflectivityColor=surfaceReflectivityColorMap.rgb;\nsurfaceReflectivityColor=toLinearSpace(surfaceReflectivityColor);\n#ifdef OVERLOADEDVALUES\nsurfaceReflectivityColor=mix(surfaceReflectivityColor,vOverloadedReflectivity,vOverloadedIntensity.z);\n#endif\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface=surfaceReflectivityColorMap.a;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#endif\n#endif\n#ifdef OVERLOADEDVALUES\nmicroSurface=mix(microSurface,vOverloadedMicroSurface.x,vOverloadedMicroSurface.y);\n#endif\n\nfloat NdotV=max(0.00000000001,dot(normalW,viewDirectionW));\n\nmicroSurface=clamp(microSurface,0.,1.)*0.98;\n\nfloat roughness=clamp(1.-microSurface,0.000001,1.0);\n\nvec3 lightDiffuseContribution=vec3(0.,0.,0.);\n#ifdef OVERLOADEDSHADOWVALUES\nvec3 shadowedOnlyLightDiffuseContribution=vec3(1.,1.,1.);\n#endif\n#ifdef SPECULARTERM\nvec3 lightSpecularContribution=vec3(0.,0.,0.);\n#endif\nfloat notShadowLevel=1.; \nfloat NdotL=-1.;\nlightingInfo info;\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\n\n\nfloat reflectance90=clamp(reflectance*25.0,0.0,1.0);\nvec3 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0)*reflectance90;\n#include<pbrLightFunctionsCall>[0..maxSimultaneousLights]\n#ifdef SPECULARTERM\nlightSpecularContribution*=vLightingIntensity.w;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 surfaceRefractionColor=vec3(0.,0.,0.);\n\n#ifdef LODBASEDMICROSFURACE\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\n#endif\n#ifdef REFRACTION\nvec3 refractionVector=refract(-viewDirectionW,normalW,vRefractionInfos.y);\n#ifdef LODBASEDMICROSFURACE\n#ifdef USEPMREMREFRACTION\nfloat lodRefraction=getMipMapIndexFromAverageSlopeWithPMREM(vMicrosurfaceTextureLods.y,alphaG);\n#else\nfloat lodRefraction=getMipMapIndexFromAverageSlope(vMicrosurfaceTextureLods.y,alphaG);\n#endif\n#else\nfloat biasRefraction=(vMicrosurfaceTextureLods.y+2.)*(1.0-microSurface);\n#endif\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0)\n{\n#ifdef LODBASEDMICROSFURACE\n#ifdef USEPMREMREFRACTION\n\nif ((vMicrosurfaceTextureLods.y-lodRefraction)>4.0)\n{\n\nfloat scaleRefraction=1.-exp2(lodRefraction)/exp2(vMicrosurfaceTextureLods.y); \nfloat maxRefraction=max(max(abs(refractionVector.x),abs(refractionVector.y)),abs(refractionVector.z));\nif (abs(refractionVector.x) != maxRefraction) refractionVector.x*=scaleRefraction;\nif (abs(refractionVector.y) != maxRefraction) refractionVector.y*=scaleRefraction;\nif (abs(refractionVector.z) != maxRefraction) refractionVector.z*=scaleRefraction;\n}\n#endif\nsurfaceRefractionColor=textureCubeLodEXT(refractionCubeSampler,refractionVector,lodRefraction).rgb*vRefractionInfos.x;\n#else\nsurfaceRefractionColor=textureCube(refractionCubeSampler,refractionVector,biasRefraction).rgb*vRefractionInfos.x;\n#endif\n}\n#ifndef REFRACTIONMAPINLINEARSPACE\nsurfaceRefractionColor=toLinearSpace(surfaceRefractionColor.rgb);\n#endif\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\n#ifdef LODBASEDMICROSFURACE\nsurfaceRefractionColor=texture2DLodEXT(refraction2DSampler,refractionCoords,lodRefraction).rgb*vRefractionInfos.x;\n#else\nsurfaceRefractionColor=texture2D(refraction2DSampler,refractionCoords,biasRefraction).rgb*vRefractionInfos.x;\n#endif \nsurfaceRefractionColor=toLinearSpace(surfaceRefractionColor.rgb);\n#endif\n#endif\n\nvec3 environmentRadiance=vReflectionColor.rgb;\nvec3 environmentIrradiance=vReflectionColor.rgb;\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef LODBASEDMICROSFURACE\n#ifdef USEPMREMREFLECTION\nfloat lodReflection=getMipMapIndexFromAverageSlopeWithPMREM(vMicrosurfaceTextureLods.x,alphaG);\n#else\nfloat lodReflection=getMipMapIndexFromAverageSlope(vMicrosurfaceTextureLods.x,alphaG);\n#endif\n#else\nfloat biasReflection=(vMicrosurfaceTextureLods.x+2.)*(1.0-microSurface);\n#endif\n#ifdef REFLECTIONMAP_3D\n#ifdef LODBASEDMICROSFURACE\n#ifdef USEPMREMREFLECTION\n\nif ((vMicrosurfaceTextureLods.y-lodReflection)>4.0)\n{\n\nfloat scaleReflection=1.-exp2(lodReflection)/exp2(vMicrosurfaceTextureLods.x); \nfloat maxReflection=max(max(abs(vReflectionUVW.x),abs(vReflectionUVW.y)),abs(vReflectionUVW.z));\nif (abs(vReflectionUVW.x) != maxReflection) vReflectionUVW.x*=scaleReflection;\nif (abs(vReflectionUVW.y) != maxReflection) vReflectionUVW.y*=scaleReflection;\nif (abs(vReflectionUVW.z) != maxReflection) vReflectionUVW.z*=scaleReflection;\n}\n#endif\nenvironmentRadiance=textureCubeLodEXT(reflectionCubeSampler,vReflectionUVW,lodReflection).rgb*vReflectionInfos.x;\n#else\nenvironmentRadiance=textureCube(reflectionCubeSampler,vReflectionUVW,biasReflection).rgb*vReflectionInfos.x;\n#endif\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#ifndef REFLECTIONMAP_SKYBOX\nvec3 normalEnvironmentSpace=(reflectionMatrix*vec4(normalW,1)).xyz;\nenvironmentIrradiance=EnvironmentIrradiance(normalEnvironmentSpace);\n#endif\n#else\nenvironmentRadiance=toLinearSpace(environmentRadiance.rgb);\nenvironmentIrradiance=textureCube(reflectionCubeSampler,normalW,20.).rgb*vReflectionInfos.x;\nenvironmentIrradiance=toLinearSpace(environmentIrradiance.rgb);\nenvironmentIrradiance*=0.2; \n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\n#ifdef LODBASEDMICROSFURACE\nenvironmentRadiance=texture2DLodEXT(reflection2DSampler,coords,lodReflection).rgb*vReflectionInfos.x;\n#else\nenvironmentRadiance=texture2D(reflection2DSampler,coords,biasReflection).rgb*vReflectionInfos.x;\n#endif\nenvironmentRadiance=toLinearSpace(environmentRadiance.rgb);\nenvironmentIrradiance=texture2D(reflection2DSampler,coords,20.).rgb*vReflectionInfos.x;\nenvironmentIrradiance=toLinearSpace(environmentIrradiance.rgb);\n#endif\n#endif\n#ifdef OVERLOADEDVALUES\nenvironmentIrradiance=mix(environmentIrradiance,vOverloadedReflection,vOverloadedMicroSurface.z);\nenvironmentRadiance=mix(environmentRadiance,vOverloadedReflection,vOverloadedMicroSurface.z);\n#endif\nenvironmentRadiance*=vLightingIntensity.z;\nenvironmentIrradiance*=vLightingIntensity.z;\n\nvec3 specularEnvironmentReflectance=FresnelSchlickEnvironmentGGX(clamp(NdotV,0.,1.),specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n\nvec3 refractance=vec3(0.0,0.0,0.0);\n#ifdef REFRACTION\nvec3 transmission=vec3(1.0,1.0,1.0);\n#ifdef LINKREFRACTIONTOTRANSPARENCY\n\ntransmission*=(1.0-alpha);\n\n\nvec3 mixedAlbedo=surfaceAlbedoContribution.rgb*surfaceAlbedo.rgb;\nfloat maxChannel=max(max(mixedAlbedo.r,mixedAlbedo.g),mixedAlbedo.b);\nvec3 tint=clamp(maxChannel*mixedAlbedo,0.0,1.0);\n\nsurfaceAlbedoContribution*=alpha;\n\nenvironmentIrradiance*=alpha;\n\nsurfaceRefractionColor*=tint;\n\nalpha=1.0;\n#endif\n\nvec3 bounceSpecularEnvironmentReflectance=(2.0*specularEnvironmentReflectance)/(1.0+specularEnvironmentReflectance);\nspecularEnvironmentReflectance=mix(bounceSpecularEnvironmentReflectance,specularEnvironmentReflectance,alpha);\n\ntransmission*=1.0-specularEnvironmentReflectance;\n\nrefractance=surfaceRefractionColor*transmission;\n#endif\n\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\nrefractance*=vLightingIntensity.z;\nenvironmentRadiance*=specularEnvironmentReflectance;\n\nvec3 surfaceEmissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV).rgb;\nsurfaceEmissiveColor=toLinearSpace(emissiveColorTex.rgb)*surfaceEmissiveColor*vEmissiveInfos.y;\n#endif\n#ifdef OVERLOADEDVALUES\nsurfaceEmissiveColor=mix(surfaceEmissiveColor,vOverloadedEmissive,vOverloadedIntensity.w);\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nsurfaceEmissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=max(lightDiffuseContribution*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#ifdef OVERLOADEDSHADOWVALUES\nshadowedOnlyLightDiffuseContribution=max(shadowedOnlyLightDiffuseContribution*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#endif\n#else\n#ifdef LINKEMISSIVEWITHALBEDO\nvec3 finalDiffuse=max((lightDiffuseContribution+surfaceEmissiveColor)*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#ifdef OVERLOADEDSHADOWVALUES\nshadowedOnlyLightDiffuseContribution=max((shadowedOnlyLightDiffuseContribution+surfaceEmissiveColor)*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#endif\n#else\nvec3 finalDiffuse=max(lightDiffuseContribution*surfaceAlbedoContribution+surfaceEmissiveColor+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#ifdef OVERLOADEDSHADOWVALUES\nshadowedOnlyLightDiffuseContribution=max(shadowedOnlyLightDiffuseContribution*surfaceAlbedoContribution+surfaceEmissiveColor+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#endif\n#endif\n#endif\n#ifdef OVERLOADEDSHADOWVALUES\nfinalDiffuse=mix(finalDiffuse,shadowedOnlyLightDiffuseContribution,(1.0-vOverloadedShadowIntensity.y));\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=lightSpecularContribution*surfaceReflectivityColor;\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+getLuminance(finalSpecular),0.,1.);\n#endif\n#ifdef RADIANCEOVERALPHA\nalpha=clamp(alpha+getLuminance(environmentRadiance),0.,1.);\n#endif\n\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 finalColor=vec4(finalDiffuse*ambientColor*vLightingIntensity.x+surfaceAlbedo.rgb*environmentIrradiance+finalSpecular*vLightingIntensity.x+environmentRadiance+surfaceEmissiveColor*vLightingIntensity.y+refractance,alpha);\n#else\nvec4 finalColor=vec4(finalDiffuse*ambientColor*vLightingIntensity.x+surfaceAlbedo.rgb*environmentIrradiance+finalSpecular*vLightingIntensity.x+environmentRadiance+refractance,alpha);\n#endif\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV).rgb*vLightmapInfos.y;\n#ifdef USELIGHTMAPASSHADOWMAP\nfinalColor.rgb*=lightmapColor;\n#else\nfinalColor.rgb+=lightmapColor;\n#endif\n#endif\nfinalColor=max(finalColor,0.0);\n#ifdef CAMERATONEMAP\nfinalColor.rgb=toneMaps(finalColor.rgb);\n#endif\nfinalColor.rgb=toGammaSpace(finalColor.rgb);\n#include<logDepthFragment>\n#include<fogFragment>(color,finalColor)\n#ifdef CAMERACONTRAST\nfinalColor=contrasts(finalColor);\n#endif\nfinalColor.rgb=clamp(finalColor.rgb,0.,1.);\n#ifdef CAMERACOLORGRADING\nfinalColor=colorGrades(finalColor);\n#endif\n#ifdef CAMERACOLORCURVES\nfinalColor.rgb=applyColorCurves(finalColor.rgb);\n#endif\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\ngl_FragColor=finalColor;\n}","pbrVertexShader":"precision highp float;\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef ALBEDO\nvarying vec2 vAlbedoUV;\nuniform mat4 albedoMatrix;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(REFLECTIVITY)\nvarying vec2 vReflectivityUV;\nuniform vec2 vReflectivityInfos;\nuniform mat4 reflectivityMatrix;\n#endif\n#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<shadowsVertexDeclaration>[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=position;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef ALBEDO\nif (vAlbedoInfos.x == 0.)\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef AMBIENT\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef OPACITY\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef EMISSIVE\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef LIGHTMAP\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(REFLECTIVITY)\nif (vReflectivityInfos.x == 0.)\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef BUMP\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n\n#include<logDepthVertex>\n}","postprocessVertexShader":"\nattribute vec2 position;\nuniform vec2 scale;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd)*scale;\ngl_Position=vec4(position,0.0,1.0);\n}","proceduralVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvPosition=position;\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","rect2dPixelShader":"varying vec4 vColor;\nvoid main(void) {\ngl_FragColor=vColor;\n}","rect2dVertexShader":"\n#ifdef Instanced\n#define att attribute\n#else\n#define att uniform\n#endif\nattribute float index;\natt vec2 zBias;\natt vec4 transformX;\natt vec4 transformY;\natt float opacity;\n#ifdef Border\natt float borderThickness;\n#endif\n#ifdef FillSolid\natt vec4 fillSolidColor;\n#endif\n#ifdef BorderSolid\natt vec4 borderSolidColor;\n#endif\n#ifdef FillGradient\natt vec4 fillGradientColor1;\natt vec4 fillGradientColor2;\natt vec4 fillGradientTY;\n#endif\n#ifdef BorderGradient\natt vec4 borderGradientColor1;\natt vec4 borderGradientColor2;\natt vec4 borderGradientTY;\n#endif\n\natt vec3 properties;\n\n#define rsub0 17.0\n#define rsub1 33.0\n#define rsub2 49.0\n#define rsub3 65.0\n#define rsub 64.0\n#define TWOPI 6.28318530\n\nvarying vec2 vUV;\nvarying vec4 vColor;\nvoid main(void) {\nvec2 pos2;\n\nif (properties.z == 0.0) {\n#ifdef Border\nfloat w=properties.x;\nfloat h=properties.y;\nvec2 borderOffset=vec2(1.0,1.0);\nfloat segi=index;\nif (index<4.0) {\nborderOffset=vec2(1.0-(borderThickness*2.0/w),1.0-(borderThickness*2.0/h));\n}\nelse {\nsegi-=4.0;\n}\nif (segi == 0.0) {\npos2=vec2(1.0,1.0);\n} \nelse if (segi == 1.0) {\npos2=vec2(1.0,0.0);\n}\nelse if (segi == 2.0) {\npos2=vec2(0.0,0.0);\n} \nelse {\npos2=vec2(0.0,1.0);\n}\npos2.x=((pos2.x-0.5)*borderOffset.x)+0.5;\npos2.y=((pos2.y-0.5)*borderOffset.y)+0.5;\n#else\nif (index == 0.0) {\npos2=vec2(0.5,0.5);\n}\nelse if (index == 1.0) {\npos2=vec2(1.0,1.0);\n}\nelse if (index == 2.0) {\npos2=vec2(1.0,0.0);\n}\nelse if (index == 3.0) {\npos2=vec2(0.0,0.0);\n}\nelse {\npos2=vec2(0.0,1.0);\n}\n#endif\n}\nelse\n{\n#ifdef Border\nfloat w=properties.x;\nfloat h=properties.y;\nfloat r=properties.z;\nfloat nru=r/w;\nfloat nrv=r/h;\nvec2 borderOffset=vec2(1.0,1.0);\nfloat segi=index;\nif (index<rsub) {\nborderOffset=vec2(1.0-(borderThickness*2.0/w),1.0-(borderThickness*2.0/h));\n}\nelse {\nsegi-=rsub;\n}\n\nif (segi<rsub0) {\npos2=vec2(1.0-nru,nrv);\n}\n\nelse if (segi<rsub1) {\npos2=vec2(nru,nrv);\n}\n\nelse if (segi<rsub2) {\npos2=vec2(nru,1.0-nrv);\n}\n\nelse {\npos2=vec2(1.0-nru,1.0-nrv);\n}\nfloat angle=TWOPI-((index-1.0)*TWOPI/(rsub-0.5));\npos2.x+=cos(angle)*nru;\npos2.y+=sin(angle)*nrv;\npos2.x=((pos2.x-0.5)*borderOffset.x)+0.5;\npos2.y=((pos2.y-0.5)*borderOffset.y)+0.5;\n#else\nif (index == 0.0) {\npos2=vec2(0.5,0.5);\n}\nelse {\nfloat w=properties.x;\nfloat h=properties.y;\nfloat r=properties.z;\nfloat nru=r/w;\nfloat nrv=r/h;\n\nif (index<rsub0) {\npos2=vec2(1.0-nru,nrv);\n}\n\nelse if (index<rsub1) {\npos2=vec2(nru,nrv);\n}\n\nelse if (index<rsub2) {\npos2=vec2(nru,1.0-nrv);\n}\n\nelse {\npos2=vec2(1.0-nru,1.0-nrv);\n}\nfloat angle=TWOPI-((index-1.0)*TWOPI/(rsub-0.5));\npos2.x+=cos(angle)*nru;\npos2.y+=sin(angle)*nrv;\n}\n#endif\n}\n#ifdef FillSolid\nvColor=fillSolidColor;\n#endif\n#ifdef BorderSolid\nvColor=borderSolidColor;\n#endif\n#ifdef FillGradient\nfloat v=dot(vec4(pos2.xy,1,1),fillGradientTY);\nvColor=mix(fillGradientColor2,fillGradientColor1,v); \n#endif\n#ifdef BorderGradient\nfloat v=dot(vec4(pos2.xy,1,1),borderGradientTY);\nvColor=mix(borderGradientColor2,borderGradientColor1,v); \n#endif\nvColor.a*=opacity;\nvec4 pos;\npos.xy=pos2.xy*properties.xy;\npos.z=1.0;\npos.w=1.0;\ngl_Position=vec4(dot(pos,transformX),dot(pos,transformY),zBias.x,1);\n}","refractionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\nvoid main() {\nfloat ref=1.0-texture2D(refractionSampler,vUV).r;\nvec2 uv=vUV-vec2(0.5);\nvec2 offset=uv*depth*ref;\nvec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;\ngl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);\n}","shadowMapPixelShader":"#ifndef FULLFLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n\nvec2 packHalf(float depth) \n{ \nconst vec2 bitOffset=vec2(1.0/255.,0.);\nvec2 color=vec2(depth,fract(depth*255.));\nreturn color-(color.yy*bitOffset);\n}\n#endif\nvarying vec4 vPosition;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef CUBEMAP\nuniform vec3 lightPosition;\nuniform vec2 depthValues;\n#endif\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#ifdef CUBEMAP\nvec3 directionToLight=vPosition.xyz-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth-depthValues.x)/(depthValues.y-depthValues.x);\ndepth=clamp(depth,0.,1.0);\n#else\nfloat depth=vPosition.z/vPosition.w;\ndepth=depth*0.5+0.5;\n#endif\n#ifdef VSM\nfloat moment1=depth;\nfloat moment2=moment1*moment1;\n#ifndef FULLFLOAT\ngl_FragColor=vec4(packHalf(moment1),packHalf(moment2));\n#else\ngl_FragColor=vec4(moment1,moment2,1.0,1.0);\n#endif\n#else\n#ifndef FULLFLOAT\ngl_FragColor=pack(depth);\n#else\ngl_FragColor=vec4(depth,1.0,1.0,1.0);\n#endif\n#endif\n}","shadowMapVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nvarying vec4 vPosition;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(position,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(position,1.0);\ngl_Position=vPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","sprite2dPixelShader":"varying vec2 vUV;\nvarying float vOpacity;\nuniform sampler2D diffuseSampler;\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\nif (color.a == 0.05) {\ndiscard;\n}\ncolor.a*=vOpacity;\ngl_FragColor=color;\n}","sprite2dVertexShader":"\n#ifdef Instanced\n#define att attribute\n#else\n#define att uniform\n#endif\n\nattribute float index;\natt vec2 topLeftUV;\natt vec2 sizeUV;\natt vec2 textureSize;\n\natt vec3 properties;\natt vec2 zBias;\natt vec4 transformX;\natt vec4 transformY;\natt float opacity;\n\n\nvarying vec2 vUV;\nvarying float vOpacity;\nvoid main(void) {\nvec2 pos2;\n\nvec2 off=vec2(0.0,0.0);\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}\nvOpacity=opacity;\npos.z=1.0;\npos.w=1.0;\ngl_Position=vec4(dot(pos,transformX),dot(pos,transformY),zBias.x,1);\n} ","spritesPixelShader":"uniform bool alphaTest;\nvarying vec4 vColor;\n\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\nif (alphaTest) \n{\nif (color.a<0.95)\ndiscard;\n}\ncolor*=vColor;\n#include<fogFragment>\ngl_FragColor=color;\n}","spritesVertexShader":"\nattribute vec4 position;\nattribute vec4 options;\nattribute vec4 cellInfo;\nattribute vec4 color;\n\nuniform vec2 textureInfos;\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#include<fogVertexDeclaration>\nvoid main(void) { \nvec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; \nvec2 cornerPos;\nfloat angle=position.w;\nvec2 size=vec2(options.x,options.y);\nvec2 offset=options.zw;\nvec2 uvScale=textureInfos.xy;\ncornerPos=vec2(offset.x-0.5,offset.y-0.5)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \n\nvColor=color;\n\nvec2 uvOffset=vec2(abs(offset.x-cellInfo.x),1.0-abs(offset.y-cellInfo.y));\nvUV=(uvOffset+cellInfo.zw)*uvScale;\n\n#ifdef FOG\nfFogDistance=viewPos.z;\n#endif\n}","ssaoPixelShader":"\nuniform sampler2D textureSampler;\nvarying vec2 vUV;\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float radius;\nuniform float area;\nuniform float fallOff;\nuniform float base;\nvec3 normalFromDepth(float depth,vec2 coords)\n{\nvec2 offset1=vec2(0.0,radius);\nvec2 offset2=vec2(radius,0.0);\nfloat depth1=texture2D(textureSampler,coords+offset1).r;\nfloat depth2=texture2D(textureSampler,coords+offset2).r;\nvec3 p1=vec3(offset1,depth1-depth);\nvec3 p2=vec3(offset2,depth2-depth);\nvec3 normal=cross(p1,p2);\nnormal.z=-normal.z;\nreturn normalize(normal);\n}\nvoid main()\n{\nvec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);\nfloat depth=texture2D(textureSampler,vUV).r;\nvec3 position=vec3(vUV,depth);\nvec3 normal=normalFromDepth(depth,vUV);\nfloat radiusDepth=radius/depth;\nfloat occlusion=0.0;\nvec3 ray;\nvec3 hemiRay;\nfloat occlusionDepth;\nfloat difference;\nfor (int i=0; i<SAMPLES; i++)\n{\nray=radiusDepth*reflect(sampleSphere[i],random);\nhemiRay=position+sign(dot(ray,normal))*ray;\nocclusionDepth=texture2D(textureSampler,clamp(hemiRay.xy,vec2(0.001,0.001),vec2(0.999,0.999))).r;\ndifference=depth-occlusionDepth;\nocclusion+=step(fallOff,difference)*(1.0-smoothstep(fallOff,area,difference));\n}\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor.r=result;\ngl_FragColor.g=result;\ngl_FragColor.b=result;\ngl_FragColor.a=1.0;\n}\n#endif\n#ifdef BILATERAL_BLUR\nuniform sampler2D depthSampler;\nuniform float outSize;\nuniform float samplerOffsets[SAMPLES];\nvoid main()\n{\nfloat texelsize=1.0/outSize;\nfloat compareDepth=texture2D(depthSampler,vUV).r;\nfloat result=0.0;\nfloat weightSum=0.0;\nfor (int i=0; i<SAMPLES; ++i)\n{\n#ifdef BILATERAL_BLUR_H\nvec2 sampleOffset=vec2(texelsize*samplerOffsets[i],0.0);\n#else\nvec2 sampleOffset=vec2(0.0,texelsize*samplerOffsets[i]);\n#endif\nvec2 samplePos=vUV+sampleOffset;\nfloat sampleDepth=texture2D(depthSampler,samplePos).r;\nfloat weight=(1.0/(0.0001+abs(compareDepth-sampleDepth)));\nresult+=texture2D(textureSampler,samplePos).r*weight;\nweightSum+=weight;\n}\nresult/=weightSum;\ngl_FragColor.rgb=vec3(result);\ngl_FragColor.a=1.0;\n}\n#endif\n","ssaoCombinePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D originalColor;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,vUV);\nvec4 sceneColor=texture2D(originalColor,vUV);\ngl_FragColor=sceneColor*ssaoColor;\n}\n","stereoscopicInterlacePixelShader":"const vec3 TWO=vec3(2.0,2.0,2.0);\nvarying vec2 vUV;\nuniform sampler2D camASampler;\nuniform sampler2D textureSampler;\nuniform vec2 stepSize;\nvoid main(void)\n{\nbool useCamB;\nvec2 texCoord1;\nvec2 texCoord2;\nvec3 frag1;\nvec3 frag2;\n#ifdef IS_STEREOSCOPIC_HORIZ\nuseCamB=vUV.x>0.5;\ntexCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);\ntexCoord2=vec2(texCoord1.x+stepSize.x,vUV.y);\n#else\nuseCamB=vUV.y>0.5;\ntexCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);\ntexCoord2=vec2(vUV.x,texCoord1.y+stepSize.y);\n#endif\n\nif (useCamB){\nfrag1=texture2D(textureSampler,texCoord1).rgb;\nfrag2=texture2D(textureSampler,texCoord2).rgb;\n}else{\nfrag1=texture2D(camASampler ,texCoord1).rgb;\nfrag2=texture2D(camASampler ,texCoord2).rgb;\n}\ngl_FragColor=vec4((frag1+frag2)/TWO,1.0);\n}","text2dPixelShader":"varying vec4 vColor;\nvarying vec2 vUV;\n\nuniform sampler2D diffuseSampler;\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\nif (color.a<0.05)\ndiscard;\ngl_FragColor=color*vColor;\n}","text2dVertexShader":"\n#ifdef Instanced\n#define att attribute\n#else\n#define att uniform\n#endif\n\nattribute float index;\natt vec2 zBias;\natt vec4 transformX;\natt vec4 transformY;\natt float opacity;\natt vec2 topLeftUV;\natt vec2 sizeUV;\natt vec2 textureSize;\natt vec4 color;\natt float superSampleFactor;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\nvoid main(void) {\nvec2 pos2;\n\nif (index == 0.0) {\npos2=vec2(0.0,0.0);\nvUV=vec2(topLeftUV.x,topLeftUV.y+sizeUV.y);\n}\n\nelse if (index == 1.0) {\npos2=vec2(0.0,1.0);\nvUV=vec2(topLeftUV.x,topLeftUV.y);\n}\n\nelse if (index == 2.0) {\npos2=vec2(1.0,1.0);\nvUV=vec2(topLeftUV.x+sizeUV.x,topLeftUV.y);\n}\n\nelse if (index == 3.0) {\npos2=vec2(1.0,0.0);\nvUV=vec2(topLeftUV.x+sizeUV.x,topLeftUV.y+sizeUV.y);\n}\n\nvUV=(floor(vUV*textureSize)+vec2(0.0,0.0))/textureSize;\nvColor=color;\nvColor.a*=opacity;\nvec4 pos;\npos.xy=floor(pos2.xy*superSampleFactor*sizeUV*textureSize); \npos.z=1.0;\npos.w=1.0;\ngl_Position=vec4(dot(pos,transformX),dot(pos,transformY),zBias.x,1);\n}","tonemapPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float _ExposureAdjustment;\n#if defined(HABLE_TONEMAPPING)\nconst float A=0.15;\nconst float B=0.50;\nconst float C=0.10;\nconst float D=0.20;\nconst float E=0.02;\nconst float F=0.30;\nconst float W=11.2;\n#endif\nfloat Luminance(vec3 c)\n{\nreturn dot(c,vec3(0.22,0.707,0.071));\n}\nvoid main(void) \n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\n#if defined(REINHARD_TONEMAPPING)\nfloat lum=Luminance(colour.rgb); \nfloat lumTm=lum*_ExposureAdjustment;\nfloat scale=lumTm/(1.0+lumTm); \ncolour*=scale/lum;\n#elif defined(HABLE_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nconst float ExposureBias=2.0;\nvec3 x=ExposureBias*colour;\nvec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;\nx=vec3(W,W,W);\nvec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);\ncolour=curr*whiteScale;\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\ncolour=vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour);\n#endif\ngl_FragColor=vec4(colour.rgb,1.0);\n}","volumetricLightScatteringPixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D lightScatteringSampler;\nuniform float decay;\nuniform float exposure;\nuniform float weight;\nuniform float density;\nuniform vec2 meshPositionOnScreen;\nvarying vec2 vUV;\nvoid main(void) {\nvec2 tc=vUV;\nvec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);\ndeltaTexCoord*=1.0/float(NUM_SAMPLES)*density;\nfloat illuminationDecay=1.0;\nvec4 color=texture2D(lightScatteringSampler,tc)*0.4;\nfor(int i=0; i<NUM_SAMPLES; i++) {\ntc-=deltaTexCoord;\nvec4 sample=texture2D(lightScatteringSampler,tc)*0.4;\nsample*=illuminationDecay*weight;\ncolor+=sample;\nilluminationDecay*=decay;\n}\nvec4 realColor=texture2D(textureSampler,vUV);\ngl_FragColor=((vec4((vec3(color.r,color.g,color.b)*exposure),1))+(realColor*(1.5-0.4)));\n}\n","volumetricLightScatteringPassPixelShader":"#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\n#endif\n#if defined(ALPHATEST)\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void)\n{\n#if defined(ALPHATEST)\nvec4 diffuseColor=texture2D(diffuseSampler,vUV);\nif (diffuseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\n","vrDistortionCorrectionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\nvec2 HmdWarp(vec2 in01) {\nvec2 theta=(in01-LensCenter)*ScaleIn; \nfloat rSq=theta.x*theta.x+theta.y*theta.y;\nvec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);\nreturn LensCenter+Scale*rvector;\n}\nvoid main(void)\n{\nvec2 tc=HmdWarp(vUV);\nif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nelse{\ngl_FragColor=vec4(texture2D(textureSampler,tc).rgb,1.0);\n}\n}"};
  60838. BABYLON.Effect.IncludesShadersStore={"bonesDeclaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nattribute vec4 matricesIndicesExtra;\nattribute vec4 matricesWeightsExtra;\n#endif\n#endif","bonesVertex":"#if NUM_BONE_INFLUENCERS>0\nmat4 influence;\ninfluence=mBones[int(matricesIndices[0])]*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence+=mBones[int(matricesIndices[1])]*matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence+=mBones[int(matricesIndices[2])]*matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence+=mBones[int(matricesIndices[3])]*matricesWeights[3];\n#endif \n#if NUM_BONE_INFLUENCERS>4\ninfluence+=mBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\ninfluence+=mBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence+=mBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence+=mBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];\n#endif \nfinalWorld=finalWorld*influence;\n#endif","bumpFragment":"#ifdef BUMP\nvec2 bumpUV=vBumpUV;\n#endif\n#if defined(BUMP) || defined(PARALLAX)\nmat3 TBN=cotangent_frame(normalW*vBumpInfos.y,-viewDirectionW,bumpUV);\n#endif\n#ifdef PARALLAX\nmat3 invTBN=transposeMat3(TBN);\n#ifdef PARALLAXOCCLUSION\nvec2 uvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,bumpUV,vBumpInfos.z);\n#else\nvec2 uvOffset=parallaxOffset(invTBN*viewDirectionW,vBumpInfos.z);\n#endif\ndiffuseUV+=uvOffset;\nbumpUV+=uvOffset;\n#endif\n#ifdef BUMP\nnormalW=perturbNormal(viewDirectionW,TBN,bumpUV);\n#endif","bumpFragmentFunctions":"#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform vec3 vBumpInfos;\nuniform sampler2D bumpSampler;\n\nmat3 cotangent_frame(vec3 normal,vec3 p,vec2 uv)\n{\n\nvec3 dp1=dFdx(p);\nvec3 dp2=dFdy(p);\nvec2 duv1=dFdx(uv);\nvec2 duv2=dFdy(uv);\n\nvec3 dp2perp=cross(dp2,normal);\nvec3 dp1perp=cross(normal,dp1);\nvec3 tangent=dp2perp*duv1.x+dp1perp*duv2.x;\nvec3 binormal=dp2perp*duv1.y+dp1perp*duv2.y;\n\nfloat invmax=inversesqrt(max(dot(tangent,tangent),dot(binormal,binormal)));\nreturn mat3(tangent*invmax,binormal*invmax,normal);\n}\nvec3 perturbNormal(vec3 viewDir,mat3 cotangentFrame,vec2 uv)\n{\nvec3 map=texture2D(bumpSampler,uv).xyz;\n#ifdef INVERTNORMALMAPX\nmap.x=1.0-map.x;\n#endif\n#ifdef INVERTNORMALMAPY\nmap.y=1.0-map.y;\n#endif\nmap=map*255./127.-128./127.;\nreturn normalize(cotangentFrame*map);\n}\n#ifdef PARALLAX\nconst float minSamples=4.;\nconst float maxSamples=15.;\nconst int iMaxSamples=15;\n\nvec2 parallaxOcclusion(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale) {\nfloat parallaxLimit=length(vViewDirCoT.xy)/vViewDirCoT.z;\nparallaxLimit*=parallaxScale;\nvec2 vOffsetDir=normalize(vViewDirCoT.xy);\nvec2 vMaxOffset=vOffsetDir*parallaxLimit;\nfloat numSamples=maxSamples+(dot(vViewDirCoT,vNormalCoT)*(minSamples-maxSamples));\nfloat stepSize=1.0/numSamples;\n\nfloat currRayHeight=1.0;\nvec2 vCurrOffset=vec2(0,0);\nvec2 vLastOffset=vec2(0,0);\nfloat lastSampledHeight=1.0;\nfloat currSampledHeight=1.0;\nfor (int i=0; i<iMaxSamples; i++)\n{\ncurrSampledHeight=texture2D(bumpSampler,vBumpUV+vCurrOffset).w;\n\nif (currSampledHeight>currRayHeight)\n{\nfloat delta1=currSampledHeight-currRayHeight;\nfloat delta2=(currRayHeight+stepSize)-lastSampledHeight;\nfloat ratio=delta1/(delta1+delta2);\nvCurrOffset=(ratio)* vLastOffset+(1.0-ratio)*vCurrOffset;\n\nbreak;\n}\nelse\n{\ncurrRayHeight-=stepSize;\nvLastOffset=vCurrOffset;\nvCurrOffset+=stepSize*vMaxOffset;\nlastSampledHeight=currSampledHeight;\n}\n}\nreturn vCurrOffset;\n}\nvec2 parallaxOffset(vec3 viewDir,float heightScale)\n{\n\nfloat height=texture2D(bumpSampler,vBumpUV).w;\nvec2 texCoordOffset=heightScale*viewDir.xy*height;\nreturn -texCoordOffset;\n}\n#endif\n#endif","clipPlaneFragment":"#ifdef CLIPPLANE\nif (fClipDistance>0.0)\n{\ndiscard;\n}\n#endif","clipPlaneFragmentDeclaration":"#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif","clipPlaneVertex":"#ifdef CLIPPLANE\nfClipDistance=dot(worldPos,vClipPlane);\n#endif","clipPlaneVertexDeclaration":"#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif","colorCurves":"const vec3 HDTVRec709_RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\nvec3 applyColorCurves(vec3 original) {\nvec3 result=original;\n\n\n\nfloat luma=dot(result.rgb,HDTVRec709_RGBLuminanceCoefficients);\nvec2 curveMix=clamp(vec2(luma*3.0-1.5,luma*-3.0+1.5),vec2(0.0,0.0),vec2(1.0,1.0));\nvec4 colorCurve=vCameraColorCurveNeutral+curveMix.x*vCameraColorCurvePositive-curveMix.y*vCameraColorCurveNegative;\nresult.rgb*=colorCurve.rgb;\nresult.rgb=mix(vec3(luma,luma,luma),result.rgb,colorCurve.a);\nreturn result;\n}","colorCurvesDefinition":"uniform vec4 vCameraColorCurveNeutral;\nuniform vec4 vCameraColorCurvePositive;\nuniform vec4 vCameraColorCurveNegative;","colorGrading":"vec4 colorGrades(vec4 color) \n{ \n\nfloat sliceContinuous=color.z*vCameraColorGradingInfos.z;\nfloat sliceInteger=floor(sliceContinuous);\n\n\nfloat sliceFraction=sliceContinuous-sliceInteger; \n\nvec2 sliceUV=color.xy*vCameraColorGradingScaleOffset.xy+vCameraColorGradingScaleOffset.zw;\n\n\nsliceUV.x+=sliceInteger*vCameraColorGradingInfos.w;\nvec4 slice0Color=texture2D(cameraColorGrading2DSampler,sliceUV);\nsliceUV.x+=vCameraColorGradingInfos.w;\nvec4 slice1Color=texture2D(cameraColorGrading2DSampler,sliceUV);\nvec3 result=mix(slice0Color.rgb,slice1Color.rgb,sliceFraction);\ncolor.rgb=mix(color.rgb,result,vCameraColorGradingInfos.x);\nreturn color;\n}","colorGradingDefinition":"uniform sampler2D cameraColorGrading2DSampler;\nuniform vec4 vCameraColorGradingInfos;\nuniform vec4 vCameraColorGradingScaleOffset;","fogFragment":"#ifdef FOG\nfloat fog=CalcFogFactor();\ncolor.rgb=fog*color.rgb+(1.0-fog)*vFogColor;\n#endif","fogFragmentDeclaration":"#ifdef FOG\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying float fFogDistance;\nfloat CalcFogFactor()\n{\nfloat fogCoeff=1.0;\nfloat fogStart=vFogInfos.y;\nfloat fogEnd=vFogInfos.z;\nfloat fogDensity=vFogInfos.w;\nif (FOGMODE_LINEAR == vFogInfos.x)\n{\nfogCoeff=(fogEnd-fFogDistance)/(fogEnd-fogStart);\n}\nelse if (FOGMODE_EXP == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fFogDistance*fogDensity);\n}\nelse if (FOGMODE_EXP2 == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fFogDistance*fFogDistance*fogDensity*fogDensity);\n}\nreturn clamp(fogCoeff,0.0,1.0);\n}\n#endif","fogVertex":"#ifdef FOG\nfFogDistance=(view*worldPos).z;\n#endif","fogVertexDeclaration":"#ifdef FOG\nvarying float fFogDistance;\n#endif","fresnelFunction":"#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection,vec3 worldNormal,float bias,float power)\n{\nfloat fresnelTerm=pow(bias+abs(dot(viewDirection,worldNormal)),power);\nreturn clamp(fresnelTerm,0.,1.);\n}\n#endif","harmonicsFunctions":"#ifdef USESPHERICALFROMREFLECTIONMAP\nuniform vec3 vSphericalX;\nuniform vec3 vSphericalY;\nuniform vec3 vSphericalZ;\nuniform vec3 vSphericalXX;\nuniform vec3 vSphericalYY;\nuniform vec3 vSphericalZZ;\nuniform vec3 vSphericalXY;\nuniform vec3 vSphericalYZ;\nuniform vec3 vSphericalZX;\nvec3 EnvironmentIrradiance(vec3 normal)\n{\n\n\n\nvec3 result =\nvSphericalX*normal.x +\nvSphericalY*normal.y +\nvSphericalZ*normal.z +\nvSphericalXX*normal.x*normal.x +\nvSphericalYY*normal.y*normal.y +\nvSphericalZZ*normal.z*normal.z +\nvSphericalYZ*normal.y*normal.z +\nvSphericalZX*normal.z*normal.x +\nvSphericalXY*normal.x*normal.y;\nreturn result.rgb;\n}\n#endif","helperFunctions":"mat3 transposeMat3(mat3 inMatrix) {\nvec3 i0=inMatrix[0];\nvec3 i1=inMatrix[1];\nvec3 i2=inMatrix[2];\nmat3 outMatrix=mat3(\nvec3(i0.x,i1.x,i2.x),\nvec3(i0.y,i1.y,i2.y),\nvec3(i0.z,i1.z,i2.z)\n);\nreturn outMatrix;\n}","instancesDeclaration":"#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif","instancesVertex":"#ifdef INSTANCES\nmat4 finalWorld=mat4(world0,world1,world2,world3);\n#else\nmat4 finalWorld=world;\n#endif","lightFragment":"#ifdef LIGHT{X}\n#ifndef SPECULARTERM\nvec3 vLightSpecular{X}=vec3(0.);\n#endif\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,vLightData{X},vLightDirection{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightDiffuse{X}.a,glossiness);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,vLightData{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightGround{X},glossiness);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,vLightData{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightDiffuse{X}.a,glossiness);\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWVSM{X}\nshadow=computeShadowWithVSM(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.z,shadowsInfo{X}.x);\n#else\n#ifdef SHADOWPCF{X}\n#if defined(POINTLIGHT{X})\nshadow=computeShadowWithPCFCube(vLightData{X}.xyz,shadowSampler{X},shadowsInfo{X}.y,shadowsInfo{X}.z,shadowsInfo{X}.x);\n#else\nshadow=computeShadowWithPCF(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.y,shadowsInfo{X}.z,shadowsInfo{X}.x);\n#endif\n#else\n#if defined(POINTLIGHT{X})\nshadow=computeShadowCube(vLightData{X}.xyz,shadowSampler{X},shadowsInfo{X}.x,shadowsInfo{X}.z);\n#else\nshadow=computeShadow(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.x,shadowsInfo{X}.z);\n#endif\n#endif\n#endif\n#else\nshadow=1.;\n#endif\ndiffuseBase+=info.diffuse*shadow;\n#ifdef SPECULARTERM\nspecularBase+=info.specular*shadow;\n#endif\n#endif","lightFragmentDeclaration":"#ifdef LIGHT{X}\nuniform vec4 vLightData{X};\nuniform vec4 vLightDiffuse{X};\n#ifdef SPECULARTERM\nuniform vec3 vLightSpecular{X};\n#endif\n#ifdef SHADOW{X}\n#if defined(SPOTLIGHT{X}) || defined(DIRLIGHT{X})\nvarying vec4 vPositionFromLight{X};\nuniform sampler2D shadowSampler{X};\n#else\nuniform samplerCube shadowSampler{X};\n#endif\nuniform vec3 shadowsInfo{X};\n#endif\n#ifdef SPOTLIGHT{X}\nuniform vec4 vLightDirection{X};\n#endif\n#ifdef HEMILIGHT{X}\nuniform vec3 vLightGround{X};\n#endif\n#endif","lightsFragmentFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n};\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 lightVectorW;\nfloat attenuation=1.0;\nif (lightData.w == 0.)\n{\nvec3 direction=lightData.xyz-vPositionW;\nattenuation=max(0.,1.0-length(direction)/range);\nlightVectorW=normalize(direction);\n}\nelse\n{\nlightVectorW=normalize(-lightData.xyz);\n}\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 direction=lightData.xyz-vPositionW;\nvec3 lightVectorW=normalize(direction);\nfloat attenuation=max(0.,1.0-length(direction)/range);\n\nfloat cosAngle=max(0.,dot(-lightDirection.xyz,lightVectorW));\nif (cosAngle>=lightDirection.w)\n{\ncosAngle=max(0.,pow(cosAngle,lightData.w));\nattenuation*=cosAngle;\n\nfloat ndl=max(0.,dot(vNormal,-lightDirection.xyz));\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW-lightDirection.xyz);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nresult.diffuse=vec3(0.);\n#ifdef SPECULARTERM\nresult.specular=vec3(0.);\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float glossiness) {\nlightingInfo result;\n\nfloat ndl=dot(vNormal,lightData.xyz)*0.5+0.5;\nresult.diffuse=mix(groundColor,diffuseColor,ndl);\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightData.xyz);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor;\n#endif\nreturn result;\n}\n","logDepthDeclaration":"#ifdef LOGARITHMICDEPTH\nuniform float logarithmicDepthConstant;\nvarying float vFragmentDepth;\n#endif","logDepthFragment":"#ifdef LOGARITHMICDEPTH\ngl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5;\n#endif","logDepthVertex":"#ifdef LOGARITHMICDEPTH\nvFragmentDepth=1.0+gl_Position.w;\ngl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant;\n#endif","pbrFunctions":"\n#define RECIPROCAL_PI2 0.15915494\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\n\nconst float kPi=3.1415926535897932384626433832795;\nconst float kRougnhessToAlphaScale=0.1;\nconst float kRougnhessToAlphaOffset=0.29248125;\nfloat Square(float value)\n{\nreturn value*value;\n}\nfloat getLuminance(vec3 color)\n{\nreturn clamp(dot(color,vec3(0.2126,0.7152,0.0722)),0.,1.);\n}\nfloat convertRoughnessToAverageSlope(float roughness)\n{\n\nconst float kMinimumVariance=0.0005;\nfloat alphaG=Square(roughness)+kMinimumVariance;\nreturn alphaG;\n}\n\nfloat getMipMapIndexFromAverageSlope(float maxMipLevel,float alpha)\n{\n\n\n\n\n\n\n\nfloat mip=kRougnhessToAlphaOffset+maxMipLevel+(maxMipLevel*kRougnhessToAlphaScale*log2(alpha));\nreturn clamp(mip,0.,maxMipLevel);\n}\nfloat getMipMapIndexFromAverageSlopeWithPMREM(float maxMipLevel,float alphaG)\n{\nfloat specularPower=clamp(2./alphaG-2.,0.000001,2048.);\n\nreturn clamp(- 0.5*log2(specularPower)+5.5,0.,maxMipLevel);\n}\n\nfloat smithVisibilityG1_TrowbridgeReitzGGX(float dot,float alphaG)\n{\nfloat tanSquared=(1.0-dot*dot)/(dot*dot);\nreturn 2.0/(1.0+sqrt(1.0+alphaG*alphaG*tanSquared));\n}\nfloat smithVisibilityG_TrowbridgeReitzGGX_Walter(float NdotL,float NdotV,float alphaG)\n{\nreturn smithVisibilityG1_TrowbridgeReitzGGX(NdotL,alphaG)*smithVisibilityG1_TrowbridgeReitzGGX(NdotV,alphaG);\n}\n\n\nfloat normalDistributionFunction_TrowbridgeReitzGGX(float NdotH,float alphaG)\n{\n\n\n\nfloat a2=Square(alphaG);\nfloat d=NdotH*NdotH*(a2-1.0)+1.0;\nreturn a2/(kPi*d*d);\n}\nvec3 fresnelSchlickGGX(float VdotH,vec3 reflectance0,vec3 reflectance90)\n{\nreturn reflectance0+(reflectance90-reflectance0)*pow(clamp(1.0-VdotH,0.,1.),5.0);\n}\nvec3 FresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n\nvec3 computeSpecularTerm(float NdotH,float NdotL,float NdotV,float VdotH,float roughness,vec3 specularColor,vec3 reflectance90)\n{\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\nfloat distribution=normalDistributionFunction_TrowbridgeReitzGGX(NdotH,alphaG);\nfloat visibility=smithVisibilityG_TrowbridgeReitzGGX_Walter(NdotL,NdotV,alphaG);\nvisibility/=(4.0*NdotL*NdotV); \nvec3 fresnel=fresnelSchlickGGX(VdotH,specularColor,reflectance90);\nfloat specTerm=max(0.,visibility*distribution)*NdotL;\nreturn fresnel*specTerm*kPi; \n}\nfloat computeDiffuseTerm(float NdotL,float NdotV,float VdotH,float roughness)\n{\n\n\nfloat diffuseFresnelNV=pow(clamp(1.0-NdotL,0.000001,1.),5.0);\nfloat diffuseFresnelNL=pow(clamp(1.0-NdotV,0.000001,1.),5.0);\nfloat diffuseFresnel90=0.5+2.0*VdotH*VdotH*roughness;\nfloat diffuseFresnelTerm =\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNL) *\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNV);\nreturn diffuseFresnelTerm*NdotL;\n\n\n}\nfloat adjustRoughnessFromLightProperties(float roughness,float lightRadius,float lightDistance)\n{\n#ifdef USEPHYSICALLIGHTFALLOFF\n\nfloat lightRoughness=lightRadius/lightDistance;\n\nfloat totalRoughness=clamp(lightRoughness+roughness,0.,1.);\nreturn totalRoughness;\n#else\nreturn roughness;\n#endif\n}\nfloat computeDefaultMicroSurface(float microSurface,vec3 reflectivityColor)\n{\nfloat kReflectivityNoAlphaWorkflow_SmoothnessMax=0.95;\nfloat reflectivityLuminance=getLuminance(reflectivityColor);\nfloat reflectivityLuma=sqrt(reflectivityLuminance);\nmicroSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;\nreturn microSurface;\n}\nvec3 toLinearSpace(vec3 color)\n{\nreturn vec3(pow(color.r,2.2),pow(color.g,2.2),pow(color.b,2.2));\n}\nvec3 toGammaSpace(vec3 color)\n{\nreturn vec3(pow(color.r,1.0/2.2),pow(color.g,1.0/2.2),pow(color.b,1.0/2.2));\n}\n#ifdef CAMERATONEMAP\nvec3 toneMaps(vec3 color)\n{\ncolor=max(color,0.0);\n\ncolor.rgb=color.rgb*vCameraInfos.x;\nfloat tuning=1.5; \n\n\nvec3 tonemapped=1.0-exp2(-color.rgb*tuning); \ncolor.rgb=mix(color.rgb,tonemapped,1.0);\nreturn color;\n}\n#endif\n#ifdef CAMERACONTRAST\nvec4 contrasts(vec4 color)\n{\ncolor=clamp(color,0.0,1.0);\nvec3 resultHighContrast=color.rgb*color.rgb*(3.0-2.0*color.rgb);\nfloat contrast=vCameraInfos.y;\nif (contrast<1.0)\n{\n\ncolor.rgb=mix(vec3(0.5,0.5,0.5),color.rgb,contrast);\n}\nelse\n{\n\ncolor.rgb=mix(color.rgb,resultHighContrast,contrast-1.0);\n}\nreturn color;\n}\n#endif","pbrLightFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n};\nfloat computeDistanceLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range)\n{ \n#ifdef USEPHYSICALLIGHTFALLOFF\nfloat lightDistanceFalloff=1.0/((lightDistanceSquared+0.0001));\n#else\nfloat lightDistanceFalloff=max(0.,1.0-length(lightOffset)/range);\n#endif\nreturn lightDistanceFalloff;\n}\nfloat computeDirectionalLightFalloff(vec3 lightDirection,vec3 directionToLightCenterW,float lightAngle,float exponent)\n{\nfloat falloff=0.0;\n#ifdef USEPHYSICALLIGHTFALLOFF\nfloat cosHalfAngle=cos(lightAngle*0.5);\nconst float kMinusLog2ConeAngleIntensityRatio=6.64385618977; \n\n\n\n\n\nfloat concentrationKappa=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);\n\n\nvec4 lightDirectionSpreadSG=vec4(-lightDirection*concentrationKappa,-concentrationKappa);\nfalloff=exp2(dot(vec4(directionToLightCenterW,1.0),lightDirectionSpreadSG));\n#else\nfloat cosAngle=max(0.000000000000001,dot(-lightDirection,directionToLightCenterW));\nif (cosAngle>=lightAngle)\n{\nfalloff=max(0.,pow(cosAngle,exponent));\n}\n#endif\nreturn falloff;\n}\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\nvec3 lightDirection;\nfloat attenuation=1.0;\nfloat lightDistance;\n\nif (lightData.w == 0.)\n{\nvec3 lightOffset=lightData.xyz-vPositionW;\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nattenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\nlightDistance=sqrt(lightDistanceSquared);\nlightDirection=normalize(lightOffset);\n}\n\nelse\n{\nlightDistance=length(-lightData.xyz);\nlightDirection=normalize(-lightData.xyz);\n}\n\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+lightDirection);\nNdotL=max(0.00000000001,dot(vNormal,lightDirection));\nfloat VdotH=clamp(0.00000000001,1.0,dot(viewDirectionW,H));\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=max(0.00000000001,dot(vNormal,H));\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,specularColor,reflectance90);\nresult.specular=specTerm*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\nvec3 lightOffset=lightData.xyz-vPositionW;\nvec3 directionToLightCenterW=normalize(lightOffset);\n\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nfloat attenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\n\nfloat directionalAttenuation=computeDirectionalLightFalloff(lightDirection.xyz,directionToLightCenterW,lightDirection.w,lightData.w);\nattenuation*=directionalAttenuation;\n\nfloat lightDistance=sqrt(lightDistanceSquared);\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW-lightDirection.xyz);\nNdotL=max(0.00000000001,dot(vNormal,-lightDirection.xyz));\nfloat VdotH=clamp(dot(viewDirectionW,H),0.00000000001,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=max(0.00000000001,dot(vNormal,H));\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,specularColor,reflectance90);\nresult.specular=specTerm*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float roughness,float NdotV,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\n\n\n\nNdotL=dot(vNormal,lightData.xyz)*0.5+0.5;\nresult.diffuse=mix(groundColor,diffuseColor,NdotL);\n#ifdef SPECULARTERM\n\nvec3 lightVectorW=normalize(lightData.xyz);\nvec3 H=normalize(viewDirectionW+lightVectorW);\nfloat NdotH=max(0.00000000001,dot(vNormal,H));\nNdotL=max(0.00000000001,NdotL);\nfloat VdotH=clamp(0.00000000001,1.0,dot(viewDirectionW,H));\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,specularColor,reflectance90);\nresult.specular=specTerm;\n#endif\nreturn result;\n}","pbrLightFunctionsCall":"#ifdef LIGHT{X}\n#ifndef SPECULARTERM\nvec3 vLightSpecular{X}=vec3(0.0);\n#endif\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,vLightData{X},vLightDirection{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightDiffuse{X}.a,roughness,NdotV,specularEnvironmentR90,NdotL);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,vLightData{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightGround{X},roughness,NdotV,specularEnvironmentR90,NdotL);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,vLightData{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightDiffuse{X}.a,roughness,NdotV,specularEnvironmentR90,NdotL);\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWVSM{X}\nnotShadowLevel=computeShadowWithVSM(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.z,shadowsInfo{X}.x);\n#else\n#ifdef SHADOWPCF{X}\n#if defined(POINTLIGHT{X})\nnotShadowLevel=computeShadowWithPCFCube(vLightData{X}.xyz,shadowSampler{X},shadowsInfo{X}.y,shadowsInfo{X}.z,shadowsInfo{X}.x);\n#else\nnotShadowLevel=computeShadowWithPCF(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.y,shadowsInfo{X}.z,shadowsInfo{X}.x);\n#endif\n#else\n#if defined(POINTLIGHT{X})\nnotShadowLevel=computeShadowCube(vLightData{X}.xyz,shadowSampler{X},shadowsInfo{X}.x,shadowsInfo{X}.z);\n#else\nnotShadowLevel=computeShadow(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.x,shadowsInfo{X}.z);\n#endif\n#endif\n#endif\n#else\nnotShadowLevel=1.;\n#endif\nlightDiffuseContribution+=info.diffuse*notShadowLevel;\n#ifdef OVERLOADEDSHADOWVALUES\nif (NdotL<0.000000000011)\n{\nnotShadowLevel=1.;\n}\nshadowedOnlyLightDiffuseContribution*=notShadowLevel;\n#endif\n#ifdef SPECULARTERM\nlightSpecularContribution+=info.specular*notShadowLevel;\n#endif\n#endif","pbrShadowFunctions":"\n#ifdef SHADOWS\n#ifndef SHADOWFULLFLOAT\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nuniform vec2 depthValues;\nfloat computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float bias)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y =-directionToLight.y;\n#ifndef SHADOWFULLFLOAT\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight))+bias;\n#else\nfloat shadow=textureCube(shadowSampler,directionToLight).x+bias;\n#endif\nif (depth>shadow)\n{\n#ifdef OVERLOADEDSHADOWVALUES\nreturn mix(1.0,darkness,vOverloadedShadowIntensity.x);\n#else\nreturn darkness;\n#endif\n}\nreturn 1.0;\n}\nfloat computeShadowWithPCFCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float bias,float darkness)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth-depthValues.x)/(depthValues.y-depthValues.x);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\nfloat visibility=1.;\nvec3 poissonDisk[4];\npoissonDisk[0]=vec3(-1.0,1.0,-1.0);\npoissonDisk[1]=vec3(1.0,-1.0,-1.0);\npoissonDisk[2]=vec3(-1.0,-1.0,-1.0);\npoissonDisk[3]=vec3(1.0,-1.0,1.0);\n\nfloat biasedDepth=depth-bias;\n#ifndef SHADOWFULLFLOAT\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<biasedDepth) visibility-=0.25;\n#else\nif (textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize).x<biasedDepth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize).x<biasedDepth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize).x<biasedDepth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize).x<biasedDepth) visibility-=0.25;\n#endif\n#ifdef OVERLOADEDSHADOWVALUES\nreturn min(1.0,mix(1.0,visibility+darkness,vOverloadedShadowIntensity.x));\n#else\nreturn min(1.0,visibility+darkness);\n#endif\n}\nfloat computeShadow(vec4 vPositionFromLight,sampler2D shadowSampler,float darkness,float bias)\n{\nvec3 depth=vPositionFromLight.xyz/vPositionFromLight.w;\ndepth=0.5*depth+vec3(0.5);\nvec2 uv=depth.xy;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\n#ifndef SHADOWFULLFLOAT\nfloat shadow=unpack(texture2D(shadowSampler,uv))+bias;\n#else\nfloat shadow=texture2D(shadowSampler,uv).x+bias;\n#endif\nif (depth.z>shadow)\n{\n#ifdef OVERLOADEDSHADOWVALUES\nreturn mix(1.0,darkness,vOverloadedShadowIntensity.x);\n#else\nreturn darkness;\n#endif\n}\nreturn 1.;\n}\nfloat computeShadowWithPCF(vec4 vPositionFromLight,sampler2D shadowSampler,float mapSize,float bias,float darkness)\n{\nvec3 depth=vPositionFromLight.xyz/vPositionFromLight.w;\ndepth=0.5*depth+vec3(0.5);\nvec2 uv=depth.xy;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat visibility=1.;\nvec2 poissonDisk[4];\npoissonDisk[0]=vec2(-0.94201624,-0.39906216);\npoissonDisk[1]=vec2(0.94558609,-0.76890725);\npoissonDisk[2]=vec2(-0.094184101,-0.92938870);\npoissonDisk[3]=vec2(0.34495938,0.29387760);\n\nfloat biasedDepth=depth.z-bias;\n#ifndef SHADOWFULLFLOAT\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[0]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[1]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[2]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[3]*mapSize))<biasedDepth) visibility-=0.25;\n#else\nif (texture2D(shadowSampler,uv+poissonDisk[0]*mapSize).x<biasedDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[1]*mapSize).x<biasedDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[2]*mapSize).x<biasedDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[3]*mapSize).x<biasedDepth) visibility-=0.25;\n#endif\n#ifdef OVERLOADEDSHADOWVALUES\nreturn min(1.0,mix(1.0,visibility+darkness,vOverloadedShadowIntensity.x));\n#else\nreturn min(1.0,visibility+darkness);\n#endif\n}\n#ifndef SHADOWFULLFLOAT\n\nfloat unpackHalf(vec2 color)\n{\nreturn color.x+(color.y/255.0);\n}\n#endif\nfloat linstep(float low,float high,float v) {\nreturn clamp((v-low)/(high-low),0.0,1.0);\n}\nfloat ChebychevInequality(vec2 moments,float compare,float bias)\n{\nfloat p=smoothstep(compare-bias,compare,moments.x);\nfloat variance=max(moments.y-moments.x*moments.x,0.02);\nfloat d=compare-moments.x;\nfloat p_max=linstep(0.2,1.0,variance/(variance+d*d));\nreturn clamp(max(p,p_max),0.0,1.0);\n}\nfloat computeShadowWithVSM(vec4 vPositionFromLight,sampler2D shadowSampler,float bias,float darkness)\n{\nvec3 depth=vPositionFromLight.xyz/vPositionFromLight.w;\ndepth=0.5*depth+vec3(0.5);\nvec2 uv=depth.xy;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0 || depth.z>=1.0)\n{\nreturn 1.0;\n}\nvec4 texel=texture2D(shadowSampler,uv);\n#ifndef SHADOWFULLFLOAT\nvec2 moments=vec2(unpackHalf(texel.xy),unpackHalf(texel.zw));\n#else\nvec2 moments=texel.xy;\n#endif\n#ifdef OVERLOADEDSHADOWVALUES\nreturn min(1.0,mix(1.0,1.0-ChebychevInequality(moments,depth.z,bias)+darkness,vOverloadedShadowIntensity.x));\n#else\nreturn min(1.0,1.0-ChebychevInequality(moments,depth.z,bias)+darkness);\n#endif\n}\n#endif","pointCloudVertex":"#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif","pointCloudVertexDeclaration":"#ifdef POINTSIZE\nuniform float pointSize;\n#endif","reflectionFunction":"vec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvec3 direction=normalize(vDirectionW);\nfloat t=clamp(direction.y*-0.5+0.5,0.,1.0);\nfloat s=atan(direction.z,direction.x)*RECIPROCAL_PI2+0.5;\nreturn vec3(s,t,0);\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR\nvec3 cameraToVertex=normalize(worldPos.xyz-vEyePosition);\nvec3 r=reflect(cameraToVertex,worldNormal);\nfloat t=clamp(r.y*-0.5+0.5,0.,1.0);\nfloat s=atan(r.z,r.x)*RECIPROCAL_PI2+0.5;\nreturn vec3(s,t,0);\n#endif\n#ifdef REFLECTIONMAP_SPHERICAL\nvec3 viewDir=normalize(vec3(view*worldPos));\nvec3 viewNormal=normalize(vec3(view*vec4(worldNormal,0.0)));\nvec3 r=reflect(viewDir,viewNormal);\nr.z=r.z-1.0;\nfloat m=2.0*length(r);\nreturn vec3(r.x/m+0.5,1.0-r.y/m-0.5,0);\n#endif\n#ifdef REFLECTIONMAP_PLANAR\nvec3 viewDir=worldPos.xyz-vEyePosition;\nvec3 coords=normalize(reflect(viewDir,worldNormal));\nreturn vec3(reflectionMatrix*vec4(coords,1));\n#endif\n#ifdef REFLECTIONMAP_CUBIC\nvec3 viewDir=worldPos.xyz-vEyePosition;\nvec3 coords=reflect(viewDir,worldNormal);\n#ifdef INVERTCUBICMAP\ncoords.y=1.0-coords.y;\n#endif\nreturn vec3(reflectionMatrix*vec4(coords,0));\n#endif\n#ifdef REFLECTIONMAP_PROJECTION\nreturn vec3(reflectionMatrix*(view*worldPos));\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nreturn vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EXPLICIT\nreturn vec3(0,0,0);\n#endif\n}","shadowsFragmentFunctions":"#ifdef SHADOWS\n#ifndef SHADOWFULLFLOAT\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nuniform vec2 depthValues;\nfloat computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float bias)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth-depthValues.x)/(depthValues.y-depthValues.x);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFULLFLOAT\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight))+bias;\n#else\nfloat shadow=textureCube(shadowSampler,directionToLight).x+bias;\n#endif\nif (depth>shadow)\n{\nreturn darkness;\n}\nreturn 1.0;\n}\nfloat computeShadowWithPCFCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float bias,float darkness)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth-depthValues.x)/(depthValues.y-depthValues.x);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\nfloat visibility=1.;\nvec3 poissonDisk[4];\npoissonDisk[0]=vec3(-1.0,1.0,-1.0);\npoissonDisk[1]=vec3(1.0,-1.0,-1.0);\npoissonDisk[2]=vec3(-1.0,-1.0,-1.0);\npoissonDisk[3]=vec3(1.0,-1.0,1.0);\n\nfloat biasedDepth=depth-bias;\n#ifndef SHADOWFULLFLOAT\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<biasedDepth) visibility-=0.25;\n#else\nif (textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize).x<biasedDepth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize).x<biasedDepth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize).x<biasedDepth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize).x<biasedDepth) visibility-=0.25;\n#endif\nreturn min(1.0,visibility+darkness);\n}\nfloat computeShadow(vec4 vPositionFromLight,sampler2D shadowSampler,float darkness,float bias)\n{\nvec3 depth=vPositionFromLight.xyz/vPositionFromLight.w;\ndepth=0.5*depth+vec3(0.5);\nvec2 uv=depth.xy;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\n#ifndef SHADOWFULLFLOAT\nfloat shadow=unpack(texture2D(shadowSampler,uv))+bias;\n#else\nfloat shadow=texture2D(shadowSampler,uv).x+bias;\n#endif\nif (depth.z>shadow)\n{\nreturn darkness;\n}\nreturn 1.;\n}\nfloat computeShadowWithPCF(vec4 vPositionFromLight,sampler2D shadowSampler,float mapSize,float bias,float darkness)\n{\nvec3 depth=vPositionFromLight.xyz/vPositionFromLight.w;\ndepth=0.5*depth+vec3(0.5);\nvec2 uv=depth.xy;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat visibility=1.;\nvec2 poissonDisk[4];\npoissonDisk[0]=vec2(-0.94201624,-0.39906216);\npoissonDisk[1]=vec2(0.94558609,-0.76890725);\npoissonDisk[2]=vec2(-0.094184101,-0.92938870);\npoissonDisk[3]=vec2(0.34495938,0.29387760);\n\nfloat biasedDepth=depth.z-bias;\n#ifndef SHADOWFULLFLOAT\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[0]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[1]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[2]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[3]*mapSize))<biasedDepth) visibility-=0.25;\n#else\nif (texture2D(shadowSampler,uv+poissonDisk[0]*mapSize).x<biasedDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[1]*mapSize).x<biasedDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[2]*mapSize).x<biasedDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[3]*mapSize).x<biasedDepth) visibility-=0.25;\n#endif\nreturn min(1.0,visibility+darkness);\n}\n#ifndef SHADOWFULLFLOAT\n\nfloat unpackHalf(vec2 color)\n{\nreturn color.x+(color.y/255.0);\n}\n#endif\nfloat linstep(float low,float high,float v) {\nreturn clamp((v-low)/(high-low),0.0,1.0);\n}\nfloat ChebychevInequality(vec2 moments,float compare,float bias)\n{\nfloat p=smoothstep(compare-bias,compare,moments.x);\nfloat variance=max(moments.y-moments.x*moments.x,0.02);\nfloat d=compare-moments.x;\nfloat p_max=linstep(0.2,1.0,variance/(variance+d*d));\nreturn clamp(max(p,p_max),0.0,1.0);\n}\nfloat computeShadowWithVSM(vec4 vPositionFromLight,sampler2D shadowSampler,float bias,float darkness)\n{\nvec3 depth=vPositionFromLight.xyz/vPositionFromLight.w;\ndepth=0.5*depth+vec3(0.5);\nvec2 uv=depth.xy;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0 || depth.z>=1.0)\n{\nreturn 1.0;\n}\nvec4 texel=texture2D(shadowSampler,uv);\n#ifndef SHADOWFULLFLOAT\nvec2 moments=vec2(unpackHalf(texel.xy),unpackHalf(texel.zw));\n#else\nvec2 moments=texel.xy;\n#endif\nreturn min(1.0,1.0-ChebychevInequality(moments,depth.z,bias)+darkness);\n}\n#endif","shadowsVertex":"#ifdef SHADOWS\n#if defined(SPOTLIGHT{X}) || defined(DIRLIGHT{X})\nvPositionFromLight{X}=lightMatrix{X}*worldPos;\n#endif\n#endif","shadowsVertexDeclaration":"#ifdef SHADOWS\n#if defined(SPOTLIGHT{X}) || defined(DIRLIGHT{X})\nuniform mat4 lightMatrix{X};\nvarying vec4 vPositionFromLight{X};\n#endif\n#endif\n"};
  60839. BABYLON.CollisionWorker="var BABYLON;!function(t){var e=function(t,e,o,i){return!(t.x>o.x+i)&&(!(o.x-i>e.x)&&(!(t.y>o.y+i)&&(!(o.y-i>e.y)&&(!(t.z>o.z+i)&&!(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(r<0)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&&c<s?(t.root=c,t.found=!0,t):h>0&&h<s?(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!(n<0)&&(s.subtractToRef(e,this._tempVector3),t.Vector3.CrossToRef(this._tempVector2,this._tempVector3,this._tempVector4),n=t.Vector3.Dot(this._tempVector4,r),!(n<0)&&(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)&&!!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||V<0)return;h<0&&(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&&D<=1&&(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&&D<=1&&(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&&D<=1&&(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;c<s;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;c<a;++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;s<r;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;t<s;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;t<a;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-r<=n&&n<=r},t.ToHex=function(t){var i=t.toString(16);return t<=15?(\"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=o<0?-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&&s+h<2*o*e},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,T<0&&d<2&&(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)},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),u<-.499&&(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(h<0&&(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]&&(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;t<16;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;r<16;r++)i.m[r]=this.m[r]+t.m[r];return this},t.prototype.addToSelf=function(t){for(var i=0;i<16;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;i<16;i++)this.m[i]=t.m[i];return this},t.prototype.copyToArray=function(t,i){void 0===i&&(i=0);for(var r=0;r<16;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;i<16;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;n<16;n++)r.m[n]=t[n+i]},t.FromFloat32ArrayToRefScaled=function(t,i,r,n){for(var o=0;o<16;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(t<0||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(t<0||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;e<16;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 r<=i},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;n<6;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;u<5;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),u-a<-180&&(u+=360),m-u>180&&(m-=360),m-u<-180&&(m+=360),this.orientation=u-a<0?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;c<e;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(t<0||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&&i<=u){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;u<i;u++)o=this._getLastNonNullVector(u),u<i-1&&(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;a<=o;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;u<=s;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;u<=s;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={}));";
  60840. if (((typeof window != "undefined" && window.module) || (typeof module != "undefined")) && typeof module.exports != "undefined") {
  60841. module.exports = BABYLON;
  60842. };