babylon.max.js 3.1 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289
  1. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  2. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  3. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  4. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  5. return c > 3 && r && Object.defineProperty(target, key, r), r;
  6. };
  7. var __extends = (this && this.__extends) || function (d, b) {
  8. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  9. function __() { this.constructor = d; }
  10. __.prototype = b.prototype;
  11. d.prototype = new __();
  12. };
  13. var BABYLON;
  14. (function (BABYLON) {
  15. BABYLON.ToGammaSpace = 1 / 2.2;
  16. BABYLON.ToLinearSpace = 2.2;
  17. BABYLON.Epsilon = 0.001;
  18. var MathTools = (function () {
  19. function MathTools() {
  20. }
  21. MathTools.WithinEpsilon = function (a, b, epsilon) {
  22. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  23. var num = a - b;
  24. return -epsilon <= num && num <= epsilon;
  25. };
  26. MathTools.ToHex = function (i) {
  27. var str = i.toString(16);
  28. if (i <= 15) {
  29. return ("0" + str).toUpperCase();
  30. }
  31. return str.toUpperCase();
  32. };
  33. // Returns -1 when value is a negative number and
  34. // +1 when value is a positive number.
  35. MathTools.Sign = function (value) {
  36. value = +value; // convert to a number
  37. if (value === 0 || isNaN(value))
  38. return value;
  39. return value > 0 ? 1 : -1;
  40. };
  41. MathTools.Clamp = function (value, min, max) {
  42. if (min === void 0) { min = 0; }
  43. if (max === void 0) { max = 1; }
  44. return Math.min(max, Math.max(min, value));
  45. };
  46. return MathTools;
  47. })();
  48. BABYLON.MathTools = MathTools;
  49. var Color3 = (function () {
  50. function Color3(r, g, b) {
  51. if (r === void 0) { r = 0; }
  52. if (g === void 0) { g = 0; }
  53. if (b === void 0) { b = 0; }
  54. this.r = r;
  55. this.g = g;
  56. this.b = b;
  57. }
  58. Color3.prototype.toString = function () {
  59. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  60. };
  61. Color3.prototype.getClassName = function () {
  62. return "Color3";
  63. };
  64. Color3.prototype.getHashCode = function () {
  65. var hash = this.r || 0;
  66. hash = (hash * 397) ^ (this.g || 0);
  67. hash = (hash * 397) ^ (this.b || 0);
  68. return hash;
  69. };
  70. // Operators
  71. Color3.prototype.toArray = function (array, index) {
  72. if (index === undefined) {
  73. index = 0;
  74. }
  75. array[index] = this.r;
  76. array[index + 1] = this.g;
  77. array[index + 2] = this.b;
  78. return this;
  79. };
  80. Color3.prototype.toColor4 = function (alpha) {
  81. if (alpha === void 0) { alpha = 1; }
  82. return new Color4(this.r, this.g, this.b, alpha);
  83. };
  84. Color3.prototype.asArray = function () {
  85. var result = [];
  86. this.toArray(result, 0);
  87. return result;
  88. };
  89. Color3.prototype.toLuminance = function () {
  90. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  91. };
  92. Color3.prototype.multiply = function (otherColor) {
  93. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  94. };
  95. Color3.prototype.multiplyToRef = function (otherColor, result) {
  96. result.r = this.r * otherColor.r;
  97. result.g = this.g * otherColor.g;
  98. result.b = this.b * otherColor.b;
  99. return this;
  100. };
  101. Color3.prototype.equals = function (otherColor) {
  102. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  103. };
  104. Color3.prototype.equalsFloats = function (r, g, b) {
  105. return this.r === r && this.g === g && this.b === b;
  106. };
  107. Color3.prototype.scale = function (scale) {
  108. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  109. };
  110. Color3.prototype.scaleToRef = function (scale, result) {
  111. result.r = this.r * scale;
  112. result.g = this.g * scale;
  113. result.b = this.b * scale;
  114. return this;
  115. };
  116. Color3.prototype.add = function (otherColor) {
  117. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  118. };
  119. Color3.prototype.addToRef = function (otherColor, result) {
  120. result.r = this.r + otherColor.r;
  121. result.g = this.g + otherColor.g;
  122. result.b = this.b + otherColor.b;
  123. return this;
  124. };
  125. Color3.prototype.subtract = function (otherColor) {
  126. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  127. };
  128. Color3.prototype.subtractToRef = function (otherColor, result) {
  129. result.r = this.r - otherColor.r;
  130. result.g = this.g - otherColor.g;
  131. result.b = this.b - otherColor.b;
  132. return this;
  133. };
  134. Color3.prototype.clone = function () {
  135. return new Color3(this.r, this.g, this.b);
  136. };
  137. Color3.prototype.copyFrom = function (source) {
  138. this.r = source.r;
  139. this.g = source.g;
  140. this.b = source.b;
  141. return this;
  142. };
  143. Color3.prototype.copyFromFloats = function (r, g, b) {
  144. this.r = r;
  145. this.g = g;
  146. this.b = b;
  147. return this;
  148. };
  149. Color3.prototype.toHexString = function () {
  150. var intR = (this.r * 255) | 0;
  151. var intG = (this.g * 255) | 0;
  152. var intB = (this.b * 255) | 0;
  153. return "#" + MathTools.ToHex(intR) + MathTools.ToHex(intG) + MathTools.ToHex(intB);
  154. };
  155. Color3.prototype.toLinearSpace = function () {
  156. var convertedColor = new Color3();
  157. this.toLinearSpaceToRef(convertedColor);
  158. return convertedColor;
  159. };
  160. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  161. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  162. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  163. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  164. return this;
  165. };
  166. Color3.prototype.toGammaSpace = function () {
  167. var convertedColor = new Color3();
  168. this.toGammaSpaceToRef(convertedColor);
  169. return convertedColor;
  170. };
  171. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  172. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  173. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  174. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  175. return this;
  176. };
  177. // Statics
  178. Color3.FromHexString = function (hex) {
  179. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  180. //Tools.Warn("Color3.FromHexString must be called with a string like #FFFFFF");
  181. return new Color3(0, 0, 0);
  182. }
  183. var r = parseInt(hex.substring(1, 3), 16);
  184. var g = parseInt(hex.substring(3, 5), 16);
  185. var b = parseInt(hex.substring(5, 7), 16);
  186. return Color3.FromInts(r, g, b);
  187. };
  188. Color3.FromArray = function (array, offset) {
  189. if (offset === void 0) { offset = 0; }
  190. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  191. };
  192. Color3.FromInts = function (r, g, b) {
  193. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  194. };
  195. Color3.Lerp = function (start, end, amount) {
  196. var r = start.r + ((end.r - start.r) * amount);
  197. var g = start.g + ((end.g - start.g) * amount);
  198. var b = start.b + ((end.b - start.b) * amount);
  199. return new Color3(r, g, b);
  200. };
  201. Color3.Red = function () { return new Color3(1, 0, 0); };
  202. Color3.Green = function () { return new Color3(0, 1, 0); };
  203. Color3.Blue = function () { return new Color3(0, 0, 1); };
  204. Color3.Black = function () { return new Color3(0, 0, 0); };
  205. Color3.White = function () { return new Color3(1, 1, 1); };
  206. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  207. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  208. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  209. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  210. return Color3;
  211. })();
  212. BABYLON.Color3 = Color3;
  213. var Color4 = (function () {
  214. function Color4(r, g, b, a) {
  215. this.r = r;
  216. this.g = g;
  217. this.b = b;
  218. this.a = a;
  219. }
  220. // Operators
  221. Color4.prototype.addInPlace = function (right) {
  222. this.r += right.r;
  223. this.g += right.g;
  224. this.b += right.b;
  225. this.a += right.a;
  226. return this;
  227. };
  228. Color4.prototype.asArray = function () {
  229. var result = [];
  230. this.toArray(result, 0);
  231. return result;
  232. };
  233. Color4.prototype.toArray = function (array, index) {
  234. if (index === undefined) {
  235. index = 0;
  236. }
  237. array[index] = this.r;
  238. array[index + 1] = this.g;
  239. array[index + 2] = this.b;
  240. array[index + 3] = this.a;
  241. return this;
  242. };
  243. Color4.prototype.add = function (right) {
  244. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  245. };
  246. Color4.prototype.subtract = function (right) {
  247. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  248. };
  249. Color4.prototype.subtractToRef = function (right, result) {
  250. result.r = this.r - right.r;
  251. result.g = this.g - right.g;
  252. result.b = this.b - right.b;
  253. result.a = this.a - right.a;
  254. return this;
  255. };
  256. Color4.prototype.scale = function (scale) {
  257. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  258. };
  259. Color4.prototype.scaleToRef = function (scale, result) {
  260. result.r = this.r * scale;
  261. result.g = this.g * scale;
  262. result.b = this.b * scale;
  263. result.a = this.a * scale;
  264. return this;
  265. };
  266. /**
  267. * Multipy an RGBA Color4 value by another and return a new Color4 object
  268. * @param color The Color4 (RGBA) value to multiply by
  269. * @returns A new Color4.
  270. */
  271. Color4.prototype.multiply = function (color) {
  272. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  273. };
  274. /**
  275. * Multipy an RGBA Color4 value by another and push the result in a reference value
  276. * @param color The Color4 (RGBA) value to multiply by
  277. * @param result The Color4 (RGBA) to fill the result in
  278. * @returns the result Color4.
  279. */
  280. Color4.prototype.multiplyToRef = function (color, result) {
  281. result.r = this.r * color.r;
  282. result.g = this.g * color.g;
  283. result.b = this.b * color.b;
  284. result.a = this.a * color.a;
  285. return result;
  286. };
  287. Color4.prototype.toString = function () {
  288. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  289. };
  290. Color4.prototype.getClassName = function () {
  291. return "Color4";
  292. };
  293. Color4.prototype.getHashCode = function () {
  294. var hash = this.r || 0;
  295. hash = (hash * 397) ^ (this.g || 0);
  296. hash = (hash * 397) ^ (this.b || 0);
  297. hash = (hash * 397) ^ (this.a || 0);
  298. return hash;
  299. };
  300. Color4.prototype.clone = function () {
  301. return new Color4(this.r, this.g, this.b, this.a);
  302. };
  303. Color4.prototype.copyFrom = function (source) {
  304. this.r = source.r;
  305. this.g = source.g;
  306. this.b = source.b;
  307. this.a = source.a;
  308. return this;
  309. };
  310. Color4.prototype.toHexString = function () {
  311. var intR = (this.r * 255) | 0;
  312. var intG = (this.g * 255) | 0;
  313. var intB = (this.b * 255) | 0;
  314. var intA = (this.a * 255) | 0;
  315. return "#" + MathTools.ToHex(intR) + MathTools.ToHex(intG) + MathTools.ToHex(intB) + MathTools.ToHex(intA);
  316. };
  317. // Statics
  318. Color4.FromHexString = function (hex) {
  319. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  320. //Tools.Warn("Color4.FromHexString must be called with a string like #FFFFFFFF");
  321. return new Color4(0, 0, 0, 0);
  322. }
  323. var r = parseInt(hex.substring(1, 3), 16);
  324. var g = parseInt(hex.substring(3, 5), 16);
  325. var b = parseInt(hex.substring(5, 7), 16);
  326. var a = parseInt(hex.substring(7, 9), 16);
  327. return Color4.FromInts(r, g, b, a);
  328. };
  329. Color4.Lerp = function (left, right, amount) {
  330. var result = new Color4(0, 0, 0, 0);
  331. Color4.LerpToRef(left, right, amount, result);
  332. return result;
  333. };
  334. Color4.LerpToRef = function (left, right, amount, result) {
  335. result.r = left.r + (right.r - left.r) * amount;
  336. result.g = left.g + (right.g - left.g) * amount;
  337. result.b = left.b + (right.b - left.b) * amount;
  338. result.a = left.a + (right.a - left.a) * amount;
  339. };
  340. Color4.FromArray = function (array, offset) {
  341. if (offset === void 0) { offset = 0; }
  342. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  343. };
  344. Color4.FromInts = function (r, g, b, a) {
  345. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  346. };
  347. Color4.CheckColors4 = function (colors, count) {
  348. // Check if color3 was used
  349. if (colors.length === count * 3) {
  350. var colors4 = [];
  351. for (var index = 0; index < colors.length; index += 3) {
  352. var newIndex = (index / 3) * 4;
  353. colors4[newIndex] = colors[index];
  354. colors4[newIndex + 1] = colors[index + 1];
  355. colors4[newIndex + 2] = colors[index + 2];
  356. colors4[newIndex + 3] = 1.0;
  357. }
  358. return colors4;
  359. }
  360. return colors;
  361. };
  362. return Color4;
  363. })();
  364. BABYLON.Color4 = Color4;
  365. var Vector2 = (function () {
  366. function Vector2(x, y) {
  367. this.x = x;
  368. this.y = y;
  369. }
  370. Vector2.prototype.toString = function () {
  371. return "{X: " + this.x + " Y:" + this.y + "}";
  372. };
  373. Vector2.prototype.getClassName = function () {
  374. return "Vector2";
  375. };
  376. Vector2.prototype.getHashCode = function () {
  377. var hash = this.x || 0;
  378. hash = (hash * 397) ^ (this.y || 0);
  379. return hash;
  380. };
  381. // Operators
  382. Vector2.prototype.toArray = function (array, index) {
  383. if (index === void 0) { index = 0; }
  384. array[index] = this.x;
  385. array[index + 1] = this.y;
  386. return this;
  387. };
  388. Vector2.prototype.asArray = function () {
  389. var result = [];
  390. this.toArray(result, 0);
  391. return result;
  392. };
  393. Vector2.prototype.copyFrom = function (source) {
  394. this.x = source.x;
  395. this.y = source.y;
  396. return this;
  397. };
  398. Vector2.prototype.copyFromFloats = function (x, y) {
  399. this.x = x;
  400. this.y = y;
  401. return this;
  402. };
  403. Vector2.prototype.add = function (otherVector) {
  404. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  405. };
  406. Vector2.prototype.addToRef = function (otherVector, result) {
  407. result.x = this.x + otherVector.x;
  408. result.y = this.y + otherVector.y;
  409. return this;
  410. };
  411. Vector2.prototype.addInPlace = function (otherVector) {
  412. this.x += otherVector.x;
  413. this.y += otherVector.y;
  414. return this;
  415. };
  416. Vector2.prototype.addVector3 = function (otherVector) {
  417. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  418. };
  419. Vector2.prototype.subtract = function (otherVector) {
  420. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  421. };
  422. Vector2.prototype.subtractToRef = function (otherVector, result) {
  423. result.x = this.x - otherVector.x;
  424. result.y = this.y - otherVector.y;
  425. return this;
  426. };
  427. Vector2.prototype.subtractInPlace = function (otherVector) {
  428. this.x -= otherVector.x;
  429. this.y -= otherVector.y;
  430. return this;
  431. };
  432. Vector2.prototype.multiplyInPlace = function (otherVector) {
  433. this.x *= otherVector.x;
  434. this.y *= otherVector.y;
  435. return this;
  436. };
  437. Vector2.prototype.multiply = function (otherVector) {
  438. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  439. };
  440. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  441. result.x = this.x * otherVector.x;
  442. result.y = this.y * otherVector.y;
  443. return this;
  444. };
  445. Vector2.prototype.multiplyByFloats = function (x, y) {
  446. return new Vector2(this.x * x, this.y * y);
  447. };
  448. Vector2.prototype.divide = function (otherVector) {
  449. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  450. };
  451. Vector2.prototype.divideToRef = function (otherVector, result) {
  452. result.x = this.x / otherVector.x;
  453. result.y = this.y / otherVector.y;
  454. return this;
  455. };
  456. Vector2.prototype.negate = function () {
  457. return new Vector2(-this.x, -this.y);
  458. };
  459. Vector2.prototype.scaleInPlace = function (scale) {
  460. this.x *= scale;
  461. this.y *= scale;
  462. return this;
  463. };
  464. Vector2.prototype.scale = function (scale) {
  465. return new Vector2(this.x * scale, this.y * scale);
  466. };
  467. Vector2.prototype.equals = function (otherVector) {
  468. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  469. };
  470. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  471. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  472. return otherVector && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon) && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon);
  473. };
  474. // Properties
  475. Vector2.prototype.length = function () {
  476. return Math.sqrt(this.x * this.x + this.y * this.y);
  477. };
  478. Vector2.prototype.lengthSquared = function () {
  479. return (this.x * this.x + this.y * this.y);
  480. };
  481. // Methods
  482. Vector2.prototype.normalize = function () {
  483. var len = this.length();
  484. if (len === 0)
  485. return this;
  486. var num = 1.0 / len;
  487. this.x *= num;
  488. this.y *= num;
  489. return this;
  490. };
  491. Vector2.prototype.clone = function () {
  492. return new Vector2(this.x, this.y);
  493. };
  494. // Statics
  495. Vector2.Zero = function () {
  496. return new Vector2(0, 0);
  497. };
  498. Vector2.FromArray = function (array, offset) {
  499. if (offset === void 0) { offset = 0; }
  500. return new Vector2(array[offset], array[offset + 1]);
  501. };
  502. Vector2.FromArrayToRef = function (array, offset, result) {
  503. result.x = array[offset];
  504. result.y = array[offset + 1];
  505. };
  506. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  507. var squared = amount * amount;
  508. var cubed = amount * squared;
  509. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  510. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  511. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  512. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  513. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  514. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  515. return new Vector2(x, y);
  516. };
  517. Vector2.Clamp = function (value, min, max) {
  518. var x = value.x;
  519. x = (x > max.x) ? max.x : x;
  520. x = (x < min.x) ? min.x : x;
  521. var y = value.y;
  522. y = (y > max.y) ? max.y : y;
  523. y = (y < min.y) ? min.y : y;
  524. return new Vector2(x, y);
  525. };
  526. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  527. var squared = amount * amount;
  528. var cubed = amount * squared;
  529. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  530. var part2 = (-2.0 * cubed) + (3.0 * squared);
  531. var part3 = (cubed - (2.0 * squared)) + amount;
  532. var part4 = cubed - squared;
  533. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  534. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  535. return new Vector2(x, y);
  536. };
  537. Vector2.Lerp = function (start, end, amount) {
  538. var x = start.x + ((end.x - start.x) * amount);
  539. var y = start.y + ((end.y - start.y) * amount);
  540. return new Vector2(x, y);
  541. };
  542. Vector2.Dot = function (left, right) {
  543. return left.x * right.x + left.y * right.y;
  544. };
  545. Vector2.Normalize = function (vector) {
  546. var newVector = vector.clone();
  547. newVector.normalize();
  548. return newVector;
  549. };
  550. Vector2.Minimize = function (left, right) {
  551. var x = (left.x < right.x) ? left.x : right.x;
  552. var y = (left.y < right.y) ? left.y : right.y;
  553. return new Vector2(x, y);
  554. };
  555. Vector2.Maximize = function (left, right) {
  556. var x = (left.x > right.x) ? left.x : right.x;
  557. var y = (left.y > right.y) ? left.y : right.y;
  558. return new Vector2(x, y);
  559. };
  560. Vector2.Transform = function (vector, transformation) {
  561. var r = Vector2.Zero();
  562. Vector2.TransformToRef(vector, transformation, r);
  563. return r;
  564. };
  565. Vector2.TransformToRef = function (vector, transformation, result) {
  566. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  567. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  568. result.x = x;
  569. result.y = y;
  570. };
  571. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  572. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  573. var sign = a < 0 ? -1 : 1;
  574. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  575. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  576. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  577. };
  578. Vector2.Distance = function (value1, value2) {
  579. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  580. };
  581. Vector2.DistanceSquared = function (value1, value2) {
  582. var x = value1.x - value2.x;
  583. var y = value1.y - value2.y;
  584. return (x * x) + (y * y);
  585. };
  586. Vector2.Center = function (value1, value2) {
  587. var center = value1.add(value2);
  588. center.scaleInPlace(0.5);
  589. return center;
  590. };
  591. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  592. var l2 = Vector2.DistanceSquared(segA, segB);
  593. if (l2 === 0.0) {
  594. return Vector2.Distance(p, segA);
  595. }
  596. var v = segB.subtract(segA);
  597. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  598. var proj = segA.add(v.multiplyByFloats(t, t));
  599. return Vector2.Distance(p, proj);
  600. };
  601. return Vector2;
  602. })();
  603. BABYLON.Vector2 = Vector2;
  604. var Vector3 = (function () {
  605. function Vector3(x, y, z) {
  606. this.x = x;
  607. this.y = y;
  608. this.z = z;
  609. }
  610. Vector3.prototype.toString = function () {
  611. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  612. };
  613. Vector3.prototype.getClassName = function () {
  614. return "Vector3";
  615. };
  616. Vector3.prototype.getHashCode = function () {
  617. var hash = this.x || 0;
  618. hash = (hash * 397) ^ (this.y || 0);
  619. hash = (hash * 397) ^ (this.z || 0);
  620. return hash;
  621. };
  622. // Operators
  623. Vector3.prototype.asArray = function () {
  624. var result = [];
  625. this.toArray(result, 0);
  626. return result;
  627. };
  628. Vector3.prototype.toArray = function (array, index) {
  629. if (index === void 0) { index = 0; }
  630. array[index] = this.x;
  631. array[index + 1] = this.y;
  632. array[index + 2] = this.z;
  633. return this;
  634. };
  635. Vector3.prototype.toQuaternion = function () {
  636. var result = new Quaternion(0, 0, 0, 1);
  637. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  638. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  639. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  640. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  641. var cosy = Math.cos(this.y * 0.5);
  642. var siny = Math.sin(this.y * 0.5);
  643. result.x = coszMinusx * siny;
  644. result.y = -sinzMinusx * siny;
  645. result.z = sinxPlusz * cosy;
  646. result.w = cosxPlusz * cosy;
  647. return result;
  648. };
  649. Vector3.prototype.addInPlace = function (otherVector) {
  650. this.x += otherVector.x;
  651. this.y += otherVector.y;
  652. this.z += otherVector.z;
  653. return this;
  654. };
  655. Vector3.prototype.add = function (otherVector) {
  656. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  657. };
  658. Vector3.prototype.addToRef = function (otherVector, result) {
  659. result.x = this.x + otherVector.x;
  660. result.y = this.y + otherVector.y;
  661. result.z = this.z + otherVector.z;
  662. return this;
  663. };
  664. Vector3.prototype.subtractInPlace = function (otherVector) {
  665. this.x -= otherVector.x;
  666. this.y -= otherVector.y;
  667. this.z -= otherVector.z;
  668. return this;
  669. };
  670. Vector3.prototype.subtract = function (otherVector) {
  671. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  672. };
  673. Vector3.prototype.subtractToRef = function (otherVector, result) {
  674. result.x = this.x - otherVector.x;
  675. result.y = this.y - otherVector.y;
  676. result.z = this.z - otherVector.z;
  677. return this;
  678. };
  679. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  680. return new Vector3(this.x - x, this.y - y, this.z - z);
  681. };
  682. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  683. result.x = this.x - x;
  684. result.y = this.y - y;
  685. result.z = this.z - z;
  686. return this;
  687. };
  688. Vector3.prototype.negate = function () {
  689. return new Vector3(-this.x, -this.y, -this.z);
  690. };
  691. Vector3.prototype.scaleInPlace = function (scale) {
  692. this.x *= scale;
  693. this.y *= scale;
  694. this.z *= scale;
  695. return this;
  696. };
  697. Vector3.prototype.scale = function (scale) {
  698. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  699. };
  700. Vector3.prototype.scaleToRef = function (scale, result) {
  701. result.x = this.x * scale;
  702. result.y = this.y * scale;
  703. result.z = this.z * scale;
  704. };
  705. Vector3.prototype.equals = function (otherVector) {
  706. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  707. };
  708. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  709. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  710. return otherVector && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon) && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon) && MathTools.WithinEpsilon(this.z, otherVector.z, epsilon);
  711. };
  712. Vector3.prototype.equalsToFloats = function (x, y, z) {
  713. return this.x === x && this.y === y && this.z === z;
  714. };
  715. Vector3.prototype.multiplyInPlace = function (otherVector) {
  716. this.x *= otherVector.x;
  717. this.y *= otherVector.y;
  718. this.z *= otherVector.z;
  719. return this;
  720. };
  721. Vector3.prototype.multiply = function (otherVector) {
  722. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  723. };
  724. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  725. result.x = this.x * otherVector.x;
  726. result.y = this.y * otherVector.y;
  727. result.z = this.z * otherVector.z;
  728. return this;
  729. };
  730. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  731. return new Vector3(this.x * x, this.y * y, this.z * z);
  732. };
  733. Vector3.prototype.divide = function (otherVector) {
  734. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  735. };
  736. Vector3.prototype.divideToRef = function (otherVector, result) {
  737. result.x = this.x / otherVector.x;
  738. result.y = this.y / otherVector.y;
  739. result.z = this.z / otherVector.z;
  740. return this;
  741. };
  742. Vector3.prototype.MinimizeInPlace = function (other) {
  743. if (other.x < this.x)
  744. this.x = other.x;
  745. if (other.y < this.y)
  746. this.y = other.y;
  747. if (other.z < this.z)
  748. this.z = other.z;
  749. return this;
  750. };
  751. Vector3.prototype.MaximizeInPlace = function (other) {
  752. if (other.x > this.x)
  753. this.x = other.x;
  754. if (other.y > this.y)
  755. this.y = other.y;
  756. if (other.z > this.z)
  757. this.z = other.z;
  758. return this;
  759. };
  760. // Properties
  761. Vector3.prototype.length = function () {
  762. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  763. };
  764. Vector3.prototype.lengthSquared = function () {
  765. return (this.x * this.x + this.y * this.y + this.z * this.z);
  766. };
  767. // Methods
  768. Vector3.prototype.normalize = function () {
  769. var len = this.length();
  770. if (len === 0 || len === 1.0)
  771. return this;
  772. var num = 1.0 / len;
  773. this.x *= num;
  774. this.y *= num;
  775. this.z *= num;
  776. return this;
  777. };
  778. Vector3.prototype.clone = function () {
  779. return new Vector3(this.x, this.y, this.z);
  780. };
  781. Vector3.prototype.copyFrom = function (source) {
  782. this.x = source.x;
  783. this.y = source.y;
  784. this.z = source.z;
  785. return this;
  786. };
  787. Vector3.prototype.copyFromFloats = function (x, y, z) {
  788. this.x = x;
  789. this.y = y;
  790. this.z = z;
  791. return this;
  792. };
  793. // Statics
  794. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  795. var d0 = Vector3.Dot(vector0, axis) - size;
  796. var d1 = Vector3.Dot(vector1, axis) - size;
  797. var s = d0 / (d0 - d1);
  798. return s;
  799. };
  800. Vector3.FromArray = function (array, offset) {
  801. if (!offset) {
  802. offset = 0;
  803. }
  804. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  805. };
  806. Vector3.FromFloatArray = function (array, offset) {
  807. if (!offset) {
  808. offset = 0;
  809. }
  810. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  811. };
  812. Vector3.FromArrayToRef = function (array, offset, result) {
  813. result.x = array[offset];
  814. result.y = array[offset + 1];
  815. result.z = array[offset + 2];
  816. };
  817. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  818. result.x = array[offset];
  819. result.y = array[offset + 1];
  820. result.z = array[offset + 2];
  821. };
  822. Vector3.FromFloatsToRef = function (x, y, z, result) {
  823. result.x = x;
  824. result.y = y;
  825. result.z = z;
  826. };
  827. Vector3.Zero = function () {
  828. return new Vector3(0, 0, 0);
  829. };
  830. Vector3.Up = function () {
  831. return new Vector3(0, 1.0, 0);
  832. };
  833. Vector3.TransformCoordinates = function (vector, transformation) {
  834. var result = Vector3.Zero();
  835. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  836. return result;
  837. };
  838. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  839. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  840. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  841. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  842. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  843. result.x = x / w;
  844. result.y = y / w;
  845. result.z = z / w;
  846. };
  847. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  848. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  849. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  850. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  851. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  852. result.x = rx / rw;
  853. result.y = ry / rw;
  854. result.z = rz / rw;
  855. };
  856. Vector3.TransformNormal = function (vector, transformation) {
  857. var result = Vector3.Zero();
  858. Vector3.TransformNormalToRef(vector, transformation, result);
  859. return result;
  860. };
  861. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  862. result.x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  863. result.y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  864. result.z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  865. };
  866. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  867. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  868. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  869. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  870. };
  871. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  872. var squared = amount * amount;
  873. var cubed = amount * squared;
  874. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  875. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  876. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  877. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  878. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  879. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  880. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  881. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  882. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  883. return new Vector3(x, y, z);
  884. };
  885. Vector3.Clamp = function (value, min, max) {
  886. var x = value.x;
  887. x = (x > max.x) ? max.x : x;
  888. x = (x < min.x) ? min.x : x;
  889. var y = value.y;
  890. y = (y > max.y) ? max.y : y;
  891. y = (y < min.y) ? min.y : y;
  892. var z = value.z;
  893. z = (z > max.z) ? max.z : z;
  894. z = (z < min.z) ? min.z : z;
  895. return new Vector3(x, y, z);
  896. };
  897. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  898. var squared = amount * amount;
  899. var cubed = amount * squared;
  900. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  901. var part2 = (-2.0 * cubed) + (3.0 * squared);
  902. var part3 = (cubed - (2.0 * squared)) + amount;
  903. var part4 = cubed - squared;
  904. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  905. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  906. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  907. return new Vector3(x, y, z);
  908. };
  909. Vector3.Lerp = function (start, end, amount) {
  910. var x = start.x + ((end.x - start.x) * amount);
  911. var y = start.y + ((end.y - start.y) * amount);
  912. var z = start.z + ((end.z - start.z) * amount);
  913. return new Vector3(x, y, z);
  914. };
  915. Vector3.Dot = function (left, right) {
  916. return (left.x * right.x + left.y * right.y + left.z * right.z);
  917. };
  918. Vector3.Cross = function (left, right) {
  919. var result = Vector3.Zero();
  920. Vector3.CrossToRef(left, right, result);
  921. return result;
  922. };
  923. Vector3.CrossToRef = function (left, right, result) {
  924. Tmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  925. Tmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  926. Tmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  927. result.copyFrom(Tmp.Vector3[0]);
  928. };
  929. Vector3.Normalize = function (vector) {
  930. var result = Vector3.Zero();
  931. Vector3.NormalizeToRef(vector, result);
  932. return result;
  933. };
  934. Vector3.NormalizeToRef = function (vector, result) {
  935. result.copyFrom(vector);
  936. result.normalize();
  937. };
  938. Vector3.Project = function (vector, world, transform, viewport) {
  939. var cw = viewport.width;
  940. var ch = viewport.height;
  941. var cx = viewport.x;
  942. var cy = viewport.y;
  943. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  944. Matrix.FromValuesToRef(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, 1, 0, cx + cw / 2.0, ch / 2.0 + cy, 0, 1, viewportMatrix);
  945. var matrix = Vector3._matrixCache ? Vector3._matrixCache : (Vector3._matrixCache = new Matrix());
  946. world.multiplyToRef(transform, matrix);
  947. matrix.multiplyToRef(viewportMatrix, matrix);
  948. return Vector3.TransformCoordinates(vector, matrix);
  949. };
  950. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  951. var matrix = Vector3._matrixCache ? Vector3._matrixCache : (Vector3._matrixCache = new Matrix());
  952. world.multiplyToRef(transform, matrix);
  953. matrix.invert();
  954. source.x = source.x / viewportWidth * 2 - 1;
  955. source.y = -(source.y / viewportHeight * 2 - 1);
  956. var vector = Vector3.TransformCoordinates(source, matrix);
  957. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  958. if (MathTools.WithinEpsilon(num, 1.0)) {
  959. vector = vector.scale(1.0 / num);
  960. }
  961. return vector;
  962. };
  963. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  964. var matrix = Vector3._matrixCache ? Vector3._matrixCache : (Vector3._matrixCache = new Matrix());
  965. world.multiplyToRef(view, matrix);
  966. matrix.multiplyToRef(projection, matrix);
  967. matrix.invert();
  968. var screenSource = new Vector3(source.x / viewportWidth * 2 - 1, -(source.y / viewportHeight * 2 - 1), source.z);
  969. var vector = Vector3.TransformCoordinates(screenSource, matrix);
  970. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  971. if (MathTools.WithinEpsilon(num, 1.0)) {
  972. vector = vector.scale(1.0 / num);
  973. }
  974. return vector;
  975. };
  976. Vector3.Minimize = function (left, right) {
  977. var min = left.clone();
  978. min.MinimizeInPlace(right);
  979. return min;
  980. };
  981. Vector3.Maximize = function (left, right) {
  982. var max = left.clone();
  983. max.MaximizeInPlace(right);
  984. return max;
  985. };
  986. Vector3.Distance = function (value1, value2) {
  987. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  988. };
  989. Vector3.DistanceSquared = function (value1, value2) {
  990. var x = value1.x - value2.x;
  991. var y = value1.y - value2.y;
  992. var z = value1.z - value2.z;
  993. return (x * x) + (y * y) + (z * z);
  994. };
  995. Vector3.Center = function (value1, value2) {
  996. var center = value1.add(value2);
  997. center.scaleInPlace(0.5);
  998. return center;
  999. };
  1000. /**
  1001. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  1002. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  1003. * to something in order to rotate it from its local system to the given target system.
  1004. */
  1005. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  1006. var rotation = Vector3.Zero();
  1007. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  1008. return rotation;
  1009. };
  1010. /**
  1011. * The same than RotationFromAxis but updates the passed ref Vector3 parameter.
  1012. */
  1013. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  1014. var u = axis1.normalize();
  1015. var w = axis3.normalize();
  1016. // world axis
  1017. var X = Axis.X;
  1018. var Y = Axis.Y;
  1019. // equation unknowns and vars
  1020. var yaw = 0.0;
  1021. var pitch = 0.0;
  1022. var roll = 0.0;
  1023. var x = 0.0;
  1024. var y = 0.0;
  1025. var z = 0.0;
  1026. var t = 0.0;
  1027. var sign = -1.0;
  1028. var nbRevert = 0;
  1029. var cross = Tmp.Vector3[0];
  1030. var dot = 0.0;
  1031. // step 1 : rotation around w
  1032. // Rv3(u) = u1, and u1 belongs to plane xOz
  1033. // Rv3(w) = w1 = w invariant
  1034. var u1 = Tmp.Vector3[1];
  1035. if (MathTools.WithinEpsilon(w.z, 0, BABYLON.Epsilon)) {
  1036. z = 1.0;
  1037. }
  1038. else if (MathTools.WithinEpsilon(w.x, 0, BABYLON.Epsilon)) {
  1039. x = 1.0;
  1040. }
  1041. else {
  1042. t = w.z / w.x;
  1043. x = -t * Math.sqrt(1 / (1 + t * t));
  1044. z = Math.sqrt(1 / (1 + t * t));
  1045. }
  1046. u1.x = x;
  1047. u1.y = y;
  1048. u1.z = z;
  1049. u1.normalize();
  1050. Vector3.CrossToRef(u, u1, cross); // returns same direction as w (=local z) if positive angle : cross(source, image)
  1051. cross.normalize();
  1052. if (Vector3.Dot(w, cross) < 0) {
  1053. sign = 1.0;
  1054. }
  1055. dot = Vector3.Dot(u, u1);
  1056. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  1057. roll = Math.acos(dot) * sign;
  1058. if (Vector3.Dot(u1, X) < 0) {
  1059. roll = Math.PI + roll;
  1060. u1 = u1.scaleInPlace(-1);
  1061. nbRevert++;
  1062. }
  1063. // step 2 : rotate around u1
  1064. // Ru1(w1) = Ru1(w) = w2, and w2 belongs to plane xOz
  1065. // u1 is yet in xOz and invariant by Ru1, so after this step u1 and w2 will be in xOz
  1066. var w2 = Tmp.Vector3[2];
  1067. var v2 = Tmp.Vector3[3];
  1068. x = 0.0;
  1069. y = 0.0;
  1070. z = 0.0;
  1071. sign = -1.0;
  1072. if (MathTools.WithinEpsilon(w.z, 0, BABYLON.Epsilon)) {
  1073. x = 1.0;
  1074. }
  1075. else {
  1076. t = u1.z / u1.x;
  1077. x = -t * Math.sqrt(1 / (1 + t * t));
  1078. z = Math.sqrt(1 / (1 + t * t));
  1079. }
  1080. w2.x = x;
  1081. w2.y = y;
  1082. w2.z = z;
  1083. w2.normalize();
  1084. Vector3.CrossToRef(w2, u1, v2); // v2 image of v1 through rotation around u1
  1085. v2.normalize();
  1086. Vector3.CrossToRef(w, w2, cross); // returns same direction as u1 (=local x) if positive angle : cross(source, image)
  1087. cross.normalize();
  1088. if (Vector3.Dot(u1, cross) < 0) {
  1089. sign = 1.0;
  1090. }
  1091. dot = Vector3.Dot(w, w2);
  1092. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  1093. pitch = Math.acos(dot) * sign;
  1094. if (Vector3.Dot(v2, Y) < 0) {
  1095. pitch = Math.PI + pitch;
  1096. nbRevert++;
  1097. }
  1098. // step 3 : rotate around v2
  1099. // Rv2(u1) = X, same as Rv2(w2) = Z, with X=(1,0,0) and Z=(0,0,1)
  1100. sign = -1.0;
  1101. Vector3.CrossToRef(X, u1, cross); // returns same direction as Y if positive angle : cross(source, image)
  1102. cross.normalize();
  1103. if (Vector3.Dot(cross, Y) < 0) {
  1104. sign = 1.0;
  1105. }
  1106. dot = Vector3.Dot(u1, X);
  1107. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  1108. yaw = -Math.acos(dot) * sign; // negative : plane zOx oriented clockwise
  1109. if (dot < 0 && nbRevert < 2) {
  1110. yaw = Math.PI + yaw;
  1111. }
  1112. ref.x = pitch;
  1113. ref.y = yaw;
  1114. ref.z = roll;
  1115. };
  1116. return Vector3;
  1117. })();
  1118. BABYLON.Vector3 = Vector3;
  1119. //Vector4 class created for EulerAngle class conversion to Quaternion
  1120. var Vector4 = (function () {
  1121. function Vector4(x, y, z, w) {
  1122. this.x = x;
  1123. this.y = y;
  1124. this.z = z;
  1125. this.w = w;
  1126. }
  1127. Vector4.prototype.toString = function () {
  1128. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "W:" + this.w + "}";
  1129. };
  1130. Vector4.prototype.getClassName = function () {
  1131. return "Vector4";
  1132. };
  1133. Vector4.prototype.getHashCode = function () {
  1134. var hash = this.x || 0;
  1135. hash = (hash * 397) ^ (this.y || 0);
  1136. hash = (hash * 397) ^ (this.z || 0);
  1137. hash = (hash * 397) ^ (this.w || 0);
  1138. return hash;
  1139. };
  1140. // Operators
  1141. Vector4.prototype.asArray = function () {
  1142. var result = [];
  1143. this.toArray(result, 0);
  1144. return result;
  1145. };
  1146. Vector4.prototype.toArray = function (array, index) {
  1147. if (index === undefined) {
  1148. index = 0;
  1149. }
  1150. array[index] = this.x;
  1151. array[index + 1] = this.y;
  1152. array[index + 2] = this.z;
  1153. array[index + 3] = this.w;
  1154. return this;
  1155. };
  1156. Vector4.prototype.addInPlace = function (otherVector) {
  1157. this.x += otherVector.x;
  1158. this.y += otherVector.y;
  1159. this.z += otherVector.z;
  1160. this.w += otherVector.w;
  1161. return this;
  1162. };
  1163. Vector4.prototype.add = function (otherVector) {
  1164. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  1165. };
  1166. Vector4.prototype.addToRef = function (otherVector, result) {
  1167. result.x = this.x + otherVector.x;
  1168. result.y = this.y + otherVector.y;
  1169. result.z = this.z + otherVector.z;
  1170. result.w = this.w + otherVector.w;
  1171. return this;
  1172. };
  1173. Vector4.prototype.subtractInPlace = function (otherVector) {
  1174. this.x -= otherVector.x;
  1175. this.y -= otherVector.y;
  1176. this.z -= otherVector.z;
  1177. this.w -= otherVector.w;
  1178. return this;
  1179. };
  1180. Vector4.prototype.subtract = function (otherVector) {
  1181. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  1182. };
  1183. Vector4.prototype.subtractToRef = function (otherVector, result) {
  1184. result.x = this.x - otherVector.x;
  1185. result.y = this.y - otherVector.y;
  1186. result.z = this.z - otherVector.z;
  1187. result.w = this.w - otherVector.w;
  1188. return this;
  1189. };
  1190. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  1191. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  1192. };
  1193. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  1194. result.x = this.x - x;
  1195. result.y = this.y - y;
  1196. result.z = this.z - z;
  1197. result.w = this.w - w;
  1198. return this;
  1199. };
  1200. Vector4.prototype.negate = function () {
  1201. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  1202. };
  1203. Vector4.prototype.scaleInPlace = function (scale) {
  1204. this.x *= scale;
  1205. this.y *= scale;
  1206. this.z *= scale;
  1207. this.w *= scale;
  1208. return this;
  1209. };
  1210. Vector4.prototype.scale = function (scale) {
  1211. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  1212. };
  1213. Vector4.prototype.scaleToRef = function (scale, result) {
  1214. result.x = this.x * scale;
  1215. result.y = this.y * scale;
  1216. result.z = this.z * scale;
  1217. result.w = this.w * scale;
  1218. };
  1219. Vector4.prototype.equals = function (otherVector) {
  1220. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  1221. };
  1222. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1223. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  1224. return otherVector
  1225. && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon)
  1226. && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon)
  1227. && MathTools.WithinEpsilon(this.z, otherVector.z, epsilon)
  1228. && MathTools.WithinEpsilon(this.w, otherVector.w, epsilon);
  1229. };
  1230. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  1231. return this.x === x && this.y === y && this.z === z && this.w === w;
  1232. };
  1233. Vector4.prototype.multiplyInPlace = function (otherVector) {
  1234. this.x *= otherVector.x;
  1235. this.y *= otherVector.y;
  1236. this.z *= otherVector.z;
  1237. this.w *= otherVector.w;
  1238. return this;
  1239. };
  1240. Vector4.prototype.multiply = function (otherVector) {
  1241. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  1242. };
  1243. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  1244. result.x = this.x * otherVector.x;
  1245. result.y = this.y * otherVector.y;
  1246. result.z = this.z * otherVector.z;
  1247. result.w = this.w * otherVector.w;
  1248. return this;
  1249. };
  1250. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  1251. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  1252. };
  1253. Vector4.prototype.divide = function (otherVector) {
  1254. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  1255. };
  1256. Vector4.prototype.divideToRef = function (otherVector, result) {
  1257. result.x = this.x / otherVector.x;
  1258. result.y = this.y / otherVector.y;
  1259. result.z = this.z / otherVector.z;
  1260. result.w = this.w / otherVector.w;
  1261. return this;
  1262. };
  1263. Vector4.prototype.MinimizeInPlace = function (other) {
  1264. if (other.x < this.x)
  1265. this.x = other.x;
  1266. if (other.y < this.y)
  1267. this.y = other.y;
  1268. if (other.z < this.z)
  1269. this.z = other.z;
  1270. if (other.w < this.w)
  1271. this.w = other.w;
  1272. return this;
  1273. };
  1274. Vector4.prototype.MaximizeInPlace = function (other) {
  1275. if (other.x > this.x)
  1276. this.x = other.x;
  1277. if (other.y > this.y)
  1278. this.y = other.y;
  1279. if (other.z > this.z)
  1280. this.z = other.z;
  1281. if (other.w > this.w)
  1282. this.w = other.w;
  1283. return this;
  1284. };
  1285. // Properties
  1286. Vector4.prototype.length = function () {
  1287. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1288. };
  1289. Vector4.prototype.lengthSquared = function () {
  1290. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1291. };
  1292. // Methods
  1293. Vector4.prototype.normalize = function () {
  1294. var len = this.length();
  1295. if (len === 0)
  1296. return this;
  1297. var num = 1.0 / len;
  1298. this.x *= num;
  1299. this.y *= num;
  1300. this.z *= num;
  1301. this.w *= num;
  1302. return this;
  1303. };
  1304. Vector4.prototype.toVector3 = function () {
  1305. return new Vector3(this.x, this.y, this.z);
  1306. };
  1307. Vector4.prototype.clone = function () {
  1308. return new Vector4(this.x, this.y, this.z, this.w);
  1309. };
  1310. Vector4.prototype.copyFrom = function (source) {
  1311. this.x = source.x;
  1312. this.y = source.y;
  1313. this.z = source.z;
  1314. this.w = source.w;
  1315. return this;
  1316. };
  1317. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  1318. this.x = x;
  1319. this.y = y;
  1320. this.z = z;
  1321. this.w = w;
  1322. return this;
  1323. };
  1324. // Statics
  1325. Vector4.FromArray = function (array, offset) {
  1326. if (!offset) {
  1327. offset = 0;
  1328. }
  1329. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1330. };
  1331. Vector4.FromArrayToRef = function (array, offset, result) {
  1332. result.x = array[offset];
  1333. result.y = array[offset + 1];
  1334. result.z = array[offset + 2];
  1335. result.w = array[offset + 3];
  1336. };
  1337. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  1338. result.x = array[offset];
  1339. result.y = array[offset + 1];
  1340. result.z = array[offset + 2];
  1341. result.w = array[offset + 3];
  1342. };
  1343. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  1344. result.x = x;
  1345. result.y = y;
  1346. result.z = z;
  1347. result.w = w;
  1348. };
  1349. Vector4.Zero = function () {
  1350. return new Vector4(0, 0, 0, 0);
  1351. };
  1352. Vector4.Normalize = function (vector) {
  1353. var result = Vector4.Zero();
  1354. Vector4.NormalizeToRef(vector, result);
  1355. return result;
  1356. };
  1357. Vector4.NormalizeToRef = function (vector, result) {
  1358. result.copyFrom(vector);
  1359. result.normalize();
  1360. };
  1361. Vector4.Minimize = function (left, right) {
  1362. var min = left.clone();
  1363. min.MinimizeInPlace(right);
  1364. return min;
  1365. };
  1366. Vector4.Maximize = function (left, right) {
  1367. var max = left.clone();
  1368. max.MaximizeInPlace(right);
  1369. return max;
  1370. };
  1371. Vector4.Distance = function (value1, value2) {
  1372. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  1373. };
  1374. Vector4.DistanceSquared = function (value1, value2) {
  1375. var x = value1.x - value2.x;
  1376. var y = value1.y - value2.y;
  1377. var z = value1.z - value2.z;
  1378. var w = value1.w - value2.w;
  1379. return (x * x) + (y * y) + (z * z) + (w * w);
  1380. };
  1381. Vector4.Center = function (value1, value2) {
  1382. var center = value1.add(value2);
  1383. center.scaleInPlace(0.5);
  1384. return center;
  1385. };
  1386. return Vector4;
  1387. })();
  1388. BABYLON.Vector4 = Vector4;
  1389. var Size = (function () {
  1390. function Size(width, height) {
  1391. this.width = width;
  1392. this.height = height;
  1393. }
  1394. Size.prototype.toString = function () {
  1395. return "{W: " + this.width + ", H: " + this.height + "}";
  1396. };
  1397. Size.prototype.getClassName = function () {
  1398. return "Size";
  1399. };
  1400. Size.prototype.getHashCode = function () {
  1401. var hash = this.width || 0;
  1402. hash = (hash * 397) ^ (this.height || 0);
  1403. return hash;
  1404. };
  1405. Size.prototype.copyFrom = function (src) {
  1406. this.width = src.width;
  1407. this.height = src.height;
  1408. };
  1409. Size.prototype.copyFromFloats = function (width, height) {
  1410. this.width = width;
  1411. this.height = height;
  1412. };
  1413. Size.prototype.multiplyByFloats = function (w, h) {
  1414. return new Size(this.width * w, this.height * h);
  1415. };
  1416. Size.prototype.clone = function () {
  1417. return new Size(this.width, this.height);
  1418. };
  1419. Size.prototype.equals = function (other) {
  1420. if (!other) {
  1421. return false;
  1422. }
  1423. return (this.width === other.width) && (this.height === other.height);
  1424. };
  1425. Object.defineProperty(Size.prototype, "surface", {
  1426. get: function () {
  1427. return this.width * this.height;
  1428. },
  1429. enumerable: true,
  1430. configurable: true
  1431. });
  1432. Size.Zero = function () {
  1433. return new Size(0, 0);
  1434. };
  1435. Size.prototype.add = function (otherSize) {
  1436. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  1437. return r;
  1438. };
  1439. Size.prototype.substract = function (otherSize) {
  1440. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  1441. return r;
  1442. };
  1443. Size.Lerp = function (start, end, amount) {
  1444. var w = start.width + ((end.width - start.width) * amount);
  1445. var h = start.height + ((end.height - start.height) * amount);
  1446. return new Size(w, h);
  1447. };
  1448. return Size;
  1449. })();
  1450. BABYLON.Size = Size;
  1451. var Quaternion = (function () {
  1452. function Quaternion(x, y, z, w) {
  1453. if (x === void 0) { x = 0; }
  1454. if (y === void 0) { y = 0; }
  1455. if (z === void 0) { z = 0; }
  1456. if (w === void 0) { w = 1; }
  1457. this.x = x;
  1458. this.y = y;
  1459. this.z = z;
  1460. this.w = w;
  1461. }
  1462. Quaternion.prototype.toString = function () {
  1463. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1464. };
  1465. Quaternion.prototype.getClassName = function () {
  1466. return "Quaternion";
  1467. };
  1468. Quaternion.prototype.getHashCode = function () {
  1469. var hash = this.x || 0;
  1470. hash = (hash * 397) ^ (this.y || 0);
  1471. hash = (hash * 397) ^ (this.z || 0);
  1472. hash = (hash * 397) ^ (this.w || 0);
  1473. return hash;
  1474. };
  1475. Quaternion.prototype.asArray = function () {
  1476. return [this.x, this.y, this.z, this.w];
  1477. };
  1478. Quaternion.prototype.equals = function (otherQuaternion) {
  1479. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  1480. };
  1481. Quaternion.prototype.clone = function () {
  1482. return new Quaternion(this.x, this.y, this.z, this.w);
  1483. };
  1484. Quaternion.prototype.copyFrom = function (other) {
  1485. this.x = other.x;
  1486. this.y = other.y;
  1487. this.z = other.z;
  1488. this.w = other.w;
  1489. return this;
  1490. };
  1491. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  1492. this.x = x;
  1493. this.y = y;
  1494. this.z = z;
  1495. this.w = w;
  1496. return this;
  1497. };
  1498. Quaternion.prototype.add = function (other) {
  1499. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  1500. };
  1501. Quaternion.prototype.subtract = function (other) {
  1502. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  1503. };
  1504. Quaternion.prototype.scale = function (value) {
  1505. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  1506. };
  1507. Quaternion.prototype.multiply = function (q1) {
  1508. var result = new Quaternion(0, 0, 0, 1.0);
  1509. this.multiplyToRef(q1, result);
  1510. return result;
  1511. };
  1512. Quaternion.prototype.multiplyToRef = function (q1, result) {
  1513. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  1514. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  1515. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  1516. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  1517. result.copyFromFloats(x, y, z, w);
  1518. return this;
  1519. };
  1520. Quaternion.prototype.multiplyInPlace = function (q1) {
  1521. this.multiplyToRef(q1, this);
  1522. return this;
  1523. };
  1524. Quaternion.prototype.conjugateToRef = function (ref) {
  1525. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  1526. return this;
  1527. };
  1528. Quaternion.prototype.conjugateInPlace = function () {
  1529. this.x *= -1;
  1530. this.y *= -1;
  1531. this.z *= -1;
  1532. return this;
  1533. };
  1534. Quaternion.prototype.conjugate = function () {
  1535. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  1536. return result;
  1537. };
  1538. Quaternion.prototype.length = function () {
  1539. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  1540. };
  1541. Quaternion.prototype.normalize = function () {
  1542. var length = 1.0 / this.length();
  1543. this.x *= length;
  1544. this.y *= length;
  1545. this.z *= length;
  1546. this.w *= length;
  1547. return this;
  1548. };
  1549. Quaternion.prototype.toEulerAngles = function (order) {
  1550. if (order === void 0) { order = "YZX"; }
  1551. var result = Vector3.Zero();
  1552. this.toEulerAnglesToRef(result, order);
  1553. return result;
  1554. };
  1555. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  1556. if (order === void 0) { order = "YZX"; }
  1557. var heading, attitude, bank;
  1558. var x = this.x, y = this.y, z = this.z, w = this.w;
  1559. switch (order) {
  1560. case "YZX":
  1561. var test = x * y + z * w;
  1562. if (test > 0.499) {
  1563. heading = 2 * Math.atan2(x, w);
  1564. attitude = Math.PI / 2;
  1565. bank = 0;
  1566. }
  1567. if (test < -0.499) {
  1568. heading = -2 * Math.atan2(x, w);
  1569. attitude = -Math.PI / 2;
  1570. bank = 0;
  1571. }
  1572. if (isNaN(heading)) {
  1573. var sqx = x * x;
  1574. var sqy = y * y;
  1575. var sqz = z * z;
  1576. heading = Math.atan2(2 * y * w - 2 * x * z, 1 - 2 * sqy - 2 * sqz); // Heading
  1577. attitude = Math.asin(2 * test); // attitude
  1578. bank = Math.atan2(2 * x * w - 2 * y * z, 1 - 2 * sqx - 2 * sqz); // bank
  1579. }
  1580. break;
  1581. default:
  1582. throw new Error("Euler order " + order + " not supported yet.");
  1583. }
  1584. result.y = heading;
  1585. result.z = attitude;
  1586. result.x = bank;
  1587. return this;
  1588. };
  1589. ;
  1590. Quaternion.prototype.toRotationMatrix = function (result) {
  1591. var xx = this.x * this.x;
  1592. var yy = this.y * this.y;
  1593. var zz = this.z * this.z;
  1594. var xy = this.x * this.y;
  1595. var zw = this.z * this.w;
  1596. var zx = this.z * this.x;
  1597. var yw = this.y * this.w;
  1598. var yz = this.y * this.z;
  1599. var xw = this.x * this.w;
  1600. result.m[0] = 1.0 - (2.0 * (yy + zz));
  1601. result.m[1] = 2.0 * (xy + zw);
  1602. result.m[2] = 2.0 * (zx - yw);
  1603. result.m[3] = 0;
  1604. result.m[4] = 2.0 * (xy - zw);
  1605. result.m[5] = 1.0 - (2.0 * (zz + xx));
  1606. result.m[6] = 2.0 * (yz + xw);
  1607. result.m[7] = 0;
  1608. result.m[8] = 2.0 * (zx + yw);
  1609. result.m[9] = 2.0 * (yz - xw);
  1610. result.m[10] = 1.0 - (2.0 * (yy + xx));
  1611. result.m[11] = 0;
  1612. result.m[12] = 0;
  1613. result.m[13] = 0;
  1614. result.m[14] = 0;
  1615. result.m[15] = 1.0;
  1616. return this;
  1617. };
  1618. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  1619. Quaternion.FromRotationMatrixToRef(matrix, this);
  1620. return this;
  1621. };
  1622. // Statics
  1623. Quaternion.FromRotationMatrix = function (matrix) {
  1624. var result = new Quaternion();
  1625. Quaternion.FromRotationMatrixToRef(matrix, result);
  1626. return result;
  1627. };
  1628. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  1629. var data = matrix.m;
  1630. var m11 = data[0], m12 = data[4], m13 = data[8];
  1631. var m21 = data[1], m22 = data[5], m23 = data[9];
  1632. var m31 = data[2], m32 = data[6], m33 = data[10];
  1633. var trace = m11 + m22 + m33;
  1634. var s;
  1635. if (trace > 0) {
  1636. s = 0.5 / Math.sqrt(trace + 1.0);
  1637. result.w = 0.25 / s;
  1638. result.x = (m32 - m23) * s;
  1639. result.y = (m13 - m31) * s;
  1640. result.z = (m21 - m12) * s;
  1641. }
  1642. else if (m11 > m22 && m11 > m33) {
  1643. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  1644. result.w = (m32 - m23) / s;
  1645. result.x = 0.25 * s;
  1646. result.y = (m12 + m21) / s;
  1647. result.z = (m13 + m31) / s;
  1648. }
  1649. else if (m22 > m33) {
  1650. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  1651. result.w = (m13 - m31) / s;
  1652. result.x = (m12 + m21) / s;
  1653. result.y = 0.25 * s;
  1654. result.z = (m23 + m32) / s;
  1655. }
  1656. else {
  1657. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  1658. result.w = (m21 - m12) / s;
  1659. result.x = (m13 + m31) / s;
  1660. result.y = (m23 + m32) / s;
  1661. result.z = 0.25 * s;
  1662. }
  1663. };
  1664. Quaternion.Inverse = function (q) {
  1665. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  1666. };
  1667. Quaternion.Identity = function () {
  1668. return new Quaternion(0, 0, 0, 1);
  1669. };
  1670. Quaternion.RotationAxis = function (axis, angle) {
  1671. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  1672. };
  1673. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  1674. var sin = Math.sin(angle / 2);
  1675. axis.normalize();
  1676. result.w = Math.cos(angle / 2);
  1677. result.x = axis.x * sin;
  1678. result.y = axis.y * sin;
  1679. result.z = axis.z * sin;
  1680. return result;
  1681. };
  1682. Quaternion.FromArray = function (array, offset) {
  1683. if (!offset) {
  1684. offset = 0;
  1685. }
  1686. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1687. };
  1688. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1689. var q = new Quaternion();
  1690. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  1691. return q;
  1692. };
  1693. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1694. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  1695. var halfRoll = roll * 0.5;
  1696. var halfPitch = pitch * 0.5;
  1697. var halfYaw = yaw * 0.5;
  1698. var sinRoll = Math.sin(halfRoll);
  1699. var cosRoll = Math.cos(halfRoll);
  1700. var sinPitch = Math.sin(halfPitch);
  1701. var cosPitch = Math.cos(halfPitch);
  1702. var sinYaw = Math.sin(halfYaw);
  1703. var cosYaw = Math.cos(halfYaw);
  1704. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  1705. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  1706. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  1707. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  1708. };
  1709. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  1710. var result = new Quaternion();
  1711. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  1712. return result;
  1713. };
  1714. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  1715. // Produces a quaternion from Euler angles in the z-x-z orientation
  1716. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  1717. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  1718. var halfBeta = beta * 0.5;
  1719. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1720. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1721. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1722. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1723. };
  1724. Quaternion.Slerp = function (left, right, amount) {
  1725. var num2;
  1726. var num3;
  1727. var num = amount;
  1728. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  1729. var flag = false;
  1730. if (num4 < 0) {
  1731. flag = true;
  1732. num4 = -num4;
  1733. }
  1734. if (num4 > 0.999999) {
  1735. num3 = 1 - num;
  1736. num2 = flag ? -num : num;
  1737. }
  1738. else {
  1739. var num5 = Math.acos(num4);
  1740. var num6 = (1.0 / Math.sin(num5));
  1741. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  1742. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  1743. }
  1744. return new Quaternion((num3 * left.x) + (num2 * right.x), (num3 * left.y) + (num2 * right.y), (num3 * left.z) + (num2 * right.z), (num3 * left.w) + (num2 * right.w));
  1745. };
  1746. return Quaternion;
  1747. })();
  1748. BABYLON.Quaternion = Quaternion;
  1749. var Matrix = (function () {
  1750. function Matrix() {
  1751. this.m = new Float32Array(16);
  1752. }
  1753. // Properties
  1754. Matrix.prototype.isIdentity = function () {
  1755. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[10] !== 1.0 || this.m[15] !== 1.0)
  1756. return false;
  1757. if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  1758. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  1759. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  1760. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0)
  1761. return false;
  1762. return true;
  1763. };
  1764. Matrix.prototype.determinant = function () {
  1765. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  1766. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  1767. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  1768. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  1769. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  1770. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  1771. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  1772. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  1773. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  1774. };
  1775. // Methods
  1776. Matrix.prototype.toArray = function () {
  1777. return this.m;
  1778. };
  1779. Matrix.prototype.asArray = function () {
  1780. return this.toArray();
  1781. };
  1782. Matrix.prototype.invert = function () {
  1783. this.invertToRef(this);
  1784. return this;
  1785. };
  1786. Matrix.prototype.reset = function () {
  1787. for (var index = 0; index < 16; index++) {
  1788. this.m[index] = 0;
  1789. }
  1790. return this;
  1791. };
  1792. Matrix.prototype.add = function (other) {
  1793. var result = new Matrix();
  1794. this.addToRef(other, result);
  1795. return result;
  1796. };
  1797. Matrix.prototype.addToRef = function (other, result) {
  1798. for (var index = 0; index < 16; index++) {
  1799. result.m[index] = this.m[index] + other.m[index];
  1800. }
  1801. return this;
  1802. };
  1803. Matrix.prototype.addToSelf = function (other) {
  1804. for (var index = 0; index < 16; index++) {
  1805. this.m[index] += other.m[index];
  1806. }
  1807. return this;
  1808. };
  1809. Matrix.prototype.invertToRef = function (other) {
  1810. var l1 = this.m[0];
  1811. var l2 = this.m[1];
  1812. var l3 = this.m[2];
  1813. var l4 = this.m[3];
  1814. var l5 = this.m[4];
  1815. var l6 = this.m[5];
  1816. var l7 = this.m[6];
  1817. var l8 = this.m[7];
  1818. var l9 = this.m[8];
  1819. var l10 = this.m[9];
  1820. var l11 = this.m[10];
  1821. var l12 = this.m[11];
  1822. var l13 = this.m[12];
  1823. var l14 = this.m[13];
  1824. var l15 = this.m[14];
  1825. var l16 = this.m[15];
  1826. var l17 = (l11 * l16) - (l12 * l15);
  1827. var l18 = (l10 * l16) - (l12 * l14);
  1828. var l19 = (l10 * l15) - (l11 * l14);
  1829. var l20 = (l9 * l16) - (l12 * l13);
  1830. var l21 = (l9 * l15) - (l11 * l13);
  1831. var l22 = (l9 * l14) - (l10 * l13);
  1832. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  1833. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  1834. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  1835. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  1836. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  1837. var l28 = (l7 * l16) - (l8 * l15);
  1838. var l29 = (l6 * l16) - (l8 * l14);
  1839. var l30 = (l6 * l15) - (l7 * l14);
  1840. var l31 = (l5 * l16) - (l8 * l13);
  1841. var l32 = (l5 * l15) - (l7 * l13);
  1842. var l33 = (l5 * l14) - (l6 * l13);
  1843. var l34 = (l7 * l12) - (l8 * l11);
  1844. var l35 = (l6 * l12) - (l8 * l10);
  1845. var l36 = (l6 * l11) - (l7 * l10);
  1846. var l37 = (l5 * l12) - (l8 * l9);
  1847. var l38 = (l5 * l11) - (l7 * l9);
  1848. var l39 = (l5 * l10) - (l6 * l9);
  1849. other.m[0] = l23 * l27;
  1850. other.m[4] = l24 * l27;
  1851. other.m[8] = l25 * l27;
  1852. other.m[12] = l26 * l27;
  1853. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  1854. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  1855. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  1856. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  1857. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  1858. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  1859. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  1860. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  1861. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  1862. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  1863. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  1864. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  1865. return this;
  1866. };
  1867. Matrix.prototype.setTranslation = function (vector3) {
  1868. this.m[12] = vector3.x;
  1869. this.m[13] = vector3.y;
  1870. this.m[14] = vector3.z;
  1871. return this;
  1872. };
  1873. Matrix.prototype.getTranslation = function () {
  1874. return new Vector3(this.m[12], this.m[13], this.m[14]);
  1875. };
  1876. Matrix.prototype.multiply = function (other) {
  1877. var result = new Matrix();
  1878. this.multiplyToRef(other, result);
  1879. return result;
  1880. };
  1881. Matrix.prototype.copyFrom = function (other) {
  1882. for (var index = 0; index < 16; index++) {
  1883. this.m[index] = other.m[index];
  1884. }
  1885. return this;
  1886. };
  1887. Matrix.prototype.copyToArray = function (array, offset) {
  1888. if (offset === void 0) { offset = 0; }
  1889. for (var index = 0; index < 16; index++) {
  1890. array[offset + index] = this.m[index];
  1891. }
  1892. return this;
  1893. };
  1894. Matrix.prototype.multiplyToRef = function (other, result) {
  1895. this.multiplyToArray(other, result.m, 0);
  1896. return this;
  1897. };
  1898. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  1899. var tm0 = this.m[0];
  1900. var tm1 = this.m[1];
  1901. var tm2 = this.m[2];
  1902. var tm3 = this.m[3];
  1903. var tm4 = this.m[4];
  1904. var tm5 = this.m[5];
  1905. var tm6 = this.m[6];
  1906. var tm7 = this.m[7];
  1907. var tm8 = this.m[8];
  1908. var tm9 = this.m[9];
  1909. var tm10 = this.m[10];
  1910. var tm11 = this.m[11];
  1911. var tm12 = this.m[12];
  1912. var tm13 = this.m[13];
  1913. var tm14 = this.m[14];
  1914. var tm15 = this.m[15];
  1915. var om0 = other.m[0];
  1916. var om1 = other.m[1];
  1917. var om2 = other.m[2];
  1918. var om3 = other.m[3];
  1919. var om4 = other.m[4];
  1920. var om5 = other.m[5];
  1921. var om6 = other.m[6];
  1922. var om7 = other.m[7];
  1923. var om8 = other.m[8];
  1924. var om9 = other.m[9];
  1925. var om10 = other.m[10];
  1926. var om11 = other.m[11];
  1927. var om12 = other.m[12];
  1928. var om13 = other.m[13];
  1929. var om14 = other.m[14];
  1930. var om15 = other.m[15];
  1931. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  1932. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  1933. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  1934. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  1935. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  1936. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  1937. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  1938. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  1939. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  1940. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  1941. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  1942. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  1943. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  1944. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  1945. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  1946. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  1947. return this;
  1948. };
  1949. Matrix.prototype.equals = function (value) {
  1950. return value &&
  1951. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  1952. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  1953. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  1954. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  1955. };
  1956. Matrix.prototype.clone = function () {
  1957. return Matrix.FromValues(this.m[0], this.m[1], this.m[2], this.m[3], this.m[4], this.m[5], this.m[6], this.m[7], this.m[8], this.m[9], this.m[10], this.m[11], this.m[12], this.m[13], this.m[14], this.m[15]);
  1958. };
  1959. Matrix.prototype.getClassName = function () {
  1960. return "Matrix";
  1961. };
  1962. Matrix.prototype.getHashCode = function () {
  1963. var hash = this.m[0] || 0;
  1964. for (var i = 1; i < 16; i++) {
  1965. hash = (hash * 397) ^ (this.m[i] || 0);
  1966. }
  1967. return hash;
  1968. };
  1969. Matrix.prototype.decompose = function (scale, rotation, translation) {
  1970. translation.x = this.m[12];
  1971. translation.y = this.m[13];
  1972. translation.z = this.m[14];
  1973. var xs = MathTools.Sign(this.m[0] * this.m[1] * this.m[2] * this.m[3]) < 0 ? -1 : 1;
  1974. var ys = MathTools.Sign(this.m[4] * this.m[5] * this.m[6] * this.m[7]) < 0 ? -1 : 1;
  1975. var zs = MathTools.Sign(this.m[8] * this.m[9] * this.m[10] * this.m[11]) < 0 ? -1 : 1;
  1976. scale.x = xs * Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  1977. scale.y = ys * Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  1978. scale.z = zs * Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  1979. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  1980. rotation.x = 0;
  1981. rotation.y = 0;
  1982. rotation.z = 0;
  1983. rotation.w = 1;
  1984. return false;
  1985. }
  1986. var rotationMatrix = Matrix.FromValues(this.m[0] / scale.x, this.m[1] / scale.x, this.m[2] / scale.x, 0, this.m[4] / scale.y, this.m[5] / scale.y, this.m[6] / scale.y, 0, this.m[8] / scale.z, this.m[9] / scale.z, this.m[10] / scale.z, 0, 0, 0, 0, 1);
  1987. Quaternion.FromRotationMatrixToRef(rotationMatrix, rotation);
  1988. return true;
  1989. };
  1990. // Statics
  1991. Matrix.FromArray = function (array, offset) {
  1992. var result = new Matrix();
  1993. if (!offset) {
  1994. offset = 0;
  1995. }
  1996. Matrix.FromArrayToRef(array, offset, result);
  1997. return result;
  1998. };
  1999. Matrix.FromArrayToRef = function (array, offset, result) {
  2000. for (var index = 0; index < 16; index++) {
  2001. result.m[index] = array[index + offset];
  2002. }
  2003. };
  2004. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  2005. for (var index = 0; index < 16; index++) {
  2006. result.m[index] = array[index + offset] * scale;
  2007. }
  2008. };
  2009. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  2010. result.m[0] = initialM11;
  2011. result.m[1] = initialM12;
  2012. result.m[2] = initialM13;
  2013. result.m[3] = initialM14;
  2014. result.m[4] = initialM21;
  2015. result.m[5] = initialM22;
  2016. result.m[6] = initialM23;
  2017. result.m[7] = initialM24;
  2018. result.m[8] = initialM31;
  2019. result.m[9] = initialM32;
  2020. result.m[10] = initialM33;
  2021. result.m[11] = initialM34;
  2022. result.m[12] = initialM41;
  2023. result.m[13] = initialM42;
  2024. result.m[14] = initialM43;
  2025. result.m[15] = initialM44;
  2026. };
  2027. Matrix.prototype.getRow = function (index) {
  2028. if (index < 0 || index > 3) {
  2029. return null;
  2030. }
  2031. var i = index * 4;
  2032. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  2033. };
  2034. Matrix.prototype.setRow = function (index, row) {
  2035. if (index < 0 || index > 3) {
  2036. return this;
  2037. }
  2038. var i = index * 4;
  2039. this.m[i + 0] = row.x;
  2040. this.m[i + 1] = row.y;
  2041. this.m[i + 2] = row.z;
  2042. this.m[i + 3] = row.w;
  2043. return this;
  2044. };
  2045. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  2046. var result = new Matrix();
  2047. result.m[0] = initialM11;
  2048. result.m[1] = initialM12;
  2049. result.m[2] = initialM13;
  2050. result.m[3] = initialM14;
  2051. result.m[4] = initialM21;
  2052. result.m[5] = initialM22;
  2053. result.m[6] = initialM23;
  2054. result.m[7] = initialM24;
  2055. result.m[8] = initialM31;
  2056. result.m[9] = initialM32;
  2057. result.m[10] = initialM33;
  2058. result.m[11] = initialM34;
  2059. result.m[12] = initialM41;
  2060. result.m[13] = initialM42;
  2061. result.m[14] = initialM43;
  2062. result.m[15] = initialM44;
  2063. return result;
  2064. };
  2065. Matrix.Compose = function (scale, rotation, translation) {
  2066. var result = Matrix.FromValues(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1);
  2067. var rotationMatrix = Matrix.Identity();
  2068. rotation.toRotationMatrix(rotationMatrix);
  2069. result = result.multiply(rotationMatrix);
  2070. result.setTranslation(translation);
  2071. return result;
  2072. };
  2073. Matrix.Identity = function () {
  2074. return Matrix.FromValues(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0);
  2075. };
  2076. Matrix.IdentityToRef = function (result) {
  2077. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, result);
  2078. };
  2079. Matrix.Zero = function () {
  2080. return Matrix.FromValues(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  2081. };
  2082. Matrix.RotationX = function (angle) {
  2083. var result = new Matrix();
  2084. Matrix.RotationXToRef(angle, result);
  2085. return result;
  2086. };
  2087. Matrix.Invert = function (source) {
  2088. var result = new Matrix();
  2089. source.invertToRef(result);
  2090. return result;
  2091. };
  2092. Matrix.RotationXToRef = function (angle, result) {
  2093. var s = Math.sin(angle);
  2094. var c = Math.cos(angle);
  2095. result.m[0] = 1.0;
  2096. result.m[15] = 1.0;
  2097. result.m[5] = c;
  2098. result.m[10] = c;
  2099. result.m[9] = -s;
  2100. result.m[6] = s;
  2101. result.m[1] = 0;
  2102. result.m[2] = 0;
  2103. result.m[3] = 0;
  2104. result.m[4] = 0;
  2105. result.m[7] = 0;
  2106. result.m[8] = 0;
  2107. result.m[11] = 0;
  2108. result.m[12] = 0;
  2109. result.m[13] = 0;
  2110. result.m[14] = 0;
  2111. };
  2112. Matrix.RotationY = function (angle) {
  2113. var result = new Matrix();
  2114. Matrix.RotationYToRef(angle, result);
  2115. return result;
  2116. };
  2117. Matrix.RotationYToRef = function (angle, result) {
  2118. var s = Math.sin(angle);
  2119. var c = Math.cos(angle);
  2120. result.m[5] = 1.0;
  2121. result.m[15] = 1.0;
  2122. result.m[0] = c;
  2123. result.m[2] = -s;
  2124. result.m[8] = s;
  2125. result.m[10] = c;
  2126. result.m[1] = 0;
  2127. result.m[3] = 0;
  2128. result.m[4] = 0;
  2129. result.m[6] = 0;
  2130. result.m[7] = 0;
  2131. result.m[9] = 0;
  2132. result.m[11] = 0;
  2133. result.m[12] = 0;
  2134. result.m[13] = 0;
  2135. result.m[14] = 0;
  2136. };
  2137. Matrix.RotationZ = function (angle) {
  2138. var result = new Matrix();
  2139. Matrix.RotationZToRef(angle, result);
  2140. return result;
  2141. };
  2142. Matrix.RotationZToRef = function (angle, result) {
  2143. var s = Math.sin(angle);
  2144. var c = Math.cos(angle);
  2145. result.m[10] = 1.0;
  2146. result.m[15] = 1.0;
  2147. result.m[0] = c;
  2148. result.m[1] = s;
  2149. result.m[4] = -s;
  2150. result.m[5] = c;
  2151. result.m[2] = 0;
  2152. result.m[3] = 0;
  2153. result.m[6] = 0;
  2154. result.m[7] = 0;
  2155. result.m[8] = 0;
  2156. result.m[9] = 0;
  2157. result.m[11] = 0;
  2158. result.m[12] = 0;
  2159. result.m[13] = 0;
  2160. result.m[14] = 0;
  2161. };
  2162. Matrix.RotationAxis = function (axis, angle) {
  2163. var result = Matrix.Zero();
  2164. Matrix.RotationAxisToRef(axis, angle, result);
  2165. return result;
  2166. };
  2167. Matrix.RotationAxisToRef = function (axis, angle, result) {
  2168. var s = Math.sin(-angle);
  2169. var c = Math.cos(-angle);
  2170. var c1 = 1 - c;
  2171. axis.normalize();
  2172. result.m[0] = (axis.x * axis.x) * c1 + c;
  2173. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  2174. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  2175. result.m[3] = 0.0;
  2176. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  2177. result.m[5] = (axis.y * axis.y) * c1 + c;
  2178. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  2179. result.m[7] = 0.0;
  2180. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  2181. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  2182. result.m[10] = (axis.z * axis.z) * c1 + c;
  2183. result.m[11] = 0.0;
  2184. result.m[15] = 1.0;
  2185. };
  2186. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  2187. var result = new Matrix();
  2188. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  2189. return result;
  2190. };
  2191. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  2192. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  2193. this._tempQuaternion.toRotationMatrix(result);
  2194. };
  2195. Matrix.Scaling = function (x, y, z) {
  2196. var result = Matrix.Zero();
  2197. Matrix.ScalingToRef(x, y, z, result);
  2198. return result;
  2199. };
  2200. Matrix.ScalingToRef = function (x, y, z, result) {
  2201. result.m[0] = x;
  2202. result.m[1] = 0;
  2203. result.m[2] = 0;
  2204. result.m[3] = 0;
  2205. result.m[4] = 0;
  2206. result.m[5] = y;
  2207. result.m[6] = 0;
  2208. result.m[7] = 0;
  2209. result.m[8] = 0;
  2210. result.m[9] = 0;
  2211. result.m[10] = z;
  2212. result.m[11] = 0;
  2213. result.m[12] = 0;
  2214. result.m[13] = 0;
  2215. result.m[14] = 0;
  2216. result.m[15] = 1.0;
  2217. };
  2218. Matrix.Translation = function (x, y, z) {
  2219. var result = Matrix.Identity();
  2220. Matrix.TranslationToRef(x, y, z, result);
  2221. return result;
  2222. };
  2223. Matrix.TranslationToRef = function (x, y, z, result) {
  2224. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, x, y, z, 1.0, result);
  2225. };
  2226. Matrix.Lerp = function (startValue, endValue, gradient) {
  2227. var result = Matrix.Zero();
  2228. for (var index = 0; index < 16; index++) {
  2229. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  2230. }
  2231. return result;
  2232. };
  2233. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  2234. var startScale = new Vector3(0, 0, 0);
  2235. var startRotation = new Quaternion();
  2236. var startTranslation = new Vector3(0, 0, 0);
  2237. startValue.decompose(startScale, startRotation, startTranslation);
  2238. var endScale = new Vector3(0, 0, 0);
  2239. var endRotation = new Quaternion();
  2240. var endTranslation = new Vector3(0, 0, 0);
  2241. endValue.decompose(endScale, endRotation, endTranslation);
  2242. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  2243. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  2244. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  2245. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  2246. };
  2247. Matrix.LookAtLH = function (eye, target, up) {
  2248. var result = Matrix.Zero();
  2249. Matrix.LookAtLHToRef(eye, target, up, result);
  2250. return result;
  2251. };
  2252. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  2253. // Z axis
  2254. target.subtractToRef(eye, this._zAxis);
  2255. this._zAxis.normalize();
  2256. // X axis
  2257. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  2258. if (this._xAxis.lengthSquared() === 0) {
  2259. this._xAxis.x = 1.0;
  2260. }
  2261. else {
  2262. this._xAxis.normalize();
  2263. }
  2264. // Y axis
  2265. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  2266. this._yAxis.normalize();
  2267. // Eye angles
  2268. var ex = -Vector3.Dot(this._xAxis, eye);
  2269. var ey = -Vector3.Dot(this._yAxis, eye);
  2270. var ez = -Vector3.Dot(this._zAxis, eye);
  2271. return Matrix.FromValuesToRef(this._xAxis.x, this._yAxis.x, this._zAxis.x, 0, this._xAxis.y, this._yAxis.y, this._zAxis.y, 0, this._xAxis.z, this._yAxis.z, this._zAxis.z, 0, ex, ey, ez, 1, result);
  2272. };
  2273. Matrix.OrthoLH = function (width, height, znear, zfar) {
  2274. var matrix = Matrix.Zero();
  2275. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  2276. return matrix;
  2277. };
  2278. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  2279. var hw = 2.0 / width;
  2280. var hh = 2.0 / height;
  2281. var id = 1.0 / (zfar - znear);
  2282. var nid = znear / (znear - zfar);
  2283. Matrix.FromValuesToRef(hw, 0, 0, 0, 0, hh, 0, 0, 0, 0, id, 0, 0, 0, nid, 1, result);
  2284. };
  2285. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  2286. var matrix = Matrix.Zero();
  2287. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  2288. return matrix;
  2289. };
  2290. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  2291. result.m[0] = 2.0 / (right - left);
  2292. result.m[1] = result.m[2] = result.m[3] = 0;
  2293. result.m[5] = 2.0 / (top - bottom);
  2294. result.m[4] = result.m[6] = result.m[7] = 0;
  2295. result.m[10] = -1.0 / (znear - zfar);
  2296. result.m[8] = result.m[9] = result.m[11] = 0;
  2297. result.m[12] = (left + right) / (left - right);
  2298. result.m[13] = (top + bottom) / (bottom - top);
  2299. result.m[14] = znear / (znear - zfar);
  2300. result.m[15] = 1.0;
  2301. };
  2302. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  2303. var matrix = Matrix.Zero();
  2304. matrix.m[0] = (2.0 * znear) / width;
  2305. matrix.m[1] = matrix.m[2] = matrix.m[3] = 0.0;
  2306. matrix.m[5] = (2.0 * znear) / height;
  2307. matrix.m[4] = matrix.m[6] = matrix.m[7] = 0.0;
  2308. matrix.m[10] = -zfar / (znear - zfar);
  2309. matrix.m[8] = matrix.m[9] = 0.0;
  2310. matrix.m[11] = 1.0;
  2311. matrix.m[12] = matrix.m[13] = matrix.m[15] = 0.0;
  2312. matrix.m[14] = (znear * zfar) / (znear - zfar);
  2313. return matrix;
  2314. };
  2315. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  2316. var matrix = Matrix.Zero();
  2317. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  2318. return matrix;
  2319. };
  2320. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  2321. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  2322. var tan = 1.0 / (Math.tan(fov * 0.5));
  2323. if (isVerticalFovFixed) {
  2324. result.m[0] = tan / aspect;
  2325. }
  2326. else {
  2327. result.m[0] = tan;
  2328. }
  2329. result.m[1] = result.m[2] = result.m[3] = 0.0;
  2330. if (isVerticalFovFixed) {
  2331. result.m[5] = tan;
  2332. }
  2333. else {
  2334. result.m[5] = tan * aspect;
  2335. }
  2336. result.m[4] = result.m[6] = result.m[7] = 0.0;
  2337. result.m[8] = result.m[9] = 0.0;
  2338. result.m[10] = -zfar / (znear - zfar);
  2339. result.m[11] = 1.0;
  2340. result.m[12] = result.m[13] = result.m[15] = 0.0;
  2341. result.m[14] = (znear * zfar) / (znear - zfar);
  2342. };
  2343. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  2344. var cw = viewport.width;
  2345. var ch = viewport.height;
  2346. var cx = viewport.x;
  2347. var cy = viewport.y;
  2348. var viewportMatrix = Matrix.FromValues(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, zmax - zmin, 0, cx + cw / 2.0, ch / 2.0 + cy, zmin, 1);
  2349. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  2350. };
  2351. Matrix.GetAsMatrix2x2 = function (matrix) {
  2352. return new Float32Array([
  2353. matrix.m[0], matrix.m[1],
  2354. matrix.m[4], matrix.m[5]
  2355. ]);
  2356. };
  2357. Matrix.GetAsMatrix3x3 = function (matrix) {
  2358. return new Float32Array([
  2359. matrix.m[0], matrix.m[1], matrix.m[2],
  2360. matrix.m[4], matrix.m[5], matrix.m[6],
  2361. matrix.m[8], matrix.m[9], matrix.m[10]
  2362. ]);
  2363. };
  2364. Matrix.Transpose = function (matrix) {
  2365. var result = new Matrix();
  2366. result.m[0] = matrix.m[0];
  2367. result.m[1] = matrix.m[4];
  2368. result.m[2] = matrix.m[8];
  2369. result.m[3] = matrix.m[12];
  2370. result.m[4] = matrix.m[1];
  2371. result.m[5] = matrix.m[5];
  2372. result.m[6] = matrix.m[9];
  2373. result.m[7] = matrix.m[13];
  2374. result.m[8] = matrix.m[2];
  2375. result.m[9] = matrix.m[6];
  2376. result.m[10] = matrix.m[10];
  2377. result.m[11] = matrix.m[14];
  2378. result.m[12] = matrix.m[3];
  2379. result.m[13] = matrix.m[7];
  2380. result.m[14] = matrix.m[11];
  2381. result.m[15] = matrix.m[15];
  2382. return result;
  2383. };
  2384. Matrix.Reflection = function (plane) {
  2385. var matrix = new Matrix();
  2386. Matrix.ReflectionToRef(plane, matrix);
  2387. return matrix;
  2388. };
  2389. Matrix.ReflectionToRef = function (plane, result) {
  2390. plane.normalize();
  2391. var x = plane.normal.x;
  2392. var y = plane.normal.y;
  2393. var z = plane.normal.z;
  2394. var temp = -2 * x;
  2395. var temp2 = -2 * y;
  2396. var temp3 = -2 * z;
  2397. result.m[0] = (temp * x) + 1;
  2398. result.m[1] = temp2 * x;
  2399. result.m[2] = temp3 * x;
  2400. result.m[3] = 0.0;
  2401. result.m[4] = temp * y;
  2402. result.m[5] = (temp2 * y) + 1;
  2403. result.m[6] = temp3 * y;
  2404. result.m[7] = 0.0;
  2405. result.m[8] = temp * z;
  2406. result.m[9] = temp2 * z;
  2407. result.m[10] = (temp3 * z) + 1;
  2408. result.m[11] = 0.0;
  2409. result.m[12] = temp * plane.d;
  2410. result.m[13] = temp2 * plane.d;
  2411. result.m[14] = temp3 * plane.d;
  2412. result.m[15] = 1.0;
  2413. };
  2414. Matrix._tempQuaternion = new Quaternion();
  2415. Matrix._xAxis = Vector3.Zero();
  2416. Matrix._yAxis = Vector3.Zero();
  2417. Matrix._zAxis = Vector3.Zero();
  2418. return Matrix;
  2419. })();
  2420. BABYLON.Matrix = Matrix;
  2421. var Plane = (function () {
  2422. function Plane(a, b, c, d) {
  2423. this.normal = new Vector3(a, b, c);
  2424. this.d = d;
  2425. }
  2426. Plane.prototype.asArray = function () {
  2427. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  2428. };
  2429. // Methods
  2430. Plane.prototype.clone = function () {
  2431. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  2432. };
  2433. Plane.prototype.getClassName = function () {
  2434. return "Plane";
  2435. };
  2436. Plane.prototype.getHashCode = function () {
  2437. var hash = this.normal.getHashCode();
  2438. hash = (hash * 397) ^ (this.d || 0);
  2439. return hash;
  2440. };
  2441. Plane.prototype.normalize = function () {
  2442. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  2443. var magnitude = 0;
  2444. if (norm !== 0) {
  2445. magnitude = 1.0 / norm;
  2446. }
  2447. this.normal.x *= magnitude;
  2448. this.normal.y *= magnitude;
  2449. this.normal.z *= magnitude;
  2450. this.d *= magnitude;
  2451. return this;
  2452. };
  2453. Plane.prototype.transform = function (transformation) {
  2454. var transposedMatrix = Matrix.Transpose(transformation);
  2455. var x = this.normal.x;
  2456. var y = this.normal.y;
  2457. var z = this.normal.z;
  2458. var d = this.d;
  2459. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  2460. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  2461. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  2462. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  2463. return new Plane(normalX, normalY, normalZ, finalD);
  2464. };
  2465. Plane.prototype.dotCoordinate = function (point) {
  2466. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  2467. };
  2468. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  2469. var x1 = point2.x - point1.x;
  2470. var y1 = point2.y - point1.y;
  2471. var z1 = point2.z - point1.z;
  2472. var x2 = point3.x - point1.x;
  2473. var y2 = point3.y - point1.y;
  2474. var z2 = point3.z - point1.z;
  2475. var yz = (y1 * z2) - (z1 * y2);
  2476. var xz = (z1 * x2) - (x1 * z2);
  2477. var xy = (x1 * y2) - (y1 * x2);
  2478. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  2479. var invPyth;
  2480. if (pyth !== 0) {
  2481. invPyth = 1.0 / pyth;
  2482. }
  2483. else {
  2484. invPyth = 0;
  2485. }
  2486. this.normal.x = yz * invPyth;
  2487. this.normal.y = xz * invPyth;
  2488. this.normal.z = xy * invPyth;
  2489. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  2490. return this;
  2491. };
  2492. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  2493. var dot = Vector3.Dot(this.normal, direction);
  2494. return (dot <= epsilon);
  2495. };
  2496. Plane.prototype.signedDistanceTo = function (point) {
  2497. return Vector3.Dot(point, this.normal) + this.d;
  2498. };
  2499. // Statics
  2500. Plane.FromArray = function (array) {
  2501. return new Plane(array[0], array[1], array[2], array[3]);
  2502. };
  2503. Plane.FromPoints = function (point1, point2, point3) {
  2504. var result = new Plane(0, 0, 0, 0);
  2505. result.copyFromPoints(point1, point2, point3);
  2506. return result;
  2507. };
  2508. Plane.FromPositionAndNormal = function (origin, normal) {
  2509. var result = new Plane(0, 0, 0, 0);
  2510. normal.normalize();
  2511. result.normal = normal;
  2512. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2513. return result;
  2514. };
  2515. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  2516. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2517. return Vector3.Dot(point, normal) + d;
  2518. };
  2519. return Plane;
  2520. })();
  2521. BABYLON.Plane = Plane;
  2522. var Viewport = (function () {
  2523. function Viewport(x, y, width, height) {
  2524. this.x = x;
  2525. this.y = y;
  2526. this.width = width;
  2527. this.height = height;
  2528. }
  2529. Viewport.prototype.toGlobal = function (renderWidth, renderHeight) {
  2530. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  2531. };
  2532. return Viewport;
  2533. })();
  2534. BABYLON.Viewport = Viewport;
  2535. var Frustum = (function () {
  2536. function Frustum() {
  2537. }
  2538. Frustum.GetPlanes = function (transform) {
  2539. var frustumPlanes = [];
  2540. for (var index = 0; index < 6; index++) {
  2541. frustumPlanes.push(new Plane(0, 0, 0, 0));
  2542. }
  2543. Frustum.GetPlanesToRef(transform, frustumPlanes);
  2544. return frustumPlanes;
  2545. };
  2546. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  2547. // Near
  2548. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  2549. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  2550. frustumPlanes[0].normal.z = transform.m[11] + transform.m[10];
  2551. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  2552. frustumPlanes[0].normalize();
  2553. // Far
  2554. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  2555. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  2556. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  2557. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  2558. frustumPlanes[1].normalize();
  2559. // Left
  2560. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  2561. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  2562. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  2563. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  2564. frustumPlanes[2].normalize();
  2565. // Right
  2566. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  2567. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  2568. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  2569. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  2570. frustumPlanes[3].normalize();
  2571. // Top
  2572. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  2573. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  2574. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  2575. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  2576. frustumPlanes[4].normalize();
  2577. // Bottom
  2578. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  2579. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  2580. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  2581. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  2582. frustumPlanes[5].normalize();
  2583. };
  2584. return Frustum;
  2585. })();
  2586. BABYLON.Frustum = Frustum;
  2587. (function (Space) {
  2588. Space[Space["LOCAL"] = 0] = "LOCAL";
  2589. Space[Space["WORLD"] = 1] = "WORLD";
  2590. })(BABYLON.Space || (BABYLON.Space = {}));
  2591. var Space = BABYLON.Space;
  2592. var Axis = (function () {
  2593. function Axis() {
  2594. }
  2595. Axis.X = new Vector3(1, 0, 0);
  2596. Axis.Y = new Vector3(0, 1, 0);
  2597. Axis.Z = new Vector3(0, 0, 1);
  2598. return Axis;
  2599. })();
  2600. BABYLON.Axis = Axis;
  2601. ;
  2602. var BezierCurve = (function () {
  2603. function BezierCurve() {
  2604. }
  2605. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  2606. // Extract X (which is equal to time here)
  2607. var f0 = 1 - 3 * x2 + 3 * x1;
  2608. var f1 = 3 * x2 - 6 * x1;
  2609. var f2 = 3 * x1;
  2610. var refinedT = t;
  2611. for (var i = 0; i < 5; i++) {
  2612. var refinedT2 = refinedT * refinedT;
  2613. var refinedT3 = refinedT2 * refinedT;
  2614. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  2615. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  2616. refinedT -= (x - t) * slope;
  2617. refinedT = Math.min(1, Math.max(0, refinedT));
  2618. }
  2619. // Resolve cubic bezier for the given x
  2620. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  2621. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  2622. Math.pow(refinedT, 3);
  2623. };
  2624. return BezierCurve;
  2625. })();
  2626. BABYLON.BezierCurve = BezierCurve;
  2627. (function (Orientation) {
  2628. Orientation[Orientation["CW"] = 0] = "CW";
  2629. Orientation[Orientation["CCW"] = 1] = "CCW";
  2630. })(BABYLON.Orientation || (BABYLON.Orientation = {}));
  2631. var Orientation = BABYLON.Orientation;
  2632. var Angle = (function () {
  2633. function Angle(radians) {
  2634. var _this = this;
  2635. this.degrees = function () { return _this._radians * 180 / Math.PI; };
  2636. this.radians = function () { return _this._radians; };
  2637. this._radians = radians;
  2638. if (this._radians < 0)
  2639. this._radians += (2 * Math.PI);
  2640. }
  2641. Angle.BetweenTwoPoints = function (a, b) {
  2642. var delta = b.subtract(a);
  2643. var theta = Math.atan2(delta.y, delta.x);
  2644. return new Angle(theta);
  2645. };
  2646. Angle.FromRadians = function (radians) {
  2647. return new Angle(radians);
  2648. };
  2649. Angle.FromDegrees = function (degrees) {
  2650. return new Angle(degrees * Math.PI / 180);
  2651. };
  2652. return Angle;
  2653. })();
  2654. BABYLON.Angle = Angle;
  2655. var Arc2 = (function () {
  2656. function Arc2(startPoint, midPoint, endPoint) {
  2657. this.startPoint = startPoint;
  2658. this.midPoint = midPoint;
  2659. this.endPoint = endPoint;
  2660. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  2661. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  2662. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  2663. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  2664. this.centerPoint = new Vector2((startToMid * (midPoint.y - endPoint.y) - midToEnd * (startPoint.y - midPoint.y)) / det, ((startPoint.x - midPoint.x) * midToEnd - (midPoint.x - endPoint.x) * startToMid) / det);
  2665. this.radius = this.centerPoint.subtract(this.startPoint).length();
  2666. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  2667. var a1 = this.startAngle.degrees();
  2668. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  2669. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  2670. // angles correction
  2671. if (a2 - a1 > +180.0)
  2672. a2 -= 360.0;
  2673. if (a2 - a1 < -180.0)
  2674. a2 += 360.0;
  2675. if (a3 - a2 > +180.0)
  2676. a3 -= 360.0;
  2677. if (a3 - a2 < -180.0)
  2678. a3 += 360.0;
  2679. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  2680. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  2681. }
  2682. return Arc2;
  2683. })();
  2684. BABYLON.Arc2 = Arc2;
  2685. var Path2 = (function () {
  2686. function Path2(x, y) {
  2687. this._points = new Array();
  2688. this._length = 0;
  2689. this.closed = false;
  2690. this._points.push(new Vector2(x, y));
  2691. }
  2692. Path2.prototype.addLineTo = function (x, y) {
  2693. if (closed) {
  2694. //Tools.Error("cannot add lines to closed paths");
  2695. return this;
  2696. }
  2697. var newPoint = new Vector2(x, y);
  2698. var previousPoint = this._points[this._points.length - 1];
  2699. this._points.push(newPoint);
  2700. this._length += newPoint.subtract(previousPoint).length();
  2701. return this;
  2702. };
  2703. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  2704. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  2705. if (closed) {
  2706. //Tools.Error("cannot add arcs to closed paths");
  2707. return this;
  2708. }
  2709. var startPoint = this._points[this._points.length - 1];
  2710. var midPoint = new Vector2(midX, midY);
  2711. var endPoint = new Vector2(endX, endY);
  2712. var arc = new Arc2(startPoint, midPoint, endPoint);
  2713. var increment = arc.angle.radians() / numberOfSegments;
  2714. if (arc.orientation === Orientation.CW)
  2715. increment *= -1;
  2716. var currentAngle = arc.startAngle.radians() + increment;
  2717. for (var i = 0; i < numberOfSegments; i++) {
  2718. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  2719. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  2720. this.addLineTo(x, y);
  2721. currentAngle += increment;
  2722. }
  2723. return this;
  2724. };
  2725. Path2.prototype.close = function () {
  2726. this.closed = true;
  2727. return this;
  2728. };
  2729. Path2.prototype.length = function () {
  2730. var result = this._length;
  2731. if (!this.closed) {
  2732. var lastPoint = this._points[this._points.length - 1];
  2733. var firstPoint = this._points[0];
  2734. result += (firstPoint.subtract(lastPoint).length());
  2735. }
  2736. return result;
  2737. };
  2738. Path2.prototype.getPoints = function () {
  2739. return this._points;
  2740. };
  2741. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  2742. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  2743. //Tools.Error("normalized length position should be between 0 and 1.");
  2744. return Vector2.Zero();
  2745. }
  2746. var lengthPosition = normalizedLengthPosition * this.length();
  2747. var previousOffset = 0;
  2748. for (var i = 0; i < this._points.length; i++) {
  2749. var j = (i + 1) % this._points.length;
  2750. var a = this._points[i];
  2751. var b = this._points[j];
  2752. var bToA = b.subtract(a);
  2753. var nextOffset = (bToA.length() + previousOffset);
  2754. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  2755. var dir = bToA.normalize();
  2756. var localOffset = lengthPosition - previousOffset;
  2757. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  2758. }
  2759. previousOffset = nextOffset;
  2760. }
  2761. //Tools.Error("internal error");
  2762. return Vector2.Zero();
  2763. };
  2764. Path2.StartingAt = function (x, y) {
  2765. return new Path2(x, y);
  2766. };
  2767. return Path2;
  2768. })();
  2769. BABYLON.Path2 = Path2;
  2770. var Path3D = (function () {
  2771. /**
  2772. * new Path3D(path, normal, raw)
  2773. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  2774. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  2775. * path : an array of Vector3, the curve axis of the Path3D
  2776. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  2777. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  2778. */
  2779. function Path3D(path, firstNormal, raw) {
  2780. this.path = path;
  2781. this._curve = new Array();
  2782. this._distances = new Array();
  2783. this._tangents = new Array();
  2784. this._normals = new Array();
  2785. this._binormals = new Array();
  2786. for (var p = 0; p < path.length; p++) {
  2787. this._curve[p] = path[p].clone(); // hard copy
  2788. }
  2789. this._raw = raw || false;
  2790. this._compute(firstNormal);
  2791. }
  2792. /**
  2793. * Returns the Path3D array of successive Vector3 designing its curve.
  2794. */
  2795. Path3D.prototype.getCurve = function () {
  2796. return this._curve;
  2797. };
  2798. /**
  2799. * Returns an array populated with tangent vectors on each Path3D curve point.
  2800. */
  2801. Path3D.prototype.getTangents = function () {
  2802. return this._tangents;
  2803. };
  2804. /**
  2805. * Returns an array populated with normal vectors on each Path3D curve point.
  2806. */
  2807. Path3D.prototype.getNormals = function () {
  2808. return this._normals;
  2809. };
  2810. /**
  2811. * Returns an array populated with binormal vectors on each Path3D curve point.
  2812. */
  2813. Path3D.prototype.getBinormals = function () {
  2814. return this._binormals;
  2815. };
  2816. /**
  2817. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  2818. */
  2819. Path3D.prototype.getDistances = function () {
  2820. return this._distances;
  2821. };
  2822. /**
  2823. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  2824. * Returns the same object updated.
  2825. */
  2826. Path3D.prototype.update = function (path, firstNormal) {
  2827. for (var p = 0; p < path.length; p++) {
  2828. this._curve[p].x = path[p].x;
  2829. this._curve[p].y = path[p].y;
  2830. this._curve[p].z = path[p].z;
  2831. }
  2832. this._compute(firstNormal);
  2833. return this;
  2834. };
  2835. // private function compute() : computes tangents, normals and binormals
  2836. Path3D.prototype._compute = function (firstNormal) {
  2837. var l = this._curve.length;
  2838. // first and last tangents
  2839. this._tangents[0] = this._getFirstNonNullVector(0);
  2840. if (!this._raw) {
  2841. this._tangents[0].normalize();
  2842. }
  2843. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  2844. if (!this._raw) {
  2845. this._tangents[l - 1].normalize();
  2846. }
  2847. // normals and binormals at first point : arbitrary vector with _normalVector()
  2848. var tg0 = this._tangents[0];
  2849. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  2850. this._normals[0] = pp0;
  2851. if (!this._raw) {
  2852. this._normals[0].normalize();
  2853. }
  2854. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  2855. if (!this._raw) {
  2856. this._binormals[0].normalize();
  2857. }
  2858. this._distances[0] = 0.0;
  2859. // normals and binormals : next points
  2860. var prev; // previous vector (segment)
  2861. var cur; // current vector (segment)
  2862. var curTang; // current tangent
  2863. // previous normal
  2864. var prevBinor; // previous binormal
  2865. for (var i = 1; i < l; i++) {
  2866. // tangents
  2867. prev = this._getLastNonNullVector(i);
  2868. if (i < l - 1) {
  2869. cur = this._getFirstNonNullVector(i);
  2870. this._tangents[i] = prev.add(cur);
  2871. this._tangents[i].normalize();
  2872. }
  2873. this._distances[i] = this._distances[i - 1] + prev.length();
  2874. // normals and binormals
  2875. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  2876. curTang = this._tangents[i];
  2877. prevBinor = this._binormals[i - 1];
  2878. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  2879. if (!this._raw) {
  2880. this._normals[i].normalize();
  2881. }
  2882. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  2883. if (!this._raw) {
  2884. this._binormals[i].normalize();
  2885. }
  2886. }
  2887. };
  2888. // private function getFirstNonNullVector(index)
  2889. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  2890. Path3D.prototype._getFirstNonNullVector = function (index) {
  2891. var i = 1;
  2892. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  2893. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  2894. i++;
  2895. nNVector = this._curve[index + i].subtract(this._curve[index]);
  2896. }
  2897. return nNVector;
  2898. };
  2899. // private function getLastNonNullVector(index)
  2900. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  2901. Path3D.prototype._getLastNonNullVector = function (index) {
  2902. var i = 1;
  2903. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  2904. while (nLVector.length() === 0 && index > i + 1) {
  2905. i++;
  2906. nLVector = this._curve[index].subtract(this._curve[index - i]);
  2907. }
  2908. return nLVector;
  2909. };
  2910. // private function normalVector(v0, vt, va) :
  2911. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  2912. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  2913. Path3D.prototype._normalVector = function (v0, vt, va) {
  2914. var normal0;
  2915. var tgl = vt.length();
  2916. if (tgl === 0.0) {
  2917. tgl = 1.0;
  2918. }
  2919. if (va === undefined || va === null) {
  2920. var point;
  2921. if (!MathTools.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) {
  2922. point = new Vector3(0.0, -1.0, 0.0);
  2923. }
  2924. else if (!MathTools.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  2925. point = new Vector3(1.0, 0.0, 0.0);
  2926. }
  2927. else if (!MathTools.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  2928. point = new Vector3(0.0, 0.0, 1.0);
  2929. }
  2930. normal0 = Vector3.Cross(vt, point);
  2931. }
  2932. else {
  2933. normal0 = Vector3.Cross(vt, va);
  2934. Vector3.CrossToRef(normal0, vt, normal0);
  2935. }
  2936. normal0.normalize();
  2937. return normal0;
  2938. };
  2939. return Path3D;
  2940. })();
  2941. BABYLON.Path3D = Path3D;
  2942. var Curve3 = (function () {
  2943. /**
  2944. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  2945. * A Curve3 is designed from a series of successive Vector3.
  2946. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  2947. */
  2948. function Curve3(points) {
  2949. this._length = 0.0;
  2950. this._points = points;
  2951. this._length = this._computeLength(points);
  2952. }
  2953. /**
  2954. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  2955. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  2956. * @param v1 (Vector3) the control point
  2957. * @param v2 (Vector3) the end point of the Quadratic Bezier
  2958. * @param nbPoints (integer) the wanted number of points in the curve
  2959. */
  2960. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  2961. nbPoints = nbPoints > 2 ? nbPoints : 3;
  2962. var bez = new Array();
  2963. var equation = function (t, val0, val1, val2) {
  2964. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  2965. return res;
  2966. };
  2967. for (var i = 0; i <= nbPoints; i++) {
  2968. bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x), equation(i / nbPoints, v0.y, v1.y, v2.y), equation(i / nbPoints, v0.z, v1.z, v2.z)));
  2969. }
  2970. return new Curve3(bez);
  2971. };
  2972. /**
  2973. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  2974. * @param v0 (Vector3) the origin point of the Cubic Bezier
  2975. * @param v1 (Vector3) the first control point
  2976. * @param v2 (Vector3) the second control point
  2977. * @param v3 (Vector3) the end point of the Cubic Bezier
  2978. * @param nbPoints (integer) the wanted number of points in the curve
  2979. */
  2980. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  2981. nbPoints = nbPoints > 3 ? nbPoints : 4;
  2982. var bez = new Array();
  2983. var equation = function (t, val0, val1, val2, val3) {
  2984. var res = (1.0 - t) * (1.0 - t) * (1.0 - t) * val0 + 3.0 * t * (1.0 - t) * (1.0 - t) * val1 + 3.0 * t * t * (1.0 - t) * val2 + t * t * t * val3;
  2985. return res;
  2986. };
  2987. for (var i = 0; i <= nbPoints; i++) {
  2988. bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x, v3.x), equation(i / nbPoints, v0.y, v1.y, v2.y, v3.y), equation(i / nbPoints, v0.z, v1.z, v2.z, v3.z)));
  2989. }
  2990. return new Curve3(bez);
  2991. };
  2992. /**
  2993. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  2994. * @param p1 (Vector3) the origin point of the Hermite Spline
  2995. * @param t1 (Vector3) the tangent vector at the origin point
  2996. * @param p2 (Vector3) the end point of the Hermite Spline
  2997. * @param t2 (Vector3) the tangent vector at the end point
  2998. * @param nbPoints (integer) the wanted number of points in the curve
  2999. */
  3000. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  3001. var hermite = new Array();
  3002. var step = 1.0 / nbPoints;
  3003. for (var i = 0; i <= nbPoints; i++) {
  3004. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  3005. }
  3006. return new Curve3(hermite);
  3007. };
  3008. /**
  3009. * Returns the Curve3 stored array of successive Vector3
  3010. */
  3011. Curve3.prototype.getPoints = function () {
  3012. return this._points;
  3013. };
  3014. /**
  3015. * Returns the computed length (float) of the curve.
  3016. */
  3017. Curve3.prototype.length = function () {
  3018. return this._length;
  3019. };
  3020. /**
  3021. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  3022. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  3023. * curveA and curveB keep unchanged.
  3024. */
  3025. Curve3.prototype.continue = function (curve) {
  3026. var lastPoint = this._points[this._points.length - 1];
  3027. var continuedPoints = this._points.slice();
  3028. var curvePoints = curve.getPoints();
  3029. for (var i = 1; i < curvePoints.length; i++) {
  3030. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  3031. }
  3032. var continuedCurve = new Curve3(continuedPoints);
  3033. return continuedCurve;
  3034. };
  3035. Curve3.prototype._computeLength = function (path) {
  3036. var l = 0;
  3037. for (var i = 1; i < path.length; i++) {
  3038. l += (path[i].subtract(path[i - 1])).length();
  3039. }
  3040. return l;
  3041. };
  3042. return Curve3;
  3043. })();
  3044. BABYLON.Curve3 = Curve3;
  3045. // SphericalHarmonics
  3046. var SphericalHarmonics = (function () {
  3047. function SphericalHarmonics() {
  3048. this.L00 = Vector3.Zero();
  3049. this.L1_1 = Vector3.Zero();
  3050. this.L10 = Vector3.Zero();
  3051. this.L11 = Vector3.Zero();
  3052. this.L2_2 = Vector3.Zero();
  3053. this.L2_1 = Vector3.Zero();
  3054. this.L20 = Vector3.Zero();
  3055. this.L21 = Vector3.Zero();
  3056. this.L22 = Vector3.Zero();
  3057. }
  3058. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  3059. var colorVector = new Vector3(color.r, color.g, color.b);
  3060. var c = colorVector.scale(deltaSolidAngle);
  3061. this.L00 = this.L00.add(c.scale(0.282095));
  3062. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  3063. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  3064. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  3065. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  3066. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  3067. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  3068. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  3069. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  3070. };
  3071. SphericalHarmonics.prototype.scale = function (scale) {
  3072. this.L00 = this.L00.scale(scale);
  3073. this.L1_1 = this.L1_1.scale(scale);
  3074. this.L10 = this.L10.scale(scale);
  3075. this.L11 = this.L11.scale(scale);
  3076. this.L2_2 = this.L2_2.scale(scale);
  3077. this.L2_1 = this.L2_1.scale(scale);
  3078. this.L20 = this.L20.scale(scale);
  3079. this.L21 = this.L21.scale(scale);
  3080. this.L22 = this.L22.scale(scale);
  3081. };
  3082. return SphericalHarmonics;
  3083. })();
  3084. BABYLON.SphericalHarmonics = SphericalHarmonics;
  3085. // SphericalPolynomial
  3086. var SphericalPolynomial = (function () {
  3087. function SphericalPolynomial() {
  3088. this.x = Vector3.Zero();
  3089. this.y = Vector3.Zero();
  3090. this.z = Vector3.Zero();
  3091. this.xx = Vector3.Zero();
  3092. this.yy = Vector3.Zero();
  3093. this.zz = Vector3.Zero();
  3094. this.xy = Vector3.Zero();
  3095. this.yz = Vector3.Zero();
  3096. this.zx = Vector3.Zero();
  3097. }
  3098. SphericalPolynomial.prototype.addAmbient = function (color) {
  3099. var colorVector = new Vector3(color.r, color.g, color.b);
  3100. this.xx = this.xx.add(colorVector);
  3101. this.yy = this.yy.add(colorVector);
  3102. this.zz = this.zz.add(colorVector);
  3103. };
  3104. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  3105. var result = new SphericalPolynomial();
  3106. result.x = harmonics.L11.scale(1.02333);
  3107. result.y = harmonics.L1_1.scale(1.02333);
  3108. result.z = harmonics.L10.scale(1.02333);
  3109. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  3110. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  3111. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  3112. result.yz = harmonics.L2_1.scale(0.858086);
  3113. result.zx = harmonics.L21.scale(0.858086);
  3114. result.xy = harmonics.L2_2.scale(0.858086);
  3115. return result;
  3116. };
  3117. return SphericalPolynomial;
  3118. })();
  3119. BABYLON.SphericalPolynomial = SphericalPolynomial;
  3120. // Vertex formats
  3121. var PositionNormalVertex = (function () {
  3122. function PositionNormalVertex(position, normal) {
  3123. if (position === void 0) { position = Vector3.Zero(); }
  3124. if (normal === void 0) { normal = Vector3.Up(); }
  3125. this.position = position;
  3126. this.normal = normal;
  3127. }
  3128. PositionNormalVertex.prototype.clone = function () {
  3129. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  3130. };
  3131. return PositionNormalVertex;
  3132. })();
  3133. BABYLON.PositionNormalVertex = PositionNormalVertex;
  3134. var PositionNormalTextureVertex = (function () {
  3135. function PositionNormalTextureVertex(position, normal, uv) {
  3136. if (position === void 0) { position = Vector3.Zero(); }
  3137. if (normal === void 0) { normal = Vector3.Up(); }
  3138. if (uv === void 0) { uv = Vector2.Zero(); }
  3139. this.position = position;
  3140. this.normal = normal;
  3141. this.uv = uv;
  3142. }
  3143. PositionNormalTextureVertex.prototype.clone = function () {
  3144. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  3145. };
  3146. return PositionNormalTextureVertex;
  3147. })();
  3148. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  3149. // Temporary pre-allocated objects for engine internal use
  3150. // usage in any internal function :
  3151. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  3152. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  3153. var Tmp = (function () {
  3154. function Tmp() {
  3155. }
  3156. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  3157. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  3158. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  3159. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  3160. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  3161. Tmp.Quaternion = [new Quaternion(0, 0, 0, 0)]; // 1 temp Quaternion at once should be enough
  3162. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  3163. Matrix.Zero(), Matrix.Zero(),
  3164. Matrix.Zero(), Matrix.Zero(),
  3165. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  3166. return Tmp;
  3167. })();
  3168. BABYLON.Tmp = Tmp;
  3169. })(BABYLON || (BABYLON = {}));
  3170. var BABYLON;
  3171. (function (BABYLON) {
  3172. function generateSerializableMember(type, sourceName) {
  3173. return function (target, propertyKey) {
  3174. if (!target.__serializableMembers) {
  3175. target.__serializableMembers = {};
  3176. }
  3177. target.__serializableMembers[propertyKey] = { type: type, sourceName: sourceName };
  3178. };
  3179. }
  3180. function serialize(sourceName) {
  3181. return generateSerializableMember(0, sourceName); // value member
  3182. }
  3183. BABYLON.serialize = serialize;
  3184. function serializeAsTexture(sourceName) {
  3185. return generateSerializableMember(1, sourceName); // texture member
  3186. }
  3187. BABYLON.serializeAsTexture = serializeAsTexture;
  3188. function serializeAsColor3(sourceName) {
  3189. return generateSerializableMember(2, sourceName); // color3 member
  3190. }
  3191. BABYLON.serializeAsColor3 = serializeAsColor3;
  3192. function serializeAsFresnelParameters(sourceName) {
  3193. return generateSerializableMember(3, sourceName); // fresnel parameters member
  3194. }
  3195. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  3196. function serializeAsVector2(sourceName) {
  3197. return generateSerializableMember(4, sourceName); // vector2 member
  3198. }
  3199. BABYLON.serializeAsVector2 = serializeAsVector2;
  3200. function serializeAsVector3(sourceName) {
  3201. return generateSerializableMember(5, sourceName); // vector3 member
  3202. }
  3203. BABYLON.serializeAsVector3 = serializeAsVector3;
  3204. function serializeAsMeshReference(sourceName) {
  3205. return generateSerializableMember(6, sourceName); // mesh reference member
  3206. }
  3207. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  3208. function serializeAsColorCurves(sourceName) {
  3209. return generateSerializableMember(7, sourceName); // color curves
  3210. }
  3211. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  3212. var SerializationHelper = (function () {
  3213. function SerializationHelper() {
  3214. }
  3215. SerializationHelper.Serialize = function (entity, serializationObject) {
  3216. if (!serializationObject) {
  3217. serializationObject = {};
  3218. }
  3219. // Tags
  3220. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  3221. // Properties
  3222. for (var property in entity.__serializableMembers) {
  3223. var propertyDescriptor = entity.__serializableMembers[property];
  3224. var targetPropertyName = propertyDescriptor.sourceName || property;
  3225. var propertyType = propertyDescriptor.type;
  3226. var sourceProperty = entity[property];
  3227. if (sourceProperty !== undefined && sourceProperty !== null) {
  3228. switch (propertyType) {
  3229. case 0:
  3230. serializationObject[targetPropertyName] = sourceProperty;
  3231. break;
  3232. case 1:
  3233. serializationObject[targetPropertyName] = sourceProperty.serialize();
  3234. break;
  3235. case 2:
  3236. serializationObject[targetPropertyName] = sourceProperty.asArray();
  3237. break;
  3238. case 3:
  3239. serializationObject[targetPropertyName] = sourceProperty.serialize();
  3240. break;
  3241. case 4:
  3242. serializationObject[targetPropertyName] = sourceProperty.asArray();
  3243. break;
  3244. case 5:
  3245. serializationObject[targetPropertyName] = sourceProperty.asArray();
  3246. break;
  3247. case 6:
  3248. serializationObject[targetPropertyName] = sourceProperty.id;
  3249. break;
  3250. case 7:
  3251. serializationObject[targetPropertyName] = sourceProperty.serialize();
  3252. break;
  3253. }
  3254. }
  3255. }
  3256. return serializationObject;
  3257. };
  3258. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  3259. var destination = creationFunction();
  3260. // Tags
  3261. BABYLON.Tags.AddTagsTo(destination, source.tags);
  3262. // Properties
  3263. for (var property in destination.__serializableMembers) {
  3264. var propertyDescriptor = destination.__serializableMembers[property];
  3265. var sourceProperty = source[propertyDescriptor.sourceName || property];
  3266. var propertyType = propertyDescriptor.type;
  3267. if (sourceProperty !== undefined && sourceProperty !== null) {
  3268. switch (propertyType) {
  3269. case 0:
  3270. destination[property] = sourceProperty;
  3271. break;
  3272. case 1:
  3273. destination[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  3274. break;
  3275. case 2:
  3276. destination[property] = BABYLON.Color3.FromArray(sourceProperty);
  3277. break;
  3278. case 3:
  3279. destination[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  3280. break;
  3281. case 4:
  3282. destination[property] = BABYLON.Vector2.FromArray(sourceProperty);
  3283. break;
  3284. case 5:
  3285. destination[property] = BABYLON.Vector3.FromArray(sourceProperty);
  3286. break;
  3287. case 6:
  3288. destination[property] = scene.getLastMeshByID(sourceProperty);
  3289. break;
  3290. case 7:
  3291. destination[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  3292. break;
  3293. }
  3294. }
  3295. }
  3296. return destination;
  3297. };
  3298. SerializationHelper.Clone = function (creationFunction, source) {
  3299. var destination = creationFunction();
  3300. // Tags
  3301. BABYLON.Tags.AddTagsTo(destination, source.tags);
  3302. // Properties
  3303. for (var property in destination.__serializableMembers) {
  3304. var propertyDescriptor = destination.__serializableMembers[property];
  3305. var sourceProperty = source[property];
  3306. var propertyType = propertyDescriptor.type;
  3307. if (sourceProperty !== undefined && sourceProperty !== null) {
  3308. switch (propertyType) {
  3309. case 0: // Value
  3310. case 6:
  3311. destination[property] = sourceProperty;
  3312. break;
  3313. case 1: // Texture
  3314. case 2: // Color3
  3315. case 3: // FresnelParameters
  3316. case 4: // Vector2
  3317. case 5: // Vector3
  3318. case 7:
  3319. destination[property] = sourceProperty.clone();
  3320. break;
  3321. }
  3322. }
  3323. }
  3324. return destination;
  3325. };
  3326. return SerializationHelper;
  3327. })();
  3328. BABYLON.SerializationHelper = SerializationHelper;
  3329. })(BABYLON || (BABYLON = {}));
  3330. var BABYLON;
  3331. (function (BABYLON) {
  3332. /**
  3333. * A class serves as a medium between the observable and its observers
  3334. */
  3335. var EventState = (function () {
  3336. /**
  3337. * If the callback of a given Observer set skipNextObservers to true the following observers will be ignored
  3338. */
  3339. function EventState(mask, skipNextObservers) {
  3340. if (skipNextObservers === void 0) { skipNextObservers = false; }
  3341. this.initalize(mask, skipNextObservers);
  3342. }
  3343. EventState.prototype.initalize = function (mask, skipNextObservers) {
  3344. if (skipNextObservers === void 0) { skipNextObservers = false; }
  3345. this.mask = mask;
  3346. this.skipNextObservers = skipNextObservers;
  3347. return this;
  3348. };
  3349. return EventState;
  3350. })();
  3351. BABYLON.EventState = EventState;
  3352. /**
  3353. * Represent an Observer registered to a given Observable object.
  3354. */
  3355. var Observer = (function () {
  3356. function Observer(callback, mask) {
  3357. this.callback = callback;
  3358. this.mask = mask;
  3359. }
  3360. return Observer;
  3361. })();
  3362. BABYLON.Observer = Observer;
  3363. /**
  3364. * The Observable class is a simple implementation of the Observable pattern.
  3365. * There's one slight particularity though: a given Observable can notify its observer using a particular mask value, only the Observers registered with this mask value will be notified.
  3366. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  3367. * For instance you may have a given Observable that have four different types of notifications: Move (mask = 0x01), Stop (mask = 0x02), Turn Right (mask = 0X04), Turn Left (mask = 0X08).
  3368. * A given observer can register itself with only Move and Stop (mask = 0x03), then it will only be notified when one of these two occurs and will never be for Turn Left/Right.
  3369. */
  3370. var Observable = (function () {
  3371. function Observable() {
  3372. this._observers = new Array();
  3373. }
  3374. /**
  3375. * Create a new Observer with the specified callback
  3376. * @param callback the callback that will be executed for that Observer
  3377. * @param mask the mask used to filter observers
  3378. * @param insertFirst if true the callback will be inserted at the first position, hence executed before the others ones. If false (default behavior) the callback will be inserted at the last position, executed after all the others already present.
  3379. */
  3380. Observable.prototype.add = function (callback, mask, insertFirst) {
  3381. if (mask === void 0) { mask = -1; }
  3382. if (insertFirst === void 0) { insertFirst = false; }
  3383. if (!callback) {
  3384. return null;
  3385. }
  3386. var observer = new Observer(callback, mask);
  3387. if (insertFirst) {
  3388. this._observers.unshift(observer);
  3389. }
  3390. else {
  3391. this._observers.push(observer);
  3392. }
  3393. return observer;
  3394. };
  3395. /**
  3396. * Remove an Observer from the Observable object
  3397. * @param observer the instance of the Observer to remove. If it doesn't belong to this Observable, false will be returned.
  3398. */
  3399. Observable.prototype.remove = function (observer) {
  3400. var index = this._observers.indexOf(observer);
  3401. if (index !== -1) {
  3402. this._observers.splice(index, 1);
  3403. return true;
  3404. }
  3405. return false;
  3406. };
  3407. /**
  3408. * Remove a callback from the Observable object
  3409. * @param callback the callback to remove. If it doesn't belong to this Observable, false will be returned.
  3410. */
  3411. Observable.prototype.removeCallback = function (callback) {
  3412. for (var index = 0; index < this._observers.length; index++) {
  3413. if (this._observers[index].callback === callback) {
  3414. this._observers.splice(index, 1);
  3415. return true;
  3416. }
  3417. }
  3418. return false;
  3419. };
  3420. /**
  3421. * Notify all Observers by calling their respective callback with the given data
  3422. * @param eventData
  3423. * @param mask
  3424. */
  3425. Observable.prototype.notifyObservers = function (eventData, mask) {
  3426. if (mask === void 0) { mask = -1; }
  3427. var state = Observable._pooledEventState ? Observable._pooledEventState.initalize(mask) : new EventState(mask);
  3428. Observable._pooledEventState = null;
  3429. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  3430. var obs = _a[_i];
  3431. if (obs.mask & mask) {
  3432. obs.callback(eventData, state);
  3433. }
  3434. if (state.skipNextObservers) {
  3435. break;
  3436. }
  3437. }
  3438. Observable._pooledEventState = state;
  3439. };
  3440. /**
  3441. * return true is the Observable has at least one Observer registered
  3442. */
  3443. Observable.prototype.hasObservers = function () {
  3444. return this._observers.length > 0;
  3445. };
  3446. /**
  3447. * Clear the list of observers
  3448. */
  3449. Observable.prototype.clear = function () {
  3450. this._observers = new Array();
  3451. };
  3452. /**
  3453. * Clone the current observable
  3454. */
  3455. Observable.prototype.clone = function () {
  3456. var result = new Observable();
  3457. result._observers = this._observers.slice(0);
  3458. return result;
  3459. };
  3460. Observable._pooledEventState = null;
  3461. return Observable;
  3462. })();
  3463. BABYLON.Observable = Observable;
  3464. })(BABYLON || (BABYLON = {}));
  3465. var BABYLON;
  3466. (function (BABYLON) {
  3467. var Database = (function () {
  3468. function Database(urlToScene, callbackManifestChecked) {
  3469. // Handling various flavors of prefixed version of IndexedDB
  3470. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  3471. this.callbackManifestChecked = callbackManifestChecked;
  3472. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  3473. this.db = null;
  3474. this.enableSceneOffline = false;
  3475. this.enableTexturesOffline = false;
  3476. this.manifestVersionFound = 0;
  3477. this.mustUpdateRessources = false;
  3478. this.hasReachedQuota = false;
  3479. if (!Database.IDBStorageEnabled) {
  3480. this.callbackManifestChecked(true);
  3481. }
  3482. else {
  3483. this.checkManifestFile();
  3484. }
  3485. }
  3486. Database.prototype.checkManifestFile = function () {
  3487. var _this = this;
  3488. function noManifestFile() {
  3489. that.enableSceneOffline = false;
  3490. that.enableTexturesOffline = false;
  3491. that.callbackManifestChecked(false);
  3492. }
  3493. var that = this;
  3494. var timeStampUsed = false;
  3495. var manifestURL = this.currentSceneUrl + ".manifest";
  3496. var xhr = new XMLHttpRequest();
  3497. if (navigator.onLine) {
  3498. // Adding a timestamp to by-pass browsers' cache
  3499. timeStampUsed = true;
  3500. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  3501. }
  3502. xhr.open("GET", manifestURL, true);
  3503. xhr.addEventListener("load", function () {
  3504. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  3505. try {
  3506. var manifestFile = JSON.parse(xhr.response);
  3507. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  3508. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  3509. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  3510. _this.manifestVersionFound = manifestFile.version;
  3511. }
  3512. if (_this.callbackManifestChecked) {
  3513. _this.callbackManifestChecked(true);
  3514. }
  3515. }
  3516. catch (ex) {
  3517. noManifestFile();
  3518. }
  3519. }
  3520. else {
  3521. noManifestFile();
  3522. }
  3523. }, false);
  3524. xhr.addEventListener("error", function (event) {
  3525. if (timeStampUsed) {
  3526. timeStampUsed = false;
  3527. // Let's retry without the timeStamp
  3528. // It could fail when coupled with HTML5 Offline API
  3529. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  3530. xhr.open("GET", retryManifestURL, true);
  3531. xhr.send();
  3532. }
  3533. else {
  3534. noManifestFile();
  3535. }
  3536. }, false);
  3537. try {
  3538. xhr.send();
  3539. }
  3540. catch (ex) {
  3541. BABYLON.Tools.Error("Error on XHR send request.");
  3542. that.callbackManifestChecked(false);
  3543. }
  3544. };
  3545. Database.prototype.openAsync = function (successCallback, errorCallback) {
  3546. var _this = this;
  3547. function handleError() {
  3548. that.isSupported = false;
  3549. if (errorCallback)
  3550. errorCallback();
  3551. }
  3552. var that = this;
  3553. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  3554. // Your browser doesn't support IndexedDB
  3555. this.isSupported = false;
  3556. if (errorCallback)
  3557. errorCallback();
  3558. }
  3559. else {
  3560. // If the DB hasn't been opened or created yet
  3561. if (!this.db) {
  3562. this.hasReachedQuota = false;
  3563. this.isSupported = true;
  3564. var request = this.idbFactory.open("babylonjs", 1);
  3565. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  3566. request.onerror = function (event) {
  3567. handleError();
  3568. };
  3569. // executes when a version change transaction cannot complete due to other active transactions
  3570. request.onblocked = function (event) {
  3571. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  3572. handleError();
  3573. };
  3574. // DB has been opened successfully
  3575. request.onsuccess = function (event) {
  3576. _this.db = request.result;
  3577. successCallback();
  3578. };
  3579. // Initialization of the DB. Creating Scenes & Textures stores
  3580. request.onupgradeneeded = function (event) {
  3581. _this.db = (event.target).result;
  3582. try {
  3583. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  3584. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  3585. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  3586. }
  3587. catch (ex) {
  3588. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  3589. handleError();
  3590. }
  3591. };
  3592. }
  3593. else {
  3594. if (successCallback)
  3595. successCallback();
  3596. }
  3597. }
  3598. };
  3599. Database.prototype.loadImageFromDB = function (url, image) {
  3600. var _this = this;
  3601. var completeURL = Database.ReturnFullUrlLocation(url);
  3602. var saveAndLoadImage = function () {
  3603. if (!_this.hasReachedQuota && _this.db !== null) {
  3604. // the texture is not yet in the DB, let's try to save it
  3605. _this._saveImageIntoDBAsync(completeURL, image);
  3606. }
  3607. else {
  3608. image.src = url;
  3609. }
  3610. };
  3611. if (!this.mustUpdateRessources) {
  3612. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  3613. }
  3614. else {
  3615. saveAndLoadImage();
  3616. }
  3617. };
  3618. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  3619. if (this.isSupported && this.db !== null) {
  3620. var texture;
  3621. var transaction = this.db.transaction(["textures"]);
  3622. transaction.onabort = function (event) {
  3623. image.src = url;
  3624. };
  3625. transaction.oncomplete = function (event) {
  3626. var blobTextureURL;
  3627. if (texture) {
  3628. var URL = window.URL || window.webkitURL;
  3629. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  3630. image.onerror = function () {
  3631. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  3632. image.src = url;
  3633. };
  3634. image.src = blobTextureURL;
  3635. }
  3636. else {
  3637. notInDBCallback();
  3638. }
  3639. };
  3640. var getRequest = transaction.objectStore("textures").get(url);
  3641. getRequest.onsuccess = function (event) {
  3642. texture = (event.target).result;
  3643. };
  3644. getRequest.onerror = function (event) {
  3645. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  3646. image.src = url;
  3647. };
  3648. }
  3649. else {
  3650. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3651. image.src = url;
  3652. }
  3653. };
  3654. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  3655. var _this = this;
  3656. if (this.isSupported) {
  3657. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  3658. var generateBlobUrl = function () {
  3659. var blobTextureURL;
  3660. if (blob) {
  3661. var URL = window.URL || window.webkitURL;
  3662. try {
  3663. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  3664. }
  3665. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  3666. catch (ex) {
  3667. blobTextureURL = URL.createObjectURL(blob);
  3668. }
  3669. }
  3670. image.src = blobTextureURL;
  3671. };
  3672. if (Database.IsUASupportingBlobStorage) {
  3673. var xhr = new XMLHttpRequest(), blob;
  3674. xhr.open("GET", url, true);
  3675. xhr.responseType = "blob";
  3676. xhr.addEventListener("load", function () {
  3677. if (xhr.status === 200) {
  3678. // Blob as response (XHR2)
  3679. blob = xhr.response;
  3680. var transaction = _this.db.transaction(["textures"], "readwrite");
  3681. // the transaction could abort because of a QuotaExceededError error
  3682. transaction.onabort = function (event) {
  3683. try {
  3684. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3685. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3686. this.hasReachedQuota = true;
  3687. }
  3688. }
  3689. catch (ex) { }
  3690. generateBlobUrl();
  3691. };
  3692. transaction.oncomplete = function (event) {
  3693. generateBlobUrl();
  3694. };
  3695. var newTexture = { textureUrl: url, data: blob };
  3696. try {
  3697. // Put the blob into the dabase
  3698. var addRequest = transaction.objectStore("textures").put(newTexture);
  3699. addRequest.onsuccess = function (event) {
  3700. };
  3701. addRequest.onerror = function (event) {
  3702. generateBlobUrl();
  3703. };
  3704. }
  3705. catch (ex) {
  3706. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  3707. if (ex.code === 25) {
  3708. Database.IsUASupportingBlobStorage = false;
  3709. }
  3710. image.src = url;
  3711. }
  3712. }
  3713. else {
  3714. image.src = url;
  3715. }
  3716. }, false);
  3717. xhr.addEventListener("error", function (event) {
  3718. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  3719. image.src = url;
  3720. }, false);
  3721. xhr.send();
  3722. }
  3723. else {
  3724. image.src = url;
  3725. }
  3726. }
  3727. else {
  3728. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3729. image.src = url;
  3730. }
  3731. };
  3732. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  3733. var _this = this;
  3734. var updateVersion = function (event) {
  3735. // the version is not yet in the DB or we need to update it
  3736. _this._saveVersionIntoDBAsync(url, versionLoaded);
  3737. };
  3738. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  3739. };
  3740. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  3741. var _this = this;
  3742. if (this.isSupported) {
  3743. var version;
  3744. try {
  3745. var transaction = this.db.transaction(["versions"]);
  3746. transaction.oncomplete = function (event) {
  3747. if (version) {
  3748. // If the version in the JSON file is > than the version in DB
  3749. if (_this.manifestVersionFound > version.data) {
  3750. _this.mustUpdateRessources = true;
  3751. updateInDBCallback();
  3752. }
  3753. else {
  3754. callback(version.data);
  3755. }
  3756. }
  3757. else {
  3758. _this.mustUpdateRessources = true;
  3759. updateInDBCallback();
  3760. }
  3761. };
  3762. transaction.onabort = function (event) {
  3763. callback(-1);
  3764. };
  3765. var getRequest = transaction.objectStore("versions").get(url);
  3766. getRequest.onsuccess = function (event) {
  3767. version = (event.target).result;
  3768. };
  3769. getRequest.onerror = function (event) {
  3770. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  3771. callback(-1);
  3772. };
  3773. }
  3774. catch (ex) {
  3775. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  3776. callback(-1);
  3777. }
  3778. }
  3779. else {
  3780. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3781. callback(-1);
  3782. }
  3783. };
  3784. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  3785. var _this = this;
  3786. if (this.isSupported && !this.hasReachedQuota) {
  3787. try {
  3788. // Open a transaction to the database
  3789. var transaction = this.db.transaction(["versions"], "readwrite");
  3790. // the transaction could abort because of a QuotaExceededError error
  3791. transaction.onabort = function (event) {
  3792. try {
  3793. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3794. _this.hasReachedQuota = true;
  3795. }
  3796. }
  3797. catch (ex) { }
  3798. callback(-1);
  3799. };
  3800. transaction.oncomplete = function (event) {
  3801. callback(_this.manifestVersionFound);
  3802. };
  3803. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  3804. // Put the scene into the database
  3805. var addRequest = transaction.objectStore("versions").put(newVersion);
  3806. addRequest.onsuccess = function (event) {
  3807. };
  3808. addRequest.onerror = function (event) {
  3809. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  3810. };
  3811. }
  3812. catch (ex) {
  3813. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  3814. callback(-1);
  3815. }
  3816. }
  3817. else {
  3818. callback(-1);
  3819. }
  3820. };
  3821. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  3822. var _this = this;
  3823. var completeUrl = Database.ReturnFullUrlLocation(url);
  3824. var saveAndLoadFile = function (event) {
  3825. // the scene is not yet in the DB, let's try to save it
  3826. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  3827. };
  3828. this._checkVersionFromDB(completeUrl, function (version) {
  3829. if (version !== -1) {
  3830. if (!_this.mustUpdateRessources) {
  3831. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  3832. }
  3833. else {
  3834. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  3835. }
  3836. }
  3837. else {
  3838. errorCallback();
  3839. }
  3840. });
  3841. };
  3842. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  3843. if (this.isSupported) {
  3844. var targetStore;
  3845. if (url.indexOf(".babylon") !== -1) {
  3846. targetStore = "scenes";
  3847. }
  3848. else {
  3849. targetStore = "textures";
  3850. }
  3851. var file;
  3852. var transaction = this.db.transaction([targetStore]);
  3853. transaction.oncomplete = function (event) {
  3854. if (file) {
  3855. callback(file.data);
  3856. }
  3857. else {
  3858. notInDBCallback();
  3859. }
  3860. };
  3861. transaction.onabort = function (event) {
  3862. notInDBCallback();
  3863. };
  3864. var getRequest = transaction.objectStore(targetStore).get(url);
  3865. getRequest.onsuccess = function (event) {
  3866. file = (event.target).result;
  3867. };
  3868. getRequest.onerror = function (event) {
  3869. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  3870. notInDBCallback();
  3871. };
  3872. }
  3873. else {
  3874. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3875. callback();
  3876. }
  3877. };
  3878. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  3879. var _this = this;
  3880. if (this.isSupported) {
  3881. var targetStore;
  3882. if (url.indexOf(".babylon") !== -1) {
  3883. targetStore = "scenes";
  3884. }
  3885. else {
  3886. targetStore = "textures";
  3887. }
  3888. // Create XHR
  3889. var xhr = new XMLHttpRequest(), fileData;
  3890. xhr.open("GET", url, true);
  3891. if (useArrayBuffer) {
  3892. xhr.responseType = "arraybuffer";
  3893. }
  3894. xhr.onprogress = progressCallback;
  3895. xhr.addEventListener("load", function () {
  3896. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  3897. // Blob as response (XHR2)
  3898. //fileData = xhr.responseText;
  3899. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  3900. if (!_this.hasReachedQuota) {
  3901. // Open a transaction to the database
  3902. var transaction = _this.db.transaction([targetStore], "readwrite");
  3903. // the transaction could abort because of a QuotaExceededError error
  3904. transaction.onabort = function (event) {
  3905. try {
  3906. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3907. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3908. this.hasReachedQuota = true;
  3909. }
  3910. }
  3911. catch (ex) { }
  3912. callback(fileData);
  3913. };
  3914. transaction.oncomplete = function (event) {
  3915. callback(fileData);
  3916. };
  3917. var newFile;
  3918. if (targetStore === "scenes") {
  3919. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  3920. }
  3921. else {
  3922. newFile = { textureUrl: url, data: fileData };
  3923. }
  3924. try {
  3925. // Put the scene into the database
  3926. var addRequest = transaction.objectStore(targetStore).put(newFile);
  3927. addRequest.onsuccess = function (event) {
  3928. };
  3929. addRequest.onerror = function (event) {
  3930. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  3931. };
  3932. }
  3933. catch (ex) {
  3934. callback(fileData);
  3935. }
  3936. }
  3937. else {
  3938. callback(fileData);
  3939. }
  3940. }
  3941. else {
  3942. callback();
  3943. }
  3944. }, false);
  3945. xhr.addEventListener("error", function (event) {
  3946. BABYLON.Tools.Error("error on XHR request.");
  3947. callback();
  3948. }, false);
  3949. xhr.send();
  3950. }
  3951. else {
  3952. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3953. callback();
  3954. }
  3955. };
  3956. Database.IsUASupportingBlobStorage = true;
  3957. Database.IDBStorageEnabled = true;
  3958. Database.parseURL = function (url) {
  3959. var a = document.createElement('a');
  3960. a.href = url;
  3961. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  3962. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  3963. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  3964. return absLocation;
  3965. };
  3966. Database.ReturnFullUrlLocation = function (url) {
  3967. if (url.indexOf("http:/") === -1) {
  3968. return (Database.parseURL(window.location.href) + url);
  3969. }
  3970. else {
  3971. return url;
  3972. }
  3973. };
  3974. return Database;
  3975. })();
  3976. BABYLON.Database = Database;
  3977. })(BABYLON || (BABYLON = {}));
  3978. var BABYLON;
  3979. (function (BABYLON) {
  3980. var Internals;
  3981. (function (Internals) {
  3982. /*
  3983. * Based on jsTGALoader - Javascript loader for TGA file
  3984. * By Vincent Thibault
  3985. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  3986. */
  3987. var TGATools = (function () {
  3988. function TGATools() {
  3989. }
  3990. TGATools.GetTGAHeader = function (data) {
  3991. var offset = 0;
  3992. var header = {
  3993. id_length: data[offset++],
  3994. colormap_type: data[offset++],
  3995. image_type: data[offset++],
  3996. colormap_index: data[offset++] | data[offset++] << 8,
  3997. colormap_length: data[offset++] | data[offset++] << 8,
  3998. colormap_size: data[offset++],
  3999. origin: [
  4000. data[offset++] | data[offset++] << 8,
  4001. data[offset++] | data[offset++] << 8
  4002. ],
  4003. width: data[offset++] | data[offset++] << 8,
  4004. height: data[offset++] | data[offset++] << 8,
  4005. pixel_size: data[offset++],
  4006. flags: data[offset++]
  4007. };
  4008. return header;
  4009. };
  4010. TGATools.UploadContent = function (gl, data) {
  4011. // Not enough data to contain header ?
  4012. if (data.length < 19) {
  4013. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  4014. return;
  4015. }
  4016. // Read Header
  4017. var offset = 18;
  4018. var header = TGATools.GetTGAHeader(data);
  4019. // Assume it's a valid Targa file.
  4020. if (header.id_length + offset > data.length) {
  4021. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  4022. return;
  4023. }
  4024. // Skip not needed data
  4025. offset += header.id_length;
  4026. var use_rle = false;
  4027. var use_pal = false;
  4028. var use_rgb = false;
  4029. var use_grey = false;
  4030. // Get some informations.
  4031. switch (header.image_type) {
  4032. case TGATools._TYPE_RLE_INDEXED:
  4033. use_rle = true;
  4034. case TGATools._TYPE_INDEXED:
  4035. use_pal = true;
  4036. break;
  4037. case TGATools._TYPE_RLE_RGB:
  4038. use_rle = true;
  4039. case TGATools._TYPE_RGB:
  4040. use_rgb = true;
  4041. break;
  4042. case TGATools._TYPE_RLE_GREY:
  4043. use_rle = true;
  4044. case TGATools._TYPE_GREY:
  4045. use_grey = true;
  4046. break;
  4047. }
  4048. var pixel_data;
  4049. var numAlphaBits = header.flags & 0xf;
  4050. var pixel_size = header.pixel_size >> 3;
  4051. var pixel_total = header.width * header.height * pixel_size;
  4052. // Read palettes
  4053. var palettes;
  4054. if (use_pal) {
  4055. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  4056. }
  4057. // Read LRE
  4058. if (use_rle) {
  4059. pixel_data = new Uint8Array(pixel_total);
  4060. var c, count, i;
  4061. var localOffset = 0;
  4062. var pixels = new Uint8Array(pixel_size);
  4063. while (offset < pixel_total && localOffset < pixel_total) {
  4064. c = data[offset++];
  4065. count = (c & 0x7f) + 1;
  4066. // RLE pixels
  4067. if (c & 0x80) {
  4068. // Bind pixel tmp array
  4069. for (i = 0; i < pixel_size; ++i) {
  4070. pixels[i] = data[offset++];
  4071. }
  4072. // Copy pixel array
  4073. for (i = 0; i < count; ++i) {
  4074. pixel_data.set(pixels, localOffset + i * pixel_size);
  4075. }
  4076. localOffset += pixel_size * count;
  4077. }
  4078. else {
  4079. count *= pixel_size;
  4080. for (i = 0; i < count; ++i) {
  4081. pixel_data[localOffset + i] = data[offset++];
  4082. }
  4083. localOffset += count;
  4084. }
  4085. }
  4086. }
  4087. else {
  4088. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  4089. }
  4090. // Load to texture
  4091. var x_start, y_start, x_step, y_step, y_end, x_end;
  4092. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  4093. default:
  4094. case TGATools._ORIGIN_UL:
  4095. x_start = 0;
  4096. x_step = 1;
  4097. x_end = header.width;
  4098. y_start = 0;
  4099. y_step = 1;
  4100. y_end = header.height;
  4101. break;
  4102. case TGATools._ORIGIN_BL:
  4103. x_start = 0;
  4104. x_step = 1;
  4105. x_end = header.width;
  4106. y_start = header.height - 1;
  4107. y_step = -1;
  4108. y_end = -1;
  4109. break;
  4110. case TGATools._ORIGIN_UR:
  4111. x_start = header.width - 1;
  4112. x_step = -1;
  4113. x_end = -1;
  4114. y_start = 0;
  4115. y_step = 1;
  4116. y_end = header.height;
  4117. break;
  4118. case TGATools._ORIGIN_BR:
  4119. x_start = header.width - 1;
  4120. x_step = -1;
  4121. x_end = -1;
  4122. y_start = header.height - 1;
  4123. y_step = -1;
  4124. y_end = -1;
  4125. break;
  4126. }
  4127. // Load the specify method
  4128. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  4129. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  4130. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  4131. };
  4132. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  4133. var image = pixel_data, colormap = palettes;
  4134. var width = header.width, height = header.height;
  4135. var color, i = 0, x, y;
  4136. var imageData = new Uint8Array(width * height * 4);
  4137. for (y = y_start; y !== y_end; y += y_step) {
  4138. for (x = x_start; x !== x_end; x += x_step, i++) {
  4139. color = image[i];
  4140. imageData[(x + width * y) * 4 + 3] = 255;
  4141. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  4142. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  4143. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  4144. }
  4145. }
  4146. return imageData;
  4147. };
  4148. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  4149. var image = pixel_data;
  4150. var width = header.width, height = header.height;
  4151. var color, i = 0, x, y;
  4152. var imageData = new Uint8Array(width * height * 4);
  4153. for (y = y_start; y !== y_end; y += y_step) {
  4154. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  4155. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  4156. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  4157. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  4158. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  4159. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  4160. }
  4161. }
  4162. return imageData;
  4163. };
  4164. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  4165. var image = pixel_data;
  4166. var width = header.width, height = header.height;
  4167. var i = 0, x, y;
  4168. var imageData = new Uint8Array(width * height * 4);
  4169. for (y = y_start; y !== y_end; y += y_step) {
  4170. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  4171. imageData[(x + width * y) * 4 + 3] = 255;
  4172. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  4173. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  4174. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  4175. }
  4176. }
  4177. return imageData;
  4178. };
  4179. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  4180. var image = pixel_data;
  4181. var width = header.width, height = header.height;
  4182. var i = 0, x, y;
  4183. var imageData = new Uint8Array(width * height * 4);
  4184. for (y = y_start; y !== y_end; y += y_step) {
  4185. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  4186. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  4187. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  4188. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  4189. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  4190. }
  4191. }
  4192. return imageData;
  4193. };
  4194. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  4195. var image = pixel_data;
  4196. var width = header.width, height = header.height;
  4197. var color, i = 0, x, y;
  4198. var imageData = new Uint8Array(width * height * 4);
  4199. for (y = y_start; y !== y_end; y += y_step) {
  4200. for (x = x_start; x !== x_end; x += x_step, i++) {
  4201. color = image[i];
  4202. imageData[(x + width * y) * 4 + 0] = color;
  4203. imageData[(x + width * y) * 4 + 1] = color;
  4204. imageData[(x + width * y) * 4 + 2] = color;
  4205. imageData[(x + width * y) * 4 + 3] = 255;
  4206. }
  4207. }
  4208. return imageData;
  4209. };
  4210. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  4211. var image = pixel_data;
  4212. var width = header.width, height = header.height;
  4213. var i = 0, x, y;
  4214. var imageData = new Uint8Array(width * height * 4);
  4215. for (y = y_start; y !== y_end; y += y_step) {
  4216. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  4217. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  4218. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  4219. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  4220. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  4221. }
  4222. }
  4223. return imageData;
  4224. };
  4225. TGATools._TYPE_NO_DATA = 0;
  4226. TGATools._TYPE_INDEXED = 1;
  4227. TGATools._TYPE_RGB = 2;
  4228. TGATools._TYPE_GREY = 3;
  4229. TGATools._TYPE_RLE_INDEXED = 9;
  4230. TGATools._TYPE_RLE_RGB = 10;
  4231. TGATools._TYPE_RLE_GREY = 11;
  4232. TGATools._ORIGIN_MASK = 0x30;
  4233. TGATools._ORIGIN_SHIFT = 0x04;
  4234. TGATools._ORIGIN_BL = 0x00;
  4235. TGATools._ORIGIN_BR = 0x01;
  4236. TGATools._ORIGIN_UL = 0x02;
  4237. TGATools._ORIGIN_UR = 0x03;
  4238. return TGATools;
  4239. })();
  4240. Internals.TGATools = TGATools;
  4241. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  4242. })(BABYLON || (BABYLON = {}));
  4243. var BABYLON;
  4244. (function (BABYLON) {
  4245. var SmartArray = (function () {
  4246. function SmartArray(capacity) {
  4247. this.length = 0;
  4248. this._duplicateId = 0;
  4249. this.data = new Array(capacity);
  4250. this._id = SmartArray._GlobalId++;
  4251. }
  4252. SmartArray.prototype.push = function (value) {
  4253. this.data[this.length++] = value;
  4254. if (this.length > this.data.length) {
  4255. this.data.length *= 2;
  4256. }
  4257. if (!value.__smartArrayFlags) {
  4258. value.__smartArrayFlags = {};
  4259. }
  4260. value.__smartArrayFlags[this._id] = this._duplicateId;
  4261. };
  4262. SmartArray.prototype.pushNoDuplicate = function (value) {
  4263. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  4264. return false;
  4265. }
  4266. this.push(value);
  4267. return true;
  4268. };
  4269. SmartArray.prototype.sort = function (compareFn) {
  4270. this.data.sort(compareFn);
  4271. };
  4272. SmartArray.prototype.reset = function () {
  4273. this.length = 0;
  4274. this._duplicateId++;
  4275. };
  4276. SmartArray.prototype.concat = function (array) {
  4277. if (array.length === 0) {
  4278. return;
  4279. }
  4280. if (this.length + array.length > this.data.length) {
  4281. this.data.length = (this.length + array.length) * 2;
  4282. }
  4283. for (var index = 0; index < array.length; index++) {
  4284. this.data[this.length++] = (array.data || array)[index];
  4285. }
  4286. };
  4287. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  4288. if (array.length === 0) {
  4289. return;
  4290. }
  4291. if (this.length + array.length > this.data.length) {
  4292. this.data.length = (this.length + array.length) * 2;
  4293. }
  4294. for (var index = 0; index < array.length; index++) {
  4295. var item = (array.data || array)[index];
  4296. this.pushNoDuplicate(item);
  4297. }
  4298. };
  4299. SmartArray.prototype.indexOf = function (value) {
  4300. var position = this.data.indexOf(value);
  4301. if (position >= this.length) {
  4302. return -1;
  4303. }
  4304. return position;
  4305. };
  4306. // Statics
  4307. SmartArray._GlobalId = 0;
  4308. return SmartArray;
  4309. })();
  4310. BABYLON.SmartArray = SmartArray;
  4311. })(BABYLON || (BABYLON = {}));
  4312. var BABYLON;
  4313. (function (BABYLON) {
  4314. /**
  4315. * This class implement a typical dictionary using a string as key and the generic type T as value.
  4316. * The underlying implementation relies on an associative array to ensure the best performances.
  4317. * The value can be anything including 'null' but except 'undefined'
  4318. */
  4319. var StringDictionary = (function () {
  4320. function StringDictionary() {
  4321. this._count = 0;
  4322. this._data = {};
  4323. }
  4324. /**
  4325. * Get a value based from its key
  4326. * @param key the given key to get the matching value from
  4327. * @return the value if found, otherwise undefined is returned
  4328. */
  4329. StringDictionary.prototype.get = function (key) {
  4330. var val = this._data[key];
  4331. if (val !== undefined) {
  4332. return val;
  4333. }
  4334. return undefined;
  4335. };
  4336. /**
  4337. * Get a value from its key or add it if it doesn't exist.
  4338. * This method will ensure you that a given key/data will be present in the dictionary.
  4339. * @param key the given key to get the matching value from
  4340. * @param factory the factory that will create the value if the key is not present in the dictionary.
  4341. * The factory will only be invoked if there's no data for the given key.
  4342. * @return the value corresponding to the key.
  4343. */
  4344. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  4345. var val = this.get(key);
  4346. if (val !== undefined) {
  4347. return val;
  4348. }
  4349. val = factory(key);
  4350. if (val) {
  4351. this.add(key, val);
  4352. }
  4353. return val;
  4354. };
  4355. /**
  4356. * Get a value from its key if present in the dictionary otherwise add it
  4357. * @param key the key to get the value from
  4358. * @param val if there's no such key/value pair in the dictionary add it with this value
  4359. * @return the value corresponding to the key
  4360. */
  4361. StringDictionary.prototype.getOrAdd = function (key, val) {
  4362. var curVal = this.get(key);
  4363. if (curVal !== undefined) {
  4364. return curVal;
  4365. }
  4366. this.add(key, val);
  4367. return val;
  4368. };
  4369. /**
  4370. * Check if there's a given key in the dictionary
  4371. * @param key the key to check for
  4372. * @return true if the key is present, false otherwise
  4373. */
  4374. StringDictionary.prototype.contains = function (key) {
  4375. return this._data[key] !== undefined;
  4376. };
  4377. /**
  4378. * Add a new key and its corresponding value
  4379. * @param key the key to add
  4380. * @param value the value corresponding to the key
  4381. * @return true if the operation completed successfully, false if we couldn't insert the key/value because there was already this key in the dictionary
  4382. */
  4383. StringDictionary.prototype.add = function (key, value) {
  4384. if (this._data[key] !== undefined) {
  4385. return false;
  4386. }
  4387. this._data[key] = value;
  4388. ++this._count;
  4389. return true;
  4390. };
  4391. StringDictionary.prototype.set = function (key, value) {
  4392. if (this._data[key] === undefined) {
  4393. return false;
  4394. }
  4395. this._data[key] = value;
  4396. return true;
  4397. };
  4398. /**
  4399. * Remove a key/value from the dictionary.
  4400. * @param key the key to remove
  4401. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  4402. */
  4403. StringDictionary.prototype.remove = function (key) {
  4404. if (this.contains(key)) {
  4405. delete this._data[key];
  4406. --this._count;
  4407. return true;
  4408. }
  4409. return false;
  4410. };
  4411. /**
  4412. * Clear the whole content of the dictionary
  4413. */
  4414. StringDictionary.prototype.clear = function () {
  4415. this._data = {};
  4416. this._count = 0;
  4417. };
  4418. Object.defineProperty(StringDictionary.prototype, "count", {
  4419. get: function () {
  4420. return this._count;
  4421. },
  4422. enumerable: true,
  4423. configurable: true
  4424. });
  4425. /**
  4426. * Execute a callback on each key/val of the dictionary.
  4427. * Note that you can remove any element in this dictionary in the callback implementation
  4428. * @param callback the callback to execute on a given key/value pair
  4429. */
  4430. StringDictionary.prototype.forEach = function (callback) {
  4431. for (var cur in this._data) {
  4432. var val = this._data[cur];
  4433. callback(cur, val);
  4434. }
  4435. };
  4436. /**
  4437. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  4438. * If the callback returns null or undefined the method will iterate to the next key/value pair
  4439. * Note that you can remove any element in this dictionary in the callback implementation
  4440. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  4441. */
  4442. StringDictionary.prototype.first = function (callback) {
  4443. for (var cur in this._data) {
  4444. var val = this._data[cur];
  4445. var res = callback(cur, val);
  4446. if (res) {
  4447. return res;
  4448. }
  4449. }
  4450. return null;
  4451. };
  4452. return StringDictionary;
  4453. })();
  4454. BABYLON.StringDictionary = StringDictionary;
  4455. })(BABYLON || (BABYLON = {}));
  4456. var BABYLON;
  4457. (function (BABYLON) {
  4458. // Screenshots
  4459. var screenshotCanvas;
  4460. var cloneValue = function (source, destinationObject) {
  4461. if (!source)
  4462. return null;
  4463. if (source instanceof BABYLON.Mesh) {
  4464. return null;
  4465. }
  4466. if (source instanceof BABYLON.SubMesh) {
  4467. return source.clone(destinationObject);
  4468. }
  4469. else if (source.clone) {
  4470. return source.clone();
  4471. }
  4472. return null;
  4473. };
  4474. var Tools = (function () {
  4475. function Tools() {
  4476. }
  4477. Tools.Instantiate = function (className) {
  4478. var arr = className.split(".");
  4479. var fn = (window || this);
  4480. for (var i = 0, len = arr.length; i < len; i++) {
  4481. fn = fn[arr[i]];
  4482. }
  4483. if (typeof fn !== "function") {
  4484. return null;
  4485. }
  4486. return fn;
  4487. };
  4488. Tools.SetImmediate = function (action) {
  4489. if (window.setImmediate) {
  4490. window.setImmediate(action);
  4491. }
  4492. else {
  4493. setTimeout(action, 1);
  4494. }
  4495. };
  4496. Tools.IsExponentOfTwo = function (value) {
  4497. var count = 1;
  4498. do {
  4499. count *= 2;
  4500. } while (count < value);
  4501. return count === value;
  4502. };
  4503. Tools.GetExponentOfTwo = function (value, max) {
  4504. var count = 1;
  4505. do {
  4506. count *= 2;
  4507. } while (count < value);
  4508. if (count > max)
  4509. count = max;
  4510. return count;
  4511. };
  4512. Tools.GetFilename = function (path) {
  4513. var index = path.lastIndexOf("/");
  4514. if (index < 0)
  4515. return path;
  4516. return path.substring(index + 1);
  4517. };
  4518. Tools.GetDOMTextContent = function (element) {
  4519. var result = "";
  4520. var child = element.firstChild;
  4521. while (child) {
  4522. if (child.nodeType === 3) {
  4523. result += child.textContent;
  4524. }
  4525. child = child.nextSibling;
  4526. }
  4527. return result;
  4528. };
  4529. Tools.ToDegrees = function (angle) {
  4530. return angle * 180 / Math.PI;
  4531. };
  4532. Tools.ToRadians = function (angle) {
  4533. return angle * Math.PI / 180;
  4534. };
  4535. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  4536. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  4537. var output = "";
  4538. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  4539. var i = 0;
  4540. var bytes = new Uint8Array(buffer);
  4541. while (i < bytes.length) {
  4542. chr1 = bytes[i++];
  4543. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  4544. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  4545. enc1 = chr1 >> 2;
  4546. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  4547. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  4548. enc4 = chr3 & 63;
  4549. if (isNaN(chr2)) {
  4550. enc3 = enc4 = 64;
  4551. }
  4552. else if (isNaN(chr3)) {
  4553. enc4 = 64;
  4554. }
  4555. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  4556. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  4557. }
  4558. return "data:image/png;base64," + output;
  4559. };
  4560. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  4561. if (bias === void 0) { bias = null; }
  4562. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4563. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4564. for (var index = indexStart; index < indexStart + indexCount; index++) {
  4565. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  4566. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4567. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4568. }
  4569. if (bias) {
  4570. minimum.x -= minimum.x * bias.x + bias.y;
  4571. minimum.y -= minimum.y * bias.x + bias.y;
  4572. minimum.z -= minimum.z * bias.x + bias.y;
  4573. maximum.x += maximum.x * bias.x + bias.y;
  4574. maximum.y += maximum.y * bias.x + bias.y;
  4575. maximum.z += maximum.z * bias.x + bias.y;
  4576. }
  4577. return {
  4578. minimum: minimum,
  4579. maximum: maximum
  4580. };
  4581. };
  4582. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  4583. if (bias === void 0) { bias = null; }
  4584. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4585. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4586. if (!stride) {
  4587. stride = 3;
  4588. }
  4589. for (var index = start; index < start + count; index++) {
  4590. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  4591. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4592. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4593. }
  4594. if (bias) {
  4595. minimum.x -= minimum.x * bias.x + bias.y;
  4596. minimum.y -= minimum.y * bias.x + bias.y;
  4597. minimum.z -= minimum.z * bias.x + bias.y;
  4598. maximum.x += maximum.x * bias.x + bias.y;
  4599. maximum.y += maximum.y * bias.x + bias.y;
  4600. maximum.z += maximum.z * bias.x + bias.y;
  4601. }
  4602. return {
  4603. minimum: minimum,
  4604. maximum: maximum
  4605. };
  4606. };
  4607. Tools.Vector2ArrayFeeder = function (array) {
  4608. return function (index) {
  4609. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  4610. var length = isFloatArray ? array.length / 2 : array.length;
  4611. if (index >= length) {
  4612. return null;
  4613. }
  4614. if (isFloatArray) {
  4615. var fa = array;
  4616. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  4617. }
  4618. var a = array;
  4619. return a[index];
  4620. };
  4621. };
  4622. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  4623. if (bias === void 0) { bias = null; }
  4624. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  4625. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  4626. var i = 0;
  4627. var cur = feeder(i++);
  4628. while (cur) {
  4629. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  4630. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  4631. cur = feeder(i++);
  4632. }
  4633. if (bias) {
  4634. minimum.x -= minimum.x * bias.x + bias.y;
  4635. minimum.y -= minimum.y * bias.x + bias.y;
  4636. maximum.x += maximum.x * bias.x + bias.y;
  4637. maximum.y += maximum.y * bias.x + bias.y;
  4638. }
  4639. return {
  4640. minimum: minimum,
  4641. maximum: maximum
  4642. };
  4643. };
  4644. Tools.MakeArray = function (obj, allowsNullUndefined) {
  4645. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  4646. return undefined;
  4647. return Array.isArray(obj) ? obj : [obj];
  4648. };
  4649. // Misc.
  4650. Tools.GetPointerPrefix = function () {
  4651. var eventPrefix = "pointer";
  4652. // Check if pointer events are supported
  4653. if (!window.PointerEvent && !navigator.pointerEnabled) {
  4654. eventPrefix = "mouse";
  4655. }
  4656. return eventPrefix;
  4657. };
  4658. Tools.QueueNewFrame = function (func) {
  4659. if (window.requestAnimationFrame)
  4660. window.requestAnimationFrame(func);
  4661. else if (window.msRequestAnimationFrame)
  4662. window.msRequestAnimationFrame(func);
  4663. else if (window.webkitRequestAnimationFrame)
  4664. window.webkitRequestAnimationFrame(func);
  4665. else if (window.mozRequestAnimationFrame)
  4666. window.mozRequestAnimationFrame(func);
  4667. else if (window.oRequestAnimationFrame)
  4668. window.oRequestAnimationFrame(func);
  4669. else {
  4670. window.setTimeout(func, 16);
  4671. }
  4672. };
  4673. Tools.RequestFullscreen = function (element, options) {
  4674. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  4675. if (!requestFunction)
  4676. return;
  4677. requestFunction.call(element, options);
  4678. };
  4679. Tools.ExitFullscreen = function () {
  4680. if (document.exitFullscreen) {
  4681. document.exitFullscreen();
  4682. }
  4683. else if (document.mozCancelFullScreen) {
  4684. document.mozCancelFullScreen();
  4685. }
  4686. else if (document.webkitCancelFullScreen) {
  4687. document.webkitCancelFullScreen();
  4688. }
  4689. else if (document.msCancelFullScreen) {
  4690. document.msCancelFullScreen();
  4691. }
  4692. };
  4693. Tools.SetCorsBehavior = function (url, img) {
  4694. if (Tools.CorsBehavior) {
  4695. switch (typeof (Tools.CorsBehavior)) {
  4696. case "function":
  4697. var result = Tools.CorsBehavior(url);
  4698. if (result) {
  4699. return result;
  4700. }
  4701. break;
  4702. case "string":
  4703. default:
  4704. img.crossOrigin = Tools.CorsBehavior;
  4705. break;
  4706. }
  4707. }
  4708. };
  4709. // External files
  4710. Tools.CleanUrl = function (url) {
  4711. url = url.replace(/#/mg, "%23");
  4712. return url;
  4713. };
  4714. Tools.LoadImage = function (url, onload, onerror, database) {
  4715. if (url instanceof ArrayBuffer) {
  4716. url = Tools.EncodeArrayBufferTobase64(url);
  4717. }
  4718. url = Tools.CleanUrl(url);
  4719. var img = new Image();
  4720. if (url.substr(0, 5) !== "data:") {
  4721. Tools.SetCorsBehavior(url, img);
  4722. }
  4723. img.onload = function () {
  4724. onload(img);
  4725. };
  4726. img.onerror = function (err) {
  4727. Tools.Error("Error while trying to load texture: " + url);
  4728. if (Tools.UseFallbackTexture) {
  4729. img.src = "data:image/jpg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD/4QBmRXhpZgAATU0AKgAAAAgABAEaAAUAAAABAAAAPgEbAAUAAAABAAAARgEoAAMAAAABAAIAAAExAAIAAAAQAAAATgAAAAAAAABgAAAAAQAAAGAAAAABcGFpbnQubmV0IDQuMC41AP/bAEMABAIDAwMCBAMDAwQEBAQFCQYFBQUFCwgIBgkNCw0NDQsMDA4QFBEODxMPDAwSGBITFRYXFxcOERkbGRYaFBYXFv/bAEMBBAQEBQUFCgYGChYPDA8WFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFv/AABEIAQABAAMBIgACEQEDEQH/xAAfAAABBQEBAQEBAQAAAAAAAAAAAQIDBAUGBwgJCgv/xAC1EAACAQMDAgQDBQUEBAAAAX0BAgMABBEFEiExQQYTUWEHInEUMoGRoQgjQrHBFVLR8CQzYnKCCQoWFxgZGiUmJygpKjQ1Njc4OTpDREVGR0hJSlNUVVZXWFlaY2RlZmdoaWpzdHV2d3h5eoOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4eLj5OXm5+jp6vHy8/T19vf4+fr/xAAfAQADAQEBAQEBAQEBAAAAAAAAAQIDBAUGBwgJCgv/xAC1EQACAQIEBAMEBwUEBAABAncAAQIDEQQFITEGEkFRB2FxEyIygQgUQpGhscEJIzNS8BVictEKFiQ04SXxFxgZGiYnKCkqNTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqCg4SFhoeIiYqSk5SVlpeYmZqio6Slpqeoqaqys7S1tre4ubrCw8TFxsfIycrS09TV1tfY2dri4+Tl5ufo6ery8/T19vf4+fr/2gAMAwEAAhEDEQA/APH6KKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76P//Z";
  4730. onload(img);
  4731. }
  4732. else {
  4733. onerror();
  4734. }
  4735. };
  4736. var noIndexedDB = function () {
  4737. img.src = url;
  4738. };
  4739. var loadFromIndexedDB = function () {
  4740. database.loadImageFromDB(url, img);
  4741. };
  4742. //ANY database to do!
  4743. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  4744. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4745. }
  4746. else {
  4747. if (url.indexOf("file:") === -1) {
  4748. noIndexedDB();
  4749. }
  4750. else {
  4751. try {
  4752. var textureName = url.substring(5).toLowerCase();
  4753. var blobURL;
  4754. try {
  4755. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  4756. }
  4757. catch (ex) {
  4758. // Chrome doesn't support oneTimeOnly parameter
  4759. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  4760. }
  4761. img.src = blobURL;
  4762. }
  4763. catch (e) {
  4764. img.src = null;
  4765. }
  4766. }
  4767. }
  4768. return img;
  4769. };
  4770. //ANY
  4771. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  4772. url = Tools.CleanUrl(url);
  4773. var noIndexedDB = function () {
  4774. var request = new XMLHttpRequest();
  4775. var loadUrl = Tools.BaseUrl + url;
  4776. request.open('GET', loadUrl, true);
  4777. if (useArrayBuffer) {
  4778. request.responseType = "arraybuffer";
  4779. }
  4780. request.onprogress = progressCallBack;
  4781. request.onreadystatechange = function () {
  4782. if (request.readyState === 4) {
  4783. request.onreadystatechange = null; //some browsers have issues where onreadystatechange can be called multiple times with the same value
  4784. if (request.status >= 200 && request.status < 300 || (navigator.isCocoonJS && (request.status === 0))) {
  4785. callback(!useArrayBuffer ? request.responseText : request.response);
  4786. }
  4787. else {
  4788. if (onError) {
  4789. onError();
  4790. }
  4791. else {
  4792. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  4793. }
  4794. }
  4795. }
  4796. };
  4797. request.send(null);
  4798. };
  4799. var loadFromIndexedDB = function () {
  4800. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  4801. };
  4802. if (url.indexOf("file:") !== -1) {
  4803. var fileName = url.substring(5).toLowerCase();
  4804. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, useArrayBuffer);
  4805. }
  4806. else {
  4807. // Caching all files
  4808. if (database && database.enableSceneOffline) {
  4809. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4810. }
  4811. else {
  4812. noIndexedDB();
  4813. }
  4814. }
  4815. };
  4816. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  4817. var reader = new FileReader();
  4818. reader.onload = function (e) {
  4819. //target doesn't have result from ts 1.3
  4820. callback(e.target['result']);
  4821. };
  4822. reader.onprogress = progressCallback;
  4823. reader.readAsDataURL(fileToLoad);
  4824. };
  4825. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  4826. var reader = new FileReader();
  4827. reader.onerror = function (e) {
  4828. Tools.Log("Error while reading file: " + fileToLoad.name);
  4829. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  4830. };
  4831. reader.onload = function (e) {
  4832. //target doesn't have result from ts 1.3
  4833. callback(e.target['result']);
  4834. };
  4835. reader.onprogress = progressCallBack;
  4836. if (!useArrayBuffer) {
  4837. // Asynchronous read
  4838. reader.readAsText(fileToLoad);
  4839. }
  4840. else {
  4841. reader.readAsArrayBuffer(fileToLoad);
  4842. }
  4843. };
  4844. //returns a downloadable url to a file content.
  4845. Tools.FileAsURL = function (content) {
  4846. var fileBlob = new Blob([content]);
  4847. var url = window.URL || window.webkitURL;
  4848. var link = url.createObjectURL(fileBlob);
  4849. return link;
  4850. };
  4851. // Misc.
  4852. Tools.Format = function (value, decimals) {
  4853. if (decimals === void 0) { decimals = 2; }
  4854. return value.toFixed(decimals);
  4855. };
  4856. Tools.CheckExtends = function (v, min, max) {
  4857. if (v.x < min.x)
  4858. min.x = v.x;
  4859. if (v.y < min.y)
  4860. min.y = v.y;
  4861. if (v.z < min.z)
  4862. min.z = v.z;
  4863. if (v.x > max.x)
  4864. max.x = v.x;
  4865. if (v.y > max.y)
  4866. max.y = v.y;
  4867. if (v.z > max.z)
  4868. max.z = v.z;
  4869. };
  4870. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  4871. for (var prop in source) {
  4872. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  4873. continue;
  4874. }
  4875. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  4876. continue;
  4877. }
  4878. var sourceValue = source[prop];
  4879. var typeOfSourceValue = typeof sourceValue;
  4880. if (typeOfSourceValue === "function") {
  4881. continue;
  4882. }
  4883. if (typeOfSourceValue === "object") {
  4884. if (sourceValue instanceof Array) {
  4885. destination[prop] = [];
  4886. if (sourceValue.length > 0) {
  4887. if (typeof sourceValue[0] == "object") {
  4888. for (var index = 0; index < sourceValue.length; index++) {
  4889. var clonedValue = cloneValue(sourceValue[index], destination);
  4890. if (destination[prop].indexOf(clonedValue) === -1) {
  4891. destination[prop].push(clonedValue);
  4892. }
  4893. }
  4894. }
  4895. else {
  4896. destination[prop] = sourceValue.slice(0);
  4897. }
  4898. }
  4899. }
  4900. else {
  4901. destination[prop] = cloneValue(sourceValue, destination);
  4902. }
  4903. }
  4904. else {
  4905. destination[prop] = sourceValue;
  4906. }
  4907. }
  4908. };
  4909. Tools.IsEmpty = function (obj) {
  4910. for (var i in obj) {
  4911. return false;
  4912. }
  4913. return true;
  4914. };
  4915. Tools.RegisterTopRootEvents = function (events) {
  4916. for (var index = 0; index < events.length; index++) {
  4917. var event = events[index];
  4918. window.addEventListener(event.name, event.handler, false);
  4919. try {
  4920. if (window.parent) {
  4921. window.parent.addEventListener(event.name, event.handler, false);
  4922. }
  4923. }
  4924. catch (e) {
  4925. }
  4926. }
  4927. };
  4928. Tools.UnregisterTopRootEvents = function (events) {
  4929. for (var index = 0; index < events.length; index++) {
  4930. var event = events[index];
  4931. window.removeEventListener(event.name, event.handler);
  4932. try {
  4933. if (window.parent) {
  4934. window.parent.removeEventListener(event.name, event.handler);
  4935. }
  4936. }
  4937. catch (e) {
  4938. }
  4939. }
  4940. };
  4941. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType) {
  4942. if (mimeType === void 0) { mimeType = "image/png"; }
  4943. // Read the contents of the framebuffer
  4944. var numberOfChannelsByLine = width * 4;
  4945. var halfHeight = height / 2;
  4946. //Reading datas from WebGL
  4947. var data = engine.readPixels(0, 0, width, height);
  4948. //To flip image on Y axis.
  4949. for (var i = 0; i < halfHeight; i++) {
  4950. for (var j = 0; j < numberOfChannelsByLine; j++) {
  4951. var currentCell = j + i * numberOfChannelsByLine;
  4952. var targetLine = height - i - 1;
  4953. var targetCell = j + targetLine * numberOfChannelsByLine;
  4954. var temp = data[currentCell];
  4955. data[currentCell] = data[targetCell];
  4956. data[targetCell] = temp;
  4957. }
  4958. }
  4959. // Create a 2D canvas to store the result
  4960. if (!screenshotCanvas) {
  4961. screenshotCanvas = document.createElement('canvas');
  4962. }
  4963. screenshotCanvas.width = width;
  4964. screenshotCanvas.height = height;
  4965. var context = screenshotCanvas.getContext('2d');
  4966. // Copy the pixels to a 2D canvas
  4967. var imageData = context.createImageData(width, height);
  4968. //cast is due to ts error in lib.d.ts, see here - https://github.com/Microsoft/TypeScript/issues/949
  4969. var castData = imageData.data;
  4970. castData.set(data);
  4971. context.putImageData(imageData, 0, 0);
  4972. var base64Image = screenshotCanvas.toDataURL(mimeType);
  4973. if (successCallback) {
  4974. successCallback(base64Image);
  4975. }
  4976. else {
  4977. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  4978. if (("download" in document.createElement("a"))) {
  4979. var a = window.document.createElement("a");
  4980. a.href = base64Image;
  4981. var date = new Date();
  4982. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  4983. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  4984. window.document.body.appendChild(a);
  4985. a.addEventListener("click", function () {
  4986. a.parentElement.removeChild(a);
  4987. });
  4988. a.click();
  4989. }
  4990. else {
  4991. var newWindow = window.open("");
  4992. var img = newWindow.document.createElement("img");
  4993. img.src = base64Image;
  4994. newWindow.document.body.appendChild(img);
  4995. }
  4996. }
  4997. };
  4998. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  4999. if (mimeType === void 0) { mimeType = "image/png"; }
  5000. var width;
  5001. var height;
  5002. //If a precision value is specified
  5003. if (size.precision) {
  5004. width = Math.round(engine.getRenderWidth() * size.precision);
  5005. height = Math.round(width / engine.getAspectRatio(camera));
  5006. size = { width: width, height: height };
  5007. }
  5008. else if (size.width && size.height) {
  5009. width = size.width;
  5010. height = size.height;
  5011. }
  5012. else if (size.width && !size.height) {
  5013. width = size.width;
  5014. height = Math.round(width / engine.getAspectRatio(camera));
  5015. size = { width: width, height: height };
  5016. }
  5017. else if (size.height && !size.width) {
  5018. height = size.height;
  5019. width = Math.round(height * engine.getAspectRatio(camera));
  5020. size = { width: width, height: height };
  5021. }
  5022. else if (!isNaN(size)) {
  5023. height = size;
  5024. width = size;
  5025. }
  5026. else {
  5027. Tools.Error("Invalid 'size' parameter !");
  5028. return;
  5029. }
  5030. var scene = camera.getScene();
  5031. var previousCamera = null;
  5032. if (scene.activeCamera !== camera) {
  5033. previousCamera = scene.activeCamera;
  5034. scene.activeCamera = camera;
  5035. }
  5036. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  5037. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false);
  5038. texture.renderList = scene.meshes;
  5039. texture.onAfterRenderObservable.add(function () {
  5040. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType);
  5041. });
  5042. scene.incrementRenderId();
  5043. scene.resetCachedMaterial();
  5044. texture.render(true);
  5045. texture.dispose();
  5046. if (previousCamera) {
  5047. scene.activeCamera = previousCamera;
  5048. }
  5049. camera.getProjectionMatrix(true); // Force cache refresh;
  5050. };
  5051. // XHR response validator for local file scenario
  5052. Tools.ValidateXHRData = function (xhr, dataType) {
  5053. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  5054. if (dataType === void 0) { dataType = 7; }
  5055. try {
  5056. if (dataType & 1) {
  5057. if (xhr.responseText && xhr.responseText.length > 0) {
  5058. return true;
  5059. }
  5060. else if (dataType === 1) {
  5061. return false;
  5062. }
  5063. }
  5064. if (dataType & 2) {
  5065. // Check header width and height since there is no "TGA" magic number
  5066. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  5067. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  5068. return true;
  5069. }
  5070. else if (dataType === 2) {
  5071. return false;
  5072. }
  5073. }
  5074. if (dataType & 4) {
  5075. // Check for the "DDS" magic number
  5076. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  5077. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  5078. return true;
  5079. }
  5080. else {
  5081. return false;
  5082. }
  5083. }
  5084. }
  5085. catch (e) {
  5086. }
  5087. return false;
  5088. };
  5089. Object.defineProperty(Tools, "NoneLogLevel", {
  5090. get: function () {
  5091. return Tools._NoneLogLevel;
  5092. },
  5093. enumerable: true,
  5094. configurable: true
  5095. });
  5096. Object.defineProperty(Tools, "MessageLogLevel", {
  5097. get: function () {
  5098. return Tools._MessageLogLevel;
  5099. },
  5100. enumerable: true,
  5101. configurable: true
  5102. });
  5103. Object.defineProperty(Tools, "WarningLogLevel", {
  5104. get: function () {
  5105. return Tools._WarningLogLevel;
  5106. },
  5107. enumerable: true,
  5108. configurable: true
  5109. });
  5110. Object.defineProperty(Tools, "ErrorLogLevel", {
  5111. get: function () {
  5112. return Tools._ErrorLogLevel;
  5113. },
  5114. enumerable: true,
  5115. configurable: true
  5116. });
  5117. Object.defineProperty(Tools, "AllLogLevel", {
  5118. get: function () {
  5119. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  5120. },
  5121. enumerable: true,
  5122. configurable: true
  5123. });
  5124. Tools._AddLogEntry = function (entry) {
  5125. Tools._LogCache = entry + Tools._LogCache;
  5126. if (Tools.OnNewCacheEntry) {
  5127. Tools.OnNewCacheEntry(entry);
  5128. }
  5129. };
  5130. Tools._FormatMessage = function (message) {
  5131. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  5132. var date = new Date();
  5133. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  5134. };
  5135. Tools._LogDisabled = function (message) {
  5136. // nothing to do
  5137. };
  5138. Tools._LogEnabled = function (message) {
  5139. var formattedMessage = Tools._FormatMessage(message);
  5140. console.log("BJS - " + formattedMessage);
  5141. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  5142. Tools._AddLogEntry(entry);
  5143. };
  5144. Tools._WarnDisabled = function (message) {
  5145. // nothing to do
  5146. };
  5147. Tools._WarnEnabled = function (message) {
  5148. var formattedMessage = Tools._FormatMessage(message);
  5149. console.warn("BJS - " + formattedMessage);
  5150. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  5151. Tools._AddLogEntry(entry);
  5152. };
  5153. Tools._ErrorDisabled = function (message) {
  5154. // nothing to do
  5155. };
  5156. Tools._ErrorEnabled = function (message) {
  5157. Tools.errorsCount++;
  5158. var formattedMessage = Tools._FormatMessage(message);
  5159. console.error("BJS - " + formattedMessage);
  5160. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  5161. Tools._AddLogEntry(entry);
  5162. };
  5163. Object.defineProperty(Tools, "LogCache", {
  5164. get: function () {
  5165. return Tools._LogCache;
  5166. },
  5167. enumerable: true,
  5168. configurable: true
  5169. });
  5170. Tools.ClearLogCache = function () {
  5171. Tools._LogCache = "";
  5172. Tools.errorsCount = 0;
  5173. };
  5174. Object.defineProperty(Tools, "LogLevels", {
  5175. set: function (level) {
  5176. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  5177. Tools.Log = Tools._LogEnabled;
  5178. }
  5179. else {
  5180. Tools.Log = Tools._LogDisabled;
  5181. }
  5182. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  5183. Tools.Warn = Tools._WarnEnabled;
  5184. }
  5185. else {
  5186. Tools.Warn = Tools._WarnDisabled;
  5187. }
  5188. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  5189. Tools.Error = Tools._ErrorEnabled;
  5190. }
  5191. else {
  5192. Tools.Error = Tools._ErrorDisabled;
  5193. }
  5194. },
  5195. enumerable: true,
  5196. configurable: true
  5197. });
  5198. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  5199. get: function () {
  5200. return Tools._PerformanceNoneLogLevel;
  5201. },
  5202. enumerable: true,
  5203. configurable: true
  5204. });
  5205. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  5206. get: function () {
  5207. return Tools._PerformanceUserMarkLogLevel;
  5208. },
  5209. enumerable: true,
  5210. configurable: true
  5211. });
  5212. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  5213. get: function () {
  5214. return Tools._PerformanceConsoleLogLevel;
  5215. },
  5216. enumerable: true,
  5217. configurable: true
  5218. });
  5219. Object.defineProperty(Tools, "PerformanceLogLevel", {
  5220. set: function (level) {
  5221. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  5222. Tools.StartPerformanceCounter = Tools._StartUserMark;
  5223. Tools.EndPerformanceCounter = Tools._EndUserMark;
  5224. return;
  5225. }
  5226. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  5227. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  5228. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  5229. return;
  5230. }
  5231. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  5232. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  5233. },
  5234. enumerable: true,
  5235. configurable: true
  5236. });
  5237. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  5238. };
  5239. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  5240. };
  5241. Tools._StartUserMark = function (counterName, condition) {
  5242. if (condition === void 0) { condition = true; }
  5243. if (!condition || !Tools._performance.mark) {
  5244. return;
  5245. }
  5246. Tools._performance.mark(counterName + "-Begin");
  5247. };
  5248. Tools._EndUserMark = function (counterName, condition) {
  5249. if (condition === void 0) { condition = true; }
  5250. if (!condition || !Tools._performance.mark) {
  5251. return;
  5252. }
  5253. Tools._performance.mark(counterName + "-End");
  5254. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  5255. };
  5256. Tools._StartPerformanceConsole = function (counterName, condition) {
  5257. if (condition === void 0) { condition = true; }
  5258. if (!condition) {
  5259. return;
  5260. }
  5261. Tools._StartUserMark(counterName, condition);
  5262. if (console.time) {
  5263. console.time(counterName);
  5264. }
  5265. };
  5266. Tools._EndPerformanceConsole = function (counterName, condition) {
  5267. if (condition === void 0) { condition = true; }
  5268. if (!condition) {
  5269. return;
  5270. }
  5271. Tools._EndUserMark(counterName, condition);
  5272. if (console.time) {
  5273. console.timeEnd(counterName);
  5274. }
  5275. };
  5276. Object.defineProperty(Tools, "Now", {
  5277. get: function () {
  5278. if (window.performance && window.performance.now) {
  5279. return window.performance.now();
  5280. }
  5281. return new Date().getTime();
  5282. },
  5283. enumerable: true,
  5284. configurable: true
  5285. });
  5286. /**
  5287. * This method will return the name of the class used to create the instance of the given object.
  5288. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  5289. * @param object the object to get the class name from
  5290. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  5291. */
  5292. Tools.getClassName = function (object, isType) {
  5293. if (isType === void 0) { isType = false; }
  5294. var name = null;
  5295. if (!isType && object.getClassName) {
  5296. name = object.getClassName();
  5297. }
  5298. else {
  5299. if (object instanceof Object) {
  5300. var classObj = isType ? object : Object.getPrototypeOf(object);
  5301. name = classObj.constructor["__bjsclassName__"];
  5302. }
  5303. if (!name) {
  5304. name = typeof object;
  5305. }
  5306. }
  5307. return name;
  5308. };
  5309. Tools.first = function (array, predicate) {
  5310. for (var _i = 0; _i < array.length; _i++) {
  5311. var el = array[_i];
  5312. if (predicate(el)) {
  5313. return el;
  5314. }
  5315. }
  5316. };
  5317. /**
  5318. * This method can be used with hashCodeFromStream when your input is an array of values that are either: number, string, boolean or custom type implementing the getHashCode():number method.
  5319. * @param array
  5320. */
  5321. Tools.arrayOrStringFeeder = function (array) {
  5322. return function (index) {
  5323. if (index >= array.length) {
  5324. return null;
  5325. }
  5326. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  5327. if (val && val.getHashCode) {
  5328. val = val.getHashCode();
  5329. }
  5330. if (typeof val === "string") {
  5331. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  5332. }
  5333. return val;
  5334. };
  5335. };
  5336. /**
  5337. * Compute the hashCode of a stream of number
  5338. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  5339. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  5340. * @return the hash code computed
  5341. */
  5342. Tools.hashCodeFromStream = function (feeder) {
  5343. // Based from here: http://stackoverflow.com/a/7616484/802124
  5344. var hash = 0;
  5345. var index = 0;
  5346. var chr = feeder(index++);
  5347. while (chr != null) {
  5348. hash = ((hash << 5) - hash) + chr;
  5349. hash |= 0; // Convert to 32bit integer
  5350. chr = feeder(index++);
  5351. }
  5352. return hash;
  5353. };
  5354. Tools.BaseUrl = "";
  5355. Tools.CorsBehavior = "anonymous";
  5356. Tools.UseFallbackTexture = true;
  5357. // Logs
  5358. Tools._NoneLogLevel = 0;
  5359. Tools._MessageLogLevel = 1;
  5360. Tools._WarningLogLevel = 2;
  5361. Tools._ErrorLogLevel = 4;
  5362. Tools._LogCache = "";
  5363. Tools.errorsCount = 0;
  5364. Tools.Log = Tools._LogEnabled;
  5365. Tools.Warn = Tools._WarnEnabled;
  5366. Tools.Error = Tools._ErrorEnabled;
  5367. // Performances
  5368. Tools._PerformanceNoneLogLevel = 0;
  5369. Tools._PerformanceUserMarkLogLevel = 1;
  5370. Tools._PerformanceConsoleLogLevel = 2;
  5371. Tools._performance = window.performance;
  5372. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  5373. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  5374. return Tools;
  5375. })();
  5376. BABYLON.Tools = Tools;
  5377. /**
  5378. * This class is used to track a performance counter which is number based.
  5379. * The user has access to many properties which give statistics of different nature
  5380. *
  5381. * The implementer can track two kinds of Performance Counter: time and count
  5382. * For time you can optionally call fetchNewFrame() to notify the start of a new frame to monitor, then call beginMonitoring() to start and endMonitoring() to record the lapsed time. endMonitoring takes a newFrame parameter for you to specify if the monitored time should be set for a new frame or accumulated to the current frame being monitored.
  5383. * For count you first have to call fetchNewFrame() to notify the start of a new frame to monitor, then call addCount() how many time required to increment the count value you monitor.
  5384. */
  5385. var PerfCounter = (function () {
  5386. function PerfCounter() {
  5387. this._startMonitoringTime = 0;
  5388. this._min = 0;
  5389. this._max = 0;
  5390. this._average = 0;
  5391. this._lastSecAverage = 0;
  5392. this._current = 0;
  5393. this._totalValueCount = 0;
  5394. this._totalAccumulated = 0;
  5395. this._lastSecAccumulated = 0;
  5396. this._lastSecTime = 0;
  5397. this._lastSecValueCount = 0;
  5398. }
  5399. Object.defineProperty(PerfCounter.prototype, "min", {
  5400. /**
  5401. * Returns the smallest value ever
  5402. */
  5403. get: function () {
  5404. return this._min;
  5405. },
  5406. enumerable: true,
  5407. configurable: true
  5408. });
  5409. Object.defineProperty(PerfCounter.prototype, "max", {
  5410. /**
  5411. * Returns the biggest value ever
  5412. */
  5413. get: function () {
  5414. return this._max;
  5415. },
  5416. enumerable: true,
  5417. configurable: true
  5418. });
  5419. Object.defineProperty(PerfCounter.prototype, "average", {
  5420. /**
  5421. * Returns the average value since the performance counter is running
  5422. */
  5423. get: function () {
  5424. return this._average;
  5425. },
  5426. enumerable: true,
  5427. configurable: true
  5428. });
  5429. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  5430. /**
  5431. * Returns the average value of the last second the counter was monitored
  5432. */
  5433. get: function () {
  5434. return this._lastSecAverage;
  5435. },
  5436. enumerable: true,
  5437. configurable: true
  5438. });
  5439. Object.defineProperty(PerfCounter.prototype, "current", {
  5440. /**
  5441. * Returns the current value
  5442. */
  5443. get: function () {
  5444. return this._current;
  5445. },
  5446. enumerable: true,
  5447. configurable: true
  5448. });
  5449. Object.defineProperty(PerfCounter.prototype, "total", {
  5450. get: function () {
  5451. return this._totalAccumulated;
  5452. },
  5453. enumerable: true,
  5454. configurable: true
  5455. });
  5456. /**
  5457. * Call this method to start monitoring a new frame.
  5458. * This scenario is typically used when you accumulate monitoring time many times for a single frame, you call this method at the start of the frame, then beginMonitoring to start recording and endMonitoring(false) to accumulated the recorded time to the PerfCounter or addCount() to accumulate a monitored count.
  5459. */
  5460. PerfCounter.prototype.fetchNewFrame = function () {
  5461. this._totalValueCount++;
  5462. this._current = 0;
  5463. this._lastSecValueCount++;
  5464. };
  5465. /**
  5466. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  5467. * @param newCount the count value to add to the monitored count
  5468. * @param fetchResult true when it's the last time in the frame you add to the counter and you wish to update the statistics properties (min/max/average), false if you only want to update statistics.
  5469. */
  5470. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  5471. this._current += newCount;
  5472. if (fetchResult) {
  5473. this._fetchResult();
  5474. }
  5475. };
  5476. /**
  5477. * Start monitoring this performance counter
  5478. */
  5479. PerfCounter.prototype.beginMonitoring = function () {
  5480. this._startMonitoringTime = Tools.Now;
  5481. };
  5482. /**
  5483. * Compute the time lapsed since the previous beginMonitoring() call.
  5484. * @param newFrame true by default to fetch the result and monitor a new frame, if false the time monitored will be added to the current frame counter
  5485. */
  5486. PerfCounter.prototype.endMonitoring = function (newFrame) {
  5487. if (newFrame === void 0) { newFrame = true; }
  5488. if (newFrame) {
  5489. this.fetchNewFrame();
  5490. }
  5491. var currentTime = Tools.Now;
  5492. this._current = currentTime - this._startMonitoringTime;
  5493. if (newFrame) {
  5494. this._fetchResult();
  5495. }
  5496. };
  5497. PerfCounter.prototype._fetchResult = function () {
  5498. this._totalAccumulated += this._current;
  5499. this._lastSecAccumulated += this._current;
  5500. // Min/Max update
  5501. this._min = Math.min(this._min, this._current);
  5502. this._max = Math.max(this._max, this._current);
  5503. this._average = this._totalAccumulated / this._totalValueCount;
  5504. // Reset last sec?
  5505. var now = Tools.Now;
  5506. if ((now - this._lastSecTime) > 1000) {
  5507. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  5508. this._lastSecTime = now;
  5509. this._lastSecAccumulated = 0;
  5510. this._lastSecValueCount = 0;
  5511. }
  5512. };
  5513. return PerfCounter;
  5514. })();
  5515. BABYLON.PerfCounter = PerfCounter;
  5516. /**
  5517. * Use this className as a decorator on a given class definition to add it a name.
  5518. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  5519. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  5520. * @param name
  5521. */
  5522. function className(name) {
  5523. return function (target) {
  5524. target["__bjsclassName__"] = name;
  5525. };
  5526. }
  5527. BABYLON.className = className;
  5528. /**
  5529. * An implementation of a loop for asynchronous functions.
  5530. */
  5531. var AsyncLoop = (function () {
  5532. /**
  5533. * Constroctor.
  5534. * @param iterations the number of iterations.
  5535. * @param _fn the function to run each iteration
  5536. * @param _successCallback the callback that will be called upon succesful execution
  5537. * @param offset starting offset.
  5538. */
  5539. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  5540. if (offset === void 0) { offset = 0; }
  5541. this.iterations = iterations;
  5542. this._fn = _fn;
  5543. this._successCallback = _successCallback;
  5544. this.index = offset - 1;
  5545. this._done = false;
  5546. }
  5547. /**
  5548. * Execute the next iteration. Must be called after the last iteration was finished.
  5549. */
  5550. AsyncLoop.prototype.executeNext = function () {
  5551. if (!this._done) {
  5552. if (this.index + 1 < this.iterations) {
  5553. ++this.index;
  5554. this._fn(this);
  5555. }
  5556. else {
  5557. this.breakLoop();
  5558. }
  5559. }
  5560. };
  5561. /**
  5562. * Break the loop and run the success callback.
  5563. */
  5564. AsyncLoop.prototype.breakLoop = function () {
  5565. this._done = true;
  5566. this._successCallback();
  5567. };
  5568. /**
  5569. * Helper function
  5570. */
  5571. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  5572. if (offset === void 0) { offset = 0; }
  5573. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  5574. loop.executeNext();
  5575. return loop;
  5576. };
  5577. /**
  5578. * A for-loop that will run a given number of iterations synchronous and the rest async.
  5579. * @param iterations total number of iterations
  5580. * @param syncedIterations number of synchronous iterations in each async iteration.
  5581. * @param fn the function to call each iteration.
  5582. * @param callback a success call back that will be called when iterating stops.
  5583. * @param breakFunction a break condition (optional)
  5584. * @param timeout timeout settings for the setTimeout function. default - 0.
  5585. * @constructor
  5586. */
  5587. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  5588. if (timeout === void 0) { timeout = 0; }
  5589. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  5590. if (breakFunction && breakFunction())
  5591. loop.breakLoop();
  5592. else {
  5593. setTimeout(function () {
  5594. for (var i = 0; i < syncedIterations; ++i) {
  5595. var iteration = (loop.index * syncedIterations) + i;
  5596. if (iteration >= iterations)
  5597. break;
  5598. fn(iteration);
  5599. if (breakFunction && breakFunction()) {
  5600. loop.breakLoop();
  5601. break;
  5602. }
  5603. }
  5604. loop.executeNext();
  5605. }, timeout);
  5606. }
  5607. }, callback);
  5608. };
  5609. return AsyncLoop;
  5610. })();
  5611. BABYLON.AsyncLoop = AsyncLoop;
  5612. })(BABYLON || (BABYLON = {}));
  5613. var BABYLON;
  5614. (function (BABYLON) {
  5615. var Internals;
  5616. (function (Internals) {
  5617. var _AlphaState = (function () {
  5618. function _AlphaState() {
  5619. this._isAlphaBlendDirty = false;
  5620. this._isBlendFunctionParametersDirty = false;
  5621. this._alphaBlend = false;
  5622. this._blendFunctionParameters = new Array(4);
  5623. }
  5624. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  5625. get: function () {
  5626. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  5627. },
  5628. enumerable: true,
  5629. configurable: true
  5630. });
  5631. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  5632. get: function () {
  5633. return this._alphaBlend;
  5634. },
  5635. set: function (value) {
  5636. if (this._alphaBlend === value) {
  5637. return;
  5638. }
  5639. this._alphaBlend = value;
  5640. this._isAlphaBlendDirty = true;
  5641. },
  5642. enumerable: true,
  5643. configurable: true
  5644. });
  5645. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  5646. if (this._blendFunctionParameters[0] === value0 &&
  5647. this._blendFunctionParameters[1] === value1 &&
  5648. this._blendFunctionParameters[2] === value2 &&
  5649. this._blendFunctionParameters[3] === value3) {
  5650. return;
  5651. }
  5652. this._blendFunctionParameters[0] = value0;
  5653. this._blendFunctionParameters[1] = value1;
  5654. this._blendFunctionParameters[2] = value2;
  5655. this._blendFunctionParameters[3] = value3;
  5656. this._isBlendFunctionParametersDirty = true;
  5657. };
  5658. _AlphaState.prototype.reset = function () {
  5659. this._alphaBlend = false;
  5660. this._blendFunctionParameters[0] = null;
  5661. this._blendFunctionParameters[1] = null;
  5662. this._blendFunctionParameters[2] = null;
  5663. this._blendFunctionParameters[3] = null;
  5664. this._isAlphaBlendDirty = true;
  5665. this._isBlendFunctionParametersDirty = false;
  5666. };
  5667. _AlphaState.prototype.apply = function (gl) {
  5668. if (!this.isDirty) {
  5669. return;
  5670. }
  5671. // Alpha blend
  5672. if (this._isAlphaBlendDirty) {
  5673. if (this._alphaBlend) {
  5674. gl.enable(gl.BLEND);
  5675. }
  5676. else {
  5677. gl.disable(gl.BLEND);
  5678. }
  5679. this._isAlphaBlendDirty = false;
  5680. }
  5681. // Alpha function
  5682. if (this._isBlendFunctionParametersDirty) {
  5683. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  5684. this._isBlendFunctionParametersDirty = false;
  5685. }
  5686. };
  5687. return _AlphaState;
  5688. })();
  5689. Internals._AlphaState = _AlphaState;
  5690. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  5691. })(BABYLON || (BABYLON = {}));
  5692. var BABYLON;
  5693. (function (BABYLON) {
  5694. var Internals;
  5695. (function (Internals) {
  5696. var _DepthCullingState = (function () {
  5697. function _DepthCullingState() {
  5698. this._isDepthTestDirty = false;
  5699. this._isDepthMaskDirty = false;
  5700. this._isDepthFuncDirty = false;
  5701. this._isCullFaceDirty = false;
  5702. this._isCullDirty = false;
  5703. this._isZOffsetDirty = false;
  5704. }
  5705. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  5706. get: function () {
  5707. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  5708. },
  5709. enumerable: true,
  5710. configurable: true
  5711. });
  5712. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  5713. get: function () {
  5714. return this._zOffset;
  5715. },
  5716. set: function (value) {
  5717. if (this._zOffset === value) {
  5718. return;
  5719. }
  5720. this._zOffset = value;
  5721. this._isZOffsetDirty = true;
  5722. },
  5723. enumerable: true,
  5724. configurable: true
  5725. });
  5726. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  5727. get: function () {
  5728. return this._cullFace;
  5729. },
  5730. set: function (value) {
  5731. if (this._cullFace === value) {
  5732. return;
  5733. }
  5734. this._cullFace = value;
  5735. this._isCullFaceDirty = true;
  5736. },
  5737. enumerable: true,
  5738. configurable: true
  5739. });
  5740. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  5741. get: function () {
  5742. return this._cull;
  5743. },
  5744. set: function (value) {
  5745. if (this._cull === value) {
  5746. return;
  5747. }
  5748. this._cull = value;
  5749. this._isCullDirty = true;
  5750. },
  5751. enumerable: true,
  5752. configurable: true
  5753. });
  5754. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  5755. get: function () {
  5756. return this._depthFunc;
  5757. },
  5758. set: function (value) {
  5759. if (this._depthFunc === value) {
  5760. return;
  5761. }
  5762. this._depthFunc = value;
  5763. this._isDepthFuncDirty = true;
  5764. },
  5765. enumerable: true,
  5766. configurable: true
  5767. });
  5768. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  5769. get: function () {
  5770. return this._depthMask;
  5771. },
  5772. set: function (value) {
  5773. if (this._depthMask === value) {
  5774. return;
  5775. }
  5776. this._depthMask = value;
  5777. this._isDepthMaskDirty = true;
  5778. },
  5779. enumerable: true,
  5780. configurable: true
  5781. });
  5782. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  5783. get: function () {
  5784. return this._depthTest;
  5785. },
  5786. set: function (value) {
  5787. if (this._depthTest === value) {
  5788. return;
  5789. }
  5790. this._depthTest = value;
  5791. this._isDepthTestDirty = true;
  5792. },
  5793. enumerable: true,
  5794. configurable: true
  5795. });
  5796. _DepthCullingState.prototype.reset = function () {
  5797. this._depthMask = true;
  5798. this._depthTest = true;
  5799. this._depthFunc = null;
  5800. this._cullFace = null;
  5801. this._cull = null;
  5802. this._zOffset = 0;
  5803. this._isDepthTestDirty = true;
  5804. this._isDepthMaskDirty = true;
  5805. this._isDepthFuncDirty = false;
  5806. this._isCullFaceDirty = false;
  5807. this._isCullDirty = false;
  5808. this._isZOffsetDirty = false;
  5809. };
  5810. _DepthCullingState.prototype.apply = function (gl) {
  5811. if (!this.isDirty) {
  5812. return;
  5813. }
  5814. // Cull
  5815. if (this._isCullDirty) {
  5816. if (this.cull) {
  5817. gl.enable(gl.CULL_FACE);
  5818. }
  5819. else {
  5820. gl.disable(gl.CULL_FACE);
  5821. }
  5822. this._isCullDirty = false;
  5823. }
  5824. // Cull face
  5825. if (this._isCullFaceDirty) {
  5826. gl.cullFace(this.cullFace);
  5827. this._isCullFaceDirty = false;
  5828. }
  5829. // Depth mask
  5830. if (this._isDepthMaskDirty) {
  5831. gl.depthMask(this.depthMask);
  5832. this._isDepthMaskDirty = false;
  5833. }
  5834. // Depth test
  5835. if (this._isDepthTestDirty) {
  5836. if (this.depthTest) {
  5837. gl.enable(gl.DEPTH_TEST);
  5838. }
  5839. else {
  5840. gl.disable(gl.DEPTH_TEST);
  5841. }
  5842. this._isDepthTestDirty = false;
  5843. }
  5844. // Depth func
  5845. if (this._isDepthFuncDirty) {
  5846. gl.depthFunc(this.depthFunc);
  5847. this._isDepthFuncDirty = false;
  5848. }
  5849. // zOffset
  5850. if (this._isZOffsetDirty) {
  5851. if (this.zOffset) {
  5852. gl.enable(gl.POLYGON_OFFSET_FILL);
  5853. gl.polygonOffset(this.zOffset, 0);
  5854. }
  5855. else {
  5856. gl.disable(gl.POLYGON_OFFSET_FILL);
  5857. }
  5858. this._isZOffsetDirty = false;
  5859. }
  5860. };
  5861. return _DepthCullingState;
  5862. })();
  5863. Internals._DepthCullingState = _DepthCullingState;
  5864. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  5865. })(BABYLON || (BABYLON = {}));
  5866. var BABYLON;
  5867. (function (BABYLON) {
  5868. var Internals;
  5869. (function (Internals) {
  5870. var _StencilState = (function () {
  5871. function _StencilState() {
  5872. this._isStencilTestDirty = false;
  5873. this._isStencilMaskDirty = false;
  5874. this._isStencilFuncDirty = false;
  5875. this._isStencilOpDirty = false;
  5876. this.reset();
  5877. }
  5878. Object.defineProperty(_StencilState.prototype, "isDirty", {
  5879. get: function () {
  5880. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  5881. },
  5882. enumerable: true,
  5883. configurable: true
  5884. });
  5885. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  5886. get: function () {
  5887. return this._stencilFunc;
  5888. },
  5889. set: function (value) {
  5890. if (this._stencilFunc === value) {
  5891. return;
  5892. }
  5893. this._stencilFunc = value;
  5894. this._isStencilFuncDirty = true;
  5895. },
  5896. enumerable: true,
  5897. configurable: true
  5898. });
  5899. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  5900. get: function () {
  5901. return this._stencilFuncRef;
  5902. },
  5903. set: function (value) {
  5904. if (this._stencilFuncRef === value) {
  5905. return;
  5906. }
  5907. this._stencilFuncRef = value;
  5908. this._isStencilFuncDirty = true;
  5909. },
  5910. enumerable: true,
  5911. configurable: true
  5912. });
  5913. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  5914. get: function () {
  5915. return this._stencilFuncMask;
  5916. },
  5917. set: function (value) {
  5918. if (this._stencilFuncMask === value) {
  5919. return;
  5920. }
  5921. this._stencilFuncMask = value;
  5922. this._isStencilFuncDirty = true;
  5923. },
  5924. enumerable: true,
  5925. configurable: true
  5926. });
  5927. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  5928. get: function () {
  5929. return this._stencilOpStencilFail;
  5930. },
  5931. set: function (value) {
  5932. if (this._stencilOpStencilFail === value) {
  5933. return;
  5934. }
  5935. this._stencilOpStencilFail = value;
  5936. this._isStencilOpDirty = true;
  5937. },
  5938. enumerable: true,
  5939. configurable: true
  5940. });
  5941. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  5942. get: function () {
  5943. return this._stencilOpDepthFail;
  5944. },
  5945. set: function (value) {
  5946. if (this._stencilOpDepthFail === value) {
  5947. return;
  5948. }
  5949. this._stencilOpDepthFail = value;
  5950. this._isStencilOpDirty = true;
  5951. },
  5952. enumerable: true,
  5953. configurable: true
  5954. });
  5955. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  5956. get: function () {
  5957. return this._stencilOpStencilDepthPass;
  5958. },
  5959. set: function (value) {
  5960. if (this._stencilOpStencilDepthPass === value) {
  5961. return;
  5962. }
  5963. this._stencilOpStencilDepthPass = value;
  5964. this._isStencilOpDirty = true;
  5965. },
  5966. enumerable: true,
  5967. configurable: true
  5968. });
  5969. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  5970. get: function () {
  5971. return this._stencilMask;
  5972. },
  5973. set: function (value) {
  5974. if (this._stencilMask === value) {
  5975. return;
  5976. }
  5977. this._stencilMask = value;
  5978. this._isStencilMaskDirty = true;
  5979. },
  5980. enumerable: true,
  5981. configurable: true
  5982. });
  5983. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  5984. get: function () {
  5985. return this._stencilTest;
  5986. },
  5987. set: function (value) {
  5988. if (this._stencilTest === value) {
  5989. return;
  5990. }
  5991. this._stencilTest = value;
  5992. this._isStencilTestDirty = true;
  5993. },
  5994. enumerable: true,
  5995. configurable: true
  5996. });
  5997. _StencilState.prototype.reset = function () {
  5998. this._stencilTest = false;
  5999. this._stencilMask = 0xFF;
  6000. this._stencilFunc = WebGLRenderingContext.ALWAYS;
  6001. this._stencilFuncRef = 1;
  6002. this._stencilFuncMask = 0xFF;
  6003. this._stencilOpStencilFail = WebGLRenderingContext.KEEP;
  6004. this._stencilOpDepthFail = WebGLRenderingContext.KEEP;
  6005. this._stencilOpStencilDepthPass = WebGLRenderingContext.REPLACE;
  6006. this._isStencilTestDirty = true;
  6007. this._isStencilMaskDirty = true;
  6008. this._isStencilFuncDirty = true;
  6009. this._isStencilOpDirty = true;
  6010. };
  6011. _StencilState.prototype.apply = function (gl) {
  6012. if (!this.isDirty) {
  6013. return;
  6014. }
  6015. // Stencil test
  6016. if (this._isStencilTestDirty) {
  6017. if (this.stencilTest) {
  6018. gl.enable(gl.STENCIL_TEST);
  6019. }
  6020. else {
  6021. gl.disable(gl.STENCIL_TEST);
  6022. }
  6023. this._isStencilTestDirty = false;
  6024. }
  6025. // Stencil mask
  6026. if (this._isStencilMaskDirty) {
  6027. gl.stencilMask(this.stencilMask);
  6028. this._isStencilMaskDirty = false;
  6029. }
  6030. // Stencil func
  6031. if (this._isStencilFuncDirty) {
  6032. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  6033. this._isStencilFuncDirty = false;
  6034. }
  6035. // Stencil op
  6036. if (this._isStencilOpDirty) {
  6037. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  6038. this._isStencilOpDirty = false;
  6039. }
  6040. };
  6041. return _StencilState;
  6042. })();
  6043. Internals._StencilState = _StencilState;
  6044. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  6045. })(BABYLON || (BABYLON = {}));
  6046. var BABYLON;
  6047. (function (BABYLON) {
  6048. var compileShader = function (gl, source, type, defines) {
  6049. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  6050. gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
  6051. gl.compileShader(shader);
  6052. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  6053. throw new Error(gl.getShaderInfoLog(shader));
  6054. }
  6055. return shader;
  6056. };
  6057. var HALF_FLOAT_OES = 0x8D61;
  6058. var getWebGLTextureType = function (gl, type) {
  6059. if (type === Engine.TEXTURETYPE_FLOAT) {
  6060. return gl.FLOAT;
  6061. }
  6062. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  6063. // Add Half Float Constant.
  6064. return HALF_FLOAT_OES;
  6065. }
  6066. return gl.UNSIGNED_BYTE;
  6067. };
  6068. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  6069. var magFilter = gl.NEAREST;
  6070. var minFilter = gl.NEAREST;
  6071. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  6072. magFilter = gl.LINEAR;
  6073. if (generateMipMaps) {
  6074. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  6075. }
  6076. else {
  6077. minFilter = gl.LINEAR;
  6078. }
  6079. }
  6080. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  6081. magFilter = gl.LINEAR;
  6082. if (generateMipMaps) {
  6083. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  6084. }
  6085. else {
  6086. minFilter = gl.LINEAR;
  6087. }
  6088. }
  6089. else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6090. magFilter = gl.NEAREST;
  6091. if (generateMipMaps) {
  6092. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  6093. }
  6094. else {
  6095. minFilter = gl.NEAREST;
  6096. }
  6097. }
  6098. return {
  6099. min: minFilter,
  6100. mag: magFilter
  6101. };
  6102. };
  6103. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, onLoad, samplingMode) {
  6104. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  6105. var engine = scene.getEngine();
  6106. var potWidth = BABYLON.Tools.GetExponentOfTwo(width, engine.getCaps().maxTextureSize);
  6107. var potHeight = BABYLON.Tools.GetExponentOfTwo(height, engine.getCaps().maxTextureSize);
  6108. engine._bindTextureDirectly(gl.TEXTURE_2D, texture);
  6109. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  6110. texture._baseWidth = width;
  6111. texture._baseHeight = height;
  6112. texture._width = potWidth;
  6113. texture._height = potHeight;
  6114. texture.isReady = true;
  6115. processFunction(potWidth, potHeight);
  6116. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  6117. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  6118. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  6119. if (!noMipmap && !isCompressed) {
  6120. gl.generateMipmap(gl.TEXTURE_2D);
  6121. }
  6122. engine._bindTextureDirectly(gl.TEXTURE_2D, null);
  6123. engine.resetTextureCache();
  6124. scene._removePendingData(texture);
  6125. if (onLoad) {
  6126. onLoad();
  6127. }
  6128. };
  6129. var partialLoad = function (url, index, loadedImages, scene, onfinish) {
  6130. var img;
  6131. var onload = function () {
  6132. loadedImages[index] = img;
  6133. loadedImages._internalCount++;
  6134. scene._removePendingData(img);
  6135. if (loadedImages._internalCount === 6) {
  6136. onfinish(loadedImages);
  6137. }
  6138. };
  6139. var onerror = function () {
  6140. scene._removePendingData(img);
  6141. };
  6142. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  6143. scene._addPendingData(img);
  6144. };
  6145. var cascadeLoad = function (rootUrl, scene, onfinish, files) {
  6146. var loadedImages = [];
  6147. loadedImages._internalCount = 0;
  6148. for (var index = 0; index < 6; index++) {
  6149. partialLoad(files[index], index, loadedImages, scene, onfinish);
  6150. }
  6151. };
  6152. var InstancingAttributeInfo = (function () {
  6153. function InstancingAttributeInfo() {
  6154. }
  6155. return InstancingAttributeInfo;
  6156. })();
  6157. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  6158. var EngineCapabilities = (function () {
  6159. function EngineCapabilities() {
  6160. }
  6161. return EngineCapabilities;
  6162. })();
  6163. BABYLON.EngineCapabilities = EngineCapabilities;
  6164. /**
  6165. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  6166. */
  6167. var Engine = (function () {
  6168. /**
  6169. * @constructor
  6170. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  6171. * @param {boolean} [antialias] - enable antialias
  6172. * @param options - further options to be sent to the getContext function
  6173. */
  6174. function Engine(canvas, antialias, options, adaptToDeviceRatio) {
  6175. var _this = this;
  6176. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = true; }
  6177. // Public members
  6178. this.isFullscreen = false;
  6179. this.isPointerLock = false;
  6180. this.cullBackFaces = true;
  6181. this.renderEvenInBackground = true;
  6182. // To enable/disable IDB support and avoid XHR on .manifest
  6183. this.enableOfflineSupport = true;
  6184. this.scenes = new Array();
  6185. this._windowIsBackground = false;
  6186. this._webGLVersion = "1.0";
  6187. this._drawCalls = new BABYLON.PerfCounter();
  6188. this._renderingQueueLaunched = false;
  6189. this._activeRenderLoops = [];
  6190. // FPS
  6191. this.fpsRange = 60;
  6192. this.previousFramesDuration = [];
  6193. this.fps = 60;
  6194. this.deltaTime = 0;
  6195. // States
  6196. this._depthCullingState = new BABYLON.Internals._DepthCullingState();
  6197. this._stencilState = new BABYLON.Internals._StencilState();
  6198. this._alphaState = new BABYLON.Internals._AlphaState();
  6199. this._alphaMode = Engine.ALPHA_DISABLE;
  6200. // Cache
  6201. this._loadedTexturesCache = new Array();
  6202. this._maxTextureChannels = 16;
  6203. this._activeTexturesCache = new Array(this._maxTextureChannels);
  6204. this._compiledEffects = {};
  6205. this._vertexAttribArraysEnabled = [];
  6206. this._uintIndicesCurrentlySet = false;
  6207. this._currentBoundBuffer = new Array();
  6208. this._currentBufferPointers = [];
  6209. this._currentInstanceLocations = new Array();
  6210. this._currentInstanceBuffers = new Array();
  6211. this._renderingCanvas = canvas;
  6212. this._externalData = new BABYLON.StringDictionary();
  6213. options = options || {};
  6214. if (antialias != null) {
  6215. options.antialias = antialias;
  6216. }
  6217. if (options.preserveDrawingBuffer === undefined) {
  6218. options.preserveDrawingBuffer = false;
  6219. }
  6220. // Checks if some of the format renders first to allow the use of webgl inspector.
  6221. var renderToFullFloat = this._canRenderToFloatTexture();
  6222. var renderToHalfFloat = this._canRenderToHalfFloatTexture();
  6223. // GL
  6224. //try {
  6225. // this._gl = <WebGLRenderingContext>(canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  6226. // if (this._gl) {
  6227. // this._webGLVersion = "2.0";
  6228. // }
  6229. //} catch (e) {
  6230. // // Do nothing
  6231. //}
  6232. if (!this._gl) {
  6233. try {
  6234. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  6235. }
  6236. catch (e) {
  6237. throw new Error("WebGL not supported");
  6238. }
  6239. }
  6240. if (!this._gl) {
  6241. throw new Error("WebGL not supported");
  6242. }
  6243. this._onBlur = function () {
  6244. _this._windowIsBackground = true;
  6245. };
  6246. this._onFocus = function () {
  6247. _this._windowIsBackground = false;
  6248. };
  6249. window.addEventListener("blur", this._onBlur);
  6250. window.addEventListener("focus", this._onFocus);
  6251. // Viewport
  6252. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  6253. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  6254. this.resize();
  6255. // Caps
  6256. this._isStencilEnable = options.stencil;
  6257. this._caps = new EngineCapabilities();
  6258. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  6259. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  6260. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  6261. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  6262. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  6263. // Infos
  6264. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  6265. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  6266. if (rendererInfo != null) {
  6267. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  6268. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  6269. }
  6270. if (!this._glVendor) {
  6271. this._glVendor = "Unknown vendor";
  6272. }
  6273. if (!this._glRenderer) {
  6274. this._glRenderer = "Unknown renderer";
  6275. }
  6276. // Extensions
  6277. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  6278. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  6279. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  6280. 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');
  6281. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  6282. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  6283. this._caps.uintIndices = this._gl.getExtension('OES_element_index_uint') !== null;
  6284. this._caps.fragmentDepthSupported = this._gl.getExtension('EXT_frag_depth') !== null;
  6285. this._caps.highPrecisionShaderSupported = true;
  6286. this._caps.drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  6287. this._caps.textureFloatLinearFiltering = this._gl.getExtension('OES_texture_float_linear');
  6288. this._caps.textureLOD = this._gl.getExtension('EXT_shader_texture_lod');
  6289. this._caps.textureFloatRender = renderToFullFloat;
  6290. this._caps.textureHalfFloat = (this._gl.getExtension('OES_texture_half_float') !== null);
  6291. this._caps.textureHalfFloatLinearFiltering = this._gl.getExtension('OES_texture_half_float_linear');
  6292. this._caps.textureHalfFloatRender = renderToHalfFloat;
  6293. if (this._gl.getShaderPrecisionFormat) {
  6294. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  6295. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  6296. }
  6297. // Depth buffer
  6298. this.setDepthBuffer(true);
  6299. this.setDepthFunctionToLessOrEqual();
  6300. this.setDepthWrite(true);
  6301. // Fullscreen
  6302. this._onFullscreenChange = function () {
  6303. if (document.fullscreen !== undefined) {
  6304. _this.isFullscreen = document.fullscreen;
  6305. }
  6306. else if (document.mozFullScreen !== undefined) {
  6307. _this.isFullscreen = document.mozFullScreen;
  6308. }
  6309. else if (document.webkitIsFullScreen !== undefined) {
  6310. _this.isFullscreen = document.webkitIsFullScreen;
  6311. }
  6312. else if (document.msIsFullScreen !== undefined) {
  6313. _this.isFullscreen = document.msIsFullScreen;
  6314. }
  6315. // Pointer lock
  6316. if (_this.isFullscreen && _this._pointerLockRequested) {
  6317. canvas.requestPointerLock = canvas.requestPointerLock ||
  6318. canvas.msRequestPointerLock ||
  6319. canvas.mozRequestPointerLock ||
  6320. canvas.webkitRequestPointerLock;
  6321. if (canvas.requestPointerLock) {
  6322. canvas.requestPointerLock();
  6323. }
  6324. }
  6325. };
  6326. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  6327. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  6328. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  6329. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  6330. // Pointer lock
  6331. this._onPointerLockChange = function () {
  6332. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  6333. document.webkitPointerLockElement === canvas ||
  6334. document.msPointerLockElement === canvas ||
  6335. document.pointerLockElement === canvas);
  6336. };
  6337. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  6338. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  6339. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  6340. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  6341. if (BABYLON.AudioEngine && !Engine.audioEngine) {
  6342. Engine.audioEngine = new BABYLON.AudioEngine();
  6343. }
  6344. //default loading screen
  6345. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  6346. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  6347. }
  6348. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  6349. get: function () {
  6350. return Engine._ALPHA_DISABLE;
  6351. },
  6352. enumerable: true,
  6353. configurable: true
  6354. });
  6355. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  6356. get: function () {
  6357. return Engine._ALPHA_ONEONE;
  6358. },
  6359. enumerable: true,
  6360. configurable: true
  6361. });
  6362. Object.defineProperty(Engine, "ALPHA_ADD", {
  6363. get: function () {
  6364. return Engine._ALPHA_ADD;
  6365. },
  6366. enumerable: true,
  6367. configurable: true
  6368. });
  6369. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  6370. get: function () {
  6371. return Engine._ALPHA_COMBINE;
  6372. },
  6373. enumerable: true,
  6374. configurable: true
  6375. });
  6376. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  6377. get: function () {
  6378. return Engine._ALPHA_SUBTRACT;
  6379. },
  6380. enumerable: true,
  6381. configurable: true
  6382. });
  6383. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  6384. get: function () {
  6385. return Engine._ALPHA_MULTIPLY;
  6386. },
  6387. enumerable: true,
  6388. configurable: true
  6389. });
  6390. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  6391. get: function () {
  6392. return Engine._ALPHA_MAXIMIZED;
  6393. },
  6394. enumerable: true,
  6395. configurable: true
  6396. });
  6397. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  6398. get: function () {
  6399. return Engine._DELAYLOADSTATE_NONE;
  6400. },
  6401. enumerable: true,
  6402. configurable: true
  6403. });
  6404. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  6405. get: function () {
  6406. return Engine._DELAYLOADSTATE_LOADED;
  6407. },
  6408. enumerable: true,
  6409. configurable: true
  6410. });
  6411. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  6412. get: function () {
  6413. return Engine._DELAYLOADSTATE_LOADING;
  6414. },
  6415. enumerable: true,
  6416. configurable: true
  6417. });
  6418. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  6419. get: function () {
  6420. return Engine._DELAYLOADSTATE_NOTLOADED;
  6421. },
  6422. enumerable: true,
  6423. configurable: true
  6424. });
  6425. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  6426. get: function () {
  6427. return Engine._TEXTUREFORMAT_ALPHA;
  6428. },
  6429. enumerable: true,
  6430. configurable: true
  6431. });
  6432. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  6433. get: function () {
  6434. return Engine._TEXTUREFORMAT_LUMINANCE;
  6435. },
  6436. enumerable: true,
  6437. configurable: true
  6438. });
  6439. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  6440. get: function () {
  6441. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  6442. },
  6443. enumerable: true,
  6444. configurable: true
  6445. });
  6446. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  6447. get: function () {
  6448. return Engine._TEXTUREFORMAT_RGB;
  6449. },
  6450. enumerable: true,
  6451. configurable: true
  6452. });
  6453. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  6454. get: function () {
  6455. return Engine._TEXTUREFORMAT_RGBA;
  6456. },
  6457. enumerable: true,
  6458. configurable: true
  6459. });
  6460. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  6461. get: function () {
  6462. return Engine._TEXTURETYPE_UNSIGNED_INT;
  6463. },
  6464. enumerable: true,
  6465. configurable: true
  6466. });
  6467. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  6468. get: function () {
  6469. return Engine._TEXTURETYPE_FLOAT;
  6470. },
  6471. enumerable: true,
  6472. configurable: true
  6473. });
  6474. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  6475. get: function () {
  6476. return Engine._TEXTURETYPE_HALF_FLOAT;
  6477. },
  6478. enumerable: true,
  6479. configurable: true
  6480. });
  6481. Object.defineProperty(Engine, "Version", {
  6482. get: function () {
  6483. return "2.5-alpha";
  6484. },
  6485. enumerable: true,
  6486. configurable: true
  6487. });
  6488. Object.defineProperty(Engine.prototype, "webGLVersion", {
  6489. get: function () {
  6490. return this._webGLVersion;
  6491. },
  6492. enumerable: true,
  6493. configurable: true
  6494. });
  6495. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  6496. /**
  6497. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  6498. */
  6499. get: function () {
  6500. return this._isStencilEnable;
  6501. },
  6502. enumerable: true,
  6503. configurable: true
  6504. });
  6505. Engine.prototype._prepareWorkingCanvas = function () {
  6506. if (this._workingCanvas) {
  6507. return;
  6508. }
  6509. this._workingCanvas = document.createElement("canvas");
  6510. this._workingContext = this._workingCanvas.getContext("2d");
  6511. };
  6512. Engine.prototype.resetTextureCache = function () {
  6513. for (var index = 0; index < this._maxTextureChannels; index++) {
  6514. this._activeTexturesCache[index] = null;
  6515. }
  6516. };
  6517. Engine.prototype.getGlInfo = function () {
  6518. return {
  6519. vendor: this._glVendor,
  6520. renderer: this._glRenderer,
  6521. version: this._glVersion
  6522. };
  6523. };
  6524. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  6525. if (useScreen === void 0) { useScreen = false; }
  6526. var viewport = camera.viewport;
  6527. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  6528. };
  6529. Engine.prototype.getRenderWidth = function (useScreen) {
  6530. if (useScreen === void 0) { useScreen = false; }
  6531. if (!useScreen && this._currentRenderTarget) {
  6532. return this._currentRenderTarget._width;
  6533. }
  6534. return this._renderingCanvas.width;
  6535. };
  6536. Engine.prototype.getRenderHeight = function (useScreen) {
  6537. if (useScreen === void 0) { useScreen = false; }
  6538. if (!useScreen && this._currentRenderTarget) {
  6539. return this._currentRenderTarget._height;
  6540. }
  6541. return this._renderingCanvas.height;
  6542. };
  6543. Engine.prototype.getRenderingCanvas = function () {
  6544. return this._renderingCanvas;
  6545. };
  6546. Engine.prototype.getRenderingCanvasClientRect = function () {
  6547. return this._renderingCanvas.getBoundingClientRect();
  6548. };
  6549. Engine.prototype.setHardwareScalingLevel = function (level) {
  6550. this._hardwareScalingLevel = level;
  6551. this.resize();
  6552. };
  6553. Engine.prototype.getHardwareScalingLevel = function () {
  6554. return this._hardwareScalingLevel;
  6555. };
  6556. Engine.prototype.getLoadedTexturesCache = function () {
  6557. return this._loadedTexturesCache;
  6558. };
  6559. Engine.prototype.getCaps = function () {
  6560. return this._caps;
  6561. };
  6562. Object.defineProperty(Engine.prototype, "drawCalls", {
  6563. get: function () {
  6564. return this._drawCalls.current;
  6565. },
  6566. enumerable: true,
  6567. configurable: true
  6568. });
  6569. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  6570. get: function () {
  6571. return this._drawCalls;
  6572. },
  6573. enumerable: true,
  6574. configurable: true
  6575. });
  6576. Engine.prototype.getDepthFunction = function () {
  6577. return this._depthCullingState.depthFunc;
  6578. };
  6579. Engine.prototype.setDepthFunction = function (depthFunc) {
  6580. this._depthCullingState.depthFunc = depthFunc;
  6581. };
  6582. Engine.prototype.setDepthFunctionToGreater = function () {
  6583. this._depthCullingState.depthFunc = this._gl.GREATER;
  6584. };
  6585. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  6586. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  6587. };
  6588. Engine.prototype.setDepthFunctionToLess = function () {
  6589. this._depthCullingState.depthFunc = this._gl.LESS;
  6590. };
  6591. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  6592. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  6593. };
  6594. Engine.prototype.getStencilBuffer = function () {
  6595. return this._stencilState.stencilTest;
  6596. };
  6597. Engine.prototype.setStencilBuffer = function (enable) {
  6598. this._stencilState.stencilTest = enable;
  6599. };
  6600. Engine.prototype.getStencilMask = function () {
  6601. return this._stencilState.stencilMask;
  6602. };
  6603. Engine.prototype.setStencilMask = function (mask) {
  6604. this._stencilState.stencilMask = mask;
  6605. };
  6606. Engine.prototype.getStencilFunction = function () {
  6607. return this._stencilState.stencilFunc;
  6608. };
  6609. Engine.prototype.getStencilFunctionReference = function () {
  6610. return this._stencilState.stencilFuncRef;
  6611. };
  6612. Engine.prototype.getStencilFunctionMask = function () {
  6613. return this._stencilState.stencilFuncMask;
  6614. };
  6615. Engine.prototype.setStencilFunction = function (stencilFunc) {
  6616. this._stencilState.stencilFunc = stencilFunc;
  6617. };
  6618. Engine.prototype.setStencilFunctionReference = function (reference) {
  6619. this._stencilState.stencilFuncRef = reference;
  6620. };
  6621. Engine.prototype.setStencilFunctionMask = function (mask) {
  6622. this._stencilState.stencilFuncMask = mask;
  6623. };
  6624. Engine.prototype.getStencilOperationFail = function () {
  6625. return this._stencilState.stencilOpStencilFail;
  6626. };
  6627. Engine.prototype.getStencilOperationDepthFail = function () {
  6628. return this._stencilState.stencilOpDepthFail;
  6629. };
  6630. Engine.prototype.getStencilOperationPass = function () {
  6631. return this._stencilState.stencilOpStencilDepthPass;
  6632. };
  6633. Engine.prototype.setStencilOperationFail = function (operation) {
  6634. this._stencilState.stencilOpStencilFail = operation;
  6635. };
  6636. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  6637. this._stencilState.stencilOpDepthFail = operation;
  6638. };
  6639. Engine.prototype.setStencilOperationPass = function (operation) {
  6640. this._stencilState.stencilOpStencilDepthPass = operation;
  6641. };
  6642. /**
  6643. * stop executing a render loop function and remove it from the execution array
  6644. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  6645. */
  6646. Engine.prototype.stopRenderLoop = function (renderFunction) {
  6647. if (!renderFunction) {
  6648. this._activeRenderLoops = [];
  6649. return;
  6650. }
  6651. var index = this._activeRenderLoops.indexOf(renderFunction);
  6652. if (index >= 0) {
  6653. this._activeRenderLoops.splice(index, 1);
  6654. }
  6655. };
  6656. Engine.prototype._renderLoop = function () {
  6657. var shouldRender = true;
  6658. if (!this.renderEvenInBackground && this._windowIsBackground) {
  6659. shouldRender = false;
  6660. }
  6661. if (shouldRender) {
  6662. // Start new frame
  6663. this.beginFrame();
  6664. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  6665. var renderFunction = this._activeRenderLoops[index];
  6666. renderFunction();
  6667. }
  6668. // Present
  6669. this.endFrame();
  6670. }
  6671. if (this._activeRenderLoops.length > 0) {
  6672. // Register new frame
  6673. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  6674. }
  6675. else {
  6676. this._renderingQueueLaunched = false;
  6677. }
  6678. };
  6679. /**
  6680. * Register and execute a render loop. The engine can have more than one render function.
  6681. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  6682. * @example
  6683. * engine.runRenderLoop(function () {
  6684. * scene.render()
  6685. * })
  6686. */
  6687. Engine.prototype.runRenderLoop = function (renderFunction) {
  6688. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  6689. return;
  6690. }
  6691. this._activeRenderLoops.push(renderFunction);
  6692. if (!this._renderingQueueLaunched) {
  6693. this._renderingQueueLaunched = true;
  6694. this._bindedRenderFunction = this._renderLoop.bind(this);
  6695. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  6696. }
  6697. };
  6698. /**
  6699. * Toggle full screen mode.
  6700. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  6701. * @param {any} options - an options object to be sent to the requestFullscreen function
  6702. */
  6703. Engine.prototype.switchFullscreen = function (requestPointerLock, options) {
  6704. if (this.isFullscreen) {
  6705. BABYLON.Tools.ExitFullscreen();
  6706. }
  6707. else {
  6708. this._pointerLockRequested = requestPointerLock;
  6709. BABYLON.Tools.RequestFullscreen(this._renderingCanvas, options);
  6710. }
  6711. };
  6712. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  6713. if (stencil === void 0) { stencil = false; }
  6714. this.applyStates();
  6715. var mode = 0;
  6716. if (backBuffer) {
  6717. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  6718. mode |= this._gl.COLOR_BUFFER_BIT;
  6719. }
  6720. if (depth) {
  6721. this._gl.clearDepth(1.0);
  6722. mode |= this._gl.DEPTH_BUFFER_BIT;
  6723. }
  6724. if (stencil) {
  6725. this._gl.clearStencil(0);
  6726. mode |= this._gl.STENCIL_BUFFER_BIT;
  6727. }
  6728. this._gl.clear(mode);
  6729. };
  6730. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  6731. var gl = this._gl;
  6732. // Save state
  6733. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  6734. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  6735. // Change state
  6736. gl.enable(gl.SCISSOR_TEST);
  6737. gl.scissor(x, y, width, height);
  6738. // Clear
  6739. this.clear(clearColor, true, true, true);
  6740. // Restore state
  6741. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  6742. if (curScissor === true) {
  6743. gl.enable(gl.SCISSOR_TEST);
  6744. }
  6745. else {
  6746. gl.disable(gl.SCISSOR_TEST);
  6747. }
  6748. };
  6749. /**
  6750. * Set the WebGL's viewport
  6751. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  6752. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  6753. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  6754. */
  6755. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  6756. var width = requiredWidth || (navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.width);
  6757. var height = requiredHeight || (navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.height);
  6758. var x = viewport.x || 0;
  6759. var y = viewport.y || 0;
  6760. this._cachedViewport = viewport;
  6761. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  6762. };
  6763. /**
  6764. * Directly set the WebGL Viewport
  6765. * The x, y, width & height are directly passed to the WebGL call
  6766. * @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.
  6767. */
  6768. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  6769. var currentViewport = this._cachedViewport;
  6770. this._cachedViewport = null;
  6771. this._gl.viewport(x, y, width, height);
  6772. return currentViewport;
  6773. };
  6774. Engine.prototype.beginFrame = function () {
  6775. this._measureFps();
  6776. };
  6777. Engine.prototype.endFrame = function () {
  6778. //this.flushFramebuffer();
  6779. };
  6780. /**
  6781. * resize the view according to the canvas' size.
  6782. * @example
  6783. * window.addEventListener("resize", function () {
  6784. * engine.resize();
  6785. * });
  6786. */
  6787. Engine.prototype.resize = function () {
  6788. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  6789. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  6790. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  6791. for (var index = 0; index < this.scenes.length; index++) {
  6792. var scene = this.scenes[index];
  6793. if (BABYLON.DebugLayer && scene.debugLayer.isVisible()) {
  6794. scene.debugLayer._syncPositions();
  6795. }
  6796. }
  6797. };
  6798. /**
  6799. * force a specific size of the canvas
  6800. * @param {number} width - the new canvas' width
  6801. * @param {number} height - the new canvas' height
  6802. */
  6803. Engine.prototype.setSize = function (width, height) {
  6804. this._renderingCanvas.width = width;
  6805. this._renderingCanvas.height = height;
  6806. for (var index = 0; index < this.scenes.length; index++) {
  6807. var scene = this.scenes[index];
  6808. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  6809. var cam = scene.cameras[camIndex];
  6810. cam._currentRenderId = 0;
  6811. }
  6812. }
  6813. };
  6814. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight) {
  6815. this._currentRenderTarget = texture;
  6816. this.bindUnboundFramebuffer(texture._framebuffer);
  6817. var gl = this._gl;
  6818. if (texture.isCube) {
  6819. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture, 0);
  6820. }
  6821. gl.viewport(0, 0, requiredWidth || texture._width, requiredHeight || texture._height);
  6822. this.wipeCaches();
  6823. };
  6824. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  6825. if (this._currentFramebuffer !== framebuffer) {
  6826. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  6827. this._currentFramebuffer = framebuffer;
  6828. }
  6829. };
  6830. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps) {
  6831. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  6832. this._currentRenderTarget = null;
  6833. if (texture.generateMipMaps && !disableGenerateMipMaps) {
  6834. var gl = this._gl;
  6835. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  6836. gl.generateMipmap(gl.TEXTURE_2D);
  6837. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  6838. }
  6839. this.bindUnboundFramebuffer(null);
  6840. };
  6841. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  6842. if (texture.generateMipMaps) {
  6843. var gl = this._gl;
  6844. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  6845. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6846. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  6847. }
  6848. };
  6849. Engine.prototype.flushFramebuffer = function () {
  6850. this._gl.flush();
  6851. };
  6852. Engine.prototype.restoreDefaultFramebuffer = function () {
  6853. this._currentRenderTarget = null;
  6854. this.bindUnboundFramebuffer(null);
  6855. this.setViewport(this._cachedViewport);
  6856. this.wipeCaches();
  6857. };
  6858. // VBOs
  6859. Engine.prototype._resetVertexBufferBinding = function () {
  6860. this.bindArrayBuffer(null);
  6861. this._cachedVertexBuffers = null;
  6862. };
  6863. Engine.prototype.createVertexBuffer = function (vertices) {
  6864. var vbo = this._gl.createBuffer();
  6865. this.bindArrayBuffer(vbo);
  6866. if (vertices instanceof Float32Array) {
  6867. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  6868. }
  6869. else {
  6870. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  6871. }
  6872. this._resetVertexBufferBinding();
  6873. vbo.references = 1;
  6874. return vbo;
  6875. };
  6876. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  6877. var vbo = this._gl.createBuffer();
  6878. this.bindArrayBuffer(vbo);
  6879. if (vertices instanceof Float32Array) {
  6880. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  6881. }
  6882. else {
  6883. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  6884. }
  6885. this._resetVertexBufferBinding();
  6886. vbo.references = 1;
  6887. return vbo;
  6888. };
  6889. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  6890. this.bindArrayBuffer(vertexBuffer);
  6891. if (offset === undefined) {
  6892. offset = 0;
  6893. }
  6894. if (count === undefined) {
  6895. if (vertices instanceof Float32Array) {
  6896. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  6897. }
  6898. else {
  6899. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  6900. }
  6901. }
  6902. else {
  6903. if (vertices instanceof Float32Array) {
  6904. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  6905. }
  6906. else {
  6907. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  6908. }
  6909. }
  6910. this._resetVertexBufferBinding();
  6911. };
  6912. Engine.prototype._resetIndexBufferBinding = function () {
  6913. this.bindIndexBuffer(null);
  6914. this._cachedIndexBuffer = null;
  6915. };
  6916. Engine.prototype.createIndexBuffer = function (indices) {
  6917. var vbo = this._gl.createBuffer();
  6918. this.bindIndexBuffer(vbo);
  6919. // Check for 32 bits indices
  6920. var arrayBuffer;
  6921. var need32Bits = false;
  6922. if (this._caps.uintIndices) {
  6923. for (var index = 0; index < indices.length; index++) {
  6924. if (indices[index] > 65535) {
  6925. need32Bits = true;
  6926. break;
  6927. }
  6928. }
  6929. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  6930. }
  6931. else {
  6932. arrayBuffer = new Uint16Array(indices);
  6933. }
  6934. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  6935. this._resetIndexBufferBinding();
  6936. vbo.references = 1;
  6937. vbo.is32Bits = need32Bits;
  6938. return vbo;
  6939. };
  6940. Engine.prototype.bindArrayBuffer = function (buffer) {
  6941. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  6942. };
  6943. Engine.prototype.bindIndexBuffer = function (buffer) {
  6944. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  6945. };
  6946. Engine.prototype.bindBuffer = function (buffer, target) {
  6947. if (this._currentBoundBuffer[target] !== buffer) {
  6948. this._gl.bindBuffer(target, buffer);
  6949. this._currentBoundBuffer[target] = buffer;
  6950. }
  6951. };
  6952. Engine.prototype.updateArrayBuffer = function (data) {
  6953. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  6954. };
  6955. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  6956. var pointer = this._currentBufferPointers[indx];
  6957. var changed = false;
  6958. if (!pointer) {
  6959. changed = true;
  6960. this._currentBufferPointers[indx] = { indx: indx, size: size, type: type, normalized: normalized, stride: stride, offset: offset, buffer: buffer };
  6961. }
  6962. else {
  6963. if (pointer.buffer !== buffer) {
  6964. pointer.buffer = buffer;
  6965. changed = true;
  6966. }
  6967. if (pointer.size !== size) {
  6968. pointer.size = size;
  6969. changed = true;
  6970. }
  6971. if (pointer.type !== type) {
  6972. pointer.type = type;
  6973. changed = true;
  6974. }
  6975. if (pointer.normalized !== normalized) {
  6976. pointer.normalized = normalized;
  6977. changed = true;
  6978. }
  6979. if (pointer.stride !== stride) {
  6980. pointer.stride = stride;
  6981. changed = true;
  6982. }
  6983. if (pointer.offset !== offset) {
  6984. pointer.offset = offset;
  6985. changed = true;
  6986. }
  6987. }
  6988. if (changed) {
  6989. this.bindArrayBuffer(buffer);
  6990. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  6991. }
  6992. };
  6993. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  6994. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  6995. this._cachedVertexBuffers = vertexBuffer;
  6996. this._cachedEffectForVertexBuffers = effect;
  6997. var attributesCount = effect.getAttributesCount();
  6998. var offset = 0;
  6999. for (var index = 0; index < attributesCount; index++) {
  7000. if (index < vertexDeclaration.length) {
  7001. var order = effect.getAttributeLocation(index);
  7002. if (order >= 0) {
  7003. if (!this._vertexAttribArraysEnabled[order]) {
  7004. this._gl.enableVertexAttribArray(order);
  7005. this._vertexAttribArraysEnabled[order] = true;
  7006. }
  7007. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  7008. }
  7009. offset += vertexDeclaration[index] * 4;
  7010. }
  7011. else {
  7012. //disable effect attributes that have no data
  7013. var order = effect.getAttributeLocation(index);
  7014. if (this._vertexAttribArraysEnabled[order]) {
  7015. this._gl.disableVertexAttribArray(order);
  7016. this._vertexAttribArraysEnabled[order] = false;
  7017. }
  7018. }
  7019. }
  7020. }
  7021. if (this._cachedIndexBuffer !== indexBuffer) {
  7022. this._cachedIndexBuffer = indexBuffer;
  7023. this.bindIndexBuffer(indexBuffer);
  7024. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  7025. }
  7026. };
  7027. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  7028. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  7029. this._cachedVertexBuffers = vertexBuffers;
  7030. this._cachedEffectForVertexBuffers = effect;
  7031. var attributes = effect.getAttributesNames();
  7032. for (var index = 0; index < attributes.length; index++) {
  7033. var order = effect.getAttributeLocation(index);
  7034. if (order >= 0) {
  7035. var vertexBuffer = vertexBuffers[attributes[index]];
  7036. if (!vertexBuffer) {
  7037. if (this._vertexAttribArraysEnabled[order]) {
  7038. this._gl.disableVertexAttribArray(order);
  7039. this._vertexAttribArraysEnabled[order] = false;
  7040. }
  7041. continue;
  7042. }
  7043. if (!this._vertexAttribArraysEnabled[order]) {
  7044. this._gl.enableVertexAttribArray(order);
  7045. this._vertexAttribArraysEnabled[order] = true;
  7046. }
  7047. var buffer = vertexBuffer.getBuffer();
  7048. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  7049. if (vertexBuffer.getIsInstanced()) {
  7050. this._caps.instancedArrays.vertexAttribDivisorANGLE(order, 1);
  7051. this._currentInstanceLocations.push(order);
  7052. this._currentInstanceBuffers.push(buffer);
  7053. }
  7054. }
  7055. }
  7056. }
  7057. if (indexBuffer != null && this._cachedIndexBuffer !== indexBuffer) {
  7058. this._cachedIndexBuffer = indexBuffer;
  7059. this.bindIndexBuffer(indexBuffer);
  7060. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  7061. }
  7062. };
  7063. Engine.prototype.unbindInstanceAttributes = function () {
  7064. var boundBuffer;
  7065. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  7066. var instancesBuffer = this._currentInstanceBuffers[i];
  7067. if (boundBuffer != instancesBuffer) {
  7068. boundBuffer = instancesBuffer;
  7069. this.bindArrayBuffer(instancesBuffer);
  7070. }
  7071. var offsetLocation = this._currentInstanceLocations[i];
  7072. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  7073. }
  7074. this._currentInstanceBuffers.length = 0;
  7075. this._currentInstanceLocations.length = 0;
  7076. };
  7077. Engine.prototype._releaseBuffer = function (buffer) {
  7078. buffer.references--;
  7079. if (buffer.references === 0) {
  7080. this._gl.deleteBuffer(buffer);
  7081. return true;
  7082. }
  7083. return false;
  7084. };
  7085. Engine.prototype.createInstancesBuffer = function (capacity) {
  7086. var buffer = this._gl.createBuffer();
  7087. buffer.capacity = capacity;
  7088. this.bindArrayBuffer(buffer);
  7089. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  7090. return buffer;
  7091. };
  7092. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  7093. this._gl.deleteBuffer(buffer);
  7094. };
  7095. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  7096. this.bindArrayBuffer(instancesBuffer);
  7097. if (data) {
  7098. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  7099. }
  7100. if (offsetLocations[0].index !== undefined) {
  7101. var stride = 0;
  7102. for (var i = 0; i < offsetLocations.length; i++) {
  7103. var ai = offsetLocations[i];
  7104. stride += ai.attributeSize * 4;
  7105. }
  7106. for (var i = 0; i < offsetLocations.length; i++) {
  7107. var ai = offsetLocations[i];
  7108. if (!this._vertexAttribArraysEnabled[ai.index]) {
  7109. this._gl.enableVertexAttribArray(ai.index);
  7110. this._vertexAttribArraysEnabled[ai.index] = true;
  7111. }
  7112. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  7113. this._caps.instancedArrays.vertexAttribDivisorANGLE(ai.index, 1);
  7114. this._currentInstanceLocations.push(ai.index);
  7115. this._currentInstanceBuffers.push(instancesBuffer);
  7116. }
  7117. }
  7118. else {
  7119. for (var index = 0; index < 4; index++) {
  7120. var offsetLocation = offsetLocations[index];
  7121. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  7122. this._gl.enableVertexAttribArray(offsetLocation);
  7123. this._vertexAttribArraysEnabled[offsetLocation] = true;
  7124. }
  7125. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  7126. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  7127. this._currentInstanceLocations.push(offsetLocation);
  7128. this._currentInstanceBuffers.push(instancesBuffer);
  7129. }
  7130. }
  7131. };
  7132. Engine.prototype.applyStates = function () {
  7133. this._depthCullingState.apply(this._gl);
  7134. this._stencilState.apply(this._gl);
  7135. this._alphaState.apply(this._gl);
  7136. };
  7137. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  7138. // Apply states
  7139. this.applyStates();
  7140. this._drawCalls.addCount(1, false);
  7141. // Render
  7142. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  7143. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  7144. if (instancesCount) {
  7145. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  7146. return;
  7147. }
  7148. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  7149. };
  7150. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  7151. // Apply states
  7152. this.applyStates();
  7153. this._drawCalls.addCount(1, false);
  7154. if (instancesCount) {
  7155. this._caps.instancedArrays.drawArraysInstancedANGLE(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  7156. return;
  7157. }
  7158. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  7159. };
  7160. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  7161. // Apply states
  7162. this.applyStates();
  7163. this._drawCalls.addCount(1, false);
  7164. if (instancesCount) {
  7165. this._caps.instancedArrays.drawArraysInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount, instancesCount);
  7166. return;
  7167. }
  7168. this._gl.drawArrays(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount);
  7169. };
  7170. // Shaders
  7171. Engine.prototype._releaseEffect = function (effect) {
  7172. if (this._compiledEffects[effect._key]) {
  7173. delete this._compiledEffects[effect._key];
  7174. if (effect.getProgram()) {
  7175. this._gl.deleteProgram(effect.getProgram());
  7176. }
  7177. }
  7178. };
  7179. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  7180. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  7181. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  7182. var name = vertex + "+" + fragment + "@" + defines;
  7183. if (this._compiledEffects[name]) {
  7184. return this._compiledEffects[name];
  7185. }
  7186. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  7187. effect._key = name;
  7188. this._compiledEffects[name] = effect;
  7189. return effect;
  7190. };
  7191. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  7192. if (uniformsNames === void 0) { uniformsNames = []; }
  7193. if (samplers === void 0) { samplers = []; }
  7194. if (defines === void 0) { defines = ""; }
  7195. return this.createEffect({
  7196. vertex: "particles",
  7197. fragmentElement: fragmentName
  7198. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  7199. };
  7200. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  7201. context = context || this._gl;
  7202. var vertexShader = compileShader(context, vertexCode, "vertex", defines);
  7203. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines);
  7204. var shaderProgram = context.createProgram();
  7205. context.attachShader(shaderProgram, vertexShader);
  7206. context.attachShader(shaderProgram, fragmentShader);
  7207. context.linkProgram(shaderProgram);
  7208. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  7209. if (!linked) {
  7210. var error = context.getProgramInfoLog(shaderProgram);
  7211. if (error) {
  7212. throw new Error(error);
  7213. }
  7214. }
  7215. context.deleteShader(vertexShader);
  7216. context.deleteShader(fragmentShader);
  7217. return shaderProgram;
  7218. };
  7219. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  7220. var results = [];
  7221. for (var index = 0; index < uniformsNames.length; index++) {
  7222. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  7223. }
  7224. return results;
  7225. };
  7226. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  7227. var results = [];
  7228. for (var index = 0; index < attributesNames.length; index++) {
  7229. try {
  7230. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  7231. }
  7232. catch (e) {
  7233. results.push(-1);
  7234. }
  7235. }
  7236. return results;
  7237. };
  7238. Engine.prototype.enableEffect = function (effect) {
  7239. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  7240. if (effect && effect.onBind) {
  7241. effect.onBind(effect);
  7242. }
  7243. return;
  7244. }
  7245. // Use program
  7246. this.setProgram(effect.getProgram());
  7247. this._currentEffect = effect;
  7248. if (effect.onBind) {
  7249. effect.onBind(effect);
  7250. }
  7251. };
  7252. Engine.prototype.setIntArray = function (uniform, array) {
  7253. if (!uniform)
  7254. return;
  7255. this._gl.uniform1iv(uniform, array);
  7256. };
  7257. Engine.prototype.setIntArray2 = function (uniform, array) {
  7258. if (!uniform || array.length % 2 !== 0)
  7259. return;
  7260. this._gl.uniform2iv(uniform, array);
  7261. };
  7262. Engine.prototype.setIntArray3 = function (uniform, array) {
  7263. if (!uniform || array.length % 3 !== 0)
  7264. return;
  7265. this._gl.uniform3iv(uniform, array);
  7266. };
  7267. Engine.prototype.setIntArray4 = function (uniform, array) {
  7268. if (!uniform || array.length % 4 !== 0)
  7269. return;
  7270. this._gl.uniform4iv(uniform, array);
  7271. };
  7272. Engine.prototype.setFloatArray = function (uniform, array) {
  7273. if (!uniform)
  7274. return;
  7275. this._gl.uniform1fv(uniform, array);
  7276. };
  7277. Engine.prototype.setFloatArray2 = function (uniform, array) {
  7278. if (!uniform || array.length % 2 !== 0)
  7279. return;
  7280. this._gl.uniform2fv(uniform, array);
  7281. };
  7282. Engine.prototype.setFloatArray3 = function (uniform, array) {
  7283. if (!uniform || array.length % 3 !== 0)
  7284. return;
  7285. this._gl.uniform3fv(uniform, array);
  7286. };
  7287. Engine.prototype.setFloatArray4 = function (uniform, array) {
  7288. if (!uniform || array.length % 4 !== 0)
  7289. return;
  7290. this._gl.uniform4fv(uniform, array);
  7291. };
  7292. Engine.prototype.setArray = function (uniform, array) {
  7293. if (!uniform)
  7294. return;
  7295. this._gl.uniform1fv(uniform, array);
  7296. };
  7297. Engine.prototype.setArray2 = function (uniform, array) {
  7298. if (!uniform || array.length % 2 !== 0)
  7299. return;
  7300. this._gl.uniform2fv(uniform, array);
  7301. };
  7302. Engine.prototype.setArray3 = function (uniform, array) {
  7303. if (!uniform || array.length % 3 !== 0)
  7304. return;
  7305. this._gl.uniform3fv(uniform, array);
  7306. };
  7307. Engine.prototype.setArray4 = function (uniform, array) {
  7308. if (!uniform || array.length % 4 !== 0)
  7309. return;
  7310. this._gl.uniform4fv(uniform, array);
  7311. };
  7312. Engine.prototype.setMatrices = function (uniform, matrices) {
  7313. if (!uniform)
  7314. return;
  7315. this._gl.uniformMatrix4fv(uniform, false, matrices);
  7316. };
  7317. Engine.prototype.setMatrix = function (uniform, matrix) {
  7318. if (!uniform)
  7319. return;
  7320. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  7321. };
  7322. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  7323. if (!uniform)
  7324. return;
  7325. this._gl.uniformMatrix3fv(uniform, false, matrix);
  7326. };
  7327. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  7328. if (!uniform)
  7329. return;
  7330. this._gl.uniformMatrix2fv(uniform, false, matrix);
  7331. };
  7332. Engine.prototype.setFloat = function (uniform, value) {
  7333. if (!uniform)
  7334. return;
  7335. this._gl.uniform1f(uniform, value);
  7336. };
  7337. Engine.prototype.setFloat2 = function (uniform, x, y) {
  7338. if (!uniform)
  7339. return;
  7340. this._gl.uniform2f(uniform, x, y);
  7341. };
  7342. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  7343. if (!uniform)
  7344. return;
  7345. this._gl.uniform3f(uniform, x, y, z);
  7346. };
  7347. Engine.prototype.setBool = function (uniform, bool) {
  7348. if (!uniform)
  7349. return;
  7350. this._gl.uniform1i(uniform, bool);
  7351. };
  7352. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  7353. if (!uniform)
  7354. return;
  7355. this._gl.uniform4f(uniform, x, y, z, w);
  7356. };
  7357. Engine.prototype.setColor3 = function (uniform, color3) {
  7358. if (!uniform)
  7359. return;
  7360. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  7361. };
  7362. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  7363. if (!uniform)
  7364. return;
  7365. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  7366. };
  7367. // States
  7368. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  7369. if (zOffset === void 0) { zOffset = 0; }
  7370. if (reverseSide === void 0) { reverseSide = false; }
  7371. // Culling
  7372. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  7373. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  7374. var cullFace = this.cullBackFaces ? showSide : hideSide;
  7375. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  7376. if (culling) {
  7377. this._depthCullingState.cullFace = cullFace;
  7378. this._depthCullingState.cull = true;
  7379. }
  7380. else {
  7381. this._depthCullingState.cull = false;
  7382. }
  7383. }
  7384. // Z offset
  7385. this._depthCullingState.zOffset = zOffset;
  7386. };
  7387. Engine.prototype.setDepthBuffer = function (enable) {
  7388. this._depthCullingState.depthTest = enable;
  7389. };
  7390. Engine.prototype.getDepthWrite = function () {
  7391. return this._depthCullingState.depthMask;
  7392. };
  7393. Engine.prototype.setDepthWrite = function (enable) {
  7394. this._depthCullingState.depthMask = enable;
  7395. };
  7396. Engine.prototype.setColorWrite = function (enable) {
  7397. this._gl.colorMask(enable, enable, enable, enable);
  7398. };
  7399. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  7400. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  7401. if (this._alphaMode === mode) {
  7402. return;
  7403. }
  7404. switch (mode) {
  7405. case Engine.ALPHA_DISABLE:
  7406. this._alphaState.alphaBlend = false;
  7407. break;
  7408. case Engine.ALPHA_COMBINE:
  7409. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  7410. this._alphaState.alphaBlend = true;
  7411. break;
  7412. case Engine.ALPHA_ONEONE:
  7413. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  7414. this._alphaState.alphaBlend = true;
  7415. break;
  7416. case Engine.ALPHA_ADD:
  7417. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  7418. this._alphaState.alphaBlend = true;
  7419. break;
  7420. case Engine.ALPHA_SUBTRACT:
  7421. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  7422. this._alphaState.alphaBlend = true;
  7423. break;
  7424. case Engine.ALPHA_MULTIPLY:
  7425. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  7426. this._alphaState.alphaBlend = true;
  7427. break;
  7428. case Engine.ALPHA_MAXIMIZED:
  7429. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  7430. this._alphaState.alphaBlend = true;
  7431. break;
  7432. }
  7433. if (!noDepthWriteChange) {
  7434. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  7435. }
  7436. this._alphaMode = mode;
  7437. };
  7438. Engine.prototype.getAlphaMode = function () {
  7439. return this._alphaMode;
  7440. };
  7441. Engine.prototype.setAlphaTesting = function (enable) {
  7442. this._alphaTest = enable;
  7443. };
  7444. Engine.prototype.getAlphaTesting = function () {
  7445. return this._alphaTest;
  7446. };
  7447. // Textures
  7448. Engine.prototype.wipeCaches = function () {
  7449. this.resetTextureCache();
  7450. this._currentEffect = null;
  7451. this._stencilState.reset();
  7452. this._depthCullingState.reset();
  7453. this.setDepthFunctionToLessOrEqual();
  7454. this._alphaState.reset();
  7455. this._cachedVertexBuffers = null;
  7456. this._cachedIndexBuffer = null;
  7457. this._cachedEffectForVertexBuffers = null;
  7458. };
  7459. Engine.prototype.setSamplingMode = function (texture, samplingMode) {
  7460. var gl = this._gl;
  7461. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  7462. var magFilter = gl.NEAREST;
  7463. var minFilter = gl.NEAREST;
  7464. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  7465. magFilter = gl.LINEAR;
  7466. minFilter = gl.LINEAR;
  7467. }
  7468. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  7469. magFilter = gl.LINEAR;
  7470. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  7471. }
  7472. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  7473. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  7474. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  7475. texture.samplingMode = samplingMode;
  7476. };
  7477. Engine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer) {
  7478. var _this = this;
  7479. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  7480. if (onLoad === void 0) { onLoad = null; }
  7481. if (onError === void 0) { onError = null; }
  7482. if (buffer === void 0) { buffer = null; }
  7483. var texture = this._gl.createTexture();
  7484. var extension;
  7485. var fromData = false;
  7486. if (url.substr(0, 5) === "data:") {
  7487. fromData = true;
  7488. }
  7489. if (!fromData)
  7490. extension = url.substr(url.length - 4, 4).toLowerCase();
  7491. else {
  7492. var oldUrl = url;
  7493. fromData = oldUrl.split(':');
  7494. url = oldUrl;
  7495. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  7496. }
  7497. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  7498. var isTGA = (extension === ".tga");
  7499. scene._addPendingData(texture);
  7500. texture.url = url;
  7501. texture.noMipmap = noMipmap;
  7502. texture.references = 1;
  7503. texture.samplingMode = samplingMode;
  7504. this._loadedTexturesCache.push(texture);
  7505. var onerror = function () {
  7506. scene._removePendingData(texture);
  7507. if (onError) {
  7508. onError();
  7509. }
  7510. };
  7511. var callback;
  7512. if (isTGA) {
  7513. callback = function (arrayBuffer) {
  7514. var data = new Uint8Array(arrayBuffer);
  7515. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  7516. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  7517. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  7518. }, onLoad, samplingMode);
  7519. };
  7520. if (!(fromData instanceof Array))
  7521. BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
  7522. callback(arrayBuffer);
  7523. }, null, scene.database, true, onerror);
  7524. else
  7525. callback(buffer);
  7526. }
  7527. else if (isDDS) {
  7528. callback = function (data) {
  7529. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  7530. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  7531. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  7532. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  7533. }, onLoad, samplingMode);
  7534. };
  7535. if (!(fromData instanceof Array))
  7536. BABYLON.Tools.LoadFile(url, function (data) {
  7537. callback(data);
  7538. }, null, scene.database, true, onerror);
  7539. else
  7540. callback(buffer);
  7541. }
  7542. else {
  7543. var onload = function (img) {
  7544. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  7545. var isPot = (img.width === potWidth && img.height === potHeight);
  7546. if (!isPot) {
  7547. _this._prepareWorkingCanvas();
  7548. _this._workingCanvas.width = potWidth;
  7549. _this._workingCanvas.height = potHeight;
  7550. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  7551. _this._workingContext.imageSmoothingEnabled = false;
  7552. _this._workingContext.mozImageSmoothingEnabled = false;
  7553. _this._workingContext.oImageSmoothingEnabled = false;
  7554. _this._workingContext.webkitImageSmoothingEnabled = false;
  7555. _this._workingContext.msImageSmoothingEnabled = false;
  7556. }
  7557. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  7558. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  7559. _this._workingContext.imageSmoothingEnabled = true;
  7560. _this._workingContext.mozImageSmoothingEnabled = true;
  7561. _this._workingContext.oImageSmoothingEnabled = true;
  7562. _this._workingContext.webkitImageSmoothingEnabled = true;
  7563. _this._workingContext.msImageSmoothingEnabled = true;
  7564. }
  7565. }
  7566. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  7567. }, onLoad, samplingMode);
  7568. };
  7569. if (!(fromData instanceof Array))
  7570. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  7571. else
  7572. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  7573. }
  7574. return texture;
  7575. };
  7576. Engine.prototype._getInternalFormat = function (format) {
  7577. var internalFormat = this._gl.RGBA;
  7578. switch (format) {
  7579. case Engine.TEXTUREFORMAT_ALPHA:
  7580. internalFormat = this._gl.ALPHA;
  7581. break;
  7582. case Engine.TEXTUREFORMAT_LUMINANCE:
  7583. internalFormat = this._gl.LUMINANCE;
  7584. break;
  7585. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  7586. internalFormat = this._gl.LUMINANCE_ALPHA;
  7587. break;
  7588. case Engine.TEXTUREFORMAT_RGB:
  7589. internalFormat = this._gl.RGB;
  7590. break;
  7591. case Engine.TEXTUREFORMAT_RGBA:
  7592. internalFormat = this._gl.RGBA;
  7593. break;
  7594. }
  7595. return internalFormat;
  7596. };
  7597. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression) {
  7598. if (compression === void 0) { compression = null; }
  7599. var internalFormat = this._getInternalFormat(format);
  7600. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  7601. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  7602. if (texture._width % 4 !== 0) {
  7603. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  7604. }
  7605. if (compression) {
  7606. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture._width, texture._height, 0, data);
  7607. }
  7608. else {
  7609. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture._width, texture._height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  7610. }
  7611. if (texture.generateMipMaps) {
  7612. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  7613. }
  7614. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  7615. this.resetTextureCache();
  7616. texture.isReady = true;
  7617. };
  7618. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression) {
  7619. if (compression === void 0) { compression = null; }
  7620. var texture = this._gl.createTexture();
  7621. texture._baseWidth = width;
  7622. texture._baseHeight = height;
  7623. texture._width = width;
  7624. texture._height = height;
  7625. texture.references = 1;
  7626. this.updateRawTexture(texture, data, format, invertY, compression);
  7627. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  7628. // Filters
  7629. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  7630. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  7631. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  7632. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  7633. texture.samplingMode = samplingMode;
  7634. this._loadedTexturesCache.push(texture);
  7635. return texture;
  7636. };
  7637. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  7638. var texture = this._gl.createTexture();
  7639. texture._baseWidth = width;
  7640. texture._baseHeight = height;
  7641. if (generateMipMaps) {
  7642. width = BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize);
  7643. height = BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize);
  7644. }
  7645. this.resetTextureCache();
  7646. texture._width = width;
  7647. texture._height = height;
  7648. texture.isReady = false;
  7649. texture.generateMipMaps = generateMipMaps;
  7650. texture.references = 1;
  7651. texture.samplingMode = samplingMode;
  7652. this.updateTextureSamplingMode(samplingMode, texture);
  7653. this._loadedTexturesCache.push(texture);
  7654. return texture;
  7655. };
  7656. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  7657. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  7658. if (texture.isCube) {
  7659. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  7660. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  7661. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  7662. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  7663. }
  7664. else {
  7665. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  7666. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  7667. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  7668. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  7669. }
  7670. };
  7671. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha) {
  7672. if (premulAlpha === void 0) { premulAlpha = false; }
  7673. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  7674. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  7675. if (premulAlpha) {
  7676. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  7677. }
  7678. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  7679. if (texture.generateMipMaps) {
  7680. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  7681. }
  7682. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  7683. this.resetTextureCache();
  7684. texture.isReady = true;
  7685. };
  7686. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  7687. if (texture._isDisabled) {
  7688. return;
  7689. }
  7690. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  7691. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  7692. try {
  7693. // Testing video texture support
  7694. if (this._videoTextureSupported === undefined) {
  7695. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  7696. if (this._gl.getError() !== 0) {
  7697. this._videoTextureSupported = false;
  7698. }
  7699. else {
  7700. this._videoTextureSupported = true;
  7701. }
  7702. }
  7703. // Copy video through the current working canvas if video texture is not supported
  7704. if (!this._videoTextureSupported) {
  7705. if (!texture._workingCanvas) {
  7706. texture._workingCanvas = document.createElement("canvas");
  7707. texture._workingContext = texture._workingCanvas.getContext("2d");
  7708. texture._workingCanvas.width = texture._width;
  7709. texture._workingCanvas.height = texture._height;
  7710. }
  7711. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  7712. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  7713. }
  7714. else {
  7715. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  7716. }
  7717. if (texture.generateMipMaps) {
  7718. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  7719. }
  7720. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  7721. this.resetTextureCache();
  7722. texture.isReady = true;
  7723. }
  7724. catch (ex) {
  7725. // Something unexpected
  7726. // Let's disable the texture
  7727. texture._isDisabled = true;
  7728. }
  7729. };
  7730. Engine.prototype.createRenderTargetTexture = function (size, options) {
  7731. // old version had a "generateMipMaps" arg instead of options.
  7732. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  7733. // in the same way, generateDepthBuffer is defaulted to true
  7734. var generateMipMaps = false;
  7735. var generateDepthBuffer = true;
  7736. var generateStencilBuffer = false;
  7737. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  7738. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  7739. if (options !== undefined) {
  7740. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  7741. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  7742. generateStencilBuffer = generateDepthBuffer && options.generateStencilBuffer;
  7743. type = options.type === undefined ? type : options.type;
  7744. if (options.samplingMode !== undefined) {
  7745. samplingMode = options.samplingMode;
  7746. }
  7747. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  7748. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  7749. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  7750. }
  7751. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  7752. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  7753. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  7754. }
  7755. }
  7756. var gl = this._gl;
  7757. var texture = gl.createTexture();
  7758. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  7759. var width = size.width || size;
  7760. var height = size.height || size;
  7761. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  7762. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  7763. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  7764. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  7765. }
  7766. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  7767. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  7768. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  7769. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  7770. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, getWebGLTextureType(gl, type), null);
  7771. var depthStencilBuffer;
  7772. // Create the depth/stencil buffer
  7773. if (generateStencilBuffer) {
  7774. depthStencilBuffer = gl.createRenderbuffer();
  7775. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  7776. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  7777. }
  7778. else if (generateDepthBuffer) {
  7779. depthStencilBuffer = gl.createRenderbuffer();
  7780. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  7781. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  7782. }
  7783. // Create the framebuffer
  7784. var framebuffer = gl.createFramebuffer();
  7785. this.bindUnboundFramebuffer(framebuffer);
  7786. // Manage attachments
  7787. if (generateStencilBuffer) {
  7788. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  7789. }
  7790. else if (generateDepthBuffer) {
  7791. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  7792. }
  7793. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  7794. if (generateMipMaps) {
  7795. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  7796. }
  7797. // Unbind
  7798. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  7799. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  7800. this.bindUnboundFramebuffer(null);
  7801. texture._framebuffer = framebuffer;
  7802. if (generateDepthBuffer) {
  7803. texture._depthBuffer = depthStencilBuffer;
  7804. }
  7805. texture._baseWidth = width;
  7806. texture._baseHeight = height;
  7807. texture._width = width;
  7808. texture._height = height;
  7809. texture.isReady = true;
  7810. texture.generateMipMaps = generateMipMaps;
  7811. texture.references = 1;
  7812. texture.samplingMode = samplingMode;
  7813. texture.type = type;
  7814. this.resetTextureCache();
  7815. this._loadedTexturesCache.push(texture);
  7816. return texture;
  7817. };
  7818. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  7819. var gl = this._gl;
  7820. var texture = gl.createTexture();
  7821. var generateMipMaps = true;
  7822. var generateDepthBuffer = true;
  7823. var generateStencilBuffer = false;
  7824. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  7825. if (options !== undefined) {
  7826. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  7827. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  7828. generateStencilBuffer = generateDepthBuffer && options.generateStencilBuffer;
  7829. if (options.samplingMode !== undefined) {
  7830. samplingMode = options.samplingMode;
  7831. }
  7832. }
  7833. texture.isCube = true;
  7834. texture.references = 1;
  7835. texture.generateMipMaps = generateMipMaps;
  7836. texture.references = 1;
  7837. texture.samplingMode = samplingMode;
  7838. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  7839. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  7840. for (var face = 0; face < 6; face++) {
  7841. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  7842. }
  7843. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  7844. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  7845. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  7846. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  7847. // Create the depth buffer
  7848. var depthStencilBuffer;
  7849. // Create the depth/stencil buffer
  7850. if (generateStencilBuffer) {
  7851. depthStencilBuffer = gl.createRenderbuffer();
  7852. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  7853. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, size, size);
  7854. }
  7855. else if (generateDepthBuffer) {
  7856. depthStencilBuffer = gl.createRenderbuffer();
  7857. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  7858. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, size, size);
  7859. }
  7860. // Create the framebuffer
  7861. var framebuffer = gl.createFramebuffer();
  7862. this.bindUnboundFramebuffer(framebuffer);
  7863. // Manage attachments
  7864. if (generateStencilBuffer) {
  7865. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  7866. }
  7867. else if (generateDepthBuffer) {
  7868. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  7869. }
  7870. // Mipmaps
  7871. if (texture.generateMipMaps) {
  7872. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  7873. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  7874. }
  7875. // Unbind
  7876. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  7877. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  7878. this.bindUnboundFramebuffer(null);
  7879. texture._framebuffer = framebuffer;
  7880. if (generateDepthBuffer) {
  7881. texture._depthBuffer = depthStencilBuffer;
  7882. }
  7883. texture._width = size;
  7884. texture._height = size;
  7885. texture.isReady = true;
  7886. this.resetTextureCache();
  7887. this._loadedTexturesCache.push(texture);
  7888. return texture;
  7889. };
  7890. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap) {
  7891. var _this = this;
  7892. var gl = this._gl;
  7893. var texture = gl.createTexture();
  7894. texture.isCube = true;
  7895. texture.url = rootUrl;
  7896. texture.references = 1;
  7897. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  7898. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  7899. if (isDDS) {
  7900. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  7901. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  7902. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  7903. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  7904. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  7905. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  7906. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  7907. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  7908. }
  7909. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  7910. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  7911. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  7912. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  7913. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  7914. _this.resetTextureCache();
  7915. texture._width = info.width;
  7916. texture._height = info.height;
  7917. texture.isReady = true;
  7918. }, null, null, true);
  7919. }
  7920. else {
  7921. cascadeLoad(rootUrl, scene, function (imgs) {
  7922. var width = BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  7923. var height = width;
  7924. _this._prepareWorkingCanvas();
  7925. _this._workingCanvas.width = width;
  7926. _this._workingCanvas.height = height;
  7927. var faces = [
  7928. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  7929. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  7930. ];
  7931. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  7932. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  7933. for (var index = 0; index < faces.length; index++) {
  7934. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  7935. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  7936. }
  7937. if (!noMipmap) {
  7938. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  7939. }
  7940. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  7941. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  7942. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  7943. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  7944. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  7945. _this.resetTextureCache();
  7946. texture._width = width;
  7947. texture._height = height;
  7948. texture.isReady = true;
  7949. }, files);
  7950. }
  7951. this._loadedTexturesCache.push(texture);
  7952. return texture;
  7953. };
  7954. Engine.prototype.updateTextureSize = function (texture, width, height) {
  7955. texture._width = width;
  7956. texture._height = height;
  7957. texture._size = width * height;
  7958. texture._baseWidth = width;
  7959. texture._baseHeight = height;
  7960. };
  7961. Engine.prototype.createRawCubeTexture = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator) {
  7962. var _this = this;
  7963. var gl = this._gl;
  7964. var texture = gl.createTexture();
  7965. scene._addPendingData(texture);
  7966. texture.isCube = true;
  7967. texture.references = 1;
  7968. texture.url = url;
  7969. var internalFormat = this._getInternalFormat(format);
  7970. var textureType = gl.UNSIGNED_BYTE;
  7971. if (type === Engine.TEXTURETYPE_FLOAT) {
  7972. textureType = gl.FLOAT;
  7973. }
  7974. var width = size;
  7975. var height = width;
  7976. var isPot = (BABYLON.Tools.IsExponentOfTwo(width) && BABYLON.Tools.IsExponentOfTwo(height));
  7977. texture._width = width;
  7978. texture._height = height;
  7979. var onerror = function () {
  7980. scene._removePendingData(texture);
  7981. };
  7982. var internalCallback = function (data) {
  7983. var rgbeDataArrays = callback(data);
  7984. var facesIndex = [
  7985. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  7986. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  7987. ];
  7988. width = texture._width;
  7989. height = texture._height;
  7990. isPot = (BABYLON.Tools.IsExponentOfTwo(width) && BABYLON.Tools.IsExponentOfTwo(height));
  7991. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  7992. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  7993. if (!noMipmap && isPot) {
  7994. if (mipmmapGenerator) {
  7995. var arrayTemp = [];
  7996. // Data are known to be in +X +Y +Z -X -Y -Z
  7997. // mipmmapGenerator data is expected to be order in +X -X +Y -Y +Z -Z
  7998. arrayTemp.push(rgbeDataArrays[0]); // +X
  7999. arrayTemp.push(rgbeDataArrays[3]); // -X
  8000. arrayTemp.push(rgbeDataArrays[1]); // +Y
  8001. arrayTemp.push(rgbeDataArrays[4]); // -Y
  8002. arrayTemp.push(rgbeDataArrays[2]); // +Z
  8003. arrayTemp.push(rgbeDataArrays[5]); // -Z
  8004. var mipData = mipmmapGenerator(arrayTemp);
  8005. for (var level = 0; level < mipData.length; level++) {
  8006. var mipSize = width >> level;
  8007. // mipData is order in +X -X +Y -Y +Z -Z
  8008. gl.texImage2D(facesIndex[0], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][0]);
  8009. gl.texImage2D(facesIndex[1], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][2]);
  8010. gl.texImage2D(facesIndex[2], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][4]);
  8011. gl.texImage2D(facesIndex[3], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][1]);
  8012. gl.texImage2D(facesIndex[4], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][3]);
  8013. gl.texImage2D(facesIndex[5], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][5]);
  8014. }
  8015. }
  8016. else {
  8017. // Data are known to be in +X +Y +Z -X -Y -Z
  8018. for (var index = 0; index < facesIndex.length; index++) {
  8019. var faceData = rgbeDataArrays[index];
  8020. gl.texImage2D(facesIndex[index], 0, internalFormat, width, height, 0, internalFormat, textureType, faceData);
  8021. }
  8022. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  8023. // Workaround firefox bug fix https://bugzilla.mozilla.org/show_bug.cgi?id=1221822
  8024. // By following the webgl standard changes from Revision 7, 2014/11/24
  8025. // Firefox Removed the support for RGB32F, since it is not natively supported on all platforms where WebGL is implemented.
  8026. if (textureType === gl.FLOAT && internalFormat === gl.RGB && gl.getError() === 1282) {
  8027. BABYLON.Tools.Log("RGB32F not renderable on Firefox, trying fallback to RGBA32F.");
  8028. // Data are known to be in +X +Y +Z -X -Y -Z
  8029. for (var index = 0; index < facesIndex.length; index++) {
  8030. var faceData = rgbeDataArrays[index];
  8031. // Create a new RGBA Face.
  8032. var newFaceData = new Float32Array(width * height * 4);
  8033. for (var x = 0; x < width; x++) {
  8034. for (var y = 0; y < height; y++) {
  8035. var index_1 = (y * width + x) * 3;
  8036. var newIndex = (y * width + x) * 4;
  8037. // Map Old Value to new value.
  8038. newFaceData[newIndex + 0] = faceData[index_1 + 0];
  8039. newFaceData[newIndex + 1] = faceData[index_1 + 1];
  8040. newFaceData[newIndex + 2] = faceData[index_1 + 2];
  8041. // Add fully opaque alpha channel.
  8042. newFaceData[newIndex + 3] = 1;
  8043. }
  8044. }
  8045. // Reupload the face.
  8046. gl.texImage2D(facesIndex[index], 0, gl.RGBA, width, height, 0, gl.RGBA, textureType, newFaceData);
  8047. }
  8048. // Try to generate mipmap again.
  8049. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  8050. }
  8051. }
  8052. }
  8053. else {
  8054. noMipmap = true;
  8055. }
  8056. if (textureType === gl.FLOAT && !_this._caps.textureFloatLinearFiltering) {
  8057. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  8058. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  8059. }
  8060. else if (textureType === HALF_FLOAT_OES && !_this._caps.textureHalfFloatLinearFiltering) {
  8061. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  8062. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  8063. }
  8064. else {
  8065. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  8066. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  8067. }
  8068. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  8069. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  8070. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  8071. texture.isReady = true;
  8072. _this.resetTextureCache();
  8073. scene._removePendingData(texture);
  8074. };
  8075. BABYLON.Tools.LoadFile(url, function (data) {
  8076. internalCallback(data);
  8077. }, onerror, scene.database, true);
  8078. return texture;
  8079. };
  8080. ;
  8081. Engine.prototype._releaseTexture = function (texture) {
  8082. var gl = this._gl;
  8083. if (texture._framebuffer) {
  8084. gl.deleteFramebuffer(texture._framebuffer);
  8085. }
  8086. if (texture._depthBuffer) {
  8087. gl.deleteRenderbuffer(texture._depthBuffer);
  8088. }
  8089. gl.deleteTexture(texture);
  8090. // Unbind channels
  8091. this.unbindAllTextures();
  8092. var index = this._loadedTexturesCache.indexOf(texture);
  8093. if (index !== -1) {
  8094. this._loadedTexturesCache.splice(index, 1);
  8095. }
  8096. };
  8097. Engine.prototype.setProgram = function (program) {
  8098. if (this._currentProgram !== program) {
  8099. this._gl.useProgram(program);
  8100. this._currentProgram = program;
  8101. }
  8102. };
  8103. Engine.prototype.bindSamplers = function (effect) {
  8104. this.setProgram(effect.getProgram());
  8105. var samplers = effect.getSamplers();
  8106. for (var index = 0; index < samplers.length; index++) {
  8107. var uniform = effect.getUniform(samplers[index]);
  8108. this._gl.uniform1i(uniform, index);
  8109. }
  8110. this._currentEffect = null;
  8111. };
  8112. Engine.prototype.activateTexture = function (texture) {
  8113. if (this._activeTexture !== texture) {
  8114. this._gl.activeTexture(texture);
  8115. this._activeTexture = texture;
  8116. }
  8117. };
  8118. Engine.prototype._bindTextureDirectly = function (target, texture) {
  8119. if (this._activeTexturesCache[this._activeTexture] !== texture) {
  8120. this._gl.bindTexture(target, texture);
  8121. this._activeTexturesCache[this._activeTexture] = texture;
  8122. }
  8123. };
  8124. Engine.prototype._bindTexture = function (channel, texture) {
  8125. if (channel < 0) {
  8126. return;
  8127. }
  8128. this.activateTexture(this._gl["TEXTURE" + channel]);
  8129. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  8130. };
  8131. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  8132. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  8133. };
  8134. Engine.prototype.unbindAllTextures = function () {
  8135. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  8136. this.activateTexture(this._gl["TEXTURE" + channel]);
  8137. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  8138. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  8139. }
  8140. };
  8141. Engine.prototype.setTexture = function (channel, uniform, texture) {
  8142. if (channel < 0) {
  8143. return;
  8144. }
  8145. this._gl.uniform1i(uniform, channel);
  8146. this._setTexture(channel, texture);
  8147. };
  8148. Engine.prototype._setTexture = function (channel, texture) {
  8149. // Not ready?
  8150. if (!texture || !texture.isReady()) {
  8151. if (this._activeTexturesCache[channel] != null) {
  8152. this.activateTexture(this._gl["TEXTURE" + channel]);
  8153. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  8154. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  8155. }
  8156. return;
  8157. }
  8158. // Video
  8159. var alreadyActivated = false;
  8160. if (texture instanceof BABYLON.VideoTexture) {
  8161. this.activateTexture(this._gl["TEXTURE" + channel]);
  8162. alreadyActivated = true;
  8163. texture.update();
  8164. }
  8165. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  8166. texture.delayLoad();
  8167. return;
  8168. }
  8169. var internalTexture = texture.getInternalTexture();
  8170. if (this._activeTexturesCache[channel] === internalTexture) {
  8171. return;
  8172. }
  8173. if (!alreadyActivated) {
  8174. this.activateTexture(this._gl["TEXTURE" + channel]);
  8175. }
  8176. if (internalTexture.isCube) {
  8177. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  8178. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  8179. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  8180. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  8181. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  8182. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  8183. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  8184. }
  8185. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  8186. }
  8187. else {
  8188. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture);
  8189. if (internalTexture._cachedWrapU !== texture.wrapU) {
  8190. internalTexture._cachedWrapU = texture.wrapU;
  8191. switch (texture.wrapU) {
  8192. case BABYLON.Texture.WRAP_ADDRESSMODE:
  8193. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  8194. break;
  8195. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  8196. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  8197. break;
  8198. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  8199. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  8200. break;
  8201. }
  8202. }
  8203. if (internalTexture._cachedWrapV !== texture.wrapV) {
  8204. internalTexture._cachedWrapV = texture.wrapV;
  8205. switch (texture.wrapV) {
  8206. case BABYLON.Texture.WRAP_ADDRESSMODE:
  8207. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  8208. break;
  8209. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  8210. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  8211. break;
  8212. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  8213. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  8214. break;
  8215. }
  8216. }
  8217. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  8218. }
  8219. };
  8220. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  8221. if (channel < 0) {
  8222. return;
  8223. }
  8224. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  8225. this._textureUnits = new Int32Array(textures.length);
  8226. }
  8227. for (var i = 0; i < textures.length; i++) {
  8228. this._textureUnits[i] = channel + i;
  8229. }
  8230. this._gl.uniform1iv(uniform, this._textureUnits);
  8231. for (var index = 0; index < textures.length; index++) {
  8232. this._setTexture(channel + index, textures[index]);
  8233. }
  8234. };
  8235. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  8236. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  8237. var value = texture.anisotropicFilteringLevel;
  8238. if (texture.getInternalTexture().samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  8239. value = 1;
  8240. }
  8241. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  8242. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  8243. texture._cachedAnisotropicFilteringLevel = value;
  8244. }
  8245. };
  8246. Engine.prototype.readPixels = function (x, y, width, height) {
  8247. var data = new Uint8Array(height * width * 4);
  8248. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  8249. return data;
  8250. };
  8251. /**
  8252. * Add an externaly attached data from its key.
  8253. * This method call will fail and return false, if such key already exists.
  8254. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  8255. * @param key the unique key that identifies the data
  8256. * @param data the data object to associate to the key for this Engine instance
  8257. * @return true if no such key were already present and the data was added successfully, false otherwise
  8258. */
  8259. Engine.prototype.addExternalData = function (key, data) {
  8260. return this._externalData.add(key, data);
  8261. };
  8262. /**
  8263. * Get an externaly attached data from its key
  8264. * @param key the unique key that identifies the data
  8265. * @return the associated data, if present (can be null), or undefined if not present
  8266. */
  8267. Engine.prototype.getExternalData = function (key) {
  8268. return this._externalData.get(key);
  8269. };
  8270. /**
  8271. * Get an externaly attached data from its key, create it using a factory if it's not already present
  8272. * @param key the unique key that identifies the data
  8273. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  8274. * @return the associated data, can be null if the factory returned null.
  8275. */
  8276. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  8277. return this._externalData.getOrAddWithFactory(key, factory);
  8278. };
  8279. /**
  8280. * Remove an externaly attached data from the Engine instance
  8281. * @param key the unique key that identifies the data
  8282. * @return true if the data was successfully removed, false if it doesn't exist
  8283. */
  8284. Engine.prototype.removeExternalData = function (key) {
  8285. return this._externalData.remove(key);
  8286. };
  8287. Engine.prototype.releaseInternalTexture = function (texture) {
  8288. if (!texture) {
  8289. return;
  8290. }
  8291. texture.references--;
  8292. // Final reference ?
  8293. if (texture.references === 0) {
  8294. var texturesCache = this.getLoadedTexturesCache();
  8295. var index = texturesCache.indexOf(texture);
  8296. if (index > -1) {
  8297. texturesCache.splice(index, 1);
  8298. }
  8299. this._releaseTexture(texture);
  8300. }
  8301. };
  8302. // Dispose
  8303. Engine.prototype.dispose = function () {
  8304. this.hideLoadingUI();
  8305. this.stopRenderLoop();
  8306. // Release scenes
  8307. while (this.scenes.length) {
  8308. this.scenes[0].dispose();
  8309. }
  8310. // Release audio engine
  8311. Engine.audioEngine.dispose();
  8312. // Release effects
  8313. for (var name in this._compiledEffects) {
  8314. this._gl.deleteProgram(this._compiledEffects[name]._program);
  8315. }
  8316. // Unbind
  8317. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  8318. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  8319. continue;
  8320. }
  8321. this._gl.disableVertexAttribArray(i);
  8322. }
  8323. this._gl = null;
  8324. // Events
  8325. window.removeEventListener("blur", this._onBlur);
  8326. window.removeEventListener("focus", this._onFocus);
  8327. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  8328. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  8329. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  8330. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  8331. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  8332. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  8333. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  8334. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  8335. };
  8336. // Loading screen
  8337. Engine.prototype.displayLoadingUI = function () {
  8338. this._loadingScreen.displayLoadingUI();
  8339. };
  8340. Engine.prototype.hideLoadingUI = function () {
  8341. this._loadingScreen.hideLoadingUI();
  8342. };
  8343. Object.defineProperty(Engine.prototype, "loadingScreen", {
  8344. get: function () {
  8345. return this._loadingScreen;
  8346. },
  8347. set: function (loadingScreen) {
  8348. this._loadingScreen = loadingScreen;
  8349. },
  8350. enumerable: true,
  8351. configurable: true
  8352. });
  8353. Object.defineProperty(Engine.prototype, "loadingUIText", {
  8354. set: function (text) {
  8355. this._loadingScreen.loadingUIText = text;
  8356. },
  8357. enumerable: true,
  8358. configurable: true
  8359. });
  8360. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  8361. set: function (color) {
  8362. this._loadingScreen.loadingUIBackgroundColor = color;
  8363. },
  8364. enumerable: true,
  8365. configurable: true
  8366. });
  8367. Engine.prototype.attachContextLostEvent = function (callback) {
  8368. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  8369. };
  8370. Engine.prototype.attachContextRestoredEvent = function (callback) {
  8371. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  8372. };
  8373. // FPS
  8374. Engine.prototype.getFps = function () {
  8375. return this.fps;
  8376. };
  8377. Engine.prototype.getDeltaTime = function () {
  8378. return this.deltaTime;
  8379. };
  8380. Engine.prototype._measureFps = function () {
  8381. this.previousFramesDuration.push(BABYLON.Tools.Now);
  8382. var length = this.previousFramesDuration.length;
  8383. if (length >= 2) {
  8384. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  8385. }
  8386. if (length >= this.fpsRange) {
  8387. if (length > this.fpsRange) {
  8388. this.previousFramesDuration.splice(0, 1);
  8389. length = this.previousFramesDuration.length;
  8390. }
  8391. var sum = 0;
  8392. for (var id = 0; id < length - 1; id++) {
  8393. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  8394. }
  8395. this.fps = 1000.0 / (sum / (length - 1));
  8396. }
  8397. };
  8398. Engine.prototype._canRenderToFloatTexture = function () {
  8399. return this._canRenderToTextureOfType(BABYLON.Engine.TEXTURETYPE_FLOAT, 'OES_texture_float');
  8400. };
  8401. Engine.prototype._canRenderToHalfFloatTexture = function () {
  8402. return this._canRenderToTextureOfType(BABYLON.Engine.TEXTURETYPE_HALF_FLOAT, 'OES_texture_half_float');
  8403. };
  8404. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  8405. Engine.prototype._canRenderToTextureOfType = function (format, extension) {
  8406. var tempcanvas = document.createElement("canvas");
  8407. tempcanvas.height = 16;
  8408. tempcanvas.width = 16;
  8409. var gl = (tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl"));
  8410. // extension.
  8411. var ext = gl.getExtension(extension);
  8412. if (!ext) {
  8413. return false;
  8414. }
  8415. // setup GLSL program
  8416. var vertexCode = "attribute vec4 a_position;\n void main() {\n gl_Position = a_position;\n }";
  8417. 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 }";
  8418. var program = this.createShaderProgram(vertexCode, fragmentCode, null, gl);
  8419. gl.useProgram(program);
  8420. // look up where the vertex data needs to go.
  8421. var positionLocation = gl.getAttribLocation(program, "a_position");
  8422. var colorLoc = gl.getUniformLocation(program, "u_color");
  8423. // provide texture coordinates for the rectangle.
  8424. var positionBuffer = gl.createBuffer();
  8425. gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);
  8426. gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([
  8427. -1.0, -1.0,
  8428. 1.0, -1.0,
  8429. -1.0, 1.0,
  8430. -1.0, 1.0,
  8431. 1.0, -1.0,
  8432. 1.0, 1.0]), gl.STATIC_DRAW);
  8433. gl.enableVertexAttribArray(positionLocation);
  8434. gl.vertexAttribPointer(positionLocation, 2, gl.FLOAT, false, 0, 0);
  8435. var whiteTex = gl.createTexture();
  8436. gl.bindTexture(gl.TEXTURE_2D, whiteTex);
  8437. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, new Uint8Array([255, 255, 255, 255]));
  8438. var tex = gl.createTexture();
  8439. gl.bindTexture(gl.TEXTURE_2D, tex);
  8440. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 1, 1, 0, gl.RGBA, getWebGLTextureType(gl, format), null);
  8441. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  8442. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  8443. var fb = gl.createFramebuffer();
  8444. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  8445. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, tex, 0);
  8446. var cleanup = function () {
  8447. gl.deleteProgram(program);
  8448. gl.disableVertexAttribArray(positionLocation);
  8449. gl.deleteBuffer(positionBuffer);
  8450. gl.deleteFramebuffer(fb);
  8451. gl.deleteTexture(whiteTex);
  8452. gl.deleteTexture(tex);
  8453. };
  8454. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  8455. if (status !== gl.FRAMEBUFFER_COMPLETE) {
  8456. BABYLON.Tools.Log("GL Support: can **NOT** render to " + format + " texture");
  8457. cleanup();
  8458. return false;
  8459. }
  8460. // Draw the rectangle.
  8461. gl.bindTexture(gl.TEXTURE_2D, whiteTex);
  8462. gl.uniform4fv(colorLoc, [0, 10, 20, 1]);
  8463. gl.drawArrays(gl.TRIANGLES, 0, 6);
  8464. gl.bindTexture(gl.TEXTURE_2D, tex);
  8465. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  8466. gl.clearColor(1, 0, 0, 1);
  8467. gl.clear(gl.COLOR_BUFFER_BIT);
  8468. gl.uniform4fv(colorLoc, [0, 1 / 10, 1 / 20, 1]);
  8469. gl.drawArrays(gl.TRIANGLES, 0, 6);
  8470. var pixel = new Uint8Array(4);
  8471. gl.readPixels(0, 0, 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, pixel);
  8472. if (pixel[0] !== 0 ||
  8473. pixel[1] < 248 ||
  8474. pixel[2] < 248 ||
  8475. pixel[3] < 254) {
  8476. BABYLON.Tools.Log("GL Support: Was not able to actually render to " + format + " texture");
  8477. cleanup();
  8478. return false;
  8479. }
  8480. // Succesfully rendered to "format" texture.
  8481. cleanup();
  8482. return true;
  8483. };
  8484. // Statics
  8485. Engine.isSupported = function () {
  8486. try {
  8487. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  8488. if (navigator.isCocoonJS) {
  8489. return true;
  8490. }
  8491. var tempcanvas = document.createElement("canvas");
  8492. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  8493. return gl != null && !!window.WebGLRenderingContext;
  8494. }
  8495. catch (e) {
  8496. return false;
  8497. }
  8498. };
  8499. // Const statics
  8500. Engine._ALPHA_DISABLE = 0;
  8501. Engine._ALPHA_ADD = 1;
  8502. Engine._ALPHA_COMBINE = 2;
  8503. Engine._ALPHA_SUBTRACT = 3;
  8504. Engine._ALPHA_MULTIPLY = 4;
  8505. Engine._ALPHA_MAXIMIZED = 5;
  8506. Engine._ALPHA_ONEONE = 6;
  8507. Engine._DELAYLOADSTATE_NONE = 0;
  8508. Engine._DELAYLOADSTATE_LOADED = 1;
  8509. Engine._DELAYLOADSTATE_LOADING = 2;
  8510. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  8511. Engine._TEXTUREFORMAT_ALPHA = 0;
  8512. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  8513. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  8514. Engine._TEXTUREFORMAT_RGB = 4;
  8515. Engine._TEXTUREFORMAT_RGBA = 5;
  8516. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  8517. Engine._TEXTURETYPE_FLOAT = 1;
  8518. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  8519. // Updatable statics so stick with vars here
  8520. Engine.CollisionsEpsilon = 0.001;
  8521. Engine.CodeRepository = "src/";
  8522. Engine.ShadersRepository = "src/Shaders/";
  8523. return Engine;
  8524. })();
  8525. BABYLON.Engine = Engine;
  8526. })(BABYLON || (BABYLON = {}));
  8527. var BABYLON;
  8528. (function (BABYLON) {
  8529. /**
  8530. * Node is the basic class for all scene objects (Mesh, Light Camera).
  8531. */
  8532. var Node = (function () {
  8533. /**
  8534. * @constructor
  8535. * @param {string} name - the name and id to be given to this node
  8536. * @param {BABYLON.Scene} the scene this node will be added to
  8537. */
  8538. function Node(name, scene) {
  8539. this.state = "";
  8540. this.animations = new Array();
  8541. this._ranges = {};
  8542. this._childrenFlag = -1;
  8543. this._isEnabled = true;
  8544. this._isReady = true;
  8545. this._currentRenderId = -1;
  8546. this._parentRenderId = -1;
  8547. this.name = name;
  8548. this.id = name;
  8549. this._scene = scene;
  8550. this._initCache();
  8551. }
  8552. Object.defineProperty(Node.prototype, "parent", {
  8553. get: function () {
  8554. return this._parentNode;
  8555. },
  8556. set: function (parent) {
  8557. if (this._parentNode === parent) {
  8558. return;
  8559. }
  8560. if (this._parentNode) {
  8561. var index = this._parentNode._children.indexOf(this);
  8562. if (index !== -1) {
  8563. this._parentNode._children.splice(index, 1);
  8564. }
  8565. }
  8566. this._parentNode = parent;
  8567. if (this._parentNode) {
  8568. if (!this._parentNode._children) {
  8569. this._parentNode._children = new Array();
  8570. }
  8571. this._parentNode._children.push(this);
  8572. }
  8573. },
  8574. enumerable: true,
  8575. configurable: true
  8576. });
  8577. Node.prototype.getScene = function () {
  8578. return this._scene;
  8579. };
  8580. Node.prototype.getEngine = function () {
  8581. return this._scene.getEngine();
  8582. };
  8583. // override it in derived class
  8584. Node.prototype.getWorldMatrix = function () {
  8585. return BABYLON.Matrix.Identity();
  8586. };
  8587. // override it in derived class if you add new variables to the cache
  8588. // and call the parent class method
  8589. Node.prototype._initCache = function () {
  8590. this._cache = {};
  8591. this._cache.parent = undefined;
  8592. };
  8593. Node.prototype.updateCache = function (force) {
  8594. if (!force && this.isSynchronized())
  8595. return;
  8596. this._cache.parent = this.parent;
  8597. this._updateCache();
  8598. };
  8599. // override it in derived class if you add new variables to the cache
  8600. // and call the parent class method if !ignoreParentClass
  8601. Node.prototype._updateCache = function (ignoreParentClass) {
  8602. };
  8603. // override it in derived class if you add new variables to the cache
  8604. Node.prototype._isSynchronized = function () {
  8605. return true;
  8606. };
  8607. Node.prototype._markSyncedWithParent = function () {
  8608. this._parentRenderId = this.parent._currentRenderId;
  8609. };
  8610. Node.prototype.isSynchronizedWithParent = function () {
  8611. if (!this.parent) {
  8612. return true;
  8613. }
  8614. if (this._parentRenderId !== this.parent._currentRenderId) {
  8615. return false;
  8616. }
  8617. return this.parent.isSynchronized();
  8618. };
  8619. Node.prototype.isSynchronized = function (updateCache) {
  8620. var check = this.hasNewParent();
  8621. check = check || !this.isSynchronizedWithParent();
  8622. check = check || !this._isSynchronized();
  8623. if (updateCache)
  8624. this.updateCache(true);
  8625. return !check;
  8626. };
  8627. Node.prototype.hasNewParent = function (update) {
  8628. if (this._cache.parent === this.parent)
  8629. return false;
  8630. if (update)
  8631. this._cache.parent = this.parent;
  8632. return true;
  8633. };
  8634. /**
  8635. * Is this node ready to be used/rendered
  8636. * @return {boolean} is it ready
  8637. */
  8638. Node.prototype.isReady = function () {
  8639. return this._isReady;
  8640. };
  8641. /**
  8642. * Is this node enabled.
  8643. * If the node has a parent and is enabled, the parent will be inspected as well.
  8644. * @return {boolean} whether this node (and its parent) is enabled.
  8645. * @see setEnabled
  8646. */
  8647. Node.prototype.isEnabled = function () {
  8648. if (!this._isEnabled) {
  8649. return false;
  8650. }
  8651. if (this.parent) {
  8652. return this.parent.isEnabled();
  8653. }
  8654. return true;
  8655. };
  8656. /**
  8657. * Set the enabled state of this node.
  8658. * @param {boolean} value - the new enabled state
  8659. * @see isEnabled
  8660. */
  8661. Node.prototype.setEnabled = function (value) {
  8662. this._isEnabled = value;
  8663. };
  8664. /**
  8665. * Is this node a descendant of the given node.
  8666. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  8667. * @param {BABYLON.Node} ancestor - The parent node to inspect
  8668. * @see parent
  8669. */
  8670. Node.prototype.isDescendantOf = function (ancestor) {
  8671. if (this.parent) {
  8672. if (this.parent === ancestor) {
  8673. return true;
  8674. }
  8675. return this.parent.isDescendantOf(ancestor);
  8676. }
  8677. return false;
  8678. };
  8679. /**
  8680. * Evaluate the list of children and determine if they should be considered as descendants considering the given criterias
  8681. * @param {BABYLON.Node[]} results the result array containing the nodes matching the given criterias
  8682. * @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.
  8683. * @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.
  8684. */
  8685. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  8686. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  8687. if (!this._children) {
  8688. return;
  8689. }
  8690. for (var index = 0; index < this._children.length; index++) {
  8691. var item = this._children[index];
  8692. if (!predicate || predicate(item)) {
  8693. results.push(item);
  8694. }
  8695. if (!directDescendantsOnly) {
  8696. item._getDescendants(results, false, predicate);
  8697. }
  8698. }
  8699. };
  8700. /**
  8701. * Will return all nodes that have this node as ascendant.
  8702. * @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.
  8703. * @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.
  8704. * @return {BABYLON.Node[]} all children nodes of all types.
  8705. */
  8706. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  8707. var results = [];
  8708. this._getDescendants(results, directDescendantsOnly, predicate);
  8709. return results;
  8710. };
  8711. /**
  8712. * @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.
  8713. * @Deprecated, legacy support.
  8714. * use getDecendants instead.
  8715. */
  8716. Node.prototype.getChildren = function (predicate) {
  8717. return this.getDescendants(true, predicate);
  8718. };
  8719. /**
  8720. * Get all child-meshes of this node.
  8721. */
  8722. Node.prototype.getChildMeshes = function (directDecendantsOnly, predicate) {
  8723. var results = [];
  8724. this._getDescendants(results, directDecendantsOnly, function (node) {
  8725. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  8726. });
  8727. return results;
  8728. };
  8729. Node.prototype._setReady = function (state) {
  8730. if (state === this._isReady) {
  8731. return;
  8732. }
  8733. if (!state) {
  8734. this._isReady = false;
  8735. return;
  8736. }
  8737. this._isReady = true;
  8738. if (this.onReady) {
  8739. this.onReady(this);
  8740. }
  8741. };
  8742. Node.prototype.getAnimationByName = function (name) {
  8743. for (var i = 0; i < this.animations.length; i++) {
  8744. var animation = this.animations[i];
  8745. if (animation.name === name) {
  8746. return animation;
  8747. }
  8748. }
  8749. return null;
  8750. };
  8751. Node.prototype.createAnimationRange = function (name, from, to) {
  8752. // check name not already in use
  8753. if (!this._ranges[name]) {
  8754. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  8755. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  8756. if (this.animations[i]) {
  8757. this.animations[i].createRange(name, from, to);
  8758. }
  8759. }
  8760. }
  8761. };
  8762. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  8763. if (deleteFrames === void 0) { deleteFrames = true; }
  8764. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  8765. if (this.animations[i]) {
  8766. this.animations[i].deleteRange(name, deleteFrames);
  8767. }
  8768. }
  8769. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  8770. };
  8771. Node.prototype.getAnimationRange = function (name) {
  8772. return this._ranges[name];
  8773. };
  8774. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  8775. var range = this.getAnimationRange(name);
  8776. if (!range) {
  8777. return null;
  8778. }
  8779. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  8780. };
  8781. Node.prototype.serializeAnimationRanges = function () {
  8782. var serializationRanges = [];
  8783. for (var name in this._ranges) {
  8784. var range = {};
  8785. range.name = name;
  8786. range.from = this._ranges[name].from;
  8787. range.to = this._ranges[name].to;
  8788. serializationRanges.push(range);
  8789. }
  8790. return serializationRanges;
  8791. };
  8792. Node.prototype.dispose = function () {
  8793. this.parent = null;
  8794. };
  8795. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  8796. if (parsedNode.ranges) {
  8797. for (var index = 0; index < parsedNode.ranges.length; index++) {
  8798. var data = parsedNode.ranges[index];
  8799. node.createAnimationRange(data.name, data.from, data.to);
  8800. }
  8801. }
  8802. };
  8803. __decorate([
  8804. BABYLON.serialize()
  8805. ], Node.prototype, "name", void 0);
  8806. __decorate([
  8807. BABYLON.serialize()
  8808. ], Node.prototype, "id", void 0);
  8809. __decorate([
  8810. BABYLON.serialize()
  8811. ], Node.prototype, "uniqueId", void 0);
  8812. __decorate([
  8813. BABYLON.serialize()
  8814. ], Node.prototype, "state", void 0);
  8815. return Node;
  8816. })();
  8817. BABYLON.Node = Node;
  8818. })(BABYLON || (BABYLON = {}));
  8819. var BABYLON;
  8820. (function (BABYLON) {
  8821. var FilesInput = (function () {
  8822. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  8823. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  8824. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  8825. this._engine = p_engine;
  8826. this._canvas = p_canvas;
  8827. this._currentScene = p_scene;
  8828. this._sceneLoadedCallback = p_sceneLoadedCallback;
  8829. this._progressCallback = p_progressCallback;
  8830. this._additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  8831. this._textureLoadingCallback = p_textureLoadingCallback;
  8832. this._startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  8833. }
  8834. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  8835. var _this = this;
  8836. if (p_elementToMonitor) {
  8837. this._elementToMonitor = p_elementToMonitor;
  8838. this._elementToMonitor.addEventListener("dragenter", function (e) { _this.drag(e); }, false);
  8839. this._elementToMonitor.addEventListener("dragover", function (e) { _this.drag(e); }, false);
  8840. this._elementToMonitor.addEventListener("drop", function (e) { _this.drop(e); }, false);
  8841. }
  8842. };
  8843. FilesInput.prototype.renderFunction = function () {
  8844. if (this._additionnalRenderLoopLogicCallback) {
  8845. this._additionnalRenderLoopLogicCallback();
  8846. }
  8847. if (this._currentScene) {
  8848. if (this._textureLoadingCallback) {
  8849. var remaining = this._currentScene.getWaitingItemsCount();
  8850. if (remaining > 0) {
  8851. this._textureLoadingCallback(remaining);
  8852. }
  8853. }
  8854. this._currentScene.render();
  8855. }
  8856. };
  8857. FilesInput.prototype.drag = function (e) {
  8858. e.stopPropagation();
  8859. e.preventDefault();
  8860. };
  8861. FilesInput.prototype.drop = function (eventDrop) {
  8862. eventDrop.stopPropagation();
  8863. eventDrop.preventDefault();
  8864. this.loadFiles(eventDrop);
  8865. };
  8866. FilesInput.prototype.loadFiles = function (event) {
  8867. if (this._startingProcessingFilesCallback)
  8868. this._startingProcessingFilesCallback();
  8869. // Handling data transfer via drag'n'drop
  8870. if (event && event.dataTransfer && event.dataTransfer.files) {
  8871. this._filesToLoad = event.dataTransfer.files;
  8872. }
  8873. // Handling files from input files
  8874. if (event && event.target && event.target.files) {
  8875. this._filesToLoad = event.target.files;
  8876. }
  8877. if (this._filesToLoad && this._filesToLoad.length > 0) {
  8878. for (var i = 0; i < this._filesToLoad.length; i++) {
  8879. switch (this._filesToLoad[i].type) {
  8880. case "image/jpeg":
  8881. case "image/png":
  8882. case "image/bmp":
  8883. FilesInput.FilesTextures[this._filesToLoad[i].name.toLowerCase()] = this._filesToLoad[i];
  8884. break;
  8885. case "image/targa":
  8886. case "image/vnd.ms-dds":
  8887. case "audio/wav":
  8888. case "audio/x-wav":
  8889. case "audio/mp3":
  8890. case "audio/mpeg":
  8891. case "audio/mpeg3":
  8892. case "audio/x-mpeg-3":
  8893. case "audio/ogg":
  8894. FilesInput.FilesToLoad[this._filesToLoad[i].name.toLowerCase()] = this._filesToLoad[i];
  8895. break;
  8896. default:
  8897. if (this._filesToLoad[i].name.indexOf(".mtl") !== -1) {
  8898. FilesInput.FilesToLoad[this._filesToLoad[i].name.toLowerCase()] = this._filesToLoad[i];
  8899. }
  8900. else if ((this._filesToLoad[i].name.indexOf(".babylon") !== -1 ||
  8901. this._filesToLoad[i].name.indexOf(".stl") !== -1 ||
  8902. this._filesToLoad[i].name.indexOf(".obj") !== -1)
  8903. && this._filesToLoad[i].name.indexOf(".manifest") === -1
  8904. && this._filesToLoad[i].name.indexOf(".incremental") === -1 && this._filesToLoad[i].name.indexOf(".babylonmeshdata") === -1
  8905. && this._filesToLoad[i].name.indexOf(".babylongeometrydata") === -1 && this._filesToLoad[i].name.indexOf(".babylonbinarymeshdata") === -1 &&
  8906. this._filesToLoad[i].name.indexOf(".binary.babylon") === -1) {
  8907. this._sceneFileToLoad = this._filesToLoad[i];
  8908. }
  8909. break;
  8910. }
  8911. }
  8912. this.reload();
  8913. }
  8914. };
  8915. FilesInput.prototype.reload = function () {
  8916. var _this = this;
  8917. var that = this;
  8918. // If a ".babylon" file has been provided
  8919. if (this._sceneFileToLoad) {
  8920. if (this._currentScene) {
  8921. if (BABYLON.Tools.errorsCount > 0) {
  8922. BABYLON.Tools.ClearLogCache();
  8923. BABYLON.Tools.Log("Babylon.js engine (v" + BABYLON.Engine.Version + ") launched");
  8924. }
  8925. this._engine.stopRenderLoop();
  8926. this._currentScene.dispose();
  8927. }
  8928. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  8929. that._currentScene = newScene;
  8930. // Wait for textures and shaders to be ready
  8931. that._currentScene.executeWhenReady(function () {
  8932. // Attach camera to canvas inputs
  8933. if (!that._currentScene.activeCamera || that._currentScene.lights.length === 0) {
  8934. that._currentScene.createDefaultCameraOrLight();
  8935. }
  8936. that._currentScene.activeCamera.attachControl(that._canvas);
  8937. if (that._sceneLoadedCallback) {
  8938. that._sceneLoadedCallback(_this._sceneFileToLoad, that._currentScene);
  8939. }
  8940. that._engine.runRenderLoop(function () { that.renderFunction(); });
  8941. });
  8942. }, function (progress) {
  8943. if (_this._progressCallback) {
  8944. _this._progressCallback(progress);
  8945. }
  8946. });
  8947. }
  8948. else {
  8949. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  8950. }
  8951. };
  8952. FilesInput.FilesTextures = new Array();
  8953. FilesInput.FilesToLoad = new Array();
  8954. return FilesInput;
  8955. })();
  8956. BABYLON.FilesInput = FilesInput;
  8957. })(BABYLON || (BABYLON = {}));
  8958. var BABYLON;
  8959. (function (BABYLON) {
  8960. var IntersectionInfo = (function () {
  8961. function IntersectionInfo(bu, bv, distance) {
  8962. this.bu = bu;
  8963. this.bv = bv;
  8964. this.distance = distance;
  8965. this.faceId = 0;
  8966. this.subMeshId = 0;
  8967. }
  8968. return IntersectionInfo;
  8969. })();
  8970. BABYLON.IntersectionInfo = IntersectionInfo;
  8971. var PickingInfo = (function () {
  8972. function PickingInfo() {
  8973. this.hit = false;
  8974. this.distance = 0;
  8975. this.pickedPoint = null;
  8976. this.pickedMesh = null;
  8977. this.bu = 0;
  8978. this.bv = 0;
  8979. this.faceId = -1;
  8980. this.subMeshId = 0;
  8981. this.pickedSprite = null;
  8982. }
  8983. // Methods
  8984. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  8985. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  8986. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  8987. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  8988. return null;
  8989. }
  8990. var indices = this.pickedMesh.getIndices();
  8991. var result;
  8992. if (useVerticesNormals) {
  8993. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  8994. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  8995. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  8996. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  8997. normal0 = normal0.scale(this.bu);
  8998. normal1 = normal1.scale(this.bv);
  8999. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  9000. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  9001. }
  9002. else {
  9003. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  9004. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  9005. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  9006. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  9007. var p1p2 = vertex1.subtract(vertex2);
  9008. var p3p2 = vertex3.subtract(vertex2);
  9009. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  9010. }
  9011. if (useWorldCoordinates) {
  9012. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  9013. }
  9014. return BABYLON.Vector3.Normalize(result);
  9015. };
  9016. PickingInfo.prototype.getTextureCoordinates = function () {
  9017. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  9018. return null;
  9019. }
  9020. var indices = this.pickedMesh.getIndices();
  9021. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  9022. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  9023. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  9024. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  9025. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  9026. uv1 = uv1.scale(this.bu);
  9027. uv2 = uv2.scale(this.bv);
  9028. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  9029. };
  9030. return PickingInfo;
  9031. })();
  9032. BABYLON.PickingInfo = PickingInfo;
  9033. })(BABYLON || (BABYLON = {}));
  9034. var BABYLON;
  9035. (function (BABYLON) {
  9036. var BoundingSphere = (function () {
  9037. function BoundingSphere(minimum, maximum) {
  9038. this.minimum = minimum;
  9039. this.maximum = maximum;
  9040. this._tempRadiusVector = BABYLON.Vector3.Zero();
  9041. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  9042. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  9043. this.radius = distance * 0.5;
  9044. this.centerWorld = BABYLON.Vector3.Zero();
  9045. this._update(BABYLON.Matrix.Identity());
  9046. }
  9047. // Methods
  9048. BoundingSphere.prototype._update = function (world) {
  9049. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  9050. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  9051. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  9052. };
  9053. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  9054. for (var i = 0; i < 6; i++) {
  9055. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  9056. return false;
  9057. }
  9058. return true;
  9059. };
  9060. BoundingSphere.prototype.intersectsPoint = function (point) {
  9061. var x = this.centerWorld.x - point.x;
  9062. var y = this.centerWorld.y - point.y;
  9063. var z = this.centerWorld.z - point.z;
  9064. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  9065. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  9066. return false;
  9067. return true;
  9068. };
  9069. // Statics
  9070. BoundingSphere.Intersects = function (sphere0, sphere1) {
  9071. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  9072. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  9073. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  9074. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  9075. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  9076. return false;
  9077. return true;
  9078. };
  9079. return BoundingSphere;
  9080. })();
  9081. BABYLON.BoundingSphere = BoundingSphere;
  9082. })(BABYLON || (BABYLON = {}));
  9083. var BABYLON;
  9084. (function (BABYLON) {
  9085. var BoundingBox = (function () {
  9086. function BoundingBox(minimum, maximum) {
  9087. this.minimum = minimum;
  9088. this.maximum = maximum;
  9089. this.vectors = new Array();
  9090. this.vectorsWorld = new Array();
  9091. // Bounding vectors
  9092. this.vectors.push(this.minimum.clone());
  9093. this.vectors.push(this.maximum.clone());
  9094. this.vectors.push(this.minimum.clone());
  9095. this.vectors[2].x = this.maximum.x;
  9096. this.vectors.push(this.minimum.clone());
  9097. this.vectors[3].y = this.maximum.y;
  9098. this.vectors.push(this.minimum.clone());
  9099. this.vectors[4].z = this.maximum.z;
  9100. this.vectors.push(this.maximum.clone());
  9101. this.vectors[5].z = this.minimum.z;
  9102. this.vectors.push(this.maximum.clone());
  9103. this.vectors[6].x = this.minimum.x;
  9104. this.vectors.push(this.maximum.clone());
  9105. this.vectors[7].y = this.minimum.y;
  9106. // OBB
  9107. this.center = this.maximum.add(this.minimum).scale(0.5);
  9108. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  9109. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  9110. // World
  9111. for (var index = 0; index < this.vectors.length; index++) {
  9112. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  9113. }
  9114. this.minimumWorld = BABYLON.Vector3.Zero();
  9115. this.maximumWorld = BABYLON.Vector3.Zero();
  9116. this._update(BABYLON.Matrix.Identity());
  9117. }
  9118. // Methods
  9119. BoundingBox.prototype.getWorldMatrix = function () {
  9120. return this._worldMatrix;
  9121. };
  9122. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  9123. this._worldMatrix.copyFrom(matrix);
  9124. return this;
  9125. };
  9126. BoundingBox.prototype._update = function (world) {
  9127. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  9128. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  9129. for (var index = 0; index < this.vectors.length; index++) {
  9130. var v = this.vectorsWorld[index];
  9131. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  9132. if (v.x < this.minimumWorld.x)
  9133. this.minimumWorld.x = v.x;
  9134. if (v.y < this.minimumWorld.y)
  9135. this.minimumWorld.y = v.y;
  9136. if (v.z < this.minimumWorld.z)
  9137. this.minimumWorld.z = v.z;
  9138. if (v.x > this.maximumWorld.x)
  9139. this.maximumWorld.x = v.x;
  9140. if (v.y > this.maximumWorld.y)
  9141. this.maximumWorld.y = v.y;
  9142. if (v.z > this.maximumWorld.z)
  9143. this.maximumWorld.z = v.z;
  9144. }
  9145. // OBB
  9146. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  9147. this.center.scaleInPlace(0.5);
  9148. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  9149. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  9150. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  9151. this._worldMatrix = world;
  9152. };
  9153. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  9154. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  9155. };
  9156. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  9157. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  9158. };
  9159. BoundingBox.prototype.intersectsPoint = function (point) {
  9160. var delta = -BABYLON.Epsilon;
  9161. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  9162. return false;
  9163. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  9164. return false;
  9165. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  9166. return false;
  9167. return true;
  9168. };
  9169. BoundingBox.prototype.intersectsSphere = function (sphere) {
  9170. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  9171. };
  9172. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  9173. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  9174. return false;
  9175. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  9176. return false;
  9177. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  9178. return false;
  9179. return true;
  9180. };
  9181. // Statics
  9182. BoundingBox.Intersects = function (box0, box1) {
  9183. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  9184. return false;
  9185. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  9186. return false;
  9187. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  9188. return false;
  9189. return true;
  9190. };
  9191. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  9192. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  9193. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  9194. return (num <= (sphereRadius * sphereRadius));
  9195. };
  9196. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  9197. for (var p = 0; p < 6; p++) {
  9198. for (var i = 0; i < 8; i++) {
  9199. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  9200. return false;
  9201. }
  9202. }
  9203. }
  9204. return true;
  9205. };
  9206. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  9207. for (var p = 0; p < 6; p++) {
  9208. var inCount = 8;
  9209. for (var i = 0; i < 8; i++) {
  9210. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  9211. --inCount;
  9212. }
  9213. else {
  9214. break;
  9215. }
  9216. }
  9217. if (inCount === 0)
  9218. return false;
  9219. }
  9220. return true;
  9221. };
  9222. return BoundingBox;
  9223. })();
  9224. BABYLON.BoundingBox = BoundingBox;
  9225. })(BABYLON || (BABYLON = {}));
  9226. var BABYLON;
  9227. (function (BABYLON) {
  9228. var computeBoxExtents = function (axis, box) {
  9229. var p = BABYLON.Vector3.Dot(box.center, axis);
  9230. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  9231. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  9232. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  9233. var r = r0 + r1 + r2;
  9234. return {
  9235. min: p - r,
  9236. max: p + r
  9237. };
  9238. };
  9239. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  9240. var axisOverlap = function (axis, box0, box1) {
  9241. var result0 = computeBoxExtents(axis, box0);
  9242. var result1 = computeBoxExtents(axis, box1);
  9243. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  9244. };
  9245. var BoundingInfo = (function () {
  9246. function BoundingInfo(minimum, maximum) {
  9247. this.minimum = minimum;
  9248. this.maximum = maximum;
  9249. this._isLocked = false;
  9250. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  9251. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  9252. }
  9253. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  9254. get: function () {
  9255. return this._isLocked;
  9256. },
  9257. set: function (value) {
  9258. this._isLocked = value;
  9259. },
  9260. enumerable: true,
  9261. configurable: true
  9262. });
  9263. // Methods
  9264. BoundingInfo.prototype.update = function (world) {
  9265. if (this._isLocked) {
  9266. return;
  9267. }
  9268. this.boundingBox._update(world);
  9269. this.boundingSphere._update(world);
  9270. };
  9271. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  9272. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  9273. return false;
  9274. return this.boundingBox.isInFrustum(frustumPlanes);
  9275. };
  9276. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  9277. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  9278. };
  9279. BoundingInfo.prototype._checkCollision = function (collider) {
  9280. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  9281. };
  9282. BoundingInfo.prototype.intersectsPoint = function (point) {
  9283. if (!this.boundingSphere.centerWorld) {
  9284. return false;
  9285. }
  9286. if (!this.boundingSphere.intersectsPoint(point)) {
  9287. return false;
  9288. }
  9289. if (!this.boundingBox.intersectsPoint(point)) {
  9290. return false;
  9291. }
  9292. return true;
  9293. };
  9294. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  9295. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  9296. return false;
  9297. }
  9298. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  9299. return false;
  9300. }
  9301. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  9302. return false;
  9303. }
  9304. if (!precise) {
  9305. return true;
  9306. }
  9307. var box0 = this.boundingBox;
  9308. var box1 = boundingInfo.boundingBox;
  9309. if (!axisOverlap(box0.directions[0], box0, box1))
  9310. return false;
  9311. if (!axisOverlap(box0.directions[1], box0, box1))
  9312. return false;
  9313. if (!axisOverlap(box0.directions[2], box0, box1))
  9314. return false;
  9315. if (!axisOverlap(box1.directions[0], box0, box1))
  9316. return false;
  9317. if (!axisOverlap(box1.directions[1], box0, box1))
  9318. return false;
  9319. if (!axisOverlap(box1.directions[2], box0, box1))
  9320. return false;
  9321. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  9322. return false;
  9323. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  9324. return false;
  9325. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  9326. return false;
  9327. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  9328. return false;
  9329. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  9330. return false;
  9331. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  9332. return false;
  9333. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  9334. return false;
  9335. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  9336. return false;
  9337. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  9338. return false;
  9339. return true;
  9340. };
  9341. return BoundingInfo;
  9342. })();
  9343. BABYLON.BoundingInfo = BoundingInfo;
  9344. })(BABYLON || (BABYLON = {}));
  9345. var BABYLON;
  9346. (function (BABYLON) {
  9347. var Ray = (function () {
  9348. function Ray(origin, direction, length) {
  9349. if (length === void 0) { length = Number.MAX_VALUE; }
  9350. this.origin = origin;
  9351. this.direction = direction;
  9352. this.length = length;
  9353. }
  9354. // Methods
  9355. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  9356. var d = 0.0;
  9357. var maxValue = Number.MAX_VALUE;
  9358. var inv;
  9359. var min;
  9360. var max;
  9361. var temp;
  9362. if (Math.abs(this.direction.x) < 0.0000001) {
  9363. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  9364. return false;
  9365. }
  9366. }
  9367. else {
  9368. inv = 1.0 / this.direction.x;
  9369. min = (minimum.x - this.origin.x) * inv;
  9370. max = (maximum.x - this.origin.x) * inv;
  9371. if (max === -Infinity) {
  9372. max = Infinity;
  9373. }
  9374. if (min > max) {
  9375. temp = min;
  9376. min = max;
  9377. max = temp;
  9378. }
  9379. d = Math.max(min, d);
  9380. maxValue = Math.min(max, maxValue);
  9381. if (d > maxValue) {
  9382. return false;
  9383. }
  9384. }
  9385. if (Math.abs(this.direction.y) < 0.0000001) {
  9386. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  9387. return false;
  9388. }
  9389. }
  9390. else {
  9391. inv = 1.0 / this.direction.y;
  9392. min = (minimum.y - this.origin.y) * inv;
  9393. max = (maximum.y - this.origin.y) * inv;
  9394. if (max === -Infinity) {
  9395. max = Infinity;
  9396. }
  9397. if (min > max) {
  9398. temp = min;
  9399. min = max;
  9400. max = temp;
  9401. }
  9402. d = Math.max(min, d);
  9403. maxValue = Math.min(max, maxValue);
  9404. if (d > maxValue) {
  9405. return false;
  9406. }
  9407. }
  9408. if (Math.abs(this.direction.z) < 0.0000001) {
  9409. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  9410. return false;
  9411. }
  9412. }
  9413. else {
  9414. inv = 1.0 / this.direction.z;
  9415. min = (minimum.z - this.origin.z) * inv;
  9416. max = (maximum.z - this.origin.z) * inv;
  9417. if (max === -Infinity) {
  9418. max = Infinity;
  9419. }
  9420. if (min > max) {
  9421. temp = min;
  9422. min = max;
  9423. max = temp;
  9424. }
  9425. d = Math.max(min, d);
  9426. maxValue = Math.min(max, maxValue);
  9427. if (d > maxValue) {
  9428. return false;
  9429. }
  9430. }
  9431. return true;
  9432. };
  9433. Ray.prototype.intersectsBox = function (box) {
  9434. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  9435. };
  9436. Ray.prototype.intersectsSphere = function (sphere) {
  9437. var x = sphere.center.x - this.origin.x;
  9438. var y = sphere.center.y - this.origin.y;
  9439. var z = sphere.center.z - this.origin.z;
  9440. var pyth = (x * x) + (y * y) + (z * z);
  9441. var rr = sphere.radius * sphere.radius;
  9442. if (pyth <= rr) {
  9443. return true;
  9444. }
  9445. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  9446. if (dot < 0.0) {
  9447. return false;
  9448. }
  9449. var temp = pyth - (dot * dot);
  9450. return temp <= rr;
  9451. };
  9452. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  9453. if (!this._edge1) {
  9454. this._edge1 = BABYLON.Vector3.Zero();
  9455. this._edge2 = BABYLON.Vector3.Zero();
  9456. this._pvec = BABYLON.Vector3.Zero();
  9457. this._tvec = BABYLON.Vector3.Zero();
  9458. this._qvec = BABYLON.Vector3.Zero();
  9459. }
  9460. vertex1.subtractToRef(vertex0, this._edge1);
  9461. vertex2.subtractToRef(vertex0, this._edge2);
  9462. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  9463. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  9464. if (det === 0) {
  9465. return null;
  9466. }
  9467. var invdet = 1 / det;
  9468. this.origin.subtractToRef(vertex0, this._tvec);
  9469. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  9470. if (bu < 0 || bu > 1.0) {
  9471. return null;
  9472. }
  9473. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  9474. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  9475. if (bv < 0 || bu + bv > 1.0) {
  9476. return null;
  9477. }
  9478. //check if the distance is longer than the predefined length.
  9479. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  9480. if (distance > this.length) {
  9481. return null;
  9482. }
  9483. return new BABYLON.IntersectionInfo(bu, bv, distance);
  9484. };
  9485. Ray.prototype.intersectsPlane = function (plane) {
  9486. var distance;
  9487. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  9488. if (Math.abs(result1) < 9.99999997475243E-07) {
  9489. return null;
  9490. }
  9491. else {
  9492. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  9493. distance = (-plane.d - result2) / result1;
  9494. if (distance < 0.0) {
  9495. if (distance < -9.99999997475243E-07) {
  9496. return null;
  9497. }
  9498. else {
  9499. return 0;
  9500. }
  9501. }
  9502. return distance;
  9503. }
  9504. };
  9505. /**
  9506. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  9507. * @param sega the first point of the segment to test the intersection against
  9508. * @param segb the second point of the segment to test the intersection against
  9509. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  9510. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  9511. */
  9512. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  9513. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  9514. var u = segb.subtract(sega);
  9515. var v = rsegb.subtract(this.origin);
  9516. var w = sega.subtract(this.origin);
  9517. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  9518. var b = BABYLON.Vector3.Dot(u, v);
  9519. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  9520. var d = BABYLON.Vector3.Dot(u, w);
  9521. var e = BABYLON.Vector3.Dot(v, w);
  9522. var D = a * c - b * b; // always >= 0
  9523. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  9524. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  9525. // compute the line parameters of the two closest points
  9526. if (D < Ray.smallnum) {
  9527. sN = 0.0; // force using point P0 on segment S1
  9528. sD = 1.0; // to prevent possible division by 0.0 later
  9529. tN = e;
  9530. tD = c;
  9531. }
  9532. else {
  9533. sN = (b * e - c * d);
  9534. tN = (a * e - b * d);
  9535. if (sN < 0.0) {
  9536. sN = 0.0;
  9537. tN = e;
  9538. tD = c;
  9539. }
  9540. else if (sN > sD) {
  9541. sN = sD;
  9542. tN = e + b;
  9543. tD = c;
  9544. }
  9545. }
  9546. if (tN < 0.0) {
  9547. tN = 0.0;
  9548. // recompute sc for this edge
  9549. if (-d < 0.0) {
  9550. sN = 0.0;
  9551. }
  9552. else if (-d > a)
  9553. sN = sD;
  9554. else {
  9555. sN = -d;
  9556. sD = a;
  9557. }
  9558. }
  9559. else if (tN > tD) {
  9560. tN = tD;
  9561. // recompute sc for this edge
  9562. if ((-d + b) < 0.0) {
  9563. sN = 0;
  9564. }
  9565. else if ((-d + b) > a) {
  9566. sN = sD;
  9567. }
  9568. else {
  9569. sN = (-d + b);
  9570. sD = a;
  9571. }
  9572. }
  9573. // finally do the division to get sc and tc
  9574. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  9575. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  9576. // get the difference of the two closest points
  9577. var qtc = v.multiplyByFloats(tc, tc, tc);
  9578. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  9579. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  9580. if (isIntersected) {
  9581. return qtc.length();
  9582. }
  9583. return -1;
  9584. };
  9585. // Statics
  9586. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  9587. var start = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  9588. var end = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  9589. var direction = end.subtract(start);
  9590. direction.normalize();
  9591. return new Ray(start, direction);
  9592. };
  9593. /**
  9594. * 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
  9595. * transformed to the given world matrix.
  9596. * @param origin The origin point
  9597. * @param end The end point
  9598. * @param world a matrix to transform the ray to. Default is the identity matrix.
  9599. */
  9600. Ray.CreateNewFromTo = function (origin, end, world) {
  9601. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  9602. var direction = end.subtract(origin);
  9603. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  9604. direction.normalize();
  9605. return Ray.Transform(new Ray(origin, direction, length), world);
  9606. };
  9607. Ray.Transform = function (ray, matrix) {
  9608. var newOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, matrix);
  9609. var newDirection = BABYLON.Vector3.TransformNormal(ray.direction, matrix);
  9610. newDirection.normalize();
  9611. return new Ray(newOrigin, newDirection, ray.length);
  9612. };
  9613. Ray.smallnum = 0.00000001;
  9614. Ray.rayl = 10e8;
  9615. return Ray;
  9616. })();
  9617. BABYLON.Ray = Ray;
  9618. })(BABYLON || (BABYLON = {}));
  9619. var BABYLON;
  9620. (function (BABYLON) {
  9621. var AbstractMesh = (function (_super) {
  9622. __extends(AbstractMesh, _super);
  9623. // Constructor
  9624. function AbstractMesh(name, scene) {
  9625. var _this = this;
  9626. _super.call(this, name, scene);
  9627. // Events
  9628. /**
  9629. * An event triggered when the mesh is disposed.
  9630. * @type {BABYLON.Observable}
  9631. */
  9632. this.onDisposeObservable = new BABYLON.Observable();
  9633. /**
  9634. * An event triggered when this mesh collides with another one
  9635. * @type {BABYLON.Observable}
  9636. */
  9637. this.onCollideObservable = new BABYLON.Observable();
  9638. /**
  9639. * An event triggered when the collision's position changes
  9640. * @type {BABYLON.Observable}
  9641. */
  9642. this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  9643. /**
  9644. * An event triggered after the world matrix is updated
  9645. * @type {BABYLON.Observable}
  9646. */
  9647. this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  9648. // Properties
  9649. this.definedFacingForward = true; // orientation for POV movement & rotation
  9650. this.position = new BABYLON.Vector3(0, 0, 0);
  9651. this._rotation = new BABYLON.Vector3(0, 0, 0);
  9652. this._scaling = new BABYLON.Vector3(1, 1, 1);
  9653. this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  9654. this.visibility = 1.0;
  9655. this.alphaIndex = Number.MAX_VALUE;
  9656. this.infiniteDistance = false;
  9657. this.isVisible = true;
  9658. this.isPickable = true;
  9659. this.showBoundingBox = false;
  9660. this.showSubMeshesBoundingBox = false;
  9661. this.isBlocker = false;
  9662. this.renderingGroupId = 0;
  9663. this.receiveShadows = false;
  9664. this.renderOutline = false;
  9665. this.outlineColor = BABYLON.Color3.Red();
  9666. this.outlineWidth = 0.02;
  9667. this.renderOverlay = false;
  9668. this.overlayColor = BABYLON.Color3.Red();
  9669. this.overlayAlpha = 0.5;
  9670. this.hasVertexAlpha = false;
  9671. this.useVertexColors = true;
  9672. this.applyFog = true;
  9673. this.computeBonesUsingShaders = true;
  9674. this.scalingDeterminant = 1;
  9675. this.numBoneInfluencers = 4;
  9676. this.useOctreeForRenderingSelection = true;
  9677. this.useOctreeForPicking = true;
  9678. this.useOctreeForCollisions = true;
  9679. this.layerMask = 0x0FFFFFFF;
  9680. this.alwaysSelectAsActiveMesh = false;
  9681. // Collisions
  9682. this._checkCollisions = false;
  9683. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  9684. this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  9685. this._collider = new BABYLON.Collider();
  9686. this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  9687. this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  9688. this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  9689. // Edges
  9690. this.edgesWidth = 1;
  9691. this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  9692. // Cache
  9693. this._localWorld = BABYLON.Matrix.Zero();
  9694. this._worldMatrix = BABYLON.Matrix.Zero();
  9695. this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  9696. this._absolutePosition = BABYLON.Vector3.Zero();
  9697. this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  9698. this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  9699. this._isDirty = false;
  9700. this._pivotMatrix = BABYLON.Matrix.Identity();
  9701. this._isDisposed = false;
  9702. this._renderId = 0;
  9703. this._intersectionsInProgress = new Array();
  9704. this._isWorldMatrixFrozen = false;
  9705. this._unIndexed = false;
  9706. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  9707. if (collidedMesh === void 0) { collidedMesh = null; }
  9708. //TODO move this to the collision coordinator!
  9709. if (_this.getScene().workerCollisions)
  9710. newPosition.multiplyInPlace(_this._collider.radius);
  9711. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  9712. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  9713. _this.position.addInPlace(_this._diffPositionForCollisions);
  9714. }
  9715. if (collidedMesh) {
  9716. _this.onCollideObservable.notifyObservers(collidedMesh);
  9717. }
  9718. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  9719. };
  9720. scene.addMesh(this);
  9721. }
  9722. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  9723. get: function () {
  9724. return AbstractMesh._BILLBOARDMODE_NONE;
  9725. },
  9726. enumerable: true,
  9727. configurable: true
  9728. });
  9729. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  9730. get: function () {
  9731. return AbstractMesh._BILLBOARDMODE_X;
  9732. },
  9733. enumerable: true,
  9734. configurable: true
  9735. });
  9736. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  9737. get: function () {
  9738. return AbstractMesh._BILLBOARDMODE_Y;
  9739. },
  9740. enumerable: true,
  9741. configurable: true
  9742. });
  9743. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  9744. get: function () {
  9745. return AbstractMesh._BILLBOARDMODE_Z;
  9746. },
  9747. enumerable: true,
  9748. configurable: true
  9749. });
  9750. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  9751. get: function () {
  9752. return AbstractMesh._BILLBOARDMODE_ALL;
  9753. },
  9754. enumerable: true,
  9755. configurable: true
  9756. });
  9757. Object.defineProperty(AbstractMesh.prototype, "onDispose", {
  9758. set: function (callback) {
  9759. if (this._onDisposeObserver) {
  9760. this.onDisposeObservable.remove(this._onDisposeObserver);
  9761. }
  9762. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  9763. },
  9764. enumerable: true,
  9765. configurable: true
  9766. });
  9767. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  9768. set: function (callback) {
  9769. if (this._onCollideObserver) {
  9770. this.onCollideObservable.remove(this._onCollideObserver);
  9771. }
  9772. this._onCollideObserver = this.onCollideObservable.add(callback);
  9773. },
  9774. enumerable: true,
  9775. configurable: true
  9776. });
  9777. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  9778. set: function (callback) {
  9779. if (this._onCollisionPositionChangeObserver) {
  9780. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  9781. }
  9782. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  9783. },
  9784. enumerable: true,
  9785. configurable: true
  9786. });
  9787. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  9788. get: function () {
  9789. return this._skeleton;
  9790. },
  9791. set: function (value) {
  9792. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  9793. this._skeleton._unregisterMeshWithPoseMatrix(this);
  9794. }
  9795. if (value && value.needInitialSkinMatrix) {
  9796. value._registerMeshWithPoseMatrix(this);
  9797. }
  9798. this._skeleton = value;
  9799. if (!this._skeleton) {
  9800. this._bonesTransformMatrices = null;
  9801. }
  9802. },
  9803. enumerable: true,
  9804. configurable: true
  9805. });
  9806. /**
  9807. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  9808. */
  9809. AbstractMesh.prototype.toString = function (fullDetails) {
  9810. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  9811. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  9812. if (this._skeleton) {
  9813. ret += ", skeleton: " + this._skeleton.name;
  9814. }
  9815. if (fullDetails) {
  9816. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  9817. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  9818. }
  9819. return ret;
  9820. };
  9821. Object.defineProperty(AbstractMesh.prototype, "rotation", {
  9822. /**
  9823. * Getting the rotation object.
  9824. * If rotation quaternion is set, this vector will (almost always) be the Zero vector!
  9825. */
  9826. get: function () {
  9827. return this._rotation;
  9828. },
  9829. set: function (newRotation) {
  9830. this._rotation = newRotation;
  9831. },
  9832. enumerable: true,
  9833. configurable: true
  9834. });
  9835. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  9836. get: function () {
  9837. return this._scaling;
  9838. },
  9839. set: function (newScaling) {
  9840. this._scaling = newScaling;
  9841. if (this.physicsImpostor) {
  9842. this.physicsImpostor.forceUpdate();
  9843. }
  9844. },
  9845. enumerable: true,
  9846. configurable: true
  9847. });
  9848. Object.defineProperty(AbstractMesh.prototype, "rotationQuaternion", {
  9849. get: function () {
  9850. return this._rotationQuaternion;
  9851. },
  9852. set: function (quaternion) {
  9853. this._rotationQuaternion = quaternion;
  9854. //reset the rotation vector.
  9855. if (quaternion && this.rotation.length()) {
  9856. this.rotation.copyFromFloats(0, 0, 0);
  9857. }
  9858. },
  9859. enumerable: true,
  9860. configurable: true
  9861. });
  9862. // Methods
  9863. AbstractMesh.prototype.updatePoseMatrix = function (matrix) {
  9864. this._poseMatrix.copyFrom(matrix);
  9865. };
  9866. AbstractMesh.prototype.getPoseMatrix = function () {
  9867. return this._poseMatrix;
  9868. };
  9869. AbstractMesh.prototype.disableEdgesRendering = function () {
  9870. if (this._edgesRenderer !== undefined) {
  9871. this._edgesRenderer.dispose();
  9872. this._edgesRenderer = undefined;
  9873. }
  9874. };
  9875. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  9876. if (epsilon === void 0) { epsilon = 0.95; }
  9877. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  9878. this.disableEdgesRendering();
  9879. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  9880. };
  9881. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  9882. get: function () {
  9883. return false;
  9884. },
  9885. enumerable: true,
  9886. configurable: true
  9887. });
  9888. AbstractMesh.prototype.getLOD = function (camera) {
  9889. return this;
  9890. };
  9891. AbstractMesh.prototype.getTotalVertices = function () {
  9892. return 0;
  9893. };
  9894. AbstractMesh.prototype.getIndices = function () {
  9895. return null;
  9896. };
  9897. AbstractMesh.prototype.getVerticesData = function (kind) {
  9898. return null;
  9899. };
  9900. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  9901. return false;
  9902. };
  9903. AbstractMesh.prototype.getBoundingInfo = function () {
  9904. if (this._masterMesh) {
  9905. return this._masterMesh.getBoundingInfo();
  9906. }
  9907. if (!this._boundingInfo) {
  9908. this._updateBoundingInfo();
  9909. }
  9910. return this._boundingInfo;
  9911. };
  9912. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  9913. this._boundingInfo = boundingInfo;
  9914. };
  9915. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  9916. get: function () {
  9917. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  9918. },
  9919. enumerable: true,
  9920. configurable: true
  9921. });
  9922. AbstractMesh.prototype._preActivate = function () {
  9923. };
  9924. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  9925. };
  9926. AbstractMesh.prototype._activate = function (renderId) {
  9927. this._renderId = renderId;
  9928. };
  9929. AbstractMesh.prototype.getWorldMatrix = function () {
  9930. if (this._masterMesh) {
  9931. return this._masterMesh.getWorldMatrix();
  9932. }
  9933. if (this._currentRenderId !== this.getScene().getRenderId()) {
  9934. this.computeWorldMatrix();
  9935. }
  9936. return this._worldMatrix;
  9937. };
  9938. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  9939. get: function () {
  9940. return this._worldMatrix;
  9941. },
  9942. enumerable: true,
  9943. configurable: true
  9944. });
  9945. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  9946. get: function () {
  9947. return this._absolutePosition;
  9948. },
  9949. enumerable: true,
  9950. configurable: true
  9951. });
  9952. AbstractMesh.prototype.freezeWorldMatrix = function () {
  9953. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  9954. this.computeWorldMatrix(true);
  9955. this._isWorldMatrixFrozen = true;
  9956. };
  9957. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  9958. this._isWorldMatrixFrozen = false;
  9959. this.computeWorldMatrix(true);
  9960. };
  9961. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  9962. get: function () {
  9963. return this._isWorldMatrixFrozen;
  9964. },
  9965. enumerable: true,
  9966. configurable: true
  9967. });
  9968. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  9969. axis.normalize();
  9970. if (!this.rotationQuaternion) {
  9971. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  9972. this.rotation = BABYLON.Vector3.Zero();
  9973. }
  9974. var rotationQuaternion;
  9975. if (!space || space === BABYLON.Space.LOCAL) {
  9976. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  9977. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  9978. }
  9979. else {
  9980. if (this.parent) {
  9981. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  9982. invertParentWorldMatrix.invert();
  9983. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  9984. }
  9985. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  9986. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  9987. }
  9988. };
  9989. AbstractMesh.prototype.translate = function (axis, distance, space) {
  9990. var displacementVector = axis.scale(distance);
  9991. if (!space || space === BABYLON.Space.LOCAL) {
  9992. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  9993. this.setPositionWithLocalVector(tempV3);
  9994. }
  9995. else {
  9996. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  9997. }
  9998. };
  9999. AbstractMesh.prototype.getAbsolutePosition = function () {
  10000. this.computeWorldMatrix();
  10001. return this._absolutePosition;
  10002. };
  10003. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  10004. if (!absolutePosition) {
  10005. return;
  10006. }
  10007. var absolutePositionX;
  10008. var absolutePositionY;
  10009. var absolutePositionZ;
  10010. if (absolutePosition.x === undefined) {
  10011. if (arguments.length < 3) {
  10012. return;
  10013. }
  10014. absolutePositionX = arguments[0];
  10015. absolutePositionY = arguments[1];
  10016. absolutePositionZ = arguments[2];
  10017. }
  10018. else {
  10019. absolutePositionX = absolutePosition.x;
  10020. absolutePositionY = absolutePosition.y;
  10021. absolutePositionZ = absolutePosition.z;
  10022. }
  10023. if (this.parent) {
  10024. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  10025. invertParentWorldMatrix.invert();
  10026. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  10027. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  10028. }
  10029. else {
  10030. this.position.x = absolutePositionX;
  10031. this.position.y = absolutePositionY;
  10032. this.position.z = absolutePositionZ;
  10033. }
  10034. };
  10035. // ================================== Point of View Movement =================================
  10036. /**
  10037. * Perform relative position change from the point of view of behind the front of the mesh.
  10038. * This is performed taking into account the meshes current rotation, so you do not have to care.
  10039. * Supports definition of mesh facing forward or backward.
  10040. * @param {number} amountRight
  10041. * @param {number} amountUp
  10042. * @param {number} amountForward
  10043. */
  10044. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  10045. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  10046. };
  10047. /**
  10048. * Calculate relative position change from the point of view of behind the front of the mesh.
  10049. * This is performed taking into account the meshes current rotation, so you do not have to care.
  10050. * Supports definition of mesh facing forward or backward.
  10051. * @param {number} amountRight
  10052. * @param {number} amountUp
  10053. * @param {number} amountForward
  10054. */
  10055. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  10056. var rotMatrix = new BABYLON.Matrix();
  10057. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  10058. rotQuaternion.toRotationMatrix(rotMatrix);
  10059. var translationDelta = BABYLON.Vector3.Zero();
  10060. var defForwardMult = this.definedFacingForward ? -1 : 1;
  10061. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  10062. return translationDelta;
  10063. };
  10064. // ================================== Point of View Rotation =================================
  10065. /**
  10066. * Perform relative rotation change from the point of view of behind the front of the mesh.
  10067. * Supports definition of mesh facing forward or backward.
  10068. * @param {number} flipBack
  10069. * @param {number} twirlClockwise
  10070. * @param {number} tiltRight
  10071. */
  10072. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  10073. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  10074. };
  10075. /**
  10076. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  10077. * Supports definition of mesh facing forward or backward.
  10078. * @param {number} flipBack
  10079. * @param {number} twirlClockwise
  10080. * @param {number} tiltRight
  10081. */
  10082. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  10083. var defForwardMult = this.definedFacingForward ? 1 : -1;
  10084. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  10085. };
  10086. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  10087. this._pivotMatrix = matrix;
  10088. this._cache.pivotMatrixUpdated = true;
  10089. };
  10090. AbstractMesh.prototype.getPivotMatrix = function () {
  10091. return this._pivotMatrix;
  10092. };
  10093. AbstractMesh.prototype._isSynchronized = function () {
  10094. if (this._isDirty) {
  10095. return false;
  10096. }
  10097. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  10098. return false;
  10099. if (this._cache.pivotMatrixUpdated) {
  10100. return false;
  10101. }
  10102. if (this.infiniteDistance) {
  10103. return false;
  10104. }
  10105. if (!this._cache.position.equals(this.position))
  10106. return false;
  10107. if (this.rotationQuaternion) {
  10108. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  10109. return false;
  10110. }
  10111. if (!this._cache.rotation.equals(this.rotation))
  10112. return false;
  10113. if (!this._cache.scaling.equals(this.scaling))
  10114. return false;
  10115. return true;
  10116. };
  10117. AbstractMesh.prototype._initCache = function () {
  10118. _super.prototype._initCache.call(this);
  10119. this._cache.localMatrixUpdated = false;
  10120. this._cache.position = BABYLON.Vector3.Zero();
  10121. this._cache.scaling = BABYLON.Vector3.Zero();
  10122. this._cache.rotation = BABYLON.Vector3.Zero();
  10123. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  10124. this._cache.billboardMode = -1;
  10125. };
  10126. AbstractMesh.prototype.markAsDirty = function (property) {
  10127. if (property === "rotation") {
  10128. this.rotationQuaternion = null;
  10129. }
  10130. this._currentRenderId = Number.MAX_VALUE;
  10131. this._isDirty = true;
  10132. };
  10133. AbstractMesh.prototype._updateBoundingInfo = function () {
  10134. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  10135. this._boundingInfo.update(this.worldMatrixFromCache);
  10136. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  10137. };
  10138. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  10139. if (!this.subMeshes) {
  10140. return;
  10141. }
  10142. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  10143. var subMesh = this.subMeshes[subIndex];
  10144. if (!subMesh.IsGlobal) {
  10145. subMesh.updateBoundingInfo(matrix);
  10146. }
  10147. }
  10148. };
  10149. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  10150. if (this._isWorldMatrixFrozen) {
  10151. return this._worldMatrix;
  10152. }
  10153. if (!force && (this._currentRenderId === this.getScene().getRenderId() || this.isSynchronized(true))) {
  10154. this._currentRenderId = this.getScene().getRenderId();
  10155. return this._worldMatrix;
  10156. }
  10157. this._cache.position.copyFrom(this.position);
  10158. this._cache.scaling.copyFrom(this.scaling);
  10159. this._cache.pivotMatrixUpdated = false;
  10160. this._cache.billboardMode = this.billboardMode;
  10161. this._currentRenderId = this.getScene().getRenderId();
  10162. this._isDirty = false;
  10163. // Scaling
  10164. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  10165. // Rotation
  10166. //rotate, if quaternion is set and rotation was used
  10167. if (this.rotationQuaternion) {
  10168. var len = this.rotation.length();
  10169. if (len) {
  10170. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  10171. this.rotation.copyFromFloats(0, 0, 0);
  10172. }
  10173. }
  10174. if (this.rotationQuaternion) {
  10175. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  10176. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  10177. }
  10178. else {
  10179. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  10180. this._cache.rotation.copyFrom(this.rotation);
  10181. }
  10182. // Translation
  10183. if (this.infiniteDistance && !this.parent) {
  10184. var camera = this.getScene().activeCamera;
  10185. if (camera) {
  10186. var cameraWorldMatrix = camera.getWorldMatrix();
  10187. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  10188. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  10189. }
  10190. }
  10191. else {
  10192. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  10193. }
  10194. // Composing transformations
  10195. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  10196. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  10197. // Billboarding
  10198. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  10199. BABYLON.Tmp.Vector3[0].copyFrom(this.position);
  10200. var localPosition = BABYLON.Tmp.Vector3[0];
  10201. if (this.parent && this.parent.getWorldMatrix) {
  10202. this._markSyncedWithParent();
  10203. var parentMatrix;
  10204. if (this._meshToBoneReferal) {
  10205. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  10206. parentMatrix = BABYLON.Tmp.Matrix[6];
  10207. }
  10208. else {
  10209. parentMatrix = this.parent.getWorldMatrix();
  10210. }
  10211. BABYLON.Vector3.TransformNormalToRef(localPosition, parentMatrix, BABYLON.Tmp.Vector3[1]);
  10212. localPosition = BABYLON.Tmp.Vector3[1];
  10213. }
  10214. var zero = this.getScene().activeCamera.globalPosition.clone();
  10215. if (this.parent && this.parent.position) {
  10216. localPosition.addInPlace(this.parent.position);
  10217. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, BABYLON.Tmp.Matrix[2]);
  10218. }
  10219. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) !== AbstractMesh.BILLBOARDMODE_ALL) {
  10220. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_X)
  10221. zero.x = localPosition.x + BABYLON.Epsilon;
  10222. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Y)
  10223. zero.y = localPosition.y + BABYLON.Epsilon;
  10224. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Z)
  10225. zero.z = localPosition.z + BABYLON.Epsilon;
  10226. }
  10227. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), BABYLON.Tmp.Matrix[3]);
  10228. BABYLON.Tmp.Matrix[3].m[12] = BABYLON.Tmp.Matrix[3].m[13] = BABYLON.Tmp.Matrix[3].m[14] = 0;
  10229. BABYLON.Tmp.Matrix[3].invert();
  10230. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[3], this._localWorld);
  10231. this._rotateYByPI.multiplyToRef(this._localWorld, BABYLON.Tmp.Matrix[5]);
  10232. }
  10233. // Local world
  10234. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  10235. // Parent
  10236. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === AbstractMesh.BILLBOARDMODE_NONE) {
  10237. this._markSyncedWithParent();
  10238. if (this._meshToBoneReferal) {
  10239. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  10240. BABYLON.Tmp.Matrix[6].multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), this._worldMatrix);
  10241. }
  10242. else {
  10243. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  10244. }
  10245. }
  10246. else {
  10247. this._worldMatrix.copyFrom(this._localWorld);
  10248. }
  10249. // Bounding info
  10250. this._updateBoundingInfo();
  10251. // Absolute position
  10252. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  10253. // Callbacks
  10254. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  10255. if (!this._poseMatrix) {
  10256. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  10257. }
  10258. return this._worldMatrix;
  10259. };
  10260. /**
  10261. * If you'd like to be callbacked after the mesh position, rotation or scaling has been updated
  10262. * @param func: callback function to add
  10263. */
  10264. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  10265. this.onAfterWorldMatrixUpdateObservable.add(func);
  10266. };
  10267. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  10268. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  10269. };
  10270. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  10271. this.computeWorldMatrix();
  10272. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  10273. };
  10274. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  10275. this.computeWorldMatrix();
  10276. var invLocalWorldMatrix = this._localWorld.clone();
  10277. invLocalWorldMatrix.invert();
  10278. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  10279. };
  10280. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  10281. this.computeWorldMatrix(true);
  10282. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  10283. };
  10284. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  10285. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  10286. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  10287. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  10288. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  10289. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  10290. /// <returns>Mesh oriented towards targetMesh</returns>
  10291. if (yawCor === void 0) { yawCor = 0; }
  10292. if (pitchCor === void 0) { pitchCor = 0; }
  10293. if (rollCor === void 0) { rollCor = 0; }
  10294. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  10295. var dv = AbstractMesh._lookAtVectorCache;
  10296. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  10297. targetPoint.subtractToRef(pos, dv);
  10298. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  10299. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  10300. var pitch = Math.atan2(dv.y, len);
  10301. this.rotationQuaternion = this.rotationQuaternion || new BABYLON.Quaternion();
  10302. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  10303. };
  10304. AbstractMesh.prototype.attachToBone = function (bone, affectedMesh) {
  10305. this._meshToBoneReferal = affectedMesh;
  10306. this.parent = bone;
  10307. if (bone.getWorldMatrix().determinant() < 0) {
  10308. this.scalingDeterminant *= -1;
  10309. }
  10310. };
  10311. AbstractMesh.prototype.detachFromBone = function () {
  10312. if (this.parent.getWorldMatrix().determinant() < 0) {
  10313. this.scalingDeterminant *= -1;
  10314. }
  10315. this._meshToBoneReferal = null;
  10316. this.parent = null;
  10317. };
  10318. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  10319. return this._boundingInfo.isInFrustum(frustumPlanes);
  10320. };
  10321. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  10322. return this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  10323. ;
  10324. };
  10325. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  10326. if (!this._boundingInfo || !mesh._boundingInfo) {
  10327. return false;
  10328. }
  10329. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  10330. };
  10331. AbstractMesh.prototype.intersectsPoint = function (point) {
  10332. if (!this._boundingInfo) {
  10333. return false;
  10334. }
  10335. return this._boundingInfo.intersectsPoint(point);
  10336. };
  10337. // Physics
  10338. /**
  10339. * @Deprecated. Use new PhysicsImpostor instead.
  10340. * */
  10341. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  10342. //legacy support
  10343. if (impostor.impostor) {
  10344. options = impostor;
  10345. impostor = impostor.impostor;
  10346. }
  10347. this.physicsImpostor = new BABYLON.PhysicsImpostor(this, impostor, options, this.getScene());
  10348. return this.physicsImpostor.physicsBody;
  10349. };
  10350. AbstractMesh.prototype.getPhysicsImpostor = function () {
  10351. return this.physicsImpostor;
  10352. };
  10353. /**
  10354. * @Deprecated. Use getPhysicsImpostor().getParam("mass");
  10355. */
  10356. AbstractMesh.prototype.getPhysicsMass = function () {
  10357. return this.physicsImpostor.getParam("mass");
  10358. };
  10359. /**
  10360. * @Deprecated. Use getPhysicsImpostor().getParam("friction");
  10361. */
  10362. AbstractMesh.prototype.getPhysicsFriction = function () {
  10363. return this.physicsImpostor.getParam("friction");
  10364. };
  10365. /**
  10366. * @Deprecated. Use getPhysicsImpostor().getParam("restitution");
  10367. */
  10368. AbstractMesh.prototype.getPhysicsRestitution = function () {
  10369. return this.physicsImpostor.getParam("restitution");
  10370. };
  10371. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  10372. if (!camera) {
  10373. camera = this.getScene().activeCamera;
  10374. }
  10375. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  10376. };
  10377. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  10378. if (!camera) {
  10379. camera = this.getScene().activeCamera;
  10380. }
  10381. return this.absolutePosition.subtract(camera.position).length();
  10382. };
  10383. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  10384. if (!this.physicsImpostor) {
  10385. return;
  10386. }
  10387. this.physicsImpostor.applyImpulse(force, contactPoint);
  10388. };
  10389. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  10390. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  10391. return;
  10392. }
  10393. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  10394. mainPivot: pivot1,
  10395. connectedPivot: pivot2,
  10396. nativeParams: options
  10397. });
  10398. };
  10399. /**
  10400. * @Deprecated
  10401. */
  10402. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  10403. BABYLON.Tools.Warn("updatePhysicsBodyPosition() is deprecated, please use updatePhysicsBody()");
  10404. this.updatePhysicsBody();
  10405. };
  10406. /**
  10407. * @Deprecated
  10408. * Calling this function is not needed anymore.
  10409. * The physics engine takes care of transofmration automatically.
  10410. */
  10411. AbstractMesh.prototype.updatePhysicsBody = function () {
  10412. //Unneeded
  10413. };
  10414. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  10415. // Collisions
  10416. get: function () {
  10417. return this._checkCollisions;
  10418. },
  10419. set: function (collisionEnabled) {
  10420. this._checkCollisions = collisionEnabled;
  10421. if (this.getScene().workerCollisions) {
  10422. this.getScene().collisionCoordinator.onMeshUpdated(this);
  10423. }
  10424. },
  10425. enumerable: true,
  10426. configurable: true
  10427. });
  10428. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  10429. var globalPosition = this.getAbsolutePosition();
  10430. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  10431. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  10432. this._collider.radius = this.ellipsoid;
  10433. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  10434. };
  10435. // Submeshes octree
  10436. /**
  10437. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  10438. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  10439. */
  10440. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  10441. if (maxCapacity === void 0) { maxCapacity = 64; }
  10442. if (maxDepth === void 0) { maxDepth = 2; }
  10443. if (!this._submeshesOctree) {
  10444. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  10445. }
  10446. this.computeWorldMatrix(true);
  10447. // Update octree
  10448. var bbox = this.getBoundingInfo().boundingBox;
  10449. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  10450. return this._submeshesOctree;
  10451. };
  10452. // Collisions
  10453. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  10454. this._generatePointsArray();
  10455. // Transformation
  10456. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  10457. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  10458. subMesh._lastColliderWorldVertices = [];
  10459. subMesh._trianglePlanes = [];
  10460. var start = subMesh.verticesStart;
  10461. var end = (subMesh.verticesStart + subMesh.verticesCount);
  10462. for (var i = start; i < end; i++) {
  10463. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  10464. }
  10465. }
  10466. // Collide
  10467. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  10468. if (collider.collisionFound) {
  10469. collider.collidedMesh = this;
  10470. }
  10471. };
  10472. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  10473. var subMeshes;
  10474. var len;
  10475. // Octrees
  10476. if (this._submeshesOctree && this.useOctreeForCollisions) {
  10477. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  10478. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  10479. len = intersections.length;
  10480. subMeshes = intersections.data;
  10481. }
  10482. else {
  10483. subMeshes = this.subMeshes;
  10484. len = subMeshes.length;
  10485. }
  10486. for (var index = 0; index < len; index++) {
  10487. var subMesh = subMeshes[index];
  10488. // Bounding test
  10489. if (len > 1 && !subMesh._checkCollision(collider))
  10490. continue;
  10491. this._collideForSubMesh(subMesh, transformMatrix, collider);
  10492. }
  10493. };
  10494. AbstractMesh.prototype._checkCollision = function (collider) {
  10495. // Bounding box test
  10496. if (!this._boundingInfo._checkCollision(collider))
  10497. return;
  10498. // Transformation matrix
  10499. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  10500. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  10501. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  10502. };
  10503. // Picking
  10504. AbstractMesh.prototype._generatePointsArray = function () {
  10505. return false;
  10506. };
  10507. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  10508. var pickingInfo = new BABYLON.PickingInfo();
  10509. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  10510. return pickingInfo;
  10511. }
  10512. if (!this._generatePointsArray()) {
  10513. return pickingInfo;
  10514. }
  10515. var intersectInfo = null;
  10516. // Octrees
  10517. var subMeshes;
  10518. var len;
  10519. if (this._submeshesOctree && this.useOctreeForPicking) {
  10520. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  10521. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  10522. len = intersections.length;
  10523. subMeshes = intersections.data;
  10524. }
  10525. else {
  10526. subMeshes = this.subMeshes;
  10527. len = subMeshes.length;
  10528. }
  10529. for (var index = 0; index < len; index++) {
  10530. var subMesh = subMeshes[index];
  10531. // Bounding test
  10532. if (len > 1 && !subMesh.canIntersects(ray))
  10533. continue;
  10534. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  10535. if (currentIntersectInfo) {
  10536. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  10537. intersectInfo = currentIntersectInfo;
  10538. intersectInfo.subMeshId = index;
  10539. if (fastCheck) {
  10540. break;
  10541. }
  10542. }
  10543. }
  10544. }
  10545. if (intersectInfo) {
  10546. // Get picked point
  10547. var world = this.getWorldMatrix();
  10548. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  10549. var direction = ray.direction.clone();
  10550. direction = direction.scale(intersectInfo.distance);
  10551. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  10552. var pickedPoint = worldOrigin.add(worldDirection);
  10553. // Return result
  10554. pickingInfo.hit = true;
  10555. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  10556. pickingInfo.pickedPoint = pickedPoint;
  10557. pickingInfo.pickedMesh = this;
  10558. pickingInfo.bu = intersectInfo.bu;
  10559. pickingInfo.bv = intersectInfo.bv;
  10560. pickingInfo.faceId = intersectInfo.faceId;
  10561. pickingInfo.subMeshId = intersectInfo.subMeshId;
  10562. return pickingInfo;
  10563. }
  10564. return pickingInfo;
  10565. };
  10566. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  10567. return null;
  10568. };
  10569. AbstractMesh.prototype.releaseSubMeshes = function () {
  10570. if (this.subMeshes) {
  10571. while (this.subMeshes.length) {
  10572. this.subMeshes[0].dispose();
  10573. }
  10574. }
  10575. else {
  10576. this.subMeshes = new Array();
  10577. }
  10578. };
  10579. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  10580. var _this = this;
  10581. var index;
  10582. // Action manager
  10583. if (this.actionManager) {
  10584. this.actionManager.dispose();
  10585. this.actionManager = null;
  10586. }
  10587. // Skeleton
  10588. this.skeleton = null;
  10589. // Animations
  10590. this.getScene().stopAnimation(this);
  10591. // Physics
  10592. if (this.physicsImpostor) {
  10593. this.physicsImpostor.dispose();
  10594. }
  10595. // Intersections in progress
  10596. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  10597. var other = this._intersectionsInProgress[index];
  10598. var pos = other._intersectionsInProgress.indexOf(this);
  10599. other._intersectionsInProgress.splice(pos, 1);
  10600. }
  10601. this._intersectionsInProgress = [];
  10602. // Lights
  10603. var lights = this.getScene().lights;
  10604. lights.forEach(function (light) {
  10605. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  10606. if (meshIndex !== -1) {
  10607. light.includedOnlyMeshes.splice(meshIndex, 1);
  10608. }
  10609. meshIndex = light.excludedMeshes.indexOf(_this);
  10610. if (meshIndex !== -1) {
  10611. light.excludedMeshes.splice(meshIndex, 1);
  10612. }
  10613. });
  10614. // Edges
  10615. if (this._edgesRenderer) {
  10616. this._edgesRenderer.dispose();
  10617. this._edgesRenderer = null;
  10618. }
  10619. // SubMeshes
  10620. this.releaseSubMeshes();
  10621. // Remove from scene
  10622. this.getScene().removeMesh(this);
  10623. if (!doNotRecurse) {
  10624. // Particles
  10625. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  10626. if (this.getScene().particleSystems[index].emitter === this) {
  10627. this.getScene().particleSystems[index].dispose();
  10628. index--;
  10629. }
  10630. }
  10631. // Children
  10632. var objects = this.getDescendants(true);
  10633. for (index = 0; index < objects.length; index++) {
  10634. objects[index].dispose();
  10635. }
  10636. }
  10637. else {
  10638. var childMeshes = this.getChildMeshes(true);
  10639. for (index = 0; index < childMeshes.length; index++) {
  10640. var child = childMeshes[index];
  10641. child.parent = null;
  10642. child.computeWorldMatrix(true);
  10643. }
  10644. }
  10645. _super.prototype.dispose.call(this);
  10646. this.onAfterWorldMatrixUpdateObservable.clear();
  10647. this.onCollideObservable.clear();
  10648. this.onCollisionPositionChangeObservable.clear();
  10649. this._isDisposed = true;
  10650. // Callback
  10651. this.onDisposeObservable.notifyObservers(this);
  10652. this.onDisposeObservable.clear();
  10653. };
  10654. // Statics
  10655. AbstractMesh._BILLBOARDMODE_NONE = 0;
  10656. AbstractMesh._BILLBOARDMODE_X = 1;
  10657. AbstractMesh._BILLBOARDMODE_Y = 2;
  10658. AbstractMesh._BILLBOARDMODE_Z = 4;
  10659. AbstractMesh._BILLBOARDMODE_ALL = 7;
  10660. AbstractMesh._rotationAxisCache = new BABYLON.Quaternion();
  10661. AbstractMesh._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  10662. return AbstractMesh;
  10663. })(BABYLON.Node);
  10664. BABYLON.AbstractMesh = AbstractMesh;
  10665. })(BABYLON || (BABYLON = {}));
  10666. var BABYLON;
  10667. (function (BABYLON) {
  10668. var Light = (function (_super) {
  10669. __extends(Light, _super);
  10670. function Light(name, scene) {
  10671. _super.call(this, name, scene);
  10672. this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  10673. this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  10674. this.intensity = 1.0;
  10675. this.range = Number.MAX_VALUE;
  10676. this.includeOnlyWithLayerMask = 0;
  10677. this.includedOnlyMeshes = new Array();
  10678. this.excludedMeshes = new Array();
  10679. this.excludeWithLayerMask = 0;
  10680. // PBR Properties.
  10681. this.radius = 0.00001;
  10682. this._excludedMeshesIds = new Array();
  10683. this._includedOnlyMeshesIds = new Array();
  10684. scene.addLight(this);
  10685. }
  10686. /**
  10687. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  10688. */
  10689. Light.prototype.toString = function (fullDetails) {
  10690. var ret = "Name: " + this.name;
  10691. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  10692. if (this.animations) {
  10693. for (var i = 0; i < this.animations.length; i++) {
  10694. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  10695. }
  10696. }
  10697. if (fullDetails) {
  10698. }
  10699. return ret;
  10700. };
  10701. Light.prototype.getShadowGenerator = function () {
  10702. return this._shadowGenerator;
  10703. };
  10704. Light.prototype.getAbsolutePosition = function () {
  10705. return BABYLON.Vector3.Zero();
  10706. };
  10707. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  10708. };
  10709. Light.prototype._getWorldMatrix = function () {
  10710. return BABYLON.Matrix.Identity();
  10711. };
  10712. Light.prototype.canAffectMesh = function (mesh) {
  10713. if (!mesh) {
  10714. return true;
  10715. }
  10716. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  10717. return false;
  10718. }
  10719. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  10720. return false;
  10721. }
  10722. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  10723. return false;
  10724. }
  10725. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  10726. return false;
  10727. }
  10728. return true;
  10729. };
  10730. Light.prototype.getWorldMatrix = function () {
  10731. this._currentRenderId = this.getScene().getRenderId();
  10732. var worldMatrix = this._getWorldMatrix();
  10733. if (this.parent && this.parent.getWorldMatrix) {
  10734. if (!this._parentedWorldMatrix) {
  10735. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  10736. }
  10737. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  10738. this._markSyncedWithParent();
  10739. return this._parentedWorldMatrix;
  10740. }
  10741. return worldMatrix;
  10742. };
  10743. Light.prototype.dispose = function () {
  10744. if (this._shadowGenerator) {
  10745. this._shadowGenerator.dispose();
  10746. this._shadowGenerator = null;
  10747. }
  10748. // Animations
  10749. this.getScene().stopAnimation(this);
  10750. // Remove from scene
  10751. this.getScene().removeLight(this);
  10752. _super.prototype.dispose.call(this);
  10753. };
  10754. Light.prototype.getTypeID = function () {
  10755. return 0;
  10756. };
  10757. Light.prototype.clone = function (name) {
  10758. return BABYLON.SerializationHelper.Clone(Light.GetConstructorFromName(this.getTypeID(), name, this.getScene()), this);
  10759. };
  10760. Light.prototype.serialize = function () {
  10761. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  10762. // Type
  10763. serializationObject.type = this.getTypeID();
  10764. // Parent
  10765. if (this.parent) {
  10766. serializationObject.parentId = this.parent.id;
  10767. }
  10768. // Inclusion / exclusions
  10769. if (this.excludedMeshes.length > 0) {
  10770. serializationObject.excludedMeshesIds = [];
  10771. this.excludedMeshes.forEach(function (mesh) {
  10772. serializationObject.excludedMeshesIds.push(mesh.id);
  10773. });
  10774. }
  10775. if (this.includedOnlyMeshes.length > 0) {
  10776. serializationObject.includedOnlyMeshesIds = [];
  10777. this.includedOnlyMeshes.forEach(function (mesh) {
  10778. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  10779. });
  10780. }
  10781. // Animations
  10782. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  10783. serializationObject.ranges = this.serializeAnimationRanges();
  10784. return serializationObject;
  10785. };
  10786. Light.GetConstructorFromName = function (type, name, scene) {
  10787. switch (type) {
  10788. case 0:
  10789. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  10790. case 1:
  10791. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  10792. case 2:
  10793. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  10794. case 3:
  10795. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  10796. }
  10797. };
  10798. Light.Parse = function (parsedLight, scene) {
  10799. var light = BABYLON.SerializationHelper.Parse(Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene), parsedLight, scene);
  10800. // Inclusion / exclusions
  10801. if (parsedLight.excludedMeshesIds) {
  10802. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  10803. }
  10804. if (parsedLight.includedOnlyMeshesIds) {
  10805. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  10806. }
  10807. // Parent
  10808. if (parsedLight.parentId) {
  10809. light._waitingParentId = parsedLight.parentId;
  10810. }
  10811. // Animations
  10812. if (parsedLight.animations) {
  10813. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  10814. var parsedAnimation = parsedLight.animations[animationIndex];
  10815. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  10816. }
  10817. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  10818. }
  10819. if (parsedLight.autoAnimate) {
  10820. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  10821. }
  10822. return light;
  10823. };
  10824. __decorate([
  10825. BABYLON.serializeAsColor3()
  10826. ], Light.prototype, "diffuse", void 0);
  10827. __decorate([
  10828. BABYLON.serializeAsColor3()
  10829. ], Light.prototype, "specular", void 0);
  10830. __decorate([
  10831. BABYLON.serialize()
  10832. ], Light.prototype, "intensity", void 0);
  10833. __decorate([
  10834. BABYLON.serialize()
  10835. ], Light.prototype, "range", void 0);
  10836. __decorate([
  10837. BABYLON.serialize()
  10838. ], Light.prototype, "includeOnlyWithLayerMask", void 0);
  10839. __decorate([
  10840. BABYLON.serialize()
  10841. ], Light.prototype, "excludeWithLayerMask", void 0);
  10842. __decorate([
  10843. BABYLON.serialize()
  10844. ], Light.prototype, "radius", void 0);
  10845. return Light;
  10846. })(BABYLON.Node);
  10847. BABYLON.Light = Light;
  10848. })(BABYLON || (BABYLON = {}));
  10849. var BABYLON;
  10850. (function (BABYLON) {
  10851. var PointLight = (function (_super) {
  10852. __extends(PointLight, _super);
  10853. function PointLight(name, position, scene) {
  10854. _super.call(this, name, scene);
  10855. this.position = position;
  10856. }
  10857. PointLight.prototype.getAbsolutePosition = function () {
  10858. return this.transformedPosition ? this.transformedPosition : this.position;
  10859. };
  10860. PointLight.prototype.computeTransformedPosition = function () {
  10861. if (this.parent && this.parent.getWorldMatrix) {
  10862. if (!this.transformedPosition) {
  10863. this.transformedPosition = BABYLON.Vector3.Zero();
  10864. }
  10865. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  10866. return true;
  10867. }
  10868. return false;
  10869. };
  10870. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  10871. if (this.parent && this.parent.getWorldMatrix) {
  10872. this.computeTransformedPosition();
  10873. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0);
  10874. return;
  10875. }
  10876. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  10877. };
  10878. PointLight.prototype.needCube = function () {
  10879. return true;
  10880. };
  10881. PointLight.prototype.supportsVSM = function () {
  10882. return false;
  10883. };
  10884. PointLight.prototype.needRefreshPerFrame = function () {
  10885. return false;
  10886. };
  10887. PointLight.prototype.getShadowDirection = function (faceIndex) {
  10888. switch (faceIndex) {
  10889. case 0:
  10890. return new BABYLON.Vector3(1, 0, 0);
  10891. case 1:
  10892. return new BABYLON.Vector3(-1, 0, 0);
  10893. case 2:
  10894. return new BABYLON.Vector3(0, -1, 0);
  10895. case 3:
  10896. return new BABYLON.Vector3(0, 1, 0);
  10897. case 4:
  10898. return new BABYLON.Vector3(0, 0, 1);
  10899. case 5:
  10900. return new BABYLON.Vector3(0, 0, -1);
  10901. }
  10902. return BABYLON.Vector3.Zero();
  10903. };
  10904. PointLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  10905. var activeCamera = this.getScene().activeCamera;
  10906. BABYLON.Matrix.PerspectiveFovLHToRef(Math.PI / 2, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  10907. };
  10908. PointLight.prototype._getWorldMatrix = function () {
  10909. if (!this._worldMatrix) {
  10910. this._worldMatrix = BABYLON.Matrix.Identity();
  10911. }
  10912. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  10913. return this._worldMatrix;
  10914. };
  10915. PointLight.prototype.getTypeID = function () {
  10916. return 0;
  10917. };
  10918. __decorate([
  10919. BABYLON.serializeAsVector3()
  10920. ], PointLight.prototype, "position", void 0);
  10921. return PointLight;
  10922. })(BABYLON.Light);
  10923. BABYLON.PointLight = PointLight;
  10924. })(BABYLON || (BABYLON = {}));
  10925. var BABYLON;
  10926. (function (BABYLON) {
  10927. var SpotLight = (function (_super) {
  10928. __extends(SpotLight, _super);
  10929. function SpotLight(name, position, direction, angle, exponent, scene) {
  10930. _super.call(this, name, scene);
  10931. this.position = position;
  10932. this.direction = direction;
  10933. this.angle = angle;
  10934. this.exponent = exponent;
  10935. }
  10936. SpotLight.prototype.getAbsolutePosition = function () {
  10937. return this.transformedPosition ? this.transformedPosition : this.position;
  10938. };
  10939. SpotLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  10940. var activeCamera = this.getScene().activeCamera;
  10941. BABYLON.Matrix.PerspectiveFovLHToRef(this.angle, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  10942. };
  10943. SpotLight.prototype.needCube = function () {
  10944. return false;
  10945. };
  10946. SpotLight.prototype.supportsVSM = function () {
  10947. return true;
  10948. };
  10949. SpotLight.prototype.needRefreshPerFrame = function () {
  10950. return false;
  10951. };
  10952. SpotLight.prototype.getShadowDirection = function (faceIndex) {
  10953. return this.direction;
  10954. };
  10955. SpotLight.prototype.setDirectionToTarget = function (target) {
  10956. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  10957. return this.direction;
  10958. };
  10959. SpotLight.prototype.computeTransformedPosition = function () {
  10960. if (this.parent && this.parent.getWorldMatrix) {
  10961. if (!this.transformedPosition) {
  10962. this.transformedPosition = BABYLON.Vector3.Zero();
  10963. }
  10964. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  10965. return true;
  10966. }
  10967. return false;
  10968. };
  10969. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  10970. var normalizeDirection;
  10971. if (this.parent && this.parent.getWorldMatrix) {
  10972. if (!this._transformedDirection) {
  10973. this._transformedDirection = BABYLON.Vector3.Zero();
  10974. }
  10975. this.computeTransformedPosition();
  10976. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  10977. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent);
  10978. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  10979. }
  10980. else {
  10981. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  10982. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  10983. }
  10984. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  10985. };
  10986. SpotLight.prototype._getWorldMatrix = function () {
  10987. if (!this._worldMatrix) {
  10988. this._worldMatrix = BABYLON.Matrix.Identity();
  10989. }
  10990. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  10991. return this._worldMatrix;
  10992. };
  10993. SpotLight.prototype.getTypeID = function () {
  10994. return 2;
  10995. };
  10996. __decorate([
  10997. BABYLON.serializeAsVector3()
  10998. ], SpotLight.prototype, "position", void 0);
  10999. __decorate([
  11000. BABYLON.serializeAsVector3()
  11001. ], SpotLight.prototype, "direction", void 0);
  11002. __decorate([
  11003. BABYLON.serialize()
  11004. ], SpotLight.prototype, "angle", void 0);
  11005. __decorate([
  11006. BABYLON.serialize()
  11007. ], SpotLight.prototype, "exponent", void 0);
  11008. return SpotLight;
  11009. })(BABYLON.Light);
  11010. BABYLON.SpotLight = SpotLight;
  11011. })(BABYLON || (BABYLON = {}));
  11012. var BABYLON;
  11013. (function (BABYLON) {
  11014. var HemisphericLight = (function (_super) {
  11015. __extends(HemisphericLight, _super);
  11016. function HemisphericLight(name, direction, scene) {
  11017. _super.call(this, name, scene);
  11018. this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  11019. this.direction = direction;
  11020. }
  11021. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  11022. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  11023. return this.direction;
  11024. };
  11025. HemisphericLight.prototype.getShadowGenerator = function () {
  11026. return null;
  11027. };
  11028. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  11029. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  11030. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  11031. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  11032. };
  11033. HemisphericLight.prototype._getWorldMatrix = function () {
  11034. if (!this._worldMatrix) {
  11035. this._worldMatrix = BABYLON.Matrix.Identity();
  11036. }
  11037. return this._worldMatrix;
  11038. };
  11039. HemisphericLight.prototype.getTypeID = function () {
  11040. return 3;
  11041. };
  11042. __decorate([
  11043. BABYLON.serializeAsColor3()
  11044. ], HemisphericLight.prototype, "groundColor", void 0);
  11045. __decorate([
  11046. BABYLON.serializeAsVector3()
  11047. ], HemisphericLight.prototype, "direction", void 0);
  11048. return HemisphericLight;
  11049. })(BABYLON.Light);
  11050. BABYLON.HemisphericLight = HemisphericLight;
  11051. })(BABYLON || (BABYLON = {}));
  11052. var BABYLON;
  11053. (function (BABYLON) {
  11054. var DirectionalLight = (function (_super) {
  11055. __extends(DirectionalLight, _super);
  11056. function DirectionalLight(name, direction, scene) {
  11057. _super.call(this, name, scene);
  11058. this.shadowOrthoScale = 0.5;
  11059. this.autoUpdateExtends = true;
  11060. // Cache
  11061. this._orthoLeft = Number.MAX_VALUE;
  11062. this._orthoRight = Number.MIN_VALUE;
  11063. this._orthoTop = Number.MIN_VALUE;
  11064. this._orthoBottom = Number.MAX_VALUE;
  11065. this.position = direction.scale(-1);
  11066. this.direction = direction;
  11067. }
  11068. DirectionalLight.prototype.getAbsolutePosition = function () {
  11069. return this.transformedPosition ? this.transformedPosition : this.position;
  11070. };
  11071. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  11072. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  11073. return this.direction;
  11074. };
  11075. DirectionalLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  11076. var activeCamera = this.getScene().activeCamera;
  11077. // Check extends
  11078. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  11079. var tempVector3 = BABYLON.Vector3.Zero();
  11080. this._orthoLeft = Number.MAX_VALUE;
  11081. this._orthoRight = Number.MIN_VALUE;
  11082. this._orthoTop = Number.MIN_VALUE;
  11083. this._orthoBottom = Number.MAX_VALUE;
  11084. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  11085. var mesh = renderList[meshIndex];
  11086. if (!mesh) {
  11087. continue;
  11088. }
  11089. var boundingInfo = mesh.getBoundingInfo();
  11090. if (!boundingInfo) {
  11091. continue;
  11092. }
  11093. var boundingBox = boundingInfo.boundingBox;
  11094. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  11095. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  11096. if (tempVector3.x < this._orthoLeft)
  11097. this._orthoLeft = tempVector3.x;
  11098. if (tempVector3.y < this._orthoBottom)
  11099. this._orthoBottom = tempVector3.y;
  11100. if (tempVector3.x > this._orthoRight)
  11101. this._orthoRight = tempVector3.x;
  11102. if (tempVector3.y > this._orthoTop)
  11103. this._orthoTop = tempVector3.y;
  11104. }
  11105. }
  11106. }
  11107. var xOffset = this._orthoRight - this._orthoLeft;
  11108. var yOffset = this._orthoTop - this._orthoBottom;
  11109. 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);
  11110. };
  11111. DirectionalLight.prototype.supportsVSM = function () {
  11112. return true;
  11113. };
  11114. DirectionalLight.prototype.needRefreshPerFrame = function () {
  11115. return true;
  11116. };
  11117. DirectionalLight.prototype.needCube = function () {
  11118. return false;
  11119. };
  11120. DirectionalLight.prototype.getShadowDirection = function (faceIndex) {
  11121. return this.direction;
  11122. };
  11123. DirectionalLight.prototype.computeTransformedPosition = function () {
  11124. if (this.parent && this.parent.getWorldMatrix) {
  11125. if (!this.transformedPosition) {
  11126. this.transformedPosition = BABYLON.Vector3.Zero();
  11127. }
  11128. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  11129. return true;
  11130. }
  11131. return false;
  11132. };
  11133. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  11134. if (this.parent && this.parent.getWorldMatrix) {
  11135. if (!this._transformedDirection) {
  11136. this._transformedDirection = BABYLON.Vector3.Zero();
  11137. }
  11138. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  11139. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  11140. return;
  11141. }
  11142. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  11143. };
  11144. DirectionalLight.prototype._getWorldMatrix = function () {
  11145. if (!this._worldMatrix) {
  11146. this._worldMatrix = BABYLON.Matrix.Identity();
  11147. }
  11148. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  11149. return this._worldMatrix;
  11150. };
  11151. DirectionalLight.prototype.getTypeID = function () {
  11152. return 1;
  11153. };
  11154. __decorate([
  11155. BABYLON.serializeAsVector3()
  11156. ], DirectionalLight.prototype, "position", void 0);
  11157. __decorate([
  11158. BABYLON.serializeAsVector3()
  11159. ], DirectionalLight.prototype, "direction", void 0);
  11160. __decorate([
  11161. BABYLON.serialize()
  11162. ], DirectionalLight.prototype, "shadowOrthoScale", void 0);
  11163. __decorate([
  11164. BABYLON.serialize()
  11165. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  11166. return DirectionalLight;
  11167. })(BABYLON.Light);
  11168. BABYLON.DirectionalLight = DirectionalLight;
  11169. })(BABYLON || (BABYLON = {}));
  11170. var BABYLON;
  11171. (function (BABYLON) {
  11172. var ShadowGenerator = (function () {
  11173. function ShadowGenerator(mapSize, light) {
  11174. var _this = this;
  11175. // Members
  11176. this._filter = ShadowGenerator.FILTER_NONE;
  11177. this.blurScale = 2;
  11178. this._blurBoxOffset = 0;
  11179. this._bias = 0.00005;
  11180. this._lightDirection = BABYLON.Vector3.Zero();
  11181. this.forceBackFacesOnly = false;
  11182. this._darkness = 0;
  11183. this._transparencyShadow = false;
  11184. this._viewMatrix = BABYLON.Matrix.Zero();
  11185. this._projectionMatrix = BABYLON.Matrix.Zero();
  11186. this._transformMatrix = BABYLON.Matrix.Zero();
  11187. this._worldViewProjection = BABYLON.Matrix.Zero();
  11188. this._currentFaceIndex = 0;
  11189. this._currentFaceIndexCache = 0;
  11190. this._useFullFloat = true;
  11191. this._light = light;
  11192. this._scene = light.getScene();
  11193. this._mapSize = mapSize;
  11194. light._shadowGenerator = this;
  11195. // Texture type fallback from float to int if not supported.
  11196. var textureType;
  11197. var caps = this._scene.getEngine().getCaps();
  11198. if (caps.textureFloat && caps.textureFloatLinearFiltering && caps.textureFloatRender) {
  11199. this._useFullFloat = true;
  11200. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  11201. }
  11202. else {
  11203. this._useFullFloat = false;
  11204. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  11205. }
  11206. // Render target
  11207. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false, true, textureType, light.needCube());
  11208. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  11209. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  11210. this._shadowMap.anisotropicFilteringLevel = 1;
  11211. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11212. this._shadowMap.renderParticles = false;
  11213. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  11214. _this._currentFaceIndex = faceIndex;
  11215. });
  11216. this._shadowMap.onAfterUnbindObservable.add(function () {
  11217. if (!_this.useBlurVarianceShadowMap) {
  11218. return;
  11219. }
  11220. if (!_this._shadowMap2) {
  11221. _this._shadowMap2 = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, _this._scene, false, true, textureType);
  11222. _this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  11223. _this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  11224. _this._shadowMap2.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  11225. _this._downSamplePostprocess = new BABYLON.PassPostProcess("downScale", 1.0 / _this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, _this._scene.getEngine());
  11226. _this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  11227. effect.setTexture("textureSampler", _this._shadowMap);
  11228. });
  11229. _this.blurBoxOffset = 1;
  11230. }
  11231. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._boxBlurPostprocess], _this._shadowMap2.getInternalTexture());
  11232. });
  11233. // Custom render function
  11234. var renderSubMesh = function (subMesh) {
  11235. var mesh = subMesh.getRenderingMesh();
  11236. var scene = _this._scene;
  11237. var engine = scene.getEngine();
  11238. // Culling
  11239. engine.setState(subMesh.getMaterial().backFaceCulling);
  11240. // Managing instances
  11241. var batch = mesh._getInstancesRenderList(subMesh._id);
  11242. if (batch.mustReturn) {
  11243. return;
  11244. }
  11245. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  11246. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  11247. engine.enableEffect(_this._effect);
  11248. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  11249. var material = subMesh.getMaterial();
  11250. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  11251. _this._effect.setVector3("lightPosition", _this.getLight().position);
  11252. if (_this.getLight().needCube()) {
  11253. _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  11254. }
  11255. // Alpha test
  11256. if (material && material.needAlphaTesting()) {
  11257. var alphaTexture = material.getAlphaTestTexture();
  11258. _this._effect.setTexture("diffuseSampler", alphaTexture);
  11259. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  11260. }
  11261. // Bones
  11262. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  11263. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  11264. }
  11265. if (_this.forceBackFacesOnly) {
  11266. engine.setState(true, 0, false, true);
  11267. }
  11268. // Draw
  11269. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  11270. if (_this.forceBackFacesOnly) {
  11271. engine.setState(true, 0, false, false);
  11272. }
  11273. }
  11274. else {
  11275. // Need to reset refresh rate of the shadowMap
  11276. _this._shadowMap.resetRefreshCounter();
  11277. }
  11278. };
  11279. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  11280. var index;
  11281. for (index = 0; index < opaqueSubMeshes.length; index++) {
  11282. renderSubMesh(opaqueSubMeshes.data[index]);
  11283. }
  11284. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  11285. renderSubMesh(alphaTestSubMeshes.data[index]);
  11286. }
  11287. if (_this._transparencyShadow) {
  11288. for (index = 0; index < transparentSubMeshes.length; index++) {
  11289. renderSubMesh(transparentSubMeshes.data[index]);
  11290. }
  11291. }
  11292. };
  11293. this._shadowMap.onClearObservable.add(function (engine) {
  11294. if (_this.useBlurVarianceShadowMap || _this.useVarianceShadowMap) {
  11295. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true, true);
  11296. }
  11297. else {
  11298. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  11299. }
  11300. });
  11301. }
  11302. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  11303. // Static
  11304. get: function () {
  11305. return ShadowGenerator._FILTER_NONE;
  11306. },
  11307. enumerable: true,
  11308. configurable: true
  11309. });
  11310. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  11311. get: function () {
  11312. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  11313. },
  11314. enumerable: true,
  11315. configurable: true
  11316. });
  11317. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  11318. get: function () {
  11319. return ShadowGenerator._FILTER_POISSONSAMPLING;
  11320. },
  11321. enumerable: true,
  11322. configurable: true
  11323. });
  11324. Object.defineProperty(ShadowGenerator, "FILTER_BLURVARIANCESHADOWMAP", {
  11325. get: function () {
  11326. return ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP;
  11327. },
  11328. enumerable: true,
  11329. configurable: true
  11330. });
  11331. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  11332. get: function () {
  11333. return this._bias;
  11334. },
  11335. set: function (bias) {
  11336. this._bias = bias;
  11337. },
  11338. enumerable: true,
  11339. configurable: true
  11340. });
  11341. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  11342. get: function () {
  11343. return this._blurBoxOffset;
  11344. },
  11345. set: function (value) {
  11346. var _this = this;
  11347. if (this._blurBoxOffset === value) {
  11348. return;
  11349. }
  11350. this._blurBoxOffset = value;
  11351. if (this._boxBlurPostprocess) {
  11352. this._boxBlurPostprocess.dispose();
  11353. }
  11354. 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);
  11355. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  11356. effect.setFloat2("screenSize", _this._mapSize / _this.blurScale, _this._mapSize / _this.blurScale);
  11357. });
  11358. },
  11359. enumerable: true,
  11360. configurable: true
  11361. });
  11362. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  11363. get: function () {
  11364. return this._filter;
  11365. },
  11366. set: function (value) {
  11367. if (this._filter === value) {
  11368. return;
  11369. }
  11370. this._filter = value;
  11371. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap || this.usePoissonSampling) {
  11372. this._shadowMap.anisotropicFilteringLevel = 16;
  11373. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  11374. }
  11375. else {
  11376. this._shadowMap.anisotropicFilteringLevel = 1;
  11377. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11378. }
  11379. },
  11380. enumerable: true,
  11381. configurable: true
  11382. });
  11383. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  11384. get: function () {
  11385. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP && this._light.supportsVSM();
  11386. },
  11387. set: function (value) {
  11388. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  11389. },
  11390. enumerable: true,
  11391. configurable: true
  11392. });
  11393. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  11394. get: function () {
  11395. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING ||
  11396. (!this._light.supportsVSM() && (this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP ||
  11397. this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP));
  11398. },
  11399. set: function (value) {
  11400. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  11401. },
  11402. enumerable: true,
  11403. configurable: true
  11404. });
  11405. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  11406. get: function () {
  11407. return this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP && this._light.supportsVSM();
  11408. },
  11409. set: function (value) {
  11410. this.filter = (value ? ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  11411. },
  11412. enumerable: true,
  11413. configurable: true
  11414. });
  11415. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  11416. var defines = [];
  11417. if (this._useFullFloat) {
  11418. defines.push("#define FULLFLOAT");
  11419. }
  11420. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  11421. defines.push("#define VSM");
  11422. }
  11423. if (this.getLight().needCube()) {
  11424. defines.push("#define CUBEMAP");
  11425. }
  11426. var attribs = [BABYLON.VertexBuffer.PositionKind];
  11427. var mesh = subMesh.getMesh();
  11428. var material = subMesh.getMaterial();
  11429. // Alpha test
  11430. if (material && material.needAlphaTesting()) {
  11431. defines.push("#define ALPHATEST");
  11432. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  11433. attribs.push(BABYLON.VertexBuffer.UVKind);
  11434. defines.push("#define UV1");
  11435. }
  11436. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  11437. var alphaTexture = material.getAlphaTestTexture();
  11438. if (alphaTexture.coordinatesIndex === 1) {
  11439. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  11440. defines.push("#define UV2");
  11441. }
  11442. }
  11443. }
  11444. // Bones
  11445. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  11446. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  11447. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  11448. if (mesh.numBoneInfluencers > 4) {
  11449. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  11450. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  11451. }
  11452. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  11453. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  11454. }
  11455. else {
  11456. defines.push("#define NUM_BONE_INFLUENCERS 0");
  11457. }
  11458. // Instances
  11459. if (useInstances) {
  11460. defines.push("#define INSTANCES");
  11461. attribs.push("world0");
  11462. attribs.push("world1");
  11463. attribs.push("world2");
  11464. attribs.push("world3");
  11465. }
  11466. // Get correct effect
  11467. var join = defines.join("\n");
  11468. if (this._cachedDefines !== join) {
  11469. this._cachedDefines = join;
  11470. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues"], ["diffuseSampler"], join);
  11471. }
  11472. return this._effect.isReady();
  11473. };
  11474. ShadowGenerator.prototype.getShadowMap = function () {
  11475. return this._shadowMap;
  11476. };
  11477. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  11478. if (this._shadowMap2) {
  11479. return this._shadowMap2;
  11480. }
  11481. return this._shadowMap;
  11482. };
  11483. ShadowGenerator.prototype.getLight = function () {
  11484. return this._light;
  11485. };
  11486. // Methods
  11487. ShadowGenerator.prototype.getTransformMatrix = function () {
  11488. var scene = this._scene;
  11489. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  11490. return this._transformMatrix;
  11491. }
  11492. this._currentRenderID = scene.getRenderId();
  11493. this._currentFaceIndexCache = this._currentFaceIndex;
  11494. var lightPosition = this._light.position;
  11495. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  11496. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  11497. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  11498. }
  11499. if (this._light.computeTransformedPosition()) {
  11500. lightPosition = this._light.transformedPosition;
  11501. }
  11502. if (this._light.needRefreshPerFrame() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  11503. this._cachedPosition = lightPosition.clone();
  11504. this._cachedDirection = this._lightDirection.clone();
  11505. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  11506. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  11507. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  11508. }
  11509. return this._transformMatrix;
  11510. };
  11511. ShadowGenerator.prototype.getDarkness = function () {
  11512. return this._darkness;
  11513. };
  11514. ShadowGenerator.prototype.setDarkness = function (darkness) {
  11515. if (darkness >= 1.0)
  11516. this._darkness = 1.0;
  11517. else if (darkness <= 0.0)
  11518. this._darkness = 0.0;
  11519. else
  11520. this._darkness = darkness;
  11521. };
  11522. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  11523. this._transparencyShadow = hasShadow;
  11524. };
  11525. ShadowGenerator.prototype._packHalf = function (depth) {
  11526. var scale = depth * 255.0;
  11527. var fract = scale - Math.floor(scale);
  11528. return new BABYLON.Vector2(depth - fract / 255.0, fract);
  11529. };
  11530. ShadowGenerator.prototype.dispose = function () {
  11531. this._shadowMap.dispose();
  11532. if (this._shadowMap2) {
  11533. this._shadowMap2.dispose();
  11534. }
  11535. if (this._downSamplePostprocess) {
  11536. this._downSamplePostprocess.dispose();
  11537. }
  11538. if (this._boxBlurPostprocess) {
  11539. this._boxBlurPostprocess.dispose();
  11540. }
  11541. };
  11542. ShadowGenerator.prototype.serialize = function () {
  11543. var serializationObject = {};
  11544. serializationObject.lightId = this._light.id;
  11545. serializationObject.mapSize = this.getShadowMap().getRenderSize();
  11546. serializationObject.useVarianceShadowMap = this.useVarianceShadowMap;
  11547. serializationObject.usePoissonSampling = this.usePoissonSampling;
  11548. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  11549. serializationObject.renderList = [];
  11550. for (var meshIndex = 0; meshIndex < this.getShadowMap().renderList.length; meshIndex++) {
  11551. var mesh = this.getShadowMap().renderList[meshIndex];
  11552. serializationObject.renderList.push(mesh.id);
  11553. }
  11554. return serializationObject;
  11555. };
  11556. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  11557. //casting to point light, as light is missing the position attr and typescript complains.
  11558. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  11559. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  11560. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  11561. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  11562. meshes.forEach(function (mesh) {
  11563. shadowGenerator.getShadowMap().renderList.push(mesh);
  11564. });
  11565. }
  11566. if (parsedShadowGenerator.usePoissonSampling) {
  11567. shadowGenerator.usePoissonSampling = true;
  11568. }
  11569. else if (parsedShadowGenerator.useVarianceShadowMap) {
  11570. shadowGenerator.useVarianceShadowMap = true;
  11571. }
  11572. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  11573. shadowGenerator.useBlurVarianceShadowMap = true;
  11574. if (parsedShadowGenerator.blurScale) {
  11575. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  11576. }
  11577. if (parsedShadowGenerator.blurBoxOffset) {
  11578. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  11579. }
  11580. }
  11581. if (parsedShadowGenerator.bias !== undefined) {
  11582. shadowGenerator.bias = parsedShadowGenerator.bias;
  11583. }
  11584. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  11585. return shadowGenerator;
  11586. };
  11587. ShadowGenerator._FILTER_NONE = 0;
  11588. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  11589. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  11590. ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP = 3;
  11591. return ShadowGenerator;
  11592. })();
  11593. BABYLON.ShadowGenerator = ShadowGenerator;
  11594. })(BABYLON || (BABYLON = {}));
  11595. var BABYLON;
  11596. (function (BABYLON) {
  11597. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  11598. if (boxMin.x > sphereCenter.x + sphereRadius)
  11599. return false;
  11600. if (sphereCenter.x - sphereRadius > boxMax.x)
  11601. return false;
  11602. if (boxMin.y > sphereCenter.y + sphereRadius)
  11603. return false;
  11604. if (sphereCenter.y - sphereRadius > boxMax.y)
  11605. return false;
  11606. if (boxMin.z > sphereCenter.z + sphereRadius)
  11607. return false;
  11608. if (sphereCenter.z - sphereRadius > boxMax.z)
  11609. return false;
  11610. return true;
  11611. };
  11612. var getLowestRoot = (function () {
  11613. var result = { root: 0, found: false };
  11614. return function (a, b, c, maxR) {
  11615. result.root = 0;
  11616. result.found = false;
  11617. var determinant = b * b - 4.0 * a * c;
  11618. if (determinant < 0)
  11619. return result;
  11620. var sqrtD = Math.sqrt(determinant);
  11621. var r1 = (-b - sqrtD) / (2.0 * a);
  11622. var r2 = (-b + sqrtD) / (2.0 * a);
  11623. if (r1 > r2) {
  11624. var temp = r2;
  11625. r2 = r1;
  11626. r1 = temp;
  11627. }
  11628. if (r1 > 0 && r1 < maxR) {
  11629. result.root = r1;
  11630. result.found = true;
  11631. return result;
  11632. }
  11633. if (r2 > 0 && r2 < maxR) {
  11634. result.root = r2;
  11635. result.found = true;
  11636. return result;
  11637. }
  11638. return result;
  11639. };
  11640. })();
  11641. var Collider = (function () {
  11642. function Collider() {
  11643. this.radius = new BABYLON.Vector3(1, 1, 1);
  11644. this.retry = 0;
  11645. this.basePointWorld = BABYLON.Vector3.Zero();
  11646. this.velocityWorld = BABYLON.Vector3.Zero();
  11647. this.normalizedVelocity = BABYLON.Vector3.Zero();
  11648. this._collisionPoint = BABYLON.Vector3.Zero();
  11649. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  11650. this._tempVector = BABYLON.Vector3.Zero();
  11651. this._tempVector2 = BABYLON.Vector3.Zero();
  11652. this._tempVector3 = BABYLON.Vector3.Zero();
  11653. this._tempVector4 = BABYLON.Vector3.Zero();
  11654. this._edge = BABYLON.Vector3.Zero();
  11655. this._baseToVertex = BABYLON.Vector3.Zero();
  11656. this._destinationPoint = BABYLON.Vector3.Zero();
  11657. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  11658. this._displacementVector = BABYLON.Vector3.Zero();
  11659. }
  11660. // Methods
  11661. Collider.prototype._initialize = function (source, dir, e) {
  11662. this.velocity = dir;
  11663. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  11664. this.basePoint = source;
  11665. source.multiplyToRef(this.radius, this.basePointWorld);
  11666. dir.multiplyToRef(this.radius, this.velocityWorld);
  11667. this.velocityWorldLength = this.velocityWorld.length();
  11668. this.epsilon = e;
  11669. this.collisionFound = false;
  11670. };
  11671. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  11672. pa.subtractToRef(point, this._tempVector);
  11673. pb.subtractToRef(point, this._tempVector2);
  11674. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  11675. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  11676. if (d < 0)
  11677. return false;
  11678. pc.subtractToRef(point, this._tempVector3);
  11679. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  11680. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  11681. if (d < 0)
  11682. return false;
  11683. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  11684. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  11685. return d >= 0;
  11686. };
  11687. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  11688. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  11689. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  11690. if (distance > this.velocityWorldLength + max + sphereRadius) {
  11691. return false;
  11692. }
  11693. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  11694. return false;
  11695. return true;
  11696. };
  11697. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  11698. var t0;
  11699. var embeddedInPlane = false;
  11700. //defensive programming, actually not needed.
  11701. if (!trianglePlaneArray) {
  11702. trianglePlaneArray = [];
  11703. }
  11704. if (!trianglePlaneArray[faceIndex]) {
  11705. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  11706. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  11707. }
  11708. var trianglePlane = trianglePlaneArray[faceIndex];
  11709. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  11710. return;
  11711. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  11712. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  11713. if (normalDotVelocity == 0) {
  11714. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  11715. return;
  11716. embeddedInPlane = true;
  11717. t0 = 0;
  11718. }
  11719. else {
  11720. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  11721. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  11722. if (t0 > t1) {
  11723. var temp = t1;
  11724. t1 = t0;
  11725. t0 = temp;
  11726. }
  11727. if (t0 > 1.0 || t1 < 0.0)
  11728. return;
  11729. if (t0 < 0)
  11730. t0 = 0;
  11731. if (t0 > 1.0)
  11732. t0 = 1.0;
  11733. }
  11734. this._collisionPoint.copyFromFloats(0, 0, 0);
  11735. var found = false;
  11736. var t = 1.0;
  11737. if (!embeddedInPlane) {
  11738. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  11739. this.velocity.scaleToRef(t0, this._tempVector);
  11740. this._planeIntersectionPoint.addInPlace(this._tempVector);
  11741. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  11742. found = true;
  11743. t = t0;
  11744. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  11745. }
  11746. }
  11747. if (!found) {
  11748. var velocitySquaredLength = this.velocity.lengthSquared();
  11749. var a = velocitySquaredLength;
  11750. this.basePoint.subtractToRef(p1, this._tempVector);
  11751. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  11752. var c = this._tempVector.lengthSquared() - 1.0;
  11753. var lowestRoot = getLowestRoot(a, b, c, t);
  11754. if (lowestRoot.found) {
  11755. t = lowestRoot.root;
  11756. found = true;
  11757. this._collisionPoint.copyFrom(p1);
  11758. }
  11759. this.basePoint.subtractToRef(p2, this._tempVector);
  11760. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  11761. c = this._tempVector.lengthSquared() - 1.0;
  11762. lowestRoot = getLowestRoot(a, b, c, t);
  11763. if (lowestRoot.found) {
  11764. t = lowestRoot.root;
  11765. found = true;
  11766. this._collisionPoint.copyFrom(p2);
  11767. }
  11768. this.basePoint.subtractToRef(p3, this._tempVector);
  11769. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  11770. c = this._tempVector.lengthSquared() - 1.0;
  11771. lowestRoot = getLowestRoot(a, b, c, t);
  11772. if (lowestRoot.found) {
  11773. t = lowestRoot.root;
  11774. found = true;
  11775. this._collisionPoint.copyFrom(p3);
  11776. }
  11777. p2.subtractToRef(p1, this._edge);
  11778. p1.subtractToRef(this.basePoint, this._baseToVertex);
  11779. var edgeSquaredLength = this._edge.lengthSquared();
  11780. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  11781. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  11782. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  11783. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  11784. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  11785. lowestRoot = getLowestRoot(a, b, c, t);
  11786. if (lowestRoot.found) {
  11787. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  11788. if (f >= 0.0 && f <= 1.0) {
  11789. t = lowestRoot.root;
  11790. found = true;
  11791. this._edge.scaleInPlace(f);
  11792. p1.addToRef(this._edge, this._collisionPoint);
  11793. }
  11794. }
  11795. p3.subtractToRef(p2, this._edge);
  11796. p2.subtractToRef(this.basePoint, this._baseToVertex);
  11797. edgeSquaredLength = this._edge.lengthSquared();
  11798. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  11799. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  11800. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  11801. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  11802. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  11803. lowestRoot = getLowestRoot(a, b, c, t);
  11804. if (lowestRoot.found) {
  11805. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  11806. if (f >= 0.0 && f <= 1.0) {
  11807. t = lowestRoot.root;
  11808. found = true;
  11809. this._edge.scaleInPlace(f);
  11810. p2.addToRef(this._edge, this._collisionPoint);
  11811. }
  11812. }
  11813. p1.subtractToRef(p3, this._edge);
  11814. p3.subtractToRef(this.basePoint, this._baseToVertex);
  11815. edgeSquaredLength = this._edge.lengthSquared();
  11816. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  11817. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  11818. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  11819. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  11820. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  11821. lowestRoot = getLowestRoot(a, b, c, t);
  11822. if (lowestRoot.found) {
  11823. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  11824. if (f >= 0.0 && f <= 1.0) {
  11825. t = lowestRoot.root;
  11826. found = true;
  11827. this._edge.scaleInPlace(f);
  11828. p3.addToRef(this._edge, this._collisionPoint);
  11829. }
  11830. }
  11831. }
  11832. if (found) {
  11833. var distToCollision = t * this.velocity.length();
  11834. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  11835. if (!this.intersectionPoint) {
  11836. this.intersectionPoint = this._collisionPoint.clone();
  11837. }
  11838. else {
  11839. this.intersectionPoint.copyFrom(this._collisionPoint);
  11840. }
  11841. this.nearestDistance = distToCollision;
  11842. this.collisionFound = true;
  11843. }
  11844. }
  11845. };
  11846. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  11847. for (var i = indexStart; i < indexEnd; i += 3) {
  11848. var p1 = pts[indices[i] - decal];
  11849. var p2 = pts[indices[i + 1] - decal];
  11850. var p3 = pts[indices[i + 2] - decal];
  11851. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  11852. }
  11853. };
  11854. Collider.prototype._getResponse = function (pos, vel) {
  11855. pos.addToRef(vel, this._destinationPoint);
  11856. vel.scaleInPlace((this.nearestDistance / vel.length()));
  11857. this.basePoint.addToRef(vel, pos);
  11858. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  11859. this._slidePlaneNormal.normalize();
  11860. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  11861. pos.addInPlace(this._displacementVector);
  11862. this.intersectionPoint.addInPlace(this._displacementVector);
  11863. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  11864. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  11865. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  11866. };
  11867. return Collider;
  11868. })();
  11869. BABYLON.Collider = Collider;
  11870. })(BABYLON || (BABYLON = {}));
  11871. var BABYLON;
  11872. (function (BABYLON) {
  11873. //WebWorker code will be inserted to this variable.
  11874. BABYLON.CollisionWorker = "";
  11875. (function (WorkerTaskType) {
  11876. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  11877. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  11878. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  11879. })(BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  11880. var WorkerTaskType = BABYLON.WorkerTaskType;
  11881. (function (WorkerReplyType) {
  11882. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  11883. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  11884. })(BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  11885. var WorkerReplyType = BABYLON.WorkerReplyType;
  11886. var CollisionCoordinatorWorker = (function () {
  11887. function CollisionCoordinatorWorker() {
  11888. var _this = this;
  11889. this._scaledPosition = BABYLON.Vector3.Zero();
  11890. this._scaledVelocity = BABYLON.Vector3.Zero();
  11891. this.onMeshUpdated = function (mesh) {
  11892. _this._addUpdateMeshesList[mesh.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(mesh);
  11893. };
  11894. this.onGeometryUpdated = function (geometry) {
  11895. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  11896. };
  11897. this._afterRender = function () {
  11898. if (!_this._init)
  11899. return;
  11900. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  11901. return;
  11902. }
  11903. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  11904. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  11905. if (_this._runningUpdated > 4) {
  11906. return;
  11907. }
  11908. ++_this._runningUpdated;
  11909. var payload = {
  11910. updatedMeshes: _this._addUpdateMeshesList,
  11911. updatedGeometries: _this._addUpdateGeometriesList,
  11912. removedGeometries: _this._toRemoveGeometryArray,
  11913. removedMeshes: _this._toRemoveMeshesArray
  11914. };
  11915. var message = {
  11916. payload: payload,
  11917. taskType: WorkerTaskType.UPDATE
  11918. };
  11919. var serializable = [];
  11920. for (var id in payload.updatedGeometries) {
  11921. if (payload.updatedGeometries.hasOwnProperty(id)) {
  11922. //prepare transferables
  11923. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  11924. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  11925. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  11926. }
  11927. }
  11928. _this._worker.postMessage(message, serializable);
  11929. _this._addUpdateMeshesList = {};
  11930. _this._addUpdateGeometriesList = {};
  11931. _this._toRemoveGeometryArray = [];
  11932. _this._toRemoveMeshesArray = [];
  11933. };
  11934. this._onMessageFromWorker = function (e) {
  11935. var returnData = e.data;
  11936. if (returnData.error != WorkerReplyType.SUCCESS) {
  11937. //TODO what errors can be returned from the worker?
  11938. BABYLON.Tools.Warn("error returned from worker!");
  11939. return;
  11940. }
  11941. switch (returnData.taskType) {
  11942. case WorkerTaskType.INIT:
  11943. _this._init = true;
  11944. //Update the worked with ALL of the scene's current state
  11945. _this._scene.meshes.forEach(function (mesh) {
  11946. _this.onMeshAdded(mesh);
  11947. });
  11948. _this._scene.getGeometries().forEach(function (geometry) {
  11949. _this.onGeometryAdded(geometry);
  11950. });
  11951. break;
  11952. case WorkerTaskType.UPDATE:
  11953. _this._runningUpdated--;
  11954. break;
  11955. case WorkerTaskType.COLLIDE:
  11956. _this._runningCollisionTask = false;
  11957. var returnPayload = returnData.payload;
  11958. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  11959. return;
  11960. _this._collisionsCallbackArray[returnPayload.collisionId](returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId));
  11961. //cleanup
  11962. _this._collisionsCallbackArray[returnPayload.collisionId] = undefined;
  11963. break;
  11964. }
  11965. };
  11966. this._collisionsCallbackArray = [];
  11967. this._init = false;
  11968. this._runningUpdated = 0;
  11969. this._runningCollisionTask = false;
  11970. this._addUpdateMeshesList = {};
  11971. this._addUpdateGeometriesList = {};
  11972. this._toRemoveGeometryArray = [];
  11973. this._toRemoveMeshesArray = [];
  11974. }
  11975. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  11976. if (!this._init)
  11977. return;
  11978. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  11979. return;
  11980. position.divideToRef(collider.radius, this._scaledPosition);
  11981. velocity.divideToRef(collider.radius, this._scaledVelocity);
  11982. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  11983. var payload = {
  11984. collider: {
  11985. position: this._scaledPosition.asArray(),
  11986. velocity: this._scaledVelocity.asArray(),
  11987. radius: collider.radius.asArray()
  11988. },
  11989. collisionId: collisionIndex,
  11990. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  11991. maximumRetry: maximumRetry
  11992. };
  11993. var message = {
  11994. payload: payload,
  11995. taskType: WorkerTaskType.COLLIDE
  11996. };
  11997. this._worker.postMessage(message);
  11998. };
  11999. CollisionCoordinatorWorker.prototype.init = function (scene) {
  12000. this._scene = scene;
  12001. this._scene.registerAfterRender(this._afterRender);
  12002. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  12003. this._worker = new Worker(workerUrl);
  12004. this._worker.onmessage = this._onMessageFromWorker;
  12005. var message = {
  12006. payload: {},
  12007. taskType: WorkerTaskType.INIT
  12008. };
  12009. this._worker.postMessage(message);
  12010. };
  12011. CollisionCoordinatorWorker.prototype.destroy = function () {
  12012. this._scene.unregisterAfterRender(this._afterRender);
  12013. this._worker.terminate();
  12014. };
  12015. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  12016. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  12017. this.onMeshUpdated(mesh);
  12018. };
  12019. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  12020. this._toRemoveMeshesArray.push(mesh.uniqueId);
  12021. };
  12022. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  12023. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  12024. geometry.onGeometryUpdated = this.onGeometryUpdated;
  12025. this.onGeometryUpdated(geometry);
  12026. };
  12027. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  12028. this._toRemoveGeometryArray.push(geometry.id);
  12029. };
  12030. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  12031. var submeshes = [];
  12032. if (mesh.subMeshes) {
  12033. submeshes = mesh.subMeshes.map(function (sm, idx) {
  12034. return {
  12035. position: idx,
  12036. verticesStart: sm.verticesStart,
  12037. verticesCount: sm.verticesCount,
  12038. indexStart: sm.indexStart,
  12039. indexCount: sm.indexCount,
  12040. hasMaterial: !!sm.getMaterial(),
  12041. sphereCenter: sm.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  12042. sphereRadius: sm.getBoundingInfo().boundingSphere.radiusWorld,
  12043. boxMinimum: sm.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  12044. boxMaximum: sm.getBoundingInfo().boundingBox.maximumWorld.asArray()
  12045. };
  12046. });
  12047. }
  12048. var geometryId = null;
  12049. if (mesh instanceof BABYLON.Mesh) {
  12050. geometryId = mesh.geometry ? mesh.geometry.id : null;
  12051. }
  12052. else if (mesh instanceof BABYLON.InstancedMesh) {
  12053. geometryId = (mesh.sourceMesh && mesh.sourceMesh.geometry) ? mesh.sourceMesh.geometry.id : null;
  12054. }
  12055. return {
  12056. uniqueId: mesh.uniqueId,
  12057. id: mesh.id,
  12058. name: mesh.name,
  12059. geometryId: geometryId,
  12060. sphereCenter: mesh.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  12061. sphereRadius: mesh.getBoundingInfo().boundingSphere.radiusWorld,
  12062. boxMinimum: mesh.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  12063. boxMaximum: mesh.getBoundingInfo().boundingBox.maximumWorld.asArray(),
  12064. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  12065. subMeshes: submeshes,
  12066. checkCollisions: mesh.checkCollisions
  12067. };
  12068. };
  12069. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  12070. return {
  12071. id: geometry.id,
  12072. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  12073. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  12074. indices: new Int32Array(geometry.getIndices() || []),
  12075. };
  12076. };
  12077. return CollisionCoordinatorWorker;
  12078. })();
  12079. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  12080. var CollisionCoordinatorLegacy = (function () {
  12081. function CollisionCoordinatorLegacy() {
  12082. this._scaledPosition = BABYLON.Vector3.Zero();
  12083. this._scaledVelocity = BABYLON.Vector3.Zero();
  12084. this._finalPosition = BABYLON.Vector3.Zero();
  12085. }
  12086. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  12087. position.divideToRef(collider.radius, this._scaledPosition);
  12088. velocity.divideToRef(collider.radius, this._scaledVelocity);
  12089. collider.collidedMesh = null;
  12090. collider.retry = 0;
  12091. collider.initialVelocity = this._scaledVelocity;
  12092. collider.initialPosition = this._scaledPosition;
  12093. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  12094. this._finalPosition.multiplyInPlace(collider.radius);
  12095. //run the callback
  12096. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  12097. };
  12098. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  12099. this._scene = scene;
  12100. };
  12101. CollisionCoordinatorLegacy.prototype.destroy = function () {
  12102. //Legacy need no destruction method.
  12103. };
  12104. //No update in legacy mode
  12105. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  12106. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  12107. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  12108. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  12109. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  12110. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  12111. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  12112. if (excludedMesh === void 0) { excludedMesh = null; }
  12113. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  12114. if (collider.retry >= maximumRetry) {
  12115. finalPosition.copyFrom(position);
  12116. return;
  12117. }
  12118. collider._initialize(position, velocity, closeDistance);
  12119. // Check all meshes
  12120. for (var index = 0; index < this._scene.meshes.length; index++) {
  12121. var mesh = this._scene.meshes[index];
  12122. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  12123. mesh._checkCollision(collider);
  12124. }
  12125. }
  12126. if (!collider.collisionFound) {
  12127. position.addToRef(velocity, finalPosition);
  12128. return;
  12129. }
  12130. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  12131. collider._getResponse(position, velocity);
  12132. }
  12133. if (velocity.length() <= closeDistance) {
  12134. finalPosition.copyFrom(position);
  12135. return;
  12136. }
  12137. collider.retry++;
  12138. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  12139. };
  12140. return CollisionCoordinatorLegacy;
  12141. })();
  12142. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  12143. })(BABYLON || (BABYLON = {}));
  12144. var BABYLON;
  12145. (function (BABYLON) {
  12146. var Camera = (function (_super) {
  12147. __extends(Camera, _super);
  12148. function Camera(name, position, scene) {
  12149. _super.call(this, name, scene);
  12150. this.upVector = BABYLON.Vector3.Up();
  12151. this.orthoLeft = null;
  12152. this.orthoRight = null;
  12153. this.orthoBottom = null;
  12154. this.orthoTop = null;
  12155. this.fov = 0.8;
  12156. this.minZ = 1.0;
  12157. this.maxZ = 10000.0;
  12158. this.inertia = 0.9;
  12159. this.mode = Camera.PERSPECTIVE_CAMERA;
  12160. this.isIntermediate = false;
  12161. this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  12162. this.layerMask = 0x0FFFFFFF;
  12163. this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  12164. // Camera rig members
  12165. this.cameraRigMode = Camera.RIG_MODE_NONE;
  12166. this._rigCameras = new Array();
  12167. // Cache
  12168. this._computedViewMatrix = BABYLON.Matrix.Identity();
  12169. this._projectionMatrix = new BABYLON.Matrix();
  12170. this._postProcesses = new Array();
  12171. this._transformMatrix = BABYLON.Matrix.Zero();
  12172. this._activeMeshes = new BABYLON.SmartArray(256);
  12173. this._globalPosition = BABYLON.Vector3.Zero();
  12174. this._refreshFrustumPlanes = true;
  12175. scene.addCamera(this);
  12176. if (!scene.activeCamera) {
  12177. scene.activeCamera = this;
  12178. }
  12179. this.position = position;
  12180. }
  12181. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  12182. get: function () {
  12183. return Camera._PERSPECTIVE_CAMERA;
  12184. },
  12185. enumerable: true,
  12186. configurable: true
  12187. });
  12188. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  12189. get: function () {
  12190. return Camera._ORTHOGRAPHIC_CAMERA;
  12191. },
  12192. enumerable: true,
  12193. configurable: true
  12194. });
  12195. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  12196. get: function () {
  12197. return Camera._FOVMODE_VERTICAL_FIXED;
  12198. },
  12199. enumerable: true,
  12200. configurable: true
  12201. });
  12202. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  12203. get: function () {
  12204. return Camera._FOVMODE_HORIZONTAL_FIXED;
  12205. },
  12206. enumerable: true,
  12207. configurable: true
  12208. });
  12209. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  12210. get: function () {
  12211. return Camera._RIG_MODE_NONE;
  12212. },
  12213. enumerable: true,
  12214. configurable: true
  12215. });
  12216. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  12217. get: function () {
  12218. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  12219. },
  12220. enumerable: true,
  12221. configurable: true
  12222. });
  12223. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  12224. get: function () {
  12225. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  12226. },
  12227. enumerable: true,
  12228. configurable: true
  12229. });
  12230. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  12231. get: function () {
  12232. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  12233. },
  12234. enumerable: true,
  12235. configurable: true
  12236. });
  12237. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  12238. get: function () {
  12239. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  12240. },
  12241. enumerable: true,
  12242. configurable: true
  12243. });
  12244. Object.defineProperty(Camera, "RIG_MODE_VR", {
  12245. get: function () {
  12246. return Camera._RIG_MODE_VR;
  12247. },
  12248. enumerable: true,
  12249. configurable: true
  12250. });
  12251. /**
  12252. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  12253. */
  12254. Camera.prototype.toString = function (fullDetails) {
  12255. var ret = "Name: " + this.name;
  12256. ret += ", type: " + this.getTypeName();
  12257. if (this.animations) {
  12258. for (var i = 0; i < this.animations.length; i++) {
  12259. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  12260. }
  12261. }
  12262. if (fullDetails) {
  12263. }
  12264. return ret;
  12265. };
  12266. Object.defineProperty(Camera.prototype, "globalPosition", {
  12267. get: function () {
  12268. return this._globalPosition;
  12269. },
  12270. enumerable: true,
  12271. configurable: true
  12272. });
  12273. Camera.prototype.getActiveMeshes = function () {
  12274. return this._activeMeshes;
  12275. };
  12276. Camera.prototype.isActiveMesh = function (mesh) {
  12277. return (this._activeMeshes.indexOf(mesh) !== -1);
  12278. };
  12279. //Cache
  12280. Camera.prototype._initCache = function () {
  12281. _super.prototype._initCache.call(this);
  12282. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  12283. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  12284. this._cache.mode = undefined;
  12285. this._cache.minZ = undefined;
  12286. this._cache.maxZ = undefined;
  12287. this._cache.fov = undefined;
  12288. this._cache.aspectRatio = undefined;
  12289. this._cache.orthoLeft = undefined;
  12290. this._cache.orthoRight = undefined;
  12291. this._cache.orthoBottom = undefined;
  12292. this._cache.orthoTop = undefined;
  12293. this._cache.renderWidth = undefined;
  12294. this._cache.renderHeight = undefined;
  12295. };
  12296. Camera.prototype._updateCache = function (ignoreParentClass) {
  12297. if (!ignoreParentClass) {
  12298. _super.prototype._updateCache.call(this);
  12299. }
  12300. var engine = this.getEngine();
  12301. this._cache.position.copyFrom(this.position);
  12302. this._cache.upVector.copyFrom(this.upVector);
  12303. this._cache.mode = this.mode;
  12304. this._cache.minZ = this.minZ;
  12305. this._cache.maxZ = this.maxZ;
  12306. this._cache.fov = this.fov;
  12307. this._cache.aspectRatio = engine.getAspectRatio(this);
  12308. this._cache.orthoLeft = this.orthoLeft;
  12309. this._cache.orthoRight = this.orthoRight;
  12310. this._cache.orthoBottom = this.orthoBottom;
  12311. this._cache.orthoTop = this.orthoTop;
  12312. this._cache.renderWidth = engine.getRenderWidth();
  12313. this._cache.renderHeight = engine.getRenderHeight();
  12314. };
  12315. Camera.prototype._updateFromScene = function () {
  12316. this.updateCache();
  12317. this.update();
  12318. };
  12319. // Synchronized
  12320. Camera.prototype._isSynchronized = function () {
  12321. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  12322. };
  12323. Camera.prototype._isSynchronizedViewMatrix = function () {
  12324. if (!_super.prototype._isSynchronized.call(this))
  12325. return false;
  12326. return this._cache.position.equals(this.position)
  12327. && this._cache.upVector.equals(this.upVector)
  12328. && this.isSynchronizedWithParent();
  12329. };
  12330. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  12331. var check = this._cache.mode === this.mode
  12332. && this._cache.minZ === this.minZ
  12333. && this._cache.maxZ === this.maxZ;
  12334. if (!check) {
  12335. return false;
  12336. }
  12337. var engine = this.getEngine();
  12338. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  12339. check = this._cache.fov === this.fov
  12340. && this._cache.aspectRatio === engine.getAspectRatio(this);
  12341. }
  12342. else {
  12343. check = this._cache.orthoLeft === this.orthoLeft
  12344. && this._cache.orthoRight === this.orthoRight
  12345. && this._cache.orthoBottom === this.orthoBottom
  12346. && this._cache.orthoTop === this.orthoTop
  12347. && this._cache.renderWidth === engine.getRenderWidth()
  12348. && this._cache.renderHeight === engine.getRenderHeight();
  12349. }
  12350. return check;
  12351. };
  12352. // Controls
  12353. Camera.prototype.attachControl = function (element, noPreventDefault) {
  12354. };
  12355. Camera.prototype.detachControl = function (element) {
  12356. };
  12357. Camera.prototype.update = function () {
  12358. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  12359. this._updateRigCameras();
  12360. }
  12361. this._checkInputs();
  12362. };
  12363. Camera.prototype._checkInputs = function () {
  12364. };
  12365. Camera.prototype._cascadePostProcessesToRigCams = function () {
  12366. // invalidate framebuffer
  12367. if (this._postProcesses.length > 0) {
  12368. this._postProcesses[0].markTextureDirty();
  12369. }
  12370. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  12371. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  12372. var cam = this._rigCameras[i];
  12373. var rigPostProcess = cam._rigPostProcess;
  12374. // for VR rig, there does not have to be a post process
  12375. if (rigPostProcess) {
  12376. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  12377. if (isPass) {
  12378. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  12379. cam.isIntermediate = this._postProcesses.length === 0;
  12380. }
  12381. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  12382. rigPostProcess.markTextureDirty();
  12383. }
  12384. else {
  12385. cam._postProcesses = this._postProcesses.slice(0);
  12386. }
  12387. }
  12388. };
  12389. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  12390. if (insertAt === void 0) { insertAt = null; }
  12391. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  12392. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  12393. return 0;
  12394. }
  12395. if (insertAt == null || insertAt < 0) {
  12396. this._postProcesses.push(postProcess);
  12397. }
  12398. else {
  12399. this._postProcesses.splice(insertAt, 0, postProcess);
  12400. }
  12401. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  12402. return this._postProcesses.indexOf(postProcess);
  12403. };
  12404. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  12405. if (atIndices === void 0) { atIndices = null; }
  12406. var result = [];
  12407. var i;
  12408. var index;
  12409. if (!atIndices) {
  12410. var idx = this._postProcesses.indexOf(postProcess);
  12411. if (idx !== -1) {
  12412. this._postProcesses.splice(idx, 1);
  12413. }
  12414. }
  12415. else {
  12416. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  12417. // iterate descending, so can just splice as we go
  12418. for (i = atIndices.length - 1; i >= 0; i--) {
  12419. if (this._postProcesses[atIndices[i]] !== postProcess) {
  12420. result.push(i);
  12421. continue;
  12422. }
  12423. this._postProcesses.splice(index, 1);
  12424. }
  12425. }
  12426. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  12427. return result;
  12428. };
  12429. Camera.prototype.getWorldMatrix = function () {
  12430. if (!this._worldMatrix) {
  12431. this._worldMatrix = BABYLON.Matrix.Identity();
  12432. }
  12433. var viewMatrix = this.getViewMatrix();
  12434. viewMatrix.invertToRef(this._worldMatrix);
  12435. return this._worldMatrix;
  12436. };
  12437. Camera.prototype._getViewMatrix = function () {
  12438. return BABYLON.Matrix.Identity();
  12439. };
  12440. Camera.prototype.getViewMatrix = function (force) {
  12441. this._computedViewMatrix = this._computeViewMatrix(force);
  12442. if (!force && this._isSynchronizedViewMatrix()) {
  12443. return this._computedViewMatrix;
  12444. }
  12445. this._refreshFrustumPlanes = true;
  12446. if (!this.parent || !this.parent.getWorldMatrix) {
  12447. this._globalPosition.copyFrom(this.position);
  12448. }
  12449. else {
  12450. if (!this._worldMatrix) {
  12451. this._worldMatrix = BABYLON.Matrix.Identity();
  12452. }
  12453. this._computedViewMatrix.invertToRef(this._worldMatrix);
  12454. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  12455. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  12456. this._computedViewMatrix.invert();
  12457. this._markSyncedWithParent();
  12458. }
  12459. this._currentRenderId = this.getScene().getRenderId();
  12460. return this._computedViewMatrix;
  12461. };
  12462. Camera.prototype._computeViewMatrix = function (force) {
  12463. if (!force && this._isSynchronizedViewMatrix()) {
  12464. return this._computedViewMatrix;
  12465. }
  12466. this._computedViewMatrix = this._getViewMatrix();
  12467. this._currentRenderId = this.getScene().getRenderId();
  12468. return this._computedViewMatrix;
  12469. };
  12470. Camera.prototype.getProjectionMatrix = function (force) {
  12471. if (!force && this._isSynchronizedProjectionMatrix()) {
  12472. return this._projectionMatrix;
  12473. }
  12474. this._refreshFrustumPlanes = true;
  12475. var engine = this.getEngine();
  12476. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  12477. if (this.minZ <= 0) {
  12478. this.minZ = 0.1;
  12479. }
  12480. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  12481. return this._projectionMatrix;
  12482. }
  12483. var halfWidth = engine.getRenderWidth() / 2.0;
  12484. var halfHeight = engine.getRenderHeight() / 2.0;
  12485. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  12486. return this._projectionMatrix;
  12487. };
  12488. Camera.prototype.getTranformationMatrix = function () {
  12489. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  12490. return this._transformMatrix;
  12491. };
  12492. Camera.prototype.updateFrustumPlanes = function () {
  12493. if (!this._refreshFrustumPlanes) {
  12494. return;
  12495. }
  12496. this.getTranformationMatrix();
  12497. if (!this._frustumPlanes) {
  12498. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  12499. }
  12500. else {
  12501. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  12502. }
  12503. this._refreshFrustumPlanes = false;
  12504. };
  12505. Camera.prototype.isInFrustum = function (target) {
  12506. this.updateFrustumPlanes();
  12507. return target.isInFrustum(this._frustumPlanes);
  12508. };
  12509. Camera.prototype.isCompletelyInFrustum = function (target) {
  12510. this.updateFrustumPlanes();
  12511. return target.isCompletelyInFrustum(this._frustumPlanes);
  12512. };
  12513. Camera.prototype.dispose = function () {
  12514. // Animations
  12515. this.getScene().stopAnimation(this);
  12516. // Remove from scene
  12517. this.getScene().removeCamera(this);
  12518. while (this._rigCameras.length > 0) {
  12519. this._rigCameras.pop().dispose();
  12520. }
  12521. // Postprocesses
  12522. for (var i = 0; i < this._postProcesses.length; ++i) {
  12523. this._postProcesses[i].dispose(this);
  12524. }
  12525. _super.prototype.dispose.call(this);
  12526. };
  12527. // ---- Camera rigs section ----
  12528. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  12529. while (this._rigCameras.length > 0) {
  12530. this._rigCameras.pop().dispose();
  12531. }
  12532. this.cameraRigMode = mode;
  12533. this._cameraRigParams = {};
  12534. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  12535. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  12536. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  12537. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  12538. // create the rig cameras, unless none
  12539. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  12540. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  12541. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  12542. }
  12543. switch (this.cameraRigMode) {
  12544. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  12545. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  12546. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  12547. break;
  12548. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  12549. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  12550. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  12551. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  12552. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  12553. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  12554. break;
  12555. case Camera.RIG_MODE_VR:
  12556. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  12557. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  12558. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  12559. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  12560. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  12561. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  12562. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  12563. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  12564. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  12565. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  12566. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  12567. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  12568. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  12569. if (metrics.compensateDistortion) {
  12570. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  12571. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  12572. }
  12573. break;
  12574. }
  12575. this._cascadePostProcessesToRigCams();
  12576. this.
  12577. update();
  12578. };
  12579. Camera.prototype._getVRProjectionMatrix = function () {
  12580. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  12581. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  12582. return this._projectionMatrix;
  12583. };
  12584. Camera.prototype.setCameraRigParameter = function (name, value) {
  12585. if (!this._cameraRigParams) {
  12586. this._cameraRigParams = {};
  12587. }
  12588. this._cameraRigParams[name] = value;
  12589. //provisionnally:
  12590. if (name === "interaxialDistance") {
  12591. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  12592. }
  12593. };
  12594. /**
  12595. * needs to be overridden by children so sub has required properties to be copied
  12596. */
  12597. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  12598. return null;
  12599. };
  12600. /**
  12601. * May need to be overridden by children
  12602. */
  12603. Camera.prototype._updateRigCameras = function () {
  12604. for (var i = 0; i < this._rigCameras.length; i++) {
  12605. this._rigCameras[i].minZ = this.minZ;
  12606. this._rigCameras[i].maxZ = this.maxZ;
  12607. this._rigCameras[i].fov = this.fov;
  12608. }
  12609. // only update viewport when ANAGLYPH
  12610. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  12611. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  12612. }
  12613. };
  12614. Camera.prototype._setupInputs = function () {
  12615. };
  12616. Camera.prototype.serialize = function () {
  12617. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  12618. // Type
  12619. serializationObject.type = this.getTypeName();
  12620. // Parent
  12621. if (this.parent) {
  12622. serializationObject.parentId = this.parent.id;
  12623. }
  12624. if (this.inputs) {
  12625. this.inputs.serialize(serializationObject);
  12626. }
  12627. // Animations
  12628. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  12629. serializationObject.ranges = this.serializeAnimationRanges();
  12630. return serializationObject;
  12631. };
  12632. Camera.prototype.getTypeName = function () {
  12633. return "Camera";
  12634. };
  12635. Camera.prototype.clone = function (name) {
  12636. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getTypeName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  12637. };
  12638. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  12639. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  12640. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  12641. switch (type) {
  12642. case "ArcRotateCamera":
  12643. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  12644. case "DeviceOrientationCamera":
  12645. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  12646. case "FollowCamera":
  12647. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  12648. case "ArcFollowCamera":
  12649. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  12650. case "GamepadCamera":
  12651. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  12652. case "TouchCamera":
  12653. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  12654. case "VirtualJoysticksCamera":
  12655. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  12656. case "WebVRFreeCamera":
  12657. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  12658. case "VRDeviceOrientationFreeCamera":
  12659. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  12660. case "AnaglyphArcRotateCamera":
  12661. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  12662. case "AnaglyphFreeCamera":
  12663. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  12664. case "AnaglyphGamepadCamera":
  12665. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  12666. case "AnaglyphUniversalCamera":
  12667. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  12668. case "StereoscopicArcRotateCamera":
  12669. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  12670. case "StereoscopicFreeCamera":
  12671. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  12672. case "StereoscopicGamepadCamera":
  12673. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  12674. case "StereoscopicUniversalCamera":
  12675. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  12676. case "FreeCamera":
  12677. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  12678. default:
  12679. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  12680. }
  12681. };
  12682. Camera.Parse = function (parsedCamera, scene) {
  12683. var type = parsedCamera.type;
  12684. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  12685. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  12686. // Parent
  12687. if (parsedCamera.parentId) {
  12688. camera._waitingParentId = parsedCamera.parentId;
  12689. }
  12690. //If camera has an input manager, let it parse inputs settings
  12691. if (camera.inputs) {
  12692. camera.inputs.parse(parsedCamera);
  12693. camera._setupInputs();
  12694. }
  12695. // Target
  12696. if (parsedCamera.target) {
  12697. if (camera.setTarget) {
  12698. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  12699. }
  12700. }
  12701. // Apply 3d rig, when found
  12702. if (parsedCamera.cameraRigMode) {
  12703. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  12704. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  12705. }
  12706. // Animations
  12707. if (parsedCamera.animations) {
  12708. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  12709. var parsedAnimation = parsedCamera.animations[animationIndex];
  12710. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  12711. }
  12712. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  12713. }
  12714. if (parsedCamera.autoAnimate) {
  12715. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  12716. }
  12717. return camera;
  12718. };
  12719. // Statics
  12720. Camera._PERSPECTIVE_CAMERA = 0;
  12721. Camera._ORTHOGRAPHIC_CAMERA = 1;
  12722. Camera._FOVMODE_VERTICAL_FIXED = 0;
  12723. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  12724. Camera._RIG_MODE_NONE = 0;
  12725. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  12726. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  12727. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  12728. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  12729. Camera._RIG_MODE_VR = 20;
  12730. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  12731. __decorate([
  12732. BABYLON.serializeAsVector3()
  12733. ], Camera.prototype, "position", void 0);
  12734. __decorate([
  12735. BABYLON.serializeAsVector3()
  12736. ], Camera.prototype, "upVector", void 0);
  12737. __decorate([
  12738. BABYLON.serialize()
  12739. ], Camera.prototype, "orthoLeft", void 0);
  12740. __decorate([
  12741. BABYLON.serialize()
  12742. ], Camera.prototype, "orthoRight", void 0);
  12743. __decorate([
  12744. BABYLON.serialize()
  12745. ], Camera.prototype, "orthoBottom", void 0);
  12746. __decorate([
  12747. BABYLON.serialize()
  12748. ], Camera.prototype, "orthoTop", void 0);
  12749. __decorate([
  12750. BABYLON.serialize()
  12751. ], Camera.prototype, "fov", void 0);
  12752. __decorate([
  12753. BABYLON.serialize()
  12754. ], Camera.prototype, "minZ", void 0);
  12755. __decorate([
  12756. BABYLON.serialize()
  12757. ], Camera.prototype, "maxZ", void 0);
  12758. __decorate([
  12759. BABYLON.serialize()
  12760. ], Camera.prototype, "inertia", void 0);
  12761. __decorate([
  12762. BABYLON.serialize()
  12763. ], Camera.prototype, "mode", void 0);
  12764. __decorate([
  12765. BABYLON.serialize()
  12766. ], Camera.prototype, "layerMask", void 0);
  12767. __decorate([
  12768. BABYLON.serialize()
  12769. ], Camera.prototype, "fovMode", void 0);
  12770. __decorate([
  12771. BABYLON.serialize()
  12772. ], Camera.prototype, "cameraRigMode", void 0);
  12773. __decorate([
  12774. BABYLON.serialize()
  12775. ], Camera.prototype, "interaxialDistance", void 0);
  12776. __decorate([
  12777. BABYLON.serialize()
  12778. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  12779. return Camera;
  12780. })(BABYLON.Node);
  12781. BABYLON.Camera = Camera;
  12782. })(BABYLON || (BABYLON = {}));
  12783. var BABYLON;
  12784. (function (BABYLON) {
  12785. BABYLON.CameraInputTypes = {};
  12786. var CameraInputsManager = (function () {
  12787. function CameraInputsManager(camera) {
  12788. this.attached = {};
  12789. this.camera = camera;
  12790. this.checkInputs = function () { };
  12791. }
  12792. CameraInputsManager.prototype.add = function (input) {
  12793. var type = input.getSimpleName();
  12794. if (this.attached[type]) {
  12795. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  12796. return;
  12797. }
  12798. this.attached[type] = input;
  12799. input.camera = this.camera;
  12800. //for checkInputs, we are dynamically creating a function
  12801. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  12802. if (input.checkInputs) {
  12803. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  12804. }
  12805. if (this.attachedElement) {
  12806. input.attachControl(this.attachedElement);
  12807. }
  12808. };
  12809. CameraInputsManager.prototype.remove = function (inputToRemove) {
  12810. for (var cam in this.attached) {
  12811. var input = this.attached[cam];
  12812. if (input === inputToRemove) {
  12813. input.detachControl(this.attachedElement);
  12814. delete this.attached[cam];
  12815. this.rebuildInputCheck();
  12816. }
  12817. }
  12818. };
  12819. CameraInputsManager.prototype.removeByType = function (inputType) {
  12820. for (var cam in this.attached) {
  12821. var input = this.attached[cam];
  12822. if (input.getTypeName() === inputType) {
  12823. input.detachControl(this.attachedElement);
  12824. delete this.attached[cam];
  12825. this.rebuildInputCheck();
  12826. }
  12827. }
  12828. };
  12829. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  12830. var current = this.checkInputs;
  12831. return function () {
  12832. current();
  12833. fn();
  12834. };
  12835. };
  12836. CameraInputsManager.prototype.attachInput = function (input) {
  12837. input.attachControl(this.attachedElement, this.noPreventDefault);
  12838. };
  12839. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  12840. if (this.attachedElement) {
  12841. return;
  12842. }
  12843. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  12844. this.attachedElement = element;
  12845. this.noPreventDefault = noPreventDefault;
  12846. for (var cam in this.attached) {
  12847. var input = this.attached[cam];
  12848. this.attached[cam].attachControl(element, noPreventDefault);
  12849. }
  12850. };
  12851. CameraInputsManager.prototype.detachElement = function (element) {
  12852. if (this.attachedElement !== element) {
  12853. return;
  12854. }
  12855. for (var cam in this.attached) {
  12856. var input = this.attached[cam];
  12857. this.attached[cam].detachControl(element);
  12858. }
  12859. this.attachedElement = null;
  12860. };
  12861. CameraInputsManager.prototype.rebuildInputCheck = function () {
  12862. this.checkInputs = function () { };
  12863. for (var cam in this.attached) {
  12864. var input = this.attached[cam];
  12865. if (input.checkInputs) {
  12866. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  12867. }
  12868. }
  12869. };
  12870. CameraInputsManager.prototype.clear = function () {
  12871. if (this.attachedElement) {
  12872. this.detachElement(this.attachedElement);
  12873. }
  12874. this.attached = {};
  12875. this.attachedElement = null;
  12876. this.checkInputs = function () { };
  12877. };
  12878. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  12879. var inputs = {};
  12880. for (var cam in this.attached) {
  12881. var input = this.attached[cam];
  12882. var res = BABYLON.SerializationHelper.Serialize(input);
  12883. inputs[input.getTypeName()] = res;
  12884. }
  12885. serializedCamera.inputsmgr = inputs;
  12886. };
  12887. CameraInputsManager.prototype.parse = function (parsedCamera) {
  12888. var parsedInputs = parsedCamera.inputsmgr;
  12889. if (parsedInputs) {
  12890. this.clear();
  12891. for (var n in parsedInputs) {
  12892. var construct = BABYLON.CameraInputTypes[n];
  12893. if (construct) {
  12894. var parsedinput = parsedInputs[n];
  12895. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  12896. this.add(input);
  12897. }
  12898. }
  12899. }
  12900. else {
  12901. //2016-03-08 this part is for managing backward compatibility
  12902. for (var n in this.attached) {
  12903. var construct = BABYLON.CameraInputTypes[this.attached[n].getTypeName()];
  12904. if (construct) {
  12905. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  12906. this.remove(this.attached[n]);
  12907. this.add(input);
  12908. }
  12909. }
  12910. }
  12911. };
  12912. return CameraInputsManager;
  12913. })();
  12914. BABYLON.CameraInputsManager = CameraInputsManager;
  12915. })(BABYLON || (BABYLON = {}));
  12916. var BABYLON;
  12917. (function (BABYLON) {
  12918. var FreeCameraMouseInput = (function () {
  12919. function FreeCameraMouseInput(touchEnabled) {
  12920. if (touchEnabled === void 0) { touchEnabled = true; }
  12921. this.touchEnabled = touchEnabled;
  12922. this.angularSensibility = 2000.0;
  12923. }
  12924. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  12925. var _this = this;
  12926. if (!this._pointerInput) {
  12927. var camera = this.camera;
  12928. var engine = this.camera.getEngine();
  12929. this._pointerInput = function (p, s) {
  12930. var evt = p.event;
  12931. if (!_this.touchEnabled && evt.pointerType === "touch") {
  12932. return;
  12933. }
  12934. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  12935. try {
  12936. evt.srcElement.setPointerCapture(evt.pointerId);
  12937. }
  12938. catch (e) {
  12939. }
  12940. _this.previousPosition = {
  12941. x: evt.clientX,
  12942. y: evt.clientY
  12943. };
  12944. if (!noPreventDefault) {
  12945. evt.preventDefault();
  12946. element.focus();
  12947. }
  12948. }
  12949. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  12950. try {
  12951. evt.srcElement.releasePointerCapture(evt.pointerId);
  12952. }
  12953. catch (e) {
  12954. }
  12955. _this.previousPosition = null;
  12956. if (!noPreventDefault) {
  12957. evt.preventDefault();
  12958. }
  12959. }
  12960. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  12961. if (!_this.previousPosition && !engine.isPointerLock) {
  12962. return;
  12963. }
  12964. var offsetX;
  12965. var offsetY;
  12966. if (!engine.isPointerLock) {
  12967. offsetX = evt.clientX - _this.previousPosition.x;
  12968. offsetY = evt.clientY - _this.previousPosition.y;
  12969. }
  12970. else {
  12971. offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  12972. offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  12973. }
  12974. camera.cameraRotation.y += offsetX / _this.angularSensibility;
  12975. camera.cameraRotation.x += offsetY / _this.angularSensibility;
  12976. _this.previousPosition = {
  12977. x: evt.clientX,
  12978. y: evt.clientY
  12979. };
  12980. if (!noPreventDefault) {
  12981. evt.preventDefault();
  12982. }
  12983. }
  12984. };
  12985. }
  12986. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  12987. };
  12988. FreeCameraMouseInput.prototype.detachControl = function (element) {
  12989. if (this._observer && element) {
  12990. this.camera.getScene().onPointerObservable.remove(this._observer);
  12991. this._observer = null;
  12992. this.previousPosition = null;
  12993. }
  12994. };
  12995. FreeCameraMouseInput.prototype.getTypeName = function () {
  12996. return "FreeCameraMouseInput";
  12997. };
  12998. FreeCameraMouseInput.prototype.getSimpleName = function () {
  12999. return "mouse";
  13000. };
  13001. __decorate([
  13002. BABYLON.serialize()
  13003. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  13004. return FreeCameraMouseInput;
  13005. })();
  13006. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  13007. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  13008. })(BABYLON || (BABYLON = {}));
  13009. var BABYLON;
  13010. (function (BABYLON) {
  13011. var FreeCameraKeyboardMoveInput = (function () {
  13012. function FreeCameraKeyboardMoveInput() {
  13013. this._keys = [];
  13014. this.keysUp = [38];
  13015. this.keysDown = [40];
  13016. this.keysLeft = [37];
  13017. this.keysRight = [39];
  13018. }
  13019. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  13020. var _this = this;
  13021. if (!this._onKeyDown) {
  13022. element.tabIndex = 1;
  13023. this._onKeyDown = function (evt) {
  13024. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  13025. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  13026. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  13027. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  13028. var index = _this._keys.indexOf(evt.keyCode);
  13029. if (index === -1) {
  13030. _this._keys.push(evt.keyCode);
  13031. }
  13032. if (!noPreventDefault) {
  13033. evt.preventDefault();
  13034. }
  13035. }
  13036. };
  13037. this._onKeyUp = function (evt) {
  13038. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  13039. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  13040. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  13041. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  13042. var index = _this._keys.indexOf(evt.keyCode);
  13043. if (index >= 0) {
  13044. _this._keys.splice(index, 1);
  13045. }
  13046. if (!noPreventDefault) {
  13047. evt.preventDefault();
  13048. }
  13049. }
  13050. };
  13051. element.addEventListener("keydown", this._onKeyDown, false);
  13052. element.addEventListener("keyup", this._onKeyUp, false);
  13053. BABYLON.Tools.RegisterTopRootEvents([
  13054. { name: "blur", handler: this._onLostFocus }
  13055. ]);
  13056. }
  13057. };
  13058. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  13059. if (this._onKeyDown) {
  13060. element.removeEventListener("keydown", this._onKeyDown);
  13061. element.removeEventListener("keyup", this._onKeyUp);
  13062. BABYLON.Tools.UnregisterTopRootEvents([
  13063. { name: "blur", handler: this._onLostFocus }
  13064. ]);
  13065. this._keys = [];
  13066. this._onKeyDown = null;
  13067. this._onKeyUp = null;
  13068. }
  13069. };
  13070. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  13071. if (this._onKeyDown) {
  13072. var camera = this.camera;
  13073. // Keyboard
  13074. for (var index = 0; index < this._keys.length; index++) {
  13075. var keyCode = this._keys[index];
  13076. var speed = camera._computeLocalCameraSpeed();
  13077. if (this.keysLeft.indexOf(keyCode) !== -1) {
  13078. camera._localDirection.copyFromFloats(-speed, 0, 0);
  13079. }
  13080. else if (this.keysUp.indexOf(keyCode) !== -1) {
  13081. camera._localDirection.copyFromFloats(0, 0, speed);
  13082. }
  13083. else if (this.keysRight.indexOf(keyCode) !== -1) {
  13084. camera._localDirection.copyFromFloats(speed, 0, 0);
  13085. }
  13086. else if (this.keysDown.indexOf(keyCode) !== -1) {
  13087. camera._localDirection.copyFromFloats(0, 0, -speed);
  13088. }
  13089. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  13090. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  13091. camera.cameraDirection.addInPlace(camera._transformedDirection);
  13092. }
  13093. }
  13094. };
  13095. FreeCameraKeyboardMoveInput.prototype.getTypeName = function () {
  13096. return "FreeCameraKeyboardMoveInput";
  13097. };
  13098. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  13099. this._keys = [];
  13100. };
  13101. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  13102. return "keyboard";
  13103. };
  13104. __decorate([
  13105. BABYLON.serialize()
  13106. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  13107. __decorate([
  13108. BABYLON.serialize()
  13109. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  13110. __decorate([
  13111. BABYLON.serialize()
  13112. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  13113. __decorate([
  13114. BABYLON.serialize()
  13115. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  13116. return FreeCameraKeyboardMoveInput;
  13117. })();
  13118. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  13119. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  13120. })(BABYLON || (BABYLON = {}));
  13121. var BABYLON;
  13122. (function (BABYLON) {
  13123. var FreeCameraTouchInput = (function () {
  13124. function FreeCameraTouchInput() {
  13125. this._offsetX = null;
  13126. this._offsetY = null;
  13127. this._pointerCount = 0;
  13128. this._pointerPressed = [];
  13129. this.touchAngularSensibility = 200000.0;
  13130. this.touchMoveSensibility = 250.0;
  13131. }
  13132. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  13133. var _this = this;
  13134. var previousPosition;
  13135. if (this._pointerInput === undefined) {
  13136. this._onLostFocus = function (evt) {
  13137. _this._offsetX = null;
  13138. _this._offsetY = null;
  13139. };
  13140. this._pointerInput = function (p, s) {
  13141. var evt = p.event;
  13142. if (evt.pointerType === "mouse") {
  13143. return;
  13144. }
  13145. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  13146. if (!noPreventDefault) {
  13147. evt.preventDefault();
  13148. }
  13149. _this._pointerPressed.push(evt.pointerId);
  13150. if (_this._pointerPressed.length !== 1) {
  13151. return;
  13152. }
  13153. previousPosition = {
  13154. x: evt.clientX,
  13155. y: evt.clientY
  13156. };
  13157. }
  13158. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  13159. if (!noPreventDefault) {
  13160. evt.preventDefault();
  13161. }
  13162. var index = _this._pointerPressed.indexOf(evt.pointerId);
  13163. if (index === -1) {
  13164. return;
  13165. }
  13166. _this._pointerPressed.splice(index, 1);
  13167. if (index != 0) {
  13168. return;
  13169. }
  13170. previousPosition = null;
  13171. _this._offsetX = null;
  13172. _this._offsetY = null;
  13173. }
  13174. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  13175. if (!noPreventDefault) {
  13176. evt.preventDefault();
  13177. }
  13178. if (!previousPosition) {
  13179. return;
  13180. }
  13181. var index = _this._pointerPressed.indexOf(evt.pointerId);
  13182. if (index != 0) {
  13183. return;
  13184. }
  13185. _this._offsetX = evt.clientX - previousPosition.x;
  13186. _this._offsetY = -(evt.clientY - previousPosition.y);
  13187. }
  13188. };
  13189. }
  13190. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  13191. element.addEventListener("blur", this._onLostFocus);
  13192. };
  13193. FreeCameraTouchInput.prototype.detachControl = function (element) {
  13194. if (this._pointerInput && element) {
  13195. this.camera.getScene().onPointerObservable.remove(this._observer);
  13196. this._observer = null;
  13197. element.removeEventListener("blur", this._onLostFocus);
  13198. this._onLostFocus = null;
  13199. this._pointerPressed = [];
  13200. this._offsetX = null;
  13201. this._offsetY = null;
  13202. this._pointerCount = 0;
  13203. }
  13204. };
  13205. FreeCameraTouchInput.prototype.checkInputs = function () {
  13206. if (this._offsetX) {
  13207. var camera = this.camera;
  13208. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  13209. if (this._pointerPressed.length > 1) {
  13210. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  13211. }
  13212. else {
  13213. var speed = camera._computeLocalCameraSpeed();
  13214. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  13215. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  13216. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  13217. }
  13218. }
  13219. };
  13220. FreeCameraTouchInput.prototype.getTypeName = function () {
  13221. return "FreeCameraTouchInput";
  13222. };
  13223. FreeCameraTouchInput.prototype.getSimpleName = function () {
  13224. return "touch";
  13225. };
  13226. __decorate([
  13227. BABYLON.serialize()
  13228. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  13229. __decorate([
  13230. BABYLON.serialize()
  13231. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  13232. return FreeCameraTouchInput;
  13233. })();
  13234. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  13235. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  13236. })(BABYLON || (BABYLON = {}));
  13237. var BABYLON;
  13238. (function (BABYLON) {
  13239. var FreeCameraDeviceOrientationInput = (function () {
  13240. function FreeCameraDeviceOrientationInput() {
  13241. var _this = this;
  13242. this._screenOrientationAngle = 0;
  13243. this._screenQuaternion = new BABYLON.Quaternion();
  13244. this._alpha = 0;
  13245. this._beta = 0;
  13246. this._gamma = 0;
  13247. this._orientationChanged = function () {
  13248. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  13249. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  13250. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  13251. };
  13252. this._deviceOrientation = function (evt) {
  13253. _this._alpha = evt.alpha;
  13254. _this._beta = evt.beta;
  13255. _this._gamma = evt.gamma;
  13256. };
  13257. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  13258. this._orientationChanged();
  13259. }
  13260. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  13261. get: function () {
  13262. return this._camera;
  13263. },
  13264. set: function (camera) {
  13265. this._camera = camera;
  13266. if (!this._camera.rotationQuaternion)
  13267. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  13268. },
  13269. enumerable: true,
  13270. configurable: true
  13271. });
  13272. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  13273. window.addEventListener("orientationchange", this._orientationChanged);
  13274. window.addEventListener("deviceorientation", this._deviceOrientation);
  13275. };
  13276. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  13277. window.removeEventListener("orientationchange", this._orientationChanged);
  13278. window.removeEventListener("deviceorientation", this._deviceOrientation);
  13279. };
  13280. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  13281. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  13282. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  13283. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  13284. //Mirror on XY Plane
  13285. this._camera.rotationQuaternion.z *= -1;
  13286. this._camera.rotationQuaternion.w *= -1;
  13287. };
  13288. FreeCameraDeviceOrientationInput.prototype.getTypeName = function () {
  13289. return "FreeCameraDeviceOrientationInput";
  13290. };
  13291. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  13292. return "deviceOrientation";
  13293. };
  13294. return FreeCameraDeviceOrientationInput;
  13295. })();
  13296. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  13297. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  13298. })(BABYLON || (BABYLON = {}));
  13299. var BABYLON;
  13300. (function (BABYLON) {
  13301. var FreeCameraGamepadInput = (function () {
  13302. function FreeCameraGamepadInput() {
  13303. this.gamepadAngularSensibility = 200;
  13304. this.gamepadMoveSensibility = 40;
  13305. }
  13306. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  13307. var _this = this;
  13308. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  13309. };
  13310. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  13311. if (this._gamepads) {
  13312. this._gamepads.dispose();
  13313. }
  13314. this.gamepad = null;
  13315. };
  13316. FreeCameraGamepadInput.prototype.checkInputs = function () {
  13317. if (this.gamepad) {
  13318. var camera = this.camera;
  13319. var LSValues = this.gamepad.leftStick;
  13320. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  13321. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  13322. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  13323. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  13324. var RSValues = this.gamepad.rightStick;
  13325. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  13326. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  13327. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  13328. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  13329. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  13330. var speed = camera._computeLocalCameraSpeed() * 50.0;
  13331. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x * speed, 0, -LSValues.y * speed), cameraTransform);
  13332. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  13333. camera.cameraRotation = camera.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  13334. }
  13335. };
  13336. FreeCameraGamepadInput.prototype._onNewGameConnected = function (gamepad) {
  13337. // Only the first gamepad can control the camera
  13338. if (gamepad.index === 0) {
  13339. this.gamepad = gamepad;
  13340. }
  13341. };
  13342. FreeCameraGamepadInput.prototype.getTypeName = function () {
  13343. return "FreeCameraGamepadInput";
  13344. };
  13345. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  13346. return "gamepad";
  13347. };
  13348. __decorate([
  13349. BABYLON.serialize()
  13350. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  13351. __decorate([
  13352. BABYLON.serialize()
  13353. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  13354. return FreeCameraGamepadInput;
  13355. })();
  13356. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  13357. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  13358. })(BABYLON || (BABYLON = {}));
  13359. var BABYLON;
  13360. (function (BABYLON) {
  13361. var ArcRotateCameraKeyboardMoveInput = (function () {
  13362. function ArcRotateCameraKeyboardMoveInput() {
  13363. this._keys = [];
  13364. this.keysUp = [38];
  13365. this.keysDown = [40];
  13366. this.keysLeft = [37];
  13367. this.keysRight = [39];
  13368. }
  13369. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  13370. var _this = this;
  13371. element.tabIndex = 1;
  13372. this._onKeyDown = function (evt) {
  13373. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  13374. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  13375. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  13376. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  13377. var index = _this._keys.indexOf(evt.keyCode);
  13378. if (index === -1) {
  13379. _this._keys.push(evt.keyCode);
  13380. }
  13381. if (evt.preventDefault) {
  13382. if (!noPreventDefault) {
  13383. evt.preventDefault();
  13384. }
  13385. }
  13386. }
  13387. };
  13388. this._onKeyUp = function (evt) {
  13389. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  13390. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  13391. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  13392. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  13393. var index = _this._keys.indexOf(evt.keyCode);
  13394. if (index >= 0) {
  13395. _this._keys.splice(index, 1);
  13396. }
  13397. if (evt.preventDefault) {
  13398. if (!noPreventDefault) {
  13399. evt.preventDefault();
  13400. }
  13401. }
  13402. }
  13403. };
  13404. this._onLostFocus = function () {
  13405. _this._keys = [];
  13406. };
  13407. element.addEventListener("keydown", this._onKeyDown, false);
  13408. element.addEventListener("keyup", this._onKeyUp, false);
  13409. BABYLON.Tools.RegisterTopRootEvents([
  13410. { name: "blur", handler: this._onLostFocus }
  13411. ]);
  13412. };
  13413. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  13414. if (element) {
  13415. element.removeEventListener("keydown", this._onKeyDown);
  13416. element.removeEventListener("keyup", this._onKeyUp);
  13417. }
  13418. BABYLON.Tools.UnregisterTopRootEvents([
  13419. { name: "blur", handler: this._onLostFocus }
  13420. ]);
  13421. this._keys = [];
  13422. this._onKeyDown = null;
  13423. this._onKeyUp = null;
  13424. this._onLostFocus = null;
  13425. };
  13426. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  13427. if (this._onKeyDown) {
  13428. var camera = this.camera;
  13429. for (var index = 0; index < this._keys.length; index++) {
  13430. var keyCode = this._keys[index];
  13431. if (this.keysLeft.indexOf(keyCode) !== -1) {
  13432. camera.inertialAlphaOffset -= 0.01;
  13433. }
  13434. else if (this.keysUp.indexOf(keyCode) !== -1) {
  13435. camera.inertialBetaOffset -= 0.01;
  13436. }
  13437. else if (this.keysRight.indexOf(keyCode) !== -1) {
  13438. camera.inertialAlphaOffset += 0.01;
  13439. }
  13440. else if (this.keysDown.indexOf(keyCode) !== -1) {
  13441. camera.inertialBetaOffset += 0.01;
  13442. }
  13443. }
  13444. }
  13445. };
  13446. ArcRotateCameraKeyboardMoveInput.prototype.getTypeName = function () {
  13447. return "ArcRotateCameraKeyboardMoveInput";
  13448. };
  13449. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  13450. return "keyboard";
  13451. };
  13452. __decorate([
  13453. BABYLON.serialize()
  13454. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  13455. __decorate([
  13456. BABYLON.serialize()
  13457. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  13458. __decorate([
  13459. BABYLON.serialize()
  13460. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  13461. __decorate([
  13462. BABYLON.serialize()
  13463. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  13464. return ArcRotateCameraKeyboardMoveInput;
  13465. })();
  13466. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  13467. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  13468. })(BABYLON || (BABYLON = {}));
  13469. var BABYLON;
  13470. (function (BABYLON) {
  13471. var ArcRotateCameraMouseWheelInput = (function () {
  13472. function ArcRotateCameraMouseWheelInput() {
  13473. this.wheelPrecision = 3.0;
  13474. }
  13475. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  13476. var _this = this;
  13477. this._wheel = function (p, s) {
  13478. //sanity check - this should be a PointerWheel event.
  13479. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  13480. return;
  13481. var event = p.event;
  13482. var delta = 0;
  13483. if (event.wheelDelta) {
  13484. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  13485. }
  13486. else if (event.detail) {
  13487. delta = -event.detail / _this.wheelPrecision;
  13488. }
  13489. if (delta)
  13490. _this.camera.inertialRadiusOffset += delta;
  13491. if (event.preventDefault) {
  13492. if (!noPreventDefault) {
  13493. event.preventDefault();
  13494. }
  13495. }
  13496. };
  13497. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  13498. };
  13499. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  13500. if (this._observer && element) {
  13501. this.camera.getScene().onPointerObservable.remove(this._observer);
  13502. this._observer = null;
  13503. this._wheel = null;
  13504. }
  13505. };
  13506. ArcRotateCameraMouseWheelInput.prototype.getTypeName = function () {
  13507. return "ArcRotateCameraMouseWheelInput";
  13508. };
  13509. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  13510. return "mousewheel";
  13511. };
  13512. __decorate([
  13513. BABYLON.serialize()
  13514. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  13515. return ArcRotateCameraMouseWheelInput;
  13516. })();
  13517. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  13518. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  13519. })(BABYLON || (BABYLON = {}));
  13520. var BABYLON;
  13521. (function (BABYLON) {
  13522. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  13523. var ArcRotateCameraPointersInput = (function () {
  13524. function ArcRotateCameraPointersInput() {
  13525. this.angularSensibilityX = 1000.0;
  13526. this.angularSensibilityY = 1000.0;
  13527. this.pinchPrecision = 6.0;
  13528. this.panningSensibility = 50.0;
  13529. this._isPanClick = false;
  13530. this.pinchInwards = true;
  13531. }
  13532. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  13533. var _this = this;
  13534. var engine = this.camera.getEngine();
  13535. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  13536. var pointA, pointB;
  13537. var previousPinchDistance = 0;
  13538. this._pointerInput = function (p, s) {
  13539. var evt = p.event;
  13540. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  13541. try {
  13542. evt.srcElement.setPointerCapture(evt.pointerId);
  13543. }
  13544. catch (e) {
  13545. }
  13546. // Manage panning with pan button click
  13547. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  13548. // manage pointers
  13549. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  13550. if (pointA === undefined) {
  13551. pointA = cacheSoloPointer;
  13552. }
  13553. else if (pointB === undefined) {
  13554. pointB = cacheSoloPointer;
  13555. }
  13556. if (!noPreventDefault) {
  13557. evt.preventDefault();
  13558. element.focus();
  13559. }
  13560. }
  13561. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  13562. try {
  13563. evt.srcElement.releasePointerCapture(evt.pointerId);
  13564. }
  13565. catch (e) {
  13566. }
  13567. cacheSoloPointer = null;
  13568. previousPinchDistance = 0;
  13569. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  13570. //but emptying completly pointers collection is required to fix a bug on iPhone :
  13571. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  13572. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  13573. pointA = pointB = undefined;
  13574. if (!noPreventDefault) {
  13575. evt.preventDefault();
  13576. }
  13577. }
  13578. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  13579. if (!noPreventDefault) {
  13580. evt.preventDefault();
  13581. }
  13582. // One button down
  13583. if (pointA && pointB === undefined) {
  13584. if (_this.panningSensibility !== 0 &&
  13585. ((evt.ctrlKey && _this.camera._useCtrlForPanning) ||
  13586. (!_this.camera._useCtrlForPanning && _this._isPanClick))) {
  13587. _this.camera
  13588. .inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  13589. _this.camera
  13590. .inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  13591. }
  13592. else {
  13593. var offsetX = evt.clientX - cacheSoloPointer.x;
  13594. var offsetY = evt.clientY - cacheSoloPointer.y;
  13595. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  13596. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  13597. }
  13598. cacheSoloPointer.x = evt.clientX;
  13599. cacheSoloPointer.y = evt.clientY;
  13600. }
  13601. else if (pointA && pointB) {
  13602. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  13603. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  13604. ed.x = evt.clientX;
  13605. ed.y = evt.clientY;
  13606. var direction = _this.pinchInwards ? 1 : -1;
  13607. var distX = pointA.x - pointB.x;
  13608. var distY = pointA.y - pointB.y;
  13609. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  13610. if (previousPinchDistance === 0) {
  13611. previousPinchDistance = pinchSquaredDistance;
  13612. return;
  13613. }
  13614. if (pinchSquaredDistance !== previousPinchDistance) {
  13615. _this.camera
  13616. .inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) /
  13617. (_this.pinchPrecision *
  13618. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  13619. direction);
  13620. previousPinchDistance = pinchSquaredDistance;
  13621. }
  13622. }
  13623. }
  13624. };
  13625. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  13626. this._onContextMenu = function (evt) {
  13627. evt.preventDefault();
  13628. };
  13629. if (!this.camera._useCtrlForPanning) {
  13630. element.addEventListener("contextmenu", this._onContextMenu, false);
  13631. }
  13632. this._onLostFocus = function () {
  13633. //this._keys = [];
  13634. pointA = pointB = undefined;
  13635. previousPinchDistance = 0;
  13636. cacheSoloPointer = null;
  13637. };
  13638. this._onMouseMove = function (evt) {
  13639. if (!engine.isPointerLock) {
  13640. return;
  13641. }
  13642. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  13643. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  13644. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  13645. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  13646. if (!noPreventDefault) {
  13647. evt.preventDefault();
  13648. }
  13649. };
  13650. this._onGestureStart = function (e) {
  13651. if (window.MSGesture === undefined) {
  13652. return;
  13653. }
  13654. if (!_this._MSGestureHandler) {
  13655. _this._MSGestureHandler = new MSGesture();
  13656. _this._MSGestureHandler.target = element;
  13657. }
  13658. _this._MSGestureHandler.addPointer(e.pointerId);
  13659. };
  13660. this._onGesture = function (e) {
  13661. _this.camera.radius *= e.scale;
  13662. if (e.preventDefault) {
  13663. if (!noPreventDefault) {
  13664. e.stopPropagation();
  13665. e.preventDefault();
  13666. }
  13667. }
  13668. };
  13669. element.addEventListener("mousemove", this._onMouseMove, false);
  13670. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  13671. element.addEventListener("MSGestureChange", this._onGesture, false);
  13672. element.addEventListener("keydown", this._onKeyDown, false);
  13673. element.addEventListener("keyup", this._onKeyUp, false);
  13674. BABYLON.Tools.RegisterTopRootEvents([
  13675. { name: "blur", handler: this._onLostFocus }
  13676. ]);
  13677. };
  13678. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  13679. if (element && this._observer) {
  13680. this.camera.getScene().onPointerObservable.remove(this._observer);
  13681. this._observer = null;
  13682. element.removeEventListener("contextmenu", this._onContextMenu);
  13683. element.removeEventListener("mousemove", this._onMouseMove);
  13684. element.removeEventListener("MSPointerDown", this._onGestureStart);
  13685. element.removeEventListener("MSGestureChange", this._onGesture);
  13686. element.removeEventListener("keydown", this._onKeyDown);
  13687. element.removeEventListener("keyup", this._onKeyUp);
  13688. this._isPanClick = false;
  13689. this.pinchInwards = true;
  13690. this._onKeyDown = null;
  13691. this._onKeyUp = null;
  13692. this._onMouseMove = null;
  13693. this._onGestureStart = null;
  13694. this._onGesture = null;
  13695. this._MSGestureHandler = null;
  13696. this._onLostFocus = null;
  13697. this._onContextMenu = null;
  13698. }
  13699. BABYLON.Tools.UnregisterTopRootEvents([
  13700. { name: "blur", handler: this._onLostFocus }
  13701. ]);
  13702. };
  13703. ArcRotateCameraPointersInput.prototype.getTypeName = function () {
  13704. return "ArcRotateCameraPointersInput";
  13705. };
  13706. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  13707. return "pointers";
  13708. };
  13709. __decorate([
  13710. BABYLON.serialize()
  13711. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  13712. __decorate([
  13713. BABYLON.serialize()
  13714. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  13715. __decorate([
  13716. BABYLON.serialize()
  13717. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  13718. __decorate([
  13719. BABYLON.serialize()
  13720. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  13721. return ArcRotateCameraPointersInput;
  13722. })();
  13723. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  13724. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  13725. })(BABYLON || (BABYLON = {}));
  13726. var BABYLON;
  13727. (function (BABYLON) {
  13728. var ArcRotateCameraGamepadInput = (function () {
  13729. function ArcRotateCameraGamepadInput() {
  13730. this.gamepadRotationSensibility = 80;
  13731. this.gamepadMoveSensibility = 40;
  13732. }
  13733. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  13734. var _this = this;
  13735. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  13736. };
  13737. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  13738. if (this._gamepads) {
  13739. this._gamepads.dispose();
  13740. }
  13741. this.gamepad = null;
  13742. };
  13743. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  13744. if (this.gamepad) {
  13745. var camera = this.camera;
  13746. var RSValues = this.gamepad.rightStick;
  13747. if (RSValues.x != 0) {
  13748. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  13749. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  13750. camera.inertialAlphaOffset += normalizedRX;
  13751. }
  13752. }
  13753. if (RSValues.y != 0) {
  13754. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  13755. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  13756. camera.inertialBetaOffset += normalizedRY;
  13757. }
  13758. }
  13759. var LSValues = this.gamepad.leftStick;
  13760. if (LSValues.y != 0) {
  13761. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  13762. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  13763. this.camera.inertialRadiusOffset -= normalizedLY;
  13764. }
  13765. }
  13766. }
  13767. };
  13768. ArcRotateCameraGamepadInput.prototype._onNewGameConnected = function (gamepad) {
  13769. // Only the first gamepad can control the camera
  13770. if (gamepad.index === 0) {
  13771. this.gamepad = gamepad;
  13772. }
  13773. };
  13774. ArcRotateCameraGamepadInput.prototype.getTypeName = function () {
  13775. return "ArcRotateCameraGamepadInput";
  13776. };
  13777. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  13778. return "gamepad";
  13779. };
  13780. __decorate([
  13781. BABYLON.serialize()
  13782. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  13783. __decorate([
  13784. BABYLON.serialize()
  13785. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  13786. return ArcRotateCameraGamepadInput;
  13787. })();
  13788. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  13789. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  13790. })(BABYLON || (BABYLON = {}));
  13791. var BABYLON;
  13792. (function (BABYLON) {
  13793. var ArcRotateCameraVRDeviceOrientationInput = (function () {
  13794. function ArcRotateCameraVRDeviceOrientationInput() {
  13795. this.alphaCorrection = 1;
  13796. this.betaCorrection = 1;
  13797. this.gammaCorrection = 1;
  13798. this._alpha = 0;
  13799. this._beta = 0;
  13800. this._gamma = 0;
  13801. this._dirty = false;
  13802. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  13803. }
  13804. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  13805. this.camera.attachControl(element, noPreventDefault);
  13806. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  13807. };
  13808. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  13809. var camera = this.camera;
  13810. this._alpha = +evt.alpha | 0;
  13811. this._beta = +evt.beta | 0;
  13812. this._gamma = +evt.gamma | 0;
  13813. this._dirty = true;
  13814. };
  13815. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  13816. if (this._dirty) {
  13817. this._dirty = false;
  13818. if (this._gamma < 0) {
  13819. this._gamma = 180 + this._gamma;
  13820. }
  13821. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  13822. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  13823. }
  13824. };
  13825. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  13826. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  13827. };
  13828. ArcRotateCameraVRDeviceOrientationInput.prototype.getTypeName = function () {
  13829. return "ArcRotateCameraVRDeviceOrientationInput";
  13830. };
  13831. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  13832. return "VRDeviceOrientation";
  13833. };
  13834. return ArcRotateCameraVRDeviceOrientationInput;
  13835. })();
  13836. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  13837. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  13838. })(BABYLON || (BABYLON = {}));
  13839. var BABYLON;
  13840. (function (BABYLON) {
  13841. var TargetCamera = (function (_super) {
  13842. __extends(TargetCamera, _super);
  13843. function TargetCamera(name, position, scene) {
  13844. _super.call(this, name, position, scene);
  13845. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  13846. this.cameraRotation = new BABYLON.Vector2(0, 0);
  13847. this.rotation = new BABYLON.Vector3(0, 0, 0);
  13848. this.speed = 2.0;
  13849. this.noRotationConstraint = false;
  13850. this.lockedTarget = null;
  13851. this._currentTarget = BABYLON.Vector3.Zero();
  13852. this._viewMatrix = BABYLON.Matrix.Zero();
  13853. this._camMatrix = BABYLON.Matrix.Zero();
  13854. this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  13855. this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  13856. this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  13857. this._defaultUpVector = new BABYLON.Vector3(0, 1, 0);
  13858. this._transformedReferencePoint = BABYLON.Vector3.Zero();
  13859. this._lookAtTemp = BABYLON.Matrix.Zero();
  13860. this._tempMatrix = BABYLON.Matrix.Zero();
  13861. }
  13862. TargetCamera.prototype.getFrontPosition = function (distance) {
  13863. var direction = this.getTarget().subtract(this.position);
  13864. direction.normalize();
  13865. direction.scaleInPlace(distance);
  13866. return this.globalPosition.add(direction);
  13867. };
  13868. TargetCamera.prototype._getLockedTargetPosition = function () {
  13869. if (!this.lockedTarget) {
  13870. return null;
  13871. }
  13872. return this.lockedTarget.position || this.lockedTarget;
  13873. };
  13874. // Cache
  13875. TargetCamera.prototype._initCache = function () {
  13876. _super.prototype._initCache.call(this);
  13877. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  13878. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  13879. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  13880. };
  13881. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  13882. if (!ignoreParentClass) {
  13883. _super.prototype._updateCache.call(this);
  13884. }
  13885. var lockedTargetPosition = this._getLockedTargetPosition();
  13886. if (!lockedTargetPosition) {
  13887. this._cache.lockedTarget = null;
  13888. }
  13889. else {
  13890. if (!this._cache.lockedTarget) {
  13891. this._cache.lockedTarget = lockedTargetPosition.clone();
  13892. }
  13893. else {
  13894. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  13895. }
  13896. }
  13897. this._cache.rotation.copyFrom(this.rotation);
  13898. if (this.rotationQuaternion)
  13899. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  13900. };
  13901. // Synchronized
  13902. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  13903. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  13904. return false;
  13905. }
  13906. var lockedTargetPosition = this._getLockedTargetPosition();
  13907. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  13908. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  13909. };
  13910. // Methods
  13911. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  13912. var engine = this.getEngine();
  13913. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  13914. };
  13915. // Target
  13916. TargetCamera.prototype.setTarget = function (target) {
  13917. this.upVector.normalize();
  13918. BABYLON.Matrix.LookAtLHToRef(this.position, target, this._defaultUpVector, this._camMatrix);
  13919. this._camMatrix.invert();
  13920. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  13921. var vDir = target.subtract(this.position);
  13922. if (vDir.x >= 0.0) {
  13923. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  13924. }
  13925. else {
  13926. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  13927. }
  13928. this.rotation.z = 0;
  13929. if (isNaN(this.rotation.x)) {
  13930. this.rotation.x = 0;
  13931. }
  13932. if (isNaN(this.rotation.y)) {
  13933. this.rotation.y = 0;
  13934. }
  13935. if (isNaN(this.rotation.z)) {
  13936. this.rotation.z = 0;
  13937. }
  13938. if (this.rotationQuaternion) {
  13939. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  13940. }
  13941. };
  13942. TargetCamera.prototype.getTarget = function () {
  13943. return this._currentTarget;
  13944. };
  13945. TargetCamera.prototype._decideIfNeedsToMove = function () {
  13946. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  13947. };
  13948. TargetCamera.prototype._updatePosition = function () {
  13949. this.position.addInPlace(this.cameraDirection);
  13950. };
  13951. TargetCamera.prototype._checkInputs = function () {
  13952. var needToMove = this._decideIfNeedsToMove();
  13953. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  13954. // Move
  13955. if (needToMove) {
  13956. this._updatePosition();
  13957. }
  13958. // Rotate
  13959. if (needToRotate) {
  13960. this.rotation.x += this.cameraRotation.x;
  13961. this.rotation.y += this.cameraRotation.y;
  13962. if (!this.noRotationConstraint) {
  13963. var limit = (Math.PI / 2) * 0.95;
  13964. if (this.rotation.x > limit)
  13965. this.rotation.x = limit;
  13966. if (this.rotation.x < -limit)
  13967. this.rotation.x = -limit;
  13968. }
  13969. }
  13970. // Inertia
  13971. if (needToMove) {
  13972. if (Math.abs(this.cameraDirection.x) < BABYLON.Epsilon) {
  13973. this.cameraDirection.x = 0;
  13974. }
  13975. if (Math.abs(this.cameraDirection.y) < BABYLON.Epsilon) {
  13976. this.cameraDirection.y = 0;
  13977. }
  13978. if (Math.abs(this.cameraDirection.z) < BABYLON.Epsilon) {
  13979. this.cameraDirection.z = 0;
  13980. }
  13981. this.cameraDirection.scaleInPlace(this.inertia);
  13982. }
  13983. if (needToRotate) {
  13984. if (Math.abs(this.cameraRotation.x) < BABYLON.Epsilon) {
  13985. this.cameraRotation.x = 0;
  13986. }
  13987. if (Math.abs(this.cameraRotation.y) < BABYLON.Epsilon) {
  13988. this.cameraRotation.y = 0;
  13989. }
  13990. this.cameraRotation.scaleInPlace(this.inertia);
  13991. }
  13992. _super.prototype._checkInputs.call(this);
  13993. };
  13994. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  13995. if (this.rotationQuaternion) {
  13996. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  13997. //update the up vector!
  13998. BABYLON.Vector3.TransformNormalToRef(this._defaultUpVector, this._cameraRotationMatrix, this.upVector);
  13999. }
  14000. else {
  14001. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  14002. }
  14003. };
  14004. TargetCamera.prototype._getViewMatrix = function () {
  14005. if (!this.lockedTarget) {
  14006. // Compute
  14007. this._updateCameraRotationMatrix();
  14008. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  14009. // Computing target and final matrix
  14010. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  14011. }
  14012. else {
  14013. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  14014. }
  14015. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  14016. return this._viewMatrix;
  14017. };
  14018. /**
  14019. * @override
  14020. * Override Camera.createRigCamera
  14021. */
  14022. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  14023. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  14024. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  14025. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR) {
  14026. if (!this.rotationQuaternion) {
  14027. this.rotationQuaternion = new BABYLON.Quaternion();
  14028. }
  14029. rigCamera._cameraRigParams = {};
  14030. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  14031. }
  14032. return rigCamera;
  14033. }
  14034. return null;
  14035. };
  14036. /**
  14037. * @override
  14038. * Override Camera._updateRigCameras
  14039. */
  14040. TargetCamera.prototype._updateRigCameras = function () {
  14041. var camLeft = this._rigCameras[0];
  14042. var camRight = this._rigCameras[1];
  14043. switch (this.cameraRigMode) {
  14044. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  14045. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  14046. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  14047. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  14048. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  14049. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  14050. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  14051. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  14052. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  14053. camLeft.setTarget(this.getTarget());
  14054. camRight.setTarget(this.getTarget());
  14055. break;
  14056. case BABYLON.Camera.RIG_MODE_VR:
  14057. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  14058. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  14059. camLeft.position.copyFrom(this.position);
  14060. camRight.position.copyFrom(this.position);
  14061. break;
  14062. }
  14063. _super.prototype._updateRigCameras.call(this);
  14064. };
  14065. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  14066. if (!this._rigCamTransformMatrix) {
  14067. this._rigCamTransformMatrix = new BABYLON.Matrix();
  14068. }
  14069. var target = this.getTarget();
  14070. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  14071. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  14072. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  14073. };
  14074. TargetCamera.prototype.getTypeName = function () {
  14075. return "TargetCamera";
  14076. };
  14077. __decorate([
  14078. BABYLON.serializeAsVector3()
  14079. ], TargetCamera.prototype, "rotation", void 0);
  14080. __decorate([
  14081. BABYLON.serialize()
  14082. ], TargetCamera.prototype, "speed", void 0);
  14083. __decorate([
  14084. BABYLON.serializeAsMeshReference("lockedTargetId")
  14085. ], TargetCamera.prototype, "lockedTarget", void 0);
  14086. return TargetCamera;
  14087. })(BABYLON.Camera);
  14088. BABYLON.TargetCamera = TargetCamera;
  14089. })(BABYLON || (BABYLON = {}));
  14090. var BABYLON;
  14091. (function (BABYLON) {
  14092. var FreeCamera = (function (_super) {
  14093. __extends(FreeCamera, _super);
  14094. function FreeCamera(name, position, scene) {
  14095. var _this = this;
  14096. _super.call(this, name, position, scene);
  14097. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  14098. this.checkCollisions = false;
  14099. this.applyGravity = false;
  14100. this._collider = new BABYLON.Collider();
  14101. this._needMoveForGravity = false;
  14102. this._oldPosition = BABYLON.Vector3.Zero();
  14103. this._diffPosition = BABYLON.Vector3.Zero();
  14104. this._newPosition = BABYLON.Vector3.Zero();
  14105. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  14106. if (collidedMesh === void 0) { collidedMesh = null; }
  14107. //TODO move this to the collision coordinator!
  14108. if (_this.getScene().workerCollisions)
  14109. newPosition.multiplyInPlace(_this._collider.radius);
  14110. var updatePosition = function (newPos) {
  14111. _this._newPosition.copyFrom(newPos);
  14112. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  14113. var oldPosition = _this.position.clone();
  14114. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  14115. _this.position.addInPlace(_this._diffPosition);
  14116. if (_this.onCollide && collidedMesh) {
  14117. _this.onCollide(collidedMesh);
  14118. }
  14119. }
  14120. };
  14121. updatePosition(newPosition);
  14122. };
  14123. this.inputs = new BABYLON.FreeCameraInputsManager(this);
  14124. this.inputs.addKeyboard().addMouse();
  14125. }
  14126. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  14127. //-- begin properties for backward compatibility for inputs
  14128. get: function () {
  14129. var mouse = this.inputs.attached["mouse"];
  14130. if (mouse)
  14131. return mouse.angularSensibility;
  14132. },
  14133. set: function (value) {
  14134. var mouse = this.inputs.attached["mouse"];
  14135. if (mouse)
  14136. mouse.angularSensibility = value;
  14137. },
  14138. enumerable: true,
  14139. configurable: true
  14140. });
  14141. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  14142. get: function () {
  14143. var keyboard = this.inputs.attached["keyboard"];
  14144. if (keyboard)
  14145. return keyboard.keysUp;
  14146. },
  14147. set: function (value) {
  14148. var keyboard = this.inputs.attached["keyboard"];
  14149. if (keyboard)
  14150. keyboard.keysUp = value;
  14151. },
  14152. enumerable: true,
  14153. configurable: true
  14154. });
  14155. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  14156. get: function () {
  14157. var keyboard = this.inputs.attached["keyboard"];
  14158. if (keyboard)
  14159. return keyboard.keysDown;
  14160. },
  14161. set: function (value) {
  14162. var keyboard = this.inputs.attached["keyboard"];
  14163. if (keyboard)
  14164. keyboard.keysDown = value;
  14165. },
  14166. enumerable: true,
  14167. configurable: true
  14168. });
  14169. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  14170. get: function () {
  14171. var keyboard = this.inputs.attached["keyboard"];
  14172. if (keyboard)
  14173. return keyboard.keysLeft;
  14174. },
  14175. set: function (value) {
  14176. var keyboard = this.inputs.attached["keyboard"];
  14177. if (keyboard)
  14178. keyboard.keysLeft = value;
  14179. },
  14180. enumerable: true,
  14181. configurable: true
  14182. });
  14183. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  14184. get: function () {
  14185. var keyboard = this.inputs.attached["keyboard"];
  14186. if (keyboard)
  14187. return keyboard.keysRight;
  14188. },
  14189. set: function (value) {
  14190. var keyboard = this.inputs.attached["keyboard"];
  14191. if (keyboard)
  14192. keyboard.keysRight = value;
  14193. },
  14194. enumerable: true,
  14195. configurable: true
  14196. });
  14197. // Controls
  14198. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  14199. this.inputs.attachElement(element, noPreventDefault);
  14200. };
  14201. FreeCamera.prototype.detachControl = function (element) {
  14202. this.inputs.detachElement(element);
  14203. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  14204. this.cameraRotation = new BABYLON.Vector2(0, 0);
  14205. };
  14206. FreeCamera.prototype._collideWithWorld = function (velocity) {
  14207. var globalPosition;
  14208. if (this.parent) {
  14209. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  14210. }
  14211. else {
  14212. globalPosition = this.position;
  14213. }
  14214. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  14215. this._collider.radius = this.ellipsoid;
  14216. //no need for clone, as long as gravity is not on.
  14217. var actualVelocity = velocity;
  14218. //add gravity to the velocity to prevent the dual-collision checking
  14219. if (this.applyGravity) {
  14220. //this prevents mending with cameraDirection, a global variable of the free camera class.
  14221. actualVelocity = velocity.add(this.getScene().gravity);
  14222. }
  14223. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  14224. };
  14225. FreeCamera.prototype._checkInputs = function () {
  14226. if (!this._localDirection) {
  14227. this._localDirection = BABYLON.Vector3.Zero();
  14228. this._transformedDirection = BABYLON.Vector3.Zero();
  14229. }
  14230. this.inputs.checkInputs();
  14231. _super.prototype._checkInputs.call(this);
  14232. };
  14233. FreeCamera.prototype._decideIfNeedsToMove = function () {
  14234. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  14235. };
  14236. FreeCamera.prototype._updatePosition = function () {
  14237. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  14238. this._collideWithWorld(this.cameraDirection);
  14239. }
  14240. else {
  14241. this.position.addInPlace(this.cameraDirection);
  14242. }
  14243. };
  14244. FreeCamera.prototype.dispose = function () {
  14245. this.inputs.clear();
  14246. _super.prototype.dispose.call(this);
  14247. };
  14248. FreeCamera.prototype.getTypeName = function () {
  14249. return "FreeCamera";
  14250. };
  14251. __decorate([
  14252. BABYLON.serializeAsVector3()
  14253. ], FreeCamera.prototype, "ellipsoid", void 0);
  14254. __decorate([
  14255. BABYLON.serialize()
  14256. ], FreeCamera.prototype, "checkCollisions", void 0);
  14257. __decorate([
  14258. BABYLON.serialize()
  14259. ], FreeCamera.prototype, "applyGravity", void 0);
  14260. return FreeCamera;
  14261. })(BABYLON.TargetCamera);
  14262. BABYLON.FreeCamera = FreeCamera;
  14263. })(BABYLON || (BABYLON = {}));
  14264. var BABYLON;
  14265. (function (BABYLON) {
  14266. var FreeCameraInputsManager = (function (_super) {
  14267. __extends(FreeCameraInputsManager, _super);
  14268. function FreeCameraInputsManager(camera) {
  14269. _super.call(this, camera);
  14270. }
  14271. FreeCameraInputsManager.prototype.addKeyboard = function () {
  14272. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  14273. return this;
  14274. };
  14275. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  14276. if (touchEnabled === void 0) { touchEnabled = true; }
  14277. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  14278. return this;
  14279. };
  14280. FreeCameraInputsManager.prototype.addGamepad = function () {
  14281. this.add(new BABYLON.FreeCameraGamepadInput());
  14282. return this;
  14283. };
  14284. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  14285. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  14286. return this;
  14287. };
  14288. FreeCameraInputsManager.prototype.addTouch = function () {
  14289. this.add(new BABYLON.FreeCameraTouchInput());
  14290. return this;
  14291. };
  14292. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  14293. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  14294. return this;
  14295. };
  14296. return FreeCameraInputsManager;
  14297. })(BABYLON.CameraInputsManager);
  14298. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  14299. })(BABYLON || (BABYLON = {}));
  14300. var BABYLON;
  14301. (function (BABYLON) {
  14302. var FollowCamera = (function (_super) {
  14303. __extends(FollowCamera, _super);
  14304. function FollowCamera(name, position, scene, target) {
  14305. _super.call(this, name, position, scene);
  14306. this.radius = 12;
  14307. this.rotationOffset = 0;
  14308. this.heightOffset = 4;
  14309. this.cameraAcceleration = 0.05;
  14310. this.maxCameraSpeed = 20;
  14311. this.target = target;
  14312. }
  14313. FollowCamera.prototype.getRadians = function (degrees) {
  14314. return degrees * Math.PI / 180;
  14315. };
  14316. FollowCamera.prototype.follow = function (cameraTarget) {
  14317. if (!cameraTarget)
  14318. return;
  14319. var yRotation;
  14320. if (cameraTarget.rotationQuaternion) {
  14321. var rotMatrix = new BABYLON.Matrix();
  14322. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  14323. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  14324. }
  14325. else {
  14326. yRotation = cameraTarget.rotation.y;
  14327. }
  14328. var radians = this.getRadians(this.rotationOffset) + yRotation;
  14329. var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
  14330. var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
  14331. var dx = targetX - this.position.x;
  14332. var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
  14333. var dz = (targetZ) - this.position.z;
  14334. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  14335. var vy = dy * this.cameraAcceleration;
  14336. var vz = dz * this.cameraAcceleration * 2;
  14337. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  14338. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  14339. }
  14340. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  14341. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  14342. }
  14343. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  14344. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  14345. }
  14346. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  14347. this.setTarget(cameraTarget.position);
  14348. };
  14349. FollowCamera.prototype._checkInputs = function () {
  14350. _super.prototype._checkInputs.call(this);
  14351. this.follow(this.target);
  14352. };
  14353. FollowCamera.prototype.getTypeName = function () {
  14354. return "FollowCamera";
  14355. };
  14356. __decorate([
  14357. BABYLON.serialize()
  14358. ], FollowCamera.prototype, "radius", void 0);
  14359. __decorate([
  14360. BABYLON.serialize()
  14361. ], FollowCamera.prototype, "rotationOffset", void 0);
  14362. __decorate([
  14363. BABYLON.serialize()
  14364. ], FollowCamera.prototype, "heightOffset", void 0);
  14365. __decorate([
  14366. BABYLON.serialize()
  14367. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  14368. __decorate([
  14369. BABYLON.serialize()
  14370. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  14371. __decorate([
  14372. BABYLON.serializeAsMeshReference("lockedTargetId")
  14373. ], FollowCamera.prototype, "target", void 0);
  14374. return FollowCamera;
  14375. })(BABYLON.TargetCamera);
  14376. BABYLON.FollowCamera = FollowCamera;
  14377. var ArcFollowCamera = (function (_super) {
  14378. __extends(ArcFollowCamera, _super);
  14379. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  14380. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  14381. this.alpha = alpha;
  14382. this.beta = beta;
  14383. this.radius = radius;
  14384. this.target = target;
  14385. this._cartesianCoordinates = BABYLON.Vector3.Zero();
  14386. this.follow();
  14387. }
  14388. ArcFollowCamera.prototype.follow = function () {
  14389. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  14390. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  14391. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  14392. this.position = this.target.position.add(this._cartesianCoordinates);
  14393. this.setTarget(this.target.position);
  14394. };
  14395. ArcFollowCamera.prototype._checkInputs = function () {
  14396. _super.prototype._checkInputs.call(this);
  14397. this.follow();
  14398. };
  14399. ArcFollowCamera.prototype.getTypeName = function () {
  14400. return "ArcFollowCamera";
  14401. };
  14402. return ArcFollowCamera;
  14403. })(BABYLON.TargetCamera);
  14404. BABYLON.ArcFollowCamera = ArcFollowCamera;
  14405. })(BABYLON || (BABYLON = {}));
  14406. var BABYLON;
  14407. (function (BABYLON) {
  14408. // We're mainly based on the logic defined into the FreeCamera code
  14409. var TouchCamera = (function (_super) {
  14410. __extends(TouchCamera, _super);
  14411. //-- end properties for backward compatibility for inputs
  14412. function TouchCamera(name, position, scene) {
  14413. _super.call(this, name, position, scene);
  14414. this.inputs.addTouch();
  14415. this._setupInputs();
  14416. }
  14417. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  14418. //-- Begin properties for backward compatibility for inputs
  14419. get: function () {
  14420. var touch = this.inputs.attached["touch"];
  14421. if (touch)
  14422. return touch.touchAngularSensibility;
  14423. },
  14424. set: function (value) {
  14425. var touch = this.inputs.attached["touch"];
  14426. if (touch)
  14427. touch.touchAngularSensibility = value;
  14428. },
  14429. enumerable: true,
  14430. configurable: true
  14431. });
  14432. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  14433. get: function () {
  14434. var touch = this.inputs.attached["touch"];
  14435. if (touch)
  14436. return touch.touchMoveSensibility;
  14437. },
  14438. set: function (value) {
  14439. var touch = this.inputs.attached["touch"];
  14440. if (touch)
  14441. touch.touchMoveSensibility = value;
  14442. },
  14443. enumerable: true,
  14444. configurable: true
  14445. });
  14446. TouchCamera.prototype.getTypeName = function () {
  14447. return "TouchCamera";
  14448. };
  14449. TouchCamera.prototype._setupInputs = function () {
  14450. var mouse = this.inputs.attached["mouse"];
  14451. if (mouse) {
  14452. mouse.touchEnabled = false;
  14453. }
  14454. };
  14455. return TouchCamera;
  14456. })(BABYLON.FreeCamera);
  14457. BABYLON.TouchCamera = TouchCamera;
  14458. })(BABYLON || (BABYLON = {}));
  14459. var BABYLON;
  14460. (function (BABYLON) {
  14461. var ArcRotateCamera = (function (_super) {
  14462. __extends(ArcRotateCamera, _super);
  14463. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  14464. var _this = this;
  14465. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  14466. this.inertialAlphaOffset = 0;
  14467. this.inertialBetaOffset = 0;
  14468. this.inertialRadiusOffset = 0;
  14469. this.lowerAlphaLimit = null;
  14470. this.upperAlphaLimit = null;
  14471. this.lowerBetaLimit = 0.01;
  14472. this.upperBetaLimit = Math.PI;
  14473. this.lowerRadiusLimit = null;
  14474. this.upperRadiusLimit = null;
  14475. this.inertialPanningX = 0;
  14476. this.inertialPanningY = 0;
  14477. //-- end properties for backward compatibility for inputs
  14478. this.zoomOnFactor = 1;
  14479. this.targetScreenOffset = BABYLON.Vector2.Zero();
  14480. this.allowUpsideDown = true;
  14481. this._viewMatrix = new BABYLON.Matrix();
  14482. // Panning
  14483. this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  14484. this.checkCollisions = false;
  14485. this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  14486. this._collider = new BABYLON.Collider();
  14487. this._previousPosition = BABYLON.Vector3.Zero();
  14488. this._collisionVelocity = BABYLON.Vector3.Zero();
  14489. this._newPosition = BABYLON.Vector3.Zero();
  14490. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  14491. if (collidedMesh === void 0) { collidedMesh = null; }
  14492. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  14493. newPosition.multiplyInPlace(_this._collider.radius);
  14494. }
  14495. if (!collidedMesh) {
  14496. _this._previousPosition.copyFrom(_this.position);
  14497. }
  14498. else {
  14499. _this.setPosition(newPosition);
  14500. if (_this.onCollide) {
  14501. _this.onCollide(collidedMesh);
  14502. }
  14503. }
  14504. // Recompute because of constraints
  14505. var cosa = Math.cos(_this.alpha);
  14506. var sina = Math.sin(_this.alpha);
  14507. var cosb = Math.cos(_this.beta);
  14508. var sinb = Math.sin(_this.beta);
  14509. if (sinb === 0) {
  14510. sinb = 0.0001;
  14511. }
  14512. var target = _this._getTargetPosition();
  14513. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  14514. _this.position.copyFrom(_this._newPosition);
  14515. var up = _this.upVector;
  14516. if (_this.allowUpsideDown && _this.beta < 0) {
  14517. up = up.clone();
  14518. up = up.negate();
  14519. }
  14520. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  14521. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  14522. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  14523. _this._collisionTriggered = false;
  14524. };
  14525. if (!target) {
  14526. this.target = BABYLON.Vector3.Zero();
  14527. }
  14528. else {
  14529. this.target = target;
  14530. }
  14531. this.alpha = alpha;
  14532. this.beta = beta;
  14533. this.radius = radius;
  14534. this.getViewMatrix();
  14535. this.inputs = new BABYLON.ArcRotateCameraInputsManager(this);
  14536. this.inputs.addKeyboard().addMouseWheel().addPointers().addGamepad();
  14537. }
  14538. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  14539. //-- begin properties for backward compatibility for inputs
  14540. get: function () {
  14541. var pointers = this.inputs.attached["pointers"];
  14542. if (pointers)
  14543. return pointers.angularSensibilityX;
  14544. },
  14545. set: function (value) {
  14546. var pointers = this.inputs.attached["pointers"];
  14547. if (pointers) {
  14548. pointers.angularSensibilityX = value;
  14549. }
  14550. },
  14551. enumerable: true,
  14552. configurable: true
  14553. });
  14554. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  14555. get: function () {
  14556. var pointers = this.inputs.attached["pointers"];
  14557. if (pointers)
  14558. return pointers.angularSensibilityY;
  14559. },
  14560. set: function (value) {
  14561. var pointers = this.inputs.attached["pointers"];
  14562. if (pointers) {
  14563. pointers.angularSensibilityY = value;
  14564. }
  14565. },
  14566. enumerable: true,
  14567. configurable: true
  14568. });
  14569. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  14570. get: function () {
  14571. var pointers = this.inputs.attached["pointers"];
  14572. if (pointers)
  14573. return pointers.pinchPrecision;
  14574. },
  14575. set: function (value) {
  14576. var pointers = this.inputs.attached["pointers"];
  14577. if (pointers) {
  14578. pointers.pinchPrecision = value;
  14579. }
  14580. },
  14581. enumerable: true,
  14582. configurable: true
  14583. });
  14584. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  14585. get: function () {
  14586. var pointers = this.inputs.attached["pointers"];
  14587. if (pointers)
  14588. return pointers.panningSensibility;
  14589. },
  14590. set: function (value) {
  14591. var pointers = this.inputs.attached["pointers"];
  14592. if (pointers) {
  14593. pointers.panningSensibility = value;
  14594. }
  14595. },
  14596. enumerable: true,
  14597. configurable: true
  14598. });
  14599. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  14600. get: function () {
  14601. var keyboard = this.inputs.attached["keyboard"];
  14602. if (keyboard)
  14603. return keyboard.keysUp;
  14604. },
  14605. set: function (value) {
  14606. var keyboard = this.inputs.attached["keyboard"];
  14607. if (keyboard)
  14608. keyboard.keysUp = value;
  14609. },
  14610. enumerable: true,
  14611. configurable: true
  14612. });
  14613. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  14614. get: function () {
  14615. var keyboard = this.inputs.attached["keyboard"];
  14616. if (keyboard)
  14617. return keyboard.keysDown;
  14618. },
  14619. set: function (value) {
  14620. var keyboard = this.inputs.attached["keyboard"];
  14621. if (keyboard)
  14622. keyboard.keysDown = value;
  14623. },
  14624. enumerable: true,
  14625. configurable: true
  14626. });
  14627. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  14628. get: function () {
  14629. var keyboard = this.inputs.attached["keyboard"];
  14630. if (keyboard)
  14631. return keyboard.keysLeft;
  14632. },
  14633. set: function (value) {
  14634. var keyboard = this.inputs.attached["keyboard"];
  14635. if (keyboard)
  14636. keyboard.keysLeft = value;
  14637. },
  14638. enumerable: true,
  14639. configurable: true
  14640. });
  14641. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  14642. get: function () {
  14643. var keyboard = this.inputs.attached["keyboard"];
  14644. if (keyboard)
  14645. return keyboard.keysRight;
  14646. },
  14647. set: function (value) {
  14648. var keyboard = this.inputs.attached["keyboard"];
  14649. if (keyboard)
  14650. keyboard.keysRight = value;
  14651. },
  14652. enumerable: true,
  14653. configurable: true
  14654. });
  14655. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  14656. get: function () {
  14657. var mousewheel = this.inputs.attached["mousewheel"];
  14658. if (mousewheel)
  14659. return mousewheel.wheelPrecision;
  14660. },
  14661. set: function (value) {
  14662. var mousewheel = this.inputs.attached["mousewheel"];
  14663. if (mousewheel)
  14664. mousewheel.wheelPrecision = value;
  14665. },
  14666. enumerable: true,
  14667. configurable: true
  14668. });
  14669. // Cache
  14670. ArcRotateCamera.prototype._initCache = function () {
  14671. _super.prototype._initCache.call(this);
  14672. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  14673. this._cache.alpha = undefined;
  14674. this._cache.beta = undefined;
  14675. this._cache.radius = undefined;
  14676. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  14677. };
  14678. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  14679. if (!ignoreParentClass) {
  14680. _super.prototype._updateCache.call(this);
  14681. }
  14682. this._cache.target.copyFrom(this._getTargetPosition());
  14683. this._cache.alpha = this.alpha;
  14684. this._cache.beta = this.beta;
  14685. this._cache.radius = this.radius;
  14686. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  14687. };
  14688. ArcRotateCamera.prototype._getTargetPosition = function () {
  14689. if (this.target.getAbsolutePosition) {
  14690. return this.target.getAbsolutePosition();
  14691. }
  14692. return this.target;
  14693. };
  14694. // Synchronized
  14695. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  14696. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  14697. return false;
  14698. return this._cache.target.equals(this.target)
  14699. && this._cache.alpha === this.alpha
  14700. && this._cache.beta === this.beta
  14701. && this._cache.radius === this.radius
  14702. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  14703. };
  14704. // Methods
  14705. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  14706. var _this = this;
  14707. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  14708. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  14709. this._useCtrlForPanning = useCtrlForPanning;
  14710. this._panningMouseButton = panningMouseButton;
  14711. this.inputs.attachElement(element, noPreventDefault);
  14712. this._reset = function () {
  14713. _this.inertialAlphaOffset = 0;
  14714. _this.inertialBetaOffset = 0;
  14715. _this.inertialRadiusOffset = 0;
  14716. };
  14717. };
  14718. ArcRotateCamera.prototype.detachControl = function (element) {
  14719. this.inputs.detachElement(element);
  14720. if (this._reset) {
  14721. this._reset();
  14722. }
  14723. };
  14724. ArcRotateCamera.prototype._checkInputs = function () {
  14725. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  14726. if (this._collisionTriggered) {
  14727. return;
  14728. }
  14729. this.inputs.checkInputs();
  14730. // Inertia
  14731. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  14732. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  14733. this.beta += this.inertialBetaOffset;
  14734. this.radius -= this.inertialRadiusOffset;
  14735. this.inertialAlphaOffset *= this.inertia;
  14736. this.inertialBetaOffset *= this.inertia;
  14737. this.inertialRadiusOffset *= this.inertia;
  14738. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  14739. this.inertialAlphaOffset = 0;
  14740. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  14741. this.inertialBetaOffset = 0;
  14742. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Epsilon)
  14743. this.inertialRadiusOffset = 0;
  14744. }
  14745. // Panning inertia
  14746. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  14747. if (!this._localDirection) {
  14748. this._localDirection = BABYLON.Vector3.Zero();
  14749. this._transformedDirection = BABYLON.Vector3.Zero();
  14750. }
  14751. this.inertialPanningX *= this.inertia;
  14752. this.inertialPanningY *= this.inertia;
  14753. if (Math.abs(this.inertialPanningX) < BABYLON.Epsilon)
  14754. this.inertialPanningX = 0;
  14755. if (Math.abs(this.inertialPanningY) < BABYLON.Epsilon)
  14756. this.inertialPanningY = 0;
  14757. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  14758. this._localDirection.multiplyInPlace(this.panningAxis);
  14759. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  14760. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  14761. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  14762. if (!this.panningAxis.y) {
  14763. this._transformedDirection.y = 0;
  14764. }
  14765. if (!this.target.getAbsolutePosition) {
  14766. this.target.addInPlace(this._transformedDirection);
  14767. }
  14768. }
  14769. // Limits
  14770. this._checkLimits();
  14771. _super.prototype._checkInputs.call(this);
  14772. };
  14773. ArcRotateCamera.prototype._checkLimits = function () {
  14774. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  14775. if (this.allowUpsideDown && this.beta > Math.PI) {
  14776. this.beta = this.beta - (2 * Math.PI);
  14777. }
  14778. }
  14779. else {
  14780. if (this.beta < this.lowerBetaLimit) {
  14781. this.beta = this.lowerBetaLimit;
  14782. }
  14783. }
  14784. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  14785. if (this.allowUpsideDown && this.beta < -Math.PI) {
  14786. this.beta = this.beta + (2 * Math.PI);
  14787. }
  14788. }
  14789. else {
  14790. if (this.beta > this.upperBetaLimit) {
  14791. this.beta = this.upperBetaLimit;
  14792. }
  14793. }
  14794. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  14795. this.alpha = this.lowerAlphaLimit;
  14796. }
  14797. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  14798. this.alpha = this.upperAlphaLimit;
  14799. }
  14800. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  14801. this.radius = this.lowerRadiusLimit;
  14802. }
  14803. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  14804. this.radius = this.upperRadiusLimit;
  14805. }
  14806. };
  14807. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  14808. var radiusv3 = this.position.subtract(this._getTargetPosition());
  14809. this.radius = radiusv3.length();
  14810. // Alpha
  14811. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  14812. if (radiusv3.z < 0) {
  14813. this.alpha = 2 * Math.PI - this.alpha;
  14814. }
  14815. // Beta
  14816. this.beta = Math.acos(radiusv3.y / this.radius);
  14817. this._checkLimits();
  14818. };
  14819. ArcRotateCamera.prototype.setPosition = function (position) {
  14820. if (this.position.equals(position)) {
  14821. return;
  14822. }
  14823. this.position.copyFrom(position);
  14824. this.rebuildAnglesAndRadius();
  14825. };
  14826. ArcRotateCamera.prototype.setTarget = function (target) {
  14827. if (this._getTargetPosition().equals(target)) {
  14828. return;
  14829. }
  14830. this.target = target;
  14831. this.rebuildAnglesAndRadius();
  14832. };
  14833. ArcRotateCamera.prototype._getViewMatrix = function () {
  14834. // Compute
  14835. var cosa = Math.cos(this.alpha);
  14836. var sina = Math.sin(this.alpha);
  14837. var cosb = Math.cos(this.beta);
  14838. var sinb = Math.sin(this.beta);
  14839. if (sinb === 0) {
  14840. sinb = 0.0001;
  14841. }
  14842. var target = this._getTargetPosition();
  14843. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  14844. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  14845. this._collider.radius = this.collisionRadius;
  14846. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  14847. this._collisionTriggered = true;
  14848. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  14849. }
  14850. else {
  14851. this.position.copyFrom(this._newPosition);
  14852. var up = this.upVector;
  14853. if (this.allowUpsideDown && this.beta < 0) {
  14854. up = up.clone();
  14855. up = up.negate();
  14856. }
  14857. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  14858. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  14859. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  14860. }
  14861. return this._viewMatrix;
  14862. };
  14863. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  14864. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  14865. meshes = meshes || this.getScene().meshes;
  14866. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  14867. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  14868. this.radius = distance * this.zoomOnFactor;
  14869. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  14870. };
  14871. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  14872. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  14873. var meshesOrMinMaxVector;
  14874. var distance;
  14875. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  14876. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  14877. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  14878. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  14879. }
  14880. else {
  14881. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  14882. distance = meshesOrMinMaxVectorAndDistance.distance;
  14883. }
  14884. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  14885. if (!doNotUpdateMaxZ) {
  14886. this.maxZ = distance * 2;
  14887. }
  14888. };
  14889. /**
  14890. * @override
  14891. * Override Camera.createRigCamera
  14892. */
  14893. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  14894. var alphaShift;
  14895. switch (this.cameraRigMode) {
  14896. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  14897. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  14898. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  14899. case BABYLON.Camera.RIG_MODE_VR:
  14900. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  14901. break;
  14902. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  14903. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  14904. break;
  14905. }
  14906. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this.target, this.getScene());
  14907. rigCam._cameraRigParams = {};
  14908. return rigCam;
  14909. };
  14910. /**
  14911. * @override
  14912. * Override Camera._updateRigCameras
  14913. */
  14914. ArcRotateCamera.prototype._updateRigCameras = function () {
  14915. var camLeft = this._rigCameras[0];
  14916. var camRight = this._rigCameras[1];
  14917. camLeft.beta = camRight.beta = this.beta;
  14918. camLeft.radius = camRight.radius = this.radius;
  14919. switch (this.cameraRigMode) {
  14920. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  14921. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  14922. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  14923. case BABYLON.Camera.RIG_MODE_VR:
  14924. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  14925. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  14926. break;
  14927. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  14928. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  14929. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  14930. break;
  14931. }
  14932. _super.prototype._updateRigCameras.call(this);
  14933. };
  14934. ArcRotateCamera.prototype.dispose = function () {
  14935. this.inputs.clear();
  14936. _super.prototype.dispose.call(this);
  14937. };
  14938. ArcRotateCamera.prototype.getTypeName = function () {
  14939. return "ArcRotateCamera";
  14940. };
  14941. __decorate([
  14942. BABYLON.serialize()
  14943. ], ArcRotateCamera.prototype, "alpha", void 0);
  14944. __decorate([
  14945. BABYLON.serialize()
  14946. ], ArcRotateCamera.prototype, "beta", void 0);
  14947. __decorate([
  14948. BABYLON.serialize()
  14949. ], ArcRotateCamera.prototype, "radius", void 0);
  14950. __decorate([
  14951. BABYLON.serializeAsVector3()
  14952. ], ArcRotateCamera.prototype, "target", void 0);
  14953. __decorate([
  14954. BABYLON.serialize()
  14955. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  14956. __decorate([
  14957. BABYLON.serialize()
  14958. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  14959. __decorate([
  14960. BABYLON.serialize()
  14961. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  14962. __decorate([
  14963. BABYLON.serialize()
  14964. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  14965. __decorate([
  14966. BABYLON.serialize()
  14967. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  14968. __decorate([
  14969. BABYLON.serialize()
  14970. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  14971. __decorate([
  14972. BABYLON.serialize()
  14973. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  14974. __decorate([
  14975. BABYLON.serialize()
  14976. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  14977. __decorate([
  14978. BABYLON.serialize()
  14979. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  14980. __decorate([
  14981. BABYLON.serialize()
  14982. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  14983. __decorate([
  14984. BABYLON.serialize()
  14985. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  14986. __decorate([
  14987. BABYLON.serialize()
  14988. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  14989. __decorate([
  14990. BABYLON.serialize()
  14991. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  14992. return ArcRotateCamera;
  14993. })(BABYLON.TargetCamera);
  14994. BABYLON.ArcRotateCamera = ArcRotateCamera;
  14995. })(BABYLON || (BABYLON = {}));
  14996. var BABYLON;
  14997. (function (BABYLON) {
  14998. var ArcRotateCameraInputsManager = (function (_super) {
  14999. __extends(ArcRotateCameraInputsManager, _super);
  15000. function ArcRotateCameraInputsManager(camera) {
  15001. _super.call(this, camera);
  15002. }
  15003. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  15004. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  15005. return this;
  15006. };
  15007. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  15008. this.add(new BABYLON.ArcRotateCameraPointersInput());
  15009. return this;
  15010. };
  15011. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  15012. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  15013. return this;
  15014. };
  15015. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  15016. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  15017. return this;
  15018. };
  15019. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  15020. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  15021. return this;
  15022. };
  15023. return ArcRotateCameraInputsManager;
  15024. })(BABYLON.CameraInputsManager);
  15025. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  15026. })(BABYLON || (BABYLON = {}));
  15027. var BABYLON;
  15028. (function (BABYLON) {
  15029. var RenderingManager = (function () {
  15030. function RenderingManager(scene) {
  15031. this._renderingGroups = new Array();
  15032. this._autoClearDepthStencil = {};
  15033. this._customOpaqueSortCompareFn = {};
  15034. this._customAlphaTestSortCompareFn = {};
  15035. this._customTransparentSortCompareFn = {};
  15036. this._scene = scene;
  15037. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  15038. this._autoClearDepthStencil[i] = true;
  15039. }
  15040. }
  15041. RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
  15042. if (this._scene._activeParticleSystems.length === 0) {
  15043. return;
  15044. }
  15045. // Particles
  15046. var activeCamera = this._scene.activeCamera;
  15047. this._scene._particlesDuration.beginMonitoring();
  15048. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  15049. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  15050. if (particleSystem.renderingGroupId !== index) {
  15051. continue;
  15052. }
  15053. if ((activeCamera.layerMask & particleSystem.layerMask) === 0) {
  15054. continue;
  15055. }
  15056. this._clearDepthStencilBuffer();
  15057. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  15058. this._scene._activeParticles.addCount(particleSystem.render(), false);
  15059. }
  15060. }
  15061. this._scene._particlesDuration.endMonitoring(false);
  15062. };
  15063. RenderingManager.prototype._renderSprites = function (index) {
  15064. if (!this._scene.spritesEnabled || this._scene.spriteManagers.length === 0) {
  15065. return;
  15066. }
  15067. // Sprites
  15068. var activeCamera = this._scene.activeCamera;
  15069. this._scene._spritesDuration.beginMonitoring();
  15070. for (var id = 0; id < this._scene.spriteManagers.length; id++) {
  15071. var spriteManager = this._scene.spriteManagers[id];
  15072. if (spriteManager.renderingGroupId === index && ((activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  15073. this._clearDepthStencilBuffer();
  15074. spriteManager.render();
  15075. }
  15076. }
  15077. this._scene._spritesDuration.endMonitoring(false);
  15078. };
  15079. RenderingManager.prototype._clearDepthStencilBuffer = function () {
  15080. if (this._depthStencilBufferAlreadyCleaned) {
  15081. return;
  15082. }
  15083. this._scene.getEngine().clear(0, false, true, true);
  15084. this._depthStencilBufferAlreadyCleaned = true;
  15085. };
  15086. RenderingManager.prototype._renderSpritesAndParticles = function () {
  15087. if (this._currentRenderSprites) {
  15088. this._renderSprites(this._currentIndex);
  15089. }
  15090. if (this._currentRenderParticles) {
  15091. this._renderParticles(this._currentIndex, this._currentActiveMeshes);
  15092. }
  15093. };
  15094. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  15095. this._currentActiveMeshes = activeMeshes;
  15096. this._currentRenderParticles = renderParticles;
  15097. this._currentRenderSprites = renderSprites;
  15098. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  15099. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  15100. var renderingGroup = this._renderingGroups[index];
  15101. var needToStepBack = false;
  15102. this._currentIndex = index;
  15103. if (renderingGroup) {
  15104. if (this._autoClearDepthStencil[index]) {
  15105. this._clearDepthStencilBuffer();
  15106. }
  15107. if (!renderingGroup.onBeforeTransparentRendering) {
  15108. renderingGroup.onBeforeTransparentRendering = this._renderSpritesAndParticles.bind(this);
  15109. }
  15110. if (!renderingGroup.render(customRenderFunction)) {
  15111. this._renderingGroups.splice(index, 1);
  15112. needToStepBack = true;
  15113. this._renderSpritesAndParticles();
  15114. }
  15115. }
  15116. else {
  15117. this._renderSpritesAndParticles();
  15118. }
  15119. if (needToStepBack) {
  15120. index--;
  15121. }
  15122. }
  15123. };
  15124. RenderingManager.prototype.reset = function () {
  15125. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  15126. var renderingGroup = this._renderingGroups[index];
  15127. if (renderingGroup) {
  15128. renderingGroup.prepare();
  15129. }
  15130. }
  15131. };
  15132. RenderingManager.prototype.dispatch = function (subMesh) {
  15133. var mesh = subMesh.getMesh();
  15134. var renderingGroupId = mesh.renderingGroupId || 0;
  15135. if (!this._renderingGroups[renderingGroupId]) {
  15136. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  15137. }
  15138. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  15139. };
  15140. /**
  15141. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  15142. * This allowed control for front to back rendering or reversly depending of the special needs.
  15143. *
  15144. * @param renderingGroupId The rendering group id corresponding to its index
  15145. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  15146. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  15147. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  15148. */
  15149. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  15150. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  15151. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  15152. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  15153. if (this._renderingGroups[renderingGroupId]) {
  15154. var group = this._renderingGroups[renderingGroupId];
  15155. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  15156. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  15157. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  15158. }
  15159. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  15160. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  15161. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  15162. };
  15163. /**
  15164. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  15165. *
  15166. * @param renderingGroupId The rendering group id corresponding to its index
  15167. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  15168. */
  15169. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  15170. this._autoClearDepthStencil[renderingGroupId] = autoClearDepthStencil;
  15171. };
  15172. /**
  15173. * The max id used for rendering groups (not included)
  15174. */
  15175. RenderingManager.MAX_RENDERINGGROUPS = 4;
  15176. /**
  15177. * The min id used for rendering groups (included)
  15178. */
  15179. RenderingManager.MIN_RENDERINGGROUPS = 0;
  15180. return RenderingManager;
  15181. })();
  15182. BABYLON.RenderingManager = RenderingManager;
  15183. })(BABYLON || (BABYLON = {}));
  15184. var BABYLON;
  15185. (function (BABYLON) {
  15186. var RenderingGroup = (function () {
  15187. /**
  15188. * Creates a new rendering group.
  15189. * @param index The rendering group index
  15190. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  15191. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  15192. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  15193. */
  15194. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  15195. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  15196. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  15197. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  15198. this.index = index;
  15199. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  15200. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  15201. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  15202. this._scene = scene;
  15203. this.opaqueSortCompareFn = opaqueSortCompareFn;
  15204. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  15205. this.transparentSortCompareFn = transparentSortCompareFn;
  15206. }
  15207. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  15208. /**
  15209. * Set the opaque sort comparison function.
  15210. * If null the sub meshes will be render in the order they were created
  15211. */
  15212. set: function (value) {
  15213. this._opaqueSortCompareFn = value;
  15214. if (value) {
  15215. this._renderOpaque = this.renderOpaqueSorted;
  15216. }
  15217. else {
  15218. this._renderOpaque = RenderingGroup.renderUnsorted;
  15219. }
  15220. },
  15221. enumerable: true,
  15222. configurable: true
  15223. });
  15224. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  15225. /**
  15226. * Set the alpha test sort comparison function.
  15227. * If null the sub meshes will be render in the order they were created
  15228. */
  15229. set: function (value) {
  15230. this._alphaTestSortCompareFn = value;
  15231. if (value) {
  15232. this._renderAlphaTest = this.renderAlphaTestSorted;
  15233. }
  15234. else {
  15235. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  15236. }
  15237. },
  15238. enumerable: true,
  15239. configurable: true
  15240. });
  15241. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  15242. /**
  15243. * Set the transparent sort comparison function.
  15244. * If null the sub meshes will be render in the order they were created
  15245. */
  15246. set: function (value) {
  15247. if (value) {
  15248. this._transparentSortCompareFn = value;
  15249. }
  15250. else {
  15251. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  15252. }
  15253. this._renderTransparent = this.renderTransparentSorted;
  15254. },
  15255. enumerable: true,
  15256. configurable: true
  15257. });
  15258. /**
  15259. * Render all the sub meshes contained in the group.
  15260. * @param customRenderFunction Used to override the default render behaviour of the group.
  15261. * @returns true if rendered some submeshes.
  15262. */
  15263. RenderingGroup.prototype.render = function (customRenderFunction) {
  15264. if (customRenderFunction) {
  15265. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  15266. return true;
  15267. }
  15268. if (this._opaqueSubMeshes.length === 0 && this._alphaTestSubMeshes.length === 0 && this._transparentSubMeshes.length === 0) {
  15269. if (this.onBeforeTransparentRendering) {
  15270. this.onBeforeTransparentRendering();
  15271. }
  15272. return false;
  15273. }
  15274. var engine = this._scene.getEngine();
  15275. // Opaque
  15276. this._renderOpaque(this._opaqueSubMeshes);
  15277. // Alpha test
  15278. engine.setAlphaTesting(true);
  15279. this._renderAlphaTest(this._alphaTestSubMeshes);
  15280. engine.setAlphaTesting(false);
  15281. if (this.onBeforeTransparentRendering) {
  15282. this.onBeforeTransparentRendering();
  15283. }
  15284. // Transparent
  15285. this._renderTransparent(this._transparentSubMeshes);
  15286. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  15287. return true;
  15288. };
  15289. /**
  15290. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  15291. * @param subMeshes The submeshes to render
  15292. */
  15293. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  15294. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera.globalPosition, false);
  15295. };
  15296. /**
  15297. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  15298. * @param subMeshes The submeshes to render
  15299. */
  15300. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  15301. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera.globalPosition, false);
  15302. };
  15303. /**
  15304. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  15305. * @param subMeshes The submeshes to render
  15306. */
  15307. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  15308. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera.globalPosition, true);
  15309. };
  15310. /**
  15311. * Renders the submeshes in a specified order.
  15312. * @param subMeshes The submeshes to sort before render
  15313. * @param sortCompareFn The comparison function use to sort
  15314. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  15315. * @param transparent Specifies to activate blending if true
  15316. */
  15317. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, cameraPosition, transparent) {
  15318. var subIndex = 0;
  15319. var subMesh;
  15320. for (; subIndex < subMeshes.length; subIndex++) {
  15321. subMesh = subMeshes.data[subIndex];
  15322. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  15323. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  15324. }
  15325. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  15326. sortedArray.sort(sortCompareFn);
  15327. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  15328. subMesh = sortedArray[subIndex];
  15329. subMesh.render(transparent);
  15330. }
  15331. };
  15332. /**
  15333. * Renders the submeshes in the order they were dispatched (no sort applied).
  15334. * @param subMeshes The submeshes to render
  15335. */
  15336. RenderingGroup.renderUnsorted = function (subMeshes) {
  15337. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  15338. var submesh = subMeshes.data[subIndex];
  15339. submesh.render(false);
  15340. }
  15341. };
  15342. /**
  15343. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  15344. * are rendered back to front if in the same alpha index.
  15345. *
  15346. * @param a The first submesh
  15347. * @param b The second submesh
  15348. * @returns The result of the comparison
  15349. */
  15350. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  15351. // Alpha index first
  15352. if (a._alphaIndex > b._alphaIndex) {
  15353. return 1;
  15354. }
  15355. if (a._alphaIndex < b._alphaIndex) {
  15356. return -1;
  15357. }
  15358. // Then distance to camera
  15359. return RenderingGroup.backToFrontSortCompare(a, b);
  15360. };
  15361. /**
  15362. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  15363. * are rendered back to front.
  15364. *
  15365. * @param a The first submesh
  15366. * @param b The second submesh
  15367. * @returns The result of the comparison
  15368. */
  15369. RenderingGroup.backToFrontSortCompare = function (a, b) {
  15370. // Then distance to camera
  15371. if (a._distanceToCamera < b._distanceToCamera) {
  15372. return 1;
  15373. }
  15374. if (a._distanceToCamera > b._distanceToCamera) {
  15375. return -1;
  15376. }
  15377. return 0;
  15378. };
  15379. /**
  15380. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  15381. * are rendered front to back (prevent overdraw).
  15382. *
  15383. * @param a The first submesh
  15384. * @param b The second submesh
  15385. * @returns The result of the comparison
  15386. */
  15387. RenderingGroup.frontToBackSortCompare = function (a, b) {
  15388. // Then distance to camera
  15389. if (a._distanceToCamera < b._distanceToCamera) {
  15390. return -1;
  15391. }
  15392. if (a._distanceToCamera > b._distanceToCamera) {
  15393. return 1;
  15394. }
  15395. return 0;
  15396. };
  15397. /**
  15398. * Resets the different lists of submeshes to prepare a new frame.
  15399. */
  15400. RenderingGroup.prototype.prepare = function () {
  15401. this._opaqueSubMeshes.reset();
  15402. this._transparentSubMeshes.reset();
  15403. this._alphaTestSubMeshes.reset();
  15404. };
  15405. /**
  15406. * Inserts the submesh in its correct queue depending on its material.
  15407. * @param subMesh The submesh to dispatch
  15408. */
  15409. RenderingGroup.prototype.dispatch = function (subMesh) {
  15410. var material = subMesh.getMaterial();
  15411. var mesh = subMesh.getMesh();
  15412. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  15413. this._transparentSubMeshes.push(subMesh);
  15414. }
  15415. else if (material.needAlphaTesting()) {
  15416. this._alphaTestSubMeshes.push(subMesh);
  15417. }
  15418. else {
  15419. this._opaqueSubMeshes.push(subMesh); // Opaque
  15420. }
  15421. };
  15422. return RenderingGroup;
  15423. })();
  15424. BABYLON.RenderingGroup = RenderingGroup;
  15425. })(BABYLON || (BABYLON = {}));
  15426. var BABYLON;
  15427. (function (BABYLON) {
  15428. var PointerEventTypes = (function () {
  15429. function PointerEventTypes() {
  15430. }
  15431. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  15432. get: function () {
  15433. return PointerEventTypes._POINTERDOWN;
  15434. },
  15435. enumerable: true,
  15436. configurable: true
  15437. });
  15438. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  15439. get: function () {
  15440. return PointerEventTypes._POINTERUP;
  15441. },
  15442. enumerable: true,
  15443. configurable: true
  15444. });
  15445. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  15446. get: function () {
  15447. return PointerEventTypes._POINTERMOVE;
  15448. },
  15449. enumerable: true,
  15450. configurable: true
  15451. });
  15452. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  15453. get: function () {
  15454. return PointerEventTypes._POINTERWHEEL;
  15455. },
  15456. enumerable: true,
  15457. configurable: true
  15458. });
  15459. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  15460. get: function () {
  15461. return PointerEventTypes._POINTERPICK;
  15462. },
  15463. enumerable: true,
  15464. configurable: true
  15465. });
  15466. PointerEventTypes._POINTERDOWN = 0x01;
  15467. PointerEventTypes._POINTERUP = 0x02;
  15468. PointerEventTypes._POINTERMOVE = 0x04;
  15469. PointerEventTypes._POINTERWHEEL = 0x08;
  15470. PointerEventTypes._POINTERPICK = 0x10;
  15471. return PointerEventTypes;
  15472. })();
  15473. BABYLON.PointerEventTypes = PointerEventTypes;
  15474. var PointerInfoBase = (function () {
  15475. function PointerInfoBase(type, event) {
  15476. this.type = type;
  15477. this.event = event;
  15478. }
  15479. return PointerInfoBase;
  15480. })();
  15481. BABYLON.PointerInfoBase = PointerInfoBase;
  15482. /**
  15483. * This class is used to store pointer related info for the onPrePointerObservable event.
  15484. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  15485. */
  15486. var PointerInfoPre = (function (_super) {
  15487. __extends(PointerInfoPre, _super);
  15488. function PointerInfoPre(type, event, localX, localY) {
  15489. _super.call(this, type, event);
  15490. this.skipOnPointerObservable = false;
  15491. this.localPosition = new BABYLON.Vector2(localX, localY);
  15492. }
  15493. return PointerInfoPre;
  15494. })(PointerInfoBase);
  15495. BABYLON.PointerInfoPre = PointerInfoPre;
  15496. /**
  15497. * This type contains all the data related to a pointer event in Babylon.js.
  15498. * 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.
  15499. */
  15500. var PointerInfo = (function (_super) {
  15501. __extends(PointerInfo, _super);
  15502. function PointerInfo(type, event, pickInfo) {
  15503. _super.call(this, type, event);
  15504. this.pickInfo = pickInfo;
  15505. }
  15506. return PointerInfo;
  15507. })(PointerInfoBase);
  15508. BABYLON.PointerInfo = PointerInfo;
  15509. /**
  15510. * Represents a scene to be rendered by the engine.
  15511. * @see http://doc.babylonjs.com/page.php?p=21911
  15512. */
  15513. var Scene = (function () {
  15514. /**
  15515. * @constructor
  15516. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  15517. */
  15518. function Scene(engine) {
  15519. // Members
  15520. this.autoClear = true;
  15521. this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  15522. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  15523. this.forceWireframe = false;
  15524. this.forcePointsCloud = false;
  15525. this.forceShowBoundingBoxes = false;
  15526. this.animationsEnabled = true;
  15527. this.constantlyUpdateMeshUnderPointer = false;
  15528. this.hoverCursor = "pointer";
  15529. // Events
  15530. /**
  15531. * An event triggered when the scene is disposed.
  15532. * @type {BABYLON.Observable}
  15533. */
  15534. this.onDisposeObservable = new BABYLON.Observable();
  15535. /**
  15536. * An event triggered before rendering the scene
  15537. * @type {BABYLON.Observable}
  15538. */
  15539. this.onBeforeRenderObservable = new BABYLON.Observable();
  15540. /**
  15541. * An event triggered after rendering the scene
  15542. * @type {BABYLON.Observable}
  15543. */
  15544. this.onAfterRenderObservable = new BABYLON.Observable();
  15545. /**
  15546. * An event triggered when the scene is ready
  15547. * @type {BABYLON.Observable}
  15548. */
  15549. this.onReadyObservable = new BABYLON.Observable();
  15550. /**
  15551. * An event triggered before rendering a camera
  15552. * @type {BABYLON.Observable}
  15553. */
  15554. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  15555. /**
  15556. * An event triggered after rendering a camera
  15557. * @type {BABYLON.Observable}
  15558. */
  15559. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  15560. /**
  15561. * An event triggered when a camera is created
  15562. * @type {BABYLON.Observable}
  15563. */
  15564. this.onNewCameraAddedObservable = new BABYLON.Observable();
  15565. /**
  15566. * An event triggered when a camera is removed
  15567. * @type {BABYLON.Observable}
  15568. */
  15569. this.onCameraRemovedObservable = new BABYLON.Observable();
  15570. /**
  15571. * An event triggered when a light is created
  15572. * @type {BABYLON.Observable}
  15573. */
  15574. this.onNewLightAddedObservable = new BABYLON.Observable();
  15575. /**
  15576. * An event triggered when a light is removed
  15577. * @type {BABYLON.Observable}
  15578. */
  15579. this.onLightRemovedObservable = new BABYLON.Observable();
  15580. /**
  15581. * An event triggered when a geometry is created
  15582. * @type {BABYLON.Observable}
  15583. */
  15584. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  15585. /**
  15586. * An event triggered when a geometry is removed
  15587. * @type {BABYLON.Observable}
  15588. */
  15589. this.onGeometryRemovedObservable = new BABYLON.Observable();
  15590. /**
  15591. * An event triggered when a mesh is created
  15592. * @type {BABYLON.Observable}
  15593. */
  15594. this.onNewMeshAddedObservable = new BABYLON.Observable();
  15595. /**
  15596. * An event triggered when a mesh is removed
  15597. * @type {BABYLON.Observable}
  15598. */
  15599. this.onMeshRemovedObservable = new BABYLON.Observable();
  15600. // Animations
  15601. this.animations = [];
  15602. /**
  15603. * 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).
  15604. * You have the possibility to skip the 3D Engine process and the call to onPointerObservable by setting PointerInfoBase.skipOnPointerObservable to true
  15605. */
  15606. this.onPrePointerObservable = new BABYLON.Observable();
  15607. /**
  15608. * Observable event triggered each time an input event is received from the rendering canvas
  15609. */
  15610. this.onPointerObservable = new BABYLON.Observable();
  15611. 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
  15612. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  15613. this._startingPointerTime = 0;
  15614. // Fog
  15615. /**
  15616. * is fog enabled on this scene.
  15617. * @type {boolean}
  15618. */
  15619. this.fogEnabled = true;
  15620. this.fogMode = Scene.FOGMODE_NONE;
  15621. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  15622. this.fogDensity = 0.1;
  15623. this.fogStart = 0;
  15624. this.fogEnd = 1000.0;
  15625. // Lights
  15626. /**
  15627. * is shadow enabled on this scene.
  15628. * @type {boolean}
  15629. */
  15630. this.shadowsEnabled = true;
  15631. /**
  15632. * is light enabled on this scene.
  15633. * @type {boolean}
  15634. */
  15635. this.lightsEnabled = true;
  15636. /**
  15637. * All of the lights added to this scene.
  15638. * @see BABYLON.Light
  15639. * @type {BABYLON.Light[]}
  15640. */
  15641. this.lights = new Array();
  15642. // Cameras
  15643. /**
  15644. * All of the cameras added to this scene.
  15645. * @see BABYLON.Camera
  15646. * @type {BABYLON.Camera[]}
  15647. */
  15648. this.cameras = new Array();
  15649. this.activeCameras = new Array();
  15650. // Meshes
  15651. /**
  15652. * All of the (abstract) meshes added to this scene.
  15653. * @see BABYLON.AbstractMesh
  15654. * @type {BABYLON.AbstractMesh[]}
  15655. */
  15656. this.meshes = new Array();
  15657. // Geometries
  15658. this._geometries = new Array();
  15659. this.materials = new Array();
  15660. this.multiMaterials = new Array();
  15661. this.defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  15662. // Textures
  15663. this.texturesEnabled = true;
  15664. this.textures = new Array();
  15665. // Particles
  15666. this.particlesEnabled = true;
  15667. this.particleSystems = new Array();
  15668. // Sprites
  15669. this.spritesEnabled = true;
  15670. this.spriteManagers = new Array();
  15671. // Layers
  15672. this.layers = new Array();
  15673. // Skeletons
  15674. this.skeletonsEnabled = true;
  15675. this.skeletons = new Array();
  15676. // Lens flares
  15677. this.lensFlaresEnabled = true;
  15678. this.lensFlareSystems = new Array();
  15679. // Collisions
  15680. this.collisionsEnabled = true;
  15681. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  15682. // Postprocesses
  15683. this.postProcessesEnabled = true;
  15684. // Customs render targets
  15685. this.renderTargetsEnabled = true;
  15686. this.dumpNextRenderTargets = false;
  15687. this.customRenderTargets = new Array();
  15688. // Imported meshes
  15689. this.importedMeshesFiles = new Array();
  15690. // Probes
  15691. this.probesEnabled = true;
  15692. this.reflectionProbes = new Array();
  15693. this._actionManagers = new Array();
  15694. this._meshesForIntersections = new BABYLON.SmartArray(256);
  15695. // Procedural textures
  15696. this.proceduralTexturesEnabled = true;
  15697. this._proceduralTextures = new Array();
  15698. this.soundTracks = new Array();
  15699. this._audioEnabled = true;
  15700. this._headphone = false;
  15701. // Performance counters
  15702. this._totalMeshesCounter = new BABYLON.PerfCounter();
  15703. this._totalLightsCounter = new BABYLON.PerfCounter();
  15704. this._totalMaterialsCounter = new BABYLON.PerfCounter();
  15705. this._totalTexturesCounter = new BABYLON.PerfCounter();
  15706. this._totalVertices = new BABYLON.PerfCounter();
  15707. this._activeIndices = new BABYLON.PerfCounter();
  15708. this._activeParticles = new BABYLON.PerfCounter();
  15709. this._lastFrameDuration = new BABYLON.PerfCounter();
  15710. this._evaluateActiveMeshesDuration = new BABYLON.PerfCounter();
  15711. this._renderTargetsDuration = new BABYLON.PerfCounter();
  15712. this._particlesDuration = new BABYLON.PerfCounter();
  15713. this._renderDuration = new BABYLON.PerfCounter();
  15714. this._spritesDuration = new BABYLON.PerfCounter();
  15715. this._activeBones = new BABYLON.PerfCounter();
  15716. this._renderId = 0;
  15717. this._executeWhenReadyTimeoutId = -1;
  15718. this._intermediateRendering = false;
  15719. this._toBeDisposed = new BABYLON.SmartArray(256);
  15720. this._pendingData = []; //ANY
  15721. this._activeMeshes = new BABYLON.SmartArray(256);
  15722. this._processedMaterials = new BABYLON.SmartArray(256);
  15723. this._renderTargets = new BABYLON.SmartArray(256);
  15724. this._activeParticleSystems = new BABYLON.SmartArray(256);
  15725. this._activeSkeletons = new BABYLON.SmartArray(32);
  15726. this._softwareSkinnedMeshes = new BABYLON.SmartArray(32);
  15727. this._activeAnimatables = new Array();
  15728. this._transformMatrix = BABYLON.Matrix.Zero();
  15729. this._edgesRenderers = new BABYLON.SmartArray(16);
  15730. this._uniqueIdCounter = 0;
  15731. this._engine = engine;
  15732. engine.scenes.push(this);
  15733. this._renderingManager = new BABYLON.RenderingManager(this);
  15734. this.postProcessManager = new BABYLON.PostProcessManager(this);
  15735. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  15736. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  15737. if (BABYLON.OutlineRenderer) {
  15738. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  15739. }
  15740. this.attachControl();
  15741. if (BABYLON.SoundTrack) {
  15742. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  15743. }
  15744. //simplification queue
  15745. if (BABYLON.SimplificationQueue) {
  15746. this.simplificationQueue = new BABYLON.SimplificationQueue();
  15747. }
  15748. //collision coordinator initialization. For now legacy per default.
  15749. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  15750. }
  15751. Object.defineProperty(Scene, "FOGMODE_NONE", {
  15752. get: function () {
  15753. return Scene._FOGMODE_NONE;
  15754. },
  15755. enumerable: true,
  15756. configurable: true
  15757. });
  15758. Object.defineProperty(Scene, "FOGMODE_EXP", {
  15759. get: function () {
  15760. return Scene._FOGMODE_EXP;
  15761. },
  15762. enumerable: true,
  15763. configurable: true
  15764. });
  15765. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  15766. get: function () {
  15767. return Scene._FOGMODE_EXP2;
  15768. },
  15769. enumerable: true,
  15770. configurable: true
  15771. });
  15772. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  15773. get: function () {
  15774. return Scene._FOGMODE_LINEAR;
  15775. },
  15776. enumerable: true,
  15777. configurable: true
  15778. });
  15779. Object.defineProperty(Scene.prototype, "onDispose", {
  15780. set: function (callback) {
  15781. if (this._onDisposeObserver) {
  15782. this.onDisposeObservable.remove(this._onDisposeObserver);
  15783. }
  15784. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  15785. },
  15786. enumerable: true,
  15787. configurable: true
  15788. });
  15789. Object.defineProperty(Scene.prototype, "beforeRender", {
  15790. set: function (callback) {
  15791. if (this._onBeforeRenderObserver) {
  15792. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  15793. }
  15794. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  15795. },
  15796. enumerable: true,
  15797. configurable: true
  15798. });
  15799. Object.defineProperty(Scene.prototype, "afterRender", {
  15800. set: function (callback) {
  15801. if (this._onAfterRenderObserver) {
  15802. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  15803. }
  15804. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  15805. },
  15806. enumerable: true,
  15807. configurable: true
  15808. });
  15809. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  15810. set: function (callback) {
  15811. if (this._onBeforeCameraRenderObserver) {
  15812. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  15813. }
  15814. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  15815. },
  15816. enumerable: true,
  15817. configurable: true
  15818. });
  15819. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  15820. set: function (callback) {
  15821. if (this._onAfterCameraRenderObserver) {
  15822. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  15823. }
  15824. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  15825. },
  15826. enumerable: true,
  15827. configurable: true
  15828. });
  15829. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  15830. get: function () {
  15831. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  15832. },
  15833. enumerable: true,
  15834. configurable: true
  15835. });
  15836. Object.defineProperty(Scene.prototype, "debugLayer", {
  15837. // Properties
  15838. get: function () {
  15839. if (!this._debugLayer) {
  15840. this._debugLayer = new BABYLON.DebugLayer(this);
  15841. }
  15842. return this._debugLayer;
  15843. },
  15844. enumerable: true,
  15845. configurable: true
  15846. });
  15847. Object.defineProperty(Scene.prototype, "workerCollisions", {
  15848. get: function () {
  15849. return this._workerCollisions;
  15850. },
  15851. set: function (enabled) {
  15852. enabled = (enabled && !!Worker);
  15853. this._workerCollisions = enabled;
  15854. if (this.collisionCoordinator) {
  15855. this.collisionCoordinator.destroy();
  15856. }
  15857. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  15858. this.collisionCoordinator.init(this);
  15859. },
  15860. enumerable: true,
  15861. configurable: true
  15862. });
  15863. Object.defineProperty(Scene.prototype, "SelectionOctree", {
  15864. get: function () {
  15865. return this._selectionOctree;
  15866. },
  15867. enumerable: true,
  15868. configurable: true
  15869. });
  15870. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  15871. /**
  15872. * The mesh that is currently under the pointer.
  15873. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  15874. */
  15875. get: function () {
  15876. return this._pointerOverMesh;
  15877. },
  15878. enumerable: true,
  15879. configurable: true
  15880. });
  15881. Object.defineProperty(Scene.prototype, "pointerX", {
  15882. /**
  15883. * Current on-screen X position of the pointer
  15884. * @return {number} X position of the pointer
  15885. */
  15886. get: function () {
  15887. return this._pointerX;
  15888. },
  15889. enumerable: true,
  15890. configurable: true
  15891. });
  15892. Object.defineProperty(Scene.prototype, "pointerY", {
  15893. /**
  15894. * Current on-screen Y position of the pointer
  15895. * @return {number} Y position of the pointer
  15896. */
  15897. get: function () {
  15898. return this._pointerY;
  15899. },
  15900. enumerable: true,
  15901. configurable: true
  15902. });
  15903. Scene.prototype.getCachedMaterial = function () {
  15904. return this._cachedMaterial;
  15905. };
  15906. Scene.prototype.getBoundingBoxRenderer = function () {
  15907. return this._boundingBoxRenderer;
  15908. };
  15909. Scene.prototype.getOutlineRenderer = function () {
  15910. return this._outlineRenderer;
  15911. };
  15912. Scene.prototype.getEngine = function () {
  15913. return this._engine;
  15914. };
  15915. Scene.prototype.getTotalVertices = function () {
  15916. return this._totalVertices.current;
  15917. };
  15918. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  15919. get: function () {
  15920. return this._totalVertices;
  15921. },
  15922. enumerable: true,
  15923. configurable: true
  15924. });
  15925. Scene.prototype.getActiveIndices = function () {
  15926. return this._activeIndices.current;
  15927. };
  15928. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  15929. get: function () {
  15930. return this._activeIndices;
  15931. },
  15932. enumerable: true,
  15933. configurable: true
  15934. });
  15935. Scene.prototype.getActiveParticles = function () {
  15936. return this._activeParticles.current;
  15937. };
  15938. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  15939. get: function () {
  15940. return this._activeParticles;
  15941. },
  15942. enumerable: true,
  15943. configurable: true
  15944. });
  15945. Scene.prototype.getActiveBones = function () {
  15946. return this._activeBones.current;
  15947. };
  15948. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  15949. get: function () {
  15950. return this._activeBones;
  15951. },
  15952. enumerable: true,
  15953. configurable: true
  15954. });
  15955. // Stats
  15956. Scene.prototype.getLastFrameDuration = function () {
  15957. return this._lastFrameDuration.current;
  15958. };
  15959. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  15960. get: function () {
  15961. return this._lastFrameDuration;
  15962. },
  15963. enumerable: true,
  15964. configurable: true
  15965. });
  15966. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  15967. return this._evaluateActiveMeshesDuration.current;
  15968. };
  15969. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  15970. get: function () {
  15971. return this._evaluateActiveMeshesDuration;
  15972. },
  15973. enumerable: true,
  15974. configurable: true
  15975. });
  15976. Scene.prototype.getActiveMeshes = function () {
  15977. return this._activeMeshes;
  15978. };
  15979. Scene.prototype.getRenderTargetsDuration = function () {
  15980. return this._renderTargetsDuration.current;
  15981. };
  15982. Scene.prototype.getRenderDuration = function () {
  15983. return this._renderDuration.current;
  15984. };
  15985. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  15986. get: function () {
  15987. return this._renderDuration;
  15988. },
  15989. enumerable: true,
  15990. configurable: true
  15991. });
  15992. Scene.prototype.getParticlesDuration = function () {
  15993. return this._particlesDuration.current;
  15994. };
  15995. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  15996. get: function () {
  15997. return this._particlesDuration;
  15998. },
  15999. enumerable: true,
  16000. configurable: true
  16001. });
  16002. Scene.prototype.getSpritesDuration = function () {
  16003. return this._spritesDuration.current;
  16004. };
  16005. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  16006. get: function () {
  16007. return this._spritesDuration;
  16008. },
  16009. enumerable: true,
  16010. configurable: true
  16011. });
  16012. Scene.prototype.getAnimationRatio = function () {
  16013. return this._animationRatio;
  16014. };
  16015. Scene.prototype.getRenderId = function () {
  16016. return this._renderId;
  16017. };
  16018. Scene.prototype.incrementRenderId = function () {
  16019. this._renderId++;
  16020. };
  16021. Scene.prototype._updatePointerPosition = function (evt) {
  16022. var canvasRect = this._engine.getRenderingCanvasClientRect();
  16023. this._pointerX = evt.clientX - canvasRect.left;
  16024. this._pointerY = evt.clientY - canvasRect.top;
  16025. this._unTranslatedPointerX = this._pointerX;
  16026. this._unTranslatedPointerY = this._pointerY;
  16027. if (this.cameraToUseForPointers) {
  16028. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  16029. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  16030. }
  16031. };
  16032. // Pointers handling
  16033. /**
  16034. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  16035. * @param attachUp defines if you want to attach events to pointerup
  16036. * @param attachDown defines if you want to attach events to pointerdown
  16037. * @param attachMove defines if you want to attach events to pointermove
  16038. */
  16039. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  16040. var _this = this;
  16041. if (attachUp === void 0) { attachUp = true; }
  16042. if (attachDown === void 0) { attachDown = true; }
  16043. if (attachMove === void 0) { attachMove = true; }
  16044. var spritePredicate = function (sprite) {
  16045. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  16046. };
  16047. this._onPointerMove = function (evt) {
  16048. _this._updatePointerPosition(evt);
  16049. // PreObservable support
  16050. if (_this.onPrePointerObservable.hasObservers()) {
  16051. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  16052. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  16053. _this.onPrePointerObservable.notifyObservers(pi, type);
  16054. if (pi.skipOnPointerObservable) {
  16055. return;
  16056. }
  16057. }
  16058. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  16059. return;
  16060. }
  16061. var canvas = _this._engine.getRenderingCanvas();
  16062. if (!_this.pointerMovePredicate) {
  16063. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && (_this.constantlyUpdateMeshUnderPointer || mesh.actionManager !== null && mesh.actionManager !== undefined); };
  16064. }
  16065. // Meshes
  16066. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  16067. if (pickResult.hit && pickResult.pickedMesh) {
  16068. _this.setPointerOverSprite(null);
  16069. _this.setPointerOverMesh(pickResult.pickedMesh);
  16070. if (_this._pointerOverMesh.actionManager && _this._pointerOverMesh.actionManager.hasPointerTriggers) {
  16071. canvas.style.cursor = _this.hoverCursor;
  16072. }
  16073. else {
  16074. canvas.style.cursor = "";
  16075. }
  16076. }
  16077. else {
  16078. _this.setPointerOverMesh(null);
  16079. // Sprites
  16080. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  16081. if (pickResult.hit && pickResult.pickedSprite) {
  16082. canvas.style.cursor = _this.hoverCursor;
  16083. _this.setPointerOverSprite(pickResult.pickedSprite);
  16084. }
  16085. else {
  16086. _this.setPointerOverSprite(null);
  16087. // Restore pointer
  16088. canvas.style.cursor = "";
  16089. }
  16090. }
  16091. if (_this.onPointerMove) {
  16092. _this.onPointerMove(evt, pickResult);
  16093. }
  16094. if (_this.onPointerObservable.hasObservers()) {
  16095. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  16096. var pi = new PointerInfo(type, evt, pickResult);
  16097. _this.onPointerObservable.notifyObservers(pi, type);
  16098. }
  16099. };
  16100. this._onPointerDown = function (evt) {
  16101. _this._updatePointerPosition(evt);
  16102. // PreObservable support
  16103. if (_this.onPrePointerObservable.hasObservers()) {
  16104. var type = PointerEventTypes.POINTERDOWN;
  16105. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  16106. _this.onPrePointerObservable.notifyObservers(pi, type);
  16107. if (pi.skipOnPointerObservable) {
  16108. return;
  16109. }
  16110. }
  16111. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  16112. return;
  16113. }
  16114. _this._startingPointerPosition.x = _this._pointerX;
  16115. _this._startingPointerPosition.y = _this._pointerY;
  16116. _this._startingPointerTime = new Date().getTime();
  16117. if (!_this.pointerDownPredicate) {
  16118. _this.pointerDownPredicate = function (mesh) {
  16119. return mesh.isPickable && mesh.isVisible && mesh.isReady() && (!mesh.actionManager || mesh.actionManager.hasPointerTriggers);
  16120. };
  16121. }
  16122. // Meshes
  16123. _this._pickedDownMesh = null;
  16124. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  16125. if (pickResult.hit && pickResult.pickedMesh) {
  16126. if (pickResult.pickedMesh.actionManager) {
  16127. _this._pickedDownMesh = pickResult.pickedMesh;
  16128. if (pickResult.pickedMesh.actionManager.hasPickTriggers) {
  16129. switch (evt.button) {
  16130. case 0:
  16131. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16132. break;
  16133. case 1:
  16134. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16135. break;
  16136. case 2:
  16137. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16138. break;
  16139. }
  16140. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16141. }
  16142. if (pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  16143. var that = _this;
  16144. window.setTimeout(function () {
  16145. 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);
  16146. if (pickResult.hit && pickResult.pickedMesh) {
  16147. if (pickResult.pickedMesh.actionManager) {
  16148. 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)) {
  16149. that._startingPointerTime = 0;
  16150. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16151. }
  16152. }
  16153. }
  16154. }, BABYLON.ActionManager.LongPressDelay);
  16155. }
  16156. }
  16157. }
  16158. if (_this.onPointerDown) {
  16159. _this.onPointerDown(evt, pickResult);
  16160. }
  16161. if (_this.onPointerObservable.hasObservers()) {
  16162. var type = PointerEventTypes.POINTERDOWN;
  16163. var pi = new PointerInfo(type, evt, pickResult);
  16164. _this.onPointerObservable.notifyObservers(pi, type);
  16165. }
  16166. // Sprites
  16167. _this._pickedDownSprite = null;
  16168. if (_this.spriteManagers.length > 0) {
  16169. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  16170. if (pickResult.hit && pickResult.pickedSprite) {
  16171. if (pickResult.pickedSprite.actionManager) {
  16172. _this._pickedDownSprite = pickResult.pickedSprite;
  16173. switch (evt.button) {
  16174. case 0:
  16175. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  16176. break;
  16177. case 1:
  16178. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  16179. break;
  16180. case 2:
  16181. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  16182. break;
  16183. }
  16184. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  16185. }
  16186. }
  16187. }
  16188. };
  16189. this._onPointerUp = function (evt) {
  16190. _this._updatePointerPosition(evt);
  16191. // PreObservable support
  16192. if (_this.onPrePointerObservable.hasObservers()) {
  16193. var type = PointerEventTypes.POINTERUP;
  16194. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  16195. _this.onPrePointerObservable.notifyObservers(pi, type);
  16196. if (pi.skipOnPointerObservable) {
  16197. return;
  16198. }
  16199. }
  16200. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  16201. return;
  16202. }
  16203. if (!_this.pointerUpPredicate) {
  16204. _this.pointerUpPredicate = function (mesh) {
  16205. return mesh.isPickable && mesh.isVisible && mesh.isReady() && (!mesh.actionManager || (mesh.actionManager.hasPickTriggers || mesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)));
  16206. };
  16207. }
  16208. // Meshes
  16209. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerUpPredicate, false, _this.cameraToUseForPointers);
  16210. if (pickResult.hit && pickResult.pickedMesh) {
  16211. if (_this._pickedDownMesh != null && pickResult.pickedMesh == _this._pickedDownMesh) {
  16212. if (_this.onPointerPick) {
  16213. _this.onPointerPick(evt, pickResult);
  16214. }
  16215. if (_this.onPointerObservable.hasObservers()) {
  16216. var type = PointerEventTypes.POINTERPICK;
  16217. var pi = new PointerInfo(type, evt, pickResult);
  16218. _this.onPointerObservable.notifyObservers(pi, type);
  16219. }
  16220. }
  16221. if (pickResult.pickedMesh.actionManager) {
  16222. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16223. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < BABYLON.ActionManager.DragMovementThreshold) {
  16224. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16225. }
  16226. }
  16227. }
  16228. if (_this._pickedDownMesh && _this._pickedDownMesh !== pickResult.pickedMesh) {
  16229. _this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(_this._pickedDownMesh, evt));
  16230. }
  16231. if (_this.onPointerUp) {
  16232. _this.onPointerUp(evt, pickResult);
  16233. }
  16234. if (_this.onPointerObservable.hasObservers()) {
  16235. var type = PointerEventTypes.POINTERUP;
  16236. var pi = new PointerInfo(type, evt, pickResult);
  16237. _this.onPointerObservable.notifyObservers(pi, type);
  16238. }
  16239. _this._startingPointerTime = 0;
  16240. // Sprites
  16241. if (_this.spriteManagers.length > 0) {
  16242. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  16243. if (pickResult.hit && pickResult.pickedSprite) {
  16244. if (pickResult.pickedSprite.actionManager) {
  16245. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  16246. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < BABYLON.ActionManager.DragMovementThreshold) {
  16247. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  16248. }
  16249. }
  16250. }
  16251. if (_this._pickedDownSprite && _this._pickedDownSprite !== pickResult.pickedSprite) {
  16252. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  16253. }
  16254. }
  16255. };
  16256. this._onKeyDown = function (evt) {
  16257. if (_this.actionManager) {
  16258. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  16259. }
  16260. };
  16261. this._onKeyUp = function (evt) {
  16262. if (_this.actionManager) {
  16263. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  16264. }
  16265. };
  16266. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  16267. var canvas = this._engine.getRenderingCanvas();
  16268. if (attachMove) {
  16269. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  16270. // Wheel
  16271. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  16272. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  16273. }
  16274. if (attachDown) {
  16275. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  16276. }
  16277. if (attachUp) {
  16278. canvas.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  16279. }
  16280. canvas.tabIndex = 1;
  16281. canvas.addEventListener("keydown", this._onKeyDown, false);
  16282. canvas.addEventListener("keyup", this._onKeyUp, false);
  16283. };
  16284. Scene.prototype.detachControl = function () {
  16285. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  16286. var canvas = this._engine.getRenderingCanvas();
  16287. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  16288. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  16289. canvas.removeEventListener(eventPrefix + "up", this._onPointerUp);
  16290. // Wheel
  16291. canvas.removeEventListener('mousewheel', this._onPointerMove);
  16292. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  16293. canvas.removeEventListener("keydown", this._onKeyDown);
  16294. canvas.removeEventListener("keyup", this._onKeyUp);
  16295. };
  16296. // Ready
  16297. Scene.prototype.isReady = function () {
  16298. if (this._pendingData.length > 0) {
  16299. return false;
  16300. }
  16301. var index;
  16302. for (index = 0; index < this._geometries.length; index++) {
  16303. var geometry = this._geometries[index];
  16304. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  16305. return false;
  16306. }
  16307. }
  16308. for (index = 0; index < this.meshes.length; index++) {
  16309. var mesh = this.meshes[index];
  16310. if (!mesh.isReady()) {
  16311. return false;
  16312. }
  16313. var mat = mesh.material;
  16314. if (mat) {
  16315. if (!mat.isReady(mesh)) {
  16316. return false;
  16317. }
  16318. }
  16319. }
  16320. return true;
  16321. };
  16322. Scene.prototype.resetCachedMaterial = function () {
  16323. this._cachedMaterial = null;
  16324. };
  16325. Scene.prototype.registerBeforeRender = function (func) {
  16326. this.onBeforeRenderObservable.add(func);
  16327. };
  16328. Scene.prototype.unregisterBeforeRender = function (func) {
  16329. this.onBeforeRenderObservable.removeCallback(func);
  16330. };
  16331. Scene.prototype.registerAfterRender = function (func) {
  16332. this.onAfterRenderObservable.add(func);
  16333. };
  16334. Scene.prototype.unregisterAfterRender = function (func) {
  16335. this.onAfterRenderObservable.removeCallback(func);
  16336. };
  16337. Scene.prototype._addPendingData = function (data) {
  16338. this._pendingData.push(data);
  16339. };
  16340. Scene.prototype._removePendingData = function (data) {
  16341. var index = this._pendingData.indexOf(data);
  16342. if (index !== -1) {
  16343. this._pendingData.splice(index, 1);
  16344. }
  16345. };
  16346. Scene.prototype.getWaitingItemsCount = function () {
  16347. return this._pendingData.length;
  16348. };
  16349. /**
  16350. * Registers a function to be executed when the scene is ready.
  16351. * @param {Function} func - the function to be executed.
  16352. */
  16353. Scene.prototype.executeWhenReady = function (func) {
  16354. var _this = this;
  16355. this.onReadyObservable.add(func);
  16356. if (this._executeWhenReadyTimeoutId !== -1) {
  16357. return;
  16358. }
  16359. this._executeWhenReadyTimeoutId = setTimeout(function () {
  16360. _this._checkIsReady();
  16361. }, 150);
  16362. };
  16363. Scene.prototype._checkIsReady = function () {
  16364. var _this = this;
  16365. if (this.isReady()) {
  16366. this.onReadyObservable.notifyObservers(this);
  16367. this.onReadyObservable.clear();
  16368. this._executeWhenReadyTimeoutId = -1;
  16369. return;
  16370. }
  16371. this._executeWhenReadyTimeoutId = setTimeout(function () {
  16372. _this._checkIsReady();
  16373. }, 150);
  16374. };
  16375. // Animations
  16376. /**
  16377. * Will start the animation sequence of a given target
  16378. * @param target - the target
  16379. * @param {number} from - from which frame should animation start
  16380. * @param {number} to - till which frame should animation run.
  16381. * @param {boolean} [loop] - should the animation loop
  16382. * @param {number} [speedRatio] - the speed in which to run the animation
  16383. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  16384. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  16385. * @return {BABYLON.Animatable} the animatable object created for this animation
  16386. * @see BABYLON.Animatable
  16387. * @see http://doc.babylonjs.com/page.php?p=22081
  16388. */
  16389. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  16390. if (speedRatio === void 0) { speedRatio = 1.0; }
  16391. this.stopAnimation(target);
  16392. if (!animatable) {
  16393. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  16394. }
  16395. // Local animations
  16396. if (target.animations) {
  16397. animatable.appendAnimations(target, target.animations);
  16398. }
  16399. // Children animations
  16400. if (target.getAnimatables) {
  16401. var animatables = target.getAnimatables();
  16402. for (var index = 0; index < animatables.length; index++) {
  16403. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  16404. }
  16405. }
  16406. animatable.reset();
  16407. return animatable;
  16408. };
  16409. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  16410. if (speedRatio === undefined) {
  16411. speedRatio = 1.0;
  16412. }
  16413. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  16414. return animatable;
  16415. };
  16416. Scene.prototype.getAnimatableByTarget = function (target) {
  16417. for (var index = 0; index < this._activeAnimatables.length; index++) {
  16418. if (this._activeAnimatables[index].target === target) {
  16419. return this._activeAnimatables[index];
  16420. }
  16421. }
  16422. return null;
  16423. };
  16424. Object.defineProperty(Scene.prototype, "Animatables", {
  16425. get: function () {
  16426. return this._activeAnimatables;
  16427. },
  16428. enumerable: true,
  16429. configurable: true
  16430. });
  16431. /**
  16432. * Will stop the animation of the given target
  16433. * @param target - the target
  16434. * @see beginAnimation
  16435. */
  16436. Scene.prototype.stopAnimation = function (target) {
  16437. var animatable = this.getAnimatableByTarget(target);
  16438. if (animatable) {
  16439. animatable.stop();
  16440. }
  16441. };
  16442. Scene.prototype._animate = function () {
  16443. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  16444. return;
  16445. }
  16446. if (!this._animationStartDate) {
  16447. if (this._pendingData.length > 0) {
  16448. return;
  16449. }
  16450. this._animationStartDate = BABYLON.Tools.Now;
  16451. }
  16452. // Getting time
  16453. var now = BABYLON.Tools.Now;
  16454. var delay = now - this._animationStartDate;
  16455. for (var index = 0; index < this._activeAnimatables.length; index++) {
  16456. this._activeAnimatables[index]._animate(delay);
  16457. }
  16458. };
  16459. // Matrix
  16460. Scene.prototype.getViewMatrix = function () {
  16461. return this._viewMatrix;
  16462. };
  16463. Scene.prototype.getProjectionMatrix = function () {
  16464. return this._projectionMatrix;
  16465. };
  16466. Scene.prototype.getTransformMatrix = function () {
  16467. return this._transformMatrix;
  16468. };
  16469. Scene.prototype.setTransformMatrix = function (view, projection) {
  16470. this._viewMatrix = view;
  16471. this._projectionMatrix = projection;
  16472. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  16473. // Update frustum
  16474. if (!this._frustumPlanes) {
  16475. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  16476. }
  16477. else {
  16478. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  16479. }
  16480. };
  16481. // Methods
  16482. Scene.prototype.addMesh = function (newMesh) {
  16483. newMesh.uniqueId = this._uniqueIdCounter++;
  16484. var position = this.meshes.push(newMesh);
  16485. //notify the collision coordinator
  16486. this.collisionCoordinator.onMeshAdded(newMesh);
  16487. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  16488. };
  16489. Scene.prototype.removeMesh = function (toRemove) {
  16490. var index = this.meshes.indexOf(toRemove);
  16491. if (index !== -1) {
  16492. // Remove from the scene if mesh found
  16493. this.meshes.splice(index, 1);
  16494. }
  16495. //notify the collision coordinator
  16496. this.collisionCoordinator.onMeshRemoved(toRemove);
  16497. this.onMeshRemovedObservable.notifyObservers(toRemove);
  16498. return index;
  16499. };
  16500. Scene.prototype.removeSkeleton = function (toRemove) {
  16501. var index = this.skeletons.indexOf(toRemove);
  16502. if (index !== -1) {
  16503. // Remove from the scene if mesh found
  16504. this.skeletons.splice(index, 1);
  16505. }
  16506. return index;
  16507. };
  16508. Scene.prototype.removeLight = function (toRemove) {
  16509. var index = this.lights.indexOf(toRemove);
  16510. if (index !== -1) {
  16511. // Remove from the scene if mesh found
  16512. this.lights.splice(index, 1);
  16513. }
  16514. this.onLightRemovedObservable.notifyObservers(toRemove);
  16515. return index;
  16516. };
  16517. Scene.prototype.removeCamera = function (toRemove) {
  16518. var index = this.cameras.indexOf(toRemove);
  16519. if (index !== -1) {
  16520. // Remove from the scene if mesh found
  16521. this.cameras.splice(index, 1);
  16522. }
  16523. // Remove from activeCameras
  16524. var index2 = this.activeCameras.indexOf(toRemove);
  16525. if (index2 !== -1) {
  16526. // Remove from the scene if mesh found
  16527. this.activeCameras.splice(index2, 1);
  16528. }
  16529. // Reset the activeCamera
  16530. if (this.activeCamera === toRemove) {
  16531. if (this.cameras.length > 0) {
  16532. this.activeCamera = this.cameras[0];
  16533. }
  16534. else {
  16535. this.activeCamera = null;
  16536. }
  16537. }
  16538. this.onCameraRemovedObservable.notifyObservers(toRemove);
  16539. return index;
  16540. };
  16541. Scene.prototype.addLight = function (newLight) {
  16542. newLight.uniqueId = this._uniqueIdCounter++;
  16543. var position = this.lights.push(newLight);
  16544. this.onNewLightAddedObservable.notifyObservers(newLight);
  16545. };
  16546. Scene.prototype.addCamera = function (newCamera) {
  16547. newCamera.uniqueId = this._uniqueIdCounter++;
  16548. var position = this.cameras.push(newCamera);
  16549. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  16550. };
  16551. /**
  16552. * Switch active camera
  16553. * @param {Camera} newCamera - new active camera
  16554. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  16555. */
  16556. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  16557. if (attachControl === void 0) { attachControl = true; }
  16558. var canvas = this._engine.getRenderingCanvas();
  16559. this.activeCamera.detachControl(canvas);
  16560. this.activeCamera = newCamera;
  16561. if (attachControl) {
  16562. newCamera.attachControl(canvas);
  16563. }
  16564. };
  16565. /**
  16566. * sets the active camera of the scene using its ID
  16567. * @param {string} id - the camera's ID
  16568. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  16569. * @see activeCamera
  16570. */
  16571. Scene.prototype.setActiveCameraByID = function (id) {
  16572. var camera = this.getCameraByID(id);
  16573. if (camera) {
  16574. this.activeCamera = camera;
  16575. return camera;
  16576. }
  16577. return null;
  16578. };
  16579. /**
  16580. * sets the active camera of the scene using its name
  16581. * @param {string} name - the camera's name
  16582. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  16583. * @see activeCamera
  16584. */
  16585. Scene.prototype.setActiveCameraByName = function (name) {
  16586. var camera = this.getCameraByName(name);
  16587. if (camera) {
  16588. this.activeCamera = camera;
  16589. return camera;
  16590. }
  16591. return null;
  16592. };
  16593. /**
  16594. * get a material using its id
  16595. * @param {string} the material's ID
  16596. * @return {BABYLON.Material|null} the material or null if none found.
  16597. */
  16598. Scene.prototype.getMaterialByID = function (id) {
  16599. for (var index = 0; index < this.materials.length; index++) {
  16600. if (this.materials[index].id === id) {
  16601. return this.materials[index];
  16602. }
  16603. }
  16604. return null;
  16605. };
  16606. /**
  16607. * get a material using its name
  16608. * @param {string} the material's name
  16609. * @return {BABYLON.Material|null} the material or null if none found.
  16610. */
  16611. Scene.prototype.getMaterialByName = function (name) {
  16612. for (var index = 0; index < this.materials.length; index++) {
  16613. if (this.materials[index].name === name) {
  16614. return this.materials[index];
  16615. }
  16616. }
  16617. return null;
  16618. };
  16619. Scene.prototype.getLensFlareSystemByName = function (name) {
  16620. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  16621. if (this.lensFlareSystems[index].name === name) {
  16622. return this.lensFlareSystems[index];
  16623. }
  16624. }
  16625. return null;
  16626. };
  16627. Scene.prototype.getLensFlareSystemByID = function (id) {
  16628. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  16629. if (this.lensFlareSystems[index].id === id) {
  16630. return this.lensFlareSystems[index];
  16631. }
  16632. }
  16633. return null;
  16634. };
  16635. Scene.prototype.getCameraByID = function (id) {
  16636. for (var index = 0; index < this.cameras.length; index++) {
  16637. if (this.cameras[index].id === id) {
  16638. return this.cameras[index];
  16639. }
  16640. }
  16641. return null;
  16642. };
  16643. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  16644. for (var index = 0; index < this.cameras.length; index++) {
  16645. if (this.cameras[index].uniqueId === uniqueId) {
  16646. return this.cameras[index];
  16647. }
  16648. }
  16649. return null;
  16650. };
  16651. /**
  16652. * get a camera using its name
  16653. * @param {string} the camera's name
  16654. * @return {BABYLON.Camera|null} the camera or null if none found.
  16655. */
  16656. Scene.prototype.getCameraByName = function (name) {
  16657. for (var index = 0; index < this.cameras.length; index++) {
  16658. if (this.cameras[index].name === name) {
  16659. return this.cameras[index];
  16660. }
  16661. }
  16662. return null;
  16663. };
  16664. /**
  16665. * get a bone using its id
  16666. * @param {string} the bone's id
  16667. * @return {BABYLON.Bone|null} the bone or null if not found
  16668. */
  16669. Scene.prototype.getBoneByID = function (id) {
  16670. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  16671. var skeleton = this.skeletons[skeletonIndex];
  16672. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  16673. if (skeleton.bones[boneIndex].id === id) {
  16674. return skeleton.bones[boneIndex];
  16675. }
  16676. }
  16677. }
  16678. return null;
  16679. };
  16680. /**
  16681. * get a bone using its id
  16682. * @param {string} the bone's name
  16683. * @return {BABYLON.Bone|null} the bone or null if not found
  16684. */
  16685. Scene.prototype.getBoneByName = function (name) {
  16686. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  16687. var skeleton = this.skeletons[skeletonIndex];
  16688. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  16689. if (skeleton.bones[boneIndex].name === name) {
  16690. return skeleton.bones[boneIndex];
  16691. }
  16692. }
  16693. }
  16694. return null;
  16695. };
  16696. /**
  16697. * get a light node using its name
  16698. * @param {string} the light's name
  16699. * @return {BABYLON.Light|null} the light or null if none found.
  16700. */
  16701. Scene.prototype.getLightByName = function (name) {
  16702. for (var index = 0; index < this.lights.length; index++) {
  16703. if (this.lights[index].name === name) {
  16704. return this.lights[index];
  16705. }
  16706. }
  16707. return null;
  16708. };
  16709. /**
  16710. * get a light node using its ID
  16711. * @param {string} the light's id
  16712. * @return {BABYLON.Light|null} the light or null if none found.
  16713. */
  16714. Scene.prototype.getLightByID = function (id) {
  16715. for (var index = 0; index < this.lights.length; index++) {
  16716. if (this.lights[index].id === id) {
  16717. return this.lights[index];
  16718. }
  16719. }
  16720. return null;
  16721. };
  16722. /**
  16723. * get a light node using its scene-generated unique ID
  16724. * @param {number} the light's unique id
  16725. * @return {BABYLON.Light|null} the light or null if none found.
  16726. */
  16727. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  16728. for (var index = 0; index < this.lights.length; index++) {
  16729. if (this.lights[index].uniqueId === uniqueId) {
  16730. return this.lights[index];
  16731. }
  16732. }
  16733. return null;
  16734. };
  16735. /**
  16736. * get a particle system by id
  16737. * @param id {number} the particle system id
  16738. * @return {BABYLON.ParticleSystem|null} the corresponding system or null if none found.
  16739. */
  16740. Scene.prototype.getParticleSystemByID = function (id) {
  16741. for (var index = 0; index < this.particleSystems.length; index++) {
  16742. if (this.particleSystems[index].id === id) {
  16743. return this.particleSystems[index];
  16744. }
  16745. }
  16746. return null;
  16747. };
  16748. /**
  16749. * get a geometry using its ID
  16750. * @param {string} the geometry's id
  16751. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  16752. */
  16753. Scene.prototype.getGeometryByID = function (id) {
  16754. for (var index = 0; index < this._geometries.length; index++) {
  16755. if (this._geometries[index].id === id) {
  16756. return this._geometries[index];
  16757. }
  16758. }
  16759. return null;
  16760. };
  16761. /**
  16762. * add a new geometry to this scene.
  16763. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  16764. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  16765. * @return {boolean} was the geometry added or not
  16766. */
  16767. Scene.prototype.pushGeometry = function (geometry, force) {
  16768. if (!force && this.getGeometryByID(geometry.id)) {
  16769. return false;
  16770. }
  16771. this._geometries.push(geometry);
  16772. //notify the collision coordinator
  16773. this.collisionCoordinator.onGeometryAdded(geometry);
  16774. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  16775. return true;
  16776. };
  16777. /**
  16778. * Removes an existing geometry
  16779. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  16780. * @return {boolean} was the geometry removed or not
  16781. */
  16782. Scene.prototype.removeGeometry = function (geometry) {
  16783. var index = this._geometries.indexOf(geometry);
  16784. if (index > -1) {
  16785. this._geometries.splice(index, 1);
  16786. //notify the collision coordinator
  16787. this.collisionCoordinator.onGeometryDeleted(geometry);
  16788. this.onGeometryRemovedObservable.notifyObservers(geometry);
  16789. return true;
  16790. }
  16791. return false;
  16792. };
  16793. Scene.prototype.getGeometries = function () {
  16794. return this._geometries;
  16795. };
  16796. /**
  16797. * Get the first added mesh found of a given ID
  16798. * @param {string} id - the id to search for
  16799. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  16800. */
  16801. Scene.prototype.getMeshByID = function (id) {
  16802. for (var index = 0; index < this.meshes.length; index++) {
  16803. if (this.meshes[index].id === id) {
  16804. return this.meshes[index];
  16805. }
  16806. }
  16807. return null;
  16808. };
  16809. Scene.prototype.getMeshesByID = function (id) {
  16810. return this.meshes.filter(function (m) {
  16811. return m.id === id;
  16812. });
  16813. };
  16814. /**
  16815. * Get a mesh with its auto-generated unique id
  16816. * @param {number} uniqueId - the unique id to search for
  16817. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  16818. */
  16819. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  16820. for (var index = 0; index < this.meshes.length; index++) {
  16821. if (this.meshes[index].uniqueId === uniqueId) {
  16822. return this.meshes[index];
  16823. }
  16824. }
  16825. return null;
  16826. };
  16827. /**
  16828. * Get a the last added mesh found of a given ID
  16829. * @param {string} id - the id to search for
  16830. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  16831. */
  16832. Scene.prototype.getLastMeshByID = function (id) {
  16833. for (var index = this.meshes.length - 1; index >= 0; index--) {
  16834. if (this.meshes[index].id === id) {
  16835. return this.meshes[index];
  16836. }
  16837. }
  16838. return null;
  16839. };
  16840. /**
  16841. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  16842. * @param {string} id - the id to search for
  16843. * @return {BABYLON.Node|null} the node found or null if not found at all.
  16844. */
  16845. Scene.prototype.getLastEntryByID = function (id) {
  16846. var index;
  16847. for (index = this.meshes.length - 1; index >= 0; index--) {
  16848. if (this.meshes[index].id === id) {
  16849. return this.meshes[index];
  16850. }
  16851. }
  16852. for (index = this.cameras.length - 1; index >= 0; index--) {
  16853. if (this.cameras[index].id === id) {
  16854. return this.cameras[index];
  16855. }
  16856. }
  16857. for (index = this.lights.length - 1; index >= 0; index--) {
  16858. if (this.lights[index].id === id) {
  16859. return this.lights[index];
  16860. }
  16861. }
  16862. return null;
  16863. };
  16864. Scene.prototype.getNodeByID = function (id) {
  16865. var mesh = this.getMeshByID(id);
  16866. if (mesh) {
  16867. return mesh;
  16868. }
  16869. var light = this.getLightByID(id);
  16870. if (light) {
  16871. return light;
  16872. }
  16873. var camera = this.getCameraByID(id);
  16874. if (camera) {
  16875. return camera;
  16876. }
  16877. var bone = this.getBoneByID(id);
  16878. return bone;
  16879. };
  16880. Scene.prototype.getNodeByName = function (name) {
  16881. var mesh = this.getMeshByName(name);
  16882. if (mesh) {
  16883. return mesh;
  16884. }
  16885. var light = this.getLightByName(name);
  16886. if (light) {
  16887. return light;
  16888. }
  16889. var camera = this.getCameraByName(name);
  16890. if (camera) {
  16891. return camera;
  16892. }
  16893. var bone = this.getBoneByName(name);
  16894. return bone;
  16895. };
  16896. Scene.prototype.getMeshByName = function (name) {
  16897. for (var index = 0; index < this.meshes.length; index++) {
  16898. if (this.meshes[index].name === name) {
  16899. return this.meshes[index];
  16900. }
  16901. }
  16902. return null;
  16903. };
  16904. Scene.prototype.getSoundByName = function (name) {
  16905. var index;
  16906. if (BABYLON.AudioEngine) {
  16907. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  16908. if (this.mainSoundTrack.soundCollection[index].name === name) {
  16909. return this.mainSoundTrack.soundCollection[index];
  16910. }
  16911. }
  16912. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  16913. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  16914. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  16915. return this.soundTracks[sdIndex].soundCollection[index];
  16916. }
  16917. }
  16918. }
  16919. }
  16920. return null;
  16921. };
  16922. Scene.prototype.getLastSkeletonByID = function (id) {
  16923. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  16924. if (this.skeletons[index].id === id) {
  16925. return this.skeletons[index];
  16926. }
  16927. }
  16928. return null;
  16929. };
  16930. Scene.prototype.getSkeletonById = function (id) {
  16931. for (var index = 0; index < this.skeletons.length; index++) {
  16932. if (this.skeletons[index].id === id) {
  16933. return this.skeletons[index];
  16934. }
  16935. }
  16936. return null;
  16937. };
  16938. Scene.prototype.getSkeletonByName = function (name) {
  16939. for (var index = 0; index < this.skeletons.length; index++) {
  16940. if (this.skeletons[index].name === name) {
  16941. return this.skeletons[index];
  16942. }
  16943. }
  16944. return null;
  16945. };
  16946. Scene.prototype.isActiveMesh = function (mesh) {
  16947. return (this._activeMeshes.indexOf(mesh) !== -1);
  16948. };
  16949. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  16950. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  16951. var material = subMesh.getMaterial();
  16952. if (mesh.showSubMeshesBoundingBox) {
  16953. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  16954. }
  16955. if (material) {
  16956. // Render targets
  16957. if (material.getRenderTargetTextures) {
  16958. if (this._processedMaterials.indexOf(material) === -1) {
  16959. this._processedMaterials.push(material);
  16960. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  16961. }
  16962. }
  16963. // Dispatch
  16964. this._activeIndices.addCount(subMesh.indexCount, false);
  16965. this._renderingManager.dispatch(subMesh);
  16966. }
  16967. }
  16968. };
  16969. Scene.prototype._isInIntermediateRendering = function () {
  16970. return this._intermediateRendering;
  16971. };
  16972. Scene.prototype._evaluateActiveMeshes = function () {
  16973. this.activeCamera._activeMeshes.reset();
  16974. this._activeMeshes.reset();
  16975. this._renderingManager.reset();
  16976. this._processedMaterials.reset();
  16977. this._activeParticleSystems.reset();
  16978. this._activeSkeletons.reset();
  16979. this._softwareSkinnedMeshes.reset();
  16980. this._boundingBoxRenderer.reset();
  16981. this._edgesRenderers.reset();
  16982. // Meshes
  16983. var meshes;
  16984. var len;
  16985. if (this._selectionOctree) {
  16986. var selection = this._selectionOctree.select(this._frustumPlanes);
  16987. meshes = selection.data;
  16988. len = selection.length;
  16989. }
  16990. else {
  16991. len = this.meshes.length;
  16992. meshes = this.meshes;
  16993. }
  16994. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  16995. var mesh = meshes[meshIndex];
  16996. if (mesh.isBlocked) {
  16997. continue;
  16998. }
  16999. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  17000. if (!mesh.isReady() || !mesh.isEnabled()) {
  17001. continue;
  17002. }
  17003. mesh.computeWorldMatrix();
  17004. // Intersections
  17005. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  17006. this._meshesForIntersections.pushNoDuplicate(mesh);
  17007. }
  17008. // Switch to current LOD
  17009. var meshLOD = mesh.getLOD(this.activeCamera);
  17010. if (!meshLOD) {
  17011. continue;
  17012. }
  17013. mesh._preActivate();
  17014. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  17015. this._activeMeshes.push(mesh);
  17016. this.activeCamera._activeMeshes.push(mesh);
  17017. mesh._activate(this._renderId);
  17018. this._activeMesh(mesh, meshLOD);
  17019. }
  17020. }
  17021. // Particle systems
  17022. this._particlesDuration.beginMonitoring();
  17023. var beforeParticlesDate = BABYLON.Tools.Now;
  17024. if (this.particlesEnabled) {
  17025. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  17026. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  17027. var particleSystem = this.particleSystems[particleIndex];
  17028. if (!particleSystem.isStarted()) {
  17029. continue;
  17030. }
  17031. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  17032. this._activeParticleSystems.push(particleSystem);
  17033. particleSystem.animate();
  17034. }
  17035. }
  17036. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  17037. }
  17038. this._particlesDuration.endMonitoring(false);
  17039. };
  17040. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  17041. if (mesh.skeleton && this.skeletonsEnabled) {
  17042. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  17043. mesh.skeleton.prepare();
  17044. }
  17045. if (!mesh.computeBonesUsingShaders) {
  17046. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  17047. }
  17048. }
  17049. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  17050. this._boundingBoxRenderer.renderList.push(sourceMesh.getBoundingInfo().boundingBox);
  17051. }
  17052. if (sourceMesh._edgesRenderer) {
  17053. this._edgesRenderers.push(sourceMesh._edgesRenderer);
  17054. }
  17055. if (mesh && mesh.subMeshes) {
  17056. // Submeshes Octrees
  17057. var len;
  17058. var subMeshes;
  17059. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  17060. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  17061. len = intersections.length;
  17062. subMeshes = intersections.data;
  17063. }
  17064. else {
  17065. subMeshes = mesh.subMeshes;
  17066. len = subMeshes.length;
  17067. }
  17068. for (var subIndex = 0; subIndex < len; subIndex++) {
  17069. var subMesh = subMeshes[subIndex];
  17070. this._evaluateSubMesh(subMesh, mesh);
  17071. }
  17072. }
  17073. };
  17074. Scene.prototype.updateTransformMatrix = function (force) {
  17075. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  17076. };
  17077. Scene.prototype._renderForCamera = function (camera) {
  17078. var engine = this._engine;
  17079. var startTime = BABYLON.Tools.Now;
  17080. this.activeCamera = camera;
  17081. if (!this.activeCamera)
  17082. throw new Error("Active camera not set");
  17083. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  17084. // Viewport
  17085. engine.setViewport(this.activeCamera.viewport);
  17086. // Camera
  17087. this.resetCachedMaterial();
  17088. this._renderId++;
  17089. this.updateTransformMatrix();
  17090. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  17091. // Meshes
  17092. this._evaluateActiveMeshesDuration.beginMonitoring();
  17093. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  17094. this._evaluateActiveMeshes();
  17095. this._evaluateActiveMeshesDuration.endMonitoring(false);
  17096. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  17097. // Software skinning
  17098. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  17099. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  17100. mesh.applySkeleton(mesh.skeleton);
  17101. }
  17102. // Render targets
  17103. this._renderTargetsDuration.beginMonitoring();
  17104. var beforeRenderTargetDate = BABYLON.Tools.Now;
  17105. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  17106. this._intermediateRendering = true;
  17107. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  17108. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  17109. var renderTarget = this._renderTargets.data[renderIndex];
  17110. if (renderTarget._shouldRender()) {
  17111. this._renderId++;
  17112. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  17113. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  17114. }
  17115. }
  17116. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  17117. this._intermediateRendering = false;
  17118. this._renderId++;
  17119. engine.restoreDefaultFramebuffer(); // Restore back buffer
  17120. }
  17121. this._renderTargetsDuration.endMonitoring(false);
  17122. // Prepare Frame
  17123. this.postProcessManager._prepareFrame();
  17124. this._renderDuration.beginMonitoring();
  17125. // Backgrounds
  17126. var layerIndex;
  17127. var layer;
  17128. if (this.layers.length) {
  17129. engine.setDepthBuffer(false);
  17130. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  17131. layer = this.layers[layerIndex];
  17132. if (layer.isBackground) {
  17133. layer.render();
  17134. }
  17135. }
  17136. engine.setDepthBuffer(true);
  17137. }
  17138. // Render
  17139. BABYLON.Tools.StartPerformanceCounter("Main render");
  17140. this._renderingManager.render(null, null, true, true);
  17141. BABYLON.Tools.EndPerformanceCounter("Main render");
  17142. // Bounding boxes
  17143. this._boundingBoxRenderer.render();
  17144. // Edges
  17145. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  17146. this._edgesRenderers.data[edgesRendererIndex].render();
  17147. }
  17148. // Lens flares
  17149. if (this.lensFlaresEnabled) {
  17150. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  17151. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  17152. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  17153. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  17154. lensFlareSystem.render();
  17155. }
  17156. }
  17157. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  17158. }
  17159. // Foregrounds
  17160. if (this.layers.length) {
  17161. engine.setDepthBuffer(false);
  17162. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  17163. layer = this.layers[layerIndex];
  17164. if (!layer.isBackground) {
  17165. layer.render();
  17166. }
  17167. }
  17168. engine.setDepthBuffer(true);
  17169. }
  17170. this._renderDuration.endMonitoring(false);
  17171. // Finalize frame
  17172. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  17173. // Update camera
  17174. this.activeCamera._updateFromScene();
  17175. // Reset some special arrays
  17176. this._renderTargets.reset();
  17177. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  17178. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  17179. };
  17180. Scene.prototype._processSubCameras = function (camera) {
  17181. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  17182. this._renderForCamera(camera);
  17183. return;
  17184. }
  17185. // rig cameras
  17186. for (var index = 0; index < camera._rigCameras.length; index++) {
  17187. this._renderForCamera(camera._rigCameras[index]);
  17188. }
  17189. this.activeCamera = camera;
  17190. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  17191. // Update camera
  17192. this.activeCamera._updateFromScene();
  17193. };
  17194. Scene.prototype._checkIntersections = function () {
  17195. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  17196. var sourceMesh = this._meshesForIntersections.data[index];
  17197. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  17198. var action = sourceMesh.actionManager.actions[actionIndex];
  17199. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  17200. var parameters = action.getTriggerParameter();
  17201. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  17202. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  17203. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  17204. if (areIntersecting && currentIntersectionInProgress === -1) {
  17205. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  17206. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  17207. sourceMesh._intersectionsInProgress.push(otherMesh);
  17208. }
  17209. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  17210. sourceMesh._intersectionsInProgress.push(otherMesh);
  17211. }
  17212. }
  17213. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  17214. //They intersected, and now they don't.
  17215. //is this trigger an exit trigger? execute an event.
  17216. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  17217. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  17218. }
  17219. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  17220. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  17221. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  17222. }
  17223. }
  17224. }
  17225. }
  17226. }
  17227. };
  17228. Scene.prototype.render = function () {
  17229. this._lastFrameDuration.beginMonitoring();
  17230. this._particlesDuration.fetchNewFrame();
  17231. this._spritesDuration.fetchNewFrame();
  17232. this._activeParticles.fetchNewFrame();
  17233. this._renderDuration.fetchNewFrame();
  17234. this._renderTargetsDuration.fetchNewFrame();
  17235. this._evaluateActiveMeshesDuration.fetchNewFrame();
  17236. this._totalVertices.fetchNewFrame();
  17237. this._activeIndices.fetchNewFrame();
  17238. this._activeBones.fetchNewFrame();
  17239. this.getEngine().drawCallsPerfCounter.fetchNewFrame();
  17240. this._meshesForIntersections.reset();
  17241. this.resetCachedMaterial();
  17242. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  17243. // Actions
  17244. if (this.actionManager) {
  17245. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  17246. }
  17247. //Simplification Queue
  17248. if (this.simplificationQueue && !this.simplificationQueue.running) {
  17249. this.simplificationQueue.executeNext();
  17250. }
  17251. // Animations
  17252. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  17253. this._animationRatio = deltaTime * (60.0 / 1000.0);
  17254. this._animate();
  17255. // Physics
  17256. if (this._physicsEngine) {
  17257. BABYLON.Tools.StartPerformanceCounter("Physics");
  17258. this._physicsEngine._step(deltaTime / 1000.0);
  17259. BABYLON.Tools.EndPerformanceCounter("Physics");
  17260. }
  17261. // Before render
  17262. this.onBeforeRenderObservable.notifyObservers(this);
  17263. // Customs render targets
  17264. this._renderTargetsDuration.beginMonitoring();
  17265. var beforeRenderTargetDate = BABYLON.Tools.Now;
  17266. var engine = this.getEngine();
  17267. var currentActiveCamera = this.activeCamera;
  17268. if (this.renderTargetsEnabled) {
  17269. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  17270. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  17271. var renderTarget = this.customRenderTargets[customIndex];
  17272. if (renderTarget._shouldRender()) {
  17273. this._renderId++;
  17274. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  17275. if (!this.activeCamera)
  17276. throw new Error("Active camera not set");
  17277. // Viewport
  17278. engine.setViewport(this.activeCamera.viewport);
  17279. // Camera
  17280. this.updateTransformMatrix();
  17281. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  17282. }
  17283. }
  17284. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  17285. this._renderId++;
  17286. }
  17287. if (this.customRenderTargets.length > 0) {
  17288. engine.restoreDefaultFramebuffer();
  17289. }
  17290. this._renderTargetsDuration.endMonitoring();
  17291. this.activeCamera = currentActiveCamera;
  17292. // Procedural textures
  17293. if (this.proceduralTexturesEnabled) {
  17294. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  17295. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  17296. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  17297. if (proceduralTexture._shouldRender()) {
  17298. proceduralTexture.render();
  17299. }
  17300. }
  17301. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  17302. }
  17303. // Clear
  17304. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true, true);
  17305. // Shadows
  17306. if (this.shadowsEnabled) {
  17307. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  17308. var light = this.lights[lightIndex];
  17309. var shadowGenerator = light.getShadowGenerator();
  17310. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  17311. this._renderTargets.push(shadowGenerator.getShadowMap());
  17312. }
  17313. }
  17314. }
  17315. // Depth renderer
  17316. if (this._depthRenderer) {
  17317. this._renderTargets.push(this._depthRenderer.getDepthMap());
  17318. }
  17319. // RenderPipeline
  17320. this.postProcessRenderPipelineManager.update();
  17321. // Multi-cameras?
  17322. if (this.activeCameras.length > 0) {
  17323. var currentRenderId = this._renderId;
  17324. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  17325. this._renderId = currentRenderId;
  17326. if (cameraIndex > 0) {
  17327. this._engine.clear(0, false, true, true);
  17328. }
  17329. this._processSubCameras(this.activeCameras[cameraIndex]);
  17330. }
  17331. }
  17332. else {
  17333. if (!this.activeCamera) {
  17334. throw new Error("No camera defined");
  17335. }
  17336. this._processSubCameras(this.activeCamera);
  17337. }
  17338. // Intersection checks
  17339. this._checkIntersections();
  17340. // Update the audio listener attached to the camera
  17341. if (BABYLON.AudioEngine) {
  17342. this._updateAudioParameters();
  17343. }
  17344. // After render
  17345. if (this.afterRender) {
  17346. this.afterRender();
  17347. }
  17348. this.onAfterRenderObservable.notifyObservers(this);
  17349. // Cleaning
  17350. for (var index = 0; index < this._toBeDisposed.length; index++) {
  17351. this._toBeDisposed.data[index].dispose();
  17352. this._toBeDisposed[index] = null;
  17353. }
  17354. this._toBeDisposed.reset();
  17355. if (this.dumpNextRenderTargets) {
  17356. this.dumpNextRenderTargets = false;
  17357. }
  17358. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  17359. this._lastFrameDuration.endMonitoring();
  17360. this._totalMeshesCounter.addCount(this.meshes.length, true);
  17361. this._totalLightsCounter.addCount(this.lights.length, true);
  17362. this._totalMaterialsCounter.addCount(this.materials.length, true);
  17363. this._totalTexturesCounter.addCount(this.textures.length, true);
  17364. this._activeBones.addCount(0, true);
  17365. this._activeIndices.addCount(0, true);
  17366. this._activeParticles.addCount(0, true);
  17367. };
  17368. Scene.prototype._updateAudioParameters = function () {
  17369. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  17370. return;
  17371. }
  17372. var listeningCamera;
  17373. var audioEngine = BABYLON.Engine.audioEngine;
  17374. if (this.activeCameras.length > 0) {
  17375. listeningCamera = this.activeCameras[0];
  17376. }
  17377. else {
  17378. listeningCamera = this.activeCamera;
  17379. }
  17380. if (listeningCamera && audioEngine.canUseWebAudio) {
  17381. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  17382. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  17383. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  17384. cameraDirection.normalize();
  17385. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  17386. var i;
  17387. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  17388. var sound = this.mainSoundTrack.soundCollection[i];
  17389. if (sound.useCustomAttenuation) {
  17390. sound.updateDistanceFromListener();
  17391. }
  17392. }
  17393. for (i = 0; i < this.soundTracks.length; i++) {
  17394. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  17395. sound = this.soundTracks[i].soundCollection[j];
  17396. if (sound.useCustomAttenuation) {
  17397. sound.updateDistanceFromListener();
  17398. }
  17399. }
  17400. }
  17401. }
  17402. };
  17403. Object.defineProperty(Scene.prototype, "audioEnabled", {
  17404. // Audio
  17405. get: function () {
  17406. return this._audioEnabled;
  17407. },
  17408. set: function (value) {
  17409. this._audioEnabled = value;
  17410. if (BABYLON.AudioEngine) {
  17411. if (this._audioEnabled) {
  17412. this._enableAudio();
  17413. }
  17414. else {
  17415. this._disableAudio();
  17416. }
  17417. }
  17418. },
  17419. enumerable: true,
  17420. configurable: true
  17421. });
  17422. Scene.prototype._disableAudio = function () {
  17423. var i;
  17424. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  17425. this.mainSoundTrack.soundCollection[i].pause();
  17426. }
  17427. for (i = 0; i < this.soundTracks.length; i++) {
  17428. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  17429. this.soundTracks[i].soundCollection[j].pause();
  17430. }
  17431. }
  17432. };
  17433. Scene.prototype._enableAudio = function () {
  17434. var i;
  17435. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  17436. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  17437. this.mainSoundTrack.soundCollection[i].play();
  17438. }
  17439. }
  17440. for (i = 0; i < this.soundTracks.length; i++) {
  17441. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  17442. if (this.soundTracks[i].soundCollection[j].isPaused) {
  17443. this.soundTracks[i].soundCollection[j].play();
  17444. }
  17445. }
  17446. }
  17447. };
  17448. Object.defineProperty(Scene.prototype, "headphone", {
  17449. get: function () {
  17450. return this._headphone;
  17451. },
  17452. set: function (value) {
  17453. this._headphone = value;
  17454. if (BABYLON.AudioEngine) {
  17455. if (this._headphone) {
  17456. this._switchAudioModeForHeadphones();
  17457. }
  17458. else {
  17459. this._switchAudioModeForNormalSpeakers();
  17460. }
  17461. }
  17462. },
  17463. enumerable: true,
  17464. configurable: true
  17465. });
  17466. Scene.prototype._switchAudioModeForHeadphones = function () {
  17467. this.mainSoundTrack.switchPanningModelToHRTF();
  17468. for (var i = 0; i < this.soundTracks.length; i++) {
  17469. this.soundTracks[i].switchPanningModelToHRTF();
  17470. }
  17471. };
  17472. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  17473. this.mainSoundTrack.switchPanningModelToEqualPower();
  17474. for (var i = 0; i < this.soundTracks.length; i++) {
  17475. this.soundTracks[i].switchPanningModelToEqualPower();
  17476. }
  17477. };
  17478. Scene.prototype.enableDepthRenderer = function () {
  17479. if (this._depthRenderer) {
  17480. return this._depthRenderer;
  17481. }
  17482. this._depthRenderer = new BABYLON.DepthRenderer(this);
  17483. return this._depthRenderer;
  17484. };
  17485. Scene.prototype.disableDepthRenderer = function () {
  17486. if (!this._depthRenderer) {
  17487. return;
  17488. }
  17489. this._depthRenderer.dispose();
  17490. this._depthRenderer = null;
  17491. };
  17492. Scene.prototype.freezeMaterials = function () {
  17493. for (var i = 0; i < this.materials.length; i++) {
  17494. this.materials[i].freeze();
  17495. }
  17496. };
  17497. Scene.prototype.unfreezeMaterials = function () {
  17498. for (var i = 0; i < this.materials.length; i++) {
  17499. this.materials[i].unfreeze();
  17500. }
  17501. };
  17502. Scene.prototype.dispose = function () {
  17503. this.beforeRender = null;
  17504. this.afterRender = null;
  17505. this.skeletons = [];
  17506. this._boundingBoxRenderer.dispose();
  17507. if (this._depthRenderer) {
  17508. this._depthRenderer.dispose();
  17509. }
  17510. // Debug layer
  17511. if (this._debugLayer) {
  17512. this._debugLayer.hide();
  17513. }
  17514. // Events
  17515. this.onDisposeObservable.notifyObservers(this);
  17516. this.onDisposeObservable.clear();
  17517. this.onBeforeRenderObservable.clear();
  17518. this.onAfterRenderObservable.clear();
  17519. this.detachControl();
  17520. // Release sounds & sounds tracks
  17521. if (BABYLON.AudioEngine) {
  17522. this.disposeSounds();
  17523. }
  17524. // Detach cameras
  17525. var canvas = this._engine.getRenderingCanvas();
  17526. var index;
  17527. for (index = 0; index < this.cameras.length; index++) {
  17528. this.cameras[index].detachControl(canvas);
  17529. }
  17530. // Release lights
  17531. while (this.lights.length) {
  17532. this.lights[0].dispose();
  17533. }
  17534. // Release meshes
  17535. while (this.meshes.length) {
  17536. this.meshes[0].dispose(true);
  17537. }
  17538. // Release cameras
  17539. while (this.cameras.length) {
  17540. this.cameras[0].dispose();
  17541. }
  17542. // Release materials
  17543. while (this.materials.length) {
  17544. this.materials[0].dispose();
  17545. }
  17546. // Release particles
  17547. while (this.particleSystems.length) {
  17548. this.particleSystems[0].dispose();
  17549. }
  17550. // Release sprites
  17551. while (this.spriteManagers.length) {
  17552. this.spriteManagers[0].dispose();
  17553. }
  17554. // Release layers
  17555. while (this.layers.length) {
  17556. this.layers[0].dispose();
  17557. }
  17558. // Release textures
  17559. while (this.textures.length) {
  17560. this.textures[0].dispose();
  17561. }
  17562. // Post-processes
  17563. this.postProcessManager.dispose();
  17564. // Physics
  17565. if (this._physicsEngine) {
  17566. this.disablePhysicsEngine();
  17567. }
  17568. // Remove from engine
  17569. index = this._engine.scenes.indexOf(this);
  17570. if (index > -1) {
  17571. this._engine.scenes.splice(index, 1);
  17572. }
  17573. this._engine.wipeCaches();
  17574. };
  17575. // Release sounds & sounds tracks
  17576. Scene.prototype.disposeSounds = function () {
  17577. this.mainSoundTrack.dispose();
  17578. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  17579. this.soundTracks[scIndex].dispose();
  17580. }
  17581. };
  17582. // Octrees
  17583. Scene.prototype.getWorldExtends = function () {
  17584. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  17585. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  17586. for (var index = 0; index < this.meshes.length; index++) {
  17587. var mesh = this.meshes[index];
  17588. mesh.computeWorldMatrix(true);
  17589. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  17590. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  17591. BABYLON.Tools.CheckExtends(minBox, min, max);
  17592. BABYLON.Tools.CheckExtends(maxBox, min, max);
  17593. }
  17594. return {
  17595. min: min,
  17596. max: max
  17597. };
  17598. };
  17599. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  17600. if (maxCapacity === void 0) { maxCapacity = 64; }
  17601. if (maxDepth === void 0) { maxDepth = 2; }
  17602. if (!this._selectionOctree) {
  17603. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  17604. }
  17605. var worldExtends = this.getWorldExtends();
  17606. // Update octree
  17607. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  17608. return this._selectionOctree;
  17609. };
  17610. // Picking
  17611. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  17612. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  17613. var engine = this._engine;
  17614. if (!camera) {
  17615. if (!this.activeCamera)
  17616. throw new Error("Active camera not set");
  17617. camera = this.activeCamera;
  17618. }
  17619. var cameraViewport = camera.viewport;
  17620. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  17621. // Moving coordinates to local viewport world
  17622. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  17623. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  17624. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  17625. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  17626. };
  17627. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  17628. var engine = this._engine;
  17629. if (!camera) {
  17630. if (!this.activeCamera)
  17631. throw new Error("Active camera not set");
  17632. camera = this.activeCamera;
  17633. }
  17634. var cameraViewport = camera.viewport;
  17635. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  17636. var identity = BABYLON.Matrix.Identity();
  17637. // Moving coordinates to local viewport world
  17638. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  17639. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  17640. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  17641. };
  17642. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  17643. var pickingInfo = null;
  17644. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  17645. var mesh = this.meshes[meshIndex];
  17646. if (predicate) {
  17647. if (!predicate(mesh)) {
  17648. continue;
  17649. }
  17650. }
  17651. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  17652. continue;
  17653. }
  17654. var world = mesh.getWorldMatrix();
  17655. var ray = rayFunction(world);
  17656. var result = mesh.intersects(ray, fastCheck);
  17657. if (!result || !result.hit)
  17658. continue;
  17659. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  17660. continue;
  17661. pickingInfo = result;
  17662. if (fastCheck) {
  17663. break;
  17664. }
  17665. }
  17666. return pickingInfo || new BABYLON.PickingInfo();
  17667. };
  17668. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  17669. var pickingInfo = null;
  17670. camera = camera || this.activeCamera;
  17671. if (this.spriteManagers.length > 0) {
  17672. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  17673. var spriteManager = this.spriteManagers[spriteIndex];
  17674. if (!spriteManager.isPickable) {
  17675. continue;
  17676. }
  17677. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  17678. if (!result || !result.hit)
  17679. continue;
  17680. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  17681. continue;
  17682. pickingInfo = result;
  17683. if (fastCheck) {
  17684. break;
  17685. }
  17686. }
  17687. }
  17688. return pickingInfo || new BABYLON.PickingInfo();
  17689. };
  17690. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  17691. var _this = this;
  17692. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  17693. /// <param name="x">X position on screen</param>
  17694. /// <param name="y">Y position on screen</param>
  17695. /// <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>
  17696. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  17697. /// <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>
  17698. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  17699. };
  17700. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  17701. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  17702. /// <param name="x">X position on screen</param>
  17703. /// <param name="y">Y position on screen</param>
  17704. /// <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>
  17705. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  17706. /// <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>
  17707. return this._internalPickSprites(this.createPickingRayInCameraSpace(x, y, camera), predicate, fastCheck, camera);
  17708. };
  17709. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  17710. var _this = this;
  17711. return this._internalPick(function (world) {
  17712. if (!_this._pickWithRayInverseMatrix) {
  17713. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  17714. }
  17715. world.invertToRef(_this._pickWithRayInverseMatrix);
  17716. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  17717. }, predicate, fastCheck);
  17718. };
  17719. Scene.prototype.setPointerOverMesh = function (mesh) {
  17720. if (this._pointerOverMesh === mesh) {
  17721. return;
  17722. }
  17723. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  17724. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  17725. }
  17726. this._pointerOverMesh = mesh;
  17727. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  17728. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  17729. }
  17730. };
  17731. Scene.prototype.getPointerOverMesh = function () {
  17732. return this._pointerOverMesh;
  17733. };
  17734. Scene.prototype.setPointerOverSprite = function (sprite) {
  17735. if (this._pointerOverSprite === sprite) {
  17736. return;
  17737. }
  17738. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  17739. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  17740. }
  17741. this._pointerOverSprite = sprite;
  17742. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  17743. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  17744. }
  17745. };
  17746. Scene.prototype.getPointerOverSprite = function () {
  17747. return this._pointerOverSprite;
  17748. };
  17749. // Physics
  17750. Scene.prototype.getPhysicsEngine = function () {
  17751. return this._physicsEngine;
  17752. };
  17753. /**
  17754. * Enables physics to the current scene
  17755. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  17756. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  17757. * @return {boolean} was the physics engine initialized
  17758. */
  17759. Scene.prototype.enablePhysics = function (gravity, plugin) {
  17760. if (this._physicsEngine) {
  17761. return true;
  17762. }
  17763. try {
  17764. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  17765. return true;
  17766. }
  17767. catch (e) {
  17768. BABYLON.Tools.Error(e.message);
  17769. return false;
  17770. }
  17771. };
  17772. Scene.prototype.disablePhysicsEngine = function () {
  17773. if (!this._physicsEngine) {
  17774. return;
  17775. }
  17776. this._physicsEngine.dispose();
  17777. this._physicsEngine = undefined;
  17778. };
  17779. Scene.prototype.isPhysicsEnabled = function () {
  17780. return this._physicsEngine !== undefined;
  17781. };
  17782. /**
  17783. *
  17784. * Sets the gravity of the physics engine (and NOT of the scene)
  17785. * @param {BABYLON.Vector3} [gravity] - the new gravity to be used
  17786. */
  17787. Scene.prototype.setGravity = function (gravity) {
  17788. BABYLON.Tools.Warn("Deprecated, please use 'scene.getPhysicsEngine().setGravity()'");
  17789. if (!this._physicsEngine) {
  17790. return;
  17791. }
  17792. this._physicsEngine.setGravity(gravity);
  17793. };
  17794. /**
  17795. * Legacy support, using the new API
  17796. * @Deprecated
  17797. */
  17798. Scene.prototype.createCompoundImpostor = function (parts, options) {
  17799. BABYLON.Tools.Warn("Scene.createCompoundImpostor is deprecated. Please use PhysicsImpostor parent/child");
  17800. if (parts.parts) {
  17801. options = parts;
  17802. parts = parts.parts;
  17803. }
  17804. var mainMesh = parts[0].mesh;
  17805. mainMesh.physicsImpostor = new BABYLON.PhysicsImpostor(mainMesh, parts[0].impostor, options, this);
  17806. for (var index = 1; index < parts.length; index++) {
  17807. var mesh = parts[index].mesh;
  17808. if (mesh.parent !== mainMesh) {
  17809. mesh.position = mesh.position.subtract(mainMesh.position);
  17810. mesh.parent = mainMesh;
  17811. }
  17812. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parts[index].impostor, options, this);
  17813. }
  17814. mainMesh.physicsImpostor.forceUpdate();
  17815. };
  17816. Scene.prototype.deleteCompoundImpostor = function (compound) {
  17817. var mesh = compound.parts[0].mesh;
  17818. mesh.physicsImpostor.dispose();
  17819. mesh.physicsImpostor = null;
  17820. };
  17821. // Misc.
  17822. Scene.prototype.createDefaultCameraOrLight = function () {
  17823. // Light
  17824. if (this.lights.length === 0) {
  17825. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  17826. }
  17827. // Camera
  17828. if (!this.activeCamera) {
  17829. var camera = new BABYLON.FreeCamera("default camera", BABYLON.Vector3.Zero(), this);
  17830. // Compute position
  17831. var worldExtends = this.getWorldExtends();
  17832. var worldCenter = worldExtends.min.add(worldExtends.max.subtract(worldExtends.min).scale(0.5));
  17833. camera.position = new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z));
  17834. camera.setTarget(worldCenter);
  17835. this.activeCamera = camera;
  17836. }
  17837. };
  17838. // Tags
  17839. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  17840. if (tagsQuery === undefined) {
  17841. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  17842. return list;
  17843. }
  17844. var listByTags = [];
  17845. forEach = forEach || (function (item) { return; });
  17846. for (var i in list) {
  17847. var item = list[i];
  17848. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  17849. listByTags.push(item);
  17850. forEach(item);
  17851. }
  17852. }
  17853. return listByTags;
  17854. };
  17855. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  17856. return this._getByTags(this.meshes, tagsQuery, forEach);
  17857. };
  17858. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  17859. return this._getByTags(this.cameras, tagsQuery, forEach);
  17860. };
  17861. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  17862. return this._getByTags(this.lights, tagsQuery, forEach);
  17863. };
  17864. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  17865. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  17866. };
  17867. /**
  17868. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  17869. * This allowed control for front to back rendering or reversly depending of the special needs.
  17870. *
  17871. * @param renderingGroupId The rendering group id corresponding to its index
  17872. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  17873. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  17874. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  17875. */
  17876. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  17877. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  17878. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  17879. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  17880. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  17881. };
  17882. /**
  17883. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  17884. *
  17885. * @param renderingGroupId The rendering group id corresponding to its index
  17886. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  17887. */
  17888. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  17889. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  17890. };
  17891. // Statics
  17892. Scene._FOGMODE_NONE = 0;
  17893. Scene._FOGMODE_EXP = 1;
  17894. Scene._FOGMODE_EXP2 = 2;
  17895. Scene._FOGMODE_LINEAR = 3;
  17896. Scene.MinDeltaTime = 1.0;
  17897. Scene.MaxDeltaTime = 1000.0;
  17898. return Scene;
  17899. })();
  17900. BABYLON.Scene = Scene;
  17901. })(BABYLON || (BABYLON = {}));
  17902. var BABYLON;
  17903. (function (BABYLON) {
  17904. var Buffer = (function () {
  17905. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  17906. if (engine instanceof BABYLON.Mesh) {
  17907. this._engine = engine.getScene().getEngine();
  17908. }
  17909. else {
  17910. this._engine = engine;
  17911. }
  17912. this._updatable = updatable;
  17913. this._data = data;
  17914. this._strideSize = stride;
  17915. if (!postponeInternalCreation) {
  17916. this.create();
  17917. }
  17918. this._instanced = instanced;
  17919. }
  17920. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride) {
  17921. // a lot of these parameters are ignored as they are overriden by the buffer
  17922. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, this._instanced, offset, size);
  17923. };
  17924. // Properties
  17925. Buffer.prototype.isUpdatable = function () {
  17926. return this._updatable;
  17927. };
  17928. Buffer.prototype.getData = function () {
  17929. return this._data;
  17930. };
  17931. Buffer.prototype.getBuffer = function () {
  17932. return this._buffer;
  17933. };
  17934. Buffer.prototype.getStrideSize = function () {
  17935. return this._strideSize;
  17936. };
  17937. Buffer.prototype.getIsInstanced = function () {
  17938. return this._instanced;
  17939. };
  17940. // Methods
  17941. Buffer.prototype.create = function (data) {
  17942. if (!data && this._buffer) {
  17943. return; // nothing to do
  17944. }
  17945. data = data || this._data;
  17946. if (!this._buffer) {
  17947. if (this._updatable) {
  17948. this._buffer = this._engine.createDynamicVertexBuffer(data);
  17949. this._data = data;
  17950. }
  17951. else {
  17952. this._buffer = this._engine.createVertexBuffer(data);
  17953. }
  17954. }
  17955. else if (this._updatable) {
  17956. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  17957. this._data = data;
  17958. }
  17959. };
  17960. Buffer.prototype.update = function (data) {
  17961. this.create(data);
  17962. };
  17963. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  17964. if (!this._buffer) {
  17965. return;
  17966. }
  17967. if (this._updatable) {
  17968. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  17969. this._data = null;
  17970. }
  17971. };
  17972. Buffer.prototype.dispose = function () {
  17973. if (!this._buffer) {
  17974. return;
  17975. }
  17976. if (this._engine._releaseBuffer(this._buffer)) {
  17977. this._buffer = null;
  17978. }
  17979. };
  17980. return Buffer;
  17981. })();
  17982. BABYLON.Buffer = Buffer;
  17983. })(BABYLON || (BABYLON = {}));
  17984. var BABYLON;
  17985. (function (BABYLON) {
  17986. var VertexBuffer = (function () {
  17987. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  17988. if (!stride) {
  17989. // Deduce stride from kind
  17990. switch (kind) {
  17991. case VertexBuffer.PositionKind:
  17992. stride = 3;
  17993. break;
  17994. case VertexBuffer.NormalKind:
  17995. stride = 3;
  17996. break;
  17997. case VertexBuffer.UVKind:
  17998. case VertexBuffer.UV2Kind:
  17999. case VertexBuffer.UV3Kind:
  18000. case VertexBuffer.UV4Kind:
  18001. case VertexBuffer.UV5Kind:
  18002. case VertexBuffer.UV6Kind:
  18003. stride = 2;
  18004. break;
  18005. case VertexBuffer.ColorKind:
  18006. stride = 4;
  18007. break;
  18008. case VertexBuffer.MatricesIndicesKind:
  18009. case VertexBuffer.MatricesIndicesExtraKind:
  18010. stride = 4;
  18011. break;
  18012. case VertexBuffer.MatricesWeightsKind:
  18013. case VertexBuffer.MatricesWeightsExtraKind:
  18014. stride = 4;
  18015. break;
  18016. }
  18017. }
  18018. if (data instanceof BABYLON.Buffer) {
  18019. if (!stride) {
  18020. stride = data.getStrideSize();
  18021. }
  18022. this._buffer = data;
  18023. this._ownsBuffer = false;
  18024. }
  18025. else {
  18026. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  18027. this._ownsBuffer = true;
  18028. }
  18029. this._stride = stride;
  18030. this._offset = offset ? offset : 0;
  18031. this._size = size ? size : stride;
  18032. this._kind = kind;
  18033. }
  18034. VertexBuffer.prototype.getKind = function () {
  18035. return this._kind;
  18036. };
  18037. // Properties
  18038. VertexBuffer.prototype.isUpdatable = function () {
  18039. return this._buffer.isUpdatable();
  18040. };
  18041. VertexBuffer.prototype.getData = function () {
  18042. return this._buffer.getData();
  18043. };
  18044. VertexBuffer.prototype.getBuffer = function () {
  18045. return this._buffer.getBuffer();
  18046. };
  18047. VertexBuffer.prototype.getStrideSize = function () {
  18048. return this._stride;
  18049. };
  18050. VertexBuffer.prototype.getOffset = function () {
  18051. return this._offset;
  18052. };
  18053. VertexBuffer.prototype.getSize = function () {
  18054. return this._size;
  18055. };
  18056. VertexBuffer.prototype.getIsInstanced = function () {
  18057. return this._buffer.getIsInstanced();
  18058. };
  18059. // Methods
  18060. VertexBuffer.prototype.create = function (data) {
  18061. return this._buffer.create(data);
  18062. };
  18063. VertexBuffer.prototype.update = function (data) {
  18064. return this._buffer.update(data);
  18065. };
  18066. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  18067. return this._buffer.updateDirectly(data, offset);
  18068. };
  18069. VertexBuffer.prototype.dispose = function () {
  18070. if (this._ownsBuffer) {
  18071. this._buffer.dispose();
  18072. }
  18073. };
  18074. Object.defineProperty(VertexBuffer, "PositionKind", {
  18075. get: function () {
  18076. return VertexBuffer._PositionKind;
  18077. },
  18078. enumerable: true,
  18079. configurable: true
  18080. });
  18081. Object.defineProperty(VertexBuffer, "NormalKind", {
  18082. get: function () {
  18083. return VertexBuffer._NormalKind;
  18084. },
  18085. enumerable: true,
  18086. configurable: true
  18087. });
  18088. Object.defineProperty(VertexBuffer, "UVKind", {
  18089. get: function () {
  18090. return VertexBuffer._UVKind;
  18091. },
  18092. enumerable: true,
  18093. configurable: true
  18094. });
  18095. Object.defineProperty(VertexBuffer, "UV2Kind", {
  18096. get: function () {
  18097. return VertexBuffer._UV2Kind;
  18098. },
  18099. enumerable: true,
  18100. configurable: true
  18101. });
  18102. Object.defineProperty(VertexBuffer, "UV3Kind", {
  18103. get: function () {
  18104. return VertexBuffer._UV3Kind;
  18105. },
  18106. enumerable: true,
  18107. configurable: true
  18108. });
  18109. Object.defineProperty(VertexBuffer, "UV4Kind", {
  18110. get: function () {
  18111. return VertexBuffer._UV4Kind;
  18112. },
  18113. enumerable: true,
  18114. configurable: true
  18115. });
  18116. Object.defineProperty(VertexBuffer, "UV5Kind", {
  18117. get: function () {
  18118. return VertexBuffer._UV5Kind;
  18119. },
  18120. enumerable: true,
  18121. configurable: true
  18122. });
  18123. Object.defineProperty(VertexBuffer, "UV6Kind", {
  18124. get: function () {
  18125. return VertexBuffer._UV6Kind;
  18126. },
  18127. enumerable: true,
  18128. configurable: true
  18129. });
  18130. Object.defineProperty(VertexBuffer, "ColorKind", {
  18131. get: function () {
  18132. return VertexBuffer._ColorKind;
  18133. },
  18134. enumerable: true,
  18135. configurable: true
  18136. });
  18137. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  18138. get: function () {
  18139. return VertexBuffer._MatricesIndicesKind;
  18140. },
  18141. enumerable: true,
  18142. configurable: true
  18143. });
  18144. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  18145. get: function () {
  18146. return VertexBuffer._MatricesWeightsKind;
  18147. },
  18148. enumerable: true,
  18149. configurable: true
  18150. });
  18151. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  18152. get: function () {
  18153. return VertexBuffer._MatricesIndicesExtraKind;
  18154. },
  18155. enumerable: true,
  18156. configurable: true
  18157. });
  18158. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  18159. get: function () {
  18160. return VertexBuffer._MatricesWeightsExtraKind;
  18161. },
  18162. enumerable: true,
  18163. configurable: true
  18164. });
  18165. // Enums
  18166. VertexBuffer._PositionKind = "position";
  18167. VertexBuffer._NormalKind = "normal";
  18168. VertexBuffer._UVKind = "uv";
  18169. VertexBuffer._UV2Kind = "uv2";
  18170. VertexBuffer._UV3Kind = "uv3";
  18171. VertexBuffer._UV4Kind = "uv4";
  18172. VertexBuffer._UV5Kind = "uv5";
  18173. VertexBuffer._UV6Kind = "uv6";
  18174. VertexBuffer._ColorKind = "color";
  18175. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  18176. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  18177. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  18178. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  18179. return VertexBuffer;
  18180. })();
  18181. BABYLON.VertexBuffer = VertexBuffer;
  18182. })(BABYLON || (BABYLON = {}));
  18183. var BABYLON;
  18184. (function (BABYLON) {
  18185. /**
  18186. * Creates an instance based on a source mesh.
  18187. */
  18188. var InstancedMesh = (function (_super) {
  18189. __extends(InstancedMesh, _super);
  18190. function InstancedMesh(name, source) {
  18191. _super.call(this, name, source.getScene());
  18192. source.instances.push(this);
  18193. this._sourceMesh = source;
  18194. this.position.copyFrom(source.position);
  18195. this.rotation.copyFrom(source.rotation);
  18196. this.scaling.copyFrom(source.scaling);
  18197. if (source.rotationQuaternion) {
  18198. this.rotationQuaternion = source.rotationQuaternion.clone();
  18199. }
  18200. this.infiniteDistance = source.infiniteDistance;
  18201. this.setPivotMatrix(source.getPivotMatrix());
  18202. this.refreshBoundingInfo();
  18203. this._syncSubMeshes();
  18204. }
  18205. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  18206. // Methods
  18207. get: function () {
  18208. return this._sourceMesh.receiveShadows;
  18209. },
  18210. enumerable: true,
  18211. configurable: true
  18212. });
  18213. Object.defineProperty(InstancedMesh.prototype, "material", {
  18214. get: function () {
  18215. return this._sourceMesh.material;
  18216. },
  18217. enumerable: true,
  18218. configurable: true
  18219. });
  18220. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  18221. get: function () {
  18222. return this._sourceMesh.visibility;
  18223. },
  18224. enumerable: true,
  18225. configurable: true
  18226. });
  18227. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  18228. get: function () {
  18229. return this._sourceMesh.skeleton;
  18230. },
  18231. enumerable: true,
  18232. configurable: true
  18233. });
  18234. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  18235. get: function () {
  18236. return this._sourceMesh.renderingGroupId;
  18237. },
  18238. enumerable: true,
  18239. configurable: true
  18240. });
  18241. InstancedMesh.prototype.getTotalVertices = function () {
  18242. return this._sourceMesh.getTotalVertices();
  18243. };
  18244. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  18245. get: function () {
  18246. return this._sourceMesh;
  18247. },
  18248. enumerable: true,
  18249. configurable: true
  18250. });
  18251. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  18252. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  18253. };
  18254. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  18255. return this._sourceMesh.isVerticesDataPresent(kind);
  18256. };
  18257. InstancedMesh.prototype.getIndices = function () {
  18258. return this._sourceMesh.getIndices();
  18259. };
  18260. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  18261. get: function () {
  18262. return this._sourceMesh._positions;
  18263. },
  18264. enumerable: true,
  18265. configurable: true
  18266. });
  18267. InstancedMesh.prototype.refreshBoundingInfo = function () {
  18268. var meshBB = this._sourceMesh.getBoundingInfo();
  18269. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  18270. this._updateBoundingInfo();
  18271. };
  18272. InstancedMesh.prototype._preActivate = function () {
  18273. if (this._currentLOD) {
  18274. this._currentLOD._preActivate();
  18275. }
  18276. };
  18277. InstancedMesh.prototype._activate = function (renderId) {
  18278. if (this._currentLOD) {
  18279. this._currentLOD._registerInstanceForRenderId(this, renderId);
  18280. }
  18281. };
  18282. InstancedMesh.prototype.getLOD = function (camera) {
  18283. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  18284. if (this._currentLOD === this.sourceMesh) {
  18285. return this;
  18286. }
  18287. return this._currentLOD;
  18288. };
  18289. InstancedMesh.prototype._syncSubMeshes = function () {
  18290. this.releaseSubMeshes();
  18291. if (this._sourceMesh.subMeshes) {
  18292. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  18293. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  18294. }
  18295. }
  18296. };
  18297. InstancedMesh.prototype._generatePointsArray = function () {
  18298. return this._sourceMesh._generatePointsArray();
  18299. };
  18300. // Clone
  18301. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  18302. var result = this._sourceMesh.createInstance(name);
  18303. // Deep copy
  18304. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes"], []);
  18305. // Bounding info
  18306. this.refreshBoundingInfo();
  18307. // Parent
  18308. if (newParent) {
  18309. result.parent = newParent;
  18310. }
  18311. if (!doNotCloneChildren) {
  18312. // Children
  18313. for (var index = 0; index < this.getScene().meshes.length; index++) {
  18314. var mesh = this.getScene().meshes[index];
  18315. if (mesh.parent === this) {
  18316. mesh.clone(mesh.name, result);
  18317. }
  18318. }
  18319. }
  18320. result.computeWorldMatrix(true);
  18321. return result;
  18322. };
  18323. // Dispoe
  18324. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  18325. // Remove from mesh
  18326. var index = this._sourceMesh.instances.indexOf(this);
  18327. this._sourceMesh.instances.splice(index, 1);
  18328. _super.prototype.dispose.call(this, doNotRecurse);
  18329. };
  18330. return InstancedMesh;
  18331. })(BABYLON.AbstractMesh);
  18332. BABYLON.InstancedMesh = InstancedMesh;
  18333. })(BABYLON || (BABYLON = {}));
  18334. var BABYLON;
  18335. (function (BABYLON) {
  18336. var _InstancesBatch = (function () {
  18337. function _InstancesBatch() {
  18338. this.mustReturn = false;
  18339. this.visibleInstances = new Array();
  18340. this.renderSelf = new Array();
  18341. }
  18342. return _InstancesBatch;
  18343. })();
  18344. BABYLON._InstancesBatch = _InstancesBatch;
  18345. var Mesh = (function (_super) {
  18346. __extends(Mesh, _super);
  18347. /**
  18348. * @constructor
  18349. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  18350. * @param {Scene} scene The scene to add this mesh to.
  18351. * @param {Node} parent The parent of this mesh, if it has one
  18352. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  18353. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  18354. * When false, achieved by calling a clone(), also passing False.
  18355. * This will make creation of children, recursive.
  18356. */
  18357. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  18358. if (parent === void 0) { parent = null; }
  18359. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  18360. _super.call(this, name, scene);
  18361. // Events
  18362. /**
  18363. * An event triggered before rendering the mesh
  18364. * @type {BABYLON.Observable}
  18365. */
  18366. this.onBeforeRenderObservable = new BABYLON.Observable();
  18367. /**
  18368. * An event triggered after rendering the mesh
  18369. * @type {BABYLON.Observable}
  18370. */
  18371. this.onAfterRenderObservable = new BABYLON.Observable();
  18372. /**
  18373. * An event triggered before drawing the mesh
  18374. * @type {BABYLON.Observable}
  18375. */
  18376. this.onBeforeDrawObservable = new BABYLON.Observable();
  18377. // Members
  18378. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  18379. this.instances = new Array();
  18380. this._LODLevels = new Array();
  18381. this._visibleInstances = {};
  18382. this._renderIdForInstances = new Array();
  18383. this._batchCache = new _InstancesBatch();
  18384. this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  18385. this._sideOrientation = Mesh._DEFAULTSIDE;
  18386. this._areNormalsFrozen = false; // Will be used by ribbons mainly
  18387. if (source) {
  18388. // Geometry
  18389. if (source._geometry) {
  18390. source._geometry.applyToMesh(this);
  18391. }
  18392. // Deep copy
  18393. BABYLON.Tools.DeepCopy(source, this, ["name", "material", "skeleton", "instances"], ["_poseMatrix"]);
  18394. // Pivot
  18395. this.setPivotMatrix(source.getPivotMatrix());
  18396. this.id = name + "." + source.id;
  18397. // Material
  18398. this.material = source.material;
  18399. var index;
  18400. if (!doNotCloneChildren) {
  18401. // Children
  18402. for (index = 0; index < scene.meshes.length; index++) {
  18403. var mesh = scene.meshes[index];
  18404. if (mesh.parent === source) {
  18405. // doNotCloneChildren is always going to be False
  18406. var newChild = mesh.clone(name + "." + mesh.name, this, doNotCloneChildren);
  18407. }
  18408. }
  18409. }
  18410. // Physics clone
  18411. var physicsEngine = this.getScene().getPhysicsEngine();
  18412. if (clonePhysicsImpostor && physicsEngine) {
  18413. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  18414. if (impostor) {
  18415. this.physicsImpostor = impostor.clone(this);
  18416. }
  18417. }
  18418. // Particles
  18419. for (index = 0; index < scene.particleSystems.length; index++) {
  18420. var system = scene.particleSystems[index];
  18421. if (system.emitter === source) {
  18422. system.clone(system.name, this);
  18423. }
  18424. }
  18425. this.computeWorldMatrix(true);
  18426. }
  18427. // Parent
  18428. if (parent !== null) {
  18429. this.parent = parent;
  18430. }
  18431. }
  18432. Object.defineProperty(Mesh, "FRONTSIDE", {
  18433. /**
  18434. * Mesh side orientation : usually the external or front surface
  18435. */
  18436. get: function () {
  18437. return Mesh._FRONTSIDE;
  18438. },
  18439. enumerable: true,
  18440. configurable: true
  18441. });
  18442. Object.defineProperty(Mesh, "BACKSIDE", {
  18443. /**
  18444. * Mesh side orientation : usually the internal or back surface
  18445. */
  18446. get: function () {
  18447. return Mesh._BACKSIDE;
  18448. },
  18449. enumerable: true,
  18450. configurable: true
  18451. });
  18452. Object.defineProperty(Mesh, "DOUBLESIDE", {
  18453. /**
  18454. * Mesh side orientation : both internal and external or front and back surfaces
  18455. */
  18456. get: function () {
  18457. return Mesh._DOUBLESIDE;
  18458. },
  18459. enumerable: true,
  18460. configurable: true
  18461. });
  18462. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  18463. /**
  18464. * Mesh side orientation : by default, `FRONTSIDE`
  18465. */
  18466. get: function () {
  18467. return Mesh._DEFAULTSIDE;
  18468. },
  18469. enumerable: true,
  18470. configurable: true
  18471. });
  18472. Object.defineProperty(Mesh, "NO_CAP", {
  18473. /**
  18474. * Mesh cap setting : no cap
  18475. */
  18476. get: function () {
  18477. return Mesh._NO_CAP;
  18478. },
  18479. enumerable: true,
  18480. configurable: true
  18481. });
  18482. Object.defineProperty(Mesh, "CAP_START", {
  18483. /**
  18484. * Mesh cap setting : one cap at the beginning of the mesh
  18485. */
  18486. get: function () {
  18487. return Mesh._CAP_START;
  18488. },
  18489. enumerable: true,
  18490. configurable: true
  18491. });
  18492. Object.defineProperty(Mesh, "CAP_END", {
  18493. /**
  18494. * Mesh cap setting : one cap at the end of the mesh
  18495. */
  18496. get: function () {
  18497. return Mesh._CAP_END;
  18498. },
  18499. enumerable: true,
  18500. configurable: true
  18501. });
  18502. Object.defineProperty(Mesh, "CAP_ALL", {
  18503. /**
  18504. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  18505. */
  18506. get: function () {
  18507. return Mesh._CAP_ALL;
  18508. },
  18509. enumerable: true,
  18510. configurable: true
  18511. });
  18512. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  18513. set: function (callback) {
  18514. if (this._onBeforeDrawObserver) {
  18515. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  18516. }
  18517. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  18518. },
  18519. enumerable: true,
  18520. configurable: true
  18521. });
  18522. // Methods
  18523. /**
  18524. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  18525. */
  18526. Mesh.prototype.toString = function (fullDetails) {
  18527. var ret = _super.prototype.toString.call(this, fullDetails);
  18528. ret += ", n vertices: " + this.getTotalVertices();
  18529. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  18530. if (this.animations) {
  18531. for (var i = 0; i < this.animations.length; i++) {
  18532. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  18533. }
  18534. }
  18535. if (fullDetails) {
  18536. ret += ", flat shading: " + (this._geometry ? (this.getVerticesData(BABYLON.VertexBuffer.PositionKind).length / 3 === this.getIndices().length ? "YES" : "NO") : "UNKNOWN");
  18537. }
  18538. return ret;
  18539. };
  18540. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  18541. get: function () {
  18542. return this._LODLevels.length > 0;
  18543. },
  18544. enumerable: true,
  18545. configurable: true
  18546. });
  18547. Mesh.prototype._sortLODLevels = function () {
  18548. this._LODLevels.sort(function (a, b) {
  18549. if (a.distance < b.distance) {
  18550. return 1;
  18551. }
  18552. if (a.distance > b.distance) {
  18553. return -1;
  18554. }
  18555. return 0;
  18556. });
  18557. };
  18558. /**
  18559. * Add a mesh as LOD level triggered at the given distance.
  18560. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  18561. * @param {number} distance The distance from the center of the object to show this level
  18562. * @param {Mesh} mesh The mesh to be added as LOD level
  18563. * @return {Mesh} This mesh (for chaining)
  18564. */
  18565. Mesh.prototype.addLODLevel = function (distance, mesh) {
  18566. if (mesh && mesh._masterMesh) {
  18567. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  18568. return this;
  18569. }
  18570. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  18571. this._LODLevels.push(level);
  18572. if (mesh) {
  18573. mesh._masterMesh = this;
  18574. }
  18575. this._sortLODLevels();
  18576. return this;
  18577. };
  18578. /**
  18579. * Returns the LOD level mesh at the passed distance or null if not found.
  18580. * It is related to the method `addLODLevel(distance, mesh)`.
  18581. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  18582. */
  18583. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  18584. for (var index = 0; index < this._LODLevels.length; index++) {
  18585. var level = this._LODLevels[index];
  18586. if (level.distance === distance) {
  18587. return level.mesh;
  18588. }
  18589. }
  18590. return null;
  18591. };
  18592. /**
  18593. * Remove a mesh from the LOD array
  18594. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  18595. * @param {Mesh} mesh The mesh to be removed.
  18596. * @return {Mesh} This mesh (for chaining)
  18597. */
  18598. Mesh.prototype.removeLODLevel = function (mesh) {
  18599. for (var index = 0; index < this._LODLevels.length; index++) {
  18600. if (this._LODLevels[index].mesh === mesh) {
  18601. this._LODLevels.splice(index, 1);
  18602. if (mesh) {
  18603. mesh._masterMesh = null;
  18604. }
  18605. }
  18606. }
  18607. this._sortLODLevels();
  18608. return this;
  18609. };
  18610. /**
  18611. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  18612. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  18613. */
  18614. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  18615. if (!this._LODLevels || this._LODLevels.length === 0) {
  18616. return this;
  18617. }
  18618. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.globalPosition).length();
  18619. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  18620. if (this.onLODLevelSelection) {
  18621. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  18622. }
  18623. return this;
  18624. }
  18625. for (var index = 0; index < this._LODLevels.length; index++) {
  18626. var level = this._LODLevels[index];
  18627. if (level.distance < distanceToCamera) {
  18628. if (level.mesh) {
  18629. level.mesh._preActivate();
  18630. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  18631. }
  18632. if (this.onLODLevelSelection) {
  18633. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  18634. }
  18635. return level.mesh;
  18636. }
  18637. }
  18638. if (this.onLODLevelSelection) {
  18639. this.onLODLevelSelection(distanceToCamera, this, this);
  18640. }
  18641. return this;
  18642. };
  18643. Object.defineProperty(Mesh.prototype, "geometry", {
  18644. /**
  18645. * Returns the mesh internal Geometry object.
  18646. */
  18647. get: function () {
  18648. return this._geometry;
  18649. },
  18650. enumerable: true,
  18651. configurable: true
  18652. });
  18653. /**
  18654. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  18655. */
  18656. Mesh.prototype.getTotalVertices = function () {
  18657. if (!this._geometry) {
  18658. return 0;
  18659. }
  18660. return this._geometry.getTotalVertices();
  18661. };
  18662. /**
  18663. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  18664. * 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.
  18665. * Returns null if the mesh has no geometry or no vertex buffer.
  18666. * Possible `kind` values :
  18667. * - BABYLON.VertexBuffer.PositionKind
  18668. * - BABYLON.VertexBuffer.UVKind
  18669. * - BABYLON.VertexBuffer.UV2Kind
  18670. * - BABYLON.VertexBuffer.UV3Kind
  18671. * - BABYLON.VertexBuffer.UV4Kind
  18672. * - BABYLON.VertexBuffer.UV5Kind
  18673. * - BABYLON.VertexBuffer.UV6Kind
  18674. * - BABYLON.VertexBuffer.ColorKind
  18675. * - BABYLON.VertexBuffer.MatricesIndicesKind
  18676. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  18677. * - BABYLON.VertexBuffer.MatricesWeightsKind
  18678. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  18679. */
  18680. Mesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  18681. if (!this._geometry) {
  18682. return null;
  18683. }
  18684. return this._geometry.getVerticesData(kind, copyWhenShared);
  18685. };
  18686. /**
  18687. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  18688. * Returns `undefined` if the mesh has no geometry.
  18689. * Possible `kind` values :
  18690. * - BABYLON.VertexBuffer.PositionKind
  18691. * - BABYLON.VertexBuffer.UVKind
  18692. * - BABYLON.VertexBuffer.UV2Kind
  18693. * - BABYLON.VertexBuffer.UV3Kind
  18694. * - BABYLON.VertexBuffer.UV4Kind
  18695. * - BABYLON.VertexBuffer.UV5Kind
  18696. * - BABYLON.VertexBuffer.UV6Kind
  18697. * - BABYLON.VertexBuffer.ColorKind
  18698. * - BABYLON.VertexBuffer.MatricesIndicesKind
  18699. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  18700. * - BABYLON.VertexBuffer.MatricesWeightsKind
  18701. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  18702. */
  18703. Mesh.prototype.getVertexBuffer = function (kind) {
  18704. if (!this._geometry) {
  18705. return undefined;
  18706. }
  18707. return this._geometry.getVertexBuffer(kind);
  18708. };
  18709. /**
  18710. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  18711. * Possible `kind` values :
  18712. * - BABYLON.VertexBuffer.PositionKind
  18713. * - BABYLON.VertexBuffer.UVKind
  18714. * - BABYLON.VertexBuffer.UV2Kind
  18715. * - BABYLON.VertexBuffer.UV3Kind
  18716. * - BABYLON.VertexBuffer.UV4Kind
  18717. * - BABYLON.VertexBuffer.UV5Kind
  18718. * - BABYLON.VertexBuffer.UV6Kind
  18719. * - BABYLON.VertexBuffer.ColorKind
  18720. * - BABYLON.VertexBuffer.MatricesIndicesKind
  18721. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  18722. * - BABYLON.VertexBuffer.MatricesWeightsKind
  18723. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  18724. */
  18725. Mesh.prototype.isVerticesDataPresent = function (kind) {
  18726. if (!this._geometry) {
  18727. if (this._delayInfo) {
  18728. return this._delayInfo.indexOf(kind) !== -1;
  18729. }
  18730. return false;
  18731. }
  18732. return this._geometry.isVerticesDataPresent(kind);
  18733. };
  18734. /**
  18735. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  18736. * Possible `kind` values :
  18737. * - BABYLON.VertexBuffer.PositionKind
  18738. * - BABYLON.VertexBuffer.UVKind
  18739. * - BABYLON.VertexBuffer.UV2Kind
  18740. * - BABYLON.VertexBuffer.UV3Kind
  18741. * - BABYLON.VertexBuffer.UV4Kind
  18742. * - BABYLON.VertexBuffer.UV5Kind
  18743. * - BABYLON.VertexBuffer.UV6Kind
  18744. * - BABYLON.VertexBuffer.ColorKind
  18745. * - BABYLON.VertexBuffer.MatricesIndicesKind
  18746. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  18747. * - BABYLON.VertexBuffer.MatricesWeightsKind
  18748. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  18749. */
  18750. Mesh.prototype.getVerticesDataKinds = function () {
  18751. if (!this._geometry) {
  18752. var result = [];
  18753. if (this._delayInfo) {
  18754. for (var kind in this._delayInfo) {
  18755. result.push(kind);
  18756. }
  18757. }
  18758. return result;
  18759. }
  18760. return this._geometry.getVerticesDataKinds();
  18761. };
  18762. /**
  18763. * Returns a positive integer : the total number of indices in this mesh geometry.
  18764. * Returns zero if the mesh has no geometry.
  18765. */
  18766. Mesh.prototype.getTotalIndices = function () {
  18767. if (!this._geometry) {
  18768. return 0;
  18769. }
  18770. return this._geometry.getTotalIndices();
  18771. };
  18772. /**
  18773. * Returns an array of integers or a Int32Array populated with the mesh indices.
  18774. * 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.
  18775. * Returns an empty array if the mesh has no geometry.
  18776. */
  18777. Mesh.prototype.getIndices = function (copyWhenShared) {
  18778. if (!this._geometry) {
  18779. return [];
  18780. }
  18781. return this._geometry.getIndices(copyWhenShared);
  18782. };
  18783. Object.defineProperty(Mesh.prototype, "isBlocked", {
  18784. get: function () {
  18785. return this._masterMesh !== null && this._masterMesh !== undefined;
  18786. },
  18787. enumerable: true,
  18788. configurable: true
  18789. });
  18790. /**
  18791. * Boolean : true once the mesh is ready after all the delayed process (loading, etc) are complete.
  18792. */
  18793. Mesh.prototype.isReady = function () {
  18794. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  18795. return false;
  18796. }
  18797. return _super.prototype.isReady.call(this);
  18798. };
  18799. /**
  18800. * Boolean : true if the mesh has been disposed.
  18801. */
  18802. Mesh.prototype.isDisposed = function () {
  18803. return this._isDisposed;
  18804. };
  18805. Object.defineProperty(Mesh.prototype, "sideOrientation", {
  18806. get: function () {
  18807. return this._sideOrientation;
  18808. },
  18809. /**
  18810. * Sets the mesh side orientation : BABYLON.Mesh.FRONTSIDE, BABYLON.Mesh.BACKSIDE, BABYLON.Mesh.DOUBLESIDE or BABYLON.Mesh.DEFAULTSIDE
  18811. * tuto : http://doc.babylonjs.com/tutorials/Discover_Basic_Elements#side-orientation
  18812. */
  18813. set: function (sideO) {
  18814. this._sideOrientation = sideO;
  18815. },
  18816. enumerable: true,
  18817. configurable: true
  18818. });
  18819. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  18820. /**
  18821. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  18822. * This property is pertinent only for updatable parametric shapes.
  18823. */
  18824. get: function () {
  18825. return this._areNormalsFrozen;
  18826. },
  18827. enumerable: true,
  18828. configurable: true
  18829. });
  18830. /**
  18831. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  18832. * It has no effect at all on other shapes.
  18833. * It prevents the mesh normals from being recomputed on next `positions` array update.
  18834. */
  18835. Mesh.prototype.freezeNormals = function () {
  18836. this._areNormalsFrozen = true;
  18837. };
  18838. /**
  18839. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  18840. * It has no effect at all on other shapes.
  18841. * It reactivates the mesh normals computation if it was previously frozen.
  18842. */
  18843. Mesh.prototype.unfreezeNormals = function () {
  18844. this._areNormalsFrozen = false;
  18845. };
  18846. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  18847. /**
  18848. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  18849. */
  18850. set: function (count) {
  18851. this._overridenInstanceCount = count;
  18852. },
  18853. enumerable: true,
  18854. configurable: true
  18855. });
  18856. // Methods
  18857. Mesh.prototype._preActivate = function () {
  18858. var sceneRenderId = this.getScene().getRenderId();
  18859. if (this._preActivateId === sceneRenderId) {
  18860. return;
  18861. }
  18862. this._preActivateId = sceneRenderId;
  18863. this._visibleInstances = null;
  18864. };
  18865. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  18866. if (this._visibleInstances) {
  18867. this._visibleInstances.intermediateDefaultRenderId = renderId;
  18868. }
  18869. };
  18870. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  18871. if (!this._visibleInstances) {
  18872. this._visibleInstances = {};
  18873. this._visibleInstances.defaultRenderId = renderId;
  18874. this._visibleInstances.selfDefaultRenderId = this._renderId;
  18875. }
  18876. if (!this._visibleInstances[renderId]) {
  18877. this._visibleInstances[renderId] = new Array();
  18878. }
  18879. this._visibleInstances[renderId].push(instance);
  18880. };
  18881. /**
  18882. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  18883. * This means the mesh underlying bounding box and sphere are recomputed.
  18884. */
  18885. Mesh.prototype.refreshBoundingInfo = function () {
  18886. if (this._boundingInfo.isLocked) {
  18887. return;
  18888. }
  18889. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18890. if (data) {
  18891. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  18892. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  18893. }
  18894. if (this.subMeshes) {
  18895. for (var index = 0; index < this.subMeshes.length; index++) {
  18896. this.subMeshes[index].refreshBoundingInfo();
  18897. }
  18898. }
  18899. this._updateBoundingInfo();
  18900. };
  18901. Mesh.prototype._createGlobalSubMesh = function () {
  18902. var totalVertices = this.getTotalVertices();
  18903. if (!totalVertices || !this.getIndices()) {
  18904. return null;
  18905. }
  18906. this.releaseSubMeshes();
  18907. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  18908. };
  18909. Mesh.prototype.subdivide = function (count) {
  18910. if (count < 1) {
  18911. return;
  18912. }
  18913. var totalIndices = this.getTotalIndices();
  18914. var subdivisionSize = (totalIndices / count) | 0;
  18915. var offset = 0;
  18916. // Ensure that subdivisionSize is a multiple of 3
  18917. while (subdivisionSize % 3 !== 0) {
  18918. subdivisionSize++;
  18919. }
  18920. this.releaseSubMeshes();
  18921. for (var index = 0; index < count; index++) {
  18922. if (offset >= totalIndices) {
  18923. break;
  18924. }
  18925. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  18926. offset += subdivisionSize;
  18927. }
  18928. this.synchronizeInstances();
  18929. };
  18930. /**
  18931. * Sets the vertex data of the mesh geometry for the requested `kind`.
  18932. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  18933. * The `data` are either a numeric array either a Float32Array.
  18934. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  18935. * 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).
  18936. * Note that a new underlying VertexBuffer object is created each call.
  18937. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  18938. *
  18939. * Possible `kind` values :
  18940. * - BABYLON.VertexBuffer.PositionKind
  18941. * - BABYLON.VertexBuffer.UVKind
  18942. * - BABYLON.VertexBuffer.UV2Kind
  18943. * - BABYLON.VertexBuffer.UV3Kind
  18944. * - BABYLON.VertexBuffer.UV4Kind
  18945. * - BABYLON.VertexBuffer.UV5Kind
  18946. * - BABYLON.VertexBuffer.UV6Kind
  18947. * - BABYLON.VertexBuffer.ColorKind
  18948. * - BABYLON.VertexBuffer.MatricesIndicesKind
  18949. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  18950. * - BABYLON.VertexBuffer.MatricesWeightsKind
  18951. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  18952. */
  18953. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  18954. if (!this._geometry) {
  18955. var vertexData = new BABYLON.VertexData();
  18956. vertexData.set(data, kind);
  18957. var scene = this.getScene();
  18958. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  18959. }
  18960. else {
  18961. this._geometry.setVerticesData(kind, data, updatable, stride);
  18962. }
  18963. };
  18964. Mesh.prototype.setVerticesBuffer = function (buffer) {
  18965. if (!this._geometry) {
  18966. var scene = this.getScene();
  18967. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene).applyToMesh(this);
  18968. }
  18969. this._geometry.setVerticesBuffer(buffer);
  18970. };
  18971. /**
  18972. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  18973. * If the mesh has no geometry, it is simply returned as it is.
  18974. * The `data` are either a numeric array either a Float32Array.
  18975. * No new underlying VertexBuffer object is created.
  18976. * 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.
  18977. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  18978. *
  18979. * Possible `kind` values :
  18980. * - BABYLON.VertexBuffer.PositionKind
  18981. * - BABYLON.VertexBuffer.UVKind
  18982. * - BABYLON.VertexBuffer.UV2Kind
  18983. * - BABYLON.VertexBuffer.UV3Kind
  18984. * - BABYLON.VertexBuffer.UV4Kind
  18985. * - BABYLON.VertexBuffer.UV5Kind
  18986. * - BABYLON.VertexBuffer.UV6Kind
  18987. * - BABYLON.VertexBuffer.ColorKind
  18988. * - BABYLON.VertexBuffer.MatricesIndicesKind
  18989. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  18990. * - BABYLON.VertexBuffer.MatricesWeightsKind
  18991. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  18992. */
  18993. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  18994. if (!this._geometry) {
  18995. return;
  18996. }
  18997. if (!makeItUnique) {
  18998. this._geometry.updateVerticesData(kind, data, updateExtends);
  18999. }
  19000. else {
  19001. this.makeGeometryUnique();
  19002. this.updateVerticesData(kind, data, updateExtends, false);
  19003. }
  19004. };
  19005. /**
  19006. * Deprecated since BabylonJS v2.3
  19007. */
  19008. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, offset, makeItUnique) {
  19009. BABYLON.Tools.Warn("Mesh.updateVerticesDataDirectly deprecated since 2.3.");
  19010. if (!this._geometry) {
  19011. return;
  19012. }
  19013. if (!makeItUnique) {
  19014. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  19015. }
  19016. else {
  19017. this.makeGeometryUnique();
  19018. this.updateVerticesDataDirectly(kind, data, offset, false);
  19019. }
  19020. };
  19021. /**
  19022. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  19023. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  19024. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  19025. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  19026. */
  19027. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  19028. if (computeNormals === void 0) { computeNormals = true; }
  19029. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19030. positionFunction(positions);
  19031. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  19032. if (computeNormals) {
  19033. var indices = this.getIndices();
  19034. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  19035. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  19036. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  19037. }
  19038. };
  19039. Mesh.prototype.makeGeometryUnique = function () {
  19040. if (!this._geometry) {
  19041. return;
  19042. }
  19043. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  19044. geometry.applyToMesh(this);
  19045. };
  19046. /**
  19047. * Sets the mesh indices.
  19048. * Expects an array populated with integers or a Int32Array.
  19049. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  19050. * This method creates a new index buffer each call.
  19051. */
  19052. Mesh.prototype.setIndices = function (indices, totalVertices) {
  19053. if (!this._geometry) {
  19054. var vertexData = new BABYLON.VertexData();
  19055. vertexData.indices = indices;
  19056. var scene = this.getScene();
  19057. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  19058. }
  19059. else {
  19060. this._geometry.setIndices(indices, totalVertices);
  19061. }
  19062. };
  19063. /**
  19064. * Invert the geometry to move from a right handed system to a left handed one.
  19065. */
  19066. Mesh.prototype.toLeftHanded = function () {
  19067. if (!this._geometry) {
  19068. return;
  19069. }
  19070. this._geometry.toLeftHanded();
  19071. };
  19072. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  19073. var engine = this.getScene().getEngine();
  19074. // Wireframe
  19075. var indexToBind;
  19076. if (this._unIndexed) {
  19077. indexToBind = null;
  19078. }
  19079. else {
  19080. switch (fillMode) {
  19081. case BABYLON.Material.PointFillMode:
  19082. indexToBind = null;
  19083. break;
  19084. case BABYLON.Material.WireFrameFillMode:
  19085. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  19086. break;
  19087. default:
  19088. case BABYLON.Material.TriangleFillMode:
  19089. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  19090. break;
  19091. }
  19092. }
  19093. // VBOs
  19094. engine.bindBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  19095. };
  19096. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  19097. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  19098. return;
  19099. }
  19100. this.onBeforeDrawObservable.notifyObservers(this);
  19101. var engine = this.getScene().getEngine();
  19102. // Draw order
  19103. switch (fillMode) {
  19104. case BABYLON.Material.PointFillMode:
  19105. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  19106. break;
  19107. case BABYLON.Material.WireFrameFillMode:
  19108. if (this._unIndexed) {
  19109. engine.drawUnIndexed(false, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  19110. }
  19111. else {
  19112. engine.draw(false, 0, instancesCount > 0 ? subMesh.linesIndexCount / 2 : subMesh.linesIndexCount, instancesCount);
  19113. }
  19114. break;
  19115. default:
  19116. if (this._unIndexed) {
  19117. engine.drawUnIndexed(true, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  19118. }
  19119. else {
  19120. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  19121. }
  19122. }
  19123. };
  19124. /**
  19125. * Registers for this mesh a javascript function called just before the rendering process.
  19126. * This function is passed the current mesh and doesn't return anything.
  19127. */
  19128. Mesh.prototype.registerBeforeRender = function (func) {
  19129. this.onBeforeRenderObservable.add(func);
  19130. };
  19131. /**
  19132. * Disposes a previously registered javascript function called before the rendering.
  19133. * This function is passed the current mesh and doesn't return anything.
  19134. */
  19135. Mesh.prototype.unregisterBeforeRender = function (func) {
  19136. this.onBeforeRenderObservable.removeCallback(func);
  19137. };
  19138. /**
  19139. * Registers for this mesh a javascript function called just after the rendering is complete.
  19140. * This function is passed the current mesh and doesn't return anything.
  19141. */
  19142. Mesh.prototype.registerAfterRender = function (func) {
  19143. this.onAfterRenderObservable.add(func);
  19144. };
  19145. /**
  19146. * Disposes a previously registered javascript function called after the rendering.
  19147. * This function is passed the current mesh and doesn't return anything.
  19148. */
  19149. Mesh.prototype.unregisterAfterRender = function (func) {
  19150. this.onAfterRenderObservable.removeCallback(func);
  19151. };
  19152. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  19153. var scene = this.getScene();
  19154. this._batchCache.mustReturn = false;
  19155. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  19156. this._batchCache.visibleInstances[subMeshId] = null;
  19157. if (this._visibleInstances) {
  19158. var currentRenderId = scene.getRenderId();
  19159. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  19160. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  19161. var selfRenderId = this._renderId;
  19162. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  19163. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  19164. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  19165. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  19166. }
  19167. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  19168. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  19169. this._batchCache.mustReturn = true;
  19170. return this._batchCache;
  19171. }
  19172. if (currentRenderId !== selfRenderId) {
  19173. this._batchCache.renderSelf[subMeshId] = false;
  19174. }
  19175. }
  19176. this._renderIdForInstances[subMeshId] = currentRenderId;
  19177. }
  19178. return this._batchCache;
  19179. };
  19180. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  19181. var visibleInstances = batch.visibleInstances[subMesh._id];
  19182. var matricesCount = visibleInstances.length + 1;
  19183. var bufferSize = matricesCount * 16 * 4;
  19184. var currentInstancesBufferSize = this._instancesBufferSize;
  19185. var instancesBuffer = this._instancesBuffer;
  19186. while (this._instancesBufferSize < bufferSize) {
  19187. this._instancesBufferSize *= 2;
  19188. }
  19189. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  19190. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  19191. }
  19192. var offset = 0;
  19193. var instancesCount = 0;
  19194. var world = this.getWorldMatrix();
  19195. if (batch.renderSelf[subMesh._id]) {
  19196. world.copyToArray(this._instancesData, offset);
  19197. offset += 16;
  19198. instancesCount++;
  19199. }
  19200. if (visibleInstances) {
  19201. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  19202. var instance = visibleInstances[instanceIndex];
  19203. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  19204. offset += 16;
  19205. instancesCount++;
  19206. }
  19207. }
  19208. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  19209. if (instancesBuffer) {
  19210. instancesBuffer.dispose();
  19211. }
  19212. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  19213. this._instancesBuffer = instancesBuffer;
  19214. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  19215. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  19216. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  19217. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  19218. }
  19219. else {
  19220. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  19221. }
  19222. engine.bindBuffers(this.geometry.getVertexBuffers(), this.geometry.getIndexBuffer(), effect);
  19223. this._draw(subMesh, fillMode, instancesCount);
  19224. engine.unbindInstanceAttributes();
  19225. };
  19226. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  19227. var scene = this.getScene();
  19228. var engine = scene.getEngine();
  19229. if (hardwareInstancedRendering) {
  19230. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  19231. }
  19232. else {
  19233. if (batch.renderSelf[subMesh._id]) {
  19234. // Draw
  19235. if (onBeforeDraw) {
  19236. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  19237. }
  19238. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  19239. }
  19240. if (batch.visibleInstances[subMesh._id]) {
  19241. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  19242. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  19243. // World
  19244. var world = instance.getWorldMatrix();
  19245. if (onBeforeDraw) {
  19246. onBeforeDraw(true, world, effectiveMaterial);
  19247. }
  19248. // Draw
  19249. this._draw(subMesh, fillMode);
  19250. }
  19251. }
  19252. }
  19253. };
  19254. /**
  19255. * Triggers the draw call for the mesh.
  19256. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  19257. */
  19258. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  19259. var scene = this.getScene();
  19260. // Managing instances
  19261. var batch = this._getInstancesRenderList(subMesh._id);
  19262. if (batch.mustReturn) {
  19263. return;
  19264. }
  19265. // Checking geometry state
  19266. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  19267. return;
  19268. }
  19269. var callbackIndex;
  19270. this.onBeforeRenderObservable.notifyObservers(this);
  19271. var engine = scene.getEngine();
  19272. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  19273. // Material
  19274. var effectiveMaterial = subMesh.getMaterial();
  19275. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  19276. return;
  19277. }
  19278. // Outline - step 1
  19279. var savedDepthWrite = engine.getDepthWrite();
  19280. if (this.renderOutline) {
  19281. engine.setDepthWrite(false);
  19282. scene.getOutlineRenderer().render(subMesh, batch);
  19283. engine.setDepthWrite(savedDepthWrite);
  19284. }
  19285. effectiveMaterial._preBind();
  19286. var effect = effectiveMaterial.getEffect();
  19287. // Bind
  19288. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  19289. this._bind(subMesh, effect, fillMode);
  19290. var world = this.getWorldMatrix();
  19291. effectiveMaterial.bind(world, this);
  19292. // Alpha mode
  19293. if (enableAlphaMode) {
  19294. engine.setAlphaMode(effectiveMaterial.alphaMode);
  19295. }
  19296. // Draw
  19297. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw);
  19298. // Unbind
  19299. effectiveMaterial.unbind();
  19300. // Outline - step 2
  19301. if (this.renderOutline && savedDepthWrite) {
  19302. engine.setDepthWrite(true);
  19303. engine.setColorWrite(false);
  19304. scene.getOutlineRenderer().render(subMesh, batch);
  19305. engine.setColorWrite(true);
  19306. }
  19307. // Overlay
  19308. if (this.renderOverlay) {
  19309. var currentMode = engine.getAlphaMode();
  19310. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  19311. scene.getOutlineRenderer().render(subMesh, batch, true);
  19312. engine.setAlphaMode(currentMode);
  19313. }
  19314. this.onAfterRenderObservable.notifyObservers(this);
  19315. };
  19316. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  19317. if (isInstance) {
  19318. effectiveMaterial.bindOnlyWorldMatrix(world);
  19319. }
  19320. };
  19321. /**
  19322. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  19323. */
  19324. Mesh.prototype.getEmittedParticleSystems = function () {
  19325. var results = new Array();
  19326. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  19327. var particleSystem = this.getScene().particleSystems[index];
  19328. if (particleSystem.emitter === this) {
  19329. results.push(particleSystem);
  19330. }
  19331. }
  19332. return results;
  19333. };
  19334. /**
  19335. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  19336. */
  19337. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  19338. var results = new Array();
  19339. var descendants = this.getDescendants();
  19340. descendants.push(this);
  19341. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  19342. var particleSystem = this.getScene().particleSystems[index];
  19343. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  19344. results.push(particleSystem);
  19345. }
  19346. }
  19347. return results;
  19348. };
  19349. Mesh.prototype._checkDelayState = function () {
  19350. var scene = this.getScene();
  19351. if (this._geometry) {
  19352. this._geometry.load(scene);
  19353. }
  19354. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  19355. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  19356. this._queueLoad(this, scene);
  19357. }
  19358. };
  19359. Mesh.prototype._queueLoad = function (mesh, scene) {
  19360. var _this = this;
  19361. scene._addPendingData(mesh);
  19362. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  19363. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  19364. if (data instanceof ArrayBuffer) {
  19365. _this._delayLoadingFunction(data, _this);
  19366. }
  19367. else {
  19368. _this._delayLoadingFunction(JSON.parse(data), _this);
  19369. }
  19370. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  19371. scene._removePendingData(_this);
  19372. }, function () { }, scene.database, getBinaryData);
  19373. };
  19374. /**
  19375. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  19376. */
  19377. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  19378. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  19379. return false;
  19380. }
  19381. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  19382. return false;
  19383. }
  19384. this._checkDelayState();
  19385. return true;
  19386. };
  19387. /**
  19388. * Sets the mesh material by the material or multiMaterial `id` property.
  19389. * The material `id` is a string identifying the material or the multiMaterial.
  19390. * This method returns nothing.
  19391. */
  19392. Mesh.prototype.setMaterialByID = function (id) {
  19393. var materials = this.getScene().materials;
  19394. var index;
  19395. for (index = 0; index < materials.length; index++) {
  19396. if (materials[index].id === id) {
  19397. this.material = materials[index];
  19398. return;
  19399. }
  19400. }
  19401. // Multi
  19402. var multiMaterials = this.getScene().multiMaterials;
  19403. for (index = 0; index < multiMaterials.length; index++) {
  19404. if (multiMaterials[index].id === id) {
  19405. this.material = multiMaterials[index];
  19406. return;
  19407. }
  19408. }
  19409. };
  19410. /**
  19411. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  19412. */
  19413. Mesh.prototype.getAnimatables = function () {
  19414. var results = [];
  19415. if (this.material) {
  19416. results.push(this.material);
  19417. }
  19418. if (this.skeleton) {
  19419. results.push(this.skeleton);
  19420. }
  19421. return results;
  19422. };
  19423. /**
  19424. * Modifies the mesh geometry according to the passed transformation matrix.
  19425. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  19426. * The mesh normals are modified accordingly the same transformation.
  19427. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  19428. * Note that, under the hood, this method sets a new VertexBuffer each call.
  19429. */
  19430. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  19431. // Position
  19432. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  19433. return;
  19434. }
  19435. var submeshes = this.subMeshes.splice(0);
  19436. this._resetPointsArrayCache();
  19437. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19438. var temp = [];
  19439. var index;
  19440. for (index = 0; index < data.length; index += 3) {
  19441. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  19442. }
  19443. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  19444. // Normals
  19445. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  19446. return;
  19447. }
  19448. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  19449. temp = [];
  19450. for (index = 0; index < data.length; index += 3) {
  19451. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  19452. }
  19453. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  19454. // flip faces?
  19455. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  19456. this.flipFaces();
  19457. }
  19458. // Restore submeshes
  19459. this.releaseSubMeshes();
  19460. this.subMeshes = submeshes;
  19461. };
  19462. /**
  19463. * Modifies the mesh geometry according to its own current World Matrix.
  19464. * The mesh World Matrix is then reset.
  19465. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  19466. * tuto : tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  19467. * Note that, under the hood, this method sets a new VertexBuffer each call.
  19468. */
  19469. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  19470. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  19471. this.scaling.copyFromFloats(1, 1, 1);
  19472. this.position.copyFromFloats(0, 0, 0);
  19473. this.rotation.copyFromFloats(0, 0, 0);
  19474. //only if quaternion is already set
  19475. if (this.rotationQuaternion) {
  19476. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  19477. }
  19478. this._worldMatrix = BABYLON.Matrix.Identity();
  19479. };
  19480. // Cache
  19481. Mesh.prototype._resetPointsArrayCache = function () {
  19482. this._positions = null;
  19483. };
  19484. Mesh.prototype._generatePointsArray = function () {
  19485. if (this._positions)
  19486. return true;
  19487. this._positions = [];
  19488. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19489. if (!data) {
  19490. return false;
  19491. }
  19492. for (var index = 0; index < data.length; index += 3) {
  19493. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  19494. }
  19495. return true;
  19496. };
  19497. /**
  19498. * Returns a new Mesh object generated from the current mesh properties.
  19499. * This method must not get confused with createInstance().
  19500. * The parameter `name` is a string, the name given to the new mesh.
  19501. * The optional parameter `newParent` can be any Node object (default `null`).
  19502. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  19503. * 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.
  19504. */
  19505. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  19506. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  19507. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  19508. };
  19509. /**
  19510. * Disposes the mesh.
  19511. * This also frees the memory allocated under the hood to all the buffers used by WebGL.
  19512. */
  19513. Mesh.prototype.dispose = function (doNotRecurse) {
  19514. if (this._geometry) {
  19515. this._geometry.releaseForMesh(this, true);
  19516. }
  19517. // Instances
  19518. if (this._instancesBuffer) {
  19519. this._instancesBuffer.dispose();
  19520. this._instancesBuffer = null;
  19521. }
  19522. while (this.instances.length) {
  19523. this.instances[0].dispose();
  19524. }
  19525. _super.prototype.dispose.call(this, doNotRecurse);
  19526. };
  19527. /**
  19528. * Modifies the mesh geometry according to a displacement map.
  19529. * 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.
  19530. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  19531. * This method returns nothing.
  19532. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  19533. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  19534. * 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.
  19535. */
  19536. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess) {
  19537. var _this = this;
  19538. var scene = this.getScene();
  19539. var onload = function (img) {
  19540. // Getting height map data
  19541. var canvas = document.createElement("canvas");
  19542. var context = canvas.getContext("2d");
  19543. var heightMapWidth = img.width;
  19544. var heightMapHeight = img.height;
  19545. canvas.width = heightMapWidth;
  19546. canvas.height = heightMapHeight;
  19547. context.drawImage(img, 0, 0);
  19548. // Create VertexData from map data
  19549. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  19550. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  19551. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  19552. //execute success callback, if set
  19553. if (onSuccess) {
  19554. onSuccess(_this);
  19555. }
  19556. };
  19557. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  19558. };
  19559. /**
  19560. * Modifies the mesh geometry according to a displacementMap buffer.
  19561. * 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.
  19562. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  19563. * This method returns nothing.
  19564. * 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.
  19565. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  19566. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  19567. */
  19568. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  19569. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  19570. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  19571. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  19572. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  19573. return;
  19574. }
  19575. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19576. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  19577. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  19578. var position = BABYLON.Vector3.Zero();
  19579. var normal = BABYLON.Vector3.Zero();
  19580. var uv = BABYLON.Vector2.Zero();
  19581. for (var index = 0; index < positions.length; index += 3) {
  19582. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  19583. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  19584. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  19585. // Compute height
  19586. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  19587. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  19588. var pos = (u + v * heightMapWidth) * 4;
  19589. var r = buffer[pos] / 255.0;
  19590. var g = buffer[pos + 1] / 255.0;
  19591. var b = buffer[pos + 2] / 255.0;
  19592. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  19593. normal.normalize();
  19594. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  19595. position = position.add(normal);
  19596. position.toArray(positions, index);
  19597. }
  19598. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  19599. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  19600. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  19601. };
  19602. /**
  19603. * Modify the mesh to get a flat shading rendering.
  19604. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  19605. * This method returns nothing.
  19606. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  19607. */
  19608. Mesh.prototype.convertToFlatShadedMesh = function () {
  19609. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  19610. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  19611. var kinds = this.getVerticesDataKinds();
  19612. var vbs = [];
  19613. var data = [];
  19614. var newdata = [];
  19615. var updatableNormals = false;
  19616. var kindIndex;
  19617. var kind;
  19618. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  19619. kind = kinds[kindIndex];
  19620. var vertexBuffer = this.getVertexBuffer(kind);
  19621. if (kind === BABYLON.VertexBuffer.NormalKind) {
  19622. updatableNormals = vertexBuffer.isUpdatable();
  19623. kinds.splice(kindIndex, 1);
  19624. kindIndex--;
  19625. continue;
  19626. }
  19627. vbs[kind] = vertexBuffer;
  19628. data[kind] = vbs[kind].getData();
  19629. newdata[kind] = [];
  19630. }
  19631. // Save previous submeshes
  19632. var previousSubmeshes = this.subMeshes.slice(0);
  19633. var indices = this.getIndices();
  19634. var totalIndices = this.getTotalIndices();
  19635. // Generating unique vertices per face
  19636. var index;
  19637. for (index = 0; index < totalIndices; index++) {
  19638. var vertexIndex = indices[index];
  19639. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  19640. kind = kinds[kindIndex];
  19641. var stride = vbs[kind].getStrideSize();
  19642. for (var offset = 0; offset < stride; offset++) {
  19643. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  19644. }
  19645. }
  19646. }
  19647. // Updating faces & normal
  19648. var normals = [];
  19649. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  19650. for (index = 0; index < totalIndices; index += 3) {
  19651. indices[index] = index;
  19652. indices[index + 1] = index + 1;
  19653. indices[index + 2] = index + 2;
  19654. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  19655. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  19656. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  19657. var p1p2 = p1.subtract(p2);
  19658. var p3p2 = p3.subtract(p2);
  19659. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  19660. // Store same normals for every vertex
  19661. for (var localIndex = 0; localIndex < 3; localIndex++) {
  19662. normals.push(normal.x);
  19663. normals.push(normal.y);
  19664. normals.push(normal.z);
  19665. }
  19666. }
  19667. this.setIndices(indices);
  19668. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  19669. // Updating vertex buffers
  19670. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  19671. kind = kinds[kindIndex];
  19672. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  19673. }
  19674. // Updating submeshes
  19675. this.releaseSubMeshes();
  19676. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  19677. var previousOne = previousSubmeshes[submeshIndex];
  19678. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  19679. }
  19680. this.synchronizeInstances();
  19681. };
  19682. /**
  19683. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  19684. * In other words, more vertices, no more indices and a single bigger VBO.
  19685. * This method returns nothing.
  19686. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  19687. *
  19688. */
  19689. Mesh.prototype.convertToUnIndexedMesh = function () {
  19690. /// <summary>Remove indices by unfolding faces into buffers</summary>
  19691. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  19692. var kinds = this.getVerticesDataKinds();
  19693. var vbs = [];
  19694. var data = [];
  19695. var newdata = [];
  19696. var updatableNormals = false;
  19697. var kindIndex;
  19698. var kind;
  19699. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  19700. kind = kinds[kindIndex];
  19701. var vertexBuffer = this.getVertexBuffer(kind);
  19702. vbs[kind] = vertexBuffer;
  19703. data[kind] = vbs[kind].getData();
  19704. newdata[kind] = [];
  19705. }
  19706. // Save previous submeshes
  19707. var previousSubmeshes = this.subMeshes.slice(0);
  19708. var indices = this.getIndices();
  19709. var totalIndices = this.getTotalIndices();
  19710. // Generating unique vertices per face
  19711. var index;
  19712. for (index = 0; index < totalIndices; index++) {
  19713. var vertexIndex = indices[index];
  19714. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  19715. kind = kinds[kindIndex];
  19716. var stride = vbs[kind].getStrideSize();
  19717. for (var offset = 0; offset < stride; offset++) {
  19718. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  19719. }
  19720. }
  19721. }
  19722. // Updating indices
  19723. for (index = 0; index < totalIndices; index += 3) {
  19724. indices[index] = index;
  19725. indices[index + 1] = index + 1;
  19726. indices[index + 2] = index + 2;
  19727. }
  19728. this.setIndices(indices);
  19729. // Updating vertex buffers
  19730. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  19731. kind = kinds[kindIndex];
  19732. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  19733. }
  19734. // Updating submeshes
  19735. this.releaseSubMeshes();
  19736. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  19737. var previousOne = previousSubmeshes[submeshIndex];
  19738. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  19739. }
  19740. this._unIndexed = true;
  19741. this.synchronizeInstances();
  19742. };
  19743. /**
  19744. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  19745. * This method returns nothing.
  19746. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  19747. */
  19748. Mesh.prototype.flipFaces = function (flipNormals) {
  19749. if (flipNormals === void 0) { flipNormals = false; }
  19750. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  19751. var i;
  19752. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  19753. for (i = 0; i < vertex_data.normals.length; i++) {
  19754. vertex_data.normals[i] *= -1;
  19755. }
  19756. }
  19757. var temp;
  19758. for (i = 0; i < vertex_data.indices.length; i += 3) {
  19759. // reassign indices
  19760. temp = vertex_data.indices[i + 1];
  19761. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  19762. vertex_data.indices[i + 2] = temp;
  19763. }
  19764. vertex_data.applyToMesh(this);
  19765. };
  19766. // Instances
  19767. /**
  19768. * Creates a new InstancedMesh object from the mesh model.
  19769. * An instance shares the same properties and the same material than its model.
  19770. * Only these properties of each instance can then be set individually :
  19771. * - position
  19772. * - rotation
  19773. * - rotationQuaternion
  19774. * - setPivotMatrix
  19775. * - scaling
  19776. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  19777. * Warning : this method is not supported for Line mesh and LineSystem
  19778. */
  19779. Mesh.prototype.createInstance = function (name) {
  19780. return new BABYLON.InstancedMesh(name, this);
  19781. };
  19782. /**
  19783. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  19784. * After this call, all the mesh instances have the same submeshes than the current mesh.
  19785. * This method returns nothing.
  19786. */
  19787. Mesh.prototype.synchronizeInstances = function () {
  19788. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  19789. var instance = this.instances[instanceIndex];
  19790. instance._syncSubMeshes();
  19791. }
  19792. };
  19793. /**
  19794. * Simplify the mesh according to the given array of settings.
  19795. * Function will return immediately and will simplify async. It returns nothing.
  19796. * @param settings a collection of simplification settings.
  19797. * @param parallelProcessing should all levels calculate parallel or one after the other.
  19798. * @param type the type of simplification to run.
  19799. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  19800. */
  19801. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  19802. if (parallelProcessing === void 0) { parallelProcessing = true; }
  19803. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  19804. this.getScene().simplificationQueue.addTask({
  19805. settings: settings,
  19806. parallelProcessing: parallelProcessing,
  19807. mesh: this,
  19808. simplificationType: simplificationType,
  19809. successCallback: successCallback
  19810. });
  19811. };
  19812. /**
  19813. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  19814. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  19815. * This should be used together with the simplification to avoid disappearing triangles.
  19816. * @param successCallback an optional success callback to be called after the optimization finished.
  19817. */
  19818. Mesh.prototype.optimizeIndices = function (successCallback) {
  19819. var _this = this;
  19820. var indices = this.getIndices();
  19821. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19822. var vectorPositions = [];
  19823. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  19824. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  19825. }
  19826. var dupes = [];
  19827. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  19828. var realPos = vectorPositions.length - 1 - iteration;
  19829. var testedPosition = vectorPositions[realPos];
  19830. for (var j = 0; j < realPos; ++j) {
  19831. var againstPosition = vectorPositions[j];
  19832. if (testedPosition.equals(againstPosition)) {
  19833. dupes[realPos] = j;
  19834. break;
  19835. }
  19836. }
  19837. }, function () {
  19838. for (var i = 0; i < indices.length; ++i) {
  19839. indices[i] = dupes[indices[i]] || indices[i];
  19840. }
  19841. //indices are now reordered
  19842. var originalSubMeshes = _this.subMeshes.slice(0);
  19843. _this.setIndices(indices);
  19844. _this.subMeshes = originalSubMeshes;
  19845. if (successCallback) {
  19846. successCallback(_this);
  19847. }
  19848. });
  19849. };
  19850. // Statics
  19851. /**
  19852. * Returns a new Mesh object what is a deep copy of the passed mesh.
  19853. * The parameter `parsedMesh` is the mesh to be copied.
  19854. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  19855. */
  19856. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  19857. var mesh = new Mesh(parsedMesh.name, scene);
  19858. mesh.id = parsedMesh.id;
  19859. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  19860. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  19861. if (parsedMesh.rotationQuaternion) {
  19862. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  19863. }
  19864. else if (parsedMesh.rotation) {
  19865. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  19866. }
  19867. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  19868. if (parsedMesh.localMatrix) {
  19869. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  19870. }
  19871. else if (parsedMesh.pivotMatrix) {
  19872. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  19873. }
  19874. mesh.setEnabled(parsedMesh.isEnabled);
  19875. mesh.isVisible = parsedMesh.isVisible;
  19876. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  19877. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  19878. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  19879. if (parsedMesh.applyFog !== undefined) {
  19880. mesh.applyFog = parsedMesh.applyFog;
  19881. }
  19882. if (parsedMesh.pickable !== undefined) {
  19883. mesh.isPickable = parsedMesh.pickable;
  19884. }
  19885. if (parsedMesh.alphaIndex !== undefined) {
  19886. mesh.alphaIndex = parsedMesh.alphaIndex;
  19887. }
  19888. mesh.receiveShadows = parsedMesh.receiveShadows;
  19889. mesh.billboardMode = parsedMesh.billboardMode;
  19890. if (parsedMesh.visibility !== undefined) {
  19891. mesh.visibility = parsedMesh.visibility;
  19892. }
  19893. mesh.checkCollisions = parsedMesh.checkCollisions;
  19894. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  19895. // freezeWorldMatrix
  19896. if (parsedMesh.freezeWorldMatrix) {
  19897. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  19898. }
  19899. // Parent
  19900. if (parsedMesh.parentId) {
  19901. mesh._waitingParentId = parsedMesh.parentId;
  19902. }
  19903. // Actions
  19904. if (parsedMesh.actions !== undefined) {
  19905. mesh._waitingActions = parsedMesh.actions;
  19906. }
  19907. // Geometry
  19908. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  19909. if (parsedMesh.delayLoadingFile) {
  19910. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  19911. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  19912. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  19913. if (parsedMesh._binaryInfo) {
  19914. mesh._binaryInfo = parsedMesh._binaryInfo;
  19915. }
  19916. mesh._delayInfo = [];
  19917. if (parsedMesh.hasUVs) {
  19918. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  19919. }
  19920. if (parsedMesh.hasUVs2) {
  19921. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  19922. }
  19923. if (parsedMesh.hasUVs3) {
  19924. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  19925. }
  19926. if (parsedMesh.hasUVs4) {
  19927. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  19928. }
  19929. if (parsedMesh.hasUVs5) {
  19930. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  19931. }
  19932. if (parsedMesh.hasUVs6) {
  19933. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  19934. }
  19935. if (parsedMesh.hasColors) {
  19936. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  19937. }
  19938. if (parsedMesh.hasMatricesIndices) {
  19939. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  19940. }
  19941. if (parsedMesh.hasMatricesWeights) {
  19942. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  19943. }
  19944. mesh._delayLoadingFunction = BABYLON.Geometry.ImportGeometry;
  19945. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  19946. mesh._checkDelayState();
  19947. }
  19948. }
  19949. else {
  19950. BABYLON.Geometry.ImportGeometry(parsedMesh, mesh);
  19951. }
  19952. // Material
  19953. if (parsedMesh.materialId) {
  19954. mesh.setMaterialByID(parsedMesh.materialId);
  19955. }
  19956. else {
  19957. mesh.material = null;
  19958. }
  19959. // Skeleton
  19960. if (parsedMesh.skeletonId > -1) {
  19961. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  19962. if (parsedMesh.numBoneInfluencers) {
  19963. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  19964. }
  19965. }
  19966. // Animations
  19967. if (parsedMesh.animations) {
  19968. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  19969. var parsedAnimation = parsedMesh.animations[animationIndex];
  19970. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  19971. }
  19972. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  19973. }
  19974. if (parsedMesh.autoAnimate) {
  19975. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  19976. }
  19977. // Layer Mask
  19978. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  19979. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  19980. }
  19981. else {
  19982. mesh.layerMask = 0x0FFFFFFF;
  19983. }
  19984. //(Deprecated) physics
  19985. if (parsedMesh.physicsImpostor) {
  19986. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  19987. mass: parsedMesh.physicsMass,
  19988. friction: parsedMesh.physicsFriction,
  19989. restitution: parsedMesh.physicsRestitution
  19990. }, scene);
  19991. }
  19992. // Instances
  19993. if (parsedMesh.instances) {
  19994. for (var index = 0; index < parsedMesh.instances.length; index++) {
  19995. var parsedInstance = parsedMesh.instances[index];
  19996. var instance = mesh.createInstance(parsedInstance.name);
  19997. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  19998. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  19999. if (parsedInstance.rotationQuaternion) {
  20000. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  20001. }
  20002. else if (parsedInstance.rotation) {
  20003. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  20004. }
  20005. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  20006. instance.checkCollisions = mesh.checkCollisions;
  20007. if (parsedMesh.animations) {
  20008. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  20009. parsedAnimation = parsedMesh.animations[animationIndex];
  20010. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  20011. }
  20012. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  20013. }
  20014. }
  20015. }
  20016. return mesh;
  20017. };
  20018. /**
  20019. * Creates a ribbon mesh.
  20020. * Please consider using the same method from the MeshBuilder class instead.
  20021. * 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.
  20022. *
  20023. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  20024. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  20025. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  20026. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  20027. * 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.
  20028. * 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.
  20029. * 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
  20030. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20031. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20032. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20033. */
  20034. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  20035. return BABYLON.MeshBuilder.CreateRibbon(name, {
  20036. pathArray: pathArray,
  20037. closeArray: closeArray,
  20038. closePath: closePath,
  20039. offset: offset,
  20040. updatable: updatable,
  20041. sideOrientation: sideOrientation,
  20042. instance: instance
  20043. }, scene);
  20044. };
  20045. /**
  20046. * Creates a plane polygonal mesh. By default, this is a disc.
  20047. * Please consider using the same method from the MeshBuilder class instead.
  20048. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  20049. * 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.
  20050. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20051. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20052. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20053. */
  20054. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  20055. var options = {
  20056. radius: radius,
  20057. tessellation: tessellation,
  20058. sideOrientation: sideOrientation,
  20059. updatable: updatable
  20060. };
  20061. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  20062. };
  20063. /**
  20064. * Creates a box mesh.
  20065. * Please consider using the same method from the MeshBuilder class instead.
  20066. * The parameter `size` sets the size (float) of each box side (default 1).
  20067. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20068. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20069. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20070. */
  20071. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  20072. var options = {
  20073. size: size,
  20074. sideOrientation: sideOrientation,
  20075. updatable: updatable
  20076. };
  20077. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  20078. };
  20079. /**
  20080. * Creates a sphere mesh.
  20081. * Please consider using the same method from the MeshBuilder class instead.
  20082. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  20083. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  20084. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20085. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20086. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20087. */
  20088. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  20089. var options = {
  20090. segments: segments,
  20091. diameterX: diameter,
  20092. diameterY: diameter,
  20093. diameterZ: diameter,
  20094. sideOrientation: sideOrientation,
  20095. updatable: updatable
  20096. };
  20097. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  20098. };
  20099. /**
  20100. * Creates a cylinder or a cone mesh.
  20101. * Please consider using the same method from the MeshBuilder class instead.
  20102. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  20103. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  20104. * 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.
  20105. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  20106. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  20107. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20108. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20109. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20110. */
  20111. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  20112. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  20113. if (scene !== undefined) {
  20114. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  20115. updatable = scene;
  20116. }
  20117. scene = subdivisions;
  20118. subdivisions = 1;
  20119. }
  20120. var options = {
  20121. height: height,
  20122. diameterTop: diameterTop,
  20123. diameterBottom: diameterBottom,
  20124. tessellation: tessellation,
  20125. subdivisions: subdivisions,
  20126. sideOrientation: sideOrientation,
  20127. updatable: updatable
  20128. };
  20129. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  20130. };
  20131. // Torus (Code from SharpDX.org)
  20132. /**
  20133. * Creates a torus mesh.
  20134. * Please consider using the same method from the MeshBuilder class instead.
  20135. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  20136. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  20137. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  20138. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20139. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20140. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20141. */
  20142. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  20143. var options = {
  20144. diameter: diameter,
  20145. thickness: thickness,
  20146. tessellation: tessellation,
  20147. sideOrientation: sideOrientation,
  20148. updatable: updatable
  20149. };
  20150. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  20151. };
  20152. /**
  20153. * Creates a torus knot mesh.
  20154. * Please consider using the same method from the MeshBuilder class instead.
  20155. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  20156. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  20157. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  20158. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  20159. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20160. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20161. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20162. */
  20163. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  20164. var options = {
  20165. radius: radius,
  20166. tube: tube,
  20167. radialSegments: radialSegments,
  20168. tubularSegments: tubularSegments,
  20169. p: p,
  20170. q: q,
  20171. sideOrientation: sideOrientation,
  20172. updatable: updatable
  20173. };
  20174. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  20175. };
  20176. /**
  20177. * Creates a line mesh.
  20178. * Please consider using the same method from the MeshBuilder class instead.
  20179. * 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.
  20180. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  20181. * The parameter `points` is an array successive Vector3.
  20182. * 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
  20183. * When updating an instance, remember that only point positions can change, not the number of points.
  20184. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20185. */
  20186. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  20187. var options = {
  20188. points: points,
  20189. updatable: updatable,
  20190. instance: instance
  20191. };
  20192. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  20193. };
  20194. /**
  20195. * Creates a dashed line mesh.
  20196. * Please consider using the same method from the MeshBuilder class instead.
  20197. * 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.
  20198. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  20199. * The parameter `points` is an array successive Vector3.
  20200. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  20201. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  20202. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  20203. * 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
  20204. * When updating an instance, remember that only point positions can change, not the number of points.
  20205. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20206. */
  20207. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  20208. var options = {
  20209. points: points,
  20210. dashSize: dashSize,
  20211. gapSize: gapSize,
  20212. dashNb: dashNb,
  20213. updatable: updatable,
  20214. instance: instance
  20215. };
  20216. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  20217. };
  20218. /**
  20219. * Creates an extruded shape mesh.
  20220. * 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.
  20221. * Please consider using the same method from the MeshBuilder class instead.
  20222. *
  20223. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  20224. * 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
  20225. * extruded along the Z axis.
  20226. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  20227. * 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.
  20228. * The parameter `scale` (float, default 1) is the value to scale the shape.
  20229. * 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
  20230. * 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
  20231. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  20232. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20233. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20234. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20235. */
  20236. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  20237. var options = {
  20238. shape: shape,
  20239. path: path,
  20240. scale: scale,
  20241. rotation: rotation,
  20242. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  20243. sideOrientation: sideOrientation,
  20244. instance: instance,
  20245. updatable: updatable
  20246. };
  20247. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  20248. };
  20249. /**
  20250. * Creates an custom extruded shape mesh.
  20251. * 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.
  20252. * Please consider using the same method from the MeshBuilder class instead.
  20253. *
  20254. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  20255. * 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
  20256. * extruded along the Z axis.
  20257. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  20258. * 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
  20259. * and the distance of this point from the begining of the path :
  20260. * ```javascript
  20261. * var rotationFunction = function(i, distance) {
  20262. * // do things
  20263. * return rotationValue; }
  20264. * ```
  20265. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  20266. * 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
  20267. * and the distance of this point from the begining of the path :
  20268. * ```javascript
  20269. * var scaleFunction = function(i, distance) {
  20270. * // do things
  20271. * return scaleValue;}
  20272. * ```
  20273. * It must returns a float value that will be the scale value applied to the shape on each path point.
  20274. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  20275. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  20276. * 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
  20277. * 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
  20278. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  20279. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20280. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20281. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20282. */
  20283. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  20284. var options = {
  20285. shape: shape,
  20286. path: path,
  20287. scaleFunction: scaleFunction,
  20288. rotationFunction: rotationFunction,
  20289. ribbonCloseArray: ribbonCloseArray,
  20290. ribbonClosePath: ribbonClosePath,
  20291. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  20292. sideOrientation: sideOrientation,
  20293. instance: instance,
  20294. updatable: updatable
  20295. };
  20296. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  20297. };
  20298. /**
  20299. * Creates lathe mesh.
  20300. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  20301. * Please consider using the same method from the MeshBuilder class instead.
  20302. * 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
  20303. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  20304. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  20305. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  20306. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20307. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20308. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20309. */
  20310. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  20311. var options = {
  20312. shape: shape,
  20313. radius: radius,
  20314. tessellation: tessellation,
  20315. sideOrientation: sideOrientation,
  20316. updatable: updatable
  20317. };
  20318. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  20319. };
  20320. /**
  20321. * Creates a plane mesh.
  20322. * Please consider using the same method from the MeshBuilder class instead.
  20323. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  20324. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20325. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20326. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20327. */
  20328. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  20329. var options = {
  20330. size: size,
  20331. width: size,
  20332. height: size,
  20333. sideOrientation: sideOrientation,
  20334. updatable: updatable
  20335. };
  20336. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  20337. };
  20338. /**
  20339. * Creates a ground mesh.
  20340. * Please consider using the same method from the MeshBuilder class instead.
  20341. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  20342. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  20343. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20344. */
  20345. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  20346. var options = {
  20347. width: width,
  20348. height: height,
  20349. subdivisions: subdivisions,
  20350. updatable: updatable
  20351. };
  20352. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  20353. };
  20354. /**
  20355. * Creates a tiled ground mesh.
  20356. * Please consider using the same method from the MeshBuilder class instead.
  20357. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  20358. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  20359. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  20360. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  20361. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  20362. * numbers of subdivisions on the ground width and height of each tile.
  20363. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20364. */
  20365. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  20366. var options = {
  20367. xmin: xmin,
  20368. zmin: zmin,
  20369. xmax: xmax,
  20370. zmax: zmax,
  20371. subdivisions: subdivisions,
  20372. precision: precision,
  20373. updatable: updatable
  20374. };
  20375. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  20376. };
  20377. /**
  20378. * Creates a ground mesh from a height map.
  20379. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  20380. * Please consider using the same method from the MeshBuilder class instead.
  20381. * The parameter `url` sets the URL of the height map image resource.
  20382. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  20383. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  20384. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  20385. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  20386. * 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).
  20387. * This function is passed the newly built mesh :
  20388. * ```javascript
  20389. * function(mesh) { // do things
  20390. * return; }
  20391. * ```
  20392. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20393. */
  20394. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  20395. var options = {
  20396. width: width,
  20397. height: height,
  20398. subdivisions: subdivisions,
  20399. minHeight: minHeight,
  20400. maxHeight: maxHeight,
  20401. updatable: updatable,
  20402. onReady: onReady
  20403. };
  20404. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  20405. };
  20406. /**
  20407. * Creates a tube mesh.
  20408. * 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.
  20409. * Please consider using the same method from the MeshBuilder class instead.
  20410. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  20411. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  20412. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  20413. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  20414. * 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.
  20415. * It must return a radius value (positive float) :
  20416. * ```javascript
  20417. * var radiusFunction = function(i, distance) {
  20418. * // do things
  20419. * return radius; }
  20420. * ```
  20421. * 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
  20422. * 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
  20423. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20424. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20425. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20426. */
  20427. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  20428. var options = {
  20429. path: path,
  20430. radius: radius,
  20431. tessellation: tessellation,
  20432. radiusFunction: radiusFunction,
  20433. arc: 1,
  20434. cap: cap,
  20435. updatable: updatable,
  20436. sideOrientation: sideOrientation,
  20437. instance: instance
  20438. };
  20439. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  20440. };
  20441. /**
  20442. * Creates a polyhedron mesh.
  20443. * Please consider using the same method from the MeshBuilder class instead.
  20444. * 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
  20445. * to choose the wanted type.
  20446. * The parameter `size` (positive float, default 1) sets the polygon size.
  20447. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  20448. * 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`.
  20449. * 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
  20450. * 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)`).
  20451. * 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
  20452. * 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.
  20453. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20454. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20455. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20456. */
  20457. Mesh.CreatePolyhedron = function (name, options, scene) {
  20458. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  20459. };
  20460. /**
  20461. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  20462. * Please consider using the same method from the MeshBuilder class instead.
  20463. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  20464. * 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`).
  20465. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  20466. * 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.
  20467. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20468. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20469. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20470. */
  20471. Mesh.CreateIcoSphere = function (name, options, scene) {
  20472. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  20473. };
  20474. /**
  20475. * Creates a decal mesh.
  20476. * Please consider using the same method from the MeshBuilder class instead.
  20477. * 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.
  20478. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  20479. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  20480. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  20481. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  20482. */
  20483. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  20484. var options = {
  20485. position: position,
  20486. normal: normal,
  20487. size: size,
  20488. angle: angle
  20489. };
  20490. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  20491. };
  20492. // Skeletons
  20493. /**
  20494. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  20495. */
  20496. Mesh.prototype.setPositionsForCPUSkinning = function () {
  20497. var source;
  20498. if (!this._sourcePositions) {
  20499. source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20500. this._sourcePositions = new Float32Array(source);
  20501. if (!this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable()) {
  20502. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  20503. }
  20504. }
  20505. return this._sourcePositions;
  20506. };
  20507. /**
  20508. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  20509. */
  20510. Mesh.prototype.setNormalsForCPUSkinning = function () {
  20511. var source;
  20512. if (!this._sourceNormals) {
  20513. source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20514. this._sourceNormals = new Float32Array(source);
  20515. if (!this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable()) {
  20516. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  20517. }
  20518. }
  20519. return this._sourceNormals;
  20520. };
  20521. /**
  20522. * Update the vertex buffers by applying transformation from the bones
  20523. * @param {skeleton} skeleton to apply
  20524. */
  20525. Mesh.prototype.applySkeleton = function (skeleton) {
  20526. if (!this.geometry) {
  20527. return;
  20528. }
  20529. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  20530. return;
  20531. }
  20532. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  20533. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  20534. return this;
  20535. }
  20536. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  20537. return this;
  20538. }
  20539. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  20540. return this;
  20541. }
  20542. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  20543. return this;
  20544. }
  20545. if (!this._sourcePositions) {
  20546. this.setPositionsForCPUSkinning();
  20547. }
  20548. if (!this._sourceNormals) {
  20549. this.setNormalsForCPUSkinning();
  20550. }
  20551. // positionsData checks for not being Float32Array will only pass at most once
  20552. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20553. if (!(positionsData instanceof Float32Array)) {
  20554. positionsData = new Float32Array(positionsData);
  20555. }
  20556. // normalsData checks for not being Float32Array will only pass at most once
  20557. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20558. if (!(normalsData instanceof Float32Array)) {
  20559. normalsData = new Float32Array(normalsData);
  20560. }
  20561. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  20562. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  20563. var needExtras = this.numBoneInfluencers > 4;
  20564. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  20565. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  20566. var skeletonMatrices = skeleton.getTransformMatrices(this);
  20567. var tempVector3 = BABYLON.Vector3.Zero();
  20568. var finalMatrix = new BABYLON.Matrix();
  20569. var tempMatrix = new BABYLON.Matrix();
  20570. var matWeightIdx = 0;
  20571. var inf;
  20572. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  20573. var weight;
  20574. for (inf = 0; inf < 4; inf++) {
  20575. weight = matricesWeightsData[matWeightIdx + inf];
  20576. if (weight > 0) {
  20577. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  20578. finalMatrix.addToSelf(tempMatrix);
  20579. }
  20580. else
  20581. break;
  20582. }
  20583. if (needExtras) {
  20584. for (inf = 0; inf < 4; inf++) {
  20585. weight = matricesWeightsExtraData[matWeightIdx + inf];
  20586. if (weight > 0) {
  20587. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  20588. finalMatrix.addToSelf(tempMatrix);
  20589. }
  20590. else
  20591. break;
  20592. }
  20593. }
  20594. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  20595. tempVector3.toArray(positionsData, index);
  20596. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  20597. tempVector3.toArray(normalsData, index);
  20598. finalMatrix.reset();
  20599. }
  20600. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  20601. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  20602. return this;
  20603. };
  20604. // Tools
  20605. /**
  20606. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  20607. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  20608. */
  20609. Mesh.MinMax = function (meshes) {
  20610. var minVector = null;
  20611. var maxVector = null;
  20612. for (var i in meshes) {
  20613. var mesh = meshes[i];
  20614. var boundingBox = mesh.getBoundingInfo().boundingBox;
  20615. if (!minVector) {
  20616. minVector = boundingBox.minimumWorld;
  20617. maxVector = boundingBox.maximumWorld;
  20618. continue;
  20619. }
  20620. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  20621. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  20622. }
  20623. return {
  20624. min: minVector,
  20625. max: maxVector
  20626. };
  20627. };
  20628. /**
  20629. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  20630. */
  20631. Mesh.Center = function (meshesOrMinMaxVector) {
  20632. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : Mesh.MinMax(meshesOrMinMaxVector);
  20633. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  20634. };
  20635. /**
  20636. * Merge the array of meshes into a single mesh for performance reasons.
  20637. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  20638. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  20639. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  20640. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  20641. */
  20642. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass) {
  20643. if (disposeSource === void 0) { disposeSource = true; }
  20644. var index;
  20645. if (!allow32BitsIndices) {
  20646. var totalVertices = 0;
  20647. // Counting vertices
  20648. for (index = 0; index < meshes.length; index++) {
  20649. if (meshes[index]) {
  20650. totalVertices += meshes[index].getTotalVertices();
  20651. if (totalVertices > 65536) {
  20652. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  20653. return null;
  20654. }
  20655. }
  20656. }
  20657. }
  20658. // Merge
  20659. var vertexData;
  20660. var otherVertexData;
  20661. var source;
  20662. for (index = 0; index < meshes.length; index++) {
  20663. if (meshes[index]) {
  20664. meshes[index].computeWorldMatrix(true);
  20665. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  20666. otherVertexData.transform(meshes[index].getWorldMatrix());
  20667. if (vertexData) {
  20668. vertexData.merge(otherVertexData);
  20669. }
  20670. else {
  20671. vertexData = otherVertexData;
  20672. source = meshes[index];
  20673. }
  20674. }
  20675. }
  20676. if (!meshSubclass) {
  20677. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  20678. }
  20679. vertexData.applyToMesh(meshSubclass);
  20680. // Setting properties
  20681. meshSubclass.material = source.material;
  20682. meshSubclass.checkCollisions = source.checkCollisions;
  20683. // Cleaning
  20684. if (disposeSource) {
  20685. for (index = 0; index < meshes.length; index++) {
  20686. if (meshes[index]) {
  20687. meshes[index].dispose();
  20688. }
  20689. }
  20690. }
  20691. return meshSubclass;
  20692. };
  20693. // Consts
  20694. Mesh._FRONTSIDE = 0;
  20695. Mesh._BACKSIDE = 1;
  20696. Mesh._DOUBLESIDE = 2;
  20697. Mesh._DEFAULTSIDE = 0;
  20698. Mesh._NO_CAP = 0;
  20699. Mesh._CAP_START = 1;
  20700. Mesh._CAP_END = 2;
  20701. Mesh._CAP_ALL = 3;
  20702. return Mesh;
  20703. })(BABYLON.AbstractMesh);
  20704. BABYLON.Mesh = Mesh;
  20705. })(BABYLON || (BABYLON = {}));
  20706. var BABYLON;
  20707. (function (BABYLON) {
  20708. var SubMesh = (function () {
  20709. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  20710. if (createBoundingBox === void 0) { createBoundingBox = true; }
  20711. this.materialIndex = materialIndex;
  20712. this.verticesStart = verticesStart;
  20713. this.verticesCount = verticesCount;
  20714. this.indexStart = indexStart;
  20715. this.indexCount = indexCount;
  20716. this._renderId = 0;
  20717. this._mesh = mesh;
  20718. this._renderingMesh = renderingMesh || mesh;
  20719. mesh.subMeshes.push(this);
  20720. this._trianglePlanes = [];
  20721. this._id = mesh.subMeshes.length - 1;
  20722. if (createBoundingBox) {
  20723. this.refreshBoundingInfo();
  20724. mesh.computeWorldMatrix(true);
  20725. }
  20726. }
  20727. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  20728. get: function () {
  20729. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  20730. },
  20731. enumerable: true,
  20732. configurable: true
  20733. });
  20734. SubMesh.prototype.getBoundingInfo = function () {
  20735. if (this.IsGlobal) {
  20736. return this._mesh.getBoundingInfo();
  20737. }
  20738. return this._boundingInfo;
  20739. };
  20740. SubMesh.prototype.getMesh = function () {
  20741. return this._mesh;
  20742. };
  20743. SubMesh.prototype.getRenderingMesh = function () {
  20744. return this._renderingMesh;
  20745. };
  20746. SubMesh.prototype.getMaterial = function () {
  20747. var rootMaterial = this._renderingMesh.material;
  20748. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  20749. var multiMaterial = rootMaterial;
  20750. return multiMaterial.getSubMaterial(this.materialIndex);
  20751. }
  20752. if (!rootMaterial) {
  20753. return this._mesh.getScene().defaultMaterial;
  20754. }
  20755. return rootMaterial;
  20756. };
  20757. // Methods
  20758. SubMesh.prototype.refreshBoundingInfo = function () {
  20759. this._lastColliderWorldVertices = null;
  20760. if (this.IsGlobal) {
  20761. return;
  20762. }
  20763. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20764. if (!data) {
  20765. this._boundingInfo = this._mesh._boundingInfo;
  20766. return;
  20767. }
  20768. var indices = this._renderingMesh.getIndices();
  20769. var extend;
  20770. //is this the only submesh?
  20771. if (this.indexStart === 0 && this.indexCount === indices.length) {
  20772. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  20773. extend = { minimum: this._renderingMesh.getBoundingInfo().minimum.clone(), maximum: this._renderingMesh.getBoundingInfo().maximum.clone() };
  20774. }
  20775. else {
  20776. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  20777. }
  20778. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  20779. };
  20780. SubMesh.prototype._checkCollision = function (collider) {
  20781. return this.getBoundingInfo()._checkCollision(collider);
  20782. };
  20783. SubMesh.prototype.updateBoundingInfo = function (world) {
  20784. if (!this.getBoundingInfo()) {
  20785. this.refreshBoundingInfo();
  20786. }
  20787. this.getBoundingInfo().update(world);
  20788. };
  20789. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  20790. return this.getBoundingInfo().isInFrustum(frustumPlanes);
  20791. };
  20792. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  20793. return this.getBoundingInfo().isCompletelyInFrustum(frustumPlanes);
  20794. };
  20795. SubMesh.prototype.render = function (enableAlphaMode) {
  20796. this._renderingMesh.render(this, enableAlphaMode);
  20797. };
  20798. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  20799. if (!this._linesIndexBuffer) {
  20800. var linesIndices = [];
  20801. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  20802. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  20803. }
  20804. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  20805. this.linesIndexCount = linesIndices.length;
  20806. }
  20807. return this._linesIndexBuffer;
  20808. };
  20809. SubMesh.prototype.canIntersects = function (ray) {
  20810. return ray.intersectsBox(this.getBoundingInfo().boundingBox);
  20811. };
  20812. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  20813. var intersectInfo = null;
  20814. // LineMesh first as it's also a Mesh...
  20815. if (this._mesh instanceof BABYLON.LinesMesh) {
  20816. var lineMesh = this._mesh;
  20817. // Line test
  20818. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  20819. var p0 = positions[indices[index]];
  20820. var p1 = positions[indices[index + 1]];
  20821. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  20822. if (length < 0) {
  20823. continue;
  20824. }
  20825. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  20826. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  20827. if (fastCheck) {
  20828. break;
  20829. }
  20830. }
  20831. }
  20832. }
  20833. else {
  20834. // Triangles test
  20835. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  20836. var p0 = positions[indices[index]];
  20837. var p1 = positions[indices[index + 1]];
  20838. var p2 = positions[indices[index + 2]];
  20839. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  20840. if (currentIntersectInfo) {
  20841. if (currentIntersectInfo.distance < 0) {
  20842. continue;
  20843. }
  20844. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  20845. intersectInfo = currentIntersectInfo;
  20846. intersectInfo.faceId = index / 3;
  20847. if (fastCheck) {
  20848. break;
  20849. }
  20850. }
  20851. }
  20852. }
  20853. }
  20854. return intersectInfo;
  20855. };
  20856. // Clone
  20857. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  20858. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  20859. if (!this.IsGlobal) {
  20860. result._boundingInfo = new BABYLON.BoundingInfo(this.getBoundingInfo().minimum, this.getBoundingInfo().maximum);
  20861. }
  20862. return result;
  20863. };
  20864. // Dispose
  20865. SubMesh.prototype.dispose = function () {
  20866. if (this._linesIndexBuffer) {
  20867. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  20868. this._linesIndexBuffer = null;
  20869. }
  20870. // Remove from mesh
  20871. var index = this._mesh.subMeshes.indexOf(this);
  20872. this._mesh.subMeshes.splice(index, 1);
  20873. };
  20874. // Statics
  20875. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  20876. var minVertexIndex = Number.MAX_VALUE;
  20877. var maxVertexIndex = -Number.MAX_VALUE;
  20878. renderingMesh = renderingMesh || mesh;
  20879. var indices = renderingMesh.getIndices();
  20880. for (var index = startIndex; index < startIndex + indexCount; index++) {
  20881. var vertexIndex = indices[index];
  20882. if (vertexIndex < minVertexIndex)
  20883. minVertexIndex = vertexIndex;
  20884. if (vertexIndex > maxVertexIndex)
  20885. maxVertexIndex = vertexIndex;
  20886. }
  20887. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  20888. };
  20889. return SubMesh;
  20890. })();
  20891. BABYLON.SubMesh = SubMesh;
  20892. })(BABYLON || (BABYLON = {}));
  20893. var BABYLON;
  20894. (function (BABYLON) {
  20895. var MeshBuilder = (function () {
  20896. function MeshBuilder() {
  20897. }
  20898. /**
  20899. * Creates a box mesh.
  20900. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  20901. * The parameter `size` sets the size (float) of each box side (default 1).
  20902. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  20903. * 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).
  20904. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  20905. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20906. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20907. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20908. */
  20909. MeshBuilder.CreateBox = function (name, options, scene) {
  20910. var box = new BABYLON.Mesh(name, scene);
  20911. var vertexData = BABYLON.VertexData.CreateBox(options);
  20912. vertexData.applyToMesh(box, options.updatable);
  20913. return box;
  20914. };
  20915. /**
  20916. * Creates a sphere mesh.
  20917. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  20918. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  20919. * 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`).
  20920. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  20921. * 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
  20922. * 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).
  20923. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20924. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20925. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20926. */
  20927. MeshBuilder.CreateSphere = function (name, options, scene) {
  20928. var sphere = new BABYLON.Mesh(name, scene);
  20929. var vertexData = BABYLON.VertexData.CreateSphere(options);
  20930. vertexData.applyToMesh(sphere, options.updatable);
  20931. return sphere;
  20932. };
  20933. /**
  20934. * Creates a plane polygonal mesh. By default, this is a disc.
  20935. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  20936. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  20937. * 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.
  20938. * 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
  20939. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20940. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20941. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20942. */
  20943. MeshBuilder.CreateDisc = function (name, options, scene) {
  20944. var disc = new BABYLON.Mesh(name, scene);
  20945. var vertexData = BABYLON.VertexData.CreateDisc(options);
  20946. vertexData.applyToMesh(disc, options.updatable);
  20947. return disc;
  20948. };
  20949. /**
  20950. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  20951. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  20952. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  20953. * 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`).
  20954. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  20955. * 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.
  20956. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20957. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20958. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20959. */
  20960. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  20961. var sphere = new BABYLON.Mesh(name, scene);
  20962. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  20963. vertexData.applyToMesh(sphere, options.updatable);
  20964. return sphere;
  20965. };
  20966. ;
  20967. /**
  20968. * Creates a ribbon mesh.
  20969. * 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.
  20970. *
  20971. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  20972. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  20973. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  20974. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  20975. * 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.
  20976. * 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.
  20977. * 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
  20978. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20979. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20980. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  20981. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20982. */
  20983. MeshBuilder.CreateRibbon = function (name, options, scene) {
  20984. var pathArray = options.pathArray;
  20985. var closeArray = options.closeArray;
  20986. var closePath = options.closePath;
  20987. var offset = options.offset;
  20988. var sideOrientation = options.sideOrientation;
  20989. var instance = options.instance;
  20990. var updatable = options.updatable;
  20991. if (instance) {
  20992. // positionFunction : ribbon case
  20993. // only pathArray and sideOrientation parameters are taken into account for positions update
  20994. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  20995. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  20996. var positionFunction = function (positions) {
  20997. var minlg = pathArray[0].length;
  20998. var i = 0;
  20999. var ns = (instance.sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  21000. for (var si = 1; si <= ns; si++) {
  21001. for (var p = 0; p < pathArray.length; p++) {
  21002. var path = pathArray[p];
  21003. var l = path.length;
  21004. minlg = (minlg < l) ? minlg : l;
  21005. var j = 0;
  21006. while (j < minlg) {
  21007. positions[i] = path[j].x;
  21008. positions[i + 1] = path[j].y;
  21009. positions[i + 2] = path[j].z;
  21010. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  21011. BABYLON.Tmp.Vector3[0].x = path[j].x;
  21012. }
  21013. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  21014. BABYLON.Tmp.Vector3[1].x = path[j].x;
  21015. }
  21016. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  21017. BABYLON.Tmp.Vector3[0].y = path[j].y;
  21018. }
  21019. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  21020. BABYLON.Tmp.Vector3[1].y = path[j].y;
  21021. }
  21022. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  21023. BABYLON.Tmp.Vector3[0].z = path[j].z;
  21024. }
  21025. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  21026. BABYLON.Tmp.Vector3[1].z = path[j].z;
  21027. }
  21028. j++;
  21029. i += 3;
  21030. }
  21031. if (instance._closePath) {
  21032. positions[i] = path[0].x;
  21033. positions[i + 1] = path[0].y;
  21034. positions[i + 2] = path[0].z;
  21035. i += 3;
  21036. }
  21037. }
  21038. }
  21039. };
  21040. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21041. positionFunction(positions);
  21042. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  21043. instance._boundingInfo.update(instance._worldMatrix);
  21044. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  21045. if (!(instance.areNormalsFrozen)) {
  21046. var indices = instance.getIndices();
  21047. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21048. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  21049. if (instance._closePath) {
  21050. var indexFirst = 0;
  21051. var indexLast = 0;
  21052. for (var p = 0; p < pathArray.length; p++) {
  21053. indexFirst = instance._idx[p] * 3;
  21054. if (p + 1 < pathArray.length) {
  21055. indexLast = (instance._idx[p + 1] - 1) * 3;
  21056. }
  21057. else {
  21058. indexLast = normals.length - 3;
  21059. }
  21060. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  21061. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  21062. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  21063. normals[indexLast] = normals[indexFirst];
  21064. normals[indexLast + 1] = normals[indexFirst + 1];
  21065. normals[indexLast + 2] = normals[indexFirst + 2];
  21066. }
  21067. }
  21068. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  21069. }
  21070. return instance;
  21071. }
  21072. else {
  21073. var ribbon = new BABYLON.Mesh(name, scene);
  21074. ribbon.sideOrientation = sideOrientation;
  21075. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  21076. if (closePath) {
  21077. ribbon._idx = vertexData._idx;
  21078. }
  21079. ribbon._closePath = closePath;
  21080. ribbon._closeArray = closeArray;
  21081. vertexData.applyToMesh(ribbon, updatable);
  21082. return ribbon;
  21083. }
  21084. };
  21085. /**
  21086. * Creates a cylinder or a cone mesh.
  21087. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  21088. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  21089. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  21090. * 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.
  21091. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  21092. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  21093. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  21094. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  21095. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  21096. * 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).
  21097. * 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
  21098. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  21099. * 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
  21100. * 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.
  21101. * If `enclose` is false, a ring surface is one element.
  21102. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  21103. * 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
  21104. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21105. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21106. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21107. */
  21108. MeshBuilder.CreateCylinder = function (name, options, scene) {
  21109. var cylinder = new BABYLON.Mesh(name, scene);
  21110. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  21111. vertexData.applyToMesh(cylinder, options.updatable);
  21112. return cylinder;
  21113. };
  21114. /**
  21115. * Creates a torus mesh.
  21116. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  21117. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  21118. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  21119. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  21120. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21121. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21122. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21123. */
  21124. MeshBuilder.CreateTorus = function (name, options, scene) {
  21125. var torus = new BABYLON.Mesh(name, scene);
  21126. var vertexData = BABYLON.VertexData.CreateTorus(options);
  21127. vertexData.applyToMesh(torus, options.updatable);
  21128. return torus;
  21129. };
  21130. /**
  21131. * Creates a torus knot mesh.
  21132. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  21133. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  21134. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  21135. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  21136. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  21137. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21138. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21139. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21140. */
  21141. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  21142. var torusKnot = new BABYLON.Mesh(name, scene);
  21143. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  21144. vertexData.applyToMesh(torusKnot, options.updatable);
  21145. return torusKnot;
  21146. };
  21147. /**
  21148. * Creates a line system mesh.
  21149. * A line system is a pool of many lines gathered in a single mesh.
  21150. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  21151. * 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.
  21152. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  21153. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  21154. * 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
  21155. * 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
  21156. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  21157. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21158. */
  21159. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  21160. var instance = options.instance;
  21161. var lines = options.lines;
  21162. if (instance) {
  21163. var positionFunction = function (positions) {
  21164. var i = 0;
  21165. for (var l = 0; l < lines.length; l++) {
  21166. var points = lines[l];
  21167. for (var p = 0; p < points.length; p++) {
  21168. positions[i] = points[p].x;
  21169. positions[i + 1] = points[p].y;
  21170. positions[i + 2] = points[p].z;
  21171. i += 3;
  21172. }
  21173. }
  21174. };
  21175. instance.updateMeshPositions(positionFunction, false);
  21176. return instance;
  21177. }
  21178. // line system creation
  21179. var lineSystem = new BABYLON.LinesMesh(name, scene);
  21180. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  21181. vertexData.applyToMesh(lineSystem, options.updatable);
  21182. return lineSystem;
  21183. };
  21184. /**
  21185. * Creates a line mesh.
  21186. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  21187. * 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.
  21188. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  21189. * The parameter `points` is an array successive Vector3.
  21190. * 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
  21191. * When updating an instance, remember that only point positions can change, not the number of points.
  21192. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21193. */
  21194. MeshBuilder.CreateLines = function (name, options, scene) {
  21195. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance }, scene);
  21196. return lines;
  21197. };
  21198. /**
  21199. * Creates a dashed line mesh.
  21200. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  21201. * 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.
  21202. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  21203. * The parameter `points` is an array successive Vector3.
  21204. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  21205. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  21206. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  21207. * 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
  21208. * When updating an instance, remember that only point positions can change, not the number of points.
  21209. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21210. */
  21211. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  21212. var points = options.points;
  21213. var instance = options.instance;
  21214. var gapSize = options.gapSize;
  21215. var dashNb = options.dashNb;
  21216. var dashSize = options.dashSize;
  21217. if (instance) {
  21218. var positionFunction = function (positions) {
  21219. var curvect = BABYLON.Vector3.Zero();
  21220. var nbSeg = positions.length / 6;
  21221. var lg = 0;
  21222. var nb = 0;
  21223. var shft = 0;
  21224. var dashshft = 0;
  21225. var curshft = 0;
  21226. var p = 0;
  21227. var i = 0;
  21228. var j = 0;
  21229. for (i = 0; i < points.length - 1; i++) {
  21230. points[i + 1].subtractToRef(points[i], curvect);
  21231. lg += curvect.length();
  21232. }
  21233. shft = lg / nbSeg;
  21234. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  21235. for (i = 0; i < points.length - 1; i++) {
  21236. points[i + 1].subtractToRef(points[i], curvect);
  21237. nb = Math.floor(curvect.length() / shft);
  21238. curvect.normalize();
  21239. j = 0;
  21240. while (j < nb && p < positions.length) {
  21241. curshft = shft * j;
  21242. positions[p] = points[i].x + curshft * curvect.x;
  21243. positions[p + 1] = points[i].y + curshft * curvect.y;
  21244. positions[p + 2] = points[i].z + curshft * curvect.z;
  21245. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  21246. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  21247. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  21248. p += 6;
  21249. j++;
  21250. }
  21251. }
  21252. while (p < positions.length) {
  21253. positions[p] = points[i].x;
  21254. positions[p + 1] = points[i].y;
  21255. positions[p + 2] = points[i].z;
  21256. p += 3;
  21257. }
  21258. };
  21259. instance.updateMeshPositions(positionFunction, false);
  21260. return instance;
  21261. }
  21262. // dashed lines creation
  21263. var dashedLines = new BABYLON.LinesMesh(name, scene);
  21264. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  21265. vertexData.applyToMesh(dashedLines, options.updatable);
  21266. dashedLines.dashSize = dashSize;
  21267. dashedLines.gapSize = gapSize;
  21268. return dashedLines;
  21269. };
  21270. /**
  21271. * Creates an extruded shape mesh.
  21272. * 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.
  21273. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  21274. *
  21275. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  21276. * 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
  21277. * extruded along the Z axis.
  21278. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  21279. * 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.
  21280. * The parameter `scale` (float, default 1) is the value to scale the shape.
  21281. * 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
  21282. * 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
  21283. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  21284. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21285. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21286. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  21287. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21288. */
  21289. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  21290. var path = options.path;
  21291. var shape = options.shape;
  21292. var scale = options.scale || 1;
  21293. var rotation = options.rotation || 0;
  21294. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  21295. var updatable = options.updatable;
  21296. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  21297. var instance = options.instance;
  21298. var invertUV = options.invertUV || false;
  21299. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, instance, invertUV);
  21300. };
  21301. /**
  21302. * Creates an custom extruded shape mesh.
  21303. * 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.
  21304. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  21305. *
  21306. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  21307. * 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
  21308. * extruded along the Z axis.
  21309. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  21310. * 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
  21311. * and the distance of this point from the begining of the path :
  21312. * ```javascript
  21313. * var rotationFunction = function(i, distance) {
  21314. * // do things
  21315. * return rotationValue; }
  21316. * ```
  21317. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  21318. * 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
  21319. * and the distance of this point from the begining of the path :
  21320. * ```javascript
  21321. * var scaleFunction = function(i, distance) {
  21322. * // do things
  21323. * return scaleValue;}
  21324. * ```
  21325. * It must returns a float value that will be the scale value applied to the shape on each path point.
  21326. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  21327. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  21328. * 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
  21329. * 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
  21330. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  21331. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21332. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21333. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  21334. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21335. */
  21336. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  21337. var path = options.path;
  21338. var shape = options.shape;
  21339. var scaleFunction = options.scaleFunction || (function () { return 1; });
  21340. var rotationFunction = options.rotationFunction || (function () { return 0; });
  21341. var ribbonCloseArray = options.ribbonCloseArray || false;
  21342. var ribbonClosePath = options.ribbonClosePath || false;
  21343. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  21344. var updatable = options.updatable;
  21345. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  21346. var instance = options.instance;
  21347. var invertUV = options.invertUV || false;
  21348. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, instance, invertUV);
  21349. };
  21350. /**
  21351. * Creates lathe mesh.
  21352. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  21353. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  21354. *
  21355. * 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
  21356. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  21357. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  21358. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  21359. * 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.
  21360. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  21361. * 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
  21362. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21363. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21364. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  21365. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21366. */
  21367. MeshBuilder.CreateLathe = function (name, options, scene) {
  21368. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  21369. var closed = (options.closed === undefined) ? true : options.closed;
  21370. var shape = options.shape;
  21371. var radius = options.radius || 1;
  21372. var tessellation = options.tessellation || 64;
  21373. var updatable = options.updatable;
  21374. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  21375. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  21376. var pi2 = Math.PI * 2;
  21377. var paths = new Array();
  21378. var invertUV = options.invertUV || false;
  21379. var i = 0;
  21380. var p = 0;
  21381. var step = pi2 / tessellation * arc;
  21382. var rotated;
  21383. var path = new Array();
  21384. ;
  21385. for (i = 0; i <= tessellation; i++) {
  21386. var path = [];
  21387. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  21388. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  21389. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  21390. }
  21391. for (p = 0; p < shape.length; p++) {
  21392. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  21393. path.push(rotated);
  21394. }
  21395. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  21396. 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));
  21397. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  21398. }
  21399. paths.push(path);
  21400. }
  21401. // lathe ribbon
  21402. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV }, scene);
  21403. return lathe;
  21404. };
  21405. /**
  21406. * Creates a plane mesh.
  21407. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  21408. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  21409. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  21410. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  21411. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21412. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21413. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21414. */
  21415. MeshBuilder.CreatePlane = function (name, options, scene) {
  21416. var plane = new BABYLON.Mesh(name, scene);
  21417. var vertexData = BABYLON.VertexData.CreatePlane(options);
  21418. vertexData.applyToMesh(plane, options.updatable);
  21419. if (options.sourcePlane) {
  21420. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  21421. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  21422. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  21423. plane.rotate(vectorProduct, product);
  21424. }
  21425. return plane;
  21426. };
  21427. /**
  21428. * Creates a ground mesh.
  21429. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  21430. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  21431. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  21432. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21433. */
  21434. MeshBuilder.CreateGround = function (name, options, scene) {
  21435. var ground = new BABYLON.GroundMesh(name, scene);
  21436. ground._setReady(false);
  21437. ground._subdivisions = options.subdivisions || 1;
  21438. ground._width = options.width || 1;
  21439. ground._height = options.height || 1;
  21440. ground._maxX = ground._width / 2;
  21441. ground._maxZ = ground._height / 2;
  21442. ground._minX = -ground._maxX;
  21443. ground._minZ = -ground._maxZ;
  21444. var vertexData = BABYLON.VertexData.CreateGround(options);
  21445. vertexData.applyToMesh(ground, options.updatable);
  21446. ground._setReady(true);
  21447. return ground;
  21448. };
  21449. /**
  21450. * Creates a tiled ground mesh.
  21451. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  21452. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  21453. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  21454. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  21455. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  21456. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  21457. * numbers of subdivisions on the ground width and height of each tile.
  21458. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21459. */
  21460. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  21461. var tiledGround = new BABYLON.Mesh(name, scene);
  21462. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  21463. vertexData.applyToMesh(tiledGround, options.updatable);
  21464. return tiledGround;
  21465. };
  21466. /**
  21467. * Creates a ground mesh from a height map.
  21468. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  21469. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  21470. * The parameter `url` sets the URL of the height map image resource.
  21471. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  21472. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  21473. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  21474. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  21475. * 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).
  21476. * This function is passed the newly built mesh :
  21477. * ```javascript
  21478. * function(mesh) { // do things
  21479. * return; }
  21480. * ```
  21481. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21482. */
  21483. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  21484. var width = options.width || 10.0;
  21485. var height = options.height || 10.0;
  21486. var subdivisions = options.subdivisions || 1 | 0;
  21487. var minHeight = options.minHeight || 0.0;
  21488. var maxHeight = options.maxHeight || 10.0;
  21489. var updatable = options.updatable;
  21490. var onReady = options.onReady;
  21491. var ground = new BABYLON.GroundMesh(name, scene);
  21492. ground._subdivisions = subdivisions;
  21493. ground._width = width;
  21494. ground._height = height;
  21495. ground._maxX = ground._width / 2.0;
  21496. ground._maxZ = ground._height / 2.0;
  21497. ground._minX = -ground._maxX;
  21498. ground._minZ = -ground._maxZ;
  21499. ground._setReady(false);
  21500. var onload = function (img) {
  21501. // Getting height map data
  21502. var canvas = document.createElement("canvas");
  21503. var context = canvas.getContext("2d");
  21504. var bufferWidth = img.width;
  21505. var bufferHeight = img.height;
  21506. canvas.width = bufferWidth;
  21507. canvas.height = bufferHeight;
  21508. context.drawImage(img, 0, 0);
  21509. // Create VertexData from map data
  21510. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  21511. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  21512. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  21513. width: width, height: height,
  21514. subdivisions: subdivisions,
  21515. minHeight: minHeight, maxHeight: maxHeight,
  21516. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  21517. });
  21518. vertexData.applyToMesh(ground, updatable);
  21519. ground._setReady(true);
  21520. //execute ready callback, if set
  21521. if (onReady) {
  21522. onReady(ground);
  21523. }
  21524. };
  21525. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  21526. return ground;
  21527. };
  21528. /**
  21529. * Creates a tube mesh.
  21530. * 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.
  21531. *
  21532. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  21533. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  21534. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  21535. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  21536. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  21537. * 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.
  21538. * It must return a radius value (positive float) :
  21539. * ```javascript
  21540. * var radiusFunction = function(i, distance) {
  21541. * // do things
  21542. * return radius; }
  21543. * ```
  21544. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  21545. * 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
  21546. * 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
  21547. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21548. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21549. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  21550. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21551. */
  21552. MeshBuilder.CreateTube = function (name, options, scene) {
  21553. var path = options.path;
  21554. var radius = options.radius || 1.0;
  21555. var tessellation = options.tessellation || 64 | 0;
  21556. var radiusFunction = options.radiusFunction;
  21557. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  21558. var invertUV = options.invertUV || false;
  21559. var updatable = options.updatable;
  21560. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  21561. var instance = options.instance;
  21562. options.arc = (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  21563. // tube geometry
  21564. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  21565. var tangents = path3D.getTangents();
  21566. var normals = path3D.getNormals();
  21567. var distances = path3D.getDistances();
  21568. var pi2 = Math.PI * 2;
  21569. var step = pi2 / tessellation * arc;
  21570. var returnRadius = function () { return radius; };
  21571. var radiusFunctionFinal = radiusFunction || returnRadius;
  21572. var circlePath;
  21573. var rad;
  21574. var normal;
  21575. var rotated;
  21576. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  21577. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  21578. for (var i = 0; i < path.length; i++) {
  21579. rad = radiusFunctionFinal(i, distances[i]); // current radius
  21580. circlePath = Array(); // current circle array
  21581. normal = normals[i]; // current normal
  21582. for (var t = 0; t < tessellation; t++) {
  21583. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  21584. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  21585. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  21586. rotated.scaleInPlace(rad).addInPlace(path[i]);
  21587. circlePath[t] = rotated;
  21588. }
  21589. circlePaths[index] = circlePath;
  21590. index++;
  21591. }
  21592. // cap
  21593. var capPath = function (nbPoints, pathIndex) {
  21594. var pointCap = Array();
  21595. for (var i = 0; i < nbPoints; i++) {
  21596. pointCap.push(path[pathIndex]);
  21597. }
  21598. return pointCap;
  21599. };
  21600. switch (cap) {
  21601. case BABYLON.Mesh.NO_CAP:
  21602. break;
  21603. case BABYLON.Mesh.CAP_START:
  21604. circlePaths[0] = capPath(tessellation, 0);
  21605. circlePaths[1] = circlePaths[2].slice(0);
  21606. break;
  21607. case BABYLON.Mesh.CAP_END:
  21608. circlePaths[index] = circlePaths[index - 1].slice(0);
  21609. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  21610. break;
  21611. case BABYLON.Mesh.CAP_ALL:
  21612. circlePaths[0] = capPath(tessellation, 0);
  21613. circlePaths[1] = circlePaths[2].slice(0);
  21614. circlePaths[index] = circlePaths[index - 1].slice(0);
  21615. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  21616. break;
  21617. default:
  21618. break;
  21619. }
  21620. return circlePaths;
  21621. };
  21622. var path3D;
  21623. var pathArray;
  21624. if (instance) {
  21625. var arc = options.arc || instance.arc;
  21626. path3D = (instance.path3D).update(path);
  21627. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  21628. instance = MeshBuilder.CreateRibbon(null, { pathArray: pathArray, instance: instance });
  21629. instance.path3D = path3D;
  21630. instance.pathArray = pathArray;
  21631. instance.arc = arc;
  21632. return instance;
  21633. }
  21634. // tube creation
  21635. path3D = new BABYLON.Path3D(path);
  21636. var newPathArray = new Array();
  21637. cap = (cap < 0 || cap > 3) ? 0 : cap;
  21638. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  21639. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV }, scene);
  21640. tube.pathArray = pathArray;
  21641. tube.path3D = path3D;
  21642. tube.tessellation = tessellation;
  21643. tube.cap = cap;
  21644. tube.arc = options.arc;
  21645. return tube;
  21646. };
  21647. /**
  21648. * Creates a polyhedron mesh.
  21649. *
  21650. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  21651. * 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
  21652. * to choose the wanted type.
  21653. * The parameter `size` (positive float, default 1) sets the polygon size.
  21654. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  21655. * 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`.
  21656. * 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
  21657. * 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)`).
  21658. * 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
  21659. * 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.
  21660. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21661. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21662. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21663. */
  21664. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  21665. var polyhedron = new BABYLON.Mesh(name, scene);
  21666. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  21667. vertexData.applyToMesh(polyhedron, options.updatable);
  21668. return polyhedron;
  21669. };
  21670. /**
  21671. * Creates a decal mesh.
  21672. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  21673. * 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.
  21674. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  21675. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  21676. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  21677. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  21678. */
  21679. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  21680. var indices = sourceMesh.getIndices();
  21681. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21682. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21683. var position = options.position || BABYLON.Vector3.Zero();
  21684. var normal = options.normal || BABYLON.Vector3.Up();
  21685. var size = options.size || new BABYLON.Vector3(1, 1, 1);
  21686. var angle = options.angle || 0;
  21687. // Getting correct rotation
  21688. if (!normal) {
  21689. var target = new BABYLON.Vector3(0, 0, 1);
  21690. var camera = sourceMesh.getScene().activeCamera;
  21691. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  21692. normal = camera.globalPosition.subtract(cameraWorldTarget);
  21693. }
  21694. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  21695. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  21696. var pitch = Math.atan2(normal.y, len);
  21697. // Matrix
  21698. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  21699. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  21700. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  21701. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  21702. var vertexData = new BABYLON.VertexData();
  21703. vertexData.indices = [];
  21704. vertexData.positions = [];
  21705. vertexData.normals = [];
  21706. vertexData.uvs = [];
  21707. var currentVertexDataIndex = 0;
  21708. var extractDecalVector3 = function (indexId) {
  21709. var vertexId = indices[indexId];
  21710. var result = new BABYLON.PositionNormalVertex();
  21711. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  21712. // Send vector to decal local world
  21713. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  21714. // Get normal
  21715. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  21716. return result;
  21717. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  21718. var clip = function (vertices, axis) {
  21719. if (vertices.length === 0) {
  21720. return vertices;
  21721. }
  21722. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  21723. var clipVertices = function (v0, v1) {
  21724. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  21725. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  21726. };
  21727. var result = new Array();
  21728. for (var index = 0; index < vertices.length; index += 3) {
  21729. var v1Out;
  21730. var v2Out;
  21731. var v3Out;
  21732. var total = 0;
  21733. var nV1, nV2, nV3, nV4;
  21734. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  21735. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  21736. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  21737. v1Out = d1 > 0;
  21738. v2Out = d2 > 0;
  21739. v3Out = d3 > 0;
  21740. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  21741. switch (total) {
  21742. case 0:
  21743. result.push(vertices[index]);
  21744. result.push(vertices[index + 1]);
  21745. result.push(vertices[index + 2]);
  21746. break;
  21747. case 1:
  21748. if (v1Out) {
  21749. nV1 = vertices[index + 1];
  21750. nV2 = vertices[index + 2];
  21751. nV3 = clipVertices(vertices[index], nV1);
  21752. nV4 = clipVertices(vertices[index], nV2);
  21753. }
  21754. if (v2Out) {
  21755. nV1 = vertices[index];
  21756. nV2 = vertices[index + 2];
  21757. nV3 = clipVertices(vertices[index + 1], nV1);
  21758. nV4 = clipVertices(vertices[index + 1], nV2);
  21759. result.push(nV3);
  21760. result.push(nV2.clone());
  21761. result.push(nV1.clone());
  21762. result.push(nV2.clone());
  21763. result.push(nV3.clone());
  21764. result.push(nV4);
  21765. break;
  21766. }
  21767. if (v3Out) {
  21768. nV1 = vertices[index];
  21769. nV2 = vertices[index + 1];
  21770. nV3 = clipVertices(vertices[index + 2], nV1);
  21771. nV4 = clipVertices(vertices[index + 2], nV2);
  21772. }
  21773. result.push(nV1.clone());
  21774. result.push(nV2.clone());
  21775. result.push(nV3);
  21776. result.push(nV4);
  21777. result.push(nV3.clone());
  21778. result.push(nV2.clone());
  21779. break;
  21780. case 2:
  21781. if (!v1Out) {
  21782. nV1 = vertices[index].clone();
  21783. nV2 = clipVertices(nV1, vertices[index + 1]);
  21784. nV3 = clipVertices(nV1, vertices[index + 2]);
  21785. result.push(nV1);
  21786. result.push(nV2);
  21787. result.push(nV3);
  21788. }
  21789. if (!v2Out) {
  21790. nV1 = vertices[index + 1].clone();
  21791. nV2 = clipVertices(nV1, vertices[index + 2]);
  21792. nV3 = clipVertices(nV1, vertices[index]);
  21793. result.push(nV1);
  21794. result.push(nV2);
  21795. result.push(nV3);
  21796. }
  21797. if (!v3Out) {
  21798. nV1 = vertices[index + 2].clone();
  21799. nV2 = clipVertices(nV1, vertices[index]);
  21800. nV3 = clipVertices(nV1, vertices[index + 1]);
  21801. result.push(nV1);
  21802. result.push(nV2);
  21803. result.push(nV3);
  21804. }
  21805. break;
  21806. case 3:
  21807. break;
  21808. }
  21809. }
  21810. return result;
  21811. };
  21812. for (var index = 0; index < indices.length; index += 3) {
  21813. var faceVertices = new Array();
  21814. faceVertices.push(extractDecalVector3(index));
  21815. faceVertices.push(extractDecalVector3(index + 1));
  21816. faceVertices.push(extractDecalVector3(index + 2));
  21817. // Clip
  21818. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  21819. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  21820. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  21821. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  21822. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  21823. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  21824. if (faceVertices.length === 0) {
  21825. continue;
  21826. }
  21827. // Add UVs and get back to world
  21828. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  21829. var vertex = faceVertices[vIndex];
  21830. //TODO check for Int32Array
  21831. vertexData.indices.push(currentVertexDataIndex);
  21832. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  21833. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  21834. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  21835. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  21836. currentVertexDataIndex++;
  21837. }
  21838. }
  21839. // Return mesh
  21840. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  21841. vertexData.applyToMesh(decal);
  21842. decal.position = position.clone();
  21843. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  21844. return decal;
  21845. };
  21846. // Privates
  21847. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV) {
  21848. // extrusion geometry
  21849. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  21850. var tangents = path3D.getTangents();
  21851. var normals = path3D.getNormals();
  21852. var binormals = path3D.getBinormals();
  21853. var distances = path3D.getDistances();
  21854. var angle = 0;
  21855. var returnScale = function () { return scale; };
  21856. var returnRotation = function () { return rotation; };
  21857. var rotate = custom ? rotateFunction : returnRotation;
  21858. var scl = custom ? scaleFunction : returnScale;
  21859. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  21860. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  21861. for (var i = 0; i < curve.length; i++) {
  21862. var shapePath = new Array();
  21863. var angleStep = rotate(i, distances[i]);
  21864. var scaleRatio = scl(i, distances[i]);
  21865. for (var p = 0; p < shape.length; p++) {
  21866. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  21867. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  21868. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  21869. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  21870. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  21871. shapePath[p] = rotated;
  21872. }
  21873. shapePaths[index] = shapePath;
  21874. angle += angleStep;
  21875. index++;
  21876. }
  21877. // cap
  21878. var capPath = function (shapePath) {
  21879. var pointCap = Array();
  21880. var barycenter = BABYLON.Vector3.Zero();
  21881. var i;
  21882. for (i = 0; i < shapePath.length; i++) {
  21883. barycenter.addInPlace(shapePath[i]);
  21884. }
  21885. barycenter.scaleInPlace(1 / shapePath.length);
  21886. for (i = 0; i < shapePath.length; i++) {
  21887. pointCap.push(barycenter);
  21888. }
  21889. return pointCap;
  21890. };
  21891. switch (cap) {
  21892. case BABYLON.Mesh.NO_CAP:
  21893. break;
  21894. case BABYLON.Mesh.CAP_START:
  21895. shapePaths[0] = capPath(shapePaths[2]);
  21896. shapePaths[1] = shapePaths[2].slice(0);
  21897. break;
  21898. case BABYLON.Mesh.CAP_END:
  21899. shapePaths[index] = shapePaths[index - 1];
  21900. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  21901. break;
  21902. case BABYLON.Mesh.CAP_ALL:
  21903. shapePaths[0] = capPath(shapePaths[2]);
  21904. shapePaths[1] = shapePaths[2].slice(0);
  21905. shapePaths[index] = shapePaths[index - 1];
  21906. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  21907. break;
  21908. default:
  21909. break;
  21910. }
  21911. return shapePaths;
  21912. };
  21913. var path3D;
  21914. var pathArray;
  21915. if (instance) {
  21916. path3D = (instance.path3D).update(curve);
  21917. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  21918. instance = BABYLON.Mesh.CreateRibbon(null, pathArray, null, null, null, null, null, null, instance);
  21919. return instance;
  21920. }
  21921. // extruded shape creation
  21922. path3D = new BABYLON.Path3D(curve);
  21923. var newShapePaths = new Array();
  21924. cap = (cap < 0 || cap > 3) ? 0 : cap;
  21925. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  21926. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV }, scene);
  21927. extrudedGeneric.pathArray = pathArray;
  21928. extrudedGeneric.path3D = path3D;
  21929. extrudedGeneric.cap = cap;
  21930. return extrudedGeneric;
  21931. };
  21932. return MeshBuilder;
  21933. })();
  21934. BABYLON.MeshBuilder = MeshBuilder;
  21935. })(BABYLON || (BABYLON = {}));
  21936. var BABYLON;
  21937. (function (BABYLON) {
  21938. var BaseTexture = (function () {
  21939. function BaseTexture(scene) {
  21940. this.hasAlpha = false;
  21941. this.getAlphaFromRGB = false;
  21942. this.level = 1;
  21943. this.coordinatesIndex = 0;
  21944. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  21945. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  21946. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  21947. this.anisotropicFilteringLevel = 4;
  21948. this.isCube = false;
  21949. this.isRenderTarget = false;
  21950. this.animations = new Array();
  21951. /**
  21952. * An event triggered when the texture is disposed.
  21953. * @type {BABYLON.Observable}
  21954. */
  21955. this.onDisposeObservable = new BABYLON.Observable();
  21956. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  21957. this._scene = scene;
  21958. this._scene.textures.push(this);
  21959. }
  21960. BaseTexture.prototype.toString = function () {
  21961. return this.name;
  21962. };
  21963. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  21964. set: function (callback) {
  21965. if (this._onDisposeObserver) {
  21966. this.onDisposeObservable.remove(this._onDisposeObserver);
  21967. }
  21968. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  21969. },
  21970. enumerable: true,
  21971. configurable: true
  21972. });
  21973. BaseTexture.prototype.getScene = function () {
  21974. return this._scene;
  21975. };
  21976. BaseTexture.prototype.getTextureMatrix = function () {
  21977. return null;
  21978. };
  21979. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  21980. return null;
  21981. };
  21982. BaseTexture.prototype.getInternalTexture = function () {
  21983. return this._texture;
  21984. };
  21985. BaseTexture.prototype.isReady = function () {
  21986. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  21987. return true;
  21988. }
  21989. if (this._texture) {
  21990. return this._texture.isReady;
  21991. }
  21992. return false;
  21993. };
  21994. BaseTexture.prototype.getSize = function () {
  21995. if (this._texture._width) {
  21996. return new BABYLON.Size(this._texture._width, this._texture._height);
  21997. }
  21998. if (this._texture._size) {
  21999. return new BABYLON.Size(this._texture._size, this._texture._size);
  22000. }
  22001. return BABYLON.Size.Zero();
  22002. };
  22003. BaseTexture.prototype.getBaseSize = function () {
  22004. if (!this.isReady() || !this._texture)
  22005. return BABYLON.Size.Zero();
  22006. if (this._texture._size) {
  22007. return new BABYLON.Size(this._texture._size, this._texture._size);
  22008. }
  22009. return new BABYLON.Size(this._texture._baseWidth, this._texture._baseHeight);
  22010. };
  22011. BaseTexture.prototype.scale = function (ratio) {
  22012. };
  22013. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  22014. get: function () {
  22015. return false;
  22016. },
  22017. enumerable: true,
  22018. configurable: true
  22019. });
  22020. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  22021. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  22022. for (var index = 0; index < texturesCache.length; index++) {
  22023. var texturesCacheEntry = texturesCache[index];
  22024. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  22025. texturesCache.splice(index, 1);
  22026. return;
  22027. }
  22028. }
  22029. };
  22030. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  22031. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  22032. for (var index = 0; index < texturesCache.length; index++) {
  22033. var texturesCacheEntry = texturesCache[index];
  22034. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  22035. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  22036. texturesCacheEntry.references++;
  22037. return texturesCacheEntry;
  22038. }
  22039. }
  22040. }
  22041. return null;
  22042. };
  22043. BaseTexture.prototype.delayLoad = function () {
  22044. };
  22045. BaseTexture.prototype.clone = function () {
  22046. return null;
  22047. };
  22048. BaseTexture.prototype.releaseInternalTexture = function () {
  22049. if (this._texture) {
  22050. this._scene.getEngine().releaseInternalTexture(this._texture);
  22051. delete this._texture;
  22052. }
  22053. };
  22054. BaseTexture.prototype.dispose = function () {
  22055. // Animations
  22056. this.getScene().stopAnimation(this);
  22057. // Remove from scene
  22058. var index = this._scene.textures.indexOf(this);
  22059. if (index >= 0) {
  22060. this._scene.textures.splice(index, 1);
  22061. }
  22062. if (this._texture === undefined) {
  22063. return;
  22064. }
  22065. // Release
  22066. this.releaseInternalTexture();
  22067. // Callback
  22068. this.onDisposeObservable.notifyObservers(this);
  22069. this.onDisposeObservable.clear();
  22070. };
  22071. BaseTexture.prototype.serialize = function () {
  22072. if (!this.name) {
  22073. return null;
  22074. }
  22075. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  22076. // Animations
  22077. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  22078. return serializationObject;
  22079. };
  22080. __decorate([
  22081. BABYLON.serialize()
  22082. ], BaseTexture.prototype, "name", void 0);
  22083. __decorate([
  22084. BABYLON.serialize()
  22085. ], BaseTexture.prototype, "hasAlpha", void 0);
  22086. __decorate([
  22087. BABYLON.serialize()
  22088. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  22089. __decorate([
  22090. BABYLON.serialize()
  22091. ], BaseTexture.prototype, "level", void 0);
  22092. __decorate([
  22093. BABYLON.serialize()
  22094. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  22095. __decorate([
  22096. BABYLON.serialize()
  22097. ], BaseTexture.prototype, "coordinatesMode", void 0);
  22098. __decorate([
  22099. BABYLON.serialize()
  22100. ], BaseTexture.prototype, "wrapU", void 0);
  22101. __decorate([
  22102. BABYLON.serialize()
  22103. ], BaseTexture.prototype, "wrapV", void 0);
  22104. __decorate([
  22105. BABYLON.serialize()
  22106. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  22107. __decorate([
  22108. BABYLON.serialize()
  22109. ], BaseTexture.prototype, "isCube", void 0);
  22110. __decorate([
  22111. BABYLON.serialize()
  22112. ], BaseTexture.prototype, "isRenderTarget", void 0);
  22113. return BaseTexture;
  22114. })();
  22115. BABYLON.BaseTexture = BaseTexture;
  22116. })(BABYLON || (BABYLON = {}));
  22117. var BABYLON;
  22118. (function (BABYLON) {
  22119. var Texture = (function (_super) {
  22120. __extends(Texture, _super);
  22121. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
  22122. var _this = this;
  22123. if (noMipmap === void 0) { noMipmap = false; }
  22124. if (invertY === void 0) { invertY = true; }
  22125. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  22126. if (onLoad === void 0) { onLoad = null; }
  22127. if (onError === void 0) { onError = null; }
  22128. if (buffer === void 0) { buffer = null; }
  22129. if (deleteBuffer === void 0) { deleteBuffer = false; }
  22130. _super.call(this, scene);
  22131. this.uOffset = 0;
  22132. this.vOffset = 0;
  22133. this.uScale = 1.0;
  22134. this.vScale = 1.0;
  22135. this.uAng = 0;
  22136. this.vAng = 0;
  22137. this.wAng = 0;
  22138. this.name = url;
  22139. this.url = url;
  22140. this._noMipmap = noMipmap;
  22141. this._invertY = invertY;
  22142. this._samplingMode = samplingMode;
  22143. this._buffer = buffer;
  22144. this._deleteBuffer = deleteBuffer;
  22145. if (!url) {
  22146. return;
  22147. }
  22148. this._texture = this._getFromCache(url, noMipmap, samplingMode);
  22149. var load = function () {
  22150. if (_this._onLoadObservarble && _this._onLoadObservarble.hasObservers()) {
  22151. _this.onLoadObservable.notifyObservers(true);
  22152. }
  22153. if (onLoad) {
  22154. onLoad();
  22155. }
  22156. };
  22157. if (!this._texture) {
  22158. if (!scene.useDelayedTextureLoading) {
  22159. this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, this._samplingMode, load, onError, this._buffer);
  22160. if (deleteBuffer) {
  22161. delete this._buffer;
  22162. }
  22163. }
  22164. else {
  22165. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  22166. this._delayedOnLoad = load;
  22167. this._delayedOnError = onError;
  22168. }
  22169. }
  22170. else {
  22171. BABYLON.Tools.SetImmediate(function () { return load(); });
  22172. }
  22173. }
  22174. Object.defineProperty(Texture.prototype, "noMipmap", {
  22175. get: function () {
  22176. return this._noMipmap;
  22177. },
  22178. enumerable: true,
  22179. configurable: true
  22180. });
  22181. Texture.prototype.delayLoad = function () {
  22182. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  22183. return;
  22184. }
  22185. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  22186. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  22187. if (!this._texture) {
  22188. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer);
  22189. if (this._deleteBuffer) {
  22190. delete this._buffer;
  22191. }
  22192. }
  22193. };
  22194. Texture.prototype.updateSamplingMode = function (samplingMode) {
  22195. if (!this._texture) {
  22196. return;
  22197. }
  22198. this._samplingMode = samplingMode;
  22199. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  22200. };
  22201. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  22202. x *= this.uScale;
  22203. y *= this.vScale;
  22204. x -= 0.5 * this.uScale;
  22205. y -= 0.5 * this.vScale;
  22206. z -= 0.5;
  22207. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  22208. t.x += 0.5 * this.uScale + this.uOffset;
  22209. t.y += 0.5 * this.vScale + this.vOffset;
  22210. t.z += 0.5;
  22211. };
  22212. Texture.prototype.getTextureMatrix = function () {
  22213. if (this.uOffset === this._cachedUOffset &&
  22214. this.vOffset === this._cachedVOffset &&
  22215. this.uScale === this._cachedUScale &&
  22216. this.vScale === this._cachedVScale &&
  22217. this.uAng === this._cachedUAng &&
  22218. this.vAng === this._cachedVAng &&
  22219. this.wAng === this._cachedWAng) {
  22220. return this._cachedTextureMatrix;
  22221. }
  22222. this._cachedUOffset = this.uOffset;
  22223. this._cachedVOffset = this.vOffset;
  22224. this._cachedUScale = this.uScale;
  22225. this._cachedVScale = this.vScale;
  22226. this._cachedUAng = this.uAng;
  22227. this._cachedVAng = this.vAng;
  22228. this._cachedWAng = this.wAng;
  22229. if (!this._cachedTextureMatrix) {
  22230. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  22231. this._rowGenerationMatrix = new BABYLON.Matrix();
  22232. this._t0 = BABYLON.Vector3.Zero();
  22233. this._t1 = BABYLON.Vector3.Zero();
  22234. this._t2 = BABYLON.Vector3.Zero();
  22235. }
  22236. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  22237. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  22238. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  22239. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  22240. this._t1.subtractInPlace(this._t0);
  22241. this._t2.subtractInPlace(this._t0);
  22242. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  22243. this._cachedTextureMatrix.m[0] = this._t1.x;
  22244. this._cachedTextureMatrix.m[1] = this._t1.y;
  22245. this._cachedTextureMatrix.m[2] = this._t1.z;
  22246. this._cachedTextureMatrix.m[4] = this._t2.x;
  22247. this._cachedTextureMatrix.m[5] = this._t2.y;
  22248. this._cachedTextureMatrix.m[6] = this._t2.z;
  22249. this._cachedTextureMatrix.m[8] = this._t0.x;
  22250. this._cachedTextureMatrix.m[9] = this._t0.y;
  22251. this._cachedTextureMatrix.m[10] = this._t0.z;
  22252. return this._cachedTextureMatrix;
  22253. };
  22254. Texture.prototype.getReflectionTextureMatrix = function () {
  22255. if (this.uOffset === this._cachedUOffset &&
  22256. this.vOffset === this._cachedVOffset &&
  22257. this.uScale === this._cachedUScale &&
  22258. this.vScale === this._cachedVScale &&
  22259. this.coordinatesMode === this._cachedCoordinatesMode) {
  22260. return this._cachedTextureMatrix;
  22261. }
  22262. if (!this._cachedTextureMatrix) {
  22263. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  22264. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  22265. }
  22266. this._cachedCoordinatesMode = this.coordinatesMode;
  22267. switch (this.coordinatesMode) {
  22268. case Texture.PLANAR_MODE:
  22269. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  22270. this._cachedTextureMatrix[0] = this.uScale;
  22271. this._cachedTextureMatrix[5] = this.vScale;
  22272. this._cachedTextureMatrix[12] = this.uOffset;
  22273. this._cachedTextureMatrix[13] = this.vOffset;
  22274. break;
  22275. case Texture.PROJECTION_MODE:
  22276. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  22277. this._projectionModeMatrix.m[0] = 0.5;
  22278. this._projectionModeMatrix.m[5] = -0.5;
  22279. this._projectionModeMatrix.m[10] = 0.0;
  22280. this._projectionModeMatrix.m[12] = 0.5;
  22281. this._projectionModeMatrix.m[13] = 0.5;
  22282. this._projectionModeMatrix.m[14] = 1.0;
  22283. this._projectionModeMatrix.m[15] = 1.0;
  22284. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  22285. break;
  22286. default:
  22287. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  22288. break;
  22289. }
  22290. return this._cachedTextureMatrix;
  22291. };
  22292. Texture.prototype.clone = function () {
  22293. var _this = this;
  22294. return BABYLON.SerializationHelper.Clone(function () {
  22295. return new Texture(_this._texture.url, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  22296. }, this);
  22297. };
  22298. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  22299. get: function () {
  22300. if (!this._onLoadObservarble) {
  22301. this._onLoadObservarble = new BABYLON.Observable();
  22302. }
  22303. return this._onLoadObservarble;
  22304. },
  22305. enumerable: true,
  22306. configurable: true
  22307. });
  22308. // Statics
  22309. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError) {
  22310. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  22311. if (onLoad === void 0) { onLoad = null; }
  22312. if (onError === void 0) { onError = null; }
  22313. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data);
  22314. };
  22315. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  22316. if (parsedTexture.isCube) {
  22317. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  22318. }
  22319. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  22320. return null;
  22321. }
  22322. var texture = BABYLON.SerializationHelper.Parse(function () {
  22323. if (parsedTexture.customType) {
  22324. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  22325. return customTexture.Parse(parsedTexture, scene, rootUrl);
  22326. }
  22327. else if (parsedTexture.mirrorPlane) {
  22328. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  22329. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  22330. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  22331. return mirrorTexture;
  22332. }
  22333. else if (parsedTexture.isRenderTarget) {
  22334. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  22335. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  22336. return renderTargetTexture;
  22337. }
  22338. else {
  22339. var texture;
  22340. if (parsedTexture.base64String) {
  22341. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
  22342. }
  22343. else {
  22344. texture = new Texture(rootUrl + parsedTexture.name, scene);
  22345. }
  22346. return texture;
  22347. }
  22348. }, parsedTexture, scene);
  22349. // Animations
  22350. if (parsedTexture.animations) {
  22351. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  22352. var parsedAnimation = parsedTexture.animations[animationIndex];
  22353. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  22354. }
  22355. }
  22356. return texture;
  22357. };
  22358. // Constants
  22359. Texture.NEAREST_SAMPLINGMODE = 1;
  22360. Texture.BILINEAR_SAMPLINGMODE = 2;
  22361. Texture.TRILINEAR_SAMPLINGMODE = 3;
  22362. Texture.EXPLICIT_MODE = 0;
  22363. Texture.SPHERICAL_MODE = 1;
  22364. Texture.PLANAR_MODE = 2;
  22365. Texture.CUBIC_MODE = 3;
  22366. Texture.PROJECTION_MODE = 4;
  22367. Texture.SKYBOX_MODE = 5;
  22368. Texture.INVCUBIC_MODE = 6;
  22369. Texture.EQUIRECTANGULAR_MODE = 7;
  22370. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  22371. Texture.CLAMP_ADDRESSMODE = 0;
  22372. Texture.WRAP_ADDRESSMODE = 1;
  22373. Texture.MIRROR_ADDRESSMODE = 2;
  22374. __decorate([
  22375. BABYLON.serialize()
  22376. ], Texture.prototype, "url", void 0);
  22377. __decorate([
  22378. BABYLON.serialize()
  22379. ], Texture.prototype, "uOffset", void 0);
  22380. __decorate([
  22381. BABYLON.serialize()
  22382. ], Texture.prototype, "vOffset", void 0);
  22383. __decorate([
  22384. BABYLON.serialize()
  22385. ], Texture.prototype, "uScale", void 0);
  22386. __decorate([
  22387. BABYLON.serialize()
  22388. ], Texture.prototype, "vScale", void 0);
  22389. __decorate([
  22390. BABYLON.serialize()
  22391. ], Texture.prototype, "uAng", void 0);
  22392. __decorate([
  22393. BABYLON.serialize()
  22394. ], Texture.prototype, "vAng", void 0);
  22395. __decorate([
  22396. BABYLON.serialize()
  22397. ], Texture.prototype, "wAng", void 0);
  22398. return Texture;
  22399. })(BABYLON.BaseTexture);
  22400. BABYLON.Texture = Texture;
  22401. })(BABYLON || (BABYLON = {}));
  22402. var BABYLON;
  22403. (function (BABYLON) {
  22404. var CubeTexture = (function (_super) {
  22405. __extends(CubeTexture, _super);
  22406. function CubeTexture(rootUrl, scene, extensions, noMipmap, files) {
  22407. _super.call(this, scene);
  22408. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  22409. this.name = rootUrl;
  22410. this.url = rootUrl;
  22411. this._noMipmap = noMipmap;
  22412. this.hasAlpha = false;
  22413. if (!rootUrl && !files) {
  22414. return;
  22415. }
  22416. this._texture = this._getFromCache(rootUrl, noMipmap);
  22417. if (!files) {
  22418. if (!extensions) {
  22419. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  22420. }
  22421. files = [];
  22422. for (var index = 0; index < extensions.length; index++) {
  22423. files.push(rootUrl + extensions[index]);
  22424. }
  22425. this._extensions = extensions;
  22426. }
  22427. this._files = files;
  22428. if (!this._texture) {
  22429. if (!scene.useDelayedTextureLoading) {
  22430. this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap);
  22431. }
  22432. else {
  22433. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  22434. }
  22435. }
  22436. this.isCube = true;
  22437. this._textureMatrix = BABYLON.Matrix.Identity();
  22438. }
  22439. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  22440. return new CubeTexture("", scene, null, noMipmap, files);
  22441. };
  22442. // Methods
  22443. CubeTexture.prototype.delayLoad = function () {
  22444. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  22445. return;
  22446. }
  22447. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  22448. this._texture = this._getFromCache(this.url, this._noMipmap);
  22449. if (!this._texture) {
  22450. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._files, this._noMipmap);
  22451. }
  22452. };
  22453. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  22454. return this._textureMatrix;
  22455. };
  22456. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  22457. var texture = BABYLON.SerializationHelper.Parse(function () {
  22458. return new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  22459. }, parsedTexture, scene);
  22460. // Animations
  22461. if (parsedTexture.animations) {
  22462. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  22463. var parsedAnimation = parsedTexture.animations[animationIndex];
  22464. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  22465. }
  22466. }
  22467. return texture;
  22468. };
  22469. CubeTexture.prototype.clone = function () {
  22470. var _this = this;
  22471. return BABYLON.SerializationHelper.Clone(function () {
  22472. return new CubeTexture(_this.url, _this.getScene(), _this._extensions, _this._noMipmap, _this._files);
  22473. }, this);
  22474. };
  22475. return CubeTexture;
  22476. })(BABYLON.BaseTexture);
  22477. BABYLON.CubeTexture = CubeTexture;
  22478. })(BABYLON || (BABYLON = {}));
  22479. var BABYLON;
  22480. (function (BABYLON) {
  22481. var RenderTargetTexture = (function (_super) {
  22482. __extends(RenderTargetTexture, _super);
  22483. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer) {
  22484. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  22485. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  22486. if (isCube === void 0) { isCube = false; }
  22487. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  22488. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  22489. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  22490. _super.call(this, null, scene, !generateMipMaps);
  22491. this.isCube = isCube;
  22492. /**
  22493. * Use this list to define the list of mesh you want to render.
  22494. */
  22495. this.renderList = new Array();
  22496. this.renderParticles = true;
  22497. this.renderSprites = false;
  22498. this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  22499. // Events
  22500. /**
  22501. * An event triggered when the texture is unbind.
  22502. * @type {BABYLON.Observable}
  22503. */
  22504. this.onAfterUnbindObservable = new BABYLON.Observable();
  22505. /**
  22506. * An event triggered before rendering the texture
  22507. * @type {BABYLON.Observable}
  22508. */
  22509. this.onBeforeRenderObservable = new BABYLON.Observable();
  22510. /**
  22511. * An event triggered after rendering the texture
  22512. * @type {BABYLON.Observable}
  22513. */
  22514. this.onAfterRenderObservable = new BABYLON.Observable();
  22515. /**
  22516. * An event triggered after the texture clear
  22517. * @type {BABYLON.Observable}
  22518. */
  22519. this.onClearObservable = new BABYLON.Observable();
  22520. this._currentRefreshId = -1;
  22521. this._refreshRate = 1;
  22522. this.name = name;
  22523. this.isRenderTarget = true;
  22524. this._size = size;
  22525. this._generateMipMaps = generateMipMaps;
  22526. this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  22527. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  22528. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  22529. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  22530. }
  22531. if (isCube) {
  22532. this._texture = scene.getEngine().createRenderTargetCubeTexture(size, {
  22533. generateMipMaps: generateMipMaps,
  22534. samplingMode: samplingMode,
  22535. generateDepthBuffer: generateDepthBuffer,
  22536. generateStencilBuffer: generateStencilBuffer
  22537. });
  22538. this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  22539. this._textureMatrix = BABYLON.Matrix.Identity();
  22540. }
  22541. else {
  22542. this._texture = scene.getEngine().createRenderTargetTexture(size, {
  22543. generateMipMaps: generateMipMaps,
  22544. type: type,
  22545. samplingMode: samplingMode,
  22546. generateDepthBuffer: generateDepthBuffer,
  22547. generateStencilBuffer: generateStencilBuffer
  22548. });
  22549. }
  22550. // Rendering groups
  22551. this._renderingManager = new BABYLON.RenderingManager(scene);
  22552. }
  22553. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  22554. get: function () {
  22555. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  22556. },
  22557. enumerable: true,
  22558. configurable: true
  22559. });
  22560. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  22561. get: function () {
  22562. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  22563. },
  22564. enumerable: true,
  22565. configurable: true
  22566. });
  22567. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  22568. get: function () {
  22569. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  22570. },
  22571. enumerable: true,
  22572. configurable: true
  22573. });
  22574. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  22575. set: function (callback) {
  22576. if (this._onAfterUnbindObserver) {
  22577. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  22578. }
  22579. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  22580. },
  22581. enumerable: true,
  22582. configurable: true
  22583. });
  22584. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  22585. set: function (callback) {
  22586. if (this._onBeforeRenderObserver) {
  22587. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  22588. }
  22589. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  22590. },
  22591. enumerable: true,
  22592. configurable: true
  22593. });
  22594. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  22595. set: function (callback) {
  22596. if (this._onAfterRenderObserver) {
  22597. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  22598. }
  22599. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  22600. },
  22601. enumerable: true,
  22602. configurable: true
  22603. });
  22604. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  22605. set: function (callback) {
  22606. if (this._onClearObserver) {
  22607. this.onClearObservable.remove(this._onClearObserver);
  22608. }
  22609. this._onClearObserver = this.onClearObservable.add(callback);
  22610. },
  22611. enumerable: true,
  22612. configurable: true
  22613. });
  22614. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  22615. this._currentRefreshId = -1;
  22616. };
  22617. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  22618. get: function () {
  22619. return this._refreshRate;
  22620. },
  22621. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  22622. set: function (value) {
  22623. this._refreshRate = value;
  22624. this.resetRefreshCounter();
  22625. },
  22626. enumerable: true,
  22627. configurable: true
  22628. });
  22629. RenderTargetTexture.prototype._shouldRender = function () {
  22630. if (this._currentRefreshId === -1) {
  22631. this._currentRefreshId = 1;
  22632. return true;
  22633. }
  22634. if (this.refreshRate === this._currentRefreshId) {
  22635. this._currentRefreshId = 1;
  22636. return true;
  22637. }
  22638. this._currentRefreshId++;
  22639. return false;
  22640. };
  22641. RenderTargetTexture.prototype.isReady = function () {
  22642. if (!this.getScene().renderTargetsEnabled) {
  22643. return false;
  22644. }
  22645. return _super.prototype.isReady.call(this);
  22646. };
  22647. RenderTargetTexture.prototype.getRenderSize = function () {
  22648. return this._size;
  22649. };
  22650. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  22651. get: function () {
  22652. return true;
  22653. },
  22654. enumerable: true,
  22655. configurable: true
  22656. });
  22657. RenderTargetTexture.prototype.scale = function (ratio) {
  22658. var newSize = this._size * ratio;
  22659. this.resize(newSize, this._generateMipMaps);
  22660. };
  22661. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  22662. if (this.isCube) {
  22663. return this._textureMatrix;
  22664. }
  22665. return _super.prototype.getReflectionTextureMatrix.call(this);
  22666. };
  22667. RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
  22668. this.releaseInternalTexture();
  22669. if (this.isCube) {
  22670. this._texture = this.getScene().getEngine().createRenderTargetCubeTexture(size);
  22671. }
  22672. else {
  22673. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  22674. }
  22675. };
  22676. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  22677. var scene = this.getScene();
  22678. if (this.useCameraPostProcesses !== undefined) {
  22679. useCameraPostProcess = this.useCameraPostProcesses;
  22680. }
  22681. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  22682. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  22683. }
  22684. if (this._waitingRenderList) {
  22685. this.renderList = [];
  22686. for (var index = 0; index < this._waitingRenderList.length; index++) {
  22687. var id = this._waitingRenderList[index];
  22688. this.renderList.push(scene.getMeshByID(id));
  22689. }
  22690. delete this._waitingRenderList;
  22691. }
  22692. // Is predicate defined?
  22693. if (this.renderListPredicate) {
  22694. this.renderList.splice(0); // Clear previous renderList
  22695. var sceneMeshes = this.getScene().meshes;
  22696. for (var index = 0; index < sceneMeshes.length; index++) {
  22697. var mesh = sceneMeshes[index];
  22698. if (this.renderListPredicate(mesh)) {
  22699. this.renderList.push(mesh);
  22700. }
  22701. }
  22702. }
  22703. if (this.renderList && this.renderList.length === 0) {
  22704. return;
  22705. }
  22706. // Prepare renderingManager
  22707. this._renderingManager.reset();
  22708. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  22709. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  22710. var sceneRenderId = scene.getRenderId();
  22711. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  22712. var mesh = currentRenderList[meshIndex];
  22713. if (mesh) {
  22714. if (!mesh.isReady()) {
  22715. // Reset _currentRefreshId
  22716. this.resetRefreshCounter();
  22717. continue;
  22718. }
  22719. mesh._preActivateForIntermediateRendering(sceneRenderId);
  22720. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
  22721. mesh._activate(sceneRenderId);
  22722. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  22723. var subMesh = mesh.subMeshes[subIndex];
  22724. scene._activeIndices.addCount(subMesh.indexCount, false);
  22725. this._renderingManager.dispatch(subMesh);
  22726. }
  22727. }
  22728. }
  22729. }
  22730. if (this.isCube) {
  22731. for (var face = 0; face < 6; face++) {
  22732. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  22733. scene.incrementRenderId();
  22734. scene.resetCachedMaterial();
  22735. }
  22736. }
  22737. else {
  22738. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  22739. }
  22740. this.onAfterUnbindObservable.notifyObservers(this);
  22741. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  22742. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  22743. }
  22744. scene.resetCachedMaterial();
  22745. };
  22746. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  22747. var scene = this.getScene();
  22748. var engine = scene.getEngine();
  22749. // Bind
  22750. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  22751. if (this.isCube) {
  22752. engine.bindFramebuffer(this._texture, faceIndex);
  22753. }
  22754. else {
  22755. engine.bindFramebuffer(this._texture);
  22756. }
  22757. }
  22758. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  22759. // Clear
  22760. if (this.onClearObservable.hasObservers()) {
  22761. this.onClearObservable.notifyObservers(engine);
  22762. }
  22763. else {
  22764. engine.clear(scene.clearColor, true, true, true);
  22765. }
  22766. if (!this._doNotChangeAspectRatio) {
  22767. scene.updateTransformMatrix(true);
  22768. }
  22769. // Render
  22770. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  22771. if (useCameraPostProcess) {
  22772. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  22773. }
  22774. if (!this._doNotChangeAspectRatio) {
  22775. scene.updateTransformMatrix(true);
  22776. }
  22777. this.onAfterRenderObservable.notifyObservers(faceIndex);
  22778. // Dump ?
  22779. if (dumpForDebug) {
  22780. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  22781. }
  22782. // Unbind
  22783. if (!this.isCube || faceIndex === 5) {
  22784. if (this.isCube) {
  22785. if (faceIndex === 5) {
  22786. engine.generateMipMapsForCubemap(this._texture);
  22787. }
  22788. }
  22789. engine.unBindFramebuffer(this._texture, this.isCube);
  22790. }
  22791. };
  22792. /**
  22793. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  22794. * This allowed control for front to back rendering or reversly depending of the special needs.
  22795. *
  22796. * @param renderingGroupId The rendering group id corresponding to its index
  22797. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  22798. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  22799. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  22800. */
  22801. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  22802. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  22803. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  22804. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  22805. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  22806. };
  22807. /**
  22808. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  22809. *
  22810. * @param renderingGroupId The rendering group id corresponding to its index
  22811. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  22812. */
  22813. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  22814. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  22815. };
  22816. RenderTargetTexture.prototype.clone = function () {
  22817. var textureSize = this.getSize();
  22818. var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  22819. // Base texture
  22820. newTexture.hasAlpha = this.hasAlpha;
  22821. newTexture.level = this.level;
  22822. // RenderTarget Texture
  22823. newTexture.coordinatesMode = this.coordinatesMode;
  22824. newTexture.renderList = this.renderList.slice(0);
  22825. return newTexture;
  22826. };
  22827. RenderTargetTexture.prototype.serialize = function () {
  22828. if (!this.name) {
  22829. return null;
  22830. }
  22831. var serializationObject = _super.prototype.serialize.call(this);
  22832. serializationObject.renderTargetSize = this.getRenderSize();
  22833. serializationObject.renderList = [];
  22834. for (var index = 0; index < this.renderList.length; index++) {
  22835. serializationObject.renderList.push(this.renderList[index].id);
  22836. }
  22837. return serializationObject;
  22838. };
  22839. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  22840. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  22841. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  22842. return RenderTargetTexture;
  22843. })(BABYLON.Texture);
  22844. BABYLON.RenderTargetTexture = RenderTargetTexture;
  22845. })(BABYLON || (BABYLON = {}));
  22846. var BABYLON;
  22847. (function (BABYLON) {
  22848. var ProceduralTexture = (function (_super) {
  22849. __extends(ProceduralTexture, _super);
  22850. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  22851. if (generateMipMaps === void 0) { generateMipMaps = true; }
  22852. if (isCube === void 0) { isCube = false; }
  22853. _super.call(this, null, scene, !generateMipMaps);
  22854. this.isCube = isCube;
  22855. this.isEnabled = true;
  22856. this._currentRefreshId = -1;
  22857. this._refreshRate = 1;
  22858. this._vertexBuffers = {};
  22859. this._uniforms = new Array();
  22860. this._samplers = new Array();
  22861. this._textures = new Array();
  22862. this._floats = new Array();
  22863. this._floatsArrays = {};
  22864. this._colors3 = new Array();
  22865. this._colors4 = new Array();
  22866. this._vectors2 = new Array();
  22867. this._vectors3 = new Array();
  22868. this._matrices = new Array();
  22869. this._fallbackTextureUsed = false;
  22870. scene._proceduralTextures.push(this);
  22871. this.name = name;
  22872. this.isRenderTarget = true;
  22873. this._size = size;
  22874. this._generateMipMaps = generateMipMaps;
  22875. this.setFragment(fragment);
  22876. this._fallbackTexture = fallbackTexture;
  22877. var engine = scene.getEngine();
  22878. if (isCube) {
  22879. this._texture = engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  22880. this.setFloat("face", 0);
  22881. }
  22882. else {
  22883. this._texture = engine.createRenderTargetTexture(size, generateMipMaps);
  22884. }
  22885. // VBO
  22886. var vertices = [];
  22887. vertices.push(1, 1);
  22888. vertices.push(-1, 1);
  22889. vertices.push(-1, -1);
  22890. vertices.push(1, -1);
  22891. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  22892. // Indices
  22893. var indices = [];
  22894. indices.push(0);
  22895. indices.push(1);
  22896. indices.push(2);
  22897. indices.push(0);
  22898. indices.push(2);
  22899. indices.push(3);
  22900. this._indexBuffer = engine.createIndexBuffer(indices);
  22901. }
  22902. ProceduralTexture.prototype.reset = function () {
  22903. if (this._effect === undefined) {
  22904. return;
  22905. }
  22906. var engine = this.getScene().getEngine();
  22907. engine._releaseEffect(this._effect);
  22908. };
  22909. ProceduralTexture.prototype.isReady = function () {
  22910. var _this = this;
  22911. var engine = this.getScene().getEngine();
  22912. var shaders;
  22913. if (!this._fragment) {
  22914. return false;
  22915. }
  22916. if (this._fallbackTextureUsed) {
  22917. return true;
  22918. }
  22919. if (this._fragment.fragmentElement !== undefined) {
  22920. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  22921. }
  22922. else {
  22923. shaders = { vertex: "procedural", fragment: this._fragment };
  22924. }
  22925. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", null, null, function () {
  22926. _this.releaseInternalTexture();
  22927. if (_this._fallbackTexture) {
  22928. _this._texture = _this._fallbackTexture._texture;
  22929. _this._texture.references++;
  22930. }
  22931. _this._fallbackTextureUsed = true;
  22932. });
  22933. return this._effect.isReady();
  22934. };
  22935. ProceduralTexture.prototype.resetRefreshCounter = function () {
  22936. this._currentRefreshId = -1;
  22937. };
  22938. ProceduralTexture.prototype.setFragment = function (fragment) {
  22939. this._fragment = fragment;
  22940. };
  22941. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  22942. get: function () {
  22943. return this._refreshRate;
  22944. },
  22945. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  22946. set: function (value) {
  22947. this._refreshRate = value;
  22948. this.resetRefreshCounter();
  22949. },
  22950. enumerable: true,
  22951. configurable: true
  22952. });
  22953. ProceduralTexture.prototype._shouldRender = function () {
  22954. if (!this.isEnabled || !this.isReady() || !this._texture) {
  22955. return false;
  22956. }
  22957. if (this._fallbackTextureUsed) {
  22958. return false;
  22959. }
  22960. if (this._currentRefreshId === -1) {
  22961. this._currentRefreshId = 1;
  22962. return true;
  22963. }
  22964. if (this.refreshRate === this._currentRefreshId) {
  22965. this._currentRefreshId = 1;
  22966. return true;
  22967. }
  22968. this._currentRefreshId++;
  22969. return false;
  22970. };
  22971. ProceduralTexture.prototype.getRenderSize = function () {
  22972. return this._size;
  22973. };
  22974. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  22975. if (this._fallbackTextureUsed) {
  22976. return;
  22977. }
  22978. this.releaseInternalTexture();
  22979. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  22980. };
  22981. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  22982. if (this._uniforms.indexOf(uniformName) === -1) {
  22983. this._uniforms.push(uniformName);
  22984. }
  22985. };
  22986. ProceduralTexture.prototype.setTexture = function (name, texture) {
  22987. if (this._samplers.indexOf(name) === -1) {
  22988. this._samplers.push(name);
  22989. }
  22990. this._textures[name] = texture;
  22991. return this;
  22992. };
  22993. ProceduralTexture.prototype.setFloat = function (name, value) {
  22994. this._checkUniform(name);
  22995. this._floats[name] = value;
  22996. return this;
  22997. };
  22998. ProceduralTexture.prototype.setFloats = function (name, value) {
  22999. this._checkUniform(name);
  23000. this._floatsArrays[name] = value;
  23001. return this;
  23002. };
  23003. ProceduralTexture.prototype.setColor3 = function (name, value) {
  23004. this._checkUniform(name);
  23005. this._colors3[name] = value;
  23006. return this;
  23007. };
  23008. ProceduralTexture.prototype.setColor4 = function (name, value) {
  23009. this._checkUniform(name);
  23010. this._colors4[name] = value;
  23011. return this;
  23012. };
  23013. ProceduralTexture.prototype.setVector2 = function (name, value) {
  23014. this._checkUniform(name);
  23015. this._vectors2[name] = value;
  23016. return this;
  23017. };
  23018. ProceduralTexture.prototype.setVector3 = function (name, value) {
  23019. this._checkUniform(name);
  23020. this._vectors3[name] = value;
  23021. return this;
  23022. };
  23023. ProceduralTexture.prototype.setMatrix = function (name, value) {
  23024. this._checkUniform(name);
  23025. this._matrices[name] = value;
  23026. return this;
  23027. };
  23028. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  23029. var scene = this.getScene();
  23030. var engine = scene.getEngine();
  23031. // Render
  23032. engine.enableEffect(this._effect);
  23033. engine.setState(false);
  23034. // Texture
  23035. for (var name in this._textures) {
  23036. this._effect.setTexture(name, this._textures[name]);
  23037. }
  23038. // Float
  23039. for (name in this._floats) {
  23040. this._effect.setFloat(name, this._floats[name]);
  23041. }
  23042. // Floats
  23043. for (name in this._floatsArrays) {
  23044. this._effect.setArray(name, this._floatsArrays[name]);
  23045. }
  23046. // Color3
  23047. for (name in this._colors3) {
  23048. this._effect.setColor3(name, this._colors3[name]);
  23049. }
  23050. // Color4
  23051. for (name in this._colors4) {
  23052. var color = this._colors4[name];
  23053. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  23054. }
  23055. // Vector2
  23056. for (name in this._vectors2) {
  23057. this._effect.setVector2(name, this._vectors2[name]);
  23058. }
  23059. // Vector3
  23060. for (name in this._vectors3) {
  23061. this._effect.setVector3(name, this._vectors3[name]);
  23062. }
  23063. // Matrix
  23064. for (name in this._matrices) {
  23065. this._effect.setMatrix(name, this._matrices[name]);
  23066. }
  23067. // VBOs
  23068. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  23069. if (this.isCube) {
  23070. for (var face = 0; face < 6; face++) {
  23071. engine.bindFramebuffer(this._texture, face);
  23072. this._effect.setFloat("face", face);
  23073. // Clear
  23074. engine.clear(scene.clearColor, true, true, true);
  23075. // Draw order
  23076. engine.draw(true, 0, 6);
  23077. // Mipmaps
  23078. if (face === 5) {
  23079. engine.generateMipMapsForCubemap(this._texture);
  23080. }
  23081. }
  23082. }
  23083. else {
  23084. engine.bindFramebuffer(this._texture);
  23085. // Clear
  23086. engine.clear(scene.clearColor, true, true, true);
  23087. // Draw order
  23088. engine.draw(true, 0, 6);
  23089. }
  23090. // Unbind
  23091. engine.unBindFramebuffer(this._texture, this.isCube);
  23092. if (this.onGenerated) {
  23093. this.onGenerated();
  23094. }
  23095. };
  23096. ProceduralTexture.prototype.clone = function () {
  23097. var textureSize = this.getSize();
  23098. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  23099. // Base texture
  23100. newTexture.hasAlpha = this.hasAlpha;
  23101. newTexture.level = this.level;
  23102. // RenderTarget Texture
  23103. newTexture.coordinatesMode = this.coordinatesMode;
  23104. return newTexture;
  23105. };
  23106. ProceduralTexture.prototype.dispose = function () {
  23107. var index = this.getScene()._proceduralTextures.indexOf(this);
  23108. if (index >= 0) {
  23109. this.getScene()._proceduralTextures.splice(index, 1);
  23110. }
  23111. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  23112. if (vertexBuffer) {
  23113. vertexBuffer.dispose();
  23114. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  23115. }
  23116. if (this._indexBuffer && this.getScene().getEngine()._releaseBuffer(this._indexBuffer)) {
  23117. this._indexBuffer = null;
  23118. }
  23119. _super.prototype.dispose.call(this);
  23120. };
  23121. return ProceduralTexture;
  23122. })(BABYLON.Texture);
  23123. BABYLON.ProceduralTexture = ProceduralTexture;
  23124. })(BABYLON || (BABYLON = {}));
  23125. var BABYLON;
  23126. (function (BABYLON) {
  23127. var MirrorTexture = (function (_super) {
  23128. __extends(MirrorTexture, _super);
  23129. function MirrorTexture(name, size, scene, generateMipMaps) {
  23130. var _this = this;
  23131. _super.call(this, name, size, scene, generateMipMaps, true);
  23132. this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  23133. this._transformMatrix = BABYLON.Matrix.Zero();
  23134. this._mirrorMatrix = BABYLON.Matrix.Zero();
  23135. this.onBeforeRenderObservable.add(function () {
  23136. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  23137. _this._savedViewMatrix = scene.getViewMatrix();
  23138. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  23139. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  23140. scene.clipPlane = _this.mirrorPlane;
  23141. scene.getEngine().cullBackFaces = false;
  23142. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.position, _this._mirrorMatrix);
  23143. });
  23144. this.onAfterRenderObservable.add(function () {
  23145. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  23146. scene.getEngine().cullBackFaces = true;
  23147. scene._mirroredCameraPosition = null;
  23148. delete scene.clipPlane;
  23149. });
  23150. }
  23151. MirrorTexture.prototype.clone = function () {
  23152. var textureSize = this.getSize();
  23153. var newTexture = new MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  23154. // Base texture
  23155. newTexture.hasAlpha = this.hasAlpha;
  23156. newTexture.level = this.level;
  23157. // Mirror Texture
  23158. newTexture.mirrorPlane = this.mirrorPlane.clone();
  23159. newTexture.renderList = this.renderList.slice(0);
  23160. return newTexture;
  23161. };
  23162. MirrorTexture.prototype.serialize = function () {
  23163. if (!this.name) {
  23164. return null;
  23165. }
  23166. var serializationObject = _super.prototype.serialize.call(this);
  23167. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  23168. return serializationObject;
  23169. };
  23170. return MirrorTexture;
  23171. })(BABYLON.RenderTargetTexture);
  23172. BABYLON.MirrorTexture = MirrorTexture;
  23173. })(BABYLON || (BABYLON = {}));
  23174. var BABYLON;
  23175. (function (BABYLON) {
  23176. /**
  23177. * Creates a refraction texture used by refraction channel of the standard material.
  23178. * @param name the texture name
  23179. * @param size size of the underlying texture
  23180. * @param scene root scene
  23181. */
  23182. var RefractionTexture = (function (_super) {
  23183. __extends(RefractionTexture, _super);
  23184. function RefractionTexture(name, size, scene, generateMipMaps) {
  23185. var _this = this;
  23186. _super.call(this, name, size, scene, generateMipMaps, true);
  23187. this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  23188. this.depth = 2.0;
  23189. this.onBeforeRenderObservable.add(function () {
  23190. scene.clipPlane = _this.refractionPlane;
  23191. });
  23192. this.onAfterRenderObservable.add(function () {
  23193. delete scene.clipPlane;
  23194. });
  23195. }
  23196. RefractionTexture.prototype.clone = function () {
  23197. var textureSize = this.getSize();
  23198. var newTexture = new RefractionTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  23199. // Base texture
  23200. newTexture.hasAlpha = this.hasAlpha;
  23201. newTexture.level = this.level;
  23202. // Refraction Texture
  23203. newTexture.refractionPlane = this.refractionPlane.clone();
  23204. newTexture.renderList = this.renderList.slice(0);
  23205. newTexture.depth = this.depth;
  23206. return newTexture;
  23207. };
  23208. RefractionTexture.prototype.serialize = function () {
  23209. if (!this.name) {
  23210. return null;
  23211. }
  23212. var serializationObject = _super.prototype.serialize.call(this);
  23213. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  23214. serializationObject.depth = this.depth;
  23215. return serializationObject;
  23216. };
  23217. return RefractionTexture;
  23218. })(BABYLON.RenderTargetTexture);
  23219. BABYLON.RefractionTexture = RefractionTexture;
  23220. })(BABYLON || (BABYLON = {}));
  23221. var BABYLON;
  23222. (function (BABYLON) {
  23223. var DynamicTexture = (function (_super) {
  23224. __extends(DynamicTexture, _super);
  23225. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  23226. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  23227. _super.call(this, null, scene, !generateMipMaps);
  23228. this.name = name;
  23229. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  23230. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  23231. this._generateMipMaps = generateMipMaps;
  23232. if (options.getContext) {
  23233. this._canvas = options;
  23234. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  23235. }
  23236. else {
  23237. this._canvas = document.createElement("canvas");
  23238. if (options.width) {
  23239. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  23240. }
  23241. else {
  23242. this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  23243. }
  23244. }
  23245. var textureSize = this.getSize();
  23246. this._canvas.width = textureSize.width;
  23247. this._canvas.height = textureSize.height;
  23248. this._context = this._canvas.getContext("2d");
  23249. }
  23250. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  23251. get: function () {
  23252. return true;
  23253. },
  23254. enumerable: true,
  23255. configurable: true
  23256. });
  23257. DynamicTexture.prototype.scale = function (ratio) {
  23258. var textureSize = this.getSize();
  23259. textureSize.width *= ratio;
  23260. textureSize.height *= ratio;
  23261. this._canvas.width = textureSize.width;
  23262. this._canvas.height = textureSize.height;
  23263. this.releaseInternalTexture();
  23264. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  23265. };
  23266. DynamicTexture.prototype.getContext = function () {
  23267. return this._context;
  23268. };
  23269. DynamicTexture.prototype.clear = function () {
  23270. var size = this.getSize();
  23271. this._context.fillRect(0, 0, size.width, size.height);
  23272. };
  23273. DynamicTexture.prototype.update = function (invertY) {
  23274. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  23275. };
  23276. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  23277. if (update === void 0) { update = true; }
  23278. var size = this.getSize();
  23279. if (clearColor) {
  23280. this._context.fillStyle = clearColor;
  23281. this._context.fillRect(0, 0, size.width, size.height);
  23282. }
  23283. this._context.font = font;
  23284. if (x === null) {
  23285. var textSize = this._context.measureText(text);
  23286. x = (size.width - textSize.width) / 2;
  23287. }
  23288. this._context.fillStyle = color;
  23289. this._context.fillText(text, x, y);
  23290. if (update) {
  23291. this.update(invertY);
  23292. }
  23293. };
  23294. DynamicTexture.prototype.clone = function () {
  23295. var textureSize = this.getSize();
  23296. var newTexture = new DynamicTexture(this.name, textureSize, this.getScene(), this._generateMipMaps);
  23297. // Base texture
  23298. newTexture.hasAlpha = this.hasAlpha;
  23299. newTexture.level = this.level;
  23300. // Dynamic Texture
  23301. newTexture.wrapU = this.wrapU;
  23302. newTexture.wrapV = this.wrapV;
  23303. return newTexture;
  23304. };
  23305. return DynamicTexture;
  23306. })(BABYLON.Texture);
  23307. BABYLON.DynamicTexture = DynamicTexture;
  23308. })(BABYLON || (BABYLON = {}));
  23309. var BABYLON;
  23310. (function (BABYLON) {
  23311. var VideoTexture = (function (_super) {
  23312. __extends(VideoTexture, _super);
  23313. /**
  23314. * Creates a video texture.
  23315. * Sample : https://doc.babylonjs.com/tutorials/01._Advanced_Texturing
  23316. * @param {Array} urlsOrVideo can be used to provide an array of urls or an already setup HTML video element.
  23317. * @param {BABYLON.Scene} scene is obviously the current scene.
  23318. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  23319. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  23320. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  23321. */
  23322. function VideoTexture(name, urlsOrVideo, scene, generateMipMaps, invertY, samplingMode) {
  23323. var _this = this;
  23324. if (generateMipMaps === void 0) { generateMipMaps = false; }
  23325. if (invertY === void 0) { invertY = false; }
  23326. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  23327. _super.call(this, null, scene, !generateMipMaps, invertY);
  23328. this._autoLaunch = true;
  23329. var urls;
  23330. this.name = name;
  23331. if (urlsOrVideo instanceof HTMLVideoElement) {
  23332. this.video = urlsOrVideo;
  23333. }
  23334. else {
  23335. urls = urlsOrVideo;
  23336. this.video = document.createElement("video");
  23337. this.video.autoplay = false;
  23338. this.video.loop = true;
  23339. }
  23340. this._generateMipMaps = generateMipMaps;
  23341. this._samplingMode = samplingMode;
  23342. if (BABYLON.Tools.IsExponentOfTwo(this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(this.video.videoHeight)) {
  23343. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  23344. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  23345. }
  23346. else {
  23347. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  23348. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  23349. this._generateMipMaps = false;
  23350. }
  23351. if (urls) {
  23352. this.video.addEventListener("canplaythrough", function () {
  23353. _this._createTexture();
  23354. });
  23355. urls.forEach(function (url) {
  23356. var source = document.createElement("source");
  23357. source.src = url;
  23358. _this.video.appendChild(source);
  23359. });
  23360. }
  23361. else {
  23362. this._createTexture();
  23363. }
  23364. this._lastUpdate = BABYLON.Tools.Now;
  23365. }
  23366. VideoTexture.prototype._createTexture = function () {
  23367. this._texture = this.getScene().getEngine().createDynamicTexture(this.video.videoWidth, this.video.videoHeight, this._generateMipMaps, this._samplingMode);
  23368. this._texture.isReady = true;
  23369. };
  23370. VideoTexture.prototype.update = function () {
  23371. if (this._autoLaunch) {
  23372. this._autoLaunch = false;
  23373. this.video.play();
  23374. }
  23375. var now = BABYLON.Tools.Now;
  23376. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  23377. return false;
  23378. }
  23379. this._lastUpdate = now;
  23380. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  23381. return true;
  23382. };
  23383. return VideoTexture;
  23384. })(BABYLON.Texture);
  23385. BABYLON.VideoTexture = VideoTexture;
  23386. })(BABYLON || (BABYLON = {}));
  23387. var BABYLON;
  23388. (function (BABYLON) {
  23389. var CustomProceduralTexture = (function (_super) {
  23390. __extends(CustomProceduralTexture, _super);
  23391. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  23392. _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps);
  23393. this._animate = true;
  23394. this._time = 0;
  23395. this._texturePath = texturePath;
  23396. //Try to load json
  23397. this.loadJson(texturePath);
  23398. this.refreshRate = 1;
  23399. }
  23400. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  23401. var _this = this;
  23402. var that = this;
  23403. function noConfigFile() {
  23404. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  23405. try {
  23406. that.setFragment(that._texturePath);
  23407. }
  23408. catch (ex) {
  23409. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  23410. }
  23411. }
  23412. var configFileUrl = jsonUrl + "/config.json";
  23413. var xhr = new XMLHttpRequest();
  23414. xhr.open("GET", configFileUrl, true);
  23415. xhr.addEventListener("load", function () {
  23416. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  23417. try {
  23418. _this._config = JSON.parse(xhr.response);
  23419. _this.updateShaderUniforms();
  23420. _this.updateTextures();
  23421. _this.setFragment(_this._texturePath + "/custom");
  23422. _this._animate = _this._config.animate;
  23423. _this.refreshRate = _this._config.refreshrate;
  23424. }
  23425. catch (ex) {
  23426. noConfigFile();
  23427. }
  23428. }
  23429. else {
  23430. noConfigFile();
  23431. }
  23432. }, false);
  23433. xhr.addEventListener("error", function () {
  23434. noConfigFile();
  23435. }, false);
  23436. try {
  23437. xhr.send();
  23438. }
  23439. catch (ex) {
  23440. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  23441. }
  23442. };
  23443. CustomProceduralTexture.prototype.isReady = function () {
  23444. if (!_super.prototype.isReady.call(this)) {
  23445. return false;
  23446. }
  23447. for (var name in this._textures) {
  23448. var texture = this._textures[name];
  23449. if (!texture.isReady()) {
  23450. return false;
  23451. }
  23452. }
  23453. return true;
  23454. };
  23455. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  23456. if (this._animate) {
  23457. this._time += this.getScene().getAnimationRatio() * 0.03;
  23458. this.updateShaderUniforms();
  23459. }
  23460. _super.prototype.render.call(this, useCameraPostProcess);
  23461. };
  23462. CustomProceduralTexture.prototype.updateTextures = function () {
  23463. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  23464. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  23465. }
  23466. };
  23467. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  23468. if (this._config) {
  23469. for (var j = 0; j < this._config.uniforms.length; j++) {
  23470. var uniform = this._config.uniforms[j];
  23471. switch (uniform.type) {
  23472. case "float":
  23473. this.setFloat(uniform.name, uniform.value);
  23474. break;
  23475. case "color3":
  23476. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  23477. break;
  23478. case "color4":
  23479. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  23480. break;
  23481. case "vector2":
  23482. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  23483. break;
  23484. case "vector3":
  23485. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  23486. break;
  23487. }
  23488. }
  23489. }
  23490. this.setFloat("time", this._time);
  23491. };
  23492. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  23493. get: function () {
  23494. return this._animate;
  23495. },
  23496. set: function (value) {
  23497. this._animate = value;
  23498. },
  23499. enumerable: true,
  23500. configurable: true
  23501. });
  23502. return CustomProceduralTexture;
  23503. })(BABYLON.ProceduralTexture);
  23504. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  23505. })(BABYLON || (BABYLON = {}));
  23506. var BABYLON;
  23507. (function (BABYLON) {
  23508. var EffectFallbacks = (function () {
  23509. function EffectFallbacks() {
  23510. this._defines = {};
  23511. this._currentRank = 32;
  23512. this._maxRank = -1;
  23513. }
  23514. EffectFallbacks.prototype.addFallback = function (rank, define) {
  23515. if (!this._defines[rank]) {
  23516. if (rank < this._currentRank) {
  23517. this._currentRank = rank;
  23518. }
  23519. if (rank > this._maxRank) {
  23520. this._maxRank = rank;
  23521. }
  23522. this._defines[rank] = new Array();
  23523. }
  23524. this._defines[rank].push(define);
  23525. };
  23526. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  23527. this._meshRank = rank;
  23528. this._mesh = mesh;
  23529. if (rank > this._maxRank) {
  23530. this._maxRank = rank;
  23531. }
  23532. };
  23533. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  23534. get: function () {
  23535. return this._currentRank <= this._maxRank;
  23536. },
  23537. enumerable: true,
  23538. configurable: true
  23539. });
  23540. EffectFallbacks.prototype.reduce = function (currentDefines) {
  23541. var currentFallbacks = this._defines[this._currentRank];
  23542. for (var index = 0; index < currentFallbacks.length; index++) {
  23543. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  23544. }
  23545. if (this._mesh && this._currentRank === this._meshRank) {
  23546. this._mesh.computeBonesUsingShaders = false;
  23547. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  23548. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  23549. }
  23550. this._currentRank++;
  23551. return currentDefines;
  23552. };
  23553. return EffectFallbacks;
  23554. })();
  23555. BABYLON.EffectFallbacks = EffectFallbacks;
  23556. var Effect = (function () {
  23557. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  23558. var _this = this;
  23559. this._isReady = false;
  23560. this._compilationError = "";
  23561. this._valueCache = {};
  23562. this._engine = engine;
  23563. this.name = baseName;
  23564. this.defines = defines;
  23565. this._uniformsNames = uniformsNames.concat(samplers);
  23566. this._samplers = samplers;
  23567. this._attributesNames = attributesNames;
  23568. this.onError = onError;
  23569. this.onCompiled = onCompiled;
  23570. this._indexParameters = indexParameters;
  23571. var vertexSource;
  23572. var fragmentSource;
  23573. if (baseName.vertexElement) {
  23574. vertexSource = document.getElementById(baseName.vertexElement);
  23575. if (!vertexSource) {
  23576. vertexSource = baseName.vertexElement;
  23577. }
  23578. }
  23579. else {
  23580. vertexSource = baseName.vertex || baseName;
  23581. }
  23582. if (baseName.fragmentElement) {
  23583. fragmentSource = document.getElementById(baseName.fragmentElement);
  23584. if (!fragmentSource) {
  23585. fragmentSource = baseName.fragmentElement;
  23586. }
  23587. }
  23588. else {
  23589. fragmentSource = baseName.fragment || baseName;
  23590. }
  23591. this._loadVertexShader(vertexSource, function (vertexCode) {
  23592. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  23593. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  23594. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  23595. _this._prepareEffect(vertexCodeWithIncludes, fragmentCodeWithIncludes, attributesNames, defines, fallbacks);
  23596. });
  23597. });
  23598. });
  23599. });
  23600. }
  23601. // Properties
  23602. Effect.prototype.isReady = function () {
  23603. return this._isReady;
  23604. };
  23605. Effect.prototype.getProgram = function () {
  23606. return this._program;
  23607. };
  23608. Effect.prototype.getAttributesNames = function () {
  23609. return this._attributesNames;
  23610. };
  23611. Effect.prototype.getAttributeLocation = function (index) {
  23612. return this._attributes[index];
  23613. };
  23614. Effect.prototype.getAttributeLocationByName = function (name) {
  23615. var index = this._attributesNames.indexOf(name);
  23616. return this._attributes[index];
  23617. };
  23618. Effect.prototype.getAttributesCount = function () {
  23619. return this._attributes.length;
  23620. };
  23621. Effect.prototype.getUniformIndex = function (uniformName) {
  23622. return this._uniformsNames.indexOf(uniformName);
  23623. };
  23624. Effect.prototype.getUniform = function (uniformName) {
  23625. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  23626. };
  23627. Effect.prototype.getSamplers = function () {
  23628. return this._samplers;
  23629. };
  23630. Effect.prototype.getCompilationError = function () {
  23631. return this._compilationError;
  23632. };
  23633. // Methods
  23634. Effect.prototype._loadVertexShader = function (vertex, callback) {
  23635. // DOM element ?
  23636. if (vertex instanceof HTMLElement) {
  23637. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  23638. callback(vertexCode);
  23639. return;
  23640. }
  23641. // Is in local store ?
  23642. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  23643. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  23644. return;
  23645. }
  23646. var vertexShaderUrl;
  23647. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  23648. vertexShaderUrl = vertex;
  23649. }
  23650. else {
  23651. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  23652. }
  23653. // Vertex shader
  23654. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  23655. };
  23656. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  23657. // DOM element ?
  23658. if (fragment instanceof HTMLElement) {
  23659. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  23660. callback(fragmentCode);
  23661. return;
  23662. }
  23663. // Is in local store ?
  23664. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  23665. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  23666. return;
  23667. }
  23668. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  23669. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  23670. return;
  23671. }
  23672. var fragmentShaderUrl;
  23673. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  23674. fragmentShaderUrl = fragment;
  23675. }
  23676. else {
  23677. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  23678. }
  23679. // Fragment shader
  23680. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  23681. };
  23682. Effect.prototype._dumpShadersName = function () {
  23683. if (this.name.vertexElement) {
  23684. BABYLON.Tools.Error("Vertex shader:" + this.name.vertexElement);
  23685. BABYLON.Tools.Error("Fragment shader:" + this.name.fragmentElement);
  23686. }
  23687. else if (this.name.vertex) {
  23688. BABYLON.Tools.Error("Vertex shader:" + this.name.vertex);
  23689. BABYLON.Tools.Error("Fragment shader:" + this.name.fragment);
  23690. }
  23691. else {
  23692. BABYLON.Tools.Error("Vertex shader:" + this.name);
  23693. BABYLON.Tools.Error("Fragment shader:" + this.name);
  23694. }
  23695. };
  23696. Effect.prototype._processIncludes = function (sourceCode, callback) {
  23697. var _this = this;
  23698. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  23699. var match = regex.exec(sourceCode);
  23700. var returnValue = new String(sourceCode);
  23701. while (match != null) {
  23702. var includeFile = match[1];
  23703. if (Effect.IncludesShadersStore[includeFile]) {
  23704. // Substitution
  23705. var includeContent = Effect.IncludesShadersStore[includeFile];
  23706. if (match[2]) {
  23707. var splits = match[3].split(",");
  23708. for (var index = 0; index < splits.length; index += 2) {
  23709. var source = new RegExp(splits[index], "g");
  23710. var dest = splits[index + 1];
  23711. includeContent = includeContent.replace(source, dest);
  23712. }
  23713. }
  23714. if (match[4]) {
  23715. var indexString = match[5];
  23716. if (indexString.indexOf("..") !== -1) {
  23717. var indexSplits = indexString.split("..");
  23718. var minIndex = parseInt(indexSplits[0]);
  23719. var maxIndex = parseInt(indexSplits[1]);
  23720. var sourceIncludeContent = includeContent.slice(0);
  23721. includeContent = "";
  23722. if (isNaN(maxIndex)) {
  23723. maxIndex = this._indexParameters[indexSplits[1]];
  23724. }
  23725. for (var i = minIndex; i <= maxIndex; i++) {
  23726. includeContent += sourceIncludeContent.replace(/\{X\}/g, i) + "\n";
  23727. }
  23728. }
  23729. else {
  23730. includeContent = includeContent.replace(/\{X\}/g, indexString);
  23731. }
  23732. }
  23733. // Replace
  23734. returnValue = returnValue.replace(match[0], includeContent);
  23735. }
  23736. else {
  23737. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  23738. BABYLON.Tools.LoadFile(includeShaderUrl, function (fileContent) {
  23739. Effect.IncludesShadersStore[includeFile] = fileContent;
  23740. _this._processIncludes(returnValue, callback);
  23741. });
  23742. return;
  23743. }
  23744. match = regex.exec(sourceCode);
  23745. }
  23746. callback(returnValue);
  23747. };
  23748. Effect.prototype._processPrecision = function (source) {
  23749. if (source.indexOf("precision highp float") === -1) {
  23750. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  23751. source = "precision mediump float;\n" + source;
  23752. }
  23753. else {
  23754. source = "precision highp float;\n" + source;
  23755. }
  23756. }
  23757. else {
  23758. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  23759. source = source.replace("precision highp float", "precision mediump float");
  23760. }
  23761. }
  23762. return source;
  23763. };
  23764. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  23765. try {
  23766. var engine = this._engine;
  23767. // Precision
  23768. vertexSourceCode = this._processPrecision(vertexSourceCode);
  23769. fragmentSourceCode = this._processPrecision(fragmentSourceCode);
  23770. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  23771. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  23772. this._attributes = engine.getAttributes(this._program, attributesNames);
  23773. var index;
  23774. for (index = 0; index < this._samplers.length; index++) {
  23775. var sampler = this.getUniform(this._samplers[index]);
  23776. if (sampler == null) {
  23777. this._samplers.splice(index, 1);
  23778. index--;
  23779. }
  23780. }
  23781. engine.bindSamplers(this);
  23782. this._isReady = true;
  23783. if (this.onCompiled) {
  23784. this.onCompiled(this);
  23785. }
  23786. }
  23787. catch (e) {
  23788. // Let's go through fallbacks then
  23789. if (fallbacks && fallbacks.isMoreFallbacks) {
  23790. BABYLON.Tools.Error("Unable to compile effect with current defines. Trying next fallback.");
  23791. this._dumpShadersName();
  23792. defines = fallbacks.reduce(defines);
  23793. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  23794. }
  23795. else {
  23796. BABYLON.Tools.Error("Unable to compile effect: ");
  23797. this._dumpShadersName();
  23798. BABYLON.Tools.Error("Defines: " + defines);
  23799. BABYLON.Tools.Error("Error: " + e.message);
  23800. this._compilationError = e.message;
  23801. if (this.onError) {
  23802. this.onError(this, this._compilationError);
  23803. }
  23804. }
  23805. }
  23806. };
  23807. Object.defineProperty(Effect.prototype, "isSupported", {
  23808. get: function () {
  23809. return this._compilationError === "";
  23810. },
  23811. enumerable: true,
  23812. configurable: true
  23813. });
  23814. Effect.prototype._bindTexture = function (channel, texture) {
  23815. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  23816. };
  23817. Effect.prototype.setTexture = function (channel, texture) {
  23818. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  23819. };
  23820. Effect.prototype.setTextureArray = function (channel, textures) {
  23821. if (this._samplers.indexOf(channel + "Ex") === -1) {
  23822. var initialPos = this._samplers.indexOf(channel);
  23823. for (var index = 1; index < textures.length; index++) {
  23824. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  23825. }
  23826. }
  23827. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  23828. };
  23829. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  23830. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  23831. };
  23832. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  23833. var changed = false;
  23834. var cache = this._valueCache[uniformName];
  23835. if (!cache || !(cache instanceof BABYLON.Matrix)) {
  23836. changed = true;
  23837. cache = new BABYLON.Matrix();
  23838. }
  23839. var tm = cache.m;
  23840. var om = matrix.m;
  23841. for (var index = 0; index < 16; index++) {
  23842. if (tm[index] !== om[index]) {
  23843. tm[index] = om[index];
  23844. changed = true;
  23845. }
  23846. }
  23847. this._valueCache[uniformName] = cache;
  23848. return changed;
  23849. };
  23850. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  23851. var cache = this._valueCache[uniformName];
  23852. if (!cache) {
  23853. cache = [x, y];
  23854. this._valueCache[uniformName] = cache;
  23855. return true;
  23856. }
  23857. var changed = false;
  23858. if (cache[0] !== x) {
  23859. cache[0] = x;
  23860. changed = true;
  23861. }
  23862. if (cache[1] !== y) {
  23863. cache[1] = y;
  23864. changed = true;
  23865. }
  23866. return changed;
  23867. };
  23868. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  23869. var cache = this._valueCache[uniformName];
  23870. if (!cache) {
  23871. cache = [x, y, z];
  23872. this._valueCache[uniformName] = cache;
  23873. return true;
  23874. }
  23875. var changed = false;
  23876. if (cache[0] !== x) {
  23877. cache[0] = x;
  23878. changed = true;
  23879. }
  23880. if (cache[1] !== y) {
  23881. cache[1] = y;
  23882. changed = true;
  23883. }
  23884. if (cache[2] !== z) {
  23885. cache[2] = z;
  23886. changed = true;
  23887. }
  23888. return changed;
  23889. };
  23890. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  23891. var cache = this._valueCache[uniformName];
  23892. if (!cache) {
  23893. cache = [x, y, z, w];
  23894. this._valueCache[uniformName] = cache;
  23895. return true;
  23896. }
  23897. var changed = false;
  23898. if (cache[0] !== x) {
  23899. cache[0] = x;
  23900. changed = true;
  23901. }
  23902. if (cache[1] !== y) {
  23903. cache[1] = y;
  23904. changed = true;
  23905. }
  23906. if (cache[2] !== z) {
  23907. cache[2] = z;
  23908. changed = true;
  23909. }
  23910. if (cache[3] !== w) {
  23911. cache[3] = w;
  23912. changed = true;
  23913. }
  23914. return changed;
  23915. };
  23916. Effect.prototype.setIntArray = function (uniformName, array) {
  23917. this._valueCache[uniformName] = null;
  23918. this._engine.setIntArray(this.getUniform(uniformName), array);
  23919. return this;
  23920. };
  23921. Effect.prototype.setIntArray2 = function (uniformName, array) {
  23922. this._valueCache[uniformName] = null;
  23923. this._engine.setIntArray2(this.getUniform(uniformName), array);
  23924. return this;
  23925. };
  23926. Effect.prototype.setIntArray3 = function (uniformName, array) {
  23927. this._valueCache[uniformName] = null;
  23928. this._engine.setIntArray3(this.getUniform(uniformName), array);
  23929. return this;
  23930. };
  23931. Effect.prototype.setIntArray4 = function (uniformName, array) {
  23932. this._valueCache[uniformName] = null;
  23933. this._engine.setIntArray4(this.getUniform(uniformName), array);
  23934. return this;
  23935. };
  23936. Effect.prototype.setFloatArray = function (uniformName, array) {
  23937. this._valueCache[uniformName] = null;
  23938. this._engine.setFloatArray(this.getUniform(uniformName), array);
  23939. return this;
  23940. };
  23941. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  23942. this._valueCache[uniformName] = null;
  23943. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  23944. return this;
  23945. };
  23946. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  23947. this._valueCache[uniformName] = null;
  23948. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  23949. return this;
  23950. };
  23951. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  23952. this._valueCache[uniformName] = null;
  23953. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  23954. return this;
  23955. };
  23956. Effect.prototype.setArray = function (uniformName, array) {
  23957. this._valueCache[uniformName] = null;
  23958. this._engine.setArray(this.getUniform(uniformName), array);
  23959. return this;
  23960. };
  23961. Effect.prototype.setArray2 = function (uniformName, array) {
  23962. this._valueCache[uniformName] = null;
  23963. this._engine.setArray2(this.getUniform(uniformName), array);
  23964. return this;
  23965. };
  23966. Effect.prototype.setArray3 = function (uniformName, array) {
  23967. this._valueCache[uniformName] = null;
  23968. this._engine.setArray3(this.getUniform(uniformName), array);
  23969. return this;
  23970. };
  23971. Effect.prototype.setArray4 = function (uniformName, array) {
  23972. this._valueCache[uniformName] = null;
  23973. this._engine.setArray4(this.getUniform(uniformName), array);
  23974. return this;
  23975. };
  23976. Effect.prototype.setMatrices = function (uniformName, matrices) {
  23977. this._valueCache[uniformName] = null;
  23978. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  23979. return this;
  23980. };
  23981. Effect.prototype.setMatrix = function (uniformName, matrix) {
  23982. if (this._cacheMatrix(uniformName, matrix)) {
  23983. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  23984. }
  23985. return this;
  23986. };
  23987. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  23988. this._valueCache[uniformName] = null;
  23989. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  23990. return this;
  23991. };
  23992. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  23993. this._valueCache[uniformName] = null;
  23994. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  23995. return this;
  23996. };
  23997. Effect.prototype.setFloat = function (uniformName, value) {
  23998. var cache = this._valueCache[uniformName];
  23999. if (cache !== undefined && cache === value)
  24000. return this;
  24001. this._valueCache[uniformName] = value;
  24002. this._engine.setFloat(this.getUniform(uniformName), value);
  24003. return this;
  24004. };
  24005. Effect.prototype.setBool = function (uniformName, bool) {
  24006. var cache = this._valueCache[uniformName];
  24007. if (cache !== undefined && cache === bool)
  24008. return this;
  24009. this._valueCache[uniformName] = bool;
  24010. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  24011. return this;
  24012. };
  24013. Effect.prototype.setVector2 = function (uniformName, vector2) {
  24014. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  24015. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  24016. }
  24017. return this;
  24018. };
  24019. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  24020. if (this._cacheFloat2(uniformName, x, y)) {
  24021. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  24022. }
  24023. return this;
  24024. };
  24025. Effect.prototype.setVector3 = function (uniformName, vector3) {
  24026. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  24027. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  24028. }
  24029. return this;
  24030. };
  24031. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  24032. if (this._cacheFloat3(uniformName, x, y, z)) {
  24033. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  24034. }
  24035. return this;
  24036. };
  24037. Effect.prototype.setVector4 = function (uniformName, vector4) {
  24038. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  24039. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  24040. }
  24041. return this;
  24042. };
  24043. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  24044. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  24045. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  24046. }
  24047. return this;
  24048. };
  24049. Effect.prototype.setColor3 = function (uniformName, color3) {
  24050. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  24051. this._engine.setColor3(this.getUniform(uniformName), color3);
  24052. }
  24053. return this;
  24054. };
  24055. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  24056. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  24057. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  24058. }
  24059. return this;
  24060. };
  24061. // Statics
  24062. Effect.ShadersStore = {};
  24063. Effect.IncludesShadersStore = {};
  24064. return Effect;
  24065. })();
  24066. BABYLON.Effect = Effect;
  24067. })(BABYLON || (BABYLON = {}));
  24068. var BABYLON;
  24069. (function (BABYLON) {
  24070. var MaterialHelper = (function () {
  24071. function MaterialHelper() {
  24072. }
  24073. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, maxSimultaneousLights) {
  24074. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  24075. var lightIndex = 0;
  24076. var needNormals = false;
  24077. var needRebuild = false;
  24078. var needShadows = false;
  24079. for (var index = 0; index < scene.lights.length; index++) {
  24080. var light = scene.lights[index];
  24081. if (!light.isEnabled()) {
  24082. continue;
  24083. }
  24084. // Excluded check
  24085. if (light._excludedMeshesIds.length > 0) {
  24086. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  24087. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  24088. if (excludedMesh) {
  24089. light.excludedMeshes.push(excludedMesh);
  24090. }
  24091. }
  24092. light._excludedMeshesIds = [];
  24093. }
  24094. // Included check
  24095. if (light._includedOnlyMeshesIds.length > 0) {
  24096. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  24097. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  24098. if (includedOnlyMesh) {
  24099. light.includedOnlyMeshes.push(includedOnlyMesh);
  24100. }
  24101. }
  24102. light._includedOnlyMeshesIds = [];
  24103. }
  24104. if (!light.canAffectMesh(mesh)) {
  24105. continue;
  24106. }
  24107. needNormals = true;
  24108. if (defines["LIGHT" + lightIndex] === undefined) {
  24109. needRebuild = true;
  24110. }
  24111. defines["LIGHT" + lightIndex] = true;
  24112. var type;
  24113. if (light instanceof BABYLON.SpotLight) {
  24114. type = "SPOTLIGHT" + lightIndex;
  24115. }
  24116. else if (light instanceof BABYLON.HemisphericLight) {
  24117. type = "HEMILIGHT" + lightIndex;
  24118. }
  24119. else if (light instanceof BABYLON.PointLight) {
  24120. type = "POINTLIGHT" + lightIndex;
  24121. }
  24122. else {
  24123. type = "DIRLIGHT" + lightIndex;
  24124. }
  24125. if (defines[type] === undefined) {
  24126. needRebuild = true;
  24127. }
  24128. defines[type] = true;
  24129. // Specular
  24130. if (!light.specular.equalsFloats(0, 0, 0) && defines["SPECULARTERM"] !== undefined) {
  24131. defines["SPECULARTERM"] = true;
  24132. }
  24133. // Shadows
  24134. if (scene.shadowsEnabled) {
  24135. var shadowGenerator = light.getShadowGenerator();
  24136. if (mesh && mesh.receiveShadows && shadowGenerator) {
  24137. if (defines["SHADOW" + lightIndex] === undefined) {
  24138. needRebuild = true;
  24139. }
  24140. defines["SHADOW" + lightIndex] = true;
  24141. defines["SHADOWS"] = true;
  24142. if (shadowGenerator.useVarianceShadowMap || shadowGenerator.useBlurVarianceShadowMap) {
  24143. if (defines["SHADOWVSM" + lightIndex] === undefined) {
  24144. needRebuild = true;
  24145. }
  24146. defines["SHADOWVSM" + lightIndex] = true;
  24147. }
  24148. if (shadowGenerator.usePoissonSampling) {
  24149. if (defines["SHADOWPCF" + lightIndex] === undefined) {
  24150. needRebuild = true;
  24151. }
  24152. defines["SHADOWPCF" + lightIndex] = true;
  24153. }
  24154. needShadows = true;
  24155. }
  24156. }
  24157. lightIndex++;
  24158. if (lightIndex === maxSimultaneousLights)
  24159. break;
  24160. }
  24161. var caps = scene.getEngine().getCaps();
  24162. if (needShadows && caps.textureFloat && caps.textureFloatLinearFiltering && caps.textureFloatRender) {
  24163. if (defines["SHADOWFULLFLOAT"] === undefined) {
  24164. needRebuild = true;
  24165. }
  24166. defines["SHADOWFULLFLOAT"] = true;
  24167. }
  24168. if (needRebuild) {
  24169. defines.rebuild();
  24170. }
  24171. return needNormals;
  24172. };
  24173. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsList, samplersList, defines, maxSimultaneousLights) {
  24174. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  24175. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  24176. if (!defines["LIGHT" + lightIndex]) {
  24177. break;
  24178. }
  24179. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex);
  24180. samplersList.push("shadowSampler" + lightIndex);
  24181. }
  24182. };
  24183. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights) {
  24184. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  24185. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  24186. if (!defines["LIGHT" + lightIndex]) {
  24187. break;
  24188. }
  24189. if (lightIndex > 0) {
  24190. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  24191. }
  24192. if (defines["SHADOW" + lightIndex]) {
  24193. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  24194. }
  24195. if (defines["SHADOWPCF" + lightIndex]) {
  24196. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  24197. }
  24198. if (defines["SHADOWVSM" + lightIndex]) {
  24199. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  24200. }
  24201. }
  24202. };
  24203. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  24204. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  24205. fallbacks.addCPUSkinningFallback(0, mesh);
  24206. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  24207. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  24208. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  24209. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  24210. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  24211. }
  24212. }
  24213. };
  24214. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  24215. if (defines["INSTANCES"]) {
  24216. attribs.push("world0");
  24217. attribs.push("world1");
  24218. attribs.push("world2");
  24219. attribs.push("world3");
  24220. }
  24221. };
  24222. // Bindings
  24223. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect, depthValuesAlreadySet) {
  24224. var shadowGenerator = light.getShadowGenerator();
  24225. if (mesh.receiveShadows && shadowGenerator) {
  24226. if (!light.needCube()) {
  24227. effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  24228. }
  24229. else {
  24230. if (!depthValuesAlreadySet) {
  24231. depthValuesAlreadySet = true;
  24232. effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  24233. }
  24234. }
  24235. effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMapForRendering());
  24236. effect.setFloat3("shadowsInfo" + lightIndex, shadowGenerator.getDarkness(), shadowGenerator.blurScale / shadowGenerator.getShadowMap().getSize().width, shadowGenerator.bias);
  24237. }
  24238. return depthValuesAlreadySet;
  24239. };
  24240. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  24241. if (light instanceof BABYLON.PointLight) {
  24242. // Point Light
  24243. light.transferToEffect(effect, "vLightData" + lightIndex);
  24244. }
  24245. else if (light instanceof BABYLON.DirectionalLight) {
  24246. // Directional Light
  24247. light.transferToEffect(effect, "vLightData" + lightIndex);
  24248. }
  24249. else if (light instanceof BABYLON.SpotLight) {
  24250. // Spot Light
  24251. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  24252. }
  24253. else if (light instanceof BABYLON.HemisphericLight) {
  24254. // Hemispheric Light
  24255. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  24256. }
  24257. };
  24258. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights) {
  24259. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  24260. var lightIndex = 0;
  24261. var depthValuesAlreadySet = false;
  24262. for (var index = 0; index < scene.lights.length; index++) {
  24263. var light = scene.lights[index];
  24264. if (!light.isEnabled()) {
  24265. continue;
  24266. }
  24267. if (!light.canAffectMesh(mesh)) {
  24268. continue;
  24269. }
  24270. MaterialHelper.BindLightProperties(light, effect, lightIndex);
  24271. light.diffuse.scaleToRef(light.intensity, BABYLON.Tmp.Color3[0]);
  24272. effect.setColor4("vLightDiffuse" + lightIndex, BABYLON.Tmp.Color3[0], light.range);
  24273. if (defines["SPECULARTERM"]) {
  24274. light.specular.scaleToRef(light.intensity, BABYLON.Tmp.Color3[1]);
  24275. effect.setColor3("vLightSpecular" + lightIndex, BABYLON.Tmp.Color3[1]);
  24276. }
  24277. // Shadows
  24278. if (scene.shadowsEnabled) {
  24279. depthValuesAlreadySet = this.BindLightShadow(light, scene, mesh, lightIndex, effect, depthValuesAlreadySet);
  24280. }
  24281. lightIndex++;
  24282. if (lightIndex === maxSimultaneousLights)
  24283. break;
  24284. }
  24285. };
  24286. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  24287. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  24288. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  24289. effect.setColor3("vFogColor", scene.fogColor);
  24290. }
  24291. };
  24292. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  24293. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  24294. effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  24295. }
  24296. };
  24297. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  24298. if (defines["LOGARITHMICDEPTH"]) {
  24299. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  24300. }
  24301. };
  24302. MaterialHelper.BindClipPlane = function (effect, scene) {
  24303. if (scene.clipPlane) {
  24304. var clipPlane = scene.clipPlane;
  24305. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  24306. }
  24307. };
  24308. return MaterialHelper;
  24309. })();
  24310. BABYLON.MaterialHelper = MaterialHelper;
  24311. })(BABYLON || (BABYLON = {}));
  24312. var BABYLON;
  24313. (function (BABYLON) {
  24314. var FresnelParameters = (function () {
  24315. function FresnelParameters() {
  24316. this.isEnabled = true;
  24317. this.leftColor = BABYLON.Color3.White();
  24318. this.rightColor = BABYLON.Color3.Black();
  24319. this.bias = 0;
  24320. this.power = 1;
  24321. }
  24322. FresnelParameters.prototype.clone = function () {
  24323. var newFresnelParameters = new FresnelParameters();
  24324. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  24325. return new FresnelParameters;
  24326. };
  24327. FresnelParameters.prototype.serialize = function () {
  24328. var serializationObject = {};
  24329. serializationObject.isEnabled = this.isEnabled;
  24330. serializationObject.leftColor = this.leftColor;
  24331. serializationObject.rightColor = this.rightColor;
  24332. serializationObject.bias = this.bias;
  24333. serializationObject.power = this.power;
  24334. return serializationObject;
  24335. };
  24336. FresnelParameters.Parse = function (parsedFresnelParameters) {
  24337. var fresnelParameters = new FresnelParameters();
  24338. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  24339. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  24340. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  24341. fresnelParameters.bias = parsedFresnelParameters.bias;
  24342. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  24343. return fresnelParameters;
  24344. };
  24345. return FresnelParameters;
  24346. })();
  24347. BABYLON.FresnelParameters = FresnelParameters;
  24348. })(BABYLON || (BABYLON = {}));
  24349. var BABYLON;
  24350. (function (BABYLON) {
  24351. var MaterialDefines = (function () {
  24352. function MaterialDefines() {
  24353. }
  24354. MaterialDefines.prototype.rebuild = function () {
  24355. if (this._keys) {
  24356. delete this._keys;
  24357. }
  24358. this._keys = Object.keys(this);
  24359. };
  24360. MaterialDefines.prototype.isEqual = function (other) {
  24361. if (this._keys.length !== other._keys.length) {
  24362. return false;
  24363. }
  24364. for (var index = 0; index < this._keys.length; index++) {
  24365. var prop = this._keys[index];
  24366. if (this[prop] !== other[prop]) {
  24367. return false;
  24368. }
  24369. }
  24370. return true;
  24371. };
  24372. MaterialDefines.prototype.cloneTo = function (other) {
  24373. if (this._keys.length !== other._keys.length) {
  24374. other._keys = this._keys.slice(0);
  24375. }
  24376. for (var index = 0; index < this._keys.length; index++) {
  24377. var prop = this._keys[index];
  24378. other[prop] = this[prop];
  24379. }
  24380. };
  24381. MaterialDefines.prototype.reset = function () {
  24382. for (var index = 0; index < this._keys.length; index++) {
  24383. var prop = this._keys[index];
  24384. if (typeof (this[prop]) === "number") {
  24385. this[prop] = 0;
  24386. }
  24387. else {
  24388. this[prop] = false;
  24389. }
  24390. }
  24391. };
  24392. MaterialDefines.prototype.toString = function () {
  24393. var result = "";
  24394. for (var index = 0; index < this._keys.length; index++) {
  24395. var prop = this._keys[index];
  24396. if (typeof (this[prop]) === "number") {
  24397. result += "#define " + prop + " " + this[prop] + "\n";
  24398. }
  24399. else if (this[prop]) {
  24400. result += "#define " + prop + "\n";
  24401. }
  24402. }
  24403. return result;
  24404. };
  24405. return MaterialDefines;
  24406. })();
  24407. BABYLON.MaterialDefines = MaterialDefines;
  24408. var Material = (function () {
  24409. function Material(name, scene, doNotAdd) {
  24410. this.name = name;
  24411. this.checkReadyOnEveryCall = false;
  24412. this.checkReadyOnlyOnce = false;
  24413. this.state = "";
  24414. this.alpha = 1.0;
  24415. this.backFaceCulling = true;
  24416. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  24417. /**
  24418. * An event triggered when the material is disposed.
  24419. * @type {BABYLON.Observable}
  24420. */
  24421. this.onDisposeObservable = new BABYLON.Observable();
  24422. /**
  24423. * An event triggered when the material is bound.
  24424. * @type {BABYLON.Observable}
  24425. */
  24426. this.onBindObservable = new BABYLON.Observable();
  24427. /**
  24428. * An event triggered when the material is unbound.
  24429. * @type {BABYLON.Observable}
  24430. */
  24431. this.onUnBindObservable = new BABYLON.Observable();
  24432. this.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  24433. this.disableDepthWrite = false;
  24434. this.fogEnabled = true;
  24435. this.pointSize = 1.0;
  24436. this.zOffset = 0;
  24437. this._wasPreviouslyReady = false;
  24438. this._fillMode = Material.TriangleFillMode;
  24439. this.id = name;
  24440. this._scene = scene;
  24441. if (!doNotAdd) {
  24442. scene.materials.push(this);
  24443. }
  24444. }
  24445. Object.defineProperty(Material, "TriangleFillMode", {
  24446. get: function () {
  24447. return Material._TriangleFillMode;
  24448. },
  24449. enumerable: true,
  24450. configurable: true
  24451. });
  24452. Object.defineProperty(Material, "WireFrameFillMode", {
  24453. get: function () {
  24454. return Material._WireFrameFillMode;
  24455. },
  24456. enumerable: true,
  24457. configurable: true
  24458. });
  24459. Object.defineProperty(Material, "PointFillMode", {
  24460. get: function () {
  24461. return Material._PointFillMode;
  24462. },
  24463. enumerable: true,
  24464. configurable: true
  24465. });
  24466. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  24467. get: function () {
  24468. return Material._ClockWiseSideOrientation;
  24469. },
  24470. enumerable: true,
  24471. configurable: true
  24472. });
  24473. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  24474. get: function () {
  24475. return Material._CounterClockWiseSideOrientation;
  24476. },
  24477. enumerable: true,
  24478. configurable: true
  24479. });
  24480. Object.defineProperty(Material.prototype, "onDispose", {
  24481. set: function (callback) {
  24482. if (this._onDisposeObserver) {
  24483. this.onDisposeObservable.remove(this._onDisposeObserver);
  24484. }
  24485. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  24486. },
  24487. enumerable: true,
  24488. configurable: true
  24489. });
  24490. Object.defineProperty(Material.prototype, "onBind", {
  24491. set: function (callback) {
  24492. if (this._onBindObserver) {
  24493. this.onBindObservable.remove(this._onBindObserver);
  24494. }
  24495. this._onBindObserver = this.onBindObservable.add(callback);
  24496. },
  24497. enumerable: true,
  24498. configurable: true
  24499. });
  24500. Object.defineProperty(Material.prototype, "wireframe", {
  24501. get: function () {
  24502. return this._fillMode === Material.WireFrameFillMode;
  24503. },
  24504. set: function (value) {
  24505. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  24506. },
  24507. enumerable: true,
  24508. configurable: true
  24509. });
  24510. Object.defineProperty(Material.prototype, "pointsCloud", {
  24511. get: function () {
  24512. return this._fillMode === Material.PointFillMode;
  24513. },
  24514. set: function (value) {
  24515. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  24516. },
  24517. enumerable: true,
  24518. configurable: true
  24519. });
  24520. Object.defineProperty(Material.prototype, "fillMode", {
  24521. get: function () {
  24522. return this._fillMode;
  24523. },
  24524. set: function (value) {
  24525. this._fillMode = value;
  24526. },
  24527. enumerable: true,
  24528. configurable: true
  24529. });
  24530. /**
  24531. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  24532. * subclasses should override adding information pertainent to themselves
  24533. */
  24534. Material.prototype.toString = function (fullDetails) {
  24535. var ret = "Name: " + this.name;
  24536. if (fullDetails) {
  24537. }
  24538. return ret;
  24539. };
  24540. Object.defineProperty(Material.prototype, "isFrozen", {
  24541. get: function () {
  24542. return this.checkReadyOnlyOnce;
  24543. },
  24544. enumerable: true,
  24545. configurable: true
  24546. });
  24547. Material.prototype.freeze = function () {
  24548. this.checkReadyOnlyOnce = true;
  24549. };
  24550. Material.prototype.unfreeze = function () {
  24551. this.checkReadyOnlyOnce = false;
  24552. };
  24553. Material.prototype.isReady = function (mesh, useInstances) {
  24554. return true;
  24555. };
  24556. Material.prototype.getEffect = function () {
  24557. return this._effect;
  24558. };
  24559. Material.prototype.getScene = function () {
  24560. return this._scene;
  24561. };
  24562. Material.prototype.needAlphaBlending = function () {
  24563. return (this.alpha < 1.0);
  24564. };
  24565. Material.prototype.needAlphaTesting = function () {
  24566. return false;
  24567. };
  24568. Material.prototype.getAlphaTestTexture = function () {
  24569. return null;
  24570. };
  24571. Material.prototype.markDirty = function () {
  24572. this._wasPreviouslyReady = false;
  24573. };
  24574. Material.prototype._preBind = function () {
  24575. var engine = this._scene.getEngine();
  24576. engine.enableEffect(this._effect);
  24577. engine.setState(this.backFaceCulling, this.zOffset, false, this.sideOrientation === Material.ClockWiseSideOrientation);
  24578. };
  24579. Material.prototype.bind = function (world, mesh) {
  24580. this._scene._cachedMaterial = this;
  24581. this.onBindObservable.notifyObservers(mesh);
  24582. if (this.disableDepthWrite) {
  24583. var engine = this._scene.getEngine();
  24584. this._cachedDepthWriteState = engine.getDepthWrite();
  24585. engine.setDepthWrite(false);
  24586. }
  24587. };
  24588. Material.prototype.bindOnlyWorldMatrix = function (world) {
  24589. };
  24590. Material.prototype.unbind = function () {
  24591. this.onUnBindObservable.notifyObservers(this);
  24592. if (this.disableDepthWrite) {
  24593. var engine = this._scene.getEngine();
  24594. engine.setDepthWrite(this._cachedDepthWriteState);
  24595. }
  24596. };
  24597. Material.prototype.clone = function (name) {
  24598. return null;
  24599. };
  24600. Material.prototype.getBindedMeshes = function () {
  24601. var result = new Array();
  24602. for (var index = 0; index < this._scene.meshes.length; index++) {
  24603. var mesh = this._scene.meshes[index];
  24604. if (mesh.material === this) {
  24605. result.push(mesh);
  24606. }
  24607. }
  24608. return result;
  24609. };
  24610. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  24611. // Animations
  24612. this.getScene().stopAnimation(this);
  24613. // Remove from scene
  24614. var index = this._scene.materials.indexOf(this);
  24615. if (index >= 0) {
  24616. this._scene.materials.splice(index, 1);
  24617. }
  24618. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  24619. if (forceDisposeEffect && this._effect) {
  24620. this._scene.getEngine()._releaseEffect(this._effect);
  24621. this._effect = null;
  24622. }
  24623. // Remove from meshes
  24624. for (index = 0; index < this._scene.meshes.length; index++) {
  24625. var mesh = this._scene.meshes[index];
  24626. if (mesh.material === this) {
  24627. mesh.material = null;
  24628. }
  24629. }
  24630. // Callback
  24631. this.onDisposeObservable.notifyObservers(this);
  24632. this.onDisposeObservable.clear();
  24633. this.onBindObservable.clear();
  24634. };
  24635. Material.prototype.serialize = function () {
  24636. return BABYLON.SerializationHelper.Serialize(this);
  24637. };
  24638. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  24639. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  24640. multiMaterial.id = parsedMultiMaterial.id;
  24641. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  24642. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  24643. var subMatId = parsedMultiMaterial.materials[matIndex];
  24644. if (subMatId) {
  24645. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  24646. }
  24647. else {
  24648. multiMaterial.subMaterials.push(null);
  24649. }
  24650. }
  24651. return multiMaterial;
  24652. };
  24653. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  24654. if (!parsedMaterial.customType) {
  24655. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  24656. }
  24657. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  24658. return materialType.Parse(parsedMaterial, scene, rootUrl);
  24659. ;
  24660. };
  24661. Material._TriangleFillMode = 0;
  24662. Material._WireFrameFillMode = 1;
  24663. Material._PointFillMode = 2;
  24664. Material._ClockWiseSideOrientation = 0;
  24665. Material._CounterClockWiseSideOrientation = 1;
  24666. __decorate([
  24667. BABYLON.serialize()
  24668. ], Material.prototype, "id", void 0);
  24669. __decorate([
  24670. BABYLON.serialize()
  24671. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  24672. __decorate([
  24673. BABYLON.serialize()
  24674. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  24675. __decorate([
  24676. BABYLON.serialize()
  24677. ], Material.prototype, "state", void 0);
  24678. __decorate([
  24679. BABYLON.serialize()
  24680. ], Material.prototype, "alpha", void 0);
  24681. __decorate([
  24682. BABYLON.serialize()
  24683. ], Material.prototype, "backFaceCulling", void 0);
  24684. __decorate([
  24685. BABYLON.serialize()
  24686. ], Material.prototype, "sideOrientation", void 0);
  24687. __decorate([
  24688. BABYLON.serialize()
  24689. ], Material.prototype, "alphaMode", void 0);
  24690. __decorate([
  24691. BABYLON.serialize()
  24692. ], Material.prototype, "disableDepthWrite", void 0);
  24693. __decorate([
  24694. BABYLON.serialize()
  24695. ], Material.prototype, "fogEnabled", void 0);
  24696. __decorate([
  24697. BABYLON.serialize()
  24698. ], Material.prototype, "pointSize", void 0);
  24699. __decorate([
  24700. BABYLON.serialize()
  24701. ], Material.prototype, "zOffset", void 0);
  24702. __decorate([
  24703. BABYLON.serialize()
  24704. ], Material.prototype, "wireframe", null);
  24705. __decorate([
  24706. BABYLON.serialize()
  24707. ], Material.prototype, "pointsCloud", null);
  24708. __decorate([
  24709. BABYLON.serialize()
  24710. ], Material.prototype, "fillMode", null);
  24711. return Material;
  24712. })();
  24713. BABYLON.Material = Material;
  24714. })(BABYLON || (BABYLON = {}));
  24715. var BABYLON;
  24716. (function (BABYLON) {
  24717. var StandardMaterialDefines = (function (_super) {
  24718. __extends(StandardMaterialDefines, _super);
  24719. function StandardMaterialDefines() {
  24720. _super.call(this);
  24721. this.DIFFUSE = false;
  24722. this.AMBIENT = false;
  24723. this.OPACITY = false;
  24724. this.OPACITYRGB = false;
  24725. this.REFLECTION = false;
  24726. this.EMISSIVE = false;
  24727. this.SPECULAR = false;
  24728. this.BUMP = false;
  24729. this.PARALLAX = false;
  24730. this.PARALLAXOCCLUSION = false;
  24731. this.SPECULAROVERALPHA = false;
  24732. this.CLIPPLANE = false;
  24733. this.ALPHATEST = false;
  24734. this.ALPHAFROMDIFFUSE = false;
  24735. this.POINTSIZE = false;
  24736. this.FOG = false;
  24737. this.SPECULARTERM = false;
  24738. this.DIFFUSEFRESNEL = false;
  24739. this.OPACITYFRESNEL = false;
  24740. this.REFLECTIONFRESNEL = false;
  24741. this.REFRACTIONFRESNEL = false;
  24742. this.EMISSIVEFRESNEL = false;
  24743. this.FRESNEL = false;
  24744. this.NORMAL = false;
  24745. this.UV1 = false;
  24746. this.UV2 = false;
  24747. this.VERTEXCOLOR = false;
  24748. this.VERTEXALPHA = false;
  24749. this.NUM_BONE_INFLUENCERS = 0;
  24750. this.BonesPerMesh = 0;
  24751. this.INSTANCES = false;
  24752. this.GLOSSINESS = false;
  24753. this.ROUGHNESS = false;
  24754. this.EMISSIVEASILLUMINATION = false;
  24755. this.LINKEMISSIVEWITHDIFFUSE = false;
  24756. this.REFLECTIONFRESNELFROMSPECULAR = false;
  24757. this.LIGHTMAP = false;
  24758. this.USELIGHTMAPASSHADOWMAP = false;
  24759. this.REFLECTIONMAP_3D = false;
  24760. this.REFLECTIONMAP_SPHERICAL = false;
  24761. this.REFLECTIONMAP_PLANAR = false;
  24762. this.REFLECTIONMAP_CUBIC = false;
  24763. this.REFLECTIONMAP_PROJECTION = false;
  24764. this.REFLECTIONMAP_SKYBOX = false;
  24765. this.REFLECTIONMAP_EXPLICIT = false;
  24766. this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  24767. this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  24768. this.INVERTCUBICMAP = false;
  24769. this.LOGARITHMICDEPTH = false;
  24770. this.REFRACTION = false;
  24771. this.REFRACTIONMAP_3D = false;
  24772. this.REFLECTIONOVERALPHA = false;
  24773. this.INVERTNORMALMAPX = false;
  24774. this.INVERTNORMALMAPY = false;
  24775. this.SHADOWFULLFLOAT = false;
  24776. this.CAMERACOLORGRADING = false;
  24777. this.CAMERACOLORCURVES = false;
  24778. this.rebuild();
  24779. }
  24780. return StandardMaterialDefines;
  24781. })(BABYLON.MaterialDefines);
  24782. var StandardMaterial = (function (_super) {
  24783. __extends(StandardMaterial, _super);
  24784. function StandardMaterial(name, scene) {
  24785. var _this = this;
  24786. _super.call(this, name, scene);
  24787. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  24788. this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  24789. this.specularColor = new BABYLON.Color3(1, 1, 1);
  24790. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  24791. this.specularPower = 64;
  24792. this.useAlphaFromDiffuseTexture = false;
  24793. this.useEmissiveAsIllumination = false;
  24794. this.linkEmissiveWithDiffuse = false;
  24795. this.useReflectionFresnelFromSpecular = false;
  24796. this.useSpecularOverAlpha = false;
  24797. this.useReflectionOverAlpha = false;
  24798. this.disableLighting = false;
  24799. this.useParallax = false;
  24800. this.useParallaxOcclusion = false;
  24801. this.parallaxScaleBias = 0.05;
  24802. this.roughness = 0;
  24803. this.indexOfRefraction = 0.98;
  24804. this.invertRefractionY = true;
  24805. this.useLightmapAsShadowmap = false;
  24806. this.useGlossinessFromSpecularMapAlpha = false;
  24807. this.maxSimultaneousLights = 4;
  24808. /**
  24809. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  24810. */
  24811. this.invertNormalMapX = false;
  24812. /**
  24813. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  24814. */
  24815. this.invertNormalMapY = false;
  24816. /**
  24817. * Color Grading 2D Lookup Texture.
  24818. * This allows special effects like sepia, black and white to sixties rendering style.
  24819. */
  24820. this.cameraColorGradingTexture = null;
  24821. /**
  24822. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  24823. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  24824. * 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;
  24825. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  24826. */
  24827. this.cameraColorCurves = null;
  24828. this._renderTargets = new BABYLON.SmartArray(16);
  24829. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  24830. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  24831. this._defines = new StandardMaterialDefines();
  24832. this._cachedDefines = new StandardMaterialDefines();
  24833. this._cachedDefines.BonesPerMesh = -1;
  24834. this.getRenderTargetTextures = function () {
  24835. _this._renderTargets.reset();
  24836. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  24837. _this._renderTargets.push(_this.reflectionTexture);
  24838. }
  24839. if (_this.refractionTexture && _this.refractionTexture.isRenderTarget) {
  24840. _this._renderTargets.push(_this.refractionTexture);
  24841. }
  24842. return _this._renderTargets;
  24843. };
  24844. }
  24845. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  24846. get: function () {
  24847. return this._useLogarithmicDepth;
  24848. },
  24849. set: function (value) {
  24850. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  24851. },
  24852. enumerable: true,
  24853. configurable: true
  24854. });
  24855. StandardMaterial.prototype.needAlphaBlending = function () {
  24856. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  24857. };
  24858. StandardMaterial.prototype.needAlphaTesting = function () {
  24859. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha;
  24860. };
  24861. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  24862. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  24863. };
  24864. StandardMaterial.prototype.getAlphaTestTexture = function () {
  24865. return this.diffuseTexture;
  24866. };
  24867. // Methods
  24868. StandardMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  24869. if (!mesh) {
  24870. return true;
  24871. }
  24872. if (this._defines.INSTANCES !== useInstances) {
  24873. return false;
  24874. }
  24875. if (mesh._materialDefines && mesh._materialDefines.isEqual(this._defines)) {
  24876. return true;
  24877. }
  24878. return false;
  24879. };
  24880. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  24881. if (this.isFrozen) {
  24882. if (this._wasPreviouslyReady) {
  24883. return true;
  24884. }
  24885. }
  24886. var scene = this.getScene();
  24887. if (!this.checkReadyOnEveryCall) {
  24888. if (this._renderId === scene.getRenderId()) {
  24889. if (this._checkCache(scene, mesh, useInstances)) {
  24890. return true;
  24891. }
  24892. }
  24893. }
  24894. var engine = scene.getEngine();
  24895. var needNormals = false;
  24896. var needUVs = false;
  24897. this._defines.reset();
  24898. // Textures
  24899. if (scene.texturesEnabled) {
  24900. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  24901. if (!this.diffuseTexture.isReady()) {
  24902. return false;
  24903. }
  24904. else {
  24905. needUVs = true;
  24906. this._defines.DIFFUSE = true;
  24907. }
  24908. }
  24909. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  24910. if (!this.ambientTexture.isReady()) {
  24911. return false;
  24912. }
  24913. else {
  24914. needUVs = true;
  24915. this._defines.AMBIENT = true;
  24916. }
  24917. }
  24918. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  24919. if (!this.opacityTexture.isReady()) {
  24920. return false;
  24921. }
  24922. else {
  24923. needUVs = true;
  24924. this._defines.OPACITY = true;
  24925. if (this.opacityTexture.getAlphaFromRGB) {
  24926. this._defines.OPACITYRGB = true;
  24927. }
  24928. }
  24929. }
  24930. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  24931. if (!this.reflectionTexture.isReady()) {
  24932. return false;
  24933. }
  24934. else {
  24935. needNormals = true;
  24936. this._defines.REFLECTION = true;
  24937. if (this.roughness > 0) {
  24938. this._defines.ROUGHNESS = true;
  24939. }
  24940. if (this.useReflectionOverAlpha) {
  24941. this._defines.REFLECTIONOVERALPHA = true;
  24942. }
  24943. if (this.reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  24944. this._defines.INVERTCUBICMAP = true;
  24945. }
  24946. this._defines.REFLECTIONMAP_3D = this.reflectionTexture.isCube;
  24947. switch (this.reflectionTexture.coordinatesMode) {
  24948. case BABYLON.Texture.CUBIC_MODE:
  24949. case BABYLON.Texture.INVCUBIC_MODE:
  24950. this._defines.REFLECTIONMAP_CUBIC = true;
  24951. break;
  24952. case BABYLON.Texture.EXPLICIT_MODE:
  24953. this._defines.REFLECTIONMAP_EXPLICIT = true;
  24954. break;
  24955. case BABYLON.Texture.PLANAR_MODE:
  24956. this._defines.REFLECTIONMAP_PLANAR = true;
  24957. break;
  24958. case BABYLON.Texture.PROJECTION_MODE:
  24959. this._defines.REFLECTIONMAP_PROJECTION = true;
  24960. break;
  24961. case BABYLON.Texture.SKYBOX_MODE:
  24962. this._defines.REFLECTIONMAP_SKYBOX = true;
  24963. break;
  24964. case BABYLON.Texture.SPHERICAL_MODE:
  24965. this._defines.REFLECTIONMAP_SPHERICAL = true;
  24966. break;
  24967. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  24968. this._defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  24969. break;
  24970. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  24971. this._defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  24972. break;
  24973. }
  24974. }
  24975. }
  24976. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  24977. if (!this.emissiveTexture.isReady()) {
  24978. return false;
  24979. }
  24980. else {
  24981. needUVs = true;
  24982. this._defines.EMISSIVE = true;
  24983. }
  24984. }
  24985. if (this.lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  24986. if (!this.lightmapTexture.isReady()) {
  24987. return false;
  24988. }
  24989. else {
  24990. needUVs = true;
  24991. this._defines.LIGHTMAP = true;
  24992. this._defines.USELIGHTMAPASSHADOWMAP = this.useLightmapAsShadowmap;
  24993. }
  24994. }
  24995. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  24996. if (!this.specularTexture.isReady()) {
  24997. return false;
  24998. }
  24999. else {
  25000. needUVs = true;
  25001. this._defines.SPECULAR = true;
  25002. this._defines.GLOSSINESS = this.useGlossinessFromSpecularMapAlpha;
  25003. }
  25004. }
  25005. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && StandardMaterial.BumpTextureEnabled) {
  25006. if (!this.bumpTexture.isReady()) {
  25007. return false;
  25008. }
  25009. else {
  25010. needUVs = true;
  25011. this._defines.BUMP = true;
  25012. if (this.useParallax) {
  25013. this._defines.PARALLAX = true;
  25014. if (this.useParallaxOcclusion) {
  25015. this._defines.PARALLAXOCCLUSION = true;
  25016. }
  25017. }
  25018. if (this.invertNormalMapX) {
  25019. this._defines.INVERTNORMALMAPX = true;
  25020. }
  25021. if (this.invertNormalMapY) {
  25022. this._defines.INVERTNORMALMAPY = true;
  25023. }
  25024. }
  25025. }
  25026. if (this.refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  25027. if (!this.refractionTexture.isReady()) {
  25028. return false;
  25029. }
  25030. else {
  25031. needUVs = true;
  25032. this._defines.REFRACTION = true;
  25033. this._defines.REFRACTIONMAP_3D = this.refractionTexture.isCube;
  25034. }
  25035. }
  25036. if (this.cameraColorGradingTexture && StandardMaterial.ColorGradingTextureEnabled) {
  25037. if (!this.cameraColorGradingTexture.isReady()) {
  25038. return false;
  25039. }
  25040. else {
  25041. this._defines.CAMERACOLORGRADING = true;
  25042. }
  25043. }
  25044. }
  25045. // Effect
  25046. if (scene.clipPlane) {
  25047. this._defines.CLIPPLANE = true;
  25048. }
  25049. if (engine.getAlphaTesting()) {
  25050. this._defines.ALPHATEST = true;
  25051. }
  25052. if (this._shouldUseAlphaFromDiffuseTexture()) {
  25053. this._defines.ALPHAFROMDIFFUSE = true;
  25054. }
  25055. if (this.useEmissiveAsIllumination) {
  25056. this._defines.EMISSIVEASILLUMINATION = true;
  25057. }
  25058. if (this.linkEmissiveWithDiffuse) {
  25059. this._defines.LINKEMISSIVEWITHDIFFUSE = true;
  25060. }
  25061. if (this.useLogarithmicDepth) {
  25062. this._defines.LOGARITHMICDEPTH = true;
  25063. }
  25064. if (this.cameraColorCurves) {
  25065. this._defines.CAMERACOLORCURVES = true;
  25066. }
  25067. // Point size
  25068. if (this.pointsCloud || scene.forcePointsCloud) {
  25069. this._defines.POINTSIZE = true;
  25070. }
  25071. // Fog
  25072. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  25073. this._defines.FOG = true;
  25074. }
  25075. if (scene.lightsEnabled && !this.disableLighting) {
  25076. needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, this._defines, this.maxSimultaneousLights);
  25077. }
  25078. if (StandardMaterial.FresnelEnabled) {
  25079. // Fresnel
  25080. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled ||
  25081. this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  25082. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled ||
  25083. this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled ||
  25084. this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  25085. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  25086. this._defines.DIFFUSEFRESNEL = true;
  25087. }
  25088. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  25089. this._defines.OPACITYFRESNEL = true;
  25090. }
  25091. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  25092. this._defines.REFLECTIONFRESNEL = true;
  25093. if (this.useReflectionFresnelFromSpecular) {
  25094. this._defines.REFLECTIONFRESNELFROMSPECULAR = true;
  25095. }
  25096. }
  25097. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  25098. this._defines.REFRACTIONFRESNEL = true;
  25099. }
  25100. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  25101. this._defines.EMISSIVEFRESNEL = true;
  25102. }
  25103. needNormals = true;
  25104. this._defines.FRESNEL = true;
  25105. }
  25106. }
  25107. if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
  25108. this._defines.SPECULAROVERALPHA = true;
  25109. }
  25110. // Attribs
  25111. if (mesh) {
  25112. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  25113. this._defines.NORMAL = true;
  25114. }
  25115. if (needUVs) {
  25116. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  25117. this._defines.UV1 = true;
  25118. }
  25119. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  25120. this._defines.UV2 = true;
  25121. }
  25122. }
  25123. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  25124. this._defines.VERTEXCOLOR = true;
  25125. if (mesh.hasVertexAlpha) {
  25126. this._defines.VERTEXALPHA = true;
  25127. }
  25128. }
  25129. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  25130. this._defines.NUM_BONE_INFLUENCERS = mesh.numBoneInfluencers;
  25131. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  25132. }
  25133. // Instances
  25134. if (useInstances) {
  25135. this._defines.INSTANCES = true;
  25136. }
  25137. }
  25138. // Get correct effect
  25139. if (!this._defines.isEqual(this._cachedDefines)) {
  25140. this._defines.cloneTo(this._cachedDefines);
  25141. scene.resetCachedMaterial();
  25142. // Fallbacks
  25143. var fallbacks = new BABYLON.EffectFallbacks();
  25144. if (this._defines.REFLECTION) {
  25145. fallbacks.addFallback(0, "REFLECTION");
  25146. }
  25147. if (this._defines.SPECULAR) {
  25148. fallbacks.addFallback(0, "SPECULAR");
  25149. }
  25150. if (this._defines.BUMP) {
  25151. fallbacks.addFallback(0, "BUMP");
  25152. }
  25153. if (this._defines.PARALLAX) {
  25154. fallbacks.addFallback(1, "PARALLAX");
  25155. }
  25156. if (this._defines.PARALLAXOCCLUSION) {
  25157. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  25158. }
  25159. if (this._defines.SPECULAROVERALPHA) {
  25160. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  25161. }
  25162. if (this._defines.FOG) {
  25163. fallbacks.addFallback(1, "FOG");
  25164. }
  25165. if (this._defines.POINTSIZE) {
  25166. fallbacks.addFallback(0, "POINTSIZE");
  25167. }
  25168. if (this._defines.LOGARITHMICDEPTH) {
  25169. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  25170. }
  25171. BABYLON.MaterialHelper.HandleFallbacksForShadows(this._defines, fallbacks, this.maxSimultaneousLights);
  25172. if (this._defines.SPECULARTERM) {
  25173. fallbacks.addFallback(0, "SPECULARTERM");
  25174. }
  25175. if (this._defines.DIFFUSEFRESNEL) {
  25176. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  25177. }
  25178. if (this._defines.OPACITYFRESNEL) {
  25179. fallbacks.addFallback(2, "OPACITYFRESNEL");
  25180. }
  25181. if (this._defines.REFLECTIONFRESNEL) {
  25182. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  25183. }
  25184. if (this._defines.EMISSIVEFRESNEL) {
  25185. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  25186. }
  25187. if (this._defines.FRESNEL) {
  25188. fallbacks.addFallback(4, "FRESNEL");
  25189. }
  25190. //Attributes
  25191. var attribs = [BABYLON.VertexBuffer.PositionKind];
  25192. if (this._defines.NORMAL) {
  25193. attribs.push(BABYLON.VertexBuffer.NormalKind);
  25194. }
  25195. if (this._defines.UV1) {
  25196. attribs.push(BABYLON.VertexBuffer.UVKind);
  25197. }
  25198. if (this._defines.UV2) {
  25199. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  25200. }
  25201. if (this._defines.VERTEXCOLOR) {
  25202. attribs.push(BABYLON.VertexBuffer.ColorKind);
  25203. }
  25204. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, this._defines, fallbacks);
  25205. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, this._defines);
  25206. var shaderName = "default";
  25207. var join = this._defines.toString();
  25208. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  25209. "vFogInfos", "vFogColor", "pointSize",
  25210. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  25211. "mBones",
  25212. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  25213. "depthValues",
  25214. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  25215. "logarithmicDepthConstant"
  25216. ];
  25217. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  25218. if (this._defines.CAMERACOLORCURVES) {
  25219. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  25220. }
  25221. if (this._defines.CAMERACOLORGRADING) {
  25222. BABYLON.ColorGradingTexture.PrepareUniformsAndSamplers(uniforms, samplers);
  25223. }
  25224. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList(uniforms, samplers, this._defines, this.maxSimultaneousLights);
  25225. this._effect = scene.getEngine().createEffect(shaderName, attribs, uniforms, samplers, join, fallbacks, this.onCompiled, this.onError, { maxSimultaneousLights: this.maxSimultaneousLights - 1 });
  25226. }
  25227. if (!this._effect.isReady()) {
  25228. return false;
  25229. }
  25230. this._renderId = scene.getRenderId();
  25231. this._wasPreviouslyReady = true;
  25232. if (mesh) {
  25233. if (!mesh._materialDefines) {
  25234. mesh._materialDefines = new StandardMaterialDefines();
  25235. }
  25236. this._defines.cloneTo(mesh._materialDefines);
  25237. }
  25238. return true;
  25239. };
  25240. StandardMaterial.prototype.unbind = function () {
  25241. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  25242. this._effect.setTexture("reflection2DSampler", null);
  25243. }
  25244. if (this.refractionTexture && this.refractionTexture.isRenderTarget) {
  25245. this._effect.setTexture("refraction2DSampler", null);
  25246. }
  25247. _super.prototype.unbind.call(this);
  25248. };
  25249. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  25250. this._effect.setMatrix("world", world);
  25251. };
  25252. StandardMaterial.prototype.bind = function (world, mesh) {
  25253. var scene = this.getScene();
  25254. // Matrices
  25255. this.bindOnlyWorldMatrix(world);
  25256. // Bones
  25257. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  25258. if (scene.getCachedMaterial() !== this) {
  25259. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  25260. if (StandardMaterial.FresnelEnabled) {
  25261. // Fresnel
  25262. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  25263. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  25264. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  25265. }
  25266. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  25267. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  25268. }
  25269. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  25270. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  25271. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  25272. }
  25273. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  25274. this._effect.setColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  25275. this._effect.setColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  25276. }
  25277. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  25278. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  25279. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  25280. }
  25281. }
  25282. // Textures
  25283. if (scene.texturesEnabled) {
  25284. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  25285. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  25286. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  25287. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  25288. }
  25289. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  25290. this._effect.setTexture("ambientSampler", this.ambientTexture);
  25291. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  25292. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  25293. }
  25294. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  25295. this._effect.setTexture("opacitySampler", this.opacityTexture);
  25296. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  25297. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  25298. }
  25299. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  25300. if (this.reflectionTexture.isCube) {
  25301. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  25302. }
  25303. else {
  25304. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  25305. }
  25306. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  25307. this._effect.setFloat2("vReflectionInfos", this.reflectionTexture.level, this.roughness);
  25308. }
  25309. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  25310. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  25311. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  25312. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  25313. }
  25314. if (this.lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  25315. this._effect.setTexture("lightmapSampler", this.lightmapTexture);
  25316. this._effect.setFloat2("vLightmapInfos", this.lightmapTexture.coordinatesIndex, this.lightmapTexture.level);
  25317. this._effect.setMatrix("lightmapMatrix", this.lightmapTexture.getTextureMatrix());
  25318. }
  25319. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  25320. this._effect.setTexture("specularSampler", this.specularTexture);
  25321. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  25322. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  25323. }
  25324. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  25325. this._effect.setTexture("bumpSampler", this.bumpTexture);
  25326. this._effect.setFloat3("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level, this.parallaxScaleBias);
  25327. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  25328. }
  25329. if (this.refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  25330. var depth = 1.0;
  25331. if (this.refractionTexture.isCube) {
  25332. this._effect.setTexture("refractionCubeSampler", this.refractionTexture);
  25333. }
  25334. else {
  25335. this._effect.setTexture("refraction2DSampler", this.refractionTexture);
  25336. this._effect.setMatrix("refractionMatrix", this.refractionTexture.getReflectionTextureMatrix());
  25337. if (this.refractionTexture.depth) {
  25338. depth = this.refractionTexture.depth;
  25339. }
  25340. }
  25341. this._effect.setFloat4("vRefractionInfos", this.refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  25342. }
  25343. if (this.cameraColorGradingTexture && StandardMaterial.ColorGradingTextureEnabled) {
  25344. BABYLON.ColorGradingTexture.Bind(this.cameraColorGradingTexture, this._effect);
  25345. }
  25346. }
  25347. // Clip plane
  25348. BABYLON.MaterialHelper.BindClipPlane(this._effect, scene);
  25349. // Point size
  25350. if (this.pointsCloud) {
  25351. this._effect.setFloat("pointSize", this.pointSize);
  25352. }
  25353. // Colors
  25354. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  25355. this._effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.position);
  25356. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  25357. if (this._defines.SPECULARTERM) {
  25358. this._effect.setColor4("vSpecularColor", this.specularColor, this.specularPower);
  25359. }
  25360. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  25361. }
  25362. if (scene.getCachedMaterial() !== this || !this.isFrozen) {
  25363. // Diffuse
  25364. this._effect.setColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  25365. // Lights
  25366. if (scene.lightsEnabled && !this.disableLighting) {
  25367. BABYLON.MaterialHelper.BindLights(scene, mesh, this._effect, this._defines, this.maxSimultaneousLights);
  25368. }
  25369. // View
  25370. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture || this.refractionTexture) {
  25371. this._effect.setMatrix("view", scene.getViewMatrix());
  25372. }
  25373. // Fog
  25374. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._effect);
  25375. // Log. depth
  25376. BABYLON.MaterialHelper.BindLogDepth(this._defines, this._effect, scene);
  25377. // Color Curves
  25378. if (this.cameraColorCurves) {
  25379. BABYLON.ColorCurves.Bind(this.cameraColorCurves, this._effect);
  25380. }
  25381. }
  25382. _super.prototype.bind.call(this, world, mesh);
  25383. };
  25384. StandardMaterial.prototype.getAnimatables = function () {
  25385. var results = [];
  25386. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  25387. results.push(this.diffuseTexture);
  25388. }
  25389. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  25390. results.push(this.ambientTexture);
  25391. }
  25392. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  25393. results.push(this.opacityTexture);
  25394. }
  25395. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  25396. results.push(this.reflectionTexture);
  25397. }
  25398. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  25399. results.push(this.emissiveTexture);
  25400. }
  25401. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  25402. results.push(this.specularTexture);
  25403. }
  25404. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  25405. results.push(this.bumpTexture);
  25406. }
  25407. if (this.lightmapTexture && this.lightmapTexture.animations && this.lightmapTexture.animations.length > 0) {
  25408. results.push(this.lightmapTexture);
  25409. }
  25410. if (this.refractionTexture && this.refractionTexture.animations && this.refractionTexture.animations.length > 0) {
  25411. results.push(this.refractionTexture);
  25412. }
  25413. if (this.cameraColorGradingTexture && this.cameraColorGradingTexture.animations && this.cameraColorGradingTexture.animations.length > 0) {
  25414. results.push(this.cameraColorGradingTexture);
  25415. }
  25416. return results;
  25417. };
  25418. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  25419. if (forceDisposeTextures) {
  25420. if (this.diffuseTexture) {
  25421. this.diffuseTexture.dispose();
  25422. }
  25423. if (this.ambientTexture) {
  25424. this.ambientTexture.dispose();
  25425. }
  25426. if (this.opacityTexture) {
  25427. this.opacityTexture.dispose();
  25428. }
  25429. if (this.reflectionTexture) {
  25430. this.reflectionTexture.dispose();
  25431. }
  25432. if (this.emissiveTexture) {
  25433. this.emissiveTexture.dispose();
  25434. }
  25435. if (this.specularTexture) {
  25436. this.specularTexture.dispose();
  25437. }
  25438. if (this.bumpTexture) {
  25439. this.bumpTexture.dispose();
  25440. }
  25441. if (this.lightmapTexture) {
  25442. this.lightmapTexture.dispose();
  25443. }
  25444. if (this.refractionTexture) {
  25445. this.refractionTexture.dispose();
  25446. }
  25447. if (this.cameraColorGradingTexture) {
  25448. this.cameraColorGradingTexture.dispose();
  25449. }
  25450. }
  25451. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  25452. };
  25453. StandardMaterial.prototype.clone = function (name) {
  25454. var _this = this;
  25455. return BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  25456. };
  25457. StandardMaterial.prototype.serialize = function () {
  25458. return BABYLON.SerializationHelper.Serialize(this);
  25459. };
  25460. // Statics
  25461. StandardMaterial.Parse = function (source, scene, rootUrl) {
  25462. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  25463. };
  25464. // Flags used to enable or disable a type of texture for all Standard Materials
  25465. StandardMaterial.DiffuseTextureEnabled = true;
  25466. StandardMaterial.AmbientTextureEnabled = true;
  25467. StandardMaterial.OpacityTextureEnabled = true;
  25468. StandardMaterial.ReflectionTextureEnabled = true;
  25469. StandardMaterial.EmissiveTextureEnabled = true;
  25470. StandardMaterial.SpecularTextureEnabled = true;
  25471. StandardMaterial.BumpTextureEnabled = true;
  25472. StandardMaterial.FresnelEnabled = true;
  25473. StandardMaterial.LightmapTextureEnabled = true;
  25474. StandardMaterial.RefractionTextureEnabled = true;
  25475. StandardMaterial.ColorGradingTextureEnabled = true;
  25476. __decorate([
  25477. BABYLON.serializeAsTexture()
  25478. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  25479. __decorate([
  25480. BABYLON.serializeAsTexture()
  25481. ], StandardMaterial.prototype, "ambientTexture", void 0);
  25482. __decorate([
  25483. BABYLON.serializeAsTexture()
  25484. ], StandardMaterial.prototype, "opacityTexture", void 0);
  25485. __decorate([
  25486. BABYLON.serializeAsTexture()
  25487. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  25488. __decorate([
  25489. BABYLON.serializeAsTexture()
  25490. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  25491. __decorate([
  25492. BABYLON.serializeAsTexture()
  25493. ], StandardMaterial.prototype, "specularTexture", void 0);
  25494. __decorate([
  25495. BABYLON.serializeAsTexture()
  25496. ], StandardMaterial.prototype, "bumpTexture", void 0);
  25497. __decorate([
  25498. BABYLON.serializeAsTexture()
  25499. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  25500. __decorate([
  25501. BABYLON.serializeAsTexture()
  25502. ], StandardMaterial.prototype, "refractionTexture", void 0);
  25503. __decorate([
  25504. BABYLON.serializeAsColor3("ambient")
  25505. ], StandardMaterial.prototype, "ambientColor", void 0);
  25506. __decorate([
  25507. BABYLON.serializeAsColor3("diffuse")
  25508. ], StandardMaterial.prototype, "diffuseColor", void 0);
  25509. __decorate([
  25510. BABYLON.serializeAsColor3("specular")
  25511. ], StandardMaterial.prototype, "specularColor", void 0);
  25512. __decorate([
  25513. BABYLON.serializeAsColor3("emissive")
  25514. ], StandardMaterial.prototype, "emissiveColor", void 0);
  25515. __decorate([
  25516. BABYLON.serialize()
  25517. ], StandardMaterial.prototype, "specularPower", void 0);
  25518. __decorate([
  25519. BABYLON.serialize()
  25520. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  25521. __decorate([
  25522. BABYLON.serialize()
  25523. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  25524. __decorate([
  25525. BABYLON.serialize()
  25526. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  25527. __decorate([
  25528. BABYLON.serialize()
  25529. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  25530. __decorate([
  25531. BABYLON.serialize()
  25532. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  25533. __decorate([
  25534. BABYLON.serialize()
  25535. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  25536. __decorate([
  25537. BABYLON.serialize()
  25538. ], StandardMaterial.prototype, "disableLighting", void 0);
  25539. __decorate([
  25540. BABYLON.serialize()
  25541. ], StandardMaterial.prototype, "useParallax", void 0);
  25542. __decorate([
  25543. BABYLON.serialize()
  25544. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  25545. __decorate([
  25546. BABYLON.serialize()
  25547. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  25548. __decorate([
  25549. BABYLON.serialize()
  25550. ], StandardMaterial.prototype, "roughness", void 0);
  25551. __decorate([
  25552. BABYLON.serialize()
  25553. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  25554. __decorate([
  25555. BABYLON.serialize()
  25556. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  25557. __decorate([
  25558. BABYLON.serialize()
  25559. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  25560. __decorate([
  25561. BABYLON.serializeAsFresnelParameters()
  25562. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  25563. __decorate([
  25564. BABYLON.serializeAsFresnelParameters()
  25565. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  25566. __decorate([
  25567. BABYLON.serializeAsFresnelParameters()
  25568. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  25569. __decorate([
  25570. BABYLON.serializeAsFresnelParameters()
  25571. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  25572. __decorate([
  25573. BABYLON.serializeAsFresnelParameters()
  25574. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  25575. __decorate([
  25576. BABYLON.serialize()
  25577. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  25578. __decorate([
  25579. BABYLON.serialize()
  25580. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  25581. __decorate([
  25582. BABYLON.serialize()
  25583. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  25584. __decorate([
  25585. BABYLON.serialize()
  25586. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  25587. __decorate([
  25588. BABYLON.serializeAsTexture()
  25589. ], StandardMaterial.prototype, "cameraColorGradingTexture", void 0);
  25590. __decorate([
  25591. BABYLON.serializeAsColorCurves()
  25592. ], StandardMaterial.prototype, "cameraColorCurves", void 0);
  25593. __decorate([
  25594. BABYLON.serialize()
  25595. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  25596. return StandardMaterial;
  25597. })(BABYLON.Material);
  25598. BABYLON.StandardMaterial = StandardMaterial;
  25599. })(BABYLON || (BABYLON = {}));
  25600. var BABYLON;
  25601. (function (BABYLON) {
  25602. var MultiMaterial = (function (_super) {
  25603. __extends(MultiMaterial, _super);
  25604. function MultiMaterial(name, scene) {
  25605. _super.call(this, name, scene, true);
  25606. this.subMaterials = new Array();
  25607. scene.multiMaterials.push(this);
  25608. }
  25609. // Properties
  25610. MultiMaterial.prototype.getSubMaterial = function (index) {
  25611. if (index < 0 || index >= this.subMaterials.length) {
  25612. return this.getScene().defaultMaterial;
  25613. }
  25614. return this.subMaterials[index];
  25615. };
  25616. // Methods
  25617. MultiMaterial.prototype.isReady = function (mesh) {
  25618. for (var index = 0; index < this.subMaterials.length; index++) {
  25619. var subMaterial = this.subMaterials[index];
  25620. if (subMaterial) {
  25621. if (!this.subMaterials[index].isReady(mesh)) {
  25622. return false;
  25623. }
  25624. }
  25625. }
  25626. return true;
  25627. };
  25628. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  25629. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  25630. for (var index = 0; index < this.subMaterials.length; index++) {
  25631. var subMaterial = null;
  25632. if (cloneChildren) {
  25633. subMaterial = this.subMaterials[index].clone(name + "-" + this.subMaterials[index].name);
  25634. }
  25635. else {
  25636. subMaterial = this.subMaterials[index];
  25637. }
  25638. newMultiMaterial.subMaterials.push(subMaterial);
  25639. }
  25640. return newMultiMaterial;
  25641. };
  25642. MultiMaterial.prototype.serialize = function () {
  25643. var serializationObject = {};
  25644. serializationObject.name = this.name;
  25645. serializationObject.id = this.id;
  25646. serializationObject.tags = BABYLON.Tags.GetTags(this);
  25647. serializationObject.materials = [];
  25648. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  25649. var subMat = this.subMaterials[matIndex];
  25650. if (subMat) {
  25651. serializationObject.materials.push(subMat.id);
  25652. }
  25653. else {
  25654. serializationObject.materials.push(null);
  25655. }
  25656. }
  25657. return serializationObject;
  25658. };
  25659. return MultiMaterial;
  25660. })(BABYLON.Material);
  25661. BABYLON.MultiMaterial = MultiMaterial;
  25662. })(BABYLON || (BABYLON = {}));
  25663. var BABYLON;
  25664. (function (BABYLON) {
  25665. var SceneLoader = (function () {
  25666. function SceneLoader() {
  25667. }
  25668. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  25669. get: function () {
  25670. return 0;
  25671. },
  25672. enumerable: true,
  25673. configurable: true
  25674. });
  25675. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  25676. get: function () {
  25677. return 1;
  25678. },
  25679. enumerable: true,
  25680. configurable: true
  25681. });
  25682. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  25683. get: function () {
  25684. return 2;
  25685. },
  25686. enumerable: true,
  25687. configurable: true
  25688. });
  25689. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  25690. get: function () {
  25691. return 3;
  25692. },
  25693. enumerable: true,
  25694. configurable: true
  25695. });
  25696. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  25697. get: function () {
  25698. return SceneLoader._ForceFullSceneLoadingForIncremental;
  25699. },
  25700. set: function (value) {
  25701. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  25702. },
  25703. enumerable: true,
  25704. configurable: true
  25705. });
  25706. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  25707. get: function () {
  25708. return SceneLoader._ShowLoadingScreen;
  25709. },
  25710. set: function (value) {
  25711. SceneLoader._ShowLoadingScreen = value;
  25712. },
  25713. enumerable: true,
  25714. configurable: true
  25715. });
  25716. Object.defineProperty(SceneLoader, "loggingLevel", {
  25717. get: function () {
  25718. return SceneLoader._loggingLevel;
  25719. },
  25720. set: function (value) {
  25721. SceneLoader._loggingLevel = value;
  25722. },
  25723. enumerable: true,
  25724. configurable: true
  25725. });
  25726. SceneLoader._getPluginForFilename = function (sceneFilename) {
  25727. var dotPosition = sceneFilename.lastIndexOf(".");
  25728. var queryStringPosition = sceneFilename.indexOf("?");
  25729. if (queryStringPosition === -1) {
  25730. queryStringPosition = sceneFilename.length;
  25731. }
  25732. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  25733. for (var index = 0; index < this._registeredPlugins.length; index++) {
  25734. var plugin = this._registeredPlugins[index];
  25735. if (plugin.extensions.indexOf(extension) !== -1) {
  25736. return plugin;
  25737. }
  25738. }
  25739. return this._registeredPlugins[0];
  25740. };
  25741. // Public functions
  25742. SceneLoader.GetPluginForExtension = function (extension) {
  25743. for (var index = 0; index < this._registeredPlugins.length; index++) {
  25744. var plugin = this._registeredPlugins[index];
  25745. if (plugin.extensions.indexOf(extension) !== -1) {
  25746. return plugin;
  25747. }
  25748. }
  25749. return null;
  25750. };
  25751. SceneLoader.RegisterPlugin = function (plugin) {
  25752. plugin.extensions = plugin.extensions.toLowerCase();
  25753. SceneLoader._registeredPlugins.push(plugin);
  25754. };
  25755. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  25756. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  25757. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  25758. return;
  25759. }
  25760. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  25761. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  25762. return;
  25763. }
  25764. var loadingToken = {};
  25765. scene._addPendingData(loadingToken);
  25766. var manifestChecked = function (success) {
  25767. scene.database = database;
  25768. var plugin = SceneLoader._getPluginForFilename(sceneFilename);
  25769. var importMeshFromData = function (data) {
  25770. var meshes = [];
  25771. var particleSystems = [];
  25772. var skeletons = [];
  25773. try {
  25774. if (plugin.importMesh) {
  25775. var syncedPlugin = plugin;
  25776. if (!syncedPlugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  25777. if (onerror) {
  25778. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  25779. }
  25780. scene._removePendingData(loadingToken);
  25781. return;
  25782. }
  25783. if (onsuccess) {
  25784. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  25785. onsuccess(meshes, particleSystems, skeletons);
  25786. scene._removePendingData(loadingToken);
  25787. }
  25788. }
  25789. else {
  25790. var asyncedPlugin = plugin;
  25791. asyncedPlugin.importMeshAsync(meshesNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  25792. if (onsuccess) {
  25793. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  25794. onsuccess(meshes, particleSystems, skeletons);
  25795. scene._removePendingData(loadingToken);
  25796. }
  25797. }, function () {
  25798. if (onerror) {
  25799. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  25800. }
  25801. scene._removePendingData(loadingToken);
  25802. });
  25803. }
  25804. }
  25805. catch (e) {
  25806. if (onerror) {
  25807. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename, e);
  25808. }
  25809. scene._removePendingData(loadingToken);
  25810. }
  25811. };
  25812. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  25813. // Direct load
  25814. importMeshFromData(sceneFilename.substr(5));
  25815. return;
  25816. }
  25817. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  25818. importMeshFromData(data);
  25819. }, progressCallBack, database);
  25820. };
  25821. if (scene.getEngine().enableOfflineSupport && !(sceneFilename.substr && sceneFilename.substr(0, 5) === "data:")) {
  25822. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  25823. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  25824. }
  25825. else {
  25826. // If the scene is a data stream or offline support is not enabled, it's a direct load
  25827. manifestChecked(true);
  25828. }
  25829. };
  25830. /**
  25831. * Load a scene
  25832. * @param rootUrl a string that defines the root url for scene and resources
  25833. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  25834. * @param engine is the instance of BABYLON.Engine to use to create the scene
  25835. */
  25836. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  25837. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  25838. };
  25839. /**
  25840. * Append a scene
  25841. * @param rootUrl a string that defines the root url for scene and resources
  25842. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  25843. * @param scene is the instance of BABYLON.Scene to append to
  25844. */
  25845. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  25846. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  25847. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  25848. return;
  25849. }
  25850. var plugin = this._getPluginForFilename(sceneFilename.name || sceneFilename);
  25851. var database;
  25852. var loadingToken = {};
  25853. scene._addPendingData(loadingToken);
  25854. if (SceneLoader.ShowLoadingScreen) {
  25855. scene.getEngine().displayLoadingUI();
  25856. }
  25857. var loadSceneFromData = function (data) {
  25858. scene.database = database;
  25859. if (plugin.load) {
  25860. var syncedPlugin = plugin;
  25861. if (!syncedPlugin.load(scene, data, rootUrl)) {
  25862. if (onerror) {
  25863. onerror(scene);
  25864. }
  25865. scene._removePendingData(loadingToken);
  25866. scene.getEngine().hideLoadingUI();
  25867. return;
  25868. }
  25869. if (onsuccess) {
  25870. onsuccess(scene);
  25871. }
  25872. scene._removePendingData(loadingToken);
  25873. }
  25874. else {
  25875. var asyncedPlugin = plugin;
  25876. asyncedPlugin.loadAsync(scene, data, rootUrl, function () {
  25877. if (onsuccess) {
  25878. onsuccess(scene);
  25879. }
  25880. }, function () {
  25881. if (onerror) {
  25882. onerror(scene);
  25883. }
  25884. scene._removePendingData(loadingToken);
  25885. scene.getEngine().hideLoadingUI();
  25886. });
  25887. }
  25888. if (SceneLoader.ShowLoadingScreen) {
  25889. scene.executeWhenReady(function () {
  25890. scene.getEngine().hideLoadingUI();
  25891. });
  25892. }
  25893. };
  25894. var manifestChecked = function (success) {
  25895. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database);
  25896. };
  25897. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  25898. // Direct load
  25899. loadSceneFromData(sceneFilename.substr(5));
  25900. return;
  25901. }
  25902. if (rootUrl.indexOf("file:") === -1) {
  25903. if (scene.getEngine().enableOfflineSupport) {
  25904. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  25905. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  25906. }
  25907. else {
  25908. manifestChecked(true);
  25909. }
  25910. }
  25911. else {
  25912. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack);
  25913. }
  25914. };
  25915. // Flags
  25916. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  25917. SceneLoader._ShowLoadingScreen = true;
  25918. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  25919. // Members
  25920. SceneLoader._registeredPlugins = new Array();
  25921. return SceneLoader;
  25922. })();
  25923. BABYLON.SceneLoader = SceneLoader;
  25924. ;
  25925. })(BABYLON || (BABYLON = {}));
  25926. var BABYLON;
  25927. (function (BABYLON) {
  25928. var Internals;
  25929. (function (Internals) {
  25930. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  25931. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  25932. var parsedMaterial = parsedData.materials[index];
  25933. if (parsedMaterial.id === id) {
  25934. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  25935. }
  25936. }
  25937. return null;
  25938. };
  25939. var isDescendantOf = function (mesh, names, hierarchyIds) {
  25940. names = (names instanceof Array) ? names : [names];
  25941. for (var i in names) {
  25942. if (mesh.name === names[i]) {
  25943. hierarchyIds.push(mesh.id);
  25944. return true;
  25945. }
  25946. }
  25947. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  25948. hierarchyIds.push(mesh.id);
  25949. return true;
  25950. }
  25951. return false;
  25952. };
  25953. var logOperation = function (operation, producer) {
  25954. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  25955. };
  25956. BABYLON.SceneLoader.RegisterPlugin({
  25957. extensions: ".babylon",
  25958. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  25959. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  25960. // when SceneLoader.debugLogging = true (default), or exception encountered.
  25961. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  25962. // and avoid problems with multiple concurrent .babylon loads.
  25963. var log = "importMesh has failed JSON parse";
  25964. try {
  25965. var parsedData = JSON.parse(data);
  25966. log = "";
  25967. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  25968. var loadedSkeletonsIds = [];
  25969. var loadedMaterialsIds = [];
  25970. var hierarchyIds = [];
  25971. var index;
  25972. var cache;
  25973. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  25974. var parsedMesh = parsedData.meshes[index];
  25975. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  25976. if (meshesNames instanceof Array) {
  25977. // Remove found mesh name from list.
  25978. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  25979. }
  25980. //Geometry?
  25981. if (parsedMesh.geometryId) {
  25982. //does the file contain geometries?
  25983. if (parsedData.geometries) {
  25984. //find the correct geometry and add it to the scene
  25985. var found = false;
  25986. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  25987. if (found || !parsedData.geometries[geometryType] || !(parsedData.geometries[geometryType] instanceof Array)) {
  25988. return;
  25989. }
  25990. else {
  25991. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  25992. if (parsedGeometryData.id === parsedMesh.geometryId) {
  25993. switch (geometryType) {
  25994. case "boxes":
  25995. BABYLON.Geometry.Primitives.Box.Parse(parsedGeometryData, scene);
  25996. break;
  25997. case "spheres":
  25998. BABYLON.Geometry.Primitives.Sphere.Parse(parsedGeometryData, scene);
  25999. break;
  26000. case "cylinders":
  26001. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedGeometryData, scene);
  26002. break;
  26003. case "toruses":
  26004. BABYLON.Geometry.Primitives.Torus.Parse(parsedGeometryData, scene);
  26005. break;
  26006. case "grounds":
  26007. BABYLON.Geometry.Primitives.Ground.Parse(parsedGeometryData, scene);
  26008. break;
  26009. case "planes":
  26010. BABYLON.Geometry.Primitives.Plane.Parse(parsedGeometryData, scene);
  26011. break;
  26012. case "torusKnots":
  26013. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedGeometryData, scene);
  26014. break;
  26015. case "vertexData":
  26016. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  26017. break;
  26018. }
  26019. found = true;
  26020. }
  26021. });
  26022. }
  26023. });
  26024. if (!found) {
  26025. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  26026. }
  26027. }
  26028. }
  26029. // Material ?
  26030. if (parsedMesh.materialId) {
  26031. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  26032. if (!materialFound && parsedData.multiMaterials) {
  26033. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  26034. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  26035. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  26036. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  26037. var subMatId = parsedMultiMaterial.materials[matIndex];
  26038. loadedMaterialsIds.push(subMatId);
  26039. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  26040. log += "\n\tMaterial " + mat.toString(fullDetails);
  26041. }
  26042. loadedMaterialsIds.push(parsedMultiMaterial.id);
  26043. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  26044. materialFound = true;
  26045. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  26046. break;
  26047. }
  26048. }
  26049. }
  26050. if (!materialFound) {
  26051. loadedMaterialsIds.push(parsedMesh.materialId);
  26052. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  26053. if (!mat) {
  26054. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  26055. }
  26056. else {
  26057. log += "\n\tMaterial " + mat.toString(fullDetails);
  26058. }
  26059. }
  26060. }
  26061. // Skeleton ?
  26062. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  26063. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  26064. if (!skeletonAlreadyLoaded) {
  26065. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  26066. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  26067. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  26068. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  26069. skeletons.push(skeleton);
  26070. loadedSkeletonsIds.push(parsedSkeleton.id);
  26071. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  26072. }
  26073. }
  26074. }
  26075. }
  26076. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  26077. meshes.push(mesh);
  26078. log += "\n\tMesh " + mesh.toString(fullDetails);
  26079. }
  26080. }
  26081. // Connecting parents
  26082. var currentMesh;
  26083. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  26084. currentMesh = scene.meshes[index];
  26085. if (currentMesh._waitingParentId) {
  26086. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  26087. currentMesh._waitingParentId = undefined;
  26088. }
  26089. }
  26090. // freeze and compute world matrix application
  26091. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  26092. currentMesh = scene.meshes[index];
  26093. if (currentMesh._waitingFreezeWorldMatrix) {
  26094. currentMesh.freezeWorldMatrix();
  26095. currentMesh._waitingFreezeWorldMatrix = undefined;
  26096. }
  26097. else {
  26098. currentMesh.computeWorldMatrix(true);
  26099. }
  26100. }
  26101. // Particles
  26102. if (parsedData.particleSystems) {
  26103. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  26104. var parsedParticleSystem = parsedData.particleSystems[index];
  26105. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  26106. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  26107. }
  26108. }
  26109. }
  26110. return true;
  26111. }
  26112. catch (err) {
  26113. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log);
  26114. log = null;
  26115. throw err;
  26116. }
  26117. finally {
  26118. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  26119. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  26120. }
  26121. }
  26122. },
  26123. load: function (scene, data, rootUrl) {
  26124. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  26125. // when SceneLoader.debugLogging = true (default), or exception encountered.
  26126. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  26127. // and avoid problems with multiple concurrent .babylon loads.
  26128. var log = "importScene has failed JSON parse";
  26129. try {
  26130. var parsedData = JSON.parse(data);
  26131. log = "";
  26132. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  26133. // Scene
  26134. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  26135. scene.autoClear = parsedData.autoClear;
  26136. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  26137. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  26138. if (parsedData.gravity) {
  26139. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  26140. }
  26141. // Fog
  26142. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  26143. scene.fogMode = parsedData.fogMode;
  26144. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  26145. scene.fogStart = parsedData.fogStart;
  26146. scene.fogEnd = parsedData.fogEnd;
  26147. scene.fogDensity = parsedData.fogDensity;
  26148. log += "\tFog mode for scene: ";
  26149. switch (scene.fogMode) {
  26150. // getters not compiling, so using hardcoded
  26151. case 1:
  26152. log += "exp\n";
  26153. break;
  26154. case 2:
  26155. log += "exp2\n";
  26156. break;
  26157. case 3:
  26158. log += "linear\n";
  26159. break;
  26160. }
  26161. }
  26162. //Physics
  26163. if (parsedData.physicsEnabled) {
  26164. var physicsPlugin;
  26165. if (parsedData.physicsEngine === "cannon") {
  26166. physicsPlugin = new BABYLON.CannonJSPlugin();
  26167. }
  26168. else if (parsedData.physicsEngine === "oimo") {
  26169. physicsPlugin = new BABYLON.OimoJSPlugin();
  26170. }
  26171. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  26172. //else - default engine, which is currently oimo
  26173. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  26174. scene.enablePhysics(physicsGravity, physicsPlugin);
  26175. }
  26176. //collisions, if defined. otherwise, default is true
  26177. if (parsedData.collisionsEnabled != undefined) {
  26178. scene.collisionsEnabled = parsedData.collisionsEnabled;
  26179. }
  26180. scene.workerCollisions = !!parsedData.workerCollisions;
  26181. var index;
  26182. var cache;
  26183. // Lights
  26184. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  26185. var parsedLight = parsedData.lights[index];
  26186. var light = BABYLON.Light.Parse(parsedLight, scene);
  26187. log += (index === 0 ? "\n\tLights:" : "");
  26188. log += "\n\t\t" + light.toString(fullDetails);
  26189. }
  26190. // Animations
  26191. if (parsedData.animations) {
  26192. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  26193. var parsedAnimation = parsedData.animations[index];
  26194. var animation = BABYLON.Animation.Parse(parsedAnimation);
  26195. scene.animations.push(animation);
  26196. log += (index === 0 ? "\n\tAnimations:" : "");
  26197. log += "\n\t\t" + animation.toString(fullDetails);
  26198. }
  26199. }
  26200. if (parsedData.autoAnimate) {
  26201. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  26202. }
  26203. // Materials
  26204. if (parsedData.materials) {
  26205. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  26206. var parsedMaterial = parsedData.materials[index];
  26207. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  26208. log += (index === 0 ? "\n\tMaterials:" : "");
  26209. log += "\n\t\t" + mat.toString(fullDetails);
  26210. }
  26211. }
  26212. if (parsedData.multiMaterials) {
  26213. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  26214. var parsedMultiMaterial = parsedData.multiMaterials[index];
  26215. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  26216. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  26217. log += "\n\t\t" + mmat.toString(fullDetails);
  26218. }
  26219. }
  26220. // Skeletons
  26221. if (parsedData.skeletons) {
  26222. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  26223. var parsedSkeleton = parsedData.skeletons[index];
  26224. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  26225. log += (index === 0 ? "\n\tSkeletons:" : "");
  26226. log += "\n\t\t" + skeleton.toString(fullDetails);
  26227. }
  26228. }
  26229. // Geometries
  26230. var geometries = parsedData.geometries;
  26231. if (geometries) {
  26232. // Boxes
  26233. var boxes = geometries.boxes;
  26234. if (boxes) {
  26235. for (index = 0, cache = boxes.length; index < cache; index++) {
  26236. var parsedBox = boxes[index];
  26237. BABYLON.Geometry.Primitives.Box.Parse(parsedBox, scene);
  26238. }
  26239. }
  26240. // Spheres
  26241. var spheres = geometries.spheres;
  26242. if (spheres) {
  26243. for (index = 0, cache = spheres.length; index < cache; index++) {
  26244. var parsedSphere = spheres[index];
  26245. BABYLON.Geometry.Primitives.Sphere.Parse(parsedSphere, scene);
  26246. }
  26247. }
  26248. // Cylinders
  26249. var cylinders = geometries.cylinders;
  26250. if (cylinders) {
  26251. for (index = 0, cache = cylinders.length; index < cache; index++) {
  26252. var parsedCylinder = cylinders[index];
  26253. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedCylinder, scene);
  26254. }
  26255. }
  26256. // Toruses
  26257. var toruses = geometries.toruses;
  26258. if (toruses) {
  26259. for (index = 0, cache = toruses.length; index < cache; index++) {
  26260. var parsedTorus = toruses[index];
  26261. BABYLON.Geometry.Primitives.Torus.Parse(parsedTorus, scene);
  26262. }
  26263. }
  26264. // Grounds
  26265. var grounds = geometries.grounds;
  26266. if (grounds) {
  26267. for (index = 0, cache = grounds.length; index < cache; index++) {
  26268. var parsedGround = grounds[index];
  26269. BABYLON.Geometry.Primitives.Ground.Parse(parsedGround, scene);
  26270. }
  26271. }
  26272. // Planes
  26273. var planes = geometries.planes;
  26274. if (planes) {
  26275. for (index = 0, cache = planes.length; index < cache; index++) {
  26276. var parsedPlane = planes[index];
  26277. BABYLON.Geometry.Primitives.Plane.Parse(parsedPlane, scene);
  26278. }
  26279. }
  26280. // TorusKnots
  26281. var torusKnots = geometries.torusKnots;
  26282. if (torusKnots) {
  26283. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  26284. var parsedTorusKnot = torusKnots[index];
  26285. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedTorusKnot, scene);
  26286. }
  26287. }
  26288. // VertexData
  26289. var vertexData = geometries.vertexData;
  26290. if (vertexData) {
  26291. for (index = 0, cache = vertexData.length; index < cache; index++) {
  26292. var parsedVertexData = vertexData[index];
  26293. BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl);
  26294. }
  26295. }
  26296. }
  26297. // Meshes
  26298. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  26299. var parsedMesh = parsedData.meshes[index];
  26300. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  26301. log += (index === 0 ? "\n\tMeshes:" : "");
  26302. log += "\n\t\t" + mesh.toString(fullDetails);
  26303. }
  26304. // Cameras
  26305. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  26306. var parsedCamera = parsedData.cameras[index];
  26307. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  26308. log += (index === 0 ? "\n\tCameras:" : "");
  26309. log += "\n\t\t" + camera.toString(fullDetails);
  26310. }
  26311. if (parsedData.activeCameraID) {
  26312. scene.setActiveCameraByID(parsedData.activeCameraID);
  26313. }
  26314. // Browsing all the graph to connect the dots
  26315. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  26316. var camera = scene.cameras[index];
  26317. if (camera._waitingParentId) {
  26318. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  26319. camera._waitingParentId = undefined;
  26320. }
  26321. }
  26322. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  26323. var light = scene.lights[index];
  26324. if (light._waitingParentId) {
  26325. light.parent = scene.getLastEntryByID(light._waitingParentId);
  26326. light._waitingParentId = undefined;
  26327. }
  26328. }
  26329. // Sounds
  26330. var loadedSounds = [];
  26331. var loadedSound;
  26332. if (BABYLON.AudioEngine && parsedData.sounds) {
  26333. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  26334. var parsedSound = parsedData.sounds[index];
  26335. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  26336. if (!parsedSound.url)
  26337. parsedSound.url = parsedSound.name;
  26338. if (!loadedSounds[parsedSound.url]) {
  26339. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  26340. loadedSounds[parsedSound.url] = loadedSound;
  26341. }
  26342. else {
  26343. BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]);
  26344. }
  26345. }
  26346. else {
  26347. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  26348. }
  26349. }
  26350. }
  26351. loadedSounds = [];
  26352. // Connect parents & children and parse actions
  26353. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  26354. var mesh = scene.meshes[index];
  26355. if (mesh._waitingParentId) {
  26356. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  26357. mesh._waitingParentId = undefined;
  26358. }
  26359. if (mesh._waitingActions) {
  26360. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  26361. mesh._waitingActions = undefined;
  26362. }
  26363. }
  26364. // freeze world matrix application
  26365. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  26366. var currentMesh = scene.meshes[index];
  26367. if (currentMesh._waitingFreezeWorldMatrix) {
  26368. currentMesh.freezeWorldMatrix();
  26369. currentMesh._waitingFreezeWorldMatrix = undefined;
  26370. }
  26371. else {
  26372. currentMesh.computeWorldMatrix(true);
  26373. }
  26374. }
  26375. // Particles Systems
  26376. if (parsedData.particleSystems) {
  26377. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  26378. var parsedParticleSystem = parsedData.particleSystems[index];
  26379. BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  26380. }
  26381. }
  26382. // Lens flares
  26383. if (parsedData.lensFlareSystems) {
  26384. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  26385. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  26386. BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  26387. }
  26388. }
  26389. // Shadows
  26390. if (parsedData.shadowGenerators) {
  26391. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  26392. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  26393. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  26394. }
  26395. }
  26396. // Actions (scene)
  26397. if (parsedData.actions) {
  26398. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  26399. }
  26400. // Finish
  26401. return true;
  26402. }
  26403. catch (err) {
  26404. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log);
  26405. log = null;
  26406. throw err;
  26407. }
  26408. finally {
  26409. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  26410. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  26411. }
  26412. }
  26413. }
  26414. });
  26415. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  26416. })(BABYLON || (BABYLON = {}));
  26417. var BABYLON;
  26418. (function (BABYLON) {
  26419. var SpriteManager = (function () {
  26420. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  26421. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  26422. this.name = name;
  26423. this.sprites = new Array();
  26424. this.renderingGroupId = 0;
  26425. this.layerMask = 0x0FFFFFFF;
  26426. this.fogEnabled = true;
  26427. this.isPickable = false;
  26428. /**
  26429. * An event triggered when the manager is disposed.
  26430. * @type {BABYLON.Observable}
  26431. */
  26432. this.onDisposeObservable = new BABYLON.Observable();
  26433. this._vertexBuffers = {};
  26434. this._capacity = capacity;
  26435. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  26436. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  26437. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  26438. this._epsilon = epsilon === undefined ? 0.01 : epsilon;
  26439. if (cellSize.width) {
  26440. this.cellWidth = cellSize.width;
  26441. this.cellHeight = cellSize.height;
  26442. }
  26443. else {
  26444. this.cellWidth = cellSize;
  26445. this.cellHeight = cellSize;
  26446. }
  26447. this._scene = scene;
  26448. this._scene.spriteManagers.push(this);
  26449. var indices = [];
  26450. var index = 0;
  26451. for (var count = 0; count < capacity; count++) {
  26452. indices.push(index);
  26453. indices.push(index + 1);
  26454. indices.push(index + 2);
  26455. indices.push(index);
  26456. indices.push(index + 2);
  26457. indices.push(index + 3);
  26458. index += 4;
  26459. }
  26460. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  26461. // VBO
  26462. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  26463. this._vertexData = new Float32Array(capacity * 16 * 4);
  26464. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  26465. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  26466. var options = this._buffer.createVertexBuffer("options", 4, 4);
  26467. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  26468. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  26469. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  26470. this._vertexBuffers["options"] = options;
  26471. this._vertexBuffers["cellInfo"] = cellInfo;
  26472. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  26473. // Effects
  26474. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  26475. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  26476. }
  26477. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  26478. set: function (callback) {
  26479. if (this._onDisposeObserver) {
  26480. this.onDisposeObservable.remove(this._onDisposeObserver);
  26481. }
  26482. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  26483. },
  26484. enumerable: true,
  26485. configurable: true
  26486. });
  26487. Object.defineProperty(SpriteManager.prototype, "texture", {
  26488. get: function () {
  26489. return this._spriteTexture;
  26490. },
  26491. set: function (value) {
  26492. this._spriteTexture = value;
  26493. },
  26494. enumerable: true,
  26495. configurable: true
  26496. });
  26497. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  26498. var arrayOffset = index * 16;
  26499. if (offsetX === 0)
  26500. offsetX = this._epsilon;
  26501. else if (offsetX === 1)
  26502. offsetX = 1 - this._epsilon;
  26503. if (offsetY === 0)
  26504. offsetY = this._epsilon;
  26505. else if (offsetY === 1)
  26506. offsetY = 1 - this._epsilon;
  26507. this._vertexData[arrayOffset] = sprite.position.x;
  26508. this._vertexData[arrayOffset + 1] = sprite.position.y;
  26509. this._vertexData[arrayOffset + 2] = sprite.position.z;
  26510. this._vertexData[arrayOffset + 3] = sprite.angle;
  26511. this._vertexData[arrayOffset + 4] = sprite.width;
  26512. this._vertexData[arrayOffset + 5] = sprite.height;
  26513. this._vertexData[arrayOffset + 6] = offsetX;
  26514. this._vertexData[arrayOffset + 7] = offsetY;
  26515. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  26516. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  26517. var offset = (sprite.cellIndex / rowSize) >> 0;
  26518. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  26519. this._vertexData[arrayOffset + 11] = offset;
  26520. // Color
  26521. this._vertexData[arrayOffset + 12] = sprite.color.r;
  26522. this._vertexData[arrayOffset + 13] = sprite.color.g;
  26523. this._vertexData[arrayOffset + 14] = sprite.color.b;
  26524. this._vertexData[arrayOffset + 15] = sprite.color.a;
  26525. };
  26526. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  26527. var count = Math.min(this._capacity, this.sprites.length);
  26528. var min = BABYLON.Vector3.Zero();
  26529. var max = BABYLON.Vector3.Zero();
  26530. var distance = Number.MAX_VALUE;
  26531. var currentSprite;
  26532. var cameraSpacePosition = BABYLON.Vector3.Zero();
  26533. var cameraView = camera.getViewMatrix();
  26534. for (var index = 0; index < count; index++) {
  26535. var sprite = this.sprites[index];
  26536. if (!sprite) {
  26537. continue;
  26538. }
  26539. if (predicate) {
  26540. if (!predicate(sprite)) {
  26541. continue;
  26542. }
  26543. }
  26544. else if (!sprite.isPickable) {
  26545. continue;
  26546. }
  26547. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  26548. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  26549. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  26550. if (ray.intersectsBoxMinMax(min, max)) {
  26551. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  26552. if (distance > currentDistance) {
  26553. distance = currentDistance;
  26554. currentSprite = sprite;
  26555. if (fastCheck) {
  26556. break;
  26557. }
  26558. }
  26559. }
  26560. }
  26561. if (currentSprite) {
  26562. var result = new BABYLON.PickingInfo();
  26563. result.hit = true;
  26564. result.pickedSprite = currentSprite;
  26565. result.distance = distance;
  26566. return result;
  26567. }
  26568. return null;
  26569. };
  26570. SpriteManager.prototype.render = function () {
  26571. // Check
  26572. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  26573. return;
  26574. var engine = this._scene.getEngine();
  26575. var baseSize = this._spriteTexture.getBaseSize();
  26576. // Sprites
  26577. var deltaTime = engine.getDeltaTime();
  26578. var max = Math.min(this._capacity, this.sprites.length);
  26579. var rowSize = baseSize.width / this.cellWidth;
  26580. var offset = 0;
  26581. for (var index = 0; index < max; index++) {
  26582. var sprite = this.sprites[index];
  26583. if (!sprite) {
  26584. continue;
  26585. }
  26586. sprite._animate(deltaTime);
  26587. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  26588. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  26589. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  26590. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  26591. }
  26592. this._buffer.update(this._vertexData);
  26593. // Render
  26594. var effect = this._effectBase;
  26595. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  26596. effect = this._effectFog;
  26597. }
  26598. engine.enableEffect(effect);
  26599. var viewMatrix = this._scene.getViewMatrix();
  26600. effect.setTexture("diffuseSampler", this._spriteTexture);
  26601. effect.setMatrix("view", viewMatrix);
  26602. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  26603. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  26604. // Fog
  26605. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  26606. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  26607. effect.setColor3("vFogColor", this._scene.fogColor);
  26608. }
  26609. // VBOs
  26610. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  26611. // Draw order
  26612. engine.setDepthFunctionToLessOrEqual();
  26613. effect.setBool("alphaTest", true);
  26614. engine.setColorWrite(false);
  26615. engine.draw(true, 0, max * 6);
  26616. engine.setColorWrite(true);
  26617. effect.setBool("alphaTest", false);
  26618. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  26619. engine.draw(true, 0, max * 6);
  26620. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  26621. };
  26622. SpriteManager.prototype.dispose = function () {
  26623. if (this._buffer) {
  26624. this._buffer.dispose();
  26625. this._buffer = null;
  26626. }
  26627. if (this._indexBuffer) {
  26628. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  26629. this._indexBuffer = null;
  26630. }
  26631. if (this._spriteTexture) {
  26632. this._spriteTexture.dispose();
  26633. this._spriteTexture = null;
  26634. }
  26635. // Remove from scene
  26636. var index = this._scene.spriteManagers.indexOf(this);
  26637. this._scene.spriteManagers.splice(index, 1);
  26638. // Callback
  26639. this.onDisposeObservable.notifyObservers(this);
  26640. this.onDisposeObservable.clear();
  26641. };
  26642. return SpriteManager;
  26643. })();
  26644. BABYLON.SpriteManager = SpriteManager;
  26645. })(BABYLON || (BABYLON = {}));
  26646. var BABYLON;
  26647. (function (BABYLON) {
  26648. var Sprite = (function () {
  26649. function Sprite(name, manager) {
  26650. this.name = name;
  26651. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  26652. this.width = 1.0;
  26653. this.height = 1.0;
  26654. this.angle = 0;
  26655. this.cellIndex = 0;
  26656. this.invertU = 0;
  26657. this.invertV = 0;
  26658. this.animations = new Array();
  26659. this.isPickable = false;
  26660. this._animationStarted = false;
  26661. this._loopAnimation = false;
  26662. this._fromIndex = 0;
  26663. this._toIndex = 0;
  26664. this._delay = 0;
  26665. this._direction = 1;
  26666. this._frameCount = 0;
  26667. this._time = 0;
  26668. this._manager = manager;
  26669. this._manager.sprites.push(this);
  26670. this.position = BABYLON.Vector3.Zero();
  26671. }
  26672. Object.defineProperty(Sprite.prototype, "size", {
  26673. get: function () {
  26674. return this.width;
  26675. },
  26676. set: function (value) {
  26677. this.width = value;
  26678. this.height = value;
  26679. },
  26680. enumerable: true,
  26681. configurable: true
  26682. });
  26683. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  26684. this._fromIndex = from;
  26685. this._toIndex = to;
  26686. this._loopAnimation = loop;
  26687. this._delay = delay;
  26688. this._animationStarted = true;
  26689. this._direction = from < to ? 1 : -1;
  26690. this.cellIndex = from;
  26691. this._time = 0;
  26692. this._onAnimationEnd = onAnimationEnd;
  26693. };
  26694. Sprite.prototype.stopAnimation = function () {
  26695. this._animationStarted = false;
  26696. };
  26697. Sprite.prototype._animate = function (deltaTime) {
  26698. if (!this._animationStarted)
  26699. return;
  26700. this._time += deltaTime;
  26701. if (this._time > this._delay) {
  26702. this._time = this._time % this._delay;
  26703. this.cellIndex += this._direction;
  26704. if (this.cellIndex === this._toIndex) {
  26705. if (this._loopAnimation) {
  26706. this.cellIndex = this._fromIndex;
  26707. }
  26708. else {
  26709. this._animationStarted = false;
  26710. if (this._onAnimationEnd) {
  26711. this._onAnimationEnd();
  26712. }
  26713. if (this.disposeWhenFinishedAnimating) {
  26714. this.dispose();
  26715. }
  26716. }
  26717. }
  26718. }
  26719. };
  26720. Sprite.prototype.dispose = function () {
  26721. for (var i = 0; i < this._manager.sprites.length; i++) {
  26722. if (this._manager.sprites[i] == this) {
  26723. this._manager.sprites.splice(i, 1);
  26724. }
  26725. }
  26726. };
  26727. return Sprite;
  26728. })();
  26729. BABYLON.Sprite = Sprite;
  26730. })(BABYLON || (BABYLON = {}));
  26731. var BABYLON;
  26732. (function (BABYLON) {
  26733. var Layer = (function () {
  26734. function Layer(name, imgUrl, scene, isBackground, color) {
  26735. this.name = name;
  26736. this.scale = new BABYLON.Vector2(1, 1);
  26737. this.offset = new BABYLON.Vector2(0, 0);
  26738. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  26739. this._vertexBuffers = {};
  26740. // Events
  26741. /**
  26742. * An event triggered when the layer is disposed.
  26743. * @type {BABYLON.Observable}
  26744. */
  26745. this.onDisposeObservable = new BABYLON.Observable();
  26746. /**
  26747. * An event triggered before rendering the scene
  26748. * @type {BABYLON.Observable}
  26749. */
  26750. this.onBeforeRenderObservable = new BABYLON.Observable();
  26751. /**
  26752. * An event triggered after rendering the scene
  26753. * @type {BABYLON.Observable}
  26754. */
  26755. this.onAfterRenderObservable = new BABYLON.Observable();
  26756. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  26757. this.isBackground = isBackground === undefined ? true : isBackground;
  26758. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  26759. this._scene = scene;
  26760. this._scene.layers.push(this);
  26761. var engine = scene.getEngine();
  26762. // VBO
  26763. var vertices = [];
  26764. vertices.push(1, 1);
  26765. vertices.push(-1, 1);
  26766. vertices.push(-1, -1);
  26767. vertices.push(1, -1);
  26768. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  26769. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  26770. // Indices
  26771. var indices = [];
  26772. indices.push(0);
  26773. indices.push(1);
  26774. indices.push(2);
  26775. indices.push(0);
  26776. indices.push(2);
  26777. indices.push(3);
  26778. this._indexBuffer = engine.createIndexBuffer(indices);
  26779. // Effects
  26780. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  26781. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  26782. }
  26783. Object.defineProperty(Layer.prototype, "onDispose", {
  26784. set: function (callback) {
  26785. if (this._onDisposeObserver) {
  26786. this.onDisposeObservable.remove(this._onDisposeObserver);
  26787. }
  26788. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  26789. },
  26790. enumerable: true,
  26791. configurable: true
  26792. });
  26793. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  26794. set: function (callback) {
  26795. if (this._onBeforeRenderObserver) {
  26796. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  26797. }
  26798. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  26799. },
  26800. enumerable: true,
  26801. configurable: true
  26802. });
  26803. Object.defineProperty(Layer.prototype, "onAfterRender", {
  26804. set: function (callback) {
  26805. if (this._onAfterRenderObserver) {
  26806. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  26807. }
  26808. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  26809. },
  26810. enumerable: true,
  26811. configurable: true
  26812. });
  26813. Layer.prototype.render = function () {
  26814. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  26815. // Check
  26816. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  26817. return;
  26818. var engine = this._scene.getEngine();
  26819. this.onBeforeRenderObservable.notifyObservers(this);
  26820. // Render
  26821. engine.enableEffect(currentEffect);
  26822. engine.setState(false);
  26823. // Texture
  26824. currentEffect.setTexture("textureSampler", this.texture);
  26825. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  26826. // Color
  26827. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  26828. // Scale / offset
  26829. currentEffect.setVector2("offset", this.offset);
  26830. currentEffect.setVector2("scale", this.scale);
  26831. // VBOs
  26832. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  26833. // Draw order
  26834. if (!this._alphaTestEffect) {
  26835. engine.setAlphaMode(this.alphaBlendingMode);
  26836. engine.draw(true, 0, 6);
  26837. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  26838. }
  26839. else {
  26840. engine.draw(true, 0, 6);
  26841. }
  26842. this.onAfterRenderObservable.notifyObservers(this);
  26843. };
  26844. Layer.prototype.dispose = function () {
  26845. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  26846. if (vertexBuffer) {
  26847. vertexBuffer.dispose();
  26848. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  26849. }
  26850. if (this._indexBuffer) {
  26851. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  26852. this._indexBuffer = null;
  26853. }
  26854. if (this.texture) {
  26855. this.texture.dispose();
  26856. this.texture = null;
  26857. }
  26858. // Remove from scene
  26859. var index = this._scene.layers.indexOf(this);
  26860. this._scene.layers.splice(index, 1);
  26861. // Callback
  26862. this.onDisposeObservable.notifyObservers(this);
  26863. this.onDisposeObservable.clear();
  26864. this.onAfterRenderObservable.clear();
  26865. this.onBeforeRenderObservable.clear();
  26866. };
  26867. return Layer;
  26868. })();
  26869. BABYLON.Layer = Layer;
  26870. })(BABYLON || (BABYLON = {}));
  26871. var BABYLON;
  26872. (function (BABYLON) {
  26873. var Particle = (function () {
  26874. function Particle() {
  26875. this.position = BABYLON.Vector3.Zero();
  26876. this.direction = BABYLON.Vector3.Zero();
  26877. this.color = new BABYLON.Color4(0, 0, 0, 0);
  26878. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  26879. this.lifeTime = 1.0;
  26880. this.age = 0;
  26881. this.size = 0;
  26882. this.angle = 0;
  26883. this.angularSpeed = 0;
  26884. }
  26885. Particle.prototype.copyTo = function (other) {
  26886. other.position.copyFrom(this.position);
  26887. other.direction.copyFrom(this.direction);
  26888. other.color.copyFrom(this.color);
  26889. other.colorStep.copyFrom(this.colorStep);
  26890. other.lifeTime = this.lifeTime;
  26891. other.age = this.age;
  26892. other.size = this.size;
  26893. other.angle = this.angle;
  26894. other.angularSpeed = this.angularSpeed;
  26895. };
  26896. return Particle;
  26897. })();
  26898. BABYLON.Particle = Particle;
  26899. })(BABYLON || (BABYLON = {}));
  26900. var BABYLON;
  26901. (function (BABYLON) {
  26902. var randomNumber = function (min, max) {
  26903. if (min === max) {
  26904. return (min);
  26905. }
  26906. var random = Math.random();
  26907. return ((random * (max - min)) + min);
  26908. };
  26909. var ParticleSystem = (function () {
  26910. function ParticleSystem(name, capacity, scene, customEffect) {
  26911. var _this = this;
  26912. this.name = name;
  26913. // Members
  26914. this.animations = [];
  26915. this.renderingGroupId = 0;
  26916. this.emitter = null;
  26917. this.emitRate = 10;
  26918. this.manualEmitCount = -1;
  26919. this.updateSpeed = 0.01;
  26920. this.targetStopDuration = 0;
  26921. this.disposeOnStop = false;
  26922. this.minEmitPower = 1;
  26923. this.maxEmitPower = 1;
  26924. this.minLifeTime = 1;
  26925. this.maxLifeTime = 1;
  26926. this.minSize = 1;
  26927. this.maxSize = 1;
  26928. this.minAngularSpeed = 0;
  26929. this.maxAngularSpeed = 0;
  26930. this.layerMask = 0x0FFFFFFF;
  26931. /**
  26932. * An event triggered when the system is disposed.
  26933. * @type {BABYLON.Observable}
  26934. */
  26935. this.onDisposeObservable = new BABYLON.Observable();
  26936. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  26937. this.forceDepthWrite = false;
  26938. this.gravity = BABYLON.Vector3.Zero();
  26939. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  26940. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  26941. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  26942. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  26943. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  26944. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  26945. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  26946. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  26947. this.particles = new Array();
  26948. this._stockParticles = new Array();
  26949. this._newPartsExcess = 0;
  26950. this._vertexBuffers = {};
  26951. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  26952. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  26953. this._scaledDirection = BABYLON.Vector3.Zero();
  26954. this._scaledGravity = BABYLON.Vector3.Zero();
  26955. this._currentRenderId = -1;
  26956. this._started = false;
  26957. this._stopped = false;
  26958. this._actualFrame = 0;
  26959. this.id = name;
  26960. this._capacity = capacity;
  26961. this._scene = scene;
  26962. this._customEffect = customEffect;
  26963. scene.particleSystems.push(this);
  26964. var indices = [];
  26965. var index = 0;
  26966. for (var count = 0; count < capacity; count++) {
  26967. indices.push(index);
  26968. indices.push(index + 1);
  26969. indices.push(index + 2);
  26970. indices.push(index);
  26971. indices.push(index + 2);
  26972. indices.push(index + 3);
  26973. index += 4;
  26974. }
  26975. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  26976. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  26977. this._vertexData = new Float32Array(capacity * 11 * 4);
  26978. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 11);
  26979. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  26980. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  26981. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  26982. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  26983. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  26984. this._vertexBuffers["options"] = options;
  26985. // Default behaviors
  26986. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  26987. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  26988. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  26989. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  26990. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  26991. };
  26992. this.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  26993. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  26994. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  26995. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  26996. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  26997. };
  26998. this.updateFunction = function (particles) {
  26999. for (var index = 0; index < particles.length; index++) {
  27000. var particle = particles[index];
  27001. particle.age += _this._scaledUpdateSpeed;
  27002. if (particle.age >= particle.lifeTime) {
  27003. _this.recycleParticle(particle);
  27004. index--;
  27005. continue;
  27006. }
  27007. else {
  27008. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  27009. particle.color.addInPlace(_this._scaledColorStep);
  27010. if (particle.color.a < 0)
  27011. particle.color.a = 0;
  27012. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  27013. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  27014. particle.position.addInPlace(_this._scaledDirection);
  27015. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  27016. particle.direction.addInPlace(_this._scaledGravity);
  27017. }
  27018. }
  27019. };
  27020. }
  27021. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  27022. set: function (callback) {
  27023. if (this._onDisposeObserver) {
  27024. this.onDisposeObservable.remove(this._onDisposeObserver);
  27025. }
  27026. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  27027. },
  27028. enumerable: true,
  27029. configurable: true
  27030. });
  27031. ParticleSystem.prototype.recycleParticle = function (particle) {
  27032. var lastParticle = this.particles.pop();
  27033. if (lastParticle !== particle) {
  27034. lastParticle.copyTo(particle);
  27035. this._stockParticles.push(lastParticle);
  27036. }
  27037. };
  27038. ParticleSystem.prototype.getCapacity = function () {
  27039. return this._capacity;
  27040. };
  27041. ParticleSystem.prototype.isAlive = function () {
  27042. return this._alive;
  27043. };
  27044. ParticleSystem.prototype.isStarted = function () {
  27045. return this._started;
  27046. };
  27047. ParticleSystem.prototype.start = function () {
  27048. this._started = true;
  27049. this._stopped = false;
  27050. this._actualFrame = 0;
  27051. };
  27052. ParticleSystem.prototype.stop = function () {
  27053. this._stopped = true;
  27054. };
  27055. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  27056. var offset = index * 11;
  27057. this._vertexData[offset] = particle.position.x;
  27058. this._vertexData[offset + 1] = particle.position.y;
  27059. this._vertexData[offset + 2] = particle.position.z;
  27060. this._vertexData[offset + 3] = particle.color.r;
  27061. this._vertexData[offset + 4] = particle.color.g;
  27062. this._vertexData[offset + 5] = particle.color.b;
  27063. this._vertexData[offset + 6] = particle.color.a;
  27064. this._vertexData[offset + 7] = particle.angle;
  27065. this._vertexData[offset + 8] = particle.size;
  27066. this._vertexData[offset + 9] = offsetX;
  27067. this._vertexData[offset + 10] = offsetY;
  27068. };
  27069. ParticleSystem.prototype._update = function (newParticles) {
  27070. // Update current
  27071. this._alive = this.particles.length > 0;
  27072. this.updateFunction(this.particles);
  27073. // Add new ones
  27074. var worldMatrix;
  27075. if (this.emitter.position) {
  27076. worldMatrix = this.emitter.getWorldMatrix();
  27077. }
  27078. else {
  27079. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  27080. }
  27081. var particle;
  27082. for (var index = 0; index < newParticles; index++) {
  27083. if (this.particles.length === this._capacity) {
  27084. break;
  27085. }
  27086. if (this._stockParticles.length !== 0) {
  27087. particle = this._stockParticles.pop();
  27088. particle.age = 0;
  27089. }
  27090. else {
  27091. particle = new BABYLON.Particle();
  27092. }
  27093. this.particles.push(particle);
  27094. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  27095. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  27096. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  27097. particle.size = randomNumber(this.minSize, this.maxSize);
  27098. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  27099. this.startPositionFunction(worldMatrix, particle.position, particle);
  27100. var step = randomNumber(0, 1.0);
  27101. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  27102. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  27103. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  27104. }
  27105. };
  27106. ParticleSystem.prototype._getEffect = function () {
  27107. if (this._customEffect) {
  27108. return this._customEffect;
  27109. }
  27110. ;
  27111. var defines = [];
  27112. if (this._scene.clipPlane) {
  27113. defines.push("#define CLIPPLANE");
  27114. }
  27115. // Effect
  27116. var join = defines.join("\n");
  27117. if (this._cachedDefines !== join) {
  27118. this._cachedDefines = join;
  27119. this._effect = this._scene.getEngine().createEffect("particles", [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  27120. }
  27121. return this._effect;
  27122. };
  27123. ParticleSystem.prototype.animate = function () {
  27124. if (!this._started)
  27125. return;
  27126. var effect = this._getEffect();
  27127. // Check
  27128. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  27129. return;
  27130. if (this._currentRenderId === this._scene.getRenderId()) {
  27131. return;
  27132. }
  27133. this._currentRenderId = this._scene.getRenderId();
  27134. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  27135. // determine the number of particles we need to create
  27136. var newParticles;
  27137. if (this.manualEmitCount > -1) {
  27138. newParticles = this.manualEmitCount;
  27139. this._newPartsExcess = 0;
  27140. this.manualEmitCount = 0;
  27141. }
  27142. else {
  27143. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  27144. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  27145. }
  27146. if (this._newPartsExcess > 1.0) {
  27147. newParticles += this._newPartsExcess >> 0;
  27148. this._newPartsExcess -= this._newPartsExcess >> 0;
  27149. }
  27150. this._alive = false;
  27151. if (!this._stopped) {
  27152. this._actualFrame += this._scaledUpdateSpeed;
  27153. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  27154. this.stop();
  27155. }
  27156. else {
  27157. newParticles = 0;
  27158. }
  27159. this._update(newParticles);
  27160. // Stopped?
  27161. if (this._stopped) {
  27162. if (!this._alive) {
  27163. this._started = false;
  27164. if (this.disposeOnStop) {
  27165. this._scene._toBeDisposed.push(this);
  27166. }
  27167. }
  27168. }
  27169. // Update VBO
  27170. var offset = 0;
  27171. for (var index = 0; index < this.particles.length; index++) {
  27172. var particle = this.particles[index];
  27173. this._appendParticleVertex(offset++, particle, 0, 0);
  27174. this._appendParticleVertex(offset++, particle, 1, 0);
  27175. this._appendParticleVertex(offset++, particle, 1, 1);
  27176. this._appendParticleVertex(offset++, particle, 0, 1);
  27177. }
  27178. this._vertexBuffer.update(this._vertexData);
  27179. };
  27180. ParticleSystem.prototype.render = function () {
  27181. var effect = this._getEffect();
  27182. // Check
  27183. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  27184. return 0;
  27185. var engine = this._scene.getEngine();
  27186. // Render
  27187. engine.enableEffect(effect);
  27188. engine.setState(false);
  27189. var viewMatrix = this._scene.getViewMatrix();
  27190. effect.setTexture("diffuseSampler", this.particleTexture);
  27191. effect.setMatrix("view", viewMatrix);
  27192. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  27193. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  27194. if (this._scene.clipPlane) {
  27195. var clipPlane = this._scene.clipPlane;
  27196. var invView = viewMatrix.clone();
  27197. invView.invert();
  27198. effect.setMatrix("invView", invView);
  27199. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  27200. }
  27201. // VBOs
  27202. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  27203. // Draw order
  27204. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  27205. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  27206. }
  27207. else {
  27208. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  27209. }
  27210. if (this.forceDepthWrite) {
  27211. engine.setDepthWrite(true);
  27212. }
  27213. engine.draw(true, 0, this.particles.length * 6);
  27214. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  27215. return this.particles.length;
  27216. };
  27217. ParticleSystem.prototype.dispose = function () {
  27218. if (this._vertexBuffer) {
  27219. this._vertexBuffer.dispose();
  27220. this._vertexBuffer = null;
  27221. }
  27222. if (this._indexBuffer) {
  27223. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  27224. this._indexBuffer = null;
  27225. }
  27226. if (this.particleTexture) {
  27227. this.particleTexture.dispose();
  27228. this.particleTexture = null;
  27229. }
  27230. // Remove from scene
  27231. var index = this._scene.particleSystems.indexOf(this);
  27232. this._scene.particleSystems.splice(index, 1);
  27233. // Callback
  27234. this.onDisposeObservable.notifyObservers(this);
  27235. this.onDisposeObservable.clear();
  27236. };
  27237. // Clone
  27238. ParticleSystem.prototype.clone = function (name, newEmitter) {
  27239. var result = new ParticleSystem(name, this._capacity, this._scene);
  27240. BABYLON.Tools.DeepCopy(this, result, ["particles"]);
  27241. if (newEmitter === undefined) {
  27242. newEmitter = this.emitter;
  27243. }
  27244. result.emitter = newEmitter;
  27245. if (this.particleTexture) {
  27246. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  27247. }
  27248. result.start();
  27249. return result;
  27250. };
  27251. ParticleSystem.prototype.serialize = function () {
  27252. var serializationObject = {};
  27253. serializationObject.name = this.name;
  27254. serializationObject.id = this.id;
  27255. // Emitter
  27256. if (this.emitter.position) {
  27257. serializationObject.emitterId = this.emitter.id;
  27258. }
  27259. else {
  27260. serializationObject.emitter = this.emitter.asArray();
  27261. }
  27262. serializationObject.capacity = this.getCapacity();
  27263. if (this.particleTexture) {
  27264. serializationObject.textureName = this.particleTexture.name;
  27265. }
  27266. // Animations
  27267. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  27268. // Particle system
  27269. serializationObject.minAngularSpeed = this.minAngularSpeed;
  27270. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  27271. serializationObject.minSize = this.minSize;
  27272. serializationObject.maxSize = this.maxSize;
  27273. serializationObject.minEmitPower = this.minEmitPower;
  27274. serializationObject.maxEmitPower = this.maxEmitPower;
  27275. serializationObject.minLifeTime = this.minLifeTime;
  27276. serializationObject.maxLifeTime = this.maxLifeTime;
  27277. serializationObject.emitRate = this.emitRate;
  27278. serializationObject.minEmitBox = this.minEmitBox.asArray();
  27279. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  27280. serializationObject.gravity = this.gravity.asArray();
  27281. serializationObject.direction1 = this.direction1.asArray();
  27282. serializationObject.direction2 = this.direction2.asArray();
  27283. serializationObject.color1 = this.color1.asArray();
  27284. serializationObject.color2 = this.color2.asArray();
  27285. serializationObject.colorDead = this.colorDead.asArray();
  27286. serializationObject.updateSpeed = this.updateSpeed;
  27287. serializationObject.targetStopDuration = this.targetStopDuration;
  27288. serializationObject.textureMask = this.textureMask.asArray();
  27289. serializationObject.blendMode = this.blendMode;
  27290. return serializationObject;
  27291. };
  27292. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  27293. var name = parsedParticleSystem.name;
  27294. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene);
  27295. if (parsedParticleSystem.id) {
  27296. particleSystem.id = parsedParticleSystem.id;
  27297. }
  27298. // Texture
  27299. if (parsedParticleSystem.textureName) {
  27300. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  27301. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  27302. }
  27303. // Emitter
  27304. if (parsedParticleSystem.emitterId) {
  27305. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  27306. }
  27307. else {
  27308. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  27309. }
  27310. // Animations
  27311. if (parsedParticleSystem.animations) {
  27312. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  27313. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  27314. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  27315. }
  27316. }
  27317. if (parsedParticleSystem.autoAnimate) {
  27318. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  27319. }
  27320. // Particle system
  27321. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  27322. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  27323. particleSystem.minSize = parsedParticleSystem.minSize;
  27324. particleSystem.maxSize = parsedParticleSystem.maxSize;
  27325. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  27326. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  27327. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  27328. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  27329. particleSystem.emitRate = parsedParticleSystem.emitRate;
  27330. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  27331. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  27332. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  27333. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  27334. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  27335. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  27336. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  27337. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  27338. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  27339. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  27340. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  27341. particleSystem.blendMode = parsedParticleSystem.blendMode;
  27342. if (!parsedParticleSystem.preventAutoStart) {
  27343. particleSystem.start();
  27344. }
  27345. return particleSystem;
  27346. };
  27347. // Statics
  27348. ParticleSystem.BLENDMODE_ONEONE = 0;
  27349. ParticleSystem.BLENDMODE_STANDARD = 1;
  27350. return ParticleSystem;
  27351. })();
  27352. BABYLON.ParticleSystem = ParticleSystem;
  27353. })(BABYLON || (BABYLON = {}));
  27354. var BABYLON;
  27355. (function (BABYLON) {
  27356. var AnimationRange = (function () {
  27357. function AnimationRange(name, from, to) {
  27358. this.name = name;
  27359. this.from = from;
  27360. this.to = to;
  27361. }
  27362. AnimationRange.prototype.clone = function () {
  27363. return new AnimationRange(this.name, this.from, this.to);
  27364. };
  27365. return AnimationRange;
  27366. })();
  27367. BABYLON.AnimationRange = AnimationRange;
  27368. /**
  27369. * Composed of a frame, and an action function
  27370. */
  27371. var AnimationEvent = (function () {
  27372. function AnimationEvent(frame, action, onlyOnce) {
  27373. this.frame = frame;
  27374. this.action = action;
  27375. this.onlyOnce = onlyOnce;
  27376. this.isDone = false;
  27377. }
  27378. return AnimationEvent;
  27379. })();
  27380. BABYLON.AnimationEvent = AnimationEvent;
  27381. var PathCursor = (function () {
  27382. function PathCursor(path) {
  27383. this.path = path;
  27384. this._onchange = new Array();
  27385. this.value = 0;
  27386. this.animations = new Array();
  27387. }
  27388. PathCursor.prototype.getPoint = function () {
  27389. var point = this.path.getPointAtLengthPosition(this.value);
  27390. return new BABYLON.Vector3(point.x, 0, point.y);
  27391. };
  27392. PathCursor.prototype.moveAhead = function (step) {
  27393. if (step === void 0) { step = 0.002; }
  27394. this.move(step);
  27395. return this;
  27396. };
  27397. PathCursor.prototype.moveBack = function (step) {
  27398. if (step === void 0) { step = 0.002; }
  27399. this.move(-step);
  27400. return this;
  27401. };
  27402. PathCursor.prototype.move = function (step) {
  27403. if (Math.abs(step) > 1) {
  27404. throw "step size should be less than 1.";
  27405. }
  27406. this.value += step;
  27407. this.ensureLimits();
  27408. this.raiseOnChange();
  27409. return this;
  27410. };
  27411. PathCursor.prototype.ensureLimits = function () {
  27412. while (this.value > 1) {
  27413. this.value -= 1;
  27414. }
  27415. while (this.value < 0) {
  27416. this.value += 1;
  27417. }
  27418. return this;
  27419. };
  27420. // used by animation engine
  27421. PathCursor.prototype.markAsDirty = function (propertyName) {
  27422. this.ensureLimits();
  27423. this.raiseOnChange();
  27424. return this;
  27425. };
  27426. PathCursor.prototype.raiseOnChange = function () {
  27427. var _this = this;
  27428. this._onchange.forEach(function (f) { return f(_this); });
  27429. return this;
  27430. };
  27431. PathCursor.prototype.onchange = function (f) {
  27432. this._onchange.push(f);
  27433. return this;
  27434. };
  27435. return PathCursor;
  27436. })();
  27437. BABYLON.PathCursor = PathCursor;
  27438. var Animation = (function () {
  27439. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  27440. this.name = name;
  27441. this.targetProperty = targetProperty;
  27442. this.framePerSecond = framePerSecond;
  27443. this.dataType = dataType;
  27444. this.loopMode = loopMode;
  27445. this.enableBlending = enableBlending;
  27446. this._offsetsCache = {};
  27447. this._highLimitsCache = {};
  27448. this._stopped = false;
  27449. this._blendingFactor = 0;
  27450. // The set of event that will be linked to this animation
  27451. this._events = new Array();
  27452. this.allowMatricesInterpolation = false;
  27453. this.blendingSpeed = 0.01;
  27454. this._ranges = {};
  27455. this.targetPropertyPath = targetProperty.split(".");
  27456. this.dataType = dataType;
  27457. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  27458. }
  27459. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  27460. var dataType = undefined;
  27461. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  27462. dataType = Animation.ANIMATIONTYPE_FLOAT;
  27463. }
  27464. else if (from instanceof BABYLON.Quaternion) {
  27465. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  27466. }
  27467. else if (from instanceof BABYLON.Vector3) {
  27468. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  27469. }
  27470. else if (from instanceof BABYLON.Vector2) {
  27471. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  27472. }
  27473. else if (from instanceof BABYLON.Color3) {
  27474. dataType = Animation.ANIMATIONTYPE_COLOR3;
  27475. }
  27476. else if (from instanceof BABYLON.Size) {
  27477. dataType = Animation.ANIMATIONTYPE_SIZE;
  27478. }
  27479. if (dataType == undefined) {
  27480. return null;
  27481. }
  27482. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  27483. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  27484. animation.setKeys(keys);
  27485. if (easingFunction !== undefined) {
  27486. animation.setEasingFunction(easingFunction);
  27487. }
  27488. return animation;
  27489. };
  27490. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  27491. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  27492. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  27493. };
  27494. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  27495. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  27496. node.animations.push(animation);
  27497. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  27498. };
  27499. // Methods
  27500. /**
  27501. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  27502. */
  27503. Animation.prototype.toString = function (fullDetails) {
  27504. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  27505. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  27506. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  27507. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  27508. if (fullDetails) {
  27509. ret += ", Ranges: {";
  27510. var first = true;
  27511. for (var name in this._ranges) {
  27512. if (first) {
  27513. ret += ", ";
  27514. first = false;
  27515. }
  27516. ret += name;
  27517. }
  27518. ret += "}";
  27519. }
  27520. return ret;
  27521. };
  27522. /**
  27523. * Add an event to this animation.
  27524. */
  27525. Animation.prototype.addEvent = function (event) {
  27526. this._events.push(event);
  27527. };
  27528. /**
  27529. * Remove all events found at the given frame
  27530. * @param frame
  27531. */
  27532. Animation.prototype.removeEvents = function (frame) {
  27533. for (var index = 0; index < this._events.length; index++) {
  27534. if (this._events[index].frame === frame) {
  27535. this._events.splice(index, 1);
  27536. index--;
  27537. }
  27538. }
  27539. };
  27540. Animation.prototype.createRange = function (name, from, to) {
  27541. // check name not already in use; could happen for bones after serialized
  27542. if (!this._ranges[name]) {
  27543. this._ranges[name] = new AnimationRange(name, from, to);
  27544. }
  27545. };
  27546. Animation.prototype.deleteRange = function (name, deleteFrames) {
  27547. if (deleteFrames === void 0) { deleteFrames = true; }
  27548. if (this._ranges[name]) {
  27549. if (deleteFrames) {
  27550. var from = this._ranges[name].from;
  27551. var to = this._ranges[name].to;
  27552. // this loop MUST go high to low for multiple splices to work
  27553. for (var key = this._keys.length - 1; key >= 0; key--) {
  27554. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  27555. this._keys.splice(key, 1);
  27556. }
  27557. }
  27558. }
  27559. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  27560. }
  27561. };
  27562. Animation.prototype.getRange = function (name) {
  27563. return this._ranges[name];
  27564. };
  27565. Animation.prototype.reset = function () {
  27566. this._offsetsCache = {};
  27567. this._highLimitsCache = {};
  27568. this.currentFrame = 0;
  27569. this._blendingFactor = 0;
  27570. this._originalBlendValue = null;
  27571. };
  27572. Animation.prototype.isStopped = function () {
  27573. return this._stopped;
  27574. };
  27575. Animation.prototype.getKeys = function () {
  27576. return this._keys;
  27577. };
  27578. Animation.prototype.getHighestFrame = function () {
  27579. var ret = 0;
  27580. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  27581. if (ret < this._keys[key].frame) {
  27582. ret = this._keys[key].frame;
  27583. }
  27584. }
  27585. return ret;
  27586. };
  27587. Animation.prototype.getEasingFunction = function () {
  27588. return this._easingFunction;
  27589. };
  27590. Animation.prototype.setEasingFunction = function (easingFunction) {
  27591. this._easingFunction = easingFunction;
  27592. };
  27593. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  27594. return startValue + (endValue - startValue) * gradient;
  27595. };
  27596. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  27597. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  27598. };
  27599. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  27600. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  27601. };
  27602. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  27603. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  27604. };
  27605. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  27606. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  27607. };
  27608. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  27609. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  27610. };
  27611. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  27612. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  27613. };
  27614. Animation.prototype.clone = function () {
  27615. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  27616. if (this._keys) {
  27617. clone.setKeys(this._keys);
  27618. }
  27619. if (this._ranges) {
  27620. clone._ranges = {};
  27621. for (var name in this._ranges) {
  27622. clone._ranges[name] = this._ranges[name].clone();
  27623. }
  27624. }
  27625. return clone;
  27626. };
  27627. Animation.prototype.setKeys = function (values) {
  27628. this._keys = values.slice(0);
  27629. this._offsetsCache = {};
  27630. this._highLimitsCache = {};
  27631. };
  27632. Animation.prototype._getKeyValue = function (value) {
  27633. if (typeof value === "function") {
  27634. return value();
  27635. }
  27636. return value;
  27637. };
  27638. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  27639. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  27640. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  27641. }
  27642. this.currentFrame = currentFrame;
  27643. // Try to get a hash to find the right key
  27644. 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));
  27645. if (this._keys[startKey].frame >= currentFrame) {
  27646. while (startKey - 1 >= 0 && this._keys[startKey].frame >= currentFrame) {
  27647. startKey--;
  27648. }
  27649. }
  27650. for (var key = startKey; key < this._keys.length; key++) {
  27651. if (this._keys[key + 1].frame >= currentFrame) {
  27652. var startValue = this._getKeyValue(this._keys[key].value);
  27653. var endValue = this._getKeyValue(this._keys[key + 1].value);
  27654. // gradient : percent of currentFrame between the frame inf and the frame sup
  27655. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  27656. // check for easingFunction and correction of gradient
  27657. if (this._easingFunction != null) {
  27658. gradient = this._easingFunction.ease(gradient);
  27659. }
  27660. switch (this.dataType) {
  27661. // Float
  27662. case Animation.ANIMATIONTYPE_FLOAT:
  27663. switch (loopMode) {
  27664. case Animation.ANIMATIONLOOPMODE_CYCLE:
  27665. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  27666. return this.floatInterpolateFunction(startValue, endValue, gradient);
  27667. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  27668. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  27669. }
  27670. break;
  27671. // Quaternion
  27672. case Animation.ANIMATIONTYPE_QUATERNION:
  27673. var quaternion = null;
  27674. switch (loopMode) {
  27675. case Animation.ANIMATIONLOOPMODE_CYCLE:
  27676. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  27677. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  27678. break;
  27679. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  27680. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  27681. break;
  27682. }
  27683. return quaternion;
  27684. // Vector3
  27685. case Animation.ANIMATIONTYPE_VECTOR3:
  27686. switch (loopMode) {
  27687. case Animation.ANIMATIONLOOPMODE_CYCLE:
  27688. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  27689. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  27690. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  27691. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  27692. }
  27693. // Vector2
  27694. case Animation.ANIMATIONTYPE_VECTOR2:
  27695. switch (loopMode) {
  27696. case Animation.ANIMATIONLOOPMODE_CYCLE:
  27697. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  27698. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  27699. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  27700. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  27701. }
  27702. // Size
  27703. case Animation.ANIMATIONTYPE_SIZE:
  27704. switch (loopMode) {
  27705. case Animation.ANIMATIONLOOPMODE_CYCLE:
  27706. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  27707. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  27708. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  27709. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  27710. }
  27711. // Color3
  27712. case Animation.ANIMATIONTYPE_COLOR3:
  27713. switch (loopMode) {
  27714. case Animation.ANIMATIONLOOPMODE_CYCLE:
  27715. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  27716. return this.color3InterpolateFunction(startValue, endValue, gradient);
  27717. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  27718. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  27719. }
  27720. // Matrix
  27721. case Animation.ANIMATIONTYPE_MATRIX:
  27722. switch (loopMode) {
  27723. case Animation.ANIMATIONLOOPMODE_CYCLE:
  27724. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  27725. if (this.allowMatricesInterpolation) {
  27726. return this.matrixInterpolateFunction(startValue, endValue, gradient);
  27727. }
  27728. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  27729. return startValue;
  27730. }
  27731. default:
  27732. break;
  27733. }
  27734. break;
  27735. }
  27736. }
  27737. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  27738. };
  27739. Animation.prototype.setValue = function (currentValue, blend) {
  27740. if (blend === void 0) { blend = false; }
  27741. // Set value
  27742. var path;
  27743. var destination;
  27744. if (this.targetPropertyPath.length > 1) {
  27745. var property = this._target[this.targetPropertyPath[0]];
  27746. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  27747. property = property[this.targetPropertyPath[index]];
  27748. }
  27749. path = this.targetPropertyPath[this.targetPropertyPath.length - 1];
  27750. destination = property;
  27751. }
  27752. else {
  27753. path = this.targetPropertyPath[0];
  27754. destination = this._target;
  27755. }
  27756. // Blending
  27757. if (this.enableBlending && this._blendingFactor <= 1.0) {
  27758. if (!this._originalBlendValue) {
  27759. if (destination[path].clone) {
  27760. this._originalBlendValue = destination[path].clone();
  27761. }
  27762. else {
  27763. this._originalBlendValue = destination[path];
  27764. }
  27765. }
  27766. if (this._originalBlendValue.prototype) {
  27767. if (this._originalBlendValue.prototype.Lerp) {
  27768. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  27769. }
  27770. else {
  27771. destination[path] = currentValue;
  27772. }
  27773. }
  27774. else if (this._originalBlendValue.m) {
  27775. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  27776. }
  27777. else {
  27778. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  27779. }
  27780. this._blendingFactor += this.blendingSpeed;
  27781. }
  27782. else {
  27783. destination[path] = currentValue;
  27784. }
  27785. if (this._target.markAsDirty) {
  27786. this._target.markAsDirty(this.targetProperty);
  27787. }
  27788. };
  27789. Animation.prototype.goToFrame = function (frame) {
  27790. if (frame < this._keys[0].frame) {
  27791. frame = this._keys[0].frame;
  27792. }
  27793. else if (frame > this._keys[this._keys.length - 1].frame) {
  27794. frame = this._keys[this._keys.length - 1].frame;
  27795. }
  27796. var currentValue = this._interpolate(frame, 0, this.loopMode);
  27797. this.setValue(currentValue);
  27798. };
  27799. Animation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  27800. if (blend === void 0) { blend = false; }
  27801. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  27802. this._stopped = true;
  27803. return false;
  27804. }
  27805. var returnValue = true;
  27806. // Adding a start key at frame 0 if missing
  27807. if (this._keys[0].frame !== 0) {
  27808. var newKey = { frame: 0, value: this._keys[0].value };
  27809. this._keys.splice(0, 0, newKey);
  27810. }
  27811. // Check limits
  27812. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  27813. from = this._keys[0].frame;
  27814. }
  27815. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  27816. to = this._keys[this._keys.length - 1].frame;
  27817. }
  27818. // Compute ratio
  27819. var range = to - from;
  27820. var offsetValue;
  27821. // ratio represents the frame delta between from and to
  27822. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  27823. var highLimitValue = 0;
  27824. if (ratio > range && !loop) {
  27825. returnValue = false;
  27826. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  27827. }
  27828. else {
  27829. // Get max value if required
  27830. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  27831. var keyOffset = to.toString() + from.toString();
  27832. if (!this._offsetsCache[keyOffset]) {
  27833. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  27834. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  27835. switch (this.dataType) {
  27836. // Float
  27837. case Animation.ANIMATIONTYPE_FLOAT:
  27838. this._offsetsCache[keyOffset] = toValue - fromValue;
  27839. break;
  27840. // Quaternion
  27841. case Animation.ANIMATIONTYPE_QUATERNION:
  27842. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  27843. break;
  27844. // Vector3
  27845. case Animation.ANIMATIONTYPE_VECTOR3:
  27846. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  27847. // Vector2
  27848. case Animation.ANIMATIONTYPE_VECTOR2:
  27849. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  27850. // Size
  27851. case Animation.ANIMATIONTYPE_SIZE:
  27852. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  27853. // Color3
  27854. case Animation.ANIMATIONTYPE_COLOR3:
  27855. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  27856. default:
  27857. break;
  27858. }
  27859. this._highLimitsCache[keyOffset] = toValue;
  27860. }
  27861. highLimitValue = this._highLimitsCache[keyOffset];
  27862. offsetValue = this._offsetsCache[keyOffset];
  27863. }
  27864. }
  27865. if (offsetValue === undefined) {
  27866. switch (this.dataType) {
  27867. // Float
  27868. case Animation.ANIMATIONTYPE_FLOAT:
  27869. offsetValue = 0;
  27870. break;
  27871. // Quaternion
  27872. case Animation.ANIMATIONTYPE_QUATERNION:
  27873. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  27874. break;
  27875. // Vector3
  27876. case Animation.ANIMATIONTYPE_VECTOR3:
  27877. offsetValue = BABYLON.Vector3.Zero();
  27878. break;
  27879. // Vector2
  27880. case Animation.ANIMATIONTYPE_VECTOR2:
  27881. offsetValue = BABYLON.Vector2.Zero();
  27882. break;
  27883. // Size
  27884. case Animation.ANIMATIONTYPE_SIZE:
  27885. offsetValue = BABYLON.Size.Zero();
  27886. break;
  27887. // Color3
  27888. case Animation.ANIMATIONTYPE_COLOR3:
  27889. offsetValue = BABYLON.Color3.Black();
  27890. }
  27891. }
  27892. // Compute value
  27893. var repeatCount = (ratio / range) >> 0;
  27894. var currentFrame = returnValue ? from + ratio % range : to;
  27895. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  27896. // Set value
  27897. this.setValue(currentValue);
  27898. // Check events
  27899. for (var index = 0; index < this._events.length; index++) {
  27900. if (currentFrame >= this._events[index].frame) {
  27901. var event = this._events[index];
  27902. if (!event.isDone) {
  27903. // If event should be done only once, remove it.
  27904. if (event.onlyOnce) {
  27905. this._events.splice(index, 1);
  27906. index--;
  27907. }
  27908. event.isDone = true;
  27909. event.action();
  27910. } // Don't do anything if the event has already be done.
  27911. }
  27912. else if (this._events[index].isDone && !this._events[index].onlyOnce) {
  27913. // reset event, the animation is looping
  27914. this._events[index].isDone = false;
  27915. }
  27916. }
  27917. if (!returnValue) {
  27918. this._stopped = true;
  27919. }
  27920. return returnValue;
  27921. };
  27922. Animation.prototype.serialize = function () {
  27923. var serializationObject = {};
  27924. serializationObject.name = this.name;
  27925. serializationObject.property = this.targetProperty;
  27926. serializationObject.framePerSecond = this.framePerSecond;
  27927. serializationObject.dataType = this.dataType;
  27928. serializationObject.loopBehavior = this.loopMode;
  27929. var dataType = this.dataType;
  27930. serializationObject.keys = [];
  27931. var keys = this.getKeys();
  27932. for (var index = 0; index < keys.length; index++) {
  27933. var animationKey = keys[index];
  27934. var key = {};
  27935. key.frame = animationKey.frame;
  27936. switch (dataType) {
  27937. case Animation.ANIMATIONTYPE_FLOAT:
  27938. key.values = [animationKey.value];
  27939. break;
  27940. case Animation.ANIMATIONTYPE_QUATERNION:
  27941. case Animation.ANIMATIONTYPE_MATRIX:
  27942. case Animation.ANIMATIONTYPE_VECTOR3:
  27943. case Animation.ANIMATIONTYPE_COLOR3:
  27944. key.values = animationKey.value.asArray();
  27945. break;
  27946. }
  27947. serializationObject.keys.push(key);
  27948. }
  27949. serializationObject.ranges = [];
  27950. for (var name in this._ranges) {
  27951. var range = {};
  27952. range.name = name;
  27953. range.from = this._ranges[name].from;
  27954. range.to = this._ranges[name].to;
  27955. serializationObject.ranges.push(range);
  27956. }
  27957. return serializationObject;
  27958. };
  27959. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  27960. get: function () {
  27961. return Animation._ANIMATIONTYPE_FLOAT;
  27962. },
  27963. enumerable: true,
  27964. configurable: true
  27965. });
  27966. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  27967. get: function () {
  27968. return Animation._ANIMATIONTYPE_VECTOR3;
  27969. },
  27970. enumerable: true,
  27971. configurable: true
  27972. });
  27973. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  27974. get: function () {
  27975. return Animation._ANIMATIONTYPE_VECTOR2;
  27976. },
  27977. enumerable: true,
  27978. configurable: true
  27979. });
  27980. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  27981. get: function () {
  27982. return Animation._ANIMATIONTYPE_SIZE;
  27983. },
  27984. enumerable: true,
  27985. configurable: true
  27986. });
  27987. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  27988. get: function () {
  27989. return Animation._ANIMATIONTYPE_QUATERNION;
  27990. },
  27991. enumerable: true,
  27992. configurable: true
  27993. });
  27994. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  27995. get: function () {
  27996. return Animation._ANIMATIONTYPE_MATRIX;
  27997. },
  27998. enumerable: true,
  27999. configurable: true
  28000. });
  28001. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  28002. get: function () {
  28003. return Animation._ANIMATIONTYPE_COLOR3;
  28004. },
  28005. enumerable: true,
  28006. configurable: true
  28007. });
  28008. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  28009. get: function () {
  28010. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  28011. },
  28012. enumerable: true,
  28013. configurable: true
  28014. });
  28015. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  28016. get: function () {
  28017. return Animation._ANIMATIONLOOPMODE_CYCLE;
  28018. },
  28019. enumerable: true,
  28020. configurable: true
  28021. });
  28022. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  28023. get: function () {
  28024. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  28025. },
  28026. enumerable: true,
  28027. configurable: true
  28028. });
  28029. Animation.Parse = function (parsedAnimation) {
  28030. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  28031. var dataType = parsedAnimation.dataType;
  28032. var keys = [];
  28033. var data;
  28034. var index;
  28035. for (index = 0; index < parsedAnimation.keys.length; index++) {
  28036. var key = parsedAnimation.keys[index];
  28037. switch (dataType) {
  28038. case Animation.ANIMATIONTYPE_FLOAT:
  28039. data = key.values[0];
  28040. break;
  28041. case Animation.ANIMATIONTYPE_QUATERNION:
  28042. data = BABYLON.Quaternion.FromArray(key.values);
  28043. break;
  28044. case Animation.ANIMATIONTYPE_MATRIX:
  28045. data = BABYLON.Matrix.FromArray(key.values);
  28046. break;
  28047. case Animation.ANIMATIONTYPE_COLOR3:
  28048. data = BABYLON.Color3.FromArray(key.values);
  28049. break;
  28050. case Animation.ANIMATIONTYPE_VECTOR3:
  28051. default:
  28052. data = BABYLON.Vector3.FromArray(key.values);
  28053. break;
  28054. }
  28055. keys.push({
  28056. frame: key.frame,
  28057. value: data
  28058. });
  28059. }
  28060. animation.setKeys(keys);
  28061. if (parsedAnimation.ranges) {
  28062. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  28063. data = parsedAnimation.ranges[index];
  28064. animation.createRange(data.name, data.from, data.to);
  28065. }
  28066. }
  28067. return animation;
  28068. };
  28069. Animation.AppendSerializedAnimations = function (source, destination) {
  28070. if (source.animations) {
  28071. destination.animations = [];
  28072. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  28073. var animation = source.animations[animationIndex];
  28074. destination.animations.push(animation.serialize());
  28075. }
  28076. }
  28077. };
  28078. // Statics
  28079. Animation._ANIMATIONTYPE_FLOAT = 0;
  28080. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  28081. Animation._ANIMATIONTYPE_QUATERNION = 2;
  28082. Animation._ANIMATIONTYPE_MATRIX = 3;
  28083. Animation._ANIMATIONTYPE_COLOR3 = 4;
  28084. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  28085. Animation._ANIMATIONTYPE_SIZE = 6;
  28086. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  28087. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  28088. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  28089. return Animation;
  28090. })();
  28091. BABYLON.Animation = Animation;
  28092. })(BABYLON || (BABYLON = {}));
  28093. var BABYLON;
  28094. (function (BABYLON) {
  28095. var Animatable = (function () {
  28096. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  28097. if (fromFrame === void 0) { fromFrame = 0; }
  28098. if (toFrame === void 0) { toFrame = 100; }
  28099. if (loopAnimation === void 0) { loopAnimation = false; }
  28100. if (speedRatio === void 0) { speedRatio = 1.0; }
  28101. this.target = target;
  28102. this.fromFrame = fromFrame;
  28103. this.toFrame = toFrame;
  28104. this.loopAnimation = loopAnimation;
  28105. this.speedRatio = speedRatio;
  28106. this.onAnimationEnd = onAnimationEnd;
  28107. this._animations = new Array();
  28108. this._paused = false;
  28109. this.animationStarted = false;
  28110. if (animations) {
  28111. this.appendAnimations(target, animations);
  28112. }
  28113. this._scene = scene;
  28114. scene._activeAnimatables.push(this);
  28115. }
  28116. // Methods
  28117. Animatable.prototype.getAnimations = function () {
  28118. return this._animations;
  28119. };
  28120. Animatable.prototype.appendAnimations = function (target, animations) {
  28121. for (var index = 0; index < animations.length; index++) {
  28122. var animation = animations[index];
  28123. animation._target = target;
  28124. this._animations.push(animation);
  28125. }
  28126. };
  28127. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  28128. var animations = this._animations;
  28129. for (var index = 0; index < animations.length; index++) {
  28130. if (animations[index].targetProperty === property) {
  28131. return animations[index];
  28132. }
  28133. }
  28134. return null;
  28135. };
  28136. Animatable.prototype.reset = function () {
  28137. var animations = this._animations;
  28138. for (var index = 0; index < animations.length; index++) {
  28139. animations[index].reset();
  28140. }
  28141. this._localDelayOffset = null;
  28142. this._pausedDelay = null;
  28143. };
  28144. Animatable.prototype.enableBlending = function (blendingSpeed) {
  28145. var animations = this._animations;
  28146. for (var index = 0; index < animations.length; index++) {
  28147. animations[index].enableBlending = true;
  28148. animations[index].blendingSpeed = blendingSpeed;
  28149. }
  28150. };
  28151. Animatable.prototype.disableBlending = function () {
  28152. var animations = this._animations;
  28153. for (var index = 0; index < animations.length; index++) {
  28154. animations[index].enableBlending = false;
  28155. }
  28156. };
  28157. Animatable.prototype.goToFrame = function (frame) {
  28158. var animations = this._animations;
  28159. for (var index = 0; index < animations.length; index++) {
  28160. animations[index].goToFrame(frame);
  28161. }
  28162. };
  28163. Animatable.prototype.pause = function () {
  28164. if (this._paused) {
  28165. return;
  28166. }
  28167. this._paused = true;
  28168. };
  28169. Animatable.prototype.restart = function () {
  28170. this._paused = false;
  28171. };
  28172. Animatable.prototype.stop = function () {
  28173. var index = this._scene._activeAnimatables.indexOf(this);
  28174. if (index > -1) {
  28175. this._scene._activeAnimatables.splice(index, 1);
  28176. var animations = this._animations;
  28177. for (var index = 0; index < animations.length; index++) {
  28178. animations[index].reset();
  28179. }
  28180. if (this.onAnimationEnd) {
  28181. this.onAnimationEnd();
  28182. }
  28183. }
  28184. };
  28185. Animatable.prototype._animate = function (delay) {
  28186. if (this._paused) {
  28187. this.animationStarted = false;
  28188. if (!this._pausedDelay) {
  28189. this._pausedDelay = delay;
  28190. }
  28191. return true;
  28192. }
  28193. if (!this._localDelayOffset) {
  28194. this._localDelayOffset = delay;
  28195. }
  28196. else if (this._pausedDelay) {
  28197. this._localDelayOffset += delay - this._pausedDelay;
  28198. this._pausedDelay = null;
  28199. }
  28200. // Animating
  28201. var running = false;
  28202. var animations = this._animations;
  28203. var index;
  28204. for (index = 0; index < animations.length; index++) {
  28205. var animation = animations[index];
  28206. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  28207. running = running || isRunning;
  28208. }
  28209. this.animationStarted = running;
  28210. if (!running) {
  28211. // Remove from active animatables
  28212. index = this._scene._activeAnimatables.indexOf(this);
  28213. this._scene._activeAnimatables.splice(index, 1);
  28214. }
  28215. if (!running && this.onAnimationEnd) {
  28216. this.onAnimationEnd();
  28217. this.onAnimationEnd = null;
  28218. }
  28219. return running;
  28220. };
  28221. return Animatable;
  28222. })();
  28223. BABYLON.Animatable = Animatable;
  28224. })(BABYLON || (BABYLON = {}));
  28225. var BABYLON;
  28226. (function (BABYLON) {
  28227. var EasingFunction = (function () {
  28228. function EasingFunction() {
  28229. // Properties
  28230. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  28231. }
  28232. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  28233. get: function () {
  28234. return EasingFunction._EASINGMODE_EASEIN;
  28235. },
  28236. enumerable: true,
  28237. configurable: true
  28238. });
  28239. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  28240. get: function () {
  28241. return EasingFunction._EASINGMODE_EASEOUT;
  28242. },
  28243. enumerable: true,
  28244. configurable: true
  28245. });
  28246. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  28247. get: function () {
  28248. return EasingFunction._EASINGMODE_EASEINOUT;
  28249. },
  28250. enumerable: true,
  28251. configurable: true
  28252. });
  28253. EasingFunction.prototype.setEasingMode = function (easingMode) {
  28254. var n = Math.min(Math.max(easingMode, 0), 2);
  28255. this._easingMode = n;
  28256. };
  28257. EasingFunction.prototype.getEasingMode = function () {
  28258. return this._easingMode;
  28259. };
  28260. EasingFunction.prototype.easeInCore = function (gradient) {
  28261. throw new Error('You must implement this method');
  28262. };
  28263. EasingFunction.prototype.ease = function (gradient) {
  28264. switch (this._easingMode) {
  28265. case EasingFunction.EASINGMODE_EASEIN:
  28266. return this.easeInCore(gradient);
  28267. case EasingFunction.EASINGMODE_EASEOUT:
  28268. return (1 - this.easeInCore(1 - gradient));
  28269. }
  28270. if (gradient >= 0.5) {
  28271. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  28272. }
  28273. return (this.easeInCore(gradient * 2) * 0.5);
  28274. };
  28275. //Statics
  28276. EasingFunction._EASINGMODE_EASEIN = 0;
  28277. EasingFunction._EASINGMODE_EASEOUT = 1;
  28278. EasingFunction._EASINGMODE_EASEINOUT = 2;
  28279. return EasingFunction;
  28280. })();
  28281. BABYLON.EasingFunction = EasingFunction;
  28282. var CircleEase = (function (_super) {
  28283. __extends(CircleEase, _super);
  28284. function CircleEase() {
  28285. _super.apply(this, arguments);
  28286. }
  28287. CircleEase.prototype.easeInCore = function (gradient) {
  28288. gradient = Math.max(0, Math.min(1, gradient));
  28289. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  28290. };
  28291. return CircleEase;
  28292. })(EasingFunction);
  28293. BABYLON.CircleEase = CircleEase;
  28294. var BackEase = (function (_super) {
  28295. __extends(BackEase, _super);
  28296. function BackEase(amplitude) {
  28297. if (amplitude === void 0) { amplitude = 1; }
  28298. _super.call(this);
  28299. this.amplitude = amplitude;
  28300. }
  28301. BackEase.prototype.easeInCore = function (gradient) {
  28302. var num = Math.max(0, this.amplitude);
  28303. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  28304. };
  28305. return BackEase;
  28306. })(EasingFunction);
  28307. BABYLON.BackEase = BackEase;
  28308. var BounceEase = (function (_super) {
  28309. __extends(BounceEase, _super);
  28310. function BounceEase(bounces, bounciness) {
  28311. if (bounces === void 0) { bounces = 3; }
  28312. if (bounciness === void 0) { bounciness = 2; }
  28313. _super.call(this);
  28314. this.bounces = bounces;
  28315. this.bounciness = bounciness;
  28316. }
  28317. BounceEase.prototype.easeInCore = function (gradient) {
  28318. var y = Math.max(0.0, this.bounces);
  28319. var bounciness = this.bounciness;
  28320. if (bounciness <= 1.0) {
  28321. bounciness = 1.001;
  28322. }
  28323. var num9 = Math.pow(bounciness, y);
  28324. var num5 = 1.0 - bounciness;
  28325. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  28326. var num15 = gradient * num4;
  28327. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  28328. var num3 = Math.floor(num65);
  28329. var num13 = num3 + 1.0;
  28330. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  28331. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  28332. var num7 = (num8 + num12) * 0.5;
  28333. var num6 = gradient - num7;
  28334. var num2 = num7 - num8;
  28335. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  28336. };
  28337. return BounceEase;
  28338. })(EasingFunction);
  28339. BABYLON.BounceEase = BounceEase;
  28340. var CubicEase = (function (_super) {
  28341. __extends(CubicEase, _super);
  28342. function CubicEase() {
  28343. _super.apply(this, arguments);
  28344. }
  28345. CubicEase.prototype.easeInCore = function (gradient) {
  28346. return (gradient * gradient * gradient);
  28347. };
  28348. return CubicEase;
  28349. })(EasingFunction);
  28350. BABYLON.CubicEase = CubicEase;
  28351. var ElasticEase = (function (_super) {
  28352. __extends(ElasticEase, _super);
  28353. function ElasticEase(oscillations, springiness) {
  28354. if (oscillations === void 0) { oscillations = 3; }
  28355. if (springiness === void 0) { springiness = 3; }
  28356. _super.call(this);
  28357. this.oscillations = oscillations;
  28358. this.springiness = springiness;
  28359. }
  28360. ElasticEase.prototype.easeInCore = function (gradient) {
  28361. var num2;
  28362. var num3 = Math.max(0.0, this.oscillations);
  28363. var num = Math.max(0.0, this.springiness);
  28364. if (num == 0) {
  28365. num2 = gradient;
  28366. }
  28367. else {
  28368. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  28369. }
  28370. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  28371. };
  28372. return ElasticEase;
  28373. })(EasingFunction);
  28374. BABYLON.ElasticEase = ElasticEase;
  28375. var ExponentialEase = (function (_super) {
  28376. __extends(ExponentialEase, _super);
  28377. function ExponentialEase(exponent) {
  28378. if (exponent === void 0) { exponent = 2; }
  28379. _super.call(this);
  28380. this.exponent = exponent;
  28381. }
  28382. ExponentialEase.prototype.easeInCore = function (gradient) {
  28383. if (this.exponent <= 0) {
  28384. return gradient;
  28385. }
  28386. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  28387. };
  28388. return ExponentialEase;
  28389. })(EasingFunction);
  28390. BABYLON.ExponentialEase = ExponentialEase;
  28391. var PowerEase = (function (_super) {
  28392. __extends(PowerEase, _super);
  28393. function PowerEase(power) {
  28394. if (power === void 0) { power = 2; }
  28395. _super.call(this);
  28396. this.power = power;
  28397. }
  28398. PowerEase.prototype.easeInCore = function (gradient) {
  28399. var y = Math.max(0.0, this.power);
  28400. return Math.pow(gradient, y);
  28401. };
  28402. return PowerEase;
  28403. })(EasingFunction);
  28404. BABYLON.PowerEase = PowerEase;
  28405. var QuadraticEase = (function (_super) {
  28406. __extends(QuadraticEase, _super);
  28407. function QuadraticEase() {
  28408. _super.apply(this, arguments);
  28409. }
  28410. QuadraticEase.prototype.easeInCore = function (gradient) {
  28411. return (gradient * gradient);
  28412. };
  28413. return QuadraticEase;
  28414. })(EasingFunction);
  28415. BABYLON.QuadraticEase = QuadraticEase;
  28416. var QuarticEase = (function (_super) {
  28417. __extends(QuarticEase, _super);
  28418. function QuarticEase() {
  28419. _super.apply(this, arguments);
  28420. }
  28421. QuarticEase.prototype.easeInCore = function (gradient) {
  28422. return (gradient * gradient * gradient * gradient);
  28423. };
  28424. return QuarticEase;
  28425. })(EasingFunction);
  28426. BABYLON.QuarticEase = QuarticEase;
  28427. var QuinticEase = (function (_super) {
  28428. __extends(QuinticEase, _super);
  28429. function QuinticEase() {
  28430. _super.apply(this, arguments);
  28431. }
  28432. QuinticEase.prototype.easeInCore = function (gradient) {
  28433. return (gradient * gradient * gradient * gradient * gradient);
  28434. };
  28435. return QuinticEase;
  28436. })(EasingFunction);
  28437. BABYLON.QuinticEase = QuinticEase;
  28438. var SineEase = (function (_super) {
  28439. __extends(SineEase, _super);
  28440. function SineEase() {
  28441. _super.apply(this, arguments);
  28442. }
  28443. SineEase.prototype.easeInCore = function (gradient) {
  28444. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  28445. };
  28446. return SineEase;
  28447. })(EasingFunction);
  28448. BABYLON.SineEase = SineEase;
  28449. var BezierCurveEase = (function (_super) {
  28450. __extends(BezierCurveEase, _super);
  28451. function BezierCurveEase(x1, y1, x2, y2) {
  28452. if (x1 === void 0) { x1 = 0; }
  28453. if (y1 === void 0) { y1 = 0; }
  28454. if (x2 === void 0) { x2 = 1; }
  28455. if (y2 === void 0) { y2 = 1; }
  28456. _super.call(this);
  28457. this.x1 = x1;
  28458. this.y1 = y1;
  28459. this.x2 = x2;
  28460. this.y2 = y2;
  28461. }
  28462. BezierCurveEase.prototype.easeInCore = function (gradient) {
  28463. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  28464. };
  28465. return BezierCurveEase;
  28466. })(EasingFunction);
  28467. BABYLON.BezierCurveEase = BezierCurveEase;
  28468. })(BABYLON || (BABYLON = {}));
  28469. var BABYLON;
  28470. (function (BABYLON) {
  28471. var Bone = (function (_super) {
  28472. __extends(Bone, _super);
  28473. function Bone(name, skeleton, parentBone, matrix, restPose) {
  28474. _super.call(this, name, skeleton.getScene());
  28475. this.name = name;
  28476. this.children = new Array();
  28477. this.animations = new Array();
  28478. this._worldTransform = new BABYLON.Matrix();
  28479. this._absoluteTransform = new BABYLON.Matrix();
  28480. this._invertedAbsoluteTransform = new BABYLON.Matrix();
  28481. this._skeleton = skeleton;
  28482. this._matrix = matrix;
  28483. this._baseMatrix = matrix;
  28484. this._restPose = restPose ? restPose : matrix.clone();
  28485. skeleton.bones.push(this);
  28486. if (parentBone) {
  28487. this._parent = parentBone;
  28488. parentBone.children.push(this);
  28489. }
  28490. else {
  28491. this._parent = null;
  28492. }
  28493. this._updateDifferenceMatrix();
  28494. }
  28495. // Members
  28496. Bone.prototype.getParent = function () {
  28497. return this._parent;
  28498. };
  28499. Bone.prototype.getLocalMatrix = function () {
  28500. return this._matrix;
  28501. };
  28502. Bone.prototype.getBaseMatrix = function () {
  28503. return this._baseMatrix;
  28504. };
  28505. Bone.prototype.getRestPose = function () {
  28506. return this._restPose;
  28507. };
  28508. Bone.prototype.returnToRest = function () {
  28509. this.updateMatrix(this._restPose.clone());
  28510. };
  28511. Bone.prototype.getWorldMatrix = function () {
  28512. return this._worldTransform;
  28513. };
  28514. Bone.prototype.getInvertedAbsoluteTransform = function () {
  28515. return this._invertedAbsoluteTransform;
  28516. };
  28517. Bone.prototype.getAbsoluteTransform = function () {
  28518. return this._absoluteTransform;
  28519. };
  28520. // Methods
  28521. Bone.prototype.updateMatrix = function (matrix) {
  28522. this._baseMatrix = matrix.clone();
  28523. this._matrix = matrix.clone();
  28524. this._skeleton._markAsDirty();
  28525. this._updateDifferenceMatrix();
  28526. };
  28527. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  28528. if (!rootMatrix) {
  28529. rootMatrix = this._baseMatrix;
  28530. }
  28531. if (this._parent) {
  28532. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  28533. }
  28534. else {
  28535. this._absoluteTransform.copyFrom(rootMatrix);
  28536. }
  28537. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  28538. for (var index = 0; index < this.children.length; index++) {
  28539. this.children[index]._updateDifferenceMatrix();
  28540. }
  28541. };
  28542. Bone.prototype.markAsDirty = function () {
  28543. this._currentRenderId++;
  28544. this._skeleton._markAsDirty();
  28545. };
  28546. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  28547. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  28548. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  28549. // all animation may be coming from a library skeleton, so may need to create animation
  28550. if (this.animations.length === 0) {
  28551. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  28552. this.animations[0].setKeys([]);
  28553. }
  28554. // get animation info / verify there is such a range from the source bone
  28555. var sourceRange = source.animations[0].getRange(rangeName);
  28556. if (!sourceRange) {
  28557. return false;
  28558. }
  28559. var from = sourceRange.from;
  28560. var to = sourceRange.to;
  28561. var sourceKeys = source.animations[0].getKeys();
  28562. // rescaling prep
  28563. var sourceBoneLength = source.length;
  28564. var sourceParent = source.getParent();
  28565. var parent = this.getParent();
  28566. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  28567. var parentRatio = parentScalingReqd ? parent.length / sourceParent.length : null;
  28568. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  28569. var destKeys = this.animations[0].getKeys();
  28570. // loop vars declaration
  28571. var orig;
  28572. var origTranslation;
  28573. var mat;
  28574. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  28575. orig = sourceKeys[key];
  28576. if (orig.frame >= from && orig.frame <= to) {
  28577. if (rescaleAsRequired) {
  28578. mat = orig.value.clone();
  28579. // scale based on parent ratio, when bone has parent
  28580. if (parentScalingReqd) {
  28581. origTranslation = mat.getTranslation();
  28582. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  28583. }
  28584. else if (dimensionsScalingReqd) {
  28585. origTranslation = mat.getTranslation();
  28586. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  28587. }
  28588. else {
  28589. mat = orig.value;
  28590. }
  28591. }
  28592. else {
  28593. mat = orig.value;
  28594. }
  28595. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  28596. }
  28597. }
  28598. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  28599. return true;
  28600. };
  28601. return Bone;
  28602. })(BABYLON.Node);
  28603. BABYLON.Bone = Bone;
  28604. })(BABYLON || (BABYLON = {}));
  28605. var BABYLON;
  28606. (function (BABYLON) {
  28607. var Skeleton = (function () {
  28608. function Skeleton(name, id, scene) {
  28609. this.name = name;
  28610. this.id = id;
  28611. this.bones = new Array();
  28612. this.needInitialSkinMatrix = false;
  28613. this._isDirty = true;
  28614. this._meshesWithPoseMatrix = new Array();
  28615. this._identity = BABYLON.Matrix.Identity();
  28616. this._ranges = {};
  28617. this.bones = [];
  28618. this._scene = scene;
  28619. scene.skeletons.push(this);
  28620. //make sure it will recalculate the matrix next time prepare is called.
  28621. this._isDirty = true;
  28622. }
  28623. // Members
  28624. Skeleton.prototype.getTransformMatrices = function (mesh) {
  28625. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  28626. return mesh._bonesTransformMatrices;
  28627. }
  28628. return this._transformMatrices;
  28629. };
  28630. Skeleton.prototype.getScene = function () {
  28631. return this._scene;
  28632. };
  28633. // Methods
  28634. /**
  28635. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  28636. */
  28637. Skeleton.prototype.toString = function (fullDetails) {
  28638. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  28639. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  28640. if (fullDetails) {
  28641. ret += ", Ranges: {";
  28642. var first = true;
  28643. for (var name_1 in this._ranges) {
  28644. if (first) {
  28645. ret += ", ";
  28646. first = false;
  28647. }
  28648. ret += name_1;
  28649. }
  28650. ret += "}";
  28651. }
  28652. return ret;
  28653. };
  28654. /**
  28655. * Get bone's index searching by name
  28656. * @param {string} name is bone's name to search for
  28657. * @return {number} Indice of the bone. Returns -1 if not found
  28658. */
  28659. Skeleton.prototype.getBoneIndexByName = function (name) {
  28660. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  28661. if (this.bones[boneIndex].name === name) {
  28662. return boneIndex;
  28663. }
  28664. }
  28665. return -1;
  28666. };
  28667. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  28668. // check name not already in use
  28669. if (!this._ranges[name]) {
  28670. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  28671. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  28672. if (this.bones[i].animations[0]) {
  28673. this.bones[i].animations[0].createRange(name, from, to);
  28674. }
  28675. }
  28676. }
  28677. };
  28678. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  28679. if (deleteFrames === void 0) { deleteFrames = true; }
  28680. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  28681. if (this.bones[i].animations[0]) {
  28682. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  28683. }
  28684. }
  28685. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  28686. };
  28687. Skeleton.prototype.getAnimationRange = function (name) {
  28688. return this._ranges[name];
  28689. };
  28690. /**
  28691. * Returns as an Array, all AnimationRanges defined on this skeleton
  28692. */
  28693. Skeleton.prototype.getAnimationRanges = function () {
  28694. var animationRanges = [];
  28695. var name;
  28696. var i = 0;
  28697. for (name in this._ranges) {
  28698. animationRanges[i] = this._ranges[name];
  28699. i++;
  28700. }
  28701. return animationRanges;
  28702. };
  28703. /**
  28704. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  28705. */
  28706. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  28707. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  28708. if (this._ranges[name] || !source.getAnimationRange(name)) {
  28709. return false;
  28710. }
  28711. var ret = true;
  28712. var frameOffset = this._getHighestAnimationFrame() + 1;
  28713. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  28714. var boneDict = {};
  28715. var sourceBones = source.bones;
  28716. var nBones;
  28717. var i;
  28718. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  28719. boneDict[sourceBones[i].name] = sourceBones[i];
  28720. }
  28721. if (this.bones.length !== sourceBones.length) {
  28722. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  28723. ret = false;
  28724. }
  28725. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  28726. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  28727. var boneName = this.bones[i].name;
  28728. var sourceBone = boneDict[boneName];
  28729. if (sourceBone) {
  28730. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  28731. }
  28732. else {
  28733. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  28734. ret = false;
  28735. }
  28736. }
  28737. // do not call createAnimationRange(), since it also is done to bones, which was already done
  28738. var range = source.getAnimationRange(name);
  28739. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  28740. return ret;
  28741. };
  28742. Skeleton.prototype.returnToRest = function () {
  28743. for (var index = 0; index < this.bones.length; index++) {
  28744. this.bones[index].returnToRest();
  28745. }
  28746. };
  28747. Skeleton.prototype._getHighestAnimationFrame = function () {
  28748. var ret = 0;
  28749. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  28750. if (this.bones[i].animations[0]) {
  28751. var highest = this.bones[i].animations[0].getHighestFrame();
  28752. if (ret < highest) {
  28753. ret = highest;
  28754. }
  28755. }
  28756. }
  28757. return ret;
  28758. };
  28759. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  28760. var range = this.getAnimationRange(name);
  28761. if (!range) {
  28762. return null;
  28763. }
  28764. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  28765. };
  28766. Skeleton.prototype._markAsDirty = function () {
  28767. this._isDirty = true;
  28768. };
  28769. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  28770. this._meshesWithPoseMatrix.push(mesh);
  28771. };
  28772. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  28773. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  28774. if (index > -1) {
  28775. this._meshesWithPoseMatrix.splice(index, 1);
  28776. }
  28777. };
  28778. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  28779. for (var index = 0; index < this.bones.length; index++) {
  28780. var bone = this.bones[index];
  28781. var parentBone = bone.getParent();
  28782. if (parentBone) {
  28783. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  28784. }
  28785. else {
  28786. if (initialSkinMatrix) {
  28787. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  28788. }
  28789. else {
  28790. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  28791. }
  28792. }
  28793. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, index * 16);
  28794. }
  28795. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  28796. };
  28797. Skeleton.prototype.prepare = function () {
  28798. if (!this._isDirty) {
  28799. return;
  28800. }
  28801. if (this.needInitialSkinMatrix) {
  28802. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  28803. var mesh = this._meshesWithPoseMatrix[index];
  28804. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  28805. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  28806. }
  28807. var poseMatrix = mesh.getPoseMatrix();
  28808. // Prepare bones
  28809. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  28810. var bone = this.bones[boneIndex];
  28811. if (!bone.getParent()) {
  28812. var matrix = bone.getBaseMatrix();
  28813. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[0]);
  28814. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[0]);
  28815. }
  28816. }
  28817. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  28818. }
  28819. }
  28820. else {
  28821. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  28822. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  28823. }
  28824. this._computeTransformMatrices(this._transformMatrices, null);
  28825. }
  28826. this._isDirty = false;
  28827. this._scene._activeBones.addCount(this.bones.length, false);
  28828. };
  28829. Skeleton.prototype.getAnimatables = function () {
  28830. if (!this._animatables || this._animatables.length !== this.bones.length) {
  28831. this._animatables = [];
  28832. for (var index = 0; index < this.bones.length; index++) {
  28833. this._animatables.push(this.bones[index]);
  28834. }
  28835. }
  28836. return this._animatables;
  28837. };
  28838. Skeleton.prototype.clone = function (name, id) {
  28839. var result = new Skeleton(name, id || name, this._scene);
  28840. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  28841. for (var index = 0; index < this.bones.length; index++) {
  28842. var source = this.bones[index];
  28843. var parentBone = null;
  28844. if (source.getParent()) {
  28845. var parentIndex = this.bones.indexOf(source.getParent());
  28846. parentBone = result.bones[parentIndex];
  28847. }
  28848. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  28849. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  28850. }
  28851. if (this._ranges) {
  28852. result._ranges = {};
  28853. for (var rangeName in this._ranges) {
  28854. result._ranges[rangeName] = this._ranges[rangeName].clone();
  28855. }
  28856. }
  28857. this._isDirty = true;
  28858. return result;
  28859. };
  28860. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  28861. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  28862. this.bones.forEach(function (bone) {
  28863. bone.animations.forEach(function (animation) {
  28864. animation.enableBlending = true;
  28865. animation.blendingSpeed = blendingSpeed;
  28866. });
  28867. });
  28868. };
  28869. Skeleton.prototype.dispose = function () {
  28870. this._meshesWithPoseMatrix = [];
  28871. // Animations
  28872. this.getScene().stopAnimation(this);
  28873. // Remove from scene
  28874. this.getScene().removeSkeleton(this);
  28875. };
  28876. Skeleton.prototype.serialize = function () {
  28877. var serializationObject = {};
  28878. serializationObject.name = this.name;
  28879. serializationObject.id = this.id;
  28880. serializationObject.dimensionsAtRest = this.dimensionsAtRest;
  28881. serializationObject.bones = [];
  28882. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  28883. for (var index = 0; index < this.bones.length; index++) {
  28884. var bone = this.bones[index];
  28885. var serializedBone = {
  28886. parentBoneIndex: bone.getParent() ? this.bones.indexOf(bone.getParent()) : -1,
  28887. name: bone.name,
  28888. matrix: bone.getLocalMatrix().toArray(),
  28889. rest: bone.getRestPose().toArray()
  28890. };
  28891. serializationObject.bones.push(serializedBone);
  28892. if (bone.length) {
  28893. serializedBone.length = bone.length;
  28894. }
  28895. if (bone.animations && bone.animations.length > 0) {
  28896. serializedBone.animation = bone.animations[0].serialize();
  28897. }
  28898. serializationObject.ranges = [];
  28899. for (var name in this._ranges) {
  28900. var range = {};
  28901. range.name = name;
  28902. range.from = this._ranges[name].from;
  28903. range.to = this._ranges[name].to;
  28904. serializationObject.ranges.push(range);
  28905. }
  28906. }
  28907. return serializationObject;
  28908. };
  28909. Skeleton.Parse = function (parsedSkeleton, scene) {
  28910. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  28911. if (parsedSkeleton.dimensionsAtRest) {
  28912. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  28913. }
  28914. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  28915. var index;
  28916. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  28917. var parsedBone = parsedSkeleton.bones[index];
  28918. var parentBone = null;
  28919. if (parsedBone.parentBoneIndex > -1) {
  28920. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  28921. }
  28922. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  28923. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  28924. if (parsedBone.length) {
  28925. bone.length = parsedBone.length;
  28926. }
  28927. if (parsedBone.animation) {
  28928. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  28929. }
  28930. }
  28931. // placed after bones, so createAnimationRange can cascade down
  28932. if (parsedSkeleton.ranges) {
  28933. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  28934. var data = parsedSkeleton.ranges[index];
  28935. skeleton.createAnimationRange(data.name, data.from, data.to);
  28936. }
  28937. }
  28938. return skeleton;
  28939. };
  28940. return Skeleton;
  28941. })();
  28942. BABYLON.Skeleton = Skeleton;
  28943. })(BABYLON || (BABYLON = {}));
  28944. var BABYLON;
  28945. (function (BABYLON) {
  28946. var PostProcess = (function () {
  28947. function PostProcess(name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType) {
  28948. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  28949. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  28950. this.name = name;
  28951. this.width = -1;
  28952. this.height = -1;
  28953. /*
  28954. Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  28955. Can only be used on a single postprocess or on the last one of a chain.
  28956. */
  28957. this.enablePixelPerfectMode = false;
  28958. this._reusable = false;
  28959. this._textures = new BABYLON.SmartArray(2);
  28960. this._currentRenderTextureInd = 0;
  28961. this._scaleRatio = new BABYLON.Vector2(1, 1);
  28962. // Events
  28963. /**
  28964. * An event triggered when the postprocess is activated.
  28965. * @type {BABYLON.Observable}
  28966. */
  28967. this.onActivateObservable = new BABYLON.Observable();
  28968. /**
  28969. * An event triggered when the postprocess changes its size.
  28970. * @type {BABYLON.Observable}
  28971. */
  28972. this.onSizeChangedObservable = new BABYLON.Observable();
  28973. /**
  28974. * An event triggered when the postprocess applies its effect.
  28975. * @type {BABYLON.Observable}
  28976. */
  28977. this.onApplyObservable = new BABYLON.Observable();
  28978. /**
  28979. * An event triggered before rendering the postprocess
  28980. * @type {BABYLON.Observable}
  28981. */
  28982. this.onBeforeRenderObservable = new BABYLON.Observable();
  28983. /**
  28984. * An event triggered after rendering the postprocess
  28985. * @type {BABYLON.Observable}
  28986. */
  28987. this.onAfterRenderObservable = new BABYLON.Observable();
  28988. if (camera != null) {
  28989. this._camera = camera;
  28990. this._scene = camera.getScene();
  28991. camera.attachPostProcess(this);
  28992. this._engine = this._scene.getEngine();
  28993. }
  28994. else {
  28995. this._engine = engine;
  28996. }
  28997. this._options = options;
  28998. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  28999. this._reusable = reusable || false;
  29000. this._textureType = textureType;
  29001. this._samplers = samplers || [];
  29002. this._samplers.push("textureSampler");
  29003. this._fragmentUrl = fragmentUrl;
  29004. this._parameters = parameters || [];
  29005. this._parameters.push("scale");
  29006. this.updateEffect(defines);
  29007. }
  29008. Object.defineProperty(PostProcess.prototype, "onActivate", {
  29009. set: function (callback) {
  29010. if (this._onActivateObserver) {
  29011. this.onActivateObservable.remove(this._onActivateObserver);
  29012. }
  29013. this._onActivateObserver = this.onActivateObservable.add(callback);
  29014. },
  29015. enumerable: true,
  29016. configurable: true
  29017. });
  29018. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  29019. set: function (callback) {
  29020. if (this._onSizeChangedObserver) {
  29021. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  29022. }
  29023. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  29024. },
  29025. enumerable: true,
  29026. configurable: true
  29027. });
  29028. Object.defineProperty(PostProcess.prototype, "onApply", {
  29029. set: function (callback) {
  29030. if (this._onApplyObserver) {
  29031. this.onApplyObservable.remove(this._onApplyObserver);
  29032. }
  29033. this._onApplyObserver = this.onApplyObservable.add(callback);
  29034. },
  29035. enumerable: true,
  29036. configurable: true
  29037. });
  29038. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  29039. set: function (callback) {
  29040. if (this._onBeforeRenderObserver) {
  29041. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  29042. }
  29043. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  29044. },
  29045. enumerable: true,
  29046. configurable: true
  29047. });
  29048. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  29049. set: function (callback) {
  29050. if (this._onAfterRenderObserver) {
  29051. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  29052. }
  29053. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  29054. },
  29055. enumerable: true,
  29056. configurable: true
  29057. });
  29058. PostProcess.prototype.updateEffect = function (defines) {
  29059. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: this._fragmentUrl }, ["position"], this._parameters, this._samplers, defines !== undefined ? defines : "");
  29060. };
  29061. PostProcess.prototype.isReusable = function () {
  29062. return this._reusable;
  29063. };
  29064. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  29065. PostProcess.prototype.markTextureDirty = function () {
  29066. this.width = -1;
  29067. };
  29068. PostProcess.prototype.activate = function (camera, sourceTexture) {
  29069. camera = camera || this._camera;
  29070. var scene = camera.getScene();
  29071. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  29072. var requiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._options) | 0;
  29073. var requiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._options) | 0;
  29074. var desiredWidth = this._options.width || requiredWidth;
  29075. var desiredHeight = this._options.height || requiredHeight;
  29076. if (this.renderTargetSamplingMode !== BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  29077. if (!this._options.width) {
  29078. desiredWidth = BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize);
  29079. }
  29080. if (!this._options.height) {
  29081. desiredHeight = BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize);
  29082. }
  29083. }
  29084. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  29085. if (this._textures.length > 0) {
  29086. for (var i = 0; i < this._textures.length; i++) {
  29087. this._engine._releaseTexture(this._textures.data[i]);
  29088. }
  29089. this._textures.reset();
  29090. }
  29091. this.width = desiredWidth;
  29092. this.height = desiredHeight;
  29093. var textureSize = { width: this.width, height: this.height };
  29094. var textureOptions = {
  29095. generateMipMaps: false,
  29096. generateDepthBuffer: camera._postProcesses.indexOf(this) === 0,
  29097. generateStencilBuffer: camera._postProcesses.indexOf(this) === 0 && this._engine.isStencilEnable,
  29098. samplingMode: this.renderTargetSamplingMode,
  29099. type: this._textureType
  29100. };
  29101. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  29102. if (this._reusable) {
  29103. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  29104. }
  29105. this.onSizeChangedObservable.notifyObservers(this);
  29106. }
  29107. if (this.enablePixelPerfectMode) {
  29108. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  29109. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd], 0, requiredWidth, requiredHeight);
  29110. }
  29111. else {
  29112. this._scaleRatio.copyFromFloats(1, 1);
  29113. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  29114. }
  29115. this.onActivateObservable.notifyObservers(camera);
  29116. // Clear
  29117. if (this.clearColor) {
  29118. this._engine.clear(this.clearColor, true, true, true);
  29119. }
  29120. else {
  29121. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true, true);
  29122. }
  29123. if (this._reusable) {
  29124. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  29125. }
  29126. };
  29127. Object.defineProperty(PostProcess.prototype, "isSupported", {
  29128. get: function () {
  29129. return this._effect.isSupported;
  29130. },
  29131. enumerable: true,
  29132. configurable: true
  29133. });
  29134. PostProcess.prototype.apply = function () {
  29135. // Check
  29136. if (!this._effect.isReady())
  29137. return null;
  29138. // States
  29139. this._engine.enableEffect(this._effect);
  29140. this._engine.setState(false);
  29141. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  29142. this._engine.setDepthBuffer(false);
  29143. this._engine.setDepthWrite(false);
  29144. // Texture
  29145. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  29146. // Parameters
  29147. this._effect.setVector2("scale", this._scaleRatio);
  29148. this.onApplyObservable.notifyObservers(this._effect);
  29149. return this._effect;
  29150. };
  29151. PostProcess.prototype.dispose = function (camera) {
  29152. camera = camera || this._camera;
  29153. if (this._textures.length > 0) {
  29154. for (var i = 0; i < this._textures.length; i++) {
  29155. this._engine._releaseTexture(this._textures.data[i]);
  29156. }
  29157. this._textures.reset();
  29158. }
  29159. if (!camera) {
  29160. return;
  29161. }
  29162. camera.detachPostProcess(this);
  29163. var index = camera._postProcesses.indexOf(this);
  29164. if (index === 0 && camera._postProcesses.length > 0) {
  29165. this._camera._postProcesses[0].markTextureDirty();
  29166. }
  29167. this.onActivateObservable.clear();
  29168. this.onAfterRenderObservable.clear();
  29169. this.onApplyObservable.clear();
  29170. this.onBeforeRenderObservable.clear();
  29171. this.onSizeChangedObservable.clear();
  29172. };
  29173. return PostProcess;
  29174. })();
  29175. BABYLON.PostProcess = PostProcess;
  29176. })(BABYLON || (BABYLON = {}));
  29177. var BABYLON;
  29178. (function (BABYLON) {
  29179. var PostProcessManager = (function () {
  29180. function PostProcessManager(scene) {
  29181. this._vertexBuffers = {};
  29182. this._scene = scene;
  29183. }
  29184. PostProcessManager.prototype._prepareBuffers = function () {
  29185. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  29186. return;
  29187. }
  29188. // VBO
  29189. var vertices = [];
  29190. vertices.push(1, 1);
  29191. vertices.push(-1, 1);
  29192. vertices.push(-1, -1);
  29193. vertices.push(1, -1);
  29194. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  29195. // Indices
  29196. var indices = [];
  29197. indices.push(0);
  29198. indices.push(1);
  29199. indices.push(2);
  29200. indices.push(0);
  29201. indices.push(2);
  29202. indices.push(3);
  29203. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  29204. };
  29205. // Methods
  29206. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  29207. var postProcesses = this._scene.activeCamera._postProcesses;
  29208. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  29209. return false;
  29210. }
  29211. postProcesses[0].activate(this._scene.activeCamera, sourceTexture);
  29212. return true;
  29213. };
  29214. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
  29215. var engine = this._scene.getEngine();
  29216. for (var index = 0; index < postProcesses.length; index++) {
  29217. if (index < postProcesses.length - 1) {
  29218. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  29219. }
  29220. else {
  29221. if (targetTexture) {
  29222. engine.bindFramebuffer(targetTexture);
  29223. }
  29224. else {
  29225. engine.restoreDefaultFramebuffer();
  29226. }
  29227. }
  29228. var pp = postProcesses[index];
  29229. var effect = pp.apply();
  29230. if (effect) {
  29231. pp.onBeforeRenderObservable.notifyObservers(effect);
  29232. // VBOs
  29233. this._prepareBuffers();
  29234. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  29235. // Draw order
  29236. engine.draw(true, 0, 6);
  29237. pp.onAfterRenderObservable.notifyObservers(effect);
  29238. }
  29239. }
  29240. // Restore depth buffer
  29241. engine.setDepthBuffer(true);
  29242. engine.setDepthWrite(true);
  29243. };
  29244. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses) {
  29245. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  29246. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  29247. return;
  29248. }
  29249. var engine = this._scene.getEngine();
  29250. for (var index = 0, len = postProcesses.length; index < len; index++) {
  29251. if (index < len - 1) {
  29252. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  29253. }
  29254. else {
  29255. if (targetTexture) {
  29256. engine.bindFramebuffer(targetTexture, faceIndex);
  29257. }
  29258. else {
  29259. engine.restoreDefaultFramebuffer();
  29260. }
  29261. }
  29262. if (doNotPresent) {
  29263. break;
  29264. }
  29265. var pp = postProcesses[index];
  29266. var effect = pp.apply();
  29267. if (effect) {
  29268. pp.onBeforeRenderObservable.notifyObservers(effect);
  29269. // VBOs
  29270. this._prepareBuffers();
  29271. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  29272. // Draw order
  29273. engine.draw(true, 0, 6);
  29274. pp.onAfterRenderObservable.notifyObservers(effect);
  29275. }
  29276. }
  29277. // Restore depth buffer
  29278. engine.setDepthBuffer(true);
  29279. engine.setDepthWrite(true);
  29280. };
  29281. PostProcessManager.prototype.dispose = function () {
  29282. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  29283. if (buffer) {
  29284. buffer.dispose();
  29285. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  29286. }
  29287. if (this._indexBuffer) {
  29288. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  29289. this._indexBuffer = null;
  29290. }
  29291. };
  29292. return PostProcessManager;
  29293. })();
  29294. BABYLON.PostProcessManager = PostProcessManager;
  29295. })(BABYLON || (BABYLON = {}));
  29296. var BABYLON;
  29297. (function (BABYLON) {
  29298. var PassPostProcess = (function (_super) {
  29299. __extends(PassPostProcess, _super);
  29300. function PassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  29301. _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable);
  29302. }
  29303. return PassPostProcess;
  29304. })(BABYLON.PostProcess);
  29305. BABYLON.PassPostProcess = PassPostProcess;
  29306. })(BABYLON || (BABYLON = {}));
  29307. var BABYLON;
  29308. (function (BABYLON) {
  29309. /**
  29310. * This is a holder class for the physics joint created by the physics plugin.
  29311. * It holds a set of functions to control the underlying joint.
  29312. */
  29313. var PhysicsJoint = (function () {
  29314. function PhysicsJoint(type, jointData) {
  29315. this.type = type;
  29316. this.jointData = jointData;
  29317. jointData.nativeParams = jointData.nativeParams || {};
  29318. }
  29319. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  29320. get: function () {
  29321. return this._physicsJoint;
  29322. },
  29323. set: function (newJoint) {
  29324. if (this._physicsJoint) {
  29325. }
  29326. this._physicsJoint = newJoint;
  29327. },
  29328. enumerable: true,
  29329. configurable: true
  29330. });
  29331. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  29332. set: function (physicsPlugin) {
  29333. this._physicsPlugin = physicsPlugin;
  29334. },
  29335. enumerable: true,
  29336. configurable: true
  29337. });
  29338. /**
  29339. * Execute a function that is physics-plugin specific.
  29340. * @param {Function} func the function that will be executed.
  29341. * It accepts two parameters: the physics world and the physics joint.
  29342. */
  29343. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  29344. func(this._physicsPlugin.world, this._physicsJoint);
  29345. };
  29346. //TODO check if the native joints are the same
  29347. //Joint Types
  29348. PhysicsJoint.DistanceJoint = 0;
  29349. PhysicsJoint.HingeJoint = 1;
  29350. PhysicsJoint.BallAndSocketJoint = 2;
  29351. PhysicsJoint.WheelJoint = 3;
  29352. PhysicsJoint.SliderJoint = 4;
  29353. //OIMO
  29354. PhysicsJoint.PrismaticJoint = 5;
  29355. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  29356. PhysicsJoint.UniversalJoint = 6;
  29357. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  29358. //Cannon
  29359. //Similar to a Ball-Joint. Different in params
  29360. PhysicsJoint.PointToPointJoint = 8;
  29361. //Cannon only at the moment
  29362. PhysicsJoint.SpringJoint = 9;
  29363. PhysicsJoint.LockJoint = 10;
  29364. return PhysicsJoint;
  29365. })();
  29366. BABYLON.PhysicsJoint = PhysicsJoint;
  29367. /**
  29368. * A class representing a physics distance joint.
  29369. */
  29370. var DistanceJoint = (function (_super) {
  29371. __extends(DistanceJoint, _super);
  29372. function DistanceJoint(jointData) {
  29373. _super.call(this, PhysicsJoint.DistanceJoint, jointData);
  29374. }
  29375. /**
  29376. * Update the predefined distance.
  29377. */
  29378. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  29379. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  29380. };
  29381. return DistanceJoint;
  29382. })(PhysicsJoint);
  29383. BABYLON.DistanceJoint = DistanceJoint;
  29384. var MotorEnabledJoint = (function (_super) {
  29385. __extends(MotorEnabledJoint, _super);
  29386. function MotorEnabledJoint(type, jointData) {
  29387. _super.call(this, type, jointData);
  29388. }
  29389. /**
  29390. * Set the motor values.
  29391. * Attention, this function is plugin specific. Engines won't react 100% the same.
  29392. * @param {number} force the force to apply
  29393. * @param {number} maxForce max force for this motor.
  29394. */
  29395. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  29396. this._physicsPlugin.setMotor(this, force, maxForce);
  29397. };
  29398. /**
  29399. * Set the motor's limits.
  29400. * Attention, this function is plugin specific. Engines won't react 100% the same.
  29401. */
  29402. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  29403. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  29404. };
  29405. return MotorEnabledJoint;
  29406. })(PhysicsJoint);
  29407. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  29408. /**
  29409. * This class represents a single hinge physics joint
  29410. */
  29411. var HingeJoint = (function (_super) {
  29412. __extends(HingeJoint, _super);
  29413. function HingeJoint(jointData) {
  29414. _super.call(this, PhysicsJoint.HingeJoint, jointData);
  29415. }
  29416. /**
  29417. * Set the motor values.
  29418. * Attention, this function is plugin specific. Engines won't react 100% the same.
  29419. * @param {number} force the force to apply
  29420. * @param {number} maxForce max force for this motor.
  29421. */
  29422. HingeJoint.prototype.setMotor = function (force, maxForce) {
  29423. this._physicsPlugin.setMotor(this, force, maxForce);
  29424. };
  29425. /**
  29426. * Set the motor's limits.
  29427. * Attention, this function is plugin specific. Engines won't react 100% the same.
  29428. */
  29429. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  29430. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  29431. };
  29432. return HingeJoint;
  29433. })(MotorEnabledJoint);
  29434. BABYLON.HingeJoint = HingeJoint;
  29435. /**
  29436. * This class represents a dual hinge physics joint (same as wheel joint)
  29437. */
  29438. var Hinge2Joint = (function (_super) {
  29439. __extends(Hinge2Joint, _super);
  29440. function Hinge2Joint(jointData) {
  29441. _super.call(this, PhysicsJoint.Hinge2Joint, jointData);
  29442. }
  29443. /**
  29444. * Set the motor values.
  29445. * Attention, this function is plugin specific. Engines won't react 100% the same.
  29446. * @param {number} force the force to apply
  29447. * @param {number} maxForce max force for this motor.
  29448. * @param {motorIndex} the motor's index, 0 or 1.
  29449. */
  29450. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  29451. if (motorIndex === void 0) { motorIndex = 0; }
  29452. this._physicsPlugin.setMotor(this, force, maxForce, motorIndex);
  29453. };
  29454. /**
  29455. * Set the motor limits.
  29456. * Attention, this function is plugin specific. Engines won't react 100% the same.
  29457. * @param {number} upperLimit the upper limit
  29458. * @param {number} lowerLimit lower limit
  29459. * @param {motorIndex} the motor's index, 0 or 1.
  29460. */
  29461. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  29462. if (motorIndex === void 0) { motorIndex = 0; }
  29463. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  29464. };
  29465. return Hinge2Joint;
  29466. })(MotorEnabledJoint);
  29467. BABYLON.Hinge2Joint = Hinge2Joint;
  29468. })(BABYLON || (BABYLON = {}));
  29469. var BABYLON;
  29470. (function (BABYLON) {
  29471. var PhysicsImpostor = (function () {
  29472. function PhysicsImpostor(object, type, _options, _scene) {
  29473. var _this = this;
  29474. if (_options === void 0) { _options = { mass: 0 }; }
  29475. this.object = object;
  29476. this.type = type;
  29477. this._options = _options;
  29478. this._scene = _scene;
  29479. this._bodyUpdateRequired = false;
  29480. this._onBeforePhysicsStepCallbacks = new Array();
  29481. this._onAfterPhysicsStepCallbacks = new Array();
  29482. this._onPhysicsCollideCallbacks = [];
  29483. this._deltaPosition = BABYLON.Vector3.Zero();
  29484. this._tmpPositionWithDelta = BABYLON.Vector3.Zero();
  29485. this._tmpRotationWithDelta = new BABYLON.Quaternion();
  29486. /**
  29487. * this function is executed by the physics engine.
  29488. */
  29489. this.beforeStep = function () {
  29490. _this.object.position.subtractToRef(_this._deltaPosition, _this._tmpPositionWithDelta);
  29491. //conjugate deltaRotation
  29492. if (_this._deltaRotationConjugated) {
  29493. _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this._tmpRotationWithDelta);
  29494. }
  29495. else {
  29496. _this._tmpRotationWithDelta.copyFrom(_this.object.rotationQuaternion);
  29497. }
  29498. _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, _this._tmpPositionWithDelta, _this._tmpRotationWithDelta);
  29499. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  29500. func(_this);
  29501. });
  29502. };
  29503. /**
  29504. * this function is executed by the physics engine.
  29505. */
  29506. this.afterStep = function () {
  29507. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  29508. func(_this);
  29509. });
  29510. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  29511. _this.object.position.addInPlace(_this._deltaPosition);
  29512. if (_this._deltaRotation) {
  29513. _this.object.rotationQuaternion.multiplyInPlace(_this._deltaRotation);
  29514. }
  29515. };
  29516. //event and body object due to cannon's event-based architecture.
  29517. this.onCollide = function (e) {
  29518. if (!_this._onPhysicsCollideCallbacks.length)
  29519. return;
  29520. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  29521. if (otherImpostor) {
  29522. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  29523. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  29524. }).forEach(function (obj) {
  29525. obj.callback(_this, otherImpostor);
  29526. });
  29527. }
  29528. };
  29529. //sanity check!
  29530. if (!this.object) {
  29531. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  29532. return;
  29533. }
  29534. //legacy support for old syntax.
  29535. if (!this._scene && object.getScene) {
  29536. this._scene = object.getScene();
  29537. }
  29538. this._physicsEngine = this._scene.getPhysicsEngine();
  29539. if (!this._physicsEngine) {
  29540. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  29541. }
  29542. else {
  29543. //set the object's quaternion, if not set
  29544. if (!this.object.rotationQuaternion) {
  29545. if (this.object.rotation) {
  29546. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  29547. }
  29548. else {
  29549. this.object.rotationQuaternion = new BABYLON.Quaternion();
  29550. }
  29551. }
  29552. //default options params
  29553. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  29554. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  29555. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  29556. this._joints = [];
  29557. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  29558. if (!this.object.parent) {
  29559. this._init();
  29560. }
  29561. }
  29562. }
  29563. /**
  29564. * This function will completly initialize this impostor.
  29565. * It will create a new body - but only if this mesh has no parent.
  29566. * If it has, this impostor will not be used other than to define the impostor
  29567. * of the child mesh.
  29568. */
  29569. PhysicsImpostor.prototype._init = function () {
  29570. this._physicsEngine.removeImpostor(this);
  29571. this.physicsBody = null;
  29572. this._parent = this._parent || this._getPhysicsParent();
  29573. if (!this.parent) {
  29574. this._physicsEngine.addImpostor(this);
  29575. }
  29576. };
  29577. PhysicsImpostor.prototype._getPhysicsParent = function () {
  29578. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  29579. var parentMesh = this.object.parent;
  29580. return parentMesh.physicsImpostor;
  29581. }
  29582. return;
  29583. };
  29584. /**
  29585. * Should a new body be generated.
  29586. */
  29587. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  29588. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  29589. };
  29590. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  29591. this.forceUpdate();
  29592. };
  29593. /**
  29594. * Force a regeneration of this or the parent's impostor's body.
  29595. * Use under cautious - This will remove all joints already implemented.
  29596. */
  29597. PhysicsImpostor.prototype.forceUpdate = function () {
  29598. this._init();
  29599. if (this.parent) {
  29600. this.parent.forceUpdate();
  29601. }
  29602. };
  29603. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  29604. /*public get mesh(): AbstractMesh {
  29605. return this._mesh;
  29606. }*/
  29607. /**
  29608. * Gets the body that holds this impostor. Either its own, or its parent.
  29609. */
  29610. get: function () {
  29611. return this._parent ? this._parent.physicsBody : this._physicsBody;
  29612. },
  29613. /**
  29614. * Set the physics body. Used mainly by the physics engine/plugin
  29615. */
  29616. set: function (physicsBody) {
  29617. if (this._physicsBody) {
  29618. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  29619. }
  29620. this._physicsBody = physicsBody;
  29621. this.resetUpdateFlags();
  29622. },
  29623. enumerable: true,
  29624. configurable: true
  29625. });
  29626. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  29627. get: function () {
  29628. return this._parent;
  29629. },
  29630. enumerable: true,
  29631. configurable: true
  29632. });
  29633. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  29634. this._bodyUpdateRequired = false;
  29635. };
  29636. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  29637. if (this.object.getBoundingInfo) {
  29638. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  29639. return this.object.getBoundingInfo().boundingBox.extendSize.scale(2).multiply(this.object.scaling);
  29640. }
  29641. else {
  29642. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  29643. }
  29644. };
  29645. PhysicsImpostor.prototype.getObjectCenter = function () {
  29646. if (this.object.getBoundingInfo) {
  29647. return this.object.getBoundingInfo().boundingBox.center;
  29648. }
  29649. else {
  29650. return this.object.position;
  29651. }
  29652. };
  29653. /**
  29654. * Get a specific parametes from the options parameter.
  29655. */
  29656. PhysicsImpostor.prototype.getParam = function (paramName) {
  29657. return this._options[paramName];
  29658. };
  29659. /**
  29660. * Sets a specific parameter in the options given to the physics plugin
  29661. */
  29662. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  29663. this._options[paramName] = value;
  29664. this._bodyUpdateRequired = true;
  29665. };
  29666. /**
  29667. * Specifically change the body's mass option. Won't recreate the physics body object
  29668. */
  29669. PhysicsImpostor.prototype.setMass = function (mass) {
  29670. if (this.getParam("mass") !== mass) {
  29671. this.setParam("mass", mass);
  29672. }
  29673. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  29674. };
  29675. PhysicsImpostor.prototype.getLinearVelocity = function () {
  29676. return this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this);
  29677. };
  29678. /**
  29679. * Set the body's linear velocity.
  29680. */
  29681. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  29682. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  29683. };
  29684. PhysicsImpostor.prototype.getAngularVelocity = function () {
  29685. return this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this);
  29686. };
  29687. /**
  29688. * Set the body's linear velocity.
  29689. */
  29690. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  29691. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  29692. };
  29693. /**
  29694. * Execute a function with the physics plugin native code.
  29695. * Provide a function the will have two variables - the world object and the physics body object.
  29696. */
  29697. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  29698. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  29699. };
  29700. /**
  29701. * Register a function that will be executed before the physics world is stepping forward.
  29702. */
  29703. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  29704. this._onBeforePhysicsStepCallbacks.push(func);
  29705. };
  29706. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  29707. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  29708. if (index > -1) {
  29709. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  29710. }
  29711. else {
  29712. BABYLON.Tools.Warn("Function to remove was not found");
  29713. }
  29714. };
  29715. /**
  29716. * Register a function that will be executed after the physics step
  29717. */
  29718. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  29719. this._onAfterPhysicsStepCallbacks.push(func);
  29720. };
  29721. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  29722. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  29723. if (index > -1) {
  29724. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  29725. }
  29726. else {
  29727. BABYLON.Tools.Warn("Function to remove was not found");
  29728. }
  29729. };
  29730. /**
  29731. * register a function that will be executed when this impostor collides against a different body.
  29732. */
  29733. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  29734. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  29735. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  29736. };
  29737. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  29738. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  29739. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  29740. if (index > -1) {
  29741. this._onPhysicsCollideCallbacks.splice(index, 1);
  29742. }
  29743. else {
  29744. BABYLON.Tools.Warn("Function to remove was not found");
  29745. }
  29746. };
  29747. /**
  29748. * Apply a force
  29749. */
  29750. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  29751. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  29752. };
  29753. /**
  29754. * Apply an impulse
  29755. */
  29756. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  29757. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  29758. };
  29759. /**
  29760. * A help function to create a joint.
  29761. */
  29762. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  29763. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  29764. this.addJoint(otherImpostor, joint);
  29765. };
  29766. /**
  29767. * Add a joint to this impostor with a different impostor.
  29768. */
  29769. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  29770. this._joints.push({
  29771. otherImpostor: otherImpostor,
  29772. joint: joint
  29773. });
  29774. this._physicsEngine.addJoint(this, otherImpostor, joint);
  29775. };
  29776. /**
  29777. * Will keep this body still, in a sleep mode.
  29778. */
  29779. PhysicsImpostor.prototype.sleep = function () {
  29780. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  29781. };
  29782. /**
  29783. * Wake the body up.
  29784. */
  29785. PhysicsImpostor.prototype.wakeUp = function () {
  29786. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  29787. };
  29788. PhysicsImpostor.prototype.clone = function (newObject) {
  29789. if (!newObject)
  29790. return null;
  29791. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  29792. };
  29793. PhysicsImpostor.prototype.dispose = function () {
  29794. var _this = this;
  29795. //no dispose if no physics engine is available.
  29796. if (!this._physicsEngine) {
  29797. return;
  29798. }
  29799. this._joints.forEach(function (j) {
  29800. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  29801. });
  29802. //dispose the physics body
  29803. this._physicsEngine.removeImpostor(this);
  29804. if (this.parent) {
  29805. this.parent.forceUpdate();
  29806. }
  29807. else {
  29808. }
  29809. };
  29810. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  29811. this._deltaPosition.copyFrom(position);
  29812. };
  29813. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  29814. if (!this._deltaRotation) {
  29815. this._deltaRotation = new BABYLON.Quaternion();
  29816. }
  29817. this._deltaRotation.copyFrom(rotation);
  29818. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  29819. };
  29820. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  29821. //Impostor types
  29822. PhysicsImpostor.NoImpostor = 0;
  29823. PhysicsImpostor.SphereImpostor = 1;
  29824. PhysicsImpostor.BoxImpostor = 2;
  29825. PhysicsImpostor.PlaneImpostor = 3;
  29826. PhysicsImpostor.MeshImpostor = 4;
  29827. PhysicsImpostor.CylinderImpostor = 7;
  29828. PhysicsImpostor.ParticleImpostor = 8;
  29829. PhysicsImpostor.HeightmapImpostor = 9;
  29830. return PhysicsImpostor;
  29831. })();
  29832. BABYLON.PhysicsImpostor = PhysicsImpostor;
  29833. })(BABYLON || (BABYLON = {}));
  29834. var BABYLON;
  29835. (function (BABYLON) {
  29836. var PhysicsEngine = (function () {
  29837. function PhysicsEngine(gravity, _physicsPlugin) {
  29838. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  29839. this._physicsPlugin = _physicsPlugin;
  29840. //new methods and parameters
  29841. this._impostors = [];
  29842. this._joints = [];
  29843. if (!this._physicsPlugin.isSupported()) {
  29844. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  29845. + "Please make sure it is included.");
  29846. }
  29847. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  29848. this.setGravity(gravity);
  29849. this.setTimeStep();
  29850. }
  29851. PhysicsEngine.prototype.setGravity = function (gravity) {
  29852. this.gravity = gravity;
  29853. this._physicsPlugin.setGravity(this.gravity);
  29854. };
  29855. /**
  29856. * Set the time step of the physics engine.
  29857. * default is 1/60.
  29858. * To slow it down, enter 1/600 for example.
  29859. * To speed it up, 1/30
  29860. * @param {number} newTimeStep the new timestep to apply to this world.
  29861. */
  29862. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  29863. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  29864. this._physicsPlugin.setTimeStep(newTimeStep);
  29865. };
  29866. PhysicsEngine.prototype.dispose = function () {
  29867. this._impostors.forEach(function (impostor) {
  29868. impostor.dispose();
  29869. });
  29870. this._physicsPlugin.dispose();
  29871. };
  29872. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  29873. return this._physicsPlugin.name;
  29874. };
  29875. /**
  29876. * Adding a new impostor for the impostor tracking.
  29877. * This will be done by the impostor itself.
  29878. * @param {PhysicsImpostor} impostor the impostor to add
  29879. */
  29880. PhysicsEngine.prototype.addImpostor = function (impostor) {
  29881. impostor.uniqueId = this._impostors.push(impostor);
  29882. //if no parent, generate the body
  29883. if (!impostor.parent) {
  29884. this._physicsPlugin.generatePhysicsBody(impostor);
  29885. }
  29886. };
  29887. /**
  29888. * Remove an impostor from the engine.
  29889. * This impostor and its mesh will not longer be updated by the physics engine.
  29890. * @param {PhysicsImpostor} impostor the impostor to remove
  29891. */
  29892. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  29893. var index = this._impostors.indexOf(impostor);
  29894. if (index > -1) {
  29895. var removed = this._impostors.splice(index, 1);
  29896. //Is it needed?
  29897. if (removed.length) {
  29898. //this will also remove it from the world.
  29899. removed[0].physicsBody = null;
  29900. }
  29901. }
  29902. };
  29903. /**
  29904. * Add a joint to the physics engine
  29905. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  29906. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  29907. * @param {PhysicsJoint} the joint that will connect both impostors.
  29908. */
  29909. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  29910. var impostorJoint = {
  29911. mainImpostor: mainImpostor,
  29912. connectedImpostor: connectedImpostor,
  29913. joint: joint
  29914. };
  29915. joint.physicsPlugin = this._physicsPlugin;
  29916. this._joints.push(impostorJoint);
  29917. this._physicsPlugin.generateJoint(impostorJoint);
  29918. };
  29919. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  29920. var matchingJoints = this._joints.filter(function (impostorJoint) {
  29921. return (impostorJoint.connectedImpostor === connectedImpostor
  29922. && impostorJoint.joint === joint
  29923. && impostorJoint.mainImpostor === mainImpostor);
  29924. });
  29925. if (matchingJoints.length) {
  29926. this._physicsPlugin.removeJoint(matchingJoints[0]);
  29927. }
  29928. };
  29929. /**
  29930. * Called by the scene. no need to call it.
  29931. */
  29932. PhysicsEngine.prototype._step = function (delta) {
  29933. var _this = this;
  29934. //check if any mesh has no body / requires an update
  29935. this._impostors.forEach(function (impostor) {
  29936. if (impostor.isBodyInitRequired()) {
  29937. _this._physicsPlugin.generatePhysicsBody(impostor);
  29938. }
  29939. });
  29940. if (delta > 0.1) {
  29941. delta = 0.1;
  29942. }
  29943. else if (delta <= 0) {
  29944. delta = 1.0 / 60.0;
  29945. }
  29946. this._physicsPlugin.executeStep(delta, this._impostors);
  29947. };
  29948. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  29949. return this._physicsPlugin;
  29950. };
  29951. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  29952. for (var i = 0; i < this._impostors.length; ++i) {
  29953. if (this._impostors[i].object === object) {
  29954. return this._impostors[i];
  29955. }
  29956. }
  29957. };
  29958. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  29959. for (var i = 0; i < this._impostors.length; ++i) {
  29960. if (this._impostors[i].physicsBody === body) {
  29961. return this._impostors[i];
  29962. }
  29963. }
  29964. };
  29965. // Statics, Legacy support.
  29966. /**
  29967. * @Deprecated
  29968. *
  29969. */
  29970. PhysicsEngine.NoImpostor = BABYLON.PhysicsImpostor.NoImpostor;
  29971. PhysicsEngine.SphereImpostor = BABYLON.PhysicsImpostor.SphereImpostor;
  29972. PhysicsEngine.BoxImpostor = BABYLON.PhysicsImpostor.BoxImpostor;
  29973. PhysicsEngine.PlaneImpostor = BABYLON.PhysicsImpostor.PlaneImpostor;
  29974. PhysicsEngine.MeshImpostor = BABYLON.PhysicsImpostor.MeshImpostor;
  29975. PhysicsEngine.CylinderImpostor = BABYLON.PhysicsImpostor.CylinderImpostor;
  29976. PhysicsEngine.HeightmapImpostor = BABYLON.PhysicsImpostor.HeightmapImpostor;
  29977. PhysicsEngine.CapsuleImpostor = -1;
  29978. PhysicsEngine.ConeImpostor = -1;
  29979. PhysicsEngine.ConvexHullImpostor = -1;
  29980. PhysicsEngine.Epsilon = 0.001;
  29981. return PhysicsEngine;
  29982. })();
  29983. BABYLON.PhysicsEngine = PhysicsEngine;
  29984. })(BABYLON || (BABYLON = {}));
  29985. var BABYLON;
  29986. (function (BABYLON) {
  29987. var VertexData = (function () {
  29988. function VertexData() {
  29989. }
  29990. VertexData.prototype.set = function (data, kind) {
  29991. switch (kind) {
  29992. case BABYLON.VertexBuffer.PositionKind:
  29993. this.positions = data;
  29994. break;
  29995. case BABYLON.VertexBuffer.NormalKind:
  29996. this.normals = data;
  29997. break;
  29998. case BABYLON.VertexBuffer.UVKind:
  29999. this.uvs = data;
  30000. break;
  30001. case BABYLON.VertexBuffer.UV2Kind:
  30002. this.uvs2 = data;
  30003. break;
  30004. case BABYLON.VertexBuffer.UV3Kind:
  30005. this.uvs3 = data;
  30006. break;
  30007. case BABYLON.VertexBuffer.UV4Kind:
  30008. this.uvs4 = data;
  30009. break;
  30010. case BABYLON.VertexBuffer.UV5Kind:
  30011. this.uvs5 = data;
  30012. break;
  30013. case BABYLON.VertexBuffer.UV6Kind:
  30014. this.uvs6 = data;
  30015. break;
  30016. case BABYLON.VertexBuffer.ColorKind:
  30017. this.colors = data;
  30018. break;
  30019. case BABYLON.VertexBuffer.MatricesIndicesKind:
  30020. this.matricesIndices = data;
  30021. break;
  30022. case BABYLON.VertexBuffer.MatricesWeightsKind:
  30023. this.matricesWeights = data;
  30024. break;
  30025. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  30026. this.matricesIndicesExtra = data;
  30027. break;
  30028. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  30029. this.matricesWeightsExtra = data;
  30030. break;
  30031. }
  30032. };
  30033. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  30034. this._applyTo(mesh, updatable);
  30035. };
  30036. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  30037. this._applyTo(geometry, updatable);
  30038. };
  30039. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  30040. this._update(mesh);
  30041. };
  30042. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  30043. this._update(geometry);
  30044. };
  30045. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  30046. if (this.positions) {
  30047. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  30048. }
  30049. if (this.normals) {
  30050. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  30051. }
  30052. if (this.uvs) {
  30053. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  30054. }
  30055. if (this.uvs2) {
  30056. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  30057. }
  30058. if (this.uvs3) {
  30059. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  30060. }
  30061. if (this.uvs4) {
  30062. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  30063. }
  30064. if (this.uvs5) {
  30065. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  30066. }
  30067. if (this.uvs6) {
  30068. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  30069. }
  30070. if (this.colors) {
  30071. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  30072. }
  30073. if (this.matricesIndices) {
  30074. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  30075. }
  30076. if (this.matricesWeights) {
  30077. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  30078. }
  30079. if (this.matricesIndicesExtra) {
  30080. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  30081. }
  30082. if (this.matricesWeightsExtra) {
  30083. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  30084. }
  30085. if (this.indices) {
  30086. meshOrGeometry.setIndices(this.indices);
  30087. }
  30088. };
  30089. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  30090. if (this.positions) {
  30091. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  30092. }
  30093. if (this.normals) {
  30094. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  30095. }
  30096. if (this.uvs) {
  30097. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  30098. }
  30099. if (this.uvs2) {
  30100. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  30101. }
  30102. if (this.uvs3) {
  30103. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  30104. }
  30105. if (this.uvs4) {
  30106. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  30107. }
  30108. if (this.uvs5) {
  30109. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  30110. }
  30111. if (this.uvs6) {
  30112. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  30113. }
  30114. if (this.colors) {
  30115. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  30116. }
  30117. if (this.matricesIndices) {
  30118. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  30119. }
  30120. if (this.matricesWeights) {
  30121. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  30122. }
  30123. if (this.matricesIndicesExtra) {
  30124. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  30125. }
  30126. if (this.matricesWeightsExtra) {
  30127. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  30128. }
  30129. if (this.indices) {
  30130. meshOrGeometry.setIndices(this.indices);
  30131. }
  30132. };
  30133. VertexData.prototype.transform = function (matrix) {
  30134. var transformed = BABYLON.Vector3.Zero();
  30135. var index;
  30136. if (this.positions) {
  30137. var position = BABYLON.Vector3.Zero();
  30138. for (index = 0; index < this.positions.length; index += 3) {
  30139. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  30140. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  30141. this.positions[index] = transformed.x;
  30142. this.positions[index + 1] = transformed.y;
  30143. this.positions[index + 2] = transformed.z;
  30144. }
  30145. }
  30146. if (this.normals) {
  30147. var normal = BABYLON.Vector3.Zero();
  30148. for (index = 0; index < this.normals.length; index += 3) {
  30149. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  30150. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  30151. this.normals[index] = transformed.x;
  30152. this.normals[index + 1] = transformed.y;
  30153. this.normals[index + 2] = transformed.z;
  30154. }
  30155. }
  30156. };
  30157. VertexData.prototype.merge = function (other) {
  30158. if (other.indices) {
  30159. if (!this.indices) {
  30160. this.indices = [];
  30161. }
  30162. var offset = this.positions ? this.positions.length / 3 : 0;
  30163. for (var index = 0; index < other.indices.length; index++) {
  30164. //TODO check type - if Int32Array!
  30165. this.indices.push(other.indices[index] + offset);
  30166. }
  30167. }
  30168. this.positions = this._mergeElement(this.positions, other.positions);
  30169. this.normals = this._mergeElement(this.normals, other.normals);
  30170. this.uvs = this._mergeElement(this.uvs, other.uvs);
  30171. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  30172. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  30173. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  30174. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  30175. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  30176. this.colors = this._mergeElement(this.colors, other.colors);
  30177. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  30178. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  30179. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  30180. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  30181. };
  30182. VertexData.prototype._mergeElement = function (source, other) {
  30183. if (!other)
  30184. return source;
  30185. if (!source)
  30186. return other;
  30187. var len = other.length + source.length;
  30188. var isSrcTypedArray = source instanceof Float32Array;
  30189. var isOthTypedArray = other instanceof Float32Array;
  30190. // use non-loop method when the source is Float32Array
  30191. if (isSrcTypedArray) {
  30192. var ret32 = new Float32Array(len);
  30193. ret32.set(source);
  30194. ret32.set(other, source.length);
  30195. return ret32;
  30196. }
  30197. else if (!isOthTypedArray) {
  30198. return source.concat(other);
  30199. }
  30200. else {
  30201. var ret = source.slice(0); // copy source to a separate array
  30202. for (var i = 0, len = other.length; i < len; i++) {
  30203. ret.push(other[i]);
  30204. }
  30205. return ret;
  30206. }
  30207. };
  30208. VertexData.prototype.serialize = function () {
  30209. var serializationObject = this.serialize();
  30210. if (this.positions) {
  30211. serializationObject.positions = this.positions;
  30212. }
  30213. if (this.normals) {
  30214. serializationObject.normals = this.normals;
  30215. }
  30216. if (this.uvs) {
  30217. serializationObject.uvs = this.uvs;
  30218. }
  30219. if (this.uvs2) {
  30220. serializationObject.uvs2 = this.uvs2;
  30221. }
  30222. if (this.uvs3) {
  30223. serializationObject.uvs3 = this.uvs3;
  30224. }
  30225. if (this.uvs4) {
  30226. serializationObject.uvs4 = this.uvs4;
  30227. }
  30228. if (this.uvs5) {
  30229. serializationObject.uvs5 = this.uvs5;
  30230. }
  30231. if (this.uvs6) {
  30232. serializationObject.uvs6 = this.uvs6;
  30233. }
  30234. if (this.colors) {
  30235. serializationObject.colors = this.colors;
  30236. }
  30237. if (this.matricesIndices) {
  30238. serializationObject.matricesIndices = this.matricesIndices;
  30239. serializationObject.matricesIndices._isExpanded = true;
  30240. }
  30241. if (this.matricesWeights) {
  30242. serializationObject.matricesWeights = this.matricesWeights;
  30243. }
  30244. if (this.matricesIndicesExtra) {
  30245. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  30246. serializationObject.matricesIndicesExtra._isExpanded = true;
  30247. }
  30248. if (this.matricesWeightsExtra) {
  30249. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  30250. }
  30251. serializationObject.indices = this.indices;
  30252. return serializationObject;
  30253. };
  30254. // Statics
  30255. VertexData.ExtractFromMesh = function (mesh, copyWhenShared) {
  30256. return VertexData._ExtractFrom(mesh, copyWhenShared);
  30257. };
  30258. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared) {
  30259. return VertexData._ExtractFrom(geometry, copyWhenShared);
  30260. };
  30261. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared) {
  30262. var result = new VertexData();
  30263. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  30264. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared);
  30265. }
  30266. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  30267. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared);
  30268. }
  30269. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  30270. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared);
  30271. }
  30272. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  30273. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared);
  30274. }
  30275. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  30276. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared);
  30277. }
  30278. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  30279. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared);
  30280. }
  30281. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  30282. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared);
  30283. }
  30284. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  30285. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared);
  30286. }
  30287. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  30288. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared);
  30289. }
  30290. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  30291. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared);
  30292. }
  30293. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  30294. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared);
  30295. }
  30296. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  30297. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared);
  30298. }
  30299. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  30300. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared);
  30301. }
  30302. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  30303. return result;
  30304. };
  30305. VertexData.CreateRibbon = function (options) {
  30306. var pathArray = options.pathArray;
  30307. var closeArray = options.closeArray || false;
  30308. var closePath = options.closePath || false;
  30309. var invertUV = options.invertUV || false;
  30310. var defaultOffset = Math.floor(pathArray[0].length / 2);
  30311. var offset = options.offset || defaultOffset;
  30312. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  30313. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30314. var positions = [];
  30315. var indices = [];
  30316. var normals = [];
  30317. var uvs = [];
  30318. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  30319. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  30320. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  30321. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  30322. var minlg; // minimal length among all paths from pathArray
  30323. var lg = []; // array of path lengths : nb of vertex per path
  30324. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  30325. var p; // path iterator
  30326. var i; // point iterator
  30327. var j; // point iterator
  30328. // if single path in pathArray
  30329. if (pathArray.length < 2) {
  30330. var ar1 = [];
  30331. var ar2 = [];
  30332. for (i = 0; i < pathArray[0].length - offset; i++) {
  30333. ar1.push(pathArray[0][i]);
  30334. ar2.push(pathArray[0][i + offset]);
  30335. }
  30336. pathArray = [ar1, ar2];
  30337. }
  30338. // positions and horizontal distances (u)
  30339. var idc = 0;
  30340. var closePathCorr = (closePath) ? 1 : 0;
  30341. var path;
  30342. var l;
  30343. minlg = pathArray[0].length;
  30344. var vectlg;
  30345. var dist;
  30346. for (p = 0; p < pathArray.length; p++) {
  30347. uTotalDistance[p] = 0;
  30348. us[p] = [0];
  30349. path = pathArray[p];
  30350. l = path.length;
  30351. minlg = (minlg < l) ? minlg : l;
  30352. j = 0;
  30353. while (j < l) {
  30354. positions.push(path[j].x, path[j].y, path[j].z);
  30355. if (j > 0) {
  30356. vectlg = path[j].subtract(path[j - 1]).length();
  30357. dist = vectlg + uTotalDistance[p];
  30358. us[p].push(dist);
  30359. uTotalDistance[p] = dist;
  30360. }
  30361. j++;
  30362. }
  30363. if (closePath) {
  30364. j--;
  30365. positions.push(path[0].x, path[0].y, path[0].z);
  30366. vectlg = path[j].subtract(path[0]).length();
  30367. dist = vectlg + uTotalDistance[p];
  30368. us[p].push(dist);
  30369. uTotalDistance[p] = dist;
  30370. }
  30371. lg[p] = l + closePathCorr;
  30372. idx[p] = idc;
  30373. idc += (l + closePathCorr);
  30374. }
  30375. // vertical distances (v)
  30376. var path1;
  30377. var path2;
  30378. var vertex1;
  30379. var vertex2;
  30380. for (i = 0; i < minlg + closePathCorr; i++) {
  30381. vTotalDistance[i] = 0;
  30382. vs[i] = [0];
  30383. for (p = 0; p < pathArray.length - 1; p++) {
  30384. path1 = pathArray[p];
  30385. path2 = pathArray[p + 1];
  30386. if (i === minlg) {
  30387. vertex1 = path1[0];
  30388. vertex2 = path2[0];
  30389. }
  30390. else {
  30391. vertex1 = path1[i];
  30392. vertex2 = path2[i];
  30393. }
  30394. vectlg = vertex2.subtract(vertex1).length();
  30395. dist = vectlg + vTotalDistance[i];
  30396. vs[i].push(dist);
  30397. vTotalDistance[i] = dist;
  30398. }
  30399. if (closeArray) {
  30400. path1 = pathArray[p];
  30401. path2 = pathArray[0];
  30402. if (i === minlg) {
  30403. vertex2 = path2[0];
  30404. }
  30405. vectlg = vertex2.subtract(vertex1).length();
  30406. dist = vectlg + vTotalDistance[i];
  30407. vTotalDistance[i] = dist;
  30408. }
  30409. }
  30410. // uvs
  30411. var u;
  30412. var v;
  30413. for (p = 0; p < pathArray.length; p++) {
  30414. for (i = 0; i < minlg + closePathCorr; i++) {
  30415. u = us[p][i] / uTotalDistance[p];
  30416. v = vs[i][p] / vTotalDistance[i];
  30417. if (invertUV) {
  30418. uvs.push(v, u);
  30419. }
  30420. else {
  30421. uvs.push(u, v);
  30422. }
  30423. }
  30424. }
  30425. // indices
  30426. p = 0; // path index
  30427. var pi = 0; // positions array index
  30428. var l1 = lg[p] - 1; // path1 length
  30429. var l2 = lg[p + 1] - 1; // path2 length
  30430. var min = (l1 < l2) ? l1 : l2; // current path stop index
  30431. var shft = idx[1] - idx[0]; // shift
  30432. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  30433. while (pi <= min && p < path1nb) {
  30434. // 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
  30435. indices.push(pi, pi + shft, pi + 1);
  30436. indices.push(pi + shft + 1, pi + 1, pi + shft);
  30437. pi += 1;
  30438. if (pi === min) {
  30439. p++;
  30440. if (p === lg.length - 1) {
  30441. shft = idx[0] - idx[p];
  30442. l1 = lg[p] - 1;
  30443. l2 = lg[0] - 1;
  30444. }
  30445. else {
  30446. shft = idx[p + 1] - idx[p];
  30447. l1 = lg[p] - 1;
  30448. l2 = lg[p + 1] - 1;
  30449. }
  30450. pi = idx[p];
  30451. min = (l1 < l2) ? l1 + pi : l2 + pi;
  30452. }
  30453. }
  30454. // normals
  30455. VertexData.ComputeNormals(positions, indices, normals);
  30456. if (closePath) {
  30457. var indexFirst = 0;
  30458. var indexLast = 0;
  30459. for (p = 0; p < pathArray.length; p++) {
  30460. indexFirst = idx[p] * 3;
  30461. if (p + 1 < pathArray.length) {
  30462. indexLast = (idx[p + 1] - 1) * 3;
  30463. }
  30464. else {
  30465. indexLast = normals.length - 3;
  30466. }
  30467. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  30468. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  30469. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  30470. normals[indexLast] = normals[indexFirst];
  30471. normals[indexLast + 1] = normals[indexFirst + 1];
  30472. normals[indexLast + 2] = normals[indexFirst + 2];
  30473. }
  30474. }
  30475. // sides
  30476. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  30477. // Result
  30478. var vertexData = new VertexData();
  30479. vertexData.indices = indices;
  30480. vertexData.positions = positions;
  30481. vertexData.normals = normals;
  30482. vertexData.uvs = uvs;
  30483. if (closePath) {
  30484. vertexData._idx = idx;
  30485. }
  30486. return vertexData;
  30487. };
  30488. VertexData.CreateBox = function (options) {
  30489. var normalsSource = [
  30490. new BABYLON.Vector3(0, 0, 1),
  30491. new BABYLON.Vector3(0, 0, -1),
  30492. new BABYLON.Vector3(1, 0, 0),
  30493. new BABYLON.Vector3(-1, 0, 0),
  30494. new BABYLON.Vector3(0, 1, 0),
  30495. new BABYLON.Vector3(0, -1, 0)
  30496. ];
  30497. var indices = [];
  30498. var positions = [];
  30499. var normals = [];
  30500. var uvs = [];
  30501. var width = options.width || options.size || 1;
  30502. var height = options.height || options.size || 1;
  30503. var depth = options.depth || options.size || 1;
  30504. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30505. var faceUV = options.faceUV || new Array(6);
  30506. var faceColors = options.faceColors;
  30507. var colors = [];
  30508. // default face colors and UV if undefined
  30509. for (var f = 0; f < 6; f++) {
  30510. if (faceUV[f] === undefined) {
  30511. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  30512. }
  30513. if (faceColors && faceColors[f] === undefined) {
  30514. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  30515. }
  30516. }
  30517. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  30518. // Create each face in turn.
  30519. for (var index = 0; index < normalsSource.length; index++) {
  30520. var normal = normalsSource[index];
  30521. // Get two vectors perpendicular to the face normal and to each other.
  30522. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  30523. var side2 = BABYLON.Vector3.Cross(normal, side1);
  30524. // Six indices (two triangles) per face.
  30525. var verticesLength = positions.length / 3;
  30526. indices.push(verticesLength);
  30527. indices.push(verticesLength + 1);
  30528. indices.push(verticesLength + 2);
  30529. indices.push(verticesLength);
  30530. indices.push(verticesLength + 2);
  30531. indices.push(verticesLength + 3);
  30532. // Four vertices per face.
  30533. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  30534. positions.push(vertex.x, vertex.y, vertex.z);
  30535. normals.push(normal.x, normal.y, normal.z);
  30536. uvs.push(faceUV[index].z, faceUV[index].w);
  30537. if (faceColors) {
  30538. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  30539. }
  30540. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  30541. positions.push(vertex.x, vertex.y, vertex.z);
  30542. normals.push(normal.x, normal.y, normal.z);
  30543. uvs.push(faceUV[index].x, faceUV[index].w);
  30544. if (faceColors) {
  30545. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  30546. }
  30547. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  30548. positions.push(vertex.x, vertex.y, vertex.z);
  30549. normals.push(normal.x, normal.y, normal.z);
  30550. uvs.push(faceUV[index].x, faceUV[index].y);
  30551. if (faceColors) {
  30552. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  30553. }
  30554. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  30555. positions.push(vertex.x, vertex.y, vertex.z);
  30556. normals.push(normal.x, normal.y, normal.z);
  30557. uvs.push(faceUV[index].z, faceUV[index].y);
  30558. if (faceColors) {
  30559. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  30560. }
  30561. }
  30562. // sides
  30563. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  30564. // Result
  30565. var vertexData = new VertexData();
  30566. vertexData.indices = indices;
  30567. vertexData.positions = positions;
  30568. vertexData.normals = normals;
  30569. vertexData.uvs = uvs;
  30570. if (faceColors) {
  30571. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  30572. vertexData.colors = totalColors;
  30573. }
  30574. return vertexData;
  30575. };
  30576. VertexData.CreateSphere = function (options) {
  30577. var segments = options.segments || 32;
  30578. var diameterX = options.diameterX || options.diameter || 1;
  30579. var diameterY = options.diameterY || options.diameter || 1;
  30580. var diameterZ = options.diameterZ || options.diameter || 1;
  30581. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  30582. var slice = (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  30583. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30584. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  30585. var totalZRotationSteps = 2 + segments;
  30586. var totalYRotationSteps = 2 * totalZRotationSteps;
  30587. var indices = [];
  30588. var positions = [];
  30589. var normals = [];
  30590. var uvs = [];
  30591. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  30592. var normalizedZ = zRotationStep / totalZRotationSteps;
  30593. var angleZ = normalizedZ * Math.PI * slice;
  30594. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  30595. var normalizedY = yRotationStep / totalYRotationSteps;
  30596. var angleY = normalizedY * Math.PI * 2 * arc;
  30597. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  30598. var rotationY = BABYLON.Matrix.RotationY(angleY);
  30599. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  30600. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  30601. var vertex = complete.multiply(radius);
  30602. var normal = complete.divide(radius).normalize();
  30603. positions.push(vertex.x, vertex.y, vertex.z);
  30604. normals.push(normal.x, normal.y, normal.z);
  30605. uvs.push(normalizedY, normalizedZ);
  30606. }
  30607. if (zRotationStep > 0) {
  30608. var verticesCount = positions.length / 3;
  30609. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  30610. indices.push((firstIndex));
  30611. indices.push((firstIndex + 1));
  30612. indices.push(firstIndex + totalYRotationSteps + 1);
  30613. indices.push((firstIndex + totalYRotationSteps + 1));
  30614. indices.push((firstIndex + 1));
  30615. indices.push((firstIndex + totalYRotationSteps + 2));
  30616. }
  30617. }
  30618. }
  30619. // Sides
  30620. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  30621. // Result
  30622. var vertexData = new VertexData();
  30623. vertexData.indices = indices;
  30624. vertexData.positions = positions;
  30625. vertexData.normals = normals;
  30626. vertexData.uvs = uvs;
  30627. return vertexData;
  30628. };
  30629. // Cylinder and cone
  30630. VertexData.CreateCylinder = function (options) {
  30631. var height = options.height || 2;
  30632. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  30633. var diameterBottom = options.diameterBottom || options.diameter || 1;
  30634. var tessellation = options.tessellation || 24;
  30635. var subdivisions = options.subdivisions || 1;
  30636. var hasRings = options.hasRings;
  30637. var enclose = options.enclose;
  30638. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  30639. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30640. var faceUV = options.faceUV || new Array(3);
  30641. var faceColors = options.faceColors;
  30642. // default face colors and UV if undefined
  30643. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  30644. var ringNb = (hasRings) ? subdivisions : 1;
  30645. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  30646. var f;
  30647. for (f = 0; f < surfaceNb; f++) {
  30648. if (faceColors && faceColors[f] === undefined) {
  30649. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  30650. }
  30651. }
  30652. for (f = 0; f < surfaceNb; f++) {
  30653. if (faceUV && faceUV[f] === undefined) {
  30654. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  30655. }
  30656. }
  30657. var indices = [];
  30658. var positions = [];
  30659. var normals = [];
  30660. var uvs = [];
  30661. var colors = [];
  30662. var angle_step = Math.PI * 2 * arc / tessellation;
  30663. var angle;
  30664. var h;
  30665. var radius;
  30666. var tan = (diameterBottom - diameterTop) / 2 / height;
  30667. var ringVertex = BABYLON.Vector3.Zero();
  30668. var ringNormal = BABYLON.Vector3.Zero();
  30669. var ringFirstVertex = BABYLON.Vector3.Zero();
  30670. var ringFirstNormal = BABYLON.Vector3.Zero();
  30671. var quadNormal = BABYLON.Vector3.Zero();
  30672. var Y = BABYLON.Axis.Y;
  30673. // positions, normals, uvs
  30674. var i;
  30675. var j;
  30676. var r;
  30677. var ringIdx = 1;
  30678. var s = 1; // surface index
  30679. var cs = 0;
  30680. var v = 0;
  30681. for (i = 0; i <= subdivisions; i++) {
  30682. h = i / subdivisions;
  30683. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  30684. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  30685. for (r = 0; r < ringIdx; r++) {
  30686. if (hasRings) {
  30687. s += r;
  30688. }
  30689. if (enclose) {
  30690. s += 2 * r;
  30691. }
  30692. for (j = 0; j <= tessellation; j++) {
  30693. angle = j * angle_step;
  30694. // position
  30695. ringVertex.x = Math.cos(-angle) * radius;
  30696. ringVertex.y = -height / 2 + h * height;
  30697. ringVertex.z = Math.sin(-angle) * radius;
  30698. // normal
  30699. if (diameterTop === 0 && i === subdivisions) {
  30700. // if no top cap, reuse former normals
  30701. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  30702. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  30703. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  30704. }
  30705. else {
  30706. ringNormal.x = ringVertex.x;
  30707. ringNormal.z = ringVertex.z;
  30708. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  30709. ringNormal.normalize();
  30710. }
  30711. // keep first ring vertex values for enclose
  30712. if (j === 0) {
  30713. ringFirstVertex.copyFrom(ringVertex);
  30714. ringFirstNormal.copyFrom(ringNormal);
  30715. }
  30716. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  30717. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  30718. if (hasRings) {
  30719. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  30720. }
  30721. else {
  30722. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  30723. }
  30724. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  30725. if (faceColors) {
  30726. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  30727. }
  30728. }
  30729. // if enclose, add four vertices and their dedicated normals
  30730. if (arc !== 1 && enclose) {
  30731. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  30732. positions.push(0, ringVertex.y, 0);
  30733. positions.push(0, ringVertex.y, 0);
  30734. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  30735. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  30736. quadNormal.normalize();
  30737. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  30738. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  30739. quadNormal.normalize();
  30740. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  30741. if (hasRings) {
  30742. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  30743. }
  30744. else {
  30745. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  30746. }
  30747. uvs.push(faceUV[s + 1].x, v);
  30748. uvs.push(faceUV[s + 1].z, v);
  30749. if (hasRings) {
  30750. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  30751. }
  30752. else {
  30753. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  30754. }
  30755. uvs.push(faceUV[s + 2].x, v);
  30756. uvs.push(faceUV[s + 2].z, v);
  30757. if (faceColors) {
  30758. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  30759. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  30760. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  30761. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  30762. }
  30763. }
  30764. if (cs !== s) {
  30765. cs = s;
  30766. }
  30767. }
  30768. }
  30769. // indices
  30770. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  30771. var s;
  30772. i = 0;
  30773. for (s = 0; s < subdivisions; s++) {
  30774. for (j = 0; j < tessellation; j++) {
  30775. var i0 = i * (e + 1) + j;
  30776. var i1 = (i + 1) * (e + 1) + j;
  30777. var i2 = i * (e + 1) + (j + 1);
  30778. var i3 = (i + 1) * (e + 1) + (j + 1);
  30779. indices.push(i0, i1, i2);
  30780. indices.push(i3, i2, i1);
  30781. }
  30782. if (arc !== 1 && enclose) {
  30783. indices.push(i0 + 2, i1 + 2, i2 + 2);
  30784. indices.push(i3 + 2, i2 + 2, i1 + 2);
  30785. indices.push(i0 + 4, i1 + 4, i2 + 4);
  30786. indices.push(i3 + 4, i2 + 4, i1 + 4);
  30787. }
  30788. i = (hasRings) ? (i + 2) : (i + 1);
  30789. }
  30790. // Caps
  30791. var createCylinderCap = function (isTop) {
  30792. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  30793. if (radius === 0) {
  30794. return;
  30795. }
  30796. // Cap positions, normals & uvs
  30797. var angle;
  30798. var circleVector;
  30799. var i;
  30800. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  30801. var c;
  30802. if (faceColors) {
  30803. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  30804. }
  30805. // cap center
  30806. var vbase = positions.length / 3;
  30807. var offset = isTop ? height / 2 : -height / 2;
  30808. var center = new BABYLON.Vector3(0, offset, 0);
  30809. positions.push(center.x, center.y, center.z);
  30810. normals.push(0, isTop ? 1 : -1, 0);
  30811. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  30812. if (faceColors) {
  30813. colors.push(c.r, c.g, c.b, c.a);
  30814. }
  30815. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  30816. for (i = 0; i <= tessellation; i++) {
  30817. angle = Math.PI * 2 * i * arc / tessellation;
  30818. var cos = Math.cos(-angle);
  30819. var sin = Math.sin(-angle);
  30820. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  30821. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  30822. positions.push(circleVector.x, circleVector.y, circleVector.z);
  30823. normals.push(0, isTop ? 1 : -1, 0);
  30824. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  30825. if (faceColors) {
  30826. colors.push(c.r, c.g, c.b, c.a);
  30827. }
  30828. }
  30829. // Cap indices
  30830. for (i = 0; i < tessellation; i++) {
  30831. if (!isTop) {
  30832. indices.push(vbase);
  30833. indices.push(vbase + (i + 1));
  30834. indices.push(vbase + (i + 2));
  30835. }
  30836. else {
  30837. indices.push(vbase);
  30838. indices.push(vbase + (i + 2));
  30839. indices.push(vbase + (i + 1));
  30840. }
  30841. }
  30842. };
  30843. // add caps to geometry
  30844. createCylinderCap(false);
  30845. createCylinderCap(true);
  30846. // Sides
  30847. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  30848. var vertexData = new VertexData();
  30849. vertexData.indices = indices;
  30850. vertexData.positions = positions;
  30851. vertexData.normals = normals;
  30852. vertexData.uvs = uvs;
  30853. if (faceColors) {
  30854. vertexData.colors = colors;
  30855. }
  30856. return vertexData;
  30857. };
  30858. VertexData.CreateTorus = function (options) {
  30859. var indices = [];
  30860. var positions = [];
  30861. var normals = [];
  30862. var uvs = [];
  30863. var diameter = options.diameter || 1;
  30864. var thickness = options.thickness || 0.5;
  30865. var tessellation = options.tessellation || 16;
  30866. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30867. var stride = tessellation + 1;
  30868. for (var i = 0; i <= tessellation; i++) {
  30869. var u = i / tessellation;
  30870. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  30871. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  30872. for (var j = 0; j <= tessellation; j++) {
  30873. var v = 1 - j / tessellation;
  30874. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  30875. var dx = Math.cos(innerAngle);
  30876. var dy = Math.sin(innerAngle);
  30877. // Create a vertex.
  30878. var normal = new BABYLON.Vector3(dx, dy, 0);
  30879. var position = normal.scale(thickness / 2);
  30880. var textureCoordinate = new BABYLON.Vector2(u, v);
  30881. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  30882. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  30883. positions.push(position.x, position.y, position.z);
  30884. normals.push(normal.x, normal.y, normal.z);
  30885. uvs.push(textureCoordinate.x, textureCoordinate.y);
  30886. // And create indices for two triangles.
  30887. var nextI = (i + 1) % stride;
  30888. var nextJ = (j + 1) % stride;
  30889. indices.push(i * stride + j);
  30890. indices.push(i * stride + nextJ);
  30891. indices.push(nextI * stride + j);
  30892. indices.push(i * stride + nextJ);
  30893. indices.push(nextI * stride + nextJ);
  30894. indices.push(nextI * stride + j);
  30895. }
  30896. }
  30897. // Sides
  30898. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  30899. // Result
  30900. var vertexData = new VertexData();
  30901. vertexData.indices = indices;
  30902. vertexData.positions = positions;
  30903. vertexData.normals = normals;
  30904. vertexData.uvs = uvs;
  30905. return vertexData;
  30906. };
  30907. VertexData.CreateLineSystem = function (options) {
  30908. var indices = [];
  30909. var positions = [];
  30910. var lines = options.lines;
  30911. var idx = 0;
  30912. for (var l = 0; l < lines.length; l++) {
  30913. var points = lines[l];
  30914. for (var index = 0; index < points.length; index++) {
  30915. positions.push(points[index].x, points[index].y, points[index].z);
  30916. if (index > 0) {
  30917. indices.push(idx - 1);
  30918. indices.push(idx);
  30919. }
  30920. idx++;
  30921. }
  30922. }
  30923. var vertexData = new VertexData();
  30924. vertexData.indices = indices;
  30925. vertexData.positions = positions;
  30926. return vertexData;
  30927. };
  30928. VertexData.CreateDashedLines = function (options) {
  30929. var dashSize = options.dashSize || 3;
  30930. var gapSize = options.gapSize || 1;
  30931. var dashNb = options.dashNb || 200;
  30932. var points = options.points;
  30933. var positions = new Array();
  30934. var indices = new Array();
  30935. var curvect = BABYLON.Vector3.Zero();
  30936. var lg = 0;
  30937. var nb = 0;
  30938. var shft = 0;
  30939. var dashshft = 0;
  30940. var curshft = 0;
  30941. var idx = 0;
  30942. var i = 0;
  30943. for (i = 0; i < points.length - 1; i++) {
  30944. points[i + 1].subtractToRef(points[i], curvect);
  30945. lg += curvect.length();
  30946. }
  30947. shft = lg / dashNb;
  30948. dashshft = dashSize * shft / (dashSize + gapSize);
  30949. for (i = 0; i < points.length - 1; i++) {
  30950. points[i + 1].subtractToRef(points[i], curvect);
  30951. nb = Math.floor(curvect.length() / shft);
  30952. curvect.normalize();
  30953. for (var j = 0; j < nb; j++) {
  30954. curshft = shft * j;
  30955. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  30956. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  30957. indices.push(idx, idx + 1);
  30958. idx += 2;
  30959. }
  30960. }
  30961. // Result
  30962. var vertexData = new VertexData();
  30963. vertexData.positions = positions;
  30964. vertexData.indices = indices;
  30965. return vertexData;
  30966. };
  30967. VertexData.CreateGround = function (options) {
  30968. var indices = [];
  30969. var positions = [];
  30970. var normals = [];
  30971. var uvs = [];
  30972. var row, col;
  30973. var width = options.width || 1;
  30974. var height = options.height || 1;
  30975. var subdivisions = options.subdivisions || 1;
  30976. for (row = 0; row <= subdivisions; row++) {
  30977. for (col = 0; col <= subdivisions; col++) {
  30978. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  30979. var normal = new BABYLON.Vector3(0, 1.0, 0);
  30980. positions.push(position.x, position.y, position.z);
  30981. normals.push(normal.x, normal.y, normal.z);
  30982. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  30983. }
  30984. }
  30985. for (row = 0; row < subdivisions; row++) {
  30986. for (col = 0; col < subdivisions; col++) {
  30987. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  30988. indices.push(col + 1 + row * (subdivisions + 1));
  30989. indices.push(col + row * (subdivisions + 1));
  30990. indices.push(col + (row + 1) * (subdivisions + 1));
  30991. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  30992. indices.push(col + row * (subdivisions + 1));
  30993. }
  30994. }
  30995. // Result
  30996. var vertexData = new VertexData();
  30997. vertexData.indices = indices;
  30998. vertexData.positions = positions;
  30999. vertexData.normals = normals;
  31000. vertexData.uvs = uvs;
  31001. return vertexData;
  31002. };
  31003. VertexData.CreateTiledGround = function (options) {
  31004. var xmin = options.xmin || -1.0;
  31005. var zmin = options.zmin || -1.0;
  31006. var xmax = options.xmax || 1.0;
  31007. var zmax = options.zmax || 1.0;
  31008. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  31009. var precision = options.precision || { w: 1, h: 1 };
  31010. var indices = [];
  31011. var positions = [];
  31012. var normals = [];
  31013. var uvs = [];
  31014. var row, col, tileRow, tileCol;
  31015. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  31016. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  31017. precision.w = (precision.w < 1) ? 1 : precision.w;
  31018. precision.h = (precision.h < 1) ? 1 : precision.h;
  31019. var tileSize = {
  31020. 'w': (xmax - xmin) / subdivisions.w,
  31021. 'h': (zmax - zmin) / subdivisions.h
  31022. };
  31023. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  31024. // Indices
  31025. var base = positions.length / 3;
  31026. var rowLength = precision.w + 1;
  31027. for (row = 0; row < precision.h; row++) {
  31028. for (col = 0; col < precision.w; col++) {
  31029. var square = [
  31030. base + col + row * rowLength,
  31031. base + (col + 1) + row * rowLength,
  31032. base + (col + 1) + (row + 1) * rowLength,
  31033. base + col + (row + 1) * rowLength
  31034. ];
  31035. indices.push(square[1]);
  31036. indices.push(square[2]);
  31037. indices.push(square[3]);
  31038. indices.push(square[0]);
  31039. indices.push(square[1]);
  31040. indices.push(square[3]);
  31041. }
  31042. }
  31043. // Position, normals and uvs
  31044. var position = BABYLON.Vector3.Zero();
  31045. var normal = new BABYLON.Vector3(0, 1.0, 0);
  31046. for (row = 0; row <= precision.h; row++) {
  31047. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  31048. for (col = 0; col <= precision.w; col++) {
  31049. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  31050. position.y = 0;
  31051. positions.push(position.x, position.y, position.z);
  31052. normals.push(normal.x, normal.y, normal.z);
  31053. uvs.push(col / precision.w, row / precision.h);
  31054. }
  31055. }
  31056. }
  31057. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  31058. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  31059. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  31060. }
  31061. }
  31062. // Result
  31063. var vertexData = new VertexData();
  31064. vertexData.indices = indices;
  31065. vertexData.positions = positions;
  31066. vertexData.normals = normals;
  31067. vertexData.uvs = uvs;
  31068. return vertexData;
  31069. };
  31070. VertexData.CreateGroundFromHeightMap = function (options) {
  31071. var indices = [];
  31072. var positions = [];
  31073. var normals = [];
  31074. var uvs = [];
  31075. var row, col;
  31076. // Vertices
  31077. for (row = 0; row <= options.subdivisions; row++) {
  31078. for (col = 0; col <= options.subdivisions; col++) {
  31079. 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));
  31080. // Compute height
  31081. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  31082. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  31083. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  31084. var r = options.buffer[pos] / 255.0;
  31085. var g = options.buffer[pos + 1] / 255.0;
  31086. var b = options.buffer[pos + 2] / 255.0;
  31087. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  31088. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  31089. // Add vertex
  31090. positions.push(position.x, position.y, position.z);
  31091. normals.push(0, 0, 0);
  31092. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  31093. }
  31094. }
  31095. // Indices
  31096. for (row = 0; row < options.subdivisions; row++) {
  31097. for (col = 0; col < options.subdivisions; col++) {
  31098. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  31099. indices.push(col + 1 + row * (options.subdivisions + 1));
  31100. indices.push(col + row * (options.subdivisions + 1));
  31101. indices.push(col + (row + 1) * (options.subdivisions + 1));
  31102. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  31103. indices.push(col + row * (options.subdivisions + 1));
  31104. }
  31105. }
  31106. // Normals
  31107. VertexData.ComputeNormals(positions, indices, normals);
  31108. // Result
  31109. var vertexData = new VertexData();
  31110. vertexData.indices = indices;
  31111. vertexData.positions = positions;
  31112. vertexData.normals = normals;
  31113. vertexData.uvs = uvs;
  31114. return vertexData;
  31115. };
  31116. VertexData.CreatePlane = function (options) {
  31117. var indices = [];
  31118. var positions = [];
  31119. var normals = [];
  31120. var uvs = [];
  31121. var width = options.width || options.size || 1;
  31122. var height = options.height || options.size || 1;
  31123. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31124. // Vertices
  31125. var halfWidth = width / 2.0;
  31126. var halfHeight = height / 2.0;
  31127. positions.push(-halfWidth, -halfHeight, 0);
  31128. normals.push(0, 0, -1.0);
  31129. uvs.push(0.0, 0.0);
  31130. positions.push(halfWidth, -halfHeight, 0);
  31131. normals.push(0, 0, -1.0);
  31132. uvs.push(1.0, 0.0);
  31133. positions.push(halfWidth, halfHeight, 0);
  31134. normals.push(0, 0, -1.0);
  31135. uvs.push(1.0, 1.0);
  31136. positions.push(-halfWidth, halfHeight, 0);
  31137. normals.push(0, 0, -1.0);
  31138. uvs.push(0.0, 1.0);
  31139. // Indices
  31140. indices.push(0);
  31141. indices.push(1);
  31142. indices.push(2);
  31143. indices.push(0);
  31144. indices.push(2);
  31145. indices.push(3);
  31146. // Sides
  31147. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  31148. // Result
  31149. var vertexData = new VertexData();
  31150. vertexData.indices = indices;
  31151. vertexData.positions = positions;
  31152. vertexData.normals = normals;
  31153. vertexData.uvs = uvs;
  31154. return vertexData;
  31155. };
  31156. VertexData.CreateDisc = function (options) {
  31157. var positions = [];
  31158. var indices = [];
  31159. var normals = [];
  31160. var uvs = [];
  31161. var radius = options.radius || 0.5;
  31162. var tessellation = options.tessellation || 64;
  31163. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  31164. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31165. // positions and uvs
  31166. positions.push(0, 0, 0); // disc center first
  31167. uvs.push(0.5, 0.5);
  31168. var theta = Math.PI * 2 * arc;
  31169. var step = theta / tessellation;
  31170. for (var a = 0; a < theta; a += step) {
  31171. var x = Math.cos(a);
  31172. var y = Math.sin(a);
  31173. var u = (x + 1) / 2;
  31174. var v = (1 - y) / 2;
  31175. positions.push(radius * x, radius * y, 0);
  31176. uvs.push(u, v);
  31177. }
  31178. if (arc === 1) {
  31179. positions.push(positions[3], positions[4], positions[5]); // close the circle
  31180. uvs.push(uvs[2], uvs[3]);
  31181. }
  31182. //indices
  31183. var vertexNb = positions.length / 3;
  31184. for (var i = 1; i < vertexNb - 1; i++) {
  31185. indices.push(i + 1, 0, i);
  31186. }
  31187. // result
  31188. VertexData.ComputeNormals(positions, indices, normals);
  31189. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  31190. var vertexData = new VertexData();
  31191. vertexData.indices = indices;
  31192. vertexData.positions = positions;
  31193. vertexData.normals = normals;
  31194. vertexData.uvs = uvs;
  31195. return vertexData;
  31196. };
  31197. VertexData.CreateIcoSphere = function (options) {
  31198. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31199. var radius = options.radius || 1;
  31200. var flat = (options.flat === undefined) ? true : options.flat;
  31201. var subdivisions = options.subdivisions || 4;
  31202. var radiusX = options.radiusX || radius;
  31203. var radiusY = options.radiusY || radius;
  31204. var radiusZ = options.radiusZ || radius;
  31205. var t = (1 + Math.sqrt(5)) / 2;
  31206. // 12 vertex x,y,z
  31207. var ico_vertices = [
  31208. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  31209. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  31210. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  31211. ];
  31212. // index of 3 vertex makes a face of icopshere
  31213. var ico_indices = [
  31214. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  31215. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  31216. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  31217. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  31218. ];
  31219. // vertex for uv have aliased position, not for UV
  31220. var vertices_unalias_id = [
  31221. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  31222. // vertex alias
  31223. 0,
  31224. 2,
  31225. 3,
  31226. 3,
  31227. 3,
  31228. 4,
  31229. 7,
  31230. 8,
  31231. 9,
  31232. 9,
  31233. 10,
  31234. 11 // 23: B + 12
  31235. ];
  31236. // uv as integer step (not pixels !)
  31237. var ico_vertexuv = [
  31238. 5, 1, 3, 1, 6, 4, 0, 0,
  31239. 5, 3, 4, 2, 2, 2, 4, 0,
  31240. 2, 0, 1, 1, 6, 0, 6, 2,
  31241. // vertex alias (for same vertex on different faces)
  31242. 0, 4,
  31243. 3, 3,
  31244. 4, 4,
  31245. 3, 1,
  31246. 4, 2,
  31247. 4, 4,
  31248. 0, 2,
  31249. 1, 1,
  31250. 2, 2,
  31251. 3, 3,
  31252. 1, 3,
  31253. 2, 4 // 23: B + 12
  31254. ];
  31255. // Vertices[0, 1, ...9, A, B] : position on UV plane
  31256. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  31257. // First island of uv mapping
  31258. // v = 4h 3+ 2
  31259. // v = 3h 9+ 4
  31260. // v = 2h 9+ 5 B
  31261. // v = 1h 9 1 0
  31262. // v = 0h 3 8 7 A
  31263. // u = 0 1 2 3 4 5 6 *a
  31264. // Second island of uv mapping
  31265. // v = 4h 0+ B+ 4+
  31266. // v = 3h A+ 2+
  31267. // v = 2h 7+ 6 3+
  31268. // v = 1h 8+ 3+
  31269. // v = 0h
  31270. // u = 0 1 2 3 4 5 6 *a
  31271. // Face layout on texture UV mapping
  31272. // ============
  31273. // \ 4 /\ 16 / ======
  31274. // \ / \ / /\ 11 /
  31275. // \/ 7 \/ / \ /
  31276. // ======= / 10 \/
  31277. // /\ 17 /\ =======
  31278. // / \ / \ \ 15 /\
  31279. // / 8 \/ 12 \ \ / \
  31280. // ============ \/ 6 \
  31281. // \ 18 /\ ============
  31282. // \ / \ \ 5 /\ 0 /
  31283. // \/ 13 \ \ / \ /
  31284. // ======= \/ 1 \/
  31285. // =============
  31286. // /\ 19 /\ 2 /\
  31287. // / \ / \ / \
  31288. // / 14 \/ 9 \/ 3 \
  31289. // ===================
  31290. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  31291. var ustep = 138 / 1024;
  31292. var vstep = 239 / 1024;
  31293. var uoffset = 60 / 1024;
  31294. var voffset = 26 / 1024;
  31295. // Second island should have margin, not to touch the first island
  31296. // avoid any borderline artefact in pixel rounding
  31297. var island_u_offset = -40 / 1024;
  31298. var island_v_offset = +20 / 1024;
  31299. // face is either island 0 or 1 :
  31300. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  31301. var island = [
  31302. 0, 0, 0, 0, 1,
  31303. 0, 0, 1, 1, 0,
  31304. 0, 0, 1, 1, 0,
  31305. 0, 1, 1, 1, 0 // 15 - 19
  31306. ];
  31307. var indices = [];
  31308. var positions = [];
  31309. var normals = [];
  31310. var uvs = [];
  31311. var current_indice = 0;
  31312. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  31313. var face_vertex_pos = new Array(3);
  31314. var face_vertex_uv = new Array(3);
  31315. var v012;
  31316. for (v012 = 0; v012 < 3; v012++) {
  31317. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  31318. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  31319. }
  31320. // create all with normals
  31321. for (var face = 0; face < 20; face++) {
  31322. // 3 vertex per face
  31323. for (v012 = 0; v012 < 3; v012++) {
  31324. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  31325. var v_id = ico_indices[3 * face + v012];
  31326. // vertex have 3D position (x,y,z)
  31327. 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]);
  31328. // Normalize to get normal, then scale to radius
  31329. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  31330. // uv Coordinates from vertex ID
  31331. 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);
  31332. }
  31333. // Subdivide the face (interpolate pos, norm, uv)
  31334. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  31335. // - norm is linear interpolation of vertex corner normal
  31336. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  31337. // - uv is linear interpolation
  31338. //
  31339. // Topology is as below for sub-divide by 2
  31340. // vertex shown as v0,v1,v2
  31341. // interp index is i1 to progress in range [v0,v1[
  31342. // interp index is i2 to progress in range [v0,v2[
  31343. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  31344. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  31345. //
  31346. //
  31347. // i2 v2
  31348. // ^ ^
  31349. // / / \
  31350. // / / \
  31351. // / / \
  31352. // / / (0,1) \
  31353. // / #---------\
  31354. // / / \ (0,0)'/ \
  31355. // / / \ / \
  31356. // / / \ / \
  31357. // / / (0,0) \ / (1,0) \
  31358. // / #---------#---------\
  31359. // v0 v1
  31360. //
  31361. // --------------------> i1
  31362. //
  31363. // interp of (i1,i2):
  31364. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  31365. // along i1 : lerp(x0,x1, i1/(S-i2))
  31366. //
  31367. // centroid of triangle is needed to get help normal computation
  31368. // (c1,c2) are used for centroid location
  31369. var interp_vertex = function (i1, i2, c1, c2) {
  31370. // vertex is interpolated from
  31371. // - face_vertex_pos[0..2]
  31372. // - face_vertex_uv[0..2]
  31373. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  31374. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  31375. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  31376. pos_interp.normalize();
  31377. var vertex_normal;
  31378. if (flat) {
  31379. // in flat mode, recalculate normal as face centroid normal
  31380. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  31381. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  31382. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  31383. }
  31384. else {
  31385. // in smooth mode, recalculate normal from each single vertex position
  31386. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  31387. }
  31388. // Vertex normal need correction due to X,Y,Z radius scaling
  31389. vertex_normal.x /= radiusX;
  31390. vertex_normal.y /= radiusY;
  31391. vertex_normal.z /= radiusZ;
  31392. vertex_normal.normalize();
  31393. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  31394. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  31395. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  31396. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  31397. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  31398. uvs.push(uv_interp.x, uv_interp.y);
  31399. // push each vertex has member of a face
  31400. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  31401. indices.push(current_indice);
  31402. current_indice++;
  31403. };
  31404. for (var i2 = 0; i2 < subdivisions; i2++) {
  31405. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  31406. // face : (i1,i2) for /\ :
  31407. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  31408. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  31409. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  31410. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  31411. if (i1 + i2 + 1 < subdivisions) {
  31412. // face : (i1,i2)' for \/ :
  31413. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  31414. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  31415. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  31416. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  31417. }
  31418. }
  31419. }
  31420. }
  31421. // Sides
  31422. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  31423. // Result
  31424. var vertexData = new VertexData();
  31425. vertexData.indices = indices;
  31426. vertexData.positions = positions;
  31427. vertexData.normals = normals;
  31428. vertexData.uvs = uvs;
  31429. return vertexData;
  31430. };
  31431. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  31432. VertexData.CreatePolyhedron = function (options) {
  31433. // provided polyhedron types :
  31434. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  31435. // 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)
  31436. var polyhedra = [];
  31437. 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]] };
  31438. 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]] };
  31439. polyhedra[2] = {
  31440. 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]],
  31441. 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]]
  31442. };
  31443. polyhedra[3] = {
  31444. 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]],
  31445. 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]]
  31446. };
  31447. polyhedra[4] = {
  31448. 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]],
  31449. 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]]
  31450. };
  31451. 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]] };
  31452. 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]] };
  31453. 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]] };
  31454. 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]] };
  31455. 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]] };
  31456. 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]] };
  31457. 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]] };
  31458. 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]] };
  31459. 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]] };
  31460. polyhedra[14] = {
  31461. 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]],
  31462. 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]]
  31463. };
  31464. var type = (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  31465. var size = options.size;
  31466. var sizeX = options.sizeX || size || 1;
  31467. var sizeY = options.sizeY || size || 1;
  31468. var sizeZ = options.sizeZ || size || 1;
  31469. var data = options.custom || polyhedra[type];
  31470. var nbfaces = data.face.length;
  31471. var faceUV = options.faceUV || new Array(nbfaces);
  31472. var faceColors = options.faceColors;
  31473. var flat = (options.flat === undefined) ? true : options.flat;
  31474. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31475. var positions = [];
  31476. var indices = [];
  31477. var normals = [];
  31478. var uvs = [];
  31479. var colors = [];
  31480. var index = 0;
  31481. var faceIdx = 0; // face cursor in the array "indexes"
  31482. var indexes = [];
  31483. var i = 0;
  31484. var f = 0;
  31485. var u, v, ang, x, y, tmp;
  31486. // default face colors and UV if undefined
  31487. if (flat) {
  31488. for (f = 0; f < nbfaces; f++) {
  31489. if (faceColors && faceColors[f] === undefined) {
  31490. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  31491. }
  31492. if (faceUV && faceUV[f] === undefined) {
  31493. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  31494. }
  31495. }
  31496. }
  31497. if (!flat) {
  31498. for (i = 0; i < data.vertex.length; i++) {
  31499. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  31500. uvs.push(0, 0);
  31501. }
  31502. for (f = 0; f < nbfaces; f++) {
  31503. for (i = 0; i < data.face[f].length - 2; i++) {
  31504. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  31505. }
  31506. }
  31507. }
  31508. else {
  31509. for (f = 0; f < nbfaces; f++) {
  31510. var fl = data.face[f].length; // number of vertices of the current face
  31511. ang = 2 * Math.PI / fl;
  31512. x = 0.5 * Math.tan(ang / 2);
  31513. y = 0.5;
  31514. // positions, uvs, colors
  31515. for (i = 0; i < fl; i++) {
  31516. // positions
  31517. 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);
  31518. indexes.push(index);
  31519. index++;
  31520. // uvs
  31521. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  31522. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  31523. uvs.push(u, v);
  31524. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  31525. y = x * Math.sin(ang) + y * Math.cos(ang);
  31526. x = tmp;
  31527. // colors
  31528. if (faceColors) {
  31529. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  31530. }
  31531. }
  31532. // indices from indexes
  31533. for (i = 0; i < fl - 2; i++) {
  31534. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  31535. }
  31536. faceIdx += fl;
  31537. }
  31538. }
  31539. VertexData.ComputeNormals(positions, indices, normals);
  31540. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  31541. var vertexData = new VertexData();
  31542. vertexData.positions = positions;
  31543. vertexData.indices = indices;
  31544. vertexData.normals = normals;
  31545. vertexData.uvs = uvs;
  31546. if (faceColors && flat) {
  31547. vertexData.colors = colors;
  31548. }
  31549. return vertexData;
  31550. };
  31551. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  31552. VertexData.CreateTorusKnot = function (options) {
  31553. var indices = [];
  31554. var positions = [];
  31555. var normals = [];
  31556. var uvs = [];
  31557. var radius = options.radius || 2;
  31558. var tube = options.tube || 0.5;
  31559. var radialSegments = options.radialSegments || 32;
  31560. var tubularSegments = options.tubularSegments || 32;
  31561. var p = options.p || 2;
  31562. var q = options.q || 3;
  31563. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31564. // Helper
  31565. var getPos = function (angle) {
  31566. var cu = Math.cos(angle);
  31567. var su = Math.sin(angle);
  31568. var quOverP = q / p * angle;
  31569. var cs = Math.cos(quOverP);
  31570. var tx = radius * (2 + cs) * 0.5 * cu;
  31571. var ty = radius * (2 + cs) * su * 0.5;
  31572. var tz = radius * Math.sin(quOverP) * 0.5;
  31573. return new BABYLON.Vector3(tx, ty, tz);
  31574. };
  31575. // Vertices
  31576. var i;
  31577. var j;
  31578. for (i = 0; i <= radialSegments; i++) {
  31579. var modI = i % radialSegments;
  31580. var u = modI / radialSegments * 2 * p * Math.PI;
  31581. var p1 = getPos(u);
  31582. var p2 = getPos(u + 0.01);
  31583. var tang = p2.subtract(p1);
  31584. var n = p2.add(p1);
  31585. var bitan = BABYLON.Vector3.Cross(tang, n);
  31586. n = BABYLON.Vector3.Cross(bitan, tang);
  31587. bitan.normalize();
  31588. n.normalize();
  31589. for (j = 0; j < tubularSegments; j++) {
  31590. var modJ = j % tubularSegments;
  31591. var v = modJ / tubularSegments * 2 * Math.PI;
  31592. var cx = -tube * Math.cos(v);
  31593. var cy = tube * Math.sin(v);
  31594. positions.push(p1.x + cx * n.x + cy * bitan.x);
  31595. positions.push(p1.y + cx * n.y + cy * bitan.y);
  31596. positions.push(p1.z + cx * n.z + cy * bitan.z);
  31597. uvs.push(i / radialSegments);
  31598. uvs.push(j / tubularSegments);
  31599. }
  31600. }
  31601. for (i = 0; i < radialSegments; i++) {
  31602. for (j = 0; j < tubularSegments; j++) {
  31603. var jNext = (j + 1) % tubularSegments;
  31604. var a = i * tubularSegments + j;
  31605. var b = (i + 1) * tubularSegments + j;
  31606. var c = (i + 1) * tubularSegments + jNext;
  31607. var d = i * tubularSegments + jNext;
  31608. indices.push(d);
  31609. indices.push(b);
  31610. indices.push(a);
  31611. indices.push(d);
  31612. indices.push(c);
  31613. indices.push(b);
  31614. }
  31615. }
  31616. // Normals
  31617. VertexData.ComputeNormals(positions, indices, normals);
  31618. // Sides
  31619. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  31620. // Result
  31621. var vertexData = new VertexData();
  31622. vertexData.indices = indices;
  31623. vertexData.positions = positions;
  31624. vertexData.normals = normals;
  31625. vertexData.uvs = uvs;
  31626. return vertexData;
  31627. };
  31628. // Tools
  31629. /**
  31630. * @param {any} - positions (number[] or Float32Array)
  31631. * @param {any} - indices (number[] or Uint16Array)
  31632. * @param {any} - normals (number[] or Float32Array)
  31633. */
  31634. VertexData.ComputeNormals = function (positions, indices, normals) {
  31635. var index = 0;
  31636. var p1p2x = 0.0;
  31637. var p1p2y = 0.0;
  31638. var p1p2z = 0.0;
  31639. var p3p2x = 0.0;
  31640. var p3p2y = 0.0;
  31641. var p3p2z = 0.0;
  31642. var faceNormalx = 0.0;
  31643. var faceNormaly = 0.0;
  31644. var faceNormalz = 0.0;
  31645. var length = 0.0;
  31646. var i1 = 0;
  31647. var i2 = 0;
  31648. var i3 = 0;
  31649. for (index = 0; index < positions.length; index++) {
  31650. normals[index] = 0.0;
  31651. }
  31652. // indice triplet = 1 face
  31653. var nbFaces = indices.length / 3;
  31654. for (index = 0; index < nbFaces; index++) {
  31655. i1 = indices[index * 3]; // get the indexes of each vertex of the face
  31656. i2 = indices[index * 3 + 1];
  31657. i3 = indices[index * 3 + 2];
  31658. p1p2x = positions[i1 * 3] - positions[i2 * 3]; // compute two vectors per face
  31659. p1p2y = positions[i1 * 3 + 1] - positions[i2 * 3 + 1];
  31660. p1p2z = positions[i1 * 3 + 2] - positions[i2 * 3 + 2];
  31661. p3p2x = positions[i3 * 3] - positions[i2 * 3];
  31662. p3p2y = positions[i3 * 3 + 1] - positions[i2 * 3 + 1];
  31663. p3p2z = positions[i3 * 3 + 2] - positions[i2 * 3 + 2];
  31664. faceNormalx = p1p2y * p3p2z - p1p2z * p3p2y; // compute the face normal with cross product
  31665. faceNormaly = p1p2z * p3p2x - p1p2x * p3p2z;
  31666. faceNormalz = p1p2x * p3p2y - p1p2y * p3p2x;
  31667. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  31668. length = (length === 0) ? 1.0 : length;
  31669. faceNormalx /= length; // normalize this normal
  31670. faceNormaly /= length;
  31671. faceNormalz /= length;
  31672. normals[i1 * 3] += faceNormalx; // accumulate all the normals per face
  31673. normals[i1 * 3 + 1] += faceNormaly;
  31674. normals[i1 * 3 + 2] += faceNormalz;
  31675. normals[i2 * 3] += faceNormalx;
  31676. normals[i2 * 3 + 1] += faceNormaly;
  31677. normals[i2 * 3 + 2] += faceNormalz;
  31678. normals[i3 * 3] += faceNormalx;
  31679. normals[i3 * 3 + 1] += faceNormaly;
  31680. normals[i3 * 3 + 2] += faceNormalz;
  31681. }
  31682. // last normalization of each normal
  31683. for (index = 0; index < normals.length / 3; index++) {
  31684. faceNormalx = normals[index * 3];
  31685. faceNormaly = normals[index * 3 + 1];
  31686. faceNormalz = normals[index * 3 + 2];
  31687. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  31688. length = (length === 0) ? 1.0 : length;
  31689. faceNormalx /= length;
  31690. faceNormaly /= length;
  31691. faceNormalz /= length;
  31692. normals[index * 3] = faceNormalx;
  31693. normals[index * 3 + 1] = faceNormaly;
  31694. normals[index * 3 + 2] = faceNormalz;
  31695. }
  31696. };
  31697. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs) {
  31698. var li = indices.length;
  31699. var ln = normals.length;
  31700. var i;
  31701. var n;
  31702. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31703. switch (sideOrientation) {
  31704. case BABYLON.Mesh.FRONTSIDE:
  31705. // nothing changed
  31706. break;
  31707. case BABYLON.Mesh.BACKSIDE:
  31708. var tmp;
  31709. // indices
  31710. for (i = 0; i < li; i += 3) {
  31711. tmp = indices[i];
  31712. indices[i] = indices[i + 2];
  31713. indices[i + 2] = tmp;
  31714. }
  31715. // normals
  31716. for (n = 0; n < ln; n++) {
  31717. normals[n] = -normals[n];
  31718. }
  31719. break;
  31720. case BABYLON.Mesh.DOUBLESIDE:
  31721. // positions
  31722. var lp = positions.length;
  31723. var l = lp / 3;
  31724. for (var p = 0; p < lp; p++) {
  31725. positions[lp + p] = positions[p];
  31726. }
  31727. // indices
  31728. for (i = 0; i < li; i += 3) {
  31729. indices[i + li] = indices[i + 2] + l;
  31730. indices[i + 1 + li] = indices[i + 1] + l;
  31731. indices[i + 2 + li] = indices[i] + l;
  31732. }
  31733. // normals
  31734. for (n = 0; n < ln; n++) {
  31735. normals[ln + n] = -normals[n];
  31736. }
  31737. // uvs
  31738. var lu = uvs.length;
  31739. for (var u = 0; u < lu; u++) {
  31740. uvs[u + lu] = uvs[u];
  31741. }
  31742. break;
  31743. }
  31744. };
  31745. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  31746. var vertexData = new VertexData();
  31747. // positions
  31748. var positions = parsedVertexData.positions;
  31749. if (positions) {
  31750. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  31751. }
  31752. // normals
  31753. var normals = parsedVertexData.normals;
  31754. if (normals) {
  31755. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  31756. }
  31757. // uvs
  31758. var uvs = parsedVertexData.uvs;
  31759. if (uvs) {
  31760. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  31761. }
  31762. // uv2s
  31763. var uv2s = parsedVertexData.uv2s;
  31764. if (uv2s) {
  31765. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  31766. }
  31767. // uv3s
  31768. var uv3s = parsedVertexData.uv3s;
  31769. if (uv3s) {
  31770. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  31771. }
  31772. // uv4s
  31773. var uv4s = parsedVertexData.uv4s;
  31774. if (uv4s) {
  31775. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  31776. }
  31777. // uv5s
  31778. var uv5s = parsedVertexData.uv5s;
  31779. if (uv5s) {
  31780. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  31781. }
  31782. // uv6s
  31783. var uv6s = parsedVertexData.uv6s;
  31784. if (uv6s) {
  31785. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  31786. }
  31787. // colors
  31788. var colors = parsedVertexData.colors;
  31789. if (colors) {
  31790. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  31791. }
  31792. // matricesIndices
  31793. var matricesIndices = parsedVertexData.matricesIndices;
  31794. if (matricesIndices) {
  31795. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  31796. }
  31797. // matricesWeights
  31798. var matricesWeights = parsedVertexData.matricesWeights;
  31799. if (matricesWeights) {
  31800. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  31801. }
  31802. // indices
  31803. var indices = parsedVertexData.indices;
  31804. if (indices) {
  31805. vertexData.indices = indices;
  31806. }
  31807. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  31808. };
  31809. return VertexData;
  31810. })();
  31811. BABYLON.VertexData = VertexData;
  31812. })(BABYLON || (BABYLON = {}));
  31813. var BABYLON;
  31814. (function (BABYLON) {
  31815. var Tags = (function () {
  31816. function Tags() {
  31817. }
  31818. Tags.EnableFor = function (obj) {
  31819. obj._tags = obj._tags || {};
  31820. obj.hasTags = function () {
  31821. return Tags.HasTags(obj);
  31822. };
  31823. obj.addTags = function (tagsString) {
  31824. return Tags.AddTagsTo(obj, tagsString);
  31825. };
  31826. obj.removeTags = function (tagsString) {
  31827. return Tags.RemoveTagsFrom(obj, tagsString);
  31828. };
  31829. obj.matchesTagsQuery = function (tagsQuery) {
  31830. return Tags.MatchesQuery(obj, tagsQuery);
  31831. };
  31832. };
  31833. Tags.DisableFor = function (obj) {
  31834. delete obj._tags;
  31835. delete obj.hasTags;
  31836. delete obj.addTags;
  31837. delete obj.removeTags;
  31838. delete obj.matchesTagsQuery;
  31839. };
  31840. Tags.HasTags = function (obj) {
  31841. if (!obj._tags) {
  31842. return false;
  31843. }
  31844. return !BABYLON.Tools.IsEmpty(obj._tags);
  31845. };
  31846. Tags.GetTags = function (obj, asString) {
  31847. if (asString === void 0) { asString = true; }
  31848. if (!obj._tags) {
  31849. return null;
  31850. }
  31851. if (asString) {
  31852. var tagsArray = [];
  31853. for (var tag in obj._tags) {
  31854. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  31855. tagsArray.push(tag);
  31856. }
  31857. }
  31858. return tagsArray.join(" ");
  31859. }
  31860. else {
  31861. return obj._tags;
  31862. }
  31863. };
  31864. // the tags 'true' and 'false' are reserved and cannot be used as tags
  31865. // a tag cannot start with '||', '&&', and '!'
  31866. // it cannot contain whitespaces
  31867. Tags.AddTagsTo = function (obj, tagsString) {
  31868. if (!tagsString) {
  31869. return;
  31870. }
  31871. if (typeof tagsString !== "string") {
  31872. return;
  31873. }
  31874. var tags = tagsString.split(" ");
  31875. for (var t in tags) {
  31876. Tags._AddTagTo(obj, tags[t]);
  31877. }
  31878. };
  31879. Tags._AddTagTo = function (obj, tag) {
  31880. tag = tag.trim();
  31881. if (tag === "" || tag === "true" || tag === "false") {
  31882. return;
  31883. }
  31884. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  31885. return;
  31886. }
  31887. Tags.EnableFor(obj);
  31888. obj._tags[tag] = true;
  31889. };
  31890. Tags.RemoveTagsFrom = function (obj, tagsString) {
  31891. if (!Tags.HasTags(obj)) {
  31892. return;
  31893. }
  31894. var tags = tagsString.split(" ");
  31895. for (var t in tags) {
  31896. Tags._RemoveTagFrom(obj, tags[t]);
  31897. }
  31898. };
  31899. Tags._RemoveTagFrom = function (obj, tag) {
  31900. delete obj._tags[tag];
  31901. };
  31902. Tags.MatchesQuery = function (obj, tagsQuery) {
  31903. if (tagsQuery === undefined) {
  31904. return true;
  31905. }
  31906. if (tagsQuery === "") {
  31907. return Tags.HasTags(obj);
  31908. }
  31909. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  31910. };
  31911. return Tags;
  31912. })();
  31913. BABYLON.Tags = Tags;
  31914. })(BABYLON || (BABYLON = {}));
  31915. var BABYLON;
  31916. (function (BABYLON) {
  31917. var Internals;
  31918. (function (Internals) {
  31919. var AndOrNotEvaluator = (function () {
  31920. function AndOrNotEvaluator() {
  31921. }
  31922. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  31923. if (!query.match(/\([^\(\)]*\)/g)) {
  31924. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  31925. }
  31926. else {
  31927. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  31928. // remove parenthesis
  31929. r = r.slice(1, r.length - 1);
  31930. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  31931. });
  31932. }
  31933. if (query === "true") {
  31934. return true;
  31935. }
  31936. if (query === "false") {
  31937. return false;
  31938. }
  31939. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  31940. };
  31941. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  31942. evaluateCallback = evaluateCallback || (function (r) {
  31943. return r === "true" ? true : false;
  31944. });
  31945. var result;
  31946. var or = parenthesisContent.split("||");
  31947. for (var i in or) {
  31948. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  31949. var and = ori.split("&&");
  31950. if (and.length > 1) {
  31951. for (var j = 0; j < and.length; ++j) {
  31952. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  31953. if (andj !== "true" && andj !== "false") {
  31954. if (andj[0] === "!") {
  31955. result = !evaluateCallback(andj.substring(1));
  31956. }
  31957. else {
  31958. result = evaluateCallback(andj);
  31959. }
  31960. }
  31961. else {
  31962. result = andj === "true" ? true : false;
  31963. }
  31964. if (!result) {
  31965. ori = "false";
  31966. break;
  31967. }
  31968. }
  31969. }
  31970. if (result || ori === "true") {
  31971. result = true;
  31972. break;
  31973. }
  31974. // result equals false (or undefined)
  31975. if (ori !== "true" && ori !== "false") {
  31976. if (ori[0] === "!") {
  31977. result = !evaluateCallback(ori.substring(1));
  31978. }
  31979. else {
  31980. result = evaluateCallback(ori);
  31981. }
  31982. }
  31983. else {
  31984. result = ori === "true" ? true : false;
  31985. }
  31986. }
  31987. // the whole parenthesis scope is replaced by 'true' or 'false'
  31988. return result ? "true" : "false";
  31989. };
  31990. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  31991. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  31992. // remove whitespaces
  31993. r = r.replace(/[\s]/g, function () { return ""; });
  31994. return r.length % 2 ? "!" : "";
  31995. });
  31996. booleanString = booleanString.trim();
  31997. if (booleanString === "!true") {
  31998. booleanString = "false";
  31999. }
  32000. else if (booleanString === "!false") {
  32001. booleanString = "true";
  32002. }
  32003. return booleanString;
  32004. };
  32005. return AndOrNotEvaluator;
  32006. })();
  32007. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  32008. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  32009. })(BABYLON || (BABYLON = {}));
  32010. var BABYLON;
  32011. (function (BABYLON) {
  32012. var PostProcessRenderPass = (function () {
  32013. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  32014. this._enabled = true;
  32015. this._refCount = 0;
  32016. this._name = name;
  32017. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  32018. this.setRenderList(renderList);
  32019. this._renderTexture.onBeforeRenderObservable.add(beforeRender);
  32020. this._renderTexture.onAfterRenderObservable.add(afterRender);
  32021. this._scene = scene;
  32022. this._renderList = renderList;
  32023. }
  32024. // private
  32025. PostProcessRenderPass.prototype._incRefCount = function () {
  32026. if (this._refCount === 0) {
  32027. this._scene.customRenderTargets.push(this._renderTexture);
  32028. }
  32029. return ++this._refCount;
  32030. };
  32031. PostProcessRenderPass.prototype._decRefCount = function () {
  32032. this._refCount--;
  32033. if (this._refCount <= 0) {
  32034. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  32035. }
  32036. return this._refCount;
  32037. };
  32038. PostProcessRenderPass.prototype._update = function () {
  32039. this.setRenderList(this._renderList);
  32040. };
  32041. // public
  32042. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  32043. this._renderTexture.renderList = renderList;
  32044. };
  32045. PostProcessRenderPass.prototype.getRenderTexture = function () {
  32046. return this._renderTexture;
  32047. };
  32048. return PostProcessRenderPass;
  32049. })();
  32050. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  32051. })(BABYLON || (BABYLON = {}));
  32052. var BABYLON;
  32053. (function (BABYLON) {
  32054. var PostProcessRenderEffect = (function () {
  32055. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  32056. this._engine = engine;
  32057. this._name = name;
  32058. this._singleInstance = singleInstance || true;
  32059. this._getPostProcess = getPostProcess;
  32060. this._cameras = [];
  32061. this._indicesForCamera = [];
  32062. this._postProcesses = {};
  32063. this._renderPasses = {};
  32064. this._renderEffectAsPasses = {};
  32065. }
  32066. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  32067. get: function () {
  32068. for (var index in this._postProcesses) {
  32069. if (!this._postProcesses[index].isSupported) {
  32070. return false;
  32071. }
  32072. }
  32073. return true;
  32074. },
  32075. enumerable: true,
  32076. configurable: true
  32077. });
  32078. PostProcessRenderEffect.prototype._update = function () {
  32079. for (var renderPassName in this._renderPasses) {
  32080. this._renderPasses[renderPassName]._update();
  32081. }
  32082. };
  32083. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  32084. this._renderPasses[renderPass._name] = renderPass;
  32085. this._linkParameters();
  32086. };
  32087. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  32088. delete this._renderPasses[renderPass._name];
  32089. this._linkParameters();
  32090. };
  32091. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  32092. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  32093. this._linkParameters();
  32094. };
  32095. PostProcessRenderEffect.prototype.getPass = function (passName) {
  32096. for (var renderPassName in this._renderPasses) {
  32097. if (renderPassName === passName) {
  32098. return this._renderPasses[passName];
  32099. }
  32100. }
  32101. };
  32102. PostProcessRenderEffect.prototype.emptyPasses = function () {
  32103. this._renderPasses = {};
  32104. this._linkParameters();
  32105. };
  32106. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  32107. var cameraKey;
  32108. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  32109. for (var i = 0; i < _cam.length; i++) {
  32110. var camera = _cam[i];
  32111. var cameraName = camera.name;
  32112. if (this._singleInstance) {
  32113. cameraKey = 0;
  32114. }
  32115. else {
  32116. cameraKey = cameraName;
  32117. }
  32118. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  32119. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  32120. if (!this._indicesForCamera[cameraName]) {
  32121. this._indicesForCamera[cameraName] = [];
  32122. }
  32123. this._indicesForCamera[cameraName].push(index);
  32124. if (this._cameras.indexOf(camera) === -1) {
  32125. this._cameras[cameraName] = camera;
  32126. }
  32127. for (var passName in this._renderPasses) {
  32128. this._renderPasses[passName]._incRefCount();
  32129. }
  32130. }
  32131. this._linkParameters();
  32132. };
  32133. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  32134. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  32135. for (var i = 0; i < _cam.length; i++) {
  32136. var camera = _cam[i];
  32137. var cameraName = camera.name;
  32138. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  32139. var index = this._cameras.indexOf(cameraName);
  32140. this._indicesForCamera.splice(index, 1);
  32141. this._cameras.splice(index, 1);
  32142. for (var passName in this._renderPasses) {
  32143. this._renderPasses[passName]._decRefCount();
  32144. }
  32145. }
  32146. };
  32147. PostProcessRenderEffect.prototype._enable = function (cameras) {
  32148. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  32149. for (var i = 0; i < _cam.length; i++) {
  32150. var camera = _cam[i];
  32151. var cameraName = camera.name;
  32152. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  32153. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  32154. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  32155. }
  32156. }
  32157. for (var passName in this._renderPasses) {
  32158. this._renderPasses[passName]._incRefCount();
  32159. }
  32160. }
  32161. };
  32162. PostProcessRenderEffect.prototype._disable = function (cameras) {
  32163. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  32164. for (var i = 0; i < _cam.length; i++) {
  32165. var camera = _cam[i];
  32166. var cameraName = camera.Name;
  32167. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  32168. for (var passName in this._renderPasses) {
  32169. this._renderPasses[passName]._decRefCount();
  32170. }
  32171. }
  32172. };
  32173. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  32174. if (this._singleInstance) {
  32175. return this._postProcesses[0];
  32176. }
  32177. else {
  32178. return this._postProcesses[camera.name];
  32179. }
  32180. };
  32181. PostProcessRenderEffect.prototype._linkParameters = function () {
  32182. var _this = this;
  32183. for (var index in this._postProcesses) {
  32184. if (this.applyParameters) {
  32185. this.applyParameters(this._postProcesses[index]);
  32186. }
  32187. this._postProcesses[index].onBeforeRenderObservable.add(function (effect) {
  32188. _this._linkTextures(effect);
  32189. });
  32190. }
  32191. };
  32192. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  32193. for (var renderPassName in this._renderPasses) {
  32194. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  32195. }
  32196. for (var renderEffectName in this._renderEffectAsPasses) {
  32197. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  32198. }
  32199. };
  32200. return PostProcessRenderEffect;
  32201. })();
  32202. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  32203. })(BABYLON || (BABYLON = {}));
  32204. var BABYLON;
  32205. (function (BABYLON) {
  32206. var PostProcessRenderPipeline = (function () {
  32207. function PostProcessRenderPipeline(engine, name) {
  32208. this._engine = engine;
  32209. this._name = name;
  32210. this._renderEffects = {};
  32211. this._renderEffectsForIsolatedPass = {};
  32212. this._cameras = [];
  32213. }
  32214. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  32215. get: function () {
  32216. for (var renderEffectName in this._renderEffects) {
  32217. if (!this._renderEffects[renderEffectName].isSupported) {
  32218. return false;
  32219. }
  32220. }
  32221. return true;
  32222. },
  32223. enumerable: true,
  32224. configurable: true
  32225. });
  32226. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  32227. this._renderEffects[renderEffect._name] = renderEffect;
  32228. };
  32229. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  32230. var renderEffects = this._renderEffects[renderEffectName];
  32231. if (!renderEffects) {
  32232. return;
  32233. }
  32234. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  32235. };
  32236. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  32237. var renderEffects = this._renderEffects[renderEffectName];
  32238. if (!renderEffects) {
  32239. return;
  32240. }
  32241. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  32242. };
  32243. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  32244. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  32245. var indicesToDelete = [];
  32246. var i;
  32247. for (i = 0; i < _cam.length; i++) {
  32248. var camera = _cam[i];
  32249. var cameraName = camera.name;
  32250. if (this._cameras.indexOf(camera) === -1) {
  32251. this._cameras[cameraName] = camera;
  32252. }
  32253. else if (unique) {
  32254. indicesToDelete.push(i);
  32255. }
  32256. }
  32257. for (i = 0; i < indicesToDelete.length; i++) {
  32258. cameras.splice(indicesToDelete[i], 1);
  32259. }
  32260. for (var renderEffectName in this._renderEffects) {
  32261. this._renderEffects[renderEffectName]._attachCameras(_cam);
  32262. }
  32263. };
  32264. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  32265. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  32266. for (var renderEffectName in this._renderEffects) {
  32267. this._renderEffects[renderEffectName]._detachCameras(_cam);
  32268. }
  32269. for (var i = 0; i < _cam.length; i++) {
  32270. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  32271. }
  32272. };
  32273. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  32274. var _this = this;
  32275. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  32276. var pass = null;
  32277. var renderEffectName;
  32278. for (renderEffectName in this._renderEffects) {
  32279. pass = this._renderEffects[renderEffectName].getPass(passName);
  32280. if (pass != null) {
  32281. break;
  32282. }
  32283. }
  32284. if (pass === null) {
  32285. return;
  32286. }
  32287. for (renderEffectName in this._renderEffects) {
  32288. this._renderEffects[renderEffectName]._disable(_cam);
  32289. }
  32290. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  32291. for (var i = 0; i < _cam.length; i++) {
  32292. var camera = _cam[i];
  32293. var cameraName = camera.name;
  32294. 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); });
  32295. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  32296. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  32297. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  32298. }
  32299. };
  32300. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  32301. var _this = this;
  32302. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  32303. for (var i = 0; i < _cam.length; i++) {
  32304. var camera = _cam[i];
  32305. var cameraName = camera.name;
  32306. 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); });
  32307. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  32308. }
  32309. for (var renderEffectName in this._renderEffects) {
  32310. this._renderEffects[renderEffectName]._enable(_cam);
  32311. }
  32312. };
  32313. PostProcessRenderPipeline.prototype._update = function () {
  32314. for (var renderEffectName in this._renderEffects) {
  32315. this._renderEffects[renderEffectName]._update();
  32316. }
  32317. for (var i = 0; i < this._cameras.length; i++) {
  32318. var cameraName = this._cameras[i].name;
  32319. if (this._renderEffectsForIsolatedPass[cameraName]) {
  32320. this._renderEffectsForIsolatedPass[cameraName]._update();
  32321. }
  32322. }
  32323. };
  32324. PostProcessRenderPipeline.prototype.dispose = function () {
  32325. // Must be implemented by children
  32326. };
  32327. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  32328. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  32329. return PostProcessRenderPipeline;
  32330. })();
  32331. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  32332. })(BABYLON || (BABYLON = {}));
  32333. var BABYLON;
  32334. (function (BABYLON) {
  32335. var PostProcessRenderPipelineManager = (function () {
  32336. function PostProcessRenderPipelineManager() {
  32337. this._renderPipelines = {};
  32338. }
  32339. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  32340. this._renderPipelines[renderPipeline._name] = renderPipeline;
  32341. };
  32342. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  32343. var renderPipeline = this._renderPipelines[renderPipelineName];
  32344. if (!renderPipeline) {
  32345. return;
  32346. }
  32347. renderPipeline._attachCameras(cameras, unique);
  32348. };
  32349. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  32350. var renderPipeline = this._renderPipelines[renderPipelineName];
  32351. if (!renderPipeline) {
  32352. return;
  32353. }
  32354. renderPipeline._detachCameras(cameras);
  32355. };
  32356. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  32357. var renderPipeline = this._renderPipelines[renderPipelineName];
  32358. if (!renderPipeline) {
  32359. return;
  32360. }
  32361. renderPipeline._enableEffect(renderEffectName, cameras);
  32362. };
  32363. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  32364. var renderPipeline = this._renderPipelines[renderPipelineName];
  32365. if (!renderPipeline) {
  32366. return;
  32367. }
  32368. renderPipeline._disableEffect(renderEffectName, cameras);
  32369. };
  32370. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  32371. var renderPipeline = this._renderPipelines[renderPipelineName];
  32372. if (!renderPipeline) {
  32373. return;
  32374. }
  32375. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  32376. };
  32377. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  32378. var renderPipeline = this._renderPipelines[renderPipelineName];
  32379. if (!renderPipeline) {
  32380. return;
  32381. }
  32382. renderPipeline._disableDisplayOnlyPass(cameras);
  32383. };
  32384. PostProcessRenderPipelineManager.prototype.update = function () {
  32385. for (var renderPipelineName in this._renderPipelines) {
  32386. var pipeline = this._renderPipelines[renderPipelineName];
  32387. if (!pipeline.isSupported) {
  32388. pipeline.dispose();
  32389. delete this._renderPipelines[renderPipelineName];
  32390. }
  32391. else {
  32392. pipeline._update();
  32393. }
  32394. }
  32395. };
  32396. return PostProcessRenderPipelineManager;
  32397. })();
  32398. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  32399. })(BABYLON || (BABYLON = {}));
  32400. var BABYLON;
  32401. (function (BABYLON) {
  32402. var BoundingBoxRenderer = (function () {
  32403. function BoundingBoxRenderer(scene) {
  32404. this.frontColor = new BABYLON.Color3(1, 1, 1);
  32405. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  32406. this.showBackLines = true;
  32407. this.renderList = new BABYLON.SmartArray(32);
  32408. this._vertexBuffers = {};
  32409. this._scene = scene;
  32410. }
  32411. BoundingBoxRenderer.prototype._prepareRessources = function () {
  32412. if (this._colorShader) {
  32413. return;
  32414. }
  32415. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  32416. attributes: [BABYLON.VertexBuffer.PositionKind],
  32417. uniforms: ["worldViewProjection", "color"]
  32418. });
  32419. var engine = this._scene.getEngine();
  32420. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  32421. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  32422. 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]);
  32423. };
  32424. BoundingBoxRenderer.prototype.reset = function () {
  32425. this.renderList.reset();
  32426. };
  32427. BoundingBoxRenderer.prototype.render = function () {
  32428. if (this.renderList.length === 0) {
  32429. return;
  32430. }
  32431. this._prepareRessources();
  32432. if (!this._colorShader.isReady()) {
  32433. return;
  32434. }
  32435. var engine = this._scene.getEngine();
  32436. engine.setDepthWrite(false);
  32437. this._colorShader._preBind();
  32438. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  32439. var boundingBox = this.renderList.data[boundingBoxIndex];
  32440. var min = boundingBox.minimum;
  32441. var max = boundingBox.maximum;
  32442. var diff = max.subtract(min);
  32443. var median = min.add(diff.scale(0.5));
  32444. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  32445. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  32446. .multiply(boundingBox.getWorldMatrix());
  32447. // VBOs
  32448. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  32449. if (this.showBackLines) {
  32450. // Back
  32451. engine.setDepthFunctionToGreaterOrEqual();
  32452. this._scene.resetCachedMaterial();
  32453. this._colorShader.setColor4("color", this.backColor.toColor4());
  32454. this._colorShader.bind(worldMatrix);
  32455. // Draw order
  32456. engine.draw(false, 0, 24);
  32457. }
  32458. // Front
  32459. engine.setDepthFunctionToLess();
  32460. this._scene.resetCachedMaterial();
  32461. this._colorShader.setColor4("color", this.frontColor.toColor4());
  32462. this._colorShader.bind(worldMatrix);
  32463. // Draw order
  32464. engine.draw(false, 0, 24);
  32465. }
  32466. this._colorShader.unbind();
  32467. engine.setDepthFunctionToLessOrEqual();
  32468. engine.setDepthWrite(true);
  32469. };
  32470. BoundingBoxRenderer.prototype.dispose = function () {
  32471. if (!this._colorShader) {
  32472. return;
  32473. }
  32474. this._colorShader.dispose();
  32475. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  32476. if (buffer) {
  32477. buffer.dispose();
  32478. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  32479. }
  32480. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  32481. };
  32482. return BoundingBoxRenderer;
  32483. })();
  32484. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  32485. })(BABYLON || (BABYLON = {}));
  32486. var BABYLON;
  32487. (function (BABYLON) {
  32488. var Condition = (function () {
  32489. function Condition(actionManager) {
  32490. this._actionManager = actionManager;
  32491. }
  32492. Condition.prototype.isValid = function () {
  32493. return true;
  32494. };
  32495. Condition.prototype._getProperty = function (propertyPath) {
  32496. return this._actionManager._getProperty(propertyPath);
  32497. };
  32498. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  32499. return this._actionManager._getEffectiveTarget(target, propertyPath);
  32500. };
  32501. Condition.prototype.serialize = function () {
  32502. };
  32503. Condition.prototype._serialize = function (serializedCondition) {
  32504. return {
  32505. type: 2,
  32506. children: [],
  32507. name: serializedCondition.name,
  32508. properties: serializedCondition.properties
  32509. };
  32510. };
  32511. return Condition;
  32512. })();
  32513. BABYLON.Condition = Condition;
  32514. var ValueCondition = (function (_super) {
  32515. __extends(ValueCondition, _super);
  32516. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  32517. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  32518. _super.call(this, actionManager);
  32519. this.propertyPath = propertyPath;
  32520. this.value = value;
  32521. this.operator = operator;
  32522. this._target = target;
  32523. this._effectiveTarget = this._getEffectiveTarget(target, this.propertyPath);
  32524. this._property = this._getProperty(this.propertyPath);
  32525. }
  32526. Object.defineProperty(ValueCondition, "IsEqual", {
  32527. get: function () {
  32528. return ValueCondition._IsEqual;
  32529. },
  32530. enumerable: true,
  32531. configurable: true
  32532. });
  32533. Object.defineProperty(ValueCondition, "IsDifferent", {
  32534. get: function () {
  32535. return ValueCondition._IsDifferent;
  32536. },
  32537. enumerable: true,
  32538. configurable: true
  32539. });
  32540. Object.defineProperty(ValueCondition, "IsGreater", {
  32541. get: function () {
  32542. return ValueCondition._IsGreater;
  32543. },
  32544. enumerable: true,
  32545. configurable: true
  32546. });
  32547. Object.defineProperty(ValueCondition, "IsLesser", {
  32548. get: function () {
  32549. return ValueCondition._IsLesser;
  32550. },
  32551. enumerable: true,
  32552. configurable: true
  32553. });
  32554. // Methods
  32555. ValueCondition.prototype.isValid = function () {
  32556. switch (this.operator) {
  32557. case ValueCondition.IsGreater:
  32558. return this._effectiveTarget[this._property] > this.value;
  32559. case ValueCondition.IsLesser:
  32560. return this._effectiveTarget[this._property] < this.value;
  32561. case ValueCondition.IsEqual:
  32562. case ValueCondition.IsDifferent:
  32563. var check;
  32564. if (this.value.equals) {
  32565. check = this.value.equals(this._effectiveTarget[this._property]);
  32566. }
  32567. else {
  32568. check = this.value === this._effectiveTarget[this._property];
  32569. }
  32570. return this.operator === ValueCondition.IsEqual ? check : !check;
  32571. }
  32572. return false;
  32573. };
  32574. ValueCondition.prototype.serialize = function () {
  32575. return this._serialize({
  32576. name: "ValueCondition",
  32577. properties: [
  32578. BABYLON.Action._GetTargetProperty(this._target),
  32579. { name: "propertyPath", value: this.propertyPath },
  32580. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  32581. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  32582. ]
  32583. });
  32584. };
  32585. ValueCondition.GetOperatorName = function (operator) {
  32586. switch (operator) {
  32587. case ValueCondition._IsEqual: return "IsEqual";
  32588. case ValueCondition._IsDifferent: return "IsDifferent";
  32589. case ValueCondition._IsGreater: return "IsGreater";
  32590. case ValueCondition._IsLesser: return "IsLesser";
  32591. default: return "";
  32592. }
  32593. };
  32594. // Statics
  32595. ValueCondition._IsEqual = 0;
  32596. ValueCondition._IsDifferent = 1;
  32597. ValueCondition._IsGreater = 2;
  32598. ValueCondition._IsLesser = 3;
  32599. return ValueCondition;
  32600. })(Condition);
  32601. BABYLON.ValueCondition = ValueCondition;
  32602. var PredicateCondition = (function (_super) {
  32603. __extends(PredicateCondition, _super);
  32604. function PredicateCondition(actionManager, predicate) {
  32605. _super.call(this, actionManager);
  32606. this.predicate = predicate;
  32607. }
  32608. PredicateCondition.prototype.isValid = function () {
  32609. return this.predicate();
  32610. };
  32611. return PredicateCondition;
  32612. })(Condition);
  32613. BABYLON.PredicateCondition = PredicateCondition;
  32614. var StateCondition = (function (_super) {
  32615. __extends(StateCondition, _super);
  32616. function StateCondition(actionManager, target, value) {
  32617. _super.call(this, actionManager);
  32618. this.value = value;
  32619. this._target = target;
  32620. }
  32621. // Methods
  32622. StateCondition.prototype.isValid = function () {
  32623. return this._target.state === this.value;
  32624. };
  32625. StateCondition.prototype.serialize = function () {
  32626. return this._serialize({
  32627. name: "StateCondition",
  32628. properties: [
  32629. BABYLON.Action._GetTargetProperty(this._target),
  32630. { name: "value", value: this.value }
  32631. ]
  32632. });
  32633. };
  32634. return StateCondition;
  32635. })(Condition);
  32636. BABYLON.StateCondition = StateCondition;
  32637. })(BABYLON || (BABYLON = {}));
  32638. var BABYLON;
  32639. (function (BABYLON) {
  32640. var Action = (function () {
  32641. function Action(triggerOptions, condition) {
  32642. this.triggerOptions = triggerOptions;
  32643. if (triggerOptions.parameter) {
  32644. this.trigger = triggerOptions.trigger;
  32645. this._triggerParameter = triggerOptions.parameter;
  32646. }
  32647. else {
  32648. this.trigger = triggerOptions;
  32649. }
  32650. this._nextActiveAction = this;
  32651. this._condition = condition;
  32652. }
  32653. // Methods
  32654. Action.prototype._prepare = function () {
  32655. };
  32656. Action.prototype.getTriggerParameter = function () {
  32657. return this._triggerParameter;
  32658. };
  32659. Action.prototype._executeCurrent = function (evt) {
  32660. if (this._nextActiveAction._condition) {
  32661. var condition = this._nextActiveAction._condition;
  32662. var currentRenderId = this._actionManager.getScene().getRenderId();
  32663. // We cache the current evaluation for the current frame
  32664. if (condition._evaluationId === currentRenderId) {
  32665. if (!condition._currentResult) {
  32666. return;
  32667. }
  32668. }
  32669. else {
  32670. condition._evaluationId = currentRenderId;
  32671. if (!condition.isValid()) {
  32672. condition._currentResult = false;
  32673. return;
  32674. }
  32675. condition._currentResult = true;
  32676. }
  32677. }
  32678. this._nextActiveAction.execute(evt);
  32679. this.skipToNextActiveAction();
  32680. };
  32681. Action.prototype.execute = function (evt) {
  32682. };
  32683. Action.prototype.skipToNextActiveAction = function () {
  32684. if (this._nextActiveAction._child) {
  32685. if (!this._nextActiveAction._child._actionManager) {
  32686. this._nextActiveAction._child._actionManager = this._actionManager;
  32687. }
  32688. this._nextActiveAction = this._nextActiveAction._child;
  32689. }
  32690. else {
  32691. this._nextActiveAction = this;
  32692. }
  32693. };
  32694. Action.prototype.then = function (action) {
  32695. this._child = action;
  32696. action._actionManager = this._actionManager;
  32697. action._prepare();
  32698. return action;
  32699. };
  32700. Action.prototype._getProperty = function (propertyPath) {
  32701. return this._actionManager._getProperty(propertyPath);
  32702. };
  32703. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  32704. return this._actionManager._getEffectiveTarget(target, propertyPath);
  32705. };
  32706. Action.prototype.serialize = function (parent) {
  32707. };
  32708. // Called by BABYLON.Action objects in serialize(...). Internal use
  32709. Action.prototype._serialize = function (serializedAction, parent) {
  32710. var serializationObject = {
  32711. type: 1,
  32712. children: [],
  32713. name: serializedAction.name,
  32714. properties: serializedAction.properties || []
  32715. };
  32716. // Serialize child
  32717. if (this._child) {
  32718. this._child.serialize(serializationObject);
  32719. }
  32720. // Check if "this" has a condition
  32721. if (this._condition) {
  32722. var serializedCondition = this._condition.serialize();
  32723. serializedCondition.children.push(serializationObject);
  32724. if (parent) {
  32725. parent.children.push(serializedCondition);
  32726. }
  32727. return serializedCondition;
  32728. }
  32729. if (parent) {
  32730. parent.children.push(serializationObject);
  32731. }
  32732. return serializationObject;
  32733. };
  32734. Action._SerializeValueAsString = function (value) {
  32735. if (typeof value === "number") {
  32736. return value.toString();
  32737. }
  32738. if (typeof value === "boolean") {
  32739. return value ? "true" : "false";
  32740. }
  32741. if (value instanceof BABYLON.Vector2) {
  32742. return value.x + ", " + value.y;
  32743. }
  32744. if (value instanceof BABYLON.Vector3) {
  32745. return value.x + ", " + value.y + ", " + value.z;
  32746. }
  32747. if (value instanceof BABYLON.Color3) {
  32748. return value.r + ", " + value.g + ", " + value.b;
  32749. }
  32750. if (value instanceof BABYLON.Color4) {
  32751. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  32752. }
  32753. return value; // string
  32754. };
  32755. Action._GetTargetProperty = function (target) {
  32756. return {
  32757. name: "target",
  32758. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  32759. : target instanceof BABYLON.Light ? "LightProperties"
  32760. : target instanceof BABYLON.Camera ? "CameraProperties"
  32761. : "SceneProperties",
  32762. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  32763. };
  32764. };
  32765. return Action;
  32766. })();
  32767. BABYLON.Action = Action;
  32768. })(BABYLON || (BABYLON = {}));
  32769. var BABYLON;
  32770. (function (BABYLON) {
  32771. /**
  32772. * ActionEvent is the event beint sent when an action is triggered.
  32773. */
  32774. var ActionEvent = (function () {
  32775. /**
  32776. * @constructor
  32777. * @param source The mesh or sprite that triggered the action.
  32778. * @param pointerX The X mouse cursor position at the time of the event
  32779. * @param pointerY The Y mouse cursor position at the time of the event
  32780. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  32781. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  32782. */
  32783. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  32784. this.source = source;
  32785. this.pointerX = pointerX;
  32786. this.pointerY = pointerY;
  32787. this.meshUnderPointer = meshUnderPointer;
  32788. this.sourceEvent = sourceEvent;
  32789. this.additionalData = additionalData;
  32790. }
  32791. /**
  32792. * Helper function to auto-create an ActionEvent from a source mesh.
  32793. * @param source The source mesh that triggered the event
  32794. * @param evt {Event} The original (browser) event
  32795. */
  32796. ActionEvent.CreateNew = function (source, evt, additionalData) {
  32797. var scene = source.getScene();
  32798. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  32799. };
  32800. /**
  32801. * Helper function to auto-create an ActionEvent from a source mesh.
  32802. * @param source The source sprite that triggered the event
  32803. * @param scene Scene associated with the sprite
  32804. * @param evt {Event} The original (browser) event
  32805. */
  32806. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  32807. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  32808. };
  32809. /**
  32810. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  32811. * @param scene the scene where the event occurred
  32812. * @param evt {Event} The original (browser) event
  32813. */
  32814. ActionEvent.CreateNewFromScene = function (scene, evt) {
  32815. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  32816. };
  32817. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  32818. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  32819. };
  32820. return ActionEvent;
  32821. })();
  32822. BABYLON.ActionEvent = ActionEvent;
  32823. /**
  32824. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  32825. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  32826. */
  32827. var ActionManager = (function () {
  32828. function ActionManager(scene) {
  32829. // Members
  32830. this.actions = new Array();
  32831. this._scene = scene;
  32832. scene._actionManagers.push(this);
  32833. }
  32834. Object.defineProperty(ActionManager, "NothingTrigger", {
  32835. get: function () {
  32836. return ActionManager._NothingTrigger;
  32837. },
  32838. enumerable: true,
  32839. configurable: true
  32840. });
  32841. Object.defineProperty(ActionManager, "OnPickTrigger", {
  32842. get: function () {
  32843. return ActionManager._OnPickTrigger;
  32844. },
  32845. enumerable: true,
  32846. configurable: true
  32847. });
  32848. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  32849. get: function () {
  32850. return ActionManager._OnLeftPickTrigger;
  32851. },
  32852. enumerable: true,
  32853. configurable: true
  32854. });
  32855. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  32856. get: function () {
  32857. return ActionManager._OnRightPickTrigger;
  32858. },
  32859. enumerable: true,
  32860. configurable: true
  32861. });
  32862. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  32863. get: function () {
  32864. return ActionManager._OnCenterPickTrigger;
  32865. },
  32866. enumerable: true,
  32867. configurable: true
  32868. });
  32869. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  32870. get: function () {
  32871. return ActionManager._OnPickDownTrigger;
  32872. },
  32873. enumerable: true,
  32874. configurable: true
  32875. });
  32876. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  32877. get: function () {
  32878. return ActionManager._OnPickUpTrigger;
  32879. },
  32880. enumerable: true,
  32881. configurable: true
  32882. });
  32883. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  32884. /// This trigger will only be raised if you also declared a OnPickDown
  32885. get: function () {
  32886. return ActionManager._OnPickOutTrigger;
  32887. },
  32888. enumerable: true,
  32889. configurable: true
  32890. });
  32891. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  32892. get: function () {
  32893. return ActionManager._OnLongPressTrigger;
  32894. },
  32895. enumerable: true,
  32896. configurable: true
  32897. });
  32898. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  32899. get: function () {
  32900. return ActionManager._OnPointerOverTrigger;
  32901. },
  32902. enumerable: true,
  32903. configurable: true
  32904. });
  32905. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  32906. get: function () {
  32907. return ActionManager._OnPointerOutTrigger;
  32908. },
  32909. enumerable: true,
  32910. configurable: true
  32911. });
  32912. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  32913. get: function () {
  32914. return ActionManager._OnEveryFrameTrigger;
  32915. },
  32916. enumerable: true,
  32917. configurable: true
  32918. });
  32919. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  32920. get: function () {
  32921. return ActionManager._OnIntersectionEnterTrigger;
  32922. },
  32923. enumerable: true,
  32924. configurable: true
  32925. });
  32926. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  32927. get: function () {
  32928. return ActionManager._OnIntersectionExitTrigger;
  32929. },
  32930. enumerable: true,
  32931. configurable: true
  32932. });
  32933. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  32934. get: function () {
  32935. return ActionManager._OnKeyDownTrigger;
  32936. },
  32937. enumerable: true,
  32938. configurable: true
  32939. });
  32940. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  32941. get: function () {
  32942. return ActionManager._OnKeyUpTrigger;
  32943. },
  32944. enumerable: true,
  32945. configurable: true
  32946. });
  32947. // Methods
  32948. ActionManager.prototype.dispose = function () {
  32949. var index = this._scene._actionManagers.indexOf(this);
  32950. if (index > -1) {
  32951. this._scene._actionManagers.splice(index, 1);
  32952. }
  32953. };
  32954. ActionManager.prototype.getScene = function () {
  32955. return this._scene;
  32956. };
  32957. /**
  32958. * Does this action manager handles actions of any of the given triggers
  32959. * @param {number[]} triggers - the triggers to be tested
  32960. * @return {boolean} whether one (or more) of the triggers is handeled
  32961. */
  32962. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  32963. for (var index = 0; index < this.actions.length; index++) {
  32964. var action = this.actions[index];
  32965. if (triggers.indexOf(action.trigger) > -1) {
  32966. return true;
  32967. }
  32968. }
  32969. return false;
  32970. };
  32971. /**
  32972. * Does this action manager handles actions of a given trigger
  32973. * @param {number} trigger - the trigger to be tested
  32974. * @return {boolean} whether the trigger is handeled
  32975. */
  32976. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  32977. for (var index = 0; index < this.actions.length; index++) {
  32978. var action = this.actions[index];
  32979. if (action.trigger === trigger) {
  32980. return true;
  32981. }
  32982. }
  32983. return false;
  32984. };
  32985. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  32986. /**
  32987. * Does this action manager has pointer triggers
  32988. * @return {boolean} whether or not it has pointer triggers
  32989. */
  32990. get: function () {
  32991. for (var index = 0; index < this.actions.length; index++) {
  32992. var action = this.actions[index];
  32993. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  32994. return true;
  32995. }
  32996. }
  32997. return false;
  32998. },
  32999. enumerable: true,
  33000. configurable: true
  33001. });
  33002. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  33003. /**
  33004. * Does this action manager has pick triggers
  33005. * @return {boolean} whether or not it has pick triggers
  33006. */
  33007. get: function () {
  33008. for (var index = 0; index < this.actions.length; index++) {
  33009. var action = this.actions[index];
  33010. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  33011. return true;
  33012. }
  33013. }
  33014. return false;
  33015. },
  33016. enumerable: true,
  33017. configurable: true
  33018. });
  33019. /**
  33020. * Registers an action to this action manager
  33021. * @param {BABYLON.Action} action - the action to be registered
  33022. * @return {BABYLON.Action} the action amended (prepared) after registration
  33023. */
  33024. ActionManager.prototype.registerAction = function (action) {
  33025. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  33026. if (this.getScene().actionManager !== this) {
  33027. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  33028. return null;
  33029. }
  33030. }
  33031. this.actions.push(action);
  33032. action._actionManager = this;
  33033. action._prepare();
  33034. return action;
  33035. };
  33036. /**
  33037. * Process a specific trigger
  33038. * @param {number} trigger - the trigger to process
  33039. * @param evt {BABYLON.ActionEvent} the event details to be processed
  33040. */
  33041. ActionManager.prototype.processTrigger = function (trigger, evt) {
  33042. for (var index = 0; index < this.actions.length; index++) {
  33043. var action = this.actions[index];
  33044. if (action.trigger === trigger) {
  33045. if (trigger === ActionManager.OnKeyUpTrigger
  33046. || trigger === ActionManager.OnKeyDownTrigger) {
  33047. var parameter = action.getTriggerParameter();
  33048. if (parameter) {
  33049. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  33050. var actualkey = String.fromCharCode(unicode).toLowerCase();
  33051. if (actualkey !== parameter.toLowerCase()) {
  33052. continue;
  33053. }
  33054. }
  33055. }
  33056. action._executeCurrent(evt);
  33057. }
  33058. }
  33059. };
  33060. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  33061. var properties = propertyPath.split(".");
  33062. for (var index = 0; index < properties.length - 1; index++) {
  33063. target = target[properties[index]];
  33064. }
  33065. return target;
  33066. };
  33067. ActionManager.prototype._getProperty = function (propertyPath) {
  33068. var properties = propertyPath.split(".");
  33069. return properties[properties.length - 1];
  33070. };
  33071. ActionManager.prototype.serialize = function (name) {
  33072. var root = {
  33073. children: [],
  33074. name: name,
  33075. type: 3,
  33076. properties: [] // Empty for root but required
  33077. };
  33078. for (var i = 0; i < this.actions.length; i++) {
  33079. var triggerObject = {
  33080. type: 0,
  33081. children: [],
  33082. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  33083. properties: []
  33084. };
  33085. var triggerOptions = this.actions[i].triggerOptions;
  33086. if (triggerOptions && typeof triggerOptions !== "number") {
  33087. if (triggerOptions.parameter instanceof BABYLON.Node) {
  33088. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  33089. }
  33090. else {
  33091. triggerObject.properties.push({ name: "parameter", targetType: null, value: triggerOptions.parameter });
  33092. }
  33093. }
  33094. // Serialize child action, recursively
  33095. this.actions[i].serialize(triggerObject);
  33096. // Add serialized trigger
  33097. root.children.push(triggerObject);
  33098. }
  33099. return root;
  33100. };
  33101. ActionManager.Parse = function (parsedActions, object, scene) {
  33102. var actionManager = new BABYLON.ActionManager(scene);
  33103. if (object === null)
  33104. scene.actionManager = actionManager;
  33105. else
  33106. object.actionManager = actionManager;
  33107. // instanciate a new object
  33108. var instanciate = function (name, params) {
  33109. var newInstance = Object.create(BABYLON[name].prototype);
  33110. newInstance.constructor.apply(newInstance, params);
  33111. return newInstance;
  33112. };
  33113. var parseParameter = function (name, value, target, propertyPath) {
  33114. if (propertyPath === null) {
  33115. // String, boolean or float
  33116. var floatValue = parseFloat(value);
  33117. if (value === "true" || value === "false")
  33118. return value === "true";
  33119. else
  33120. return isNaN(floatValue) ? value : floatValue;
  33121. }
  33122. var effectiveTarget = propertyPath.split(".");
  33123. var values = value.split(",");
  33124. // Get effective Target
  33125. for (var i = 0; i < effectiveTarget.length; i++) {
  33126. target = target[effectiveTarget[i]];
  33127. }
  33128. // Return appropriate value with its type
  33129. if (typeof (target) === "boolean")
  33130. return values[0] === "true";
  33131. if (typeof (target) === "string")
  33132. return values[0];
  33133. // Parameters with multiple values such as Vector3 etc.
  33134. var split = new Array();
  33135. for (var i = 0; i < values.length; i++)
  33136. split.push(parseFloat(values[i]));
  33137. if (target instanceof BABYLON.Vector3)
  33138. return BABYLON.Vector3.FromArray(split);
  33139. if (target instanceof BABYLON.Vector4)
  33140. return BABYLON.Vector4.FromArray(split);
  33141. if (target instanceof BABYLON.Color3)
  33142. return BABYLON.Color3.FromArray(split);
  33143. if (target instanceof BABYLON.Color4)
  33144. return BABYLON.Color4.FromArray(split);
  33145. return parseFloat(values[0]);
  33146. };
  33147. // traverse graph per trigger
  33148. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  33149. if (combineArray === void 0) { combineArray = null; }
  33150. if (parsedAction.detached)
  33151. return;
  33152. var parameters = new Array();
  33153. var target = null;
  33154. var propertyPath = null;
  33155. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  33156. // Parameters
  33157. if (parsedAction.type === 2)
  33158. parameters.push(actionManager);
  33159. else
  33160. parameters.push(trigger);
  33161. if (combine) {
  33162. var actions = new Array();
  33163. for (var j = 0; j < parsedAction.combine.length; j++) {
  33164. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  33165. }
  33166. parameters.push(actions);
  33167. }
  33168. else {
  33169. for (var i = 0; i < parsedAction.properties.length; i++) {
  33170. var value = parsedAction.properties[i].value;
  33171. var name = parsedAction.properties[i].name;
  33172. var targetType = parsedAction.properties[i].targetType;
  33173. if (name === "target")
  33174. if (targetType !== null && targetType === "SceneProperties")
  33175. value = target = scene;
  33176. else
  33177. value = target = scene.getNodeByName(value);
  33178. else if (name === "parent")
  33179. value = scene.getNodeByName(value);
  33180. else if (name === "sound")
  33181. value = scene.getSoundByName(value);
  33182. else if (name !== "propertyPath") {
  33183. if (parsedAction.type === 2 && name === "operator")
  33184. value = BABYLON.ValueCondition[value];
  33185. else
  33186. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  33187. }
  33188. else {
  33189. propertyPath = value;
  33190. }
  33191. parameters.push(value);
  33192. }
  33193. }
  33194. if (combineArray === null) {
  33195. parameters.push(condition);
  33196. }
  33197. else {
  33198. parameters.push(null);
  33199. }
  33200. // If interpolate value action
  33201. if (parsedAction.name === "InterpolateValueAction") {
  33202. var param = parameters[parameters.length - 2];
  33203. parameters[parameters.length - 1] = param;
  33204. parameters[parameters.length - 2] = condition;
  33205. }
  33206. // Action or condition(s) and not CombineAction
  33207. var newAction = instanciate(parsedAction.name, parameters);
  33208. if (newAction instanceof BABYLON.Condition && condition !== null) {
  33209. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  33210. if (action)
  33211. action.then(nothing);
  33212. else
  33213. actionManager.registerAction(nothing);
  33214. action = nothing;
  33215. }
  33216. if (combineArray === null) {
  33217. if (newAction instanceof BABYLON.Condition) {
  33218. condition = newAction;
  33219. newAction = action;
  33220. }
  33221. else {
  33222. condition = null;
  33223. if (action)
  33224. action.then(newAction);
  33225. else
  33226. actionManager.registerAction(newAction);
  33227. }
  33228. }
  33229. else {
  33230. combineArray.push(newAction);
  33231. }
  33232. for (var i = 0; i < parsedAction.children.length; i++)
  33233. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  33234. };
  33235. // triggers
  33236. for (var i = 0; i < parsedActions.children.length; i++) {
  33237. var triggerParams;
  33238. var trigger = parsedActions.children[i];
  33239. if (trigger.properties.length > 0) {
  33240. var param = trigger.properties[0].value;
  33241. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  33242. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  33243. }
  33244. else
  33245. triggerParams = BABYLON.ActionManager[trigger.name];
  33246. for (var j = 0; j < trigger.children.length; j++) {
  33247. if (!trigger.detached)
  33248. traverse(trigger.children[j], triggerParams, null, null);
  33249. }
  33250. }
  33251. };
  33252. ActionManager.GetTriggerName = function (trigger) {
  33253. switch (trigger) {
  33254. case 0: return "NothingTrigger";
  33255. case 1: return "OnPickTrigger";
  33256. case 2: return "OnLeftPickTrigger";
  33257. case 3: return "OnRightPickTrigger";
  33258. case 4: return "OnCenterPickTrigger";
  33259. case 5: return "OnPickDownTrigger";
  33260. case 6: return "OnPickUpTrigger";
  33261. case 7: return "OnLongPressTrigger";
  33262. case 8: return "OnPointerOverTrigger";
  33263. case 9: return "OnPointerOutTrigger";
  33264. case 10: return "OnEveryFrameTrigger";
  33265. case 11: return "OnIntersectionEnterTrigger";
  33266. case 12: return "OnIntersectionExitTrigger";
  33267. case 13: return "OnKeyDownTrigger";
  33268. case 14: return "OnKeyUpTrigger";
  33269. case 15: return "OnPickOutTrigger";
  33270. default: return "";
  33271. }
  33272. };
  33273. // Statics
  33274. ActionManager._NothingTrigger = 0;
  33275. ActionManager._OnPickTrigger = 1;
  33276. ActionManager._OnLeftPickTrigger = 2;
  33277. ActionManager._OnRightPickTrigger = 3;
  33278. ActionManager._OnCenterPickTrigger = 4;
  33279. ActionManager._OnPickDownTrigger = 5;
  33280. ActionManager._OnPickUpTrigger = 6;
  33281. ActionManager._OnLongPressTrigger = 7;
  33282. ActionManager._OnPointerOverTrigger = 8;
  33283. ActionManager._OnPointerOutTrigger = 9;
  33284. ActionManager._OnEveryFrameTrigger = 10;
  33285. ActionManager._OnIntersectionEnterTrigger = 11;
  33286. ActionManager._OnIntersectionExitTrigger = 12;
  33287. ActionManager._OnKeyDownTrigger = 13;
  33288. ActionManager._OnKeyUpTrigger = 14;
  33289. ActionManager._OnPickOutTrigger = 15;
  33290. ActionManager.DragMovementThreshold = 10; // in pixels
  33291. ActionManager.LongPressDelay = 500; // in milliseconds
  33292. return ActionManager;
  33293. })();
  33294. BABYLON.ActionManager = ActionManager;
  33295. })(BABYLON || (BABYLON = {}));
  33296. var BABYLON;
  33297. (function (BABYLON) {
  33298. var InterpolateValueAction = (function (_super) {
  33299. __extends(InterpolateValueAction, _super);
  33300. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  33301. if (duration === void 0) { duration = 1000; }
  33302. _super.call(this, triggerOptions, condition);
  33303. this.propertyPath = propertyPath;
  33304. this.value = value;
  33305. this.duration = duration;
  33306. this.stopOtherAnimations = stopOtherAnimations;
  33307. this.onInterpolationDone = onInterpolationDone;
  33308. this._target = this._effectiveTarget = target;
  33309. }
  33310. InterpolateValueAction.prototype._prepare = function () {
  33311. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  33312. this._property = this._getProperty(this.propertyPath);
  33313. };
  33314. InterpolateValueAction.prototype.execute = function () {
  33315. var scene = this._actionManager.getScene();
  33316. var keys = [
  33317. {
  33318. frame: 0,
  33319. value: this._effectiveTarget[this._property]
  33320. }, {
  33321. frame: 100,
  33322. value: this.value
  33323. }
  33324. ];
  33325. var dataType;
  33326. if (typeof this.value === "number") {
  33327. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  33328. }
  33329. else if (this.value instanceof BABYLON.Color3) {
  33330. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  33331. }
  33332. else if (this.value instanceof BABYLON.Vector3) {
  33333. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  33334. }
  33335. else if (this.value instanceof BABYLON.Matrix) {
  33336. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  33337. }
  33338. else if (this.value instanceof BABYLON.Quaternion) {
  33339. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  33340. }
  33341. else {
  33342. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  33343. return;
  33344. }
  33345. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  33346. animation.setKeys(keys);
  33347. if (this.stopOtherAnimations) {
  33348. scene.stopAnimation(this._effectiveTarget);
  33349. }
  33350. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, this.onInterpolationDone);
  33351. };
  33352. InterpolateValueAction.prototype.serialize = function (parent) {
  33353. return _super.prototype._serialize.call(this, {
  33354. name: "InterpolateValueAction",
  33355. properties: [
  33356. BABYLON.Action._GetTargetProperty(this._target),
  33357. { name: "propertyPath", value: this.propertyPath },
  33358. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  33359. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  33360. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  33361. ]
  33362. }, parent);
  33363. };
  33364. return InterpolateValueAction;
  33365. })(BABYLON.Action);
  33366. BABYLON.InterpolateValueAction = InterpolateValueAction;
  33367. })(BABYLON || (BABYLON = {}));
  33368. var BABYLON;
  33369. (function (BABYLON) {
  33370. var SwitchBooleanAction = (function (_super) {
  33371. __extends(SwitchBooleanAction, _super);
  33372. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  33373. _super.call(this, triggerOptions, condition);
  33374. this.propertyPath = propertyPath;
  33375. this._target = this._effectiveTarget = target;
  33376. }
  33377. SwitchBooleanAction.prototype._prepare = function () {
  33378. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  33379. this._property = this._getProperty(this.propertyPath);
  33380. };
  33381. SwitchBooleanAction.prototype.execute = function () {
  33382. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  33383. };
  33384. SwitchBooleanAction.prototype.serialize = function (parent) {
  33385. return _super.prototype._serialize.call(this, {
  33386. name: "SwitchBooleanAction",
  33387. properties: [
  33388. BABYLON.Action._GetTargetProperty(this._target),
  33389. { name: "propertyPath", value: this.propertyPath }
  33390. ]
  33391. }, parent);
  33392. };
  33393. return SwitchBooleanAction;
  33394. })(BABYLON.Action);
  33395. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  33396. var SetStateAction = (function (_super) {
  33397. __extends(SetStateAction, _super);
  33398. function SetStateAction(triggerOptions, target, value, condition) {
  33399. _super.call(this, triggerOptions, condition);
  33400. this.value = value;
  33401. this._target = target;
  33402. }
  33403. SetStateAction.prototype.execute = function () {
  33404. this._target.state = this.value;
  33405. };
  33406. SetStateAction.prototype.serialize = function (parent) {
  33407. return _super.prototype._serialize.call(this, {
  33408. name: "SetStateAction",
  33409. properties: [
  33410. BABYLON.Action._GetTargetProperty(this._target),
  33411. { name: "value", value: this.value }
  33412. ]
  33413. }, parent);
  33414. };
  33415. return SetStateAction;
  33416. })(BABYLON.Action);
  33417. BABYLON.SetStateAction = SetStateAction;
  33418. var SetValueAction = (function (_super) {
  33419. __extends(SetValueAction, _super);
  33420. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  33421. _super.call(this, triggerOptions, condition);
  33422. this.propertyPath = propertyPath;
  33423. this.value = value;
  33424. this._target = this._effectiveTarget = target;
  33425. }
  33426. SetValueAction.prototype._prepare = function () {
  33427. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  33428. this._property = this._getProperty(this.propertyPath);
  33429. };
  33430. SetValueAction.prototype.execute = function () {
  33431. this._effectiveTarget[this._property] = this.value;
  33432. if (this._target.markAsDirty) {
  33433. this._target.markAsDirty(this._property);
  33434. }
  33435. };
  33436. SetValueAction.prototype.serialize = function (parent) {
  33437. return _super.prototype._serialize.call(this, {
  33438. name: "SetValueAction",
  33439. properties: [
  33440. BABYLON.Action._GetTargetProperty(this._target),
  33441. { name: "propertyPath", value: this.propertyPath },
  33442. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  33443. ]
  33444. }, parent);
  33445. };
  33446. return SetValueAction;
  33447. })(BABYLON.Action);
  33448. BABYLON.SetValueAction = SetValueAction;
  33449. var IncrementValueAction = (function (_super) {
  33450. __extends(IncrementValueAction, _super);
  33451. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  33452. _super.call(this, triggerOptions, condition);
  33453. this.propertyPath = propertyPath;
  33454. this.value = value;
  33455. this._target = this._effectiveTarget = target;
  33456. }
  33457. IncrementValueAction.prototype._prepare = function () {
  33458. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  33459. this._property = this._getProperty(this.propertyPath);
  33460. if (typeof this._effectiveTarget[this._property] !== "number") {
  33461. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  33462. }
  33463. };
  33464. IncrementValueAction.prototype.execute = function () {
  33465. this._effectiveTarget[this._property] += this.value;
  33466. if (this._target.markAsDirty) {
  33467. this._target.markAsDirty(this._property);
  33468. }
  33469. };
  33470. IncrementValueAction.prototype.serialize = function (parent) {
  33471. return _super.prototype._serialize.call(this, {
  33472. name: "IncrementValueAction",
  33473. properties: [
  33474. BABYLON.Action._GetTargetProperty(this._target),
  33475. { name: "propertyPath", value: this.propertyPath },
  33476. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  33477. ]
  33478. }, parent);
  33479. };
  33480. return IncrementValueAction;
  33481. })(BABYLON.Action);
  33482. BABYLON.IncrementValueAction = IncrementValueAction;
  33483. var PlayAnimationAction = (function (_super) {
  33484. __extends(PlayAnimationAction, _super);
  33485. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  33486. _super.call(this, triggerOptions, condition);
  33487. this.from = from;
  33488. this.to = to;
  33489. this.loop = loop;
  33490. this._target = target;
  33491. }
  33492. PlayAnimationAction.prototype._prepare = function () {
  33493. };
  33494. PlayAnimationAction.prototype.execute = function () {
  33495. var scene = this._actionManager.getScene();
  33496. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  33497. };
  33498. PlayAnimationAction.prototype.serialize = function (parent) {
  33499. return _super.prototype._serialize.call(this, {
  33500. name: "PlayAnimationAction",
  33501. properties: [
  33502. BABYLON.Action._GetTargetProperty(this._target),
  33503. { name: "from", value: String(this.from) },
  33504. { name: "to", value: String(this.to) },
  33505. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  33506. ]
  33507. }, parent);
  33508. };
  33509. return PlayAnimationAction;
  33510. })(BABYLON.Action);
  33511. BABYLON.PlayAnimationAction = PlayAnimationAction;
  33512. var StopAnimationAction = (function (_super) {
  33513. __extends(StopAnimationAction, _super);
  33514. function StopAnimationAction(triggerOptions, target, condition) {
  33515. _super.call(this, triggerOptions, condition);
  33516. this._target = target;
  33517. }
  33518. StopAnimationAction.prototype._prepare = function () {
  33519. };
  33520. StopAnimationAction.prototype.execute = function () {
  33521. var scene = this._actionManager.getScene();
  33522. scene.stopAnimation(this._target);
  33523. };
  33524. StopAnimationAction.prototype.serialize = function (parent) {
  33525. return _super.prototype._serialize.call(this, {
  33526. name: "StopAnimationAction",
  33527. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  33528. }, parent);
  33529. };
  33530. return StopAnimationAction;
  33531. })(BABYLON.Action);
  33532. BABYLON.StopAnimationAction = StopAnimationAction;
  33533. var DoNothingAction = (function (_super) {
  33534. __extends(DoNothingAction, _super);
  33535. function DoNothingAction(triggerOptions, condition) {
  33536. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  33537. _super.call(this, triggerOptions, condition);
  33538. }
  33539. DoNothingAction.prototype.execute = function () {
  33540. };
  33541. DoNothingAction.prototype.serialize = function (parent) {
  33542. return _super.prototype._serialize.call(this, {
  33543. name: "DoNothingAction",
  33544. properties: []
  33545. }, parent);
  33546. };
  33547. return DoNothingAction;
  33548. })(BABYLON.Action);
  33549. BABYLON.DoNothingAction = DoNothingAction;
  33550. var CombineAction = (function (_super) {
  33551. __extends(CombineAction, _super);
  33552. function CombineAction(triggerOptions, children, condition) {
  33553. _super.call(this, triggerOptions, condition);
  33554. this.children = children;
  33555. }
  33556. CombineAction.prototype._prepare = function () {
  33557. for (var index = 0; index < this.children.length; index++) {
  33558. this.children[index]._actionManager = this._actionManager;
  33559. this.children[index]._prepare();
  33560. }
  33561. };
  33562. CombineAction.prototype.execute = function (evt) {
  33563. for (var index = 0; index < this.children.length; index++) {
  33564. this.children[index].execute(evt);
  33565. }
  33566. };
  33567. CombineAction.prototype.serialize = function (parent) {
  33568. var serializationObject = _super.prototype._serialize.call(this, {
  33569. name: "CombineAction",
  33570. properties: [],
  33571. combine: []
  33572. }, parent);
  33573. for (var i = 0; i < this.children.length; i++) {
  33574. serializationObject.combine.push(this.children[i].serialize(null));
  33575. }
  33576. return serializationObject;
  33577. };
  33578. return CombineAction;
  33579. })(BABYLON.Action);
  33580. BABYLON.CombineAction = CombineAction;
  33581. var ExecuteCodeAction = (function (_super) {
  33582. __extends(ExecuteCodeAction, _super);
  33583. function ExecuteCodeAction(triggerOptions, func, condition) {
  33584. _super.call(this, triggerOptions, condition);
  33585. this.func = func;
  33586. }
  33587. ExecuteCodeAction.prototype.execute = function (evt) {
  33588. this.func(evt);
  33589. };
  33590. return ExecuteCodeAction;
  33591. })(BABYLON.Action);
  33592. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  33593. var SetParentAction = (function (_super) {
  33594. __extends(SetParentAction, _super);
  33595. function SetParentAction(triggerOptions, target, parent, condition) {
  33596. _super.call(this, triggerOptions, condition);
  33597. this._target = target;
  33598. this._parent = parent;
  33599. }
  33600. SetParentAction.prototype._prepare = function () {
  33601. };
  33602. SetParentAction.prototype.execute = function () {
  33603. if (this._target.parent === this._parent) {
  33604. return;
  33605. }
  33606. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  33607. invertParentWorldMatrix.invert();
  33608. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  33609. this._target.parent = this._parent;
  33610. };
  33611. SetParentAction.prototype.serialize = function (parent) {
  33612. return _super.prototype._serialize.call(this, {
  33613. name: "SetParentAction",
  33614. properties: [
  33615. BABYLON.Action._GetTargetProperty(this._target),
  33616. BABYLON.Action._GetTargetProperty(this._parent),
  33617. ]
  33618. }, parent);
  33619. };
  33620. return SetParentAction;
  33621. })(BABYLON.Action);
  33622. BABYLON.SetParentAction = SetParentAction;
  33623. var PlaySoundAction = (function (_super) {
  33624. __extends(PlaySoundAction, _super);
  33625. function PlaySoundAction(triggerOptions, sound, condition) {
  33626. _super.call(this, triggerOptions, condition);
  33627. this._sound = sound;
  33628. }
  33629. PlaySoundAction.prototype._prepare = function () {
  33630. };
  33631. PlaySoundAction.prototype.execute = function () {
  33632. if (this._sound !== undefined)
  33633. this._sound.play();
  33634. };
  33635. PlaySoundAction.prototype.serialize = function (parent) {
  33636. return _super.prototype._serialize.call(this, {
  33637. name: "PlaySoundAction",
  33638. properties: [{ name: "sound", value: this._sound.name }]
  33639. }, parent);
  33640. };
  33641. return PlaySoundAction;
  33642. })(BABYLON.Action);
  33643. BABYLON.PlaySoundAction = PlaySoundAction;
  33644. var StopSoundAction = (function (_super) {
  33645. __extends(StopSoundAction, _super);
  33646. function StopSoundAction(triggerOptions, sound, condition) {
  33647. _super.call(this, triggerOptions, condition);
  33648. this._sound = sound;
  33649. }
  33650. StopSoundAction.prototype._prepare = function () {
  33651. };
  33652. StopSoundAction.prototype.execute = function () {
  33653. if (this._sound !== undefined)
  33654. this._sound.stop();
  33655. };
  33656. StopSoundAction.prototype.serialize = function (parent) {
  33657. return _super.prototype._serialize.call(this, {
  33658. name: "StopSoundAction",
  33659. properties: [{ name: "sound", value: this._sound.name }]
  33660. }, parent);
  33661. };
  33662. return StopSoundAction;
  33663. })(BABYLON.Action);
  33664. BABYLON.StopSoundAction = StopSoundAction;
  33665. })(BABYLON || (BABYLON = {}));
  33666. var BABYLON;
  33667. (function (BABYLON) {
  33668. var Geometry = (function () {
  33669. function Geometry(id, scene, vertexData, updatable, mesh) {
  33670. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  33671. this._totalVertices = 0;
  33672. this._isDisposed = false;
  33673. this.id = id;
  33674. this._engine = scene.getEngine();
  33675. this._meshes = [];
  33676. this._scene = scene;
  33677. //Init vertex buffer cache
  33678. this._vertexBuffers = {};
  33679. this._indices = [];
  33680. // vertexData
  33681. if (vertexData) {
  33682. this.setAllVerticesData(vertexData, updatable);
  33683. }
  33684. else {
  33685. this._totalVertices = 0;
  33686. this._indices = [];
  33687. }
  33688. // applyToMesh
  33689. if (mesh) {
  33690. if (mesh instanceof BABYLON.LinesMesh) {
  33691. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  33692. this.updateExtend();
  33693. }
  33694. this.applyToMesh(mesh);
  33695. mesh.computeWorldMatrix(true);
  33696. }
  33697. }
  33698. Object.defineProperty(Geometry.prototype, "boundingBias", {
  33699. /**
  33700. * 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
  33701. * @returns The Bias Vector
  33702. */
  33703. get: function () {
  33704. return this._boundingBias;
  33705. },
  33706. set: function (value) {
  33707. if (this._boundingBias && this._boundingBias.equals(value)) {
  33708. return;
  33709. }
  33710. this._boundingBias = value.clone();
  33711. this.updateBoundingInfo(true, null);
  33712. },
  33713. enumerable: true,
  33714. configurable: true
  33715. });
  33716. Object.defineProperty(Geometry.prototype, "extend", {
  33717. get: function () {
  33718. return this._extend;
  33719. },
  33720. enumerable: true,
  33721. configurable: true
  33722. });
  33723. Geometry.prototype.getScene = function () {
  33724. return this._scene;
  33725. };
  33726. Geometry.prototype.getEngine = function () {
  33727. return this._engine;
  33728. };
  33729. Geometry.prototype.isReady = function () {
  33730. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  33731. };
  33732. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  33733. vertexData.applyToGeometry(this, updatable);
  33734. this.notifyUpdate();
  33735. };
  33736. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  33737. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  33738. this.setVerticesBuffer(buffer);
  33739. };
  33740. Geometry.prototype.setVerticesBuffer = function (buffer) {
  33741. var kind = buffer.getKind();
  33742. if (this._vertexBuffers[kind]) {
  33743. this._vertexBuffers[kind].dispose();
  33744. }
  33745. this._vertexBuffers[kind] = buffer;
  33746. if (kind === BABYLON.VertexBuffer.PositionKind) {
  33747. var data = buffer.getData();
  33748. var stride = buffer.getStrideSize();
  33749. this._totalVertices = data.length / stride;
  33750. this.updateExtend(data, stride);
  33751. var meshes = this._meshes;
  33752. var numOfMeshes = meshes.length;
  33753. for (var index = 0; index < numOfMeshes; index++) {
  33754. var mesh = meshes[index];
  33755. mesh._resetPointsArrayCache();
  33756. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  33757. mesh._createGlobalSubMesh();
  33758. mesh.computeWorldMatrix(true);
  33759. }
  33760. }
  33761. this.notifyUpdate(kind);
  33762. };
  33763. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  33764. var vertexBuffer = this.getVertexBuffer(kind);
  33765. if (!vertexBuffer) {
  33766. return;
  33767. }
  33768. vertexBuffer.updateDirectly(data, offset);
  33769. this.notifyUpdate(kind);
  33770. };
  33771. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  33772. var vertexBuffer = this.getVertexBuffer(kind);
  33773. if (!vertexBuffer) {
  33774. return;
  33775. }
  33776. vertexBuffer.update(data);
  33777. if (kind === BABYLON.VertexBuffer.PositionKind) {
  33778. var stride = vertexBuffer.getStrideSize();
  33779. this._totalVertices = data.length / stride;
  33780. this.updateBoundingInfo(updateExtends, data);
  33781. }
  33782. this.notifyUpdate(kind);
  33783. };
  33784. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  33785. if (updateExtends) {
  33786. this.updateExtend(data);
  33787. }
  33788. var meshes = this._meshes;
  33789. var numOfMeshes = meshes.length;
  33790. for (var index = 0; index < numOfMeshes; index++) {
  33791. var mesh = meshes[index];
  33792. mesh._resetPointsArrayCache();
  33793. if (updateExtends) {
  33794. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  33795. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  33796. var subMesh = mesh.subMeshes[subIndex];
  33797. subMesh.refreshBoundingInfo();
  33798. }
  33799. }
  33800. }
  33801. };
  33802. Geometry.prototype.getTotalVertices = function () {
  33803. if (!this.isReady()) {
  33804. return 0;
  33805. }
  33806. return this._totalVertices;
  33807. };
  33808. Geometry.prototype.getVerticesData = function (kind, copyWhenShared) {
  33809. var vertexBuffer = this.getVertexBuffer(kind);
  33810. if (!vertexBuffer) {
  33811. return null;
  33812. }
  33813. var orig = vertexBuffer.getData();
  33814. if (!copyWhenShared || this._meshes.length === 1) {
  33815. return orig;
  33816. }
  33817. else {
  33818. var len = orig.length;
  33819. var copy = [];
  33820. for (var i = 0; i < len; i++) {
  33821. copy.push(orig[i]);
  33822. }
  33823. return copy;
  33824. }
  33825. };
  33826. Geometry.prototype.getVertexBuffer = function (kind) {
  33827. if (!this.isReady()) {
  33828. return null;
  33829. }
  33830. return this._vertexBuffers[kind];
  33831. };
  33832. Geometry.prototype.getVertexBuffers = function () {
  33833. if (!this.isReady()) {
  33834. return null;
  33835. }
  33836. return this._vertexBuffers;
  33837. };
  33838. Geometry.prototype.isVerticesDataPresent = function (kind) {
  33839. if (!this._vertexBuffers) {
  33840. if (this._delayInfo) {
  33841. return this._delayInfo.indexOf(kind) !== -1;
  33842. }
  33843. return false;
  33844. }
  33845. return this._vertexBuffers[kind] !== undefined;
  33846. };
  33847. Geometry.prototype.getVerticesDataKinds = function () {
  33848. var result = [];
  33849. var kind;
  33850. if (!this._vertexBuffers && this._delayInfo) {
  33851. for (kind in this._delayInfo) {
  33852. result.push(kind);
  33853. }
  33854. }
  33855. else {
  33856. for (kind in this._vertexBuffers) {
  33857. result.push(kind);
  33858. }
  33859. }
  33860. return result;
  33861. };
  33862. Geometry.prototype.setIndices = function (indices, totalVertices) {
  33863. if (this._indexBuffer) {
  33864. this._engine._releaseBuffer(this._indexBuffer);
  33865. }
  33866. this._indices = indices;
  33867. if (this._meshes.length !== 0 && this._indices) {
  33868. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  33869. }
  33870. if (totalVertices !== undefined) {
  33871. this._totalVertices = totalVertices;
  33872. }
  33873. var meshes = this._meshes;
  33874. var numOfMeshes = meshes.length;
  33875. for (var index = 0; index < numOfMeshes; index++) {
  33876. meshes[index]._createGlobalSubMesh();
  33877. }
  33878. this.notifyUpdate();
  33879. };
  33880. Geometry.prototype.getTotalIndices = function () {
  33881. if (!this.isReady()) {
  33882. return 0;
  33883. }
  33884. return this._indices.length;
  33885. };
  33886. Geometry.prototype.getIndices = function (copyWhenShared) {
  33887. if (!this.isReady()) {
  33888. return null;
  33889. }
  33890. var orig = this._indices;
  33891. if (!copyWhenShared || this._meshes.length === 1) {
  33892. return orig;
  33893. }
  33894. else {
  33895. var len = orig.length;
  33896. var copy = [];
  33897. for (var i = 0; i < len; i++) {
  33898. copy.push(orig[i]);
  33899. }
  33900. return copy;
  33901. }
  33902. };
  33903. Geometry.prototype.getIndexBuffer = function () {
  33904. if (!this.isReady()) {
  33905. return null;
  33906. }
  33907. return this._indexBuffer;
  33908. };
  33909. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  33910. var meshes = this._meshes;
  33911. var index = meshes.indexOf(mesh);
  33912. if (index === -1) {
  33913. return;
  33914. }
  33915. for (var kind in this._vertexBuffers) {
  33916. this._vertexBuffers[kind].dispose();
  33917. }
  33918. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  33919. this._indexBuffer = null;
  33920. }
  33921. meshes.splice(index, 1);
  33922. mesh._geometry = null;
  33923. if (meshes.length === 0 && shouldDispose) {
  33924. this.dispose();
  33925. }
  33926. };
  33927. Geometry.prototype.applyToMesh = function (mesh) {
  33928. if (mesh._geometry === this) {
  33929. return;
  33930. }
  33931. var previousGeometry = mesh._geometry;
  33932. if (previousGeometry) {
  33933. previousGeometry.releaseForMesh(mesh);
  33934. }
  33935. var meshes = this._meshes;
  33936. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  33937. mesh._geometry = this;
  33938. this._scene.pushGeometry(this);
  33939. meshes.push(mesh);
  33940. if (this.isReady()) {
  33941. this._applyToMesh(mesh);
  33942. }
  33943. else {
  33944. mesh._boundingInfo = this._boundingInfo;
  33945. }
  33946. };
  33947. Geometry.prototype.updateExtend = function (data, stride) {
  33948. if (data === void 0) { data = null; }
  33949. if (!data) {
  33950. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  33951. }
  33952. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  33953. };
  33954. Geometry.prototype._applyToMesh = function (mesh) {
  33955. var numOfMeshes = this._meshes.length;
  33956. // vertexBuffers
  33957. for (var kind in this._vertexBuffers) {
  33958. if (numOfMeshes === 1) {
  33959. this._vertexBuffers[kind].create();
  33960. }
  33961. this._vertexBuffers[kind].getBuffer().references = numOfMeshes;
  33962. if (kind === BABYLON.VertexBuffer.PositionKind) {
  33963. mesh._resetPointsArrayCache();
  33964. if (!this._extend) {
  33965. this.updateExtend(this._vertexBuffers[kind].getData());
  33966. }
  33967. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  33968. mesh._createGlobalSubMesh();
  33969. //bounding info was just created again, world matrix should be applied again.
  33970. mesh._updateBoundingInfo();
  33971. }
  33972. }
  33973. // indexBuffer
  33974. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  33975. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  33976. }
  33977. if (this._indexBuffer) {
  33978. this._indexBuffer.references = numOfMeshes;
  33979. }
  33980. };
  33981. Geometry.prototype.notifyUpdate = function (kind) {
  33982. if (this.onGeometryUpdated) {
  33983. this.onGeometryUpdated(this, kind);
  33984. }
  33985. };
  33986. Geometry.prototype.load = function (scene, onLoaded) {
  33987. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  33988. return;
  33989. }
  33990. if (this.isReady()) {
  33991. if (onLoaded) {
  33992. onLoaded();
  33993. }
  33994. return;
  33995. }
  33996. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  33997. this._queueLoad(scene, onLoaded);
  33998. };
  33999. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  34000. var _this = this;
  34001. scene._addPendingData(this);
  34002. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  34003. _this._delayLoadingFunction(JSON.parse(data), _this);
  34004. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  34005. _this._delayInfo = [];
  34006. scene._removePendingData(_this);
  34007. var meshes = _this._meshes;
  34008. var numOfMeshes = meshes.length;
  34009. for (var index = 0; index < numOfMeshes; index++) {
  34010. _this._applyToMesh(meshes[index]);
  34011. }
  34012. if (onLoaded) {
  34013. onLoaded();
  34014. }
  34015. }, function () { }, scene.database);
  34016. };
  34017. /**
  34018. * Invert the geometry to move from a right handed system to a left handed one.
  34019. */
  34020. Geometry.prototype.toLeftHanded = function () {
  34021. // Flip faces
  34022. var tIndices = this.getIndices(false);
  34023. if (tIndices != null && tIndices.length > 0) {
  34024. for (var i = 0; i < tIndices.length; i += 3) {
  34025. var tTemp = tIndices[i + 0];
  34026. tIndices[i + 0] = tIndices[i + 2];
  34027. tIndices[i + 2] = tTemp;
  34028. }
  34029. this.setIndices(tIndices);
  34030. }
  34031. // Negate position.z
  34032. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  34033. if (tPositions != null && tPositions.length > 0) {
  34034. for (var i = 0; i < tPositions.length; i += 3) {
  34035. tPositions[i + 2] = -tPositions[i + 2];
  34036. }
  34037. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  34038. }
  34039. // Negate normal.z
  34040. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  34041. if (tNormals != null && tNormals.length > 0) {
  34042. for (var i = 0; i < tNormals.length; i += 3) {
  34043. tNormals[i + 2] = -tNormals[i + 2];
  34044. }
  34045. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  34046. }
  34047. };
  34048. Geometry.prototype.isDisposed = function () {
  34049. return this._isDisposed;
  34050. };
  34051. Geometry.prototype.dispose = function () {
  34052. var meshes = this._meshes;
  34053. var numOfMeshes = meshes.length;
  34054. var index;
  34055. for (index = 0; index < numOfMeshes; index++) {
  34056. this.releaseForMesh(meshes[index]);
  34057. }
  34058. this._meshes = [];
  34059. for (var kind in this._vertexBuffers) {
  34060. this._vertexBuffers[kind].dispose();
  34061. }
  34062. this._vertexBuffers = {};
  34063. this._totalVertices = 0;
  34064. if (this._indexBuffer) {
  34065. this._engine._releaseBuffer(this._indexBuffer);
  34066. }
  34067. this._indexBuffer = null;
  34068. this._indices = [];
  34069. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  34070. this.delayLoadingFile = null;
  34071. this._delayLoadingFunction = null;
  34072. this._delayInfo = [];
  34073. this._boundingInfo = null;
  34074. this._scene.removeGeometry(this);
  34075. this._isDisposed = true;
  34076. };
  34077. Geometry.prototype.copy = function (id) {
  34078. var vertexData = new BABYLON.VertexData();
  34079. vertexData.indices = [];
  34080. var indices = this.getIndices();
  34081. for (var index = 0; index < indices.length; index++) {
  34082. vertexData.indices.push(indices[index]);
  34083. }
  34084. var updatable = false;
  34085. var stopChecking = false;
  34086. var kind;
  34087. for (kind in this._vertexBuffers) {
  34088. // using slice() to make a copy of the array and not just reference it
  34089. var data = this.getVerticesData(kind);
  34090. if (data instanceof Float32Array) {
  34091. vertexData.set(new Float32Array(data), kind);
  34092. }
  34093. else {
  34094. vertexData.set(data.slice(0), kind);
  34095. }
  34096. if (!stopChecking) {
  34097. updatable = this.getVertexBuffer(kind).isUpdatable();
  34098. stopChecking = !updatable;
  34099. }
  34100. }
  34101. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  34102. geometry.delayLoadState = this.delayLoadState;
  34103. geometry.delayLoadingFile = this.delayLoadingFile;
  34104. geometry._delayLoadingFunction = this._delayLoadingFunction;
  34105. for (kind in this._delayInfo) {
  34106. geometry._delayInfo = geometry._delayInfo || [];
  34107. geometry._delayInfo.push(kind);
  34108. }
  34109. // Bounding info
  34110. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  34111. return geometry;
  34112. };
  34113. Geometry.prototype.serialize = function () {
  34114. var serializationObject = {};
  34115. serializationObject.id = this.id;
  34116. if (BABYLON.Tags.HasTags(this)) {
  34117. serializationObject.tags = BABYLON.Tags.GetTags(this);
  34118. }
  34119. return serializationObject;
  34120. };
  34121. Geometry.prototype.serializeVerticeData = function () {
  34122. var serializationObject = this.serialize();
  34123. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  34124. serializationObject.positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34125. }
  34126. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  34127. serializationObject.normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  34128. }
  34129. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  34130. serializationObject.uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  34131. }
  34132. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  34133. serializationObject.uvs2 = this.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  34134. }
  34135. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  34136. serializationObject.uvs3 = this.getVerticesData(BABYLON.VertexBuffer.UV3Kind);
  34137. }
  34138. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  34139. serializationObject.uvs4 = this.getVerticesData(BABYLON.VertexBuffer.UV4Kind);
  34140. }
  34141. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  34142. serializationObject.uvs5 = this.getVerticesData(BABYLON.VertexBuffer.UV5Kind);
  34143. }
  34144. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  34145. serializationObject.uvs6 = this.getVerticesData(BABYLON.VertexBuffer.UV6Kind);
  34146. }
  34147. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  34148. serializationObject.colors = this.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  34149. }
  34150. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  34151. serializationObject.matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  34152. serializationObject.matricesIndices._isExpanded = true;
  34153. }
  34154. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  34155. serializationObject.matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  34156. }
  34157. serializationObject.indices = this.getIndices();
  34158. return serializationObject;
  34159. };
  34160. // Statics
  34161. Geometry.ExtractFromMesh = function (mesh, id) {
  34162. var geometry = mesh._geometry;
  34163. if (!geometry) {
  34164. return null;
  34165. }
  34166. return geometry.copy(id);
  34167. };
  34168. // from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  34169. // be aware Math.random() could cause collisions
  34170. Geometry.RandomId = function () {
  34171. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  34172. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  34173. return v.toString(16);
  34174. });
  34175. };
  34176. Geometry.ImportGeometry = function (parsedGeometry, mesh) {
  34177. var scene = mesh.getScene();
  34178. // Geometry
  34179. var geometryId = parsedGeometry.geometryId;
  34180. if (geometryId) {
  34181. var geometry = scene.getGeometryByID(geometryId);
  34182. if (geometry) {
  34183. geometry.applyToMesh(mesh);
  34184. }
  34185. }
  34186. else if (parsedGeometry instanceof ArrayBuffer) {
  34187. var binaryInfo = mesh._binaryInfo;
  34188. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  34189. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  34190. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  34191. }
  34192. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  34193. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  34194. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  34195. }
  34196. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  34197. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  34198. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  34199. }
  34200. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  34201. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  34202. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  34203. }
  34204. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  34205. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  34206. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  34207. }
  34208. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  34209. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  34210. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  34211. }
  34212. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  34213. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  34214. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  34215. }
  34216. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  34217. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  34218. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  34219. }
  34220. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  34221. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  34222. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  34223. }
  34224. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  34225. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  34226. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  34227. }
  34228. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  34229. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  34230. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  34231. }
  34232. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  34233. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  34234. mesh.setIndices(indicesData);
  34235. }
  34236. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  34237. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  34238. mesh.subMeshes = [];
  34239. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  34240. var materialIndex = subMeshesData[(i * 5) + 0];
  34241. var verticesStart = subMeshesData[(i * 5) + 1];
  34242. var verticesCount = subMeshesData[(i * 5) + 2];
  34243. var indexStart = subMeshesData[(i * 5) + 3];
  34244. var indexCount = subMeshesData[(i * 5) + 4];
  34245. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  34246. }
  34247. }
  34248. }
  34249. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  34250. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  34251. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  34252. if (parsedGeometry.uvs) {
  34253. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  34254. }
  34255. if (parsedGeometry.uvs2) {
  34256. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  34257. }
  34258. if (parsedGeometry.uvs3) {
  34259. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, false);
  34260. }
  34261. if (parsedGeometry.uvs4) {
  34262. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, false);
  34263. }
  34264. if (parsedGeometry.uvs5) {
  34265. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, false);
  34266. }
  34267. if (parsedGeometry.uvs6) {
  34268. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, false);
  34269. }
  34270. if (parsedGeometry.colors) {
  34271. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), false);
  34272. }
  34273. if (parsedGeometry.matricesIndices) {
  34274. if (!parsedGeometry.matricesIndices._isExpanded) {
  34275. var floatIndices = [];
  34276. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  34277. var matricesIndex = parsedGeometry.matricesIndices[i];
  34278. floatIndices.push(matricesIndex & 0x000000FF);
  34279. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  34280. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  34281. floatIndices.push(matricesIndex >> 24);
  34282. }
  34283. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  34284. }
  34285. else {
  34286. delete parsedGeometry.matricesIndices._isExpanded;
  34287. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  34288. }
  34289. }
  34290. if (parsedGeometry.matricesIndicesExtra) {
  34291. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  34292. var floatIndices = [];
  34293. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  34294. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  34295. floatIndices.push(matricesIndex & 0x000000FF);
  34296. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  34297. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  34298. floatIndices.push(matricesIndex >> 24);
  34299. }
  34300. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, false);
  34301. }
  34302. else {
  34303. delete parsedGeometry.matricesIndices._isExpanded;
  34304. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, false);
  34305. }
  34306. }
  34307. if (parsedGeometry.matricesWeights) {
  34308. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  34309. }
  34310. if (parsedGeometry.matricesWeightsExtra) {
  34311. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, false);
  34312. }
  34313. mesh.setIndices(parsedGeometry.indices);
  34314. }
  34315. // SubMeshes
  34316. if (parsedGeometry.subMeshes) {
  34317. mesh.subMeshes = [];
  34318. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  34319. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  34320. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  34321. }
  34322. }
  34323. // Flat shading
  34324. if (mesh._shouldGenerateFlatShading) {
  34325. mesh.convertToFlatShadedMesh();
  34326. delete mesh._shouldGenerateFlatShading;
  34327. }
  34328. // Update
  34329. mesh.computeWorldMatrix(true);
  34330. // Octree
  34331. if (scene['_selectionOctree']) {
  34332. scene['_selectionOctree'].addMesh(mesh);
  34333. }
  34334. };
  34335. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  34336. if (scene.getGeometryByID(parsedVertexData.id)) {
  34337. return null; // null since geometry could be something else than a box...
  34338. }
  34339. var geometry = new Geometry(parsedVertexData.id, scene);
  34340. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  34341. if (parsedVertexData.delayLoadingFile) {
  34342. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  34343. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  34344. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  34345. geometry._delayInfo = [];
  34346. if (parsedVertexData.hasUVs) {
  34347. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  34348. }
  34349. if (parsedVertexData.hasUVs2) {
  34350. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  34351. }
  34352. if (parsedVertexData.hasUVs3) {
  34353. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  34354. }
  34355. if (parsedVertexData.hasUVs4) {
  34356. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  34357. }
  34358. if (parsedVertexData.hasUVs5) {
  34359. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  34360. }
  34361. if (parsedVertexData.hasUVs6) {
  34362. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  34363. }
  34364. if (parsedVertexData.hasColors) {
  34365. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  34366. }
  34367. if (parsedVertexData.hasMatricesIndices) {
  34368. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  34369. }
  34370. if (parsedVertexData.hasMatricesWeights) {
  34371. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  34372. }
  34373. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  34374. }
  34375. else {
  34376. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  34377. }
  34378. scene.pushGeometry(geometry, true);
  34379. return geometry;
  34380. };
  34381. return Geometry;
  34382. })();
  34383. BABYLON.Geometry = Geometry;
  34384. /////// Primitives //////////////////////////////////////////////
  34385. var Geometry;
  34386. (function (Geometry) {
  34387. var Primitives;
  34388. (function (Primitives) {
  34389. /// Abstract class
  34390. var _Primitive = (function (_super) {
  34391. __extends(_Primitive, _super);
  34392. function _Primitive(id, scene, _canBeRegenerated, mesh) {
  34393. _super.call(this, id, scene, null, false, mesh); // updatable = false to be sure not to update vertices
  34394. this._canBeRegenerated = _canBeRegenerated;
  34395. this._beingRegenerated = true;
  34396. this.regenerate();
  34397. this._beingRegenerated = false;
  34398. }
  34399. _Primitive.prototype.canBeRegenerated = function () {
  34400. return this._canBeRegenerated;
  34401. };
  34402. _Primitive.prototype.regenerate = function () {
  34403. if (!this._canBeRegenerated) {
  34404. return;
  34405. }
  34406. this._beingRegenerated = true;
  34407. this.setAllVerticesData(this._regenerateVertexData(), false);
  34408. this._beingRegenerated = false;
  34409. };
  34410. _Primitive.prototype.asNewGeometry = function (id) {
  34411. return _super.prototype.copy.call(this, id);
  34412. };
  34413. // overrides
  34414. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  34415. if (!this._beingRegenerated) {
  34416. return;
  34417. }
  34418. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  34419. };
  34420. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  34421. if (!this._beingRegenerated) {
  34422. return;
  34423. }
  34424. _super.prototype.setVerticesData.call(this, kind, data, false);
  34425. };
  34426. // to override
  34427. // protected
  34428. _Primitive.prototype._regenerateVertexData = function () {
  34429. throw new Error("Abstract method");
  34430. };
  34431. _Primitive.prototype.copy = function (id) {
  34432. throw new Error("Must be overriden in sub-classes.");
  34433. };
  34434. _Primitive.prototype.serialize = function () {
  34435. var serializationObject = _super.prototype.serialize.call(this);
  34436. serializationObject.canBeRegenerated = this.canBeRegenerated();
  34437. return serializationObject;
  34438. };
  34439. return _Primitive;
  34440. })(Geometry);
  34441. Primitives._Primitive = _Primitive;
  34442. var Ribbon = (function (_super) {
  34443. __extends(Ribbon, _super);
  34444. // Members
  34445. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  34446. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  34447. _super.call(this, id, scene, canBeRegenerated, mesh);
  34448. this.pathArray = pathArray;
  34449. this.closeArray = closeArray;
  34450. this.closePath = closePath;
  34451. this.offset = offset;
  34452. this.side = side;
  34453. }
  34454. Ribbon.prototype._regenerateVertexData = function () {
  34455. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  34456. };
  34457. Ribbon.prototype.copy = function (id) {
  34458. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  34459. };
  34460. return Ribbon;
  34461. })(_Primitive);
  34462. Primitives.Ribbon = Ribbon;
  34463. var Box = (function (_super) {
  34464. __extends(Box, _super);
  34465. // Members
  34466. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  34467. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  34468. _super.call(this, id, scene, canBeRegenerated, mesh);
  34469. this.size = size;
  34470. this.side = side;
  34471. }
  34472. Box.prototype._regenerateVertexData = function () {
  34473. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  34474. };
  34475. Box.prototype.copy = function (id) {
  34476. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  34477. };
  34478. Box.prototype.serialize = function () {
  34479. var serializationObject = _super.prototype.serialize.call(this);
  34480. serializationObject.size = this.size;
  34481. return serializationObject;
  34482. };
  34483. Box.Parse = function (parsedBox, scene) {
  34484. if (scene.getGeometryByID(parsedBox.id)) {
  34485. return null; // null since geometry could be something else than a box...
  34486. }
  34487. var box = new Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  34488. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  34489. scene.pushGeometry(box, true);
  34490. return box;
  34491. };
  34492. return Box;
  34493. })(_Primitive);
  34494. Primitives.Box = Box;
  34495. var Sphere = (function (_super) {
  34496. __extends(Sphere, _super);
  34497. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  34498. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  34499. _super.call(this, id, scene, canBeRegenerated, mesh);
  34500. this.segments = segments;
  34501. this.diameter = diameter;
  34502. this.side = side;
  34503. }
  34504. Sphere.prototype._regenerateVertexData = function () {
  34505. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  34506. };
  34507. Sphere.prototype.copy = function (id) {
  34508. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  34509. };
  34510. Sphere.prototype.serialize = function () {
  34511. var serializationObject = _super.prototype.serialize.call(this);
  34512. serializationObject.segments = this.segments;
  34513. serializationObject.diameter = this.diameter;
  34514. return serializationObject;
  34515. };
  34516. Sphere.Parse = function (parsedSphere, scene) {
  34517. if (scene.getGeometryByID(parsedSphere.id)) {
  34518. return null; // null since geometry could be something else than a sphere...
  34519. }
  34520. var sphere = new Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  34521. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  34522. scene.pushGeometry(sphere, true);
  34523. return sphere;
  34524. };
  34525. return Sphere;
  34526. })(_Primitive);
  34527. Primitives.Sphere = Sphere;
  34528. var Disc = (function (_super) {
  34529. __extends(Disc, _super);
  34530. // Members
  34531. function Disc(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  34532. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  34533. _super.call(this, id, scene, canBeRegenerated, mesh);
  34534. this.radius = radius;
  34535. this.tessellation = tessellation;
  34536. this.side = side;
  34537. }
  34538. Disc.prototype._regenerateVertexData = function () {
  34539. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  34540. };
  34541. Disc.prototype.copy = function (id) {
  34542. return new Disc(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  34543. };
  34544. return Disc;
  34545. })(_Primitive);
  34546. Primitives.Disc = Disc;
  34547. var Cylinder = (function (_super) {
  34548. __extends(Cylinder, _super);
  34549. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  34550. if (subdivisions === void 0) { subdivisions = 1; }
  34551. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  34552. _super.call(this, id, scene, canBeRegenerated, mesh);
  34553. this.height = height;
  34554. this.diameterTop = diameterTop;
  34555. this.diameterBottom = diameterBottom;
  34556. this.tessellation = tessellation;
  34557. this.subdivisions = subdivisions;
  34558. this.side = side;
  34559. }
  34560. Cylinder.prototype._regenerateVertexData = function () {
  34561. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  34562. };
  34563. Cylinder.prototype.copy = function (id) {
  34564. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  34565. };
  34566. Cylinder.prototype.serialize = function () {
  34567. var serializationObject = _super.prototype.serialize.call(this);
  34568. serializationObject.height = this.height;
  34569. serializationObject.diameterTop = this.diameterTop;
  34570. serializationObject.diameterBottom = this.diameterBottom;
  34571. serializationObject.tessellation = this.tessellation;
  34572. return serializationObject;
  34573. };
  34574. Cylinder.Parse = function (parsedCylinder, scene) {
  34575. if (scene.getGeometryByID(parsedCylinder.id)) {
  34576. return null; // null since geometry could be something else than a cylinder...
  34577. }
  34578. var cylinder = new Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  34579. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  34580. scene.pushGeometry(cylinder, true);
  34581. return cylinder;
  34582. };
  34583. return Cylinder;
  34584. })(_Primitive);
  34585. Primitives.Cylinder = Cylinder;
  34586. var Torus = (function (_super) {
  34587. __extends(Torus, _super);
  34588. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  34589. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  34590. _super.call(this, id, scene, canBeRegenerated, mesh);
  34591. this.diameter = diameter;
  34592. this.thickness = thickness;
  34593. this.tessellation = tessellation;
  34594. this.side = side;
  34595. }
  34596. Torus.prototype._regenerateVertexData = function () {
  34597. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  34598. };
  34599. Torus.prototype.copy = function (id) {
  34600. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  34601. };
  34602. Torus.prototype.serialize = function () {
  34603. var serializationObject = _super.prototype.serialize.call(this);
  34604. serializationObject.diameter = this.diameter;
  34605. serializationObject.thickness = this.thickness;
  34606. serializationObject.tessellation = this.tessellation;
  34607. return serializationObject;
  34608. };
  34609. Torus.Parse = function (parsedTorus, scene) {
  34610. if (scene.getGeometryByID(parsedTorus.id)) {
  34611. return null; // null since geometry could be something else than a torus...
  34612. }
  34613. var torus = new Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  34614. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  34615. scene.pushGeometry(torus, true);
  34616. return torus;
  34617. };
  34618. return Torus;
  34619. })(_Primitive);
  34620. Primitives.Torus = Torus;
  34621. var Ground = (function (_super) {
  34622. __extends(Ground, _super);
  34623. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  34624. _super.call(this, id, scene, canBeRegenerated, mesh);
  34625. this.width = width;
  34626. this.height = height;
  34627. this.subdivisions = subdivisions;
  34628. }
  34629. Ground.prototype._regenerateVertexData = function () {
  34630. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  34631. };
  34632. Ground.prototype.copy = function (id) {
  34633. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  34634. };
  34635. Ground.prototype.serialize = function () {
  34636. var serializationObject = _super.prototype.serialize.call(this);
  34637. serializationObject.width = this.width;
  34638. serializationObject.height = this.height;
  34639. serializationObject.subdivisions = this.subdivisions;
  34640. return serializationObject;
  34641. };
  34642. Ground.Parse = function (parsedGround, scene) {
  34643. if (scene.getGeometryByID(parsedGround.id)) {
  34644. return null; // null since geometry could be something else than a ground...
  34645. }
  34646. var ground = new Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  34647. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  34648. scene.pushGeometry(ground, true);
  34649. return ground;
  34650. };
  34651. return Ground;
  34652. })(_Primitive);
  34653. Primitives.Ground = Ground;
  34654. var TiledGround = (function (_super) {
  34655. __extends(TiledGround, _super);
  34656. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  34657. _super.call(this, id, scene, canBeRegenerated, mesh);
  34658. this.xmin = xmin;
  34659. this.zmin = zmin;
  34660. this.xmax = xmax;
  34661. this.zmax = zmax;
  34662. this.subdivisions = subdivisions;
  34663. this.precision = precision;
  34664. }
  34665. TiledGround.prototype._regenerateVertexData = function () {
  34666. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  34667. };
  34668. TiledGround.prototype.copy = function (id) {
  34669. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  34670. };
  34671. return TiledGround;
  34672. })(_Primitive);
  34673. Primitives.TiledGround = TiledGround;
  34674. var Plane = (function (_super) {
  34675. __extends(Plane, _super);
  34676. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  34677. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  34678. _super.call(this, id, scene, canBeRegenerated, mesh);
  34679. this.size = size;
  34680. this.side = side;
  34681. }
  34682. Plane.prototype._regenerateVertexData = function () {
  34683. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  34684. };
  34685. Plane.prototype.copy = function (id) {
  34686. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  34687. };
  34688. Plane.prototype.serialize = function () {
  34689. var serializationObject = _super.prototype.serialize.call(this);
  34690. serializationObject.size = this.size;
  34691. return serializationObject;
  34692. };
  34693. Plane.Parse = function (parsedPlane, scene) {
  34694. if (scene.getGeometryByID(parsedPlane.id)) {
  34695. return null; // null since geometry could be something else than a ground...
  34696. }
  34697. var plane = new Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  34698. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  34699. scene.pushGeometry(plane, true);
  34700. return plane;
  34701. };
  34702. return Plane;
  34703. })(_Primitive);
  34704. Primitives.Plane = Plane;
  34705. var TorusKnot = (function (_super) {
  34706. __extends(TorusKnot, _super);
  34707. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  34708. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  34709. _super.call(this, id, scene, canBeRegenerated, mesh);
  34710. this.radius = radius;
  34711. this.tube = tube;
  34712. this.radialSegments = radialSegments;
  34713. this.tubularSegments = tubularSegments;
  34714. this.p = p;
  34715. this.q = q;
  34716. this.side = side;
  34717. }
  34718. TorusKnot.prototype._regenerateVertexData = function () {
  34719. 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 });
  34720. };
  34721. TorusKnot.prototype.copy = function (id) {
  34722. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  34723. };
  34724. TorusKnot.prototype.serialize = function () {
  34725. var serializationObject = _super.prototype.serialize.call(this);
  34726. serializationObject.radius = this.radius;
  34727. serializationObject.tube = this.tube;
  34728. serializationObject.radialSegments = this.radialSegments;
  34729. serializationObject.tubularSegments = this.tubularSegments;
  34730. serializationObject.p = this.p;
  34731. serializationObject.q = this.q;
  34732. return serializationObject;
  34733. };
  34734. ;
  34735. TorusKnot.Parse = function (parsedTorusKnot, scene) {
  34736. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  34737. return null; // null since geometry could be something else than a ground...
  34738. }
  34739. var torusKnot = new Geometry.Primitives.TorusKnot(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  34740. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  34741. scene.pushGeometry(torusKnot, true);
  34742. return torusKnot;
  34743. };
  34744. return TorusKnot;
  34745. })(_Primitive);
  34746. Primitives.TorusKnot = TorusKnot;
  34747. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  34748. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  34749. })(BABYLON || (BABYLON = {}));
  34750. var BABYLON;
  34751. (function (BABYLON) {
  34752. var GroundMesh = (function (_super) {
  34753. __extends(GroundMesh, _super);
  34754. function GroundMesh(name, scene) {
  34755. _super.call(this, name, scene);
  34756. this.generateOctree = false;
  34757. this._worldInverse = new BABYLON.Matrix();
  34758. }
  34759. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  34760. get: function () {
  34761. return this._subdivisions;
  34762. },
  34763. enumerable: true,
  34764. configurable: true
  34765. });
  34766. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  34767. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  34768. this._subdivisions = chunksCount;
  34769. this.subdivide(this._subdivisions);
  34770. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  34771. };
  34772. /**
  34773. * Returns a height (y) value in the Worl system :
  34774. * the ground altitude at the coordinates (x, z) expressed in the World system.
  34775. * Returns the ground y position if (x, z) are outside the ground surface.
  34776. * Not pertinent if the ground is rotated.
  34777. */
  34778. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  34779. // express x and y in the ground local system
  34780. x -= this.position.x;
  34781. z -= this.position.z;
  34782. x /= this.scaling.x;
  34783. z /= this.scaling.z;
  34784. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  34785. return this.position.y;
  34786. }
  34787. if (!this._heightQuads || this._heightQuads.length == 0) {
  34788. this._initHeightQuads();
  34789. this._computeHeightQuads();
  34790. }
  34791. var facet = this._getFacetAt(x, z);
  34792. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  34793. // return y in the World system
  34794. return y * this.scaling.y + this.position.y;
  34795. };
  34796. /**
  34797. * Returns a normalized vector (Vector3) orthogonal to the ground
  34798. * at the ground coordinates (x, z) expressed in the World system.
  34799. * Returns Vector3(0, 1, 0) if (x, z) are outside the ground surface.
  34800. * Not pertinent if the ground is rotated.
  34801. */
  34802. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  34803. var normal = new BABYLON.Vector3(0, 1, 0);
  34804. this.getNormalAtCoordinatesToRef(x, z, normal);
  34805. return normal;
  34806. };
  34807. /**
  34808. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  34809. * at the ground coordinates (x, z) expressed in the World system.
  34810. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  34811. * Not pertinent if the ground is rotated.
  34812. */
  34813. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  34814. // express x and y in the ground local system
  34815. x -= this.position.x;
  34816. z -= this.position.z;
  34817. x /= this.scaling.x;
  34818. z /= this.scaling.z;
  34819. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  34820. return;
  34821. }
  34822. if (!this._heightQuads || this._heightQuads.length == 0) {
  34823. this._initHeightQuads();
  34824. this._computeHeightQuads();
  34825. }
  34826. var facet = this._getFacetAt(x, z);
  34827. ref.x = facet.x;
  34828. ref.y = facet.y;
  34829. ref.z = facet.z;
  34830. };
  34831. /**
  34832. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  34833. * if the ground has been updated.
  34834. * This can be used in the render loop
  34835. */
  34836. GroundMesh.prototype.updateCoordinateHeights = function () {
  34837. if (!this._heightQuads || this._heightQuads.length == 0) {
  34838. this._initHeightQuads();
  34839. }
  34840. this._computeHeightQuads();
  34841. };
  34842. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  34843. GroundMesh.prototype._getFacetAt = function (x, z) {
  34844. // retrieve col and row from x, z coordinates in the ground local system
  34845. var col = Math.floor((x + this._maxX) * this._subdivisions / this._width);
  34846. var row = Math.floor(-(z + this._maxZ) * this._subdivisions / this._height + this._subdivisions);
  34847. var quad = this._heightQuads[row * this._subdivisions + col];
  34848. var facet;
  34849. if (z < quad.slope.x * x + quad.slope.y) {
  34850. facet = quad.facet1;
  34851. }
  34852. else {
  34853. facet = quad.facet2;
  34854. }
  34855. return facet;
  34856. };
  34857. // Creates and populates the heightMap array with "facet" elements :
  34858. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  34859. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  34860. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  34861. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  34862. GroundMesh.prototype._initHeightQuads = function () {
  34863. this._heightQuads = new Array();
  34864. for (var row = 0; row < this._subdivisions; row++) {
  34865. for (var col = 0; col < this._subdivisions; col++) {
  34866. var quad = { slope: BABYLON.Vector2.Zero(), facet1: new BABYLON.Vector4(0, 0, 0, 0), facet2: new BABYLON.Vector4(0, 0, 0, 0) };
  34867. this._heightQuads[row * this._subdivisions + col] = quad;
  34868. }
  34869. }
  34870. };
  34871. // Compute each quad element values and update the the heightMap array :
  34872. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  34873. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  34874. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  34875. GroundMesh.prototype._computeHeightQuads = function () {
  34876. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34877. var v1 = BABYLON.Tmp.Vector3[3];
  34878. var v2 = BABYLON.Tmp.Vector3[2];
  34879. var v3 = BABYLON.Tmp.Vector3[1];
  34880. var v4 = BABYLON.Tmp.Vector3[0];
  34881. var v1v2 = BABYLON.Tmp.Vector3[4];
  34882. var v1v3 = BABYLON.Tmp.Vector3[5];
  34883. var v1v4 = BABYLON.Tmp.Vector3[6];
  34884. var norm1 = BABYLON.Tmp.Vector3[7];
  34885. var norm2 = BABYLON.Tmp.Vector3[8];
  34886. var i = 0;
  34887. var j = 0;
  34888. var k = 0;
  34889. var cd = 0; // 2D slope coefficient : z = cd * x + h
  34890. var h = 0;
  34891. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  34892. var d2 = 0;
  34893. for (var row = 0; row < this._subdivisions; row++) {
  34894. for (var col = 0; col < this._subdivisions; col++) {
  34895. i = col * 3;
  34896. j = row * (this._subdivisions + 1) * 3;
  34897. k = (row + 1) * (this._subdivisions + 1) * 3;
  34898. v1.x = positions[j + i];
  34899. v1.y = positions[j + i + 1];
  34900. v1.z = positions[j + i + 2];
  34901. v2.x = positions[j + i + 3];
  34902. v2.y = positions[j + i + 4];
  34903. v2.z = positions[j + i + 5];
  34904. v3.x = positions[k + i];
  34905. v3.y = positions[k + i + 1];
  34906. v3.z = positions[k + i + 2];
  34907. v4.x = positions[k + i + 3];
  34908. v4.y = positions[k + i + 4];
  34909. v4.z = positions[k + i + 5];
  34910. // 2D slope V1V4
  34911. cd = (v4.z - v1.z) / (v4.x - v1.x);
  34912. h = v1.z - cd * v1.x; // v1 belongs to the slope
  34913. // facet equations :
  34914. // we compute each facet normal vector
  34915. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  34916. // we compute the value d by applying the equation to v1 which belongs to the plane
  34917. // then we store the facet equation in a Vector4
  34918. v2.subtractToRef(v1, v1v2);
  34919. v3.subtractToRef(v1, v1v3);
  34920. v4.subtractToRef(v1, v1v4);
  34921. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  34922. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  34923. norm1.normalize();
  34924. norm2.normalize();
  34925. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  34926. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  34927. var quad = this._heightQuads[row * this._subdivisions + col];
  34928. quad.slope.copyFromFloats(cd, h);
  34929. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  34930. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  34931. }
  34932. }
  34933. };
  34934. return GroundMesh;
  34935. })(BABYLON.Mesh);
  34936. BABYLON.GroundMesh = GroundMesh;
  34937. })(BABYLON || (BABYLON = {}));
  34938. var BABYLON;
  34939. (function (BABYLON) {
  34940. var LinesMesh = (function (_super) {
  34941. __extends(LinesMesh, _super);
  34942. function LinesMesh(name, scene, parent, source, doNotCloneChildren) {
  34943. if (parent === void 0) { parent = null; }
  34944. _super.call(this, name, scene, parent, source, doNotCloneChildren);
  34945. this.color = new BABYLON.Color3(1, 1, 1);
  34946. this.alpha = 1;
  34947. this._positionBuffer = {};
  34948. if (source) {
  34949. this.color = source.color.clone();
  34950. this.alpha = source.alpha;
  34951. }
  34952. this._intersectionThreshold = 0.1;
  34953. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  34954. attributes: [BABYLON.VertexBuffer.PositionKind],
  34955. uniforms: ["worldViewProjection", "color"],
  34956. needAlphaBlending: true
  34957. });
  34958. this._positionBuffer[BABYLON.VertexBuffer.PositionKind] = null;
  34959. }
  34960. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  34961. /**
  34962. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  34963. * This margin is expressed in world space coordinates, so its value may vary.
  34964. * Default value is 0.1
  34965. * @returns the intersection Threshold value.
  34966. */
  34967. get: function () {
  34968. return this._intersectionThreshold;
  34969. },
  34970. /**
  34971. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  34972. * This margin is expressed in world space coordinates, so its value may vary.
  34973. * @param value the new threshold to apply
  34974. */
  34975. set: function (value) {
  34976. if (this._intersectionThreshold === value) {
  34977. return;
  34978. }
  34979. this._intersectionThreshold = value;
  34980. if (this.geometry) {
  34981. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  34982. }
  34983. },
  34984. enumerable: true,
  34985. configurable: true
  34986. });
  34987. Object.defineProperty(LinesMesh.prototype, "material", {
  34988. get: function () {
  34989. return this._colorShader;
  34990. },
  34991. enumerable: true,
  34992. configurable: true
  34993. });
  34994. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  34995. get: function () {
  34996. return false;
  34997. },
  34998. enumerable: true,
  34999. configurable: true
  35000. });
  35001. LinesMesh.prototype.createInstance = function (name) {
  35002. BABYLON.Tools.Log("LinesMeshes do not support createInstance.");
  35003. return null;
  35004. };
  35005. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  35006. var engine = this.getScene().getEngine();
  35007. this._positionBuffer[BABYLON.VertexBuffer.PositionKind] = this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind);
  35008. // VBOs
  35009. engine.bindBuffers(this._positionBuffer, this._geometry.getIndexBuffer(), this._colorShader.getEffect());
  35010. // Color
  35011. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  35012. };
  35013. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  35014. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  35015. return;
  35016. }
  35017. var engine = this.getScene().getEngine();
  35018. // Draw order
  35019. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  35020. };
  35021. LinesMesh.prototype.dispose = function (doNotRecurse) {
  35022. this._colorShader.dispose();
  35023. _super.prototype.dispose.call(this, doNotRecurse);
  35024. };
  35025. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  35026. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  35027. };
  35028. return LinesMesh;
  35029. })(BABYLON.Mesh);
  35030. BABYLON.LinesMesh = LinesMesh;
  35031. })(BABYLON || (BABYLON = {}));
  35032. var BABYLON;
  35033. (function (BABYLON) {
  35034. var DefaultLoadingScreen = (function () {
  35035. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  35036. var _this = this;
  35037. if (_loadingText === void 0) { _loadingText = ""; }
  35038. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  35039. this._renderingCanvas = _renderingCanvas;
  35040. this._loadingText = _loadingText;
  35041. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  35042. // Resize
  35043. this._resizeLoadingUI = function () {
  35044. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  35045. _this._loadingDiv.style.position = "absolute";
  35046. _this._loadingDiv.style.left = canvasRect.left + "px";
  35047. _this._loadingDiv.style.top = canvasRect.top + "px";
  35048. _this._loadingDiv.style.width = canvasRect.width + "px";
  35049. _this._loadingDiv.style.height = canvasRect.height + "px";
  35050. };
  35051. }
  35052. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  35053. var _this = this;
  35054. if (this._loadingDiv) {
  35055. // Do not add a loading screen if there is already one
  35056. return;
  35057. }
  35058. this._loadingDiv = document.createElement("div");
  35059. this._loadingDiv.id = "babylonjsLoadingDiv";
  35060. this._loadingDiv.style.opacity = "0";
  35061. this._loadingDiv.style.transition = "opacity 1.5s ease";
  35062. // Loading text
  35063. this._loadingTextDiv = document.createElement("div");
  35064. this._loadingTextDiv.style.position = "absolute";
  35065. this._loadingTextDiv.style.left = "0";
  35066. this._loadingTextDiv.style.top = "50%";
  35067. this._loadingTextDiv.style.marginTop = "80px";
  35068. this._loadingTextDiv.style.width = "100%";
  35069. this._loadingTextDiv.style.height = "20px";
  35070. this._loadingTextDiv.style.fontFamily = "Arial";
  35071. this._loadingTextDiv.style.fontSize = "14px";
  35072. this._loadingTextDiv.style.color = "white";
  35073. this._loadingTextDiv.style.textAlign = "center";
  35074. this._loadingTextDiv.innerHTML = "Loading";
  35075. this._loadingDiv.appendChild(this._loadingTextDiv);
  35076. //set the predefined text
  35077. this._loadingTextDiv.innerHTML = this._loadingText;
  35078. // Loading img
  35079. var imgBack = new Image();
  35080. 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==";
  35081. imgBack.style.position = "absolute";
  35082. imgBack.style.left = "50%";
  35083. imgBack.style.top = "50%";
  35084. imgBack.style.marginLeft = "-50px";
  35085. imgBack.style.marginTop = "-50px";
  35086. imgBack.style.transition = "transform 1.0s ease";
  35087. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  35088. var deg = 360;
  35089. var onTransitionEnd = function () {
  35090. deg += 360;
  35091. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  35092. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  35093. };
  35094. imgBack.addEventListener("transitionend", onTransitionEnd);
  35095. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  35096. this._loadingDiv.appendChild(imgBack);
  35097. // front image
  35098. var imgFront = new Image();
  35099. 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=";
  35100. imgFront.style.position = "absolute";
  35101. imgFront.style.left = "50%";
  35102. imgFront.style.top = "50%";
  35103. imgFront.style.marginLeft = "-50px";
  35104. imgFront.style.marginTop = "-50px";
  35105. this._loadingDiv.appendChild(imgFront);
  35106. this._resizeLoadingUI();
  35107. window.addEventListener("resize", this._resizeLoadingUI);
  35108. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  35109. document.body.appendChild(this._loadingDiv);
  35110. setTimeout(function () {
  35111. _this._loadingDiv.style.opacity = "1";
  35112. imgBack.style.transform = "rotateZ(360deg)";
  35113. imgBack.style.webkitTransform = "rotateZ(360deg)";
  35114. }, 0);
  35115. };
  35116. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  35117. var _this = this;
  35118. if (!this._loadingDiv) {
  35119. return;
  35120. }
  35121. var onTransitionEnd = function () {
  35122. if (!_this._loadingDiv) {
  35123. return;
  35124. }
  35125. document.body.removeChild(_this._loadingDiv);
  35126. window.removeEventListener("resize", _this._resizeLoadingUI);
  35127. _this._loadingDiv = null;
  35128. };
  35129. this._loadingDiv.style.opacity = "0";
  35130. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  35131. };
  35132. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  35133. set: function (text) {
  35134. this._loadingText = text;
  35135. if (this._loadingTextDiv) {
  35136. this._loadingTextDiv.innerHTML = this._loadingText;
  35137. }
  35138. },
  35139. enumerable: true,
  35140. configurable: true
  35141. });
  35142. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  35143. get: function () {
  35144. return this._loadingDivBackgroundColor;
  35145. },
  35146. set: function (color) {
  35147. this._loadingDivBackgroundColor = color;
  35148. if (!this._loadingDiv) {
  35149. return;
  35150. }
  35151. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  35152. },
  35153. enumerable: true,
  35154. configurable: true
  35155. });
  35156. return DefaultLoadingScreen;
  35157. })();
  35158. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  35159. })(BABYLON || (BABYLON = {}));
  35160. var BABYLON;
  35161. (function (BABYLON) {
  35162. var AudioEngine = (function () {
  35163. function AudioEngine() {
  35164. this._audioContext = null;
  35165. this._audioContextInitialized = false;
  35166. this.canUseWebAudio = false;
  35167. this.WarnedWebAudioUnsupported = false;
  35168. this.unlocked = false;
  35169. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  35170. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  35171. this.canUseWebAudio = true;
  35172. }
  35173. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  35174. this._unlockiOSaudio();
  35175. }
  35176. else {
  35177. this.unlocked = true;
  35178. }
  35179. }
  35180. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  35181. get: function () {
  35182. if (!this._audioContextInitialized) {
  35183. this._initializeAudioContext();
  35184. }
  35185. return this._audioContext;
  35186. },
  35187. enumerable: true,
  35188. configurable: true
  35189. });
  35190. AudioEngine.prototype._unlockiOSaudio = function () {
  35191. var _this = this;
  35192. var unlockaudio = function () {
  35193. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  35194. var source = _this.audioContext.createBufferSource();
  35195. source.buffer = buffer;
  35196. source.connect(_this.audioContext.destination);
  35197. source.start(0);
  35198. setTimeout(function () {
  35199. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  35200. _this.unlocked = true;
  35201. window.removeEventListener('touchend', unlockaudio, false);
  35202. if (_this.onAudioUnlocked) {
  35203. _this.onAudioUnlocked();
  35204. }
  35205. }
  35206. }, 0);
  35207. };
  35208. window.addEventListener('touchend', unlockaudio, false);
  35209. };
  35210. AudioEngine.prototype._initializeAudioContext = function () {
  35211. try {
  35212. if (this.canUseWebAudio) {
  35213. this._audioContext = new AudioContext();
  35214. // create a global volume gain node
  35215. this.masterGain = this._audioContext.createGain();
  35216. this.masterGain.gain.value = 1;
  35217. this.masterGain.connect(this._audioContext.destination);
  35218. this._audioContextInitialized = true;
  35219. }
  35220. }
  35221. catch (e) {
  35222. this.canUseWebAudio = false;
  35223. BABYLON.Tools.Error("Web Audio: " + e.message);
  35224. }
  35225. };
  35226. AudioEngine.prototype.dispose = function () {
  35227. if (this.canUseWebAudio && this._audioContextInitialized) {
  35228. if (this._connectedAnalyser) {
  35229. this._connectedAnalyser.stopDebugCanvas();
  35230. this._connectedAnalyser.dispose();
  35231. this.masterGain.disconnect();
  35232. this.masterGain.connect(this._audioContext.destination);
  35233. this._connectedAnalyser = null;
  35234. }
  35235. this.masterGain.gain.value = 1;
  35236. }
  35237. this.WarnedWebAudioUnsupported = false;
  35238. };
  35239. AudioEngine.prototype.getGlobalVolume = function () {
  35240. if (this.canUseWebAudio && this._audioContextInitialized) {
  35241. return this.masterGain.gain.value;
  35242. }
  35243. else {
  35244. return -1;
  35245. }
  35246. };
  35247. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  35248. if (this.canUseWebAudio && this._audioContextInitialized) {
  35249. this.masterGain.gain.value = newVolume;
  35250. }
  35251. };
  35252. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  35253. if (this._connectedAnalyser) {
  35254. this._connectedAnalyser.stopDebugCanvas();
  35255. }
  35256. if (this.canUseWebAudio && this._audioContextInitialized) {
  35257. this._connectedAnalyser = analyser;
  35258. this.masterGain.disconnect();
  35259. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  35260. }
  35261. };
  35262. return AudioEngine;
  35263. })();
  35264. BABYLON.AudioEngine = AudioEngine;
  35265. })(BABYLON || (BABYLON = {}));
  35266. var BABYLON;
  35267. (function (BABYLON) {
  35268. var Sound = (function () {
  35269. /**
  35270. * Create a sound and attach it to a scene
  35271. * @param name Name of your sound
  35272. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  35273. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  35274. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  35275. */
  35276. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  35277. var _this = this;
  35278. this.autoplay = false;
  35279. this.loop = false;
  35280. this.useCustomAttenuation = false;
  35281. this.spatialSound = false;
  35282. this.refDistance = 1;
  35283. this.rolloffFactor = 1;
  35284. this.maxDistance = 100;
  35285. this.distanceModel = "linear";
  35286. this._panningModel = "equalpower";
  35287. this._playbackRate = 1;
  35288. this._streaming = false;
  35289. this._startTime = 0;
  35290. this._startOffset = 0;
  35291. this._position = BABYLON.Vector3.Zero();
  35292. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  35293. this._volume = 1;
  35294. this._isLoaded = false;
  35295. this._isReadyToPlay = false;
  35296. this.isPlaying = false;
  35297. this.isPaused = false;
  35298. this._isDirectional = false;
  35299. // Used if you'd like to create a directional sound.
  35300. // If not set, the sound will be omnidirectional
  35301. this._coneInnerAngle = 360;
  35302. this._coneOuterAngle = 360;
  35303. this._coneOuterGain = 0;
  35304. this._isOutputConnected = false;
  35305. this.name = name;
  35306. this._scene = scene;
  35307. this._readyToPlayCallback = readyToPlayCallback;
  35308. // Default custom attenuation function is a linear attenuation
  35309. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  35310. if (currentDistance < maxDistance) {
  35311. return currentVolume * (1 - currentDistance / maxDistance);
  35312. }
  35313. else {
  35314. return 0;
  35315. }
  35316. };
  35317. if (options) {
  35318. this.autoplay = options.autoplay || false;
  35319. this.loop = options.loop || false;
  35320. // if volume === 0, we need another way to check this option
  35321. if (options.volume !== undefined) {
  35322. this._volume = options.volume;
  35323. }
  35324. this.spatialSound = options.spatialSound || false;
  35325. this.maxDistance = options.maxDistance || 100;
  35326. this.useCustomAttenuation = options.useCustomAttenuation || false;
  35327. this.rolloffFactor = options.rolloffFactor || 1;
  35328. this.refDistance = options.refDistance || 1;
  35329. this.distanceModel = options.distanceModel || "linear";
  35330. this._playbackRate = options.playbackRate || 1;
  35331. this._streaming = options.streaming || false;
  35332. }
  35333. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  35334. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  35335. this._soundGain.gain.value = this._volume;
  35336. this._inputAudioNode = this._soundGain;
  35337. this._ouputAudioNode = this._soundGain;
  35338. if (this.spatialSound) {
  35339. this._createSpatialParameters();
  35340. }
  35341. this._scene.mainSoundTrack.AddSound(this);
  35342. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  35343. if (urlOrArrayBuffer) {
  35344. // If it's an URL
  35345. if (typeof (urlOrArrayBuffer) === "string") {
  35346. // Loading sound using XHR2
  35347. if (!this._streaming) {
  35348. BABYLON.Tools.LoadFile(urlOrArrayBuffer, function (data) { _this._soundLoaded(data); }, null, this._scene.database, true);
  35349. }
  35350. else {
  35351. this._htmlAudioElement = new Audio(urlOrArrayBuffer);
  35352. this._htmlAudioElement.controls = false;
  35353. this._htmlAudioElement.loop = this.loop;
  35354. this._htmlAudioElement.crossOrigin = "anonymous";
  35355. this._htmlAudioElement.preload = "auto";
  35356. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  35357. _this._isReadyToPlay = true;
  35358. if (_this.autoplay) {
  35359. _this.play();
  35360. }
  35361. if (_this._readyToPlayCallback) {
  35362. _this._readyToPlayCallback();
  35363. }
  35364. });
  35365. document.body.appendChild(this._htmlAudioElement);
  35366. }
  35367. }
  35368. else {
  35369. if (urlOrArrayBuffer instanceof ArrayBuffer) {
  35370. if (urlOrArrayBuffer.byteLength > 0) {
  35371. this._soundLoaded(urlOrArrayBuffer);
  35372. }
  35373. }
  35374. else {
  35375. BABYLON.Tools.Error("Parameter must be a URL to the sound or an ArrayBuffer of the sound.");
  35376. }
  35377. }
  35378. }
  35379. }
  35380. else {
  35381. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  35382. this._scene.mainSoundTrack.AddSound(this);
  35383. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  35384. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  35385. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  35386. }
  35387. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  35388. if (this._readyToPlayCallback) {
  35389. window.setTimeout(function () {
  35390. _this._readyToPlayCallback();
  35391. }, 1000);
  35392. }
  35393. }
  35394. }
  35395. Sound.prototype.dispose = function () {
  35396. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  35397. if (this.isPlaying) {
  35398. this.stop();
  35399. }
  35400. this._isReadyToPlay = false;
  35401. if (this.soundTrackId === -1) {
  35402. this._scene.mainSoundTrack.RemoveSound(this);
  35403. }
  35404. else {
  35405. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  35406. }
  35407. if (this._soundGain) {
  35408. this._soundGain.disconnect();
  35409. this._soundGain = null;
  35410. }
  35411. if (this._soundPanner) {
  35412. this._soundPanner.disconnect();
  35413. this._soundPanner = null;
  35414. }
  35415. if (this._soundSource) {
  35416. this._soundSource.disconnect();
  35417. this._soundSource = null;
  35418. }
  35419. this._audioBuffer = null;
  35420. if (this._htmlAudioElement) {
  35421. this._htmlAudioElement.pause();
  35422. this._htmlAudioElement.src = "";
  35423. document.body.removeChild(this._htmlAudioElement);
  35424. }
  35425. if (this._connectedMesh) {
  35426. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  35427. this._connectedMesh = null;
  35428. }
  35429. }
  35430. };
  35431. Sound.prototype._soundLoaded = function (audioData) {
  35432. var _this = this;
  35433. this._isLoaded = true;
  35434. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  35435. _this._audioBuffer = buffer;
  35436. _this._isReadyToPlay = true;
  35437. if (_this.autoplay) {
  35438. _this.play();
  35439. }
  35440. if (_this._readyToPlayCallback) {
  35441. _this._readyToPlayCallback();
  35442. }
  35443. }, function () { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name); });
  35444. };
  35445. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  35446. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  35447. this._audioBuffer = audioBuffer;
  35448. this._isReadyToPlay = true;
  35449. }
  35450. };
  35451. Sound.prototype.updateOptions = function (options) {
  35452. if (options) {
  35453. this.loop = options.loop || this.loop;
  35454. this.maxDistance = options.maxDistance || this.maxDistance;
  35455. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  35456. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  35457. this.refDistance = options.refDistance || this.refDistance;
  35458. this.distanceModel = options.distanceModel || this.distanceModel;
  35459. this._playbackRate = options.playbackRate || this._playbackRate;
  35460. this._updateSpatialParameters();
  35461. if (this.isPlaying) {
  35462. if (this._streaming) {
  35463. this._htmlAudioElement.playbackRate = this._playbackRate;
  35464. }
  35465. else {
  35466. this._soundSource.playbackRate.value = this._playbackRate;
  35467. }
  35468. }
  35469. }
  35470. };
  35471. Sound.prototype._createSpatialParameters = function () {
  35472. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  35473. if (this._scene.headphone) {
  35474. this._panningModel = "HRTF";
  35475. }
  35476. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  35477. this._updateSpatialParameters();
  35478. this._soundPanner.connect(this._ouputAudioNode);
  35479. this._inputAudioNode = this._soundPanner;
  35480. }
  35481. };
  35482. Sound.prototype._updateSpatialParameters = function () {
  35483. if (this.spatialSound) {
  35484. if (this.useCustomAttenuation) {
  35485. // Tricks to disable in a way embedded Web Audio attenuation
  35486. this._soundPanner.distanceModel = "linear";
  35487. this._soundPanner.maxDistance = Number.MAX_VALUE;
  35488. this._soundPanner.refDistance = 1;
  35489. this._soundPanner.rolloffFactor = 1;
  35490. this._soundPanner.panningModel = this._panningModel;
  35491. }
  35492. else {
  35493. this._soundPanner.distanceModel = this.distanceModel;
  35494. this._soundPanner.maxDistance = this.maxDistance;
  35495. this._soundPanner.refDistance = this.refDistance;
  35496. this._soundPanner.rolloffFactor = this.rolloffFactor;
  35497. this._soundPanner.panningModel = this._panningModel;
  35498. }
  35499. }
  35500. };
  35501. Sound.prototype.switchPanningModelToHRTF = function () {
  35502. this._panningModel = "HRTF";
  35503. this._switchPanningModel();
  35504. };
  35505. Sound.prototype.switchPanningModelToEqualPower = function () {
  35506. this._panningModel = "equalpower";
  35507. this._switchPanningModel();
  35508. };
  35509. Sound.prototype._switchPanningModel = function () {
  35510. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  35511. this._soundPanner.panningModel = this._panningModel;
  35512. }
  35513. };
  35514. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  35515. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  35516. if (this._isOutputConnected) {
  35517. this._ouputAudioNode.disconnect();
  35518. }
  35519. this._ouputAudioNode.connect(soundTrackAudioNode);
  35520. this._isOutputConnected = true;
  35521. }
  35522. };
  35523. /**
  35524. * Transform this sound into a directional source
  35525. * @param coneInnerAngle Size of the inner cone in degree
  35526. * @param coneOuterAngle Size of the outer cone in degree
  35527. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  35528. */
  35529. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  35530. if (coneOuterAngle < coneInnerAngle) {
  35531. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  35532. return;
  35533. }
  35534. this._coneInnerAngle = coneInnerAngle;
  35535. this._coneOuterAngle = coneOuterAngle;
  35536. this._coneOuterGain = coneOuterGain;
  35537. this._isDirectional = true;
  35538. if (this.isPlaying && this.loop) {
  35539. this.stop();
  35540. this.play();
  35541. }
  35542. };
  35543. Sound.prototype.setPosition = function (newPosition) {
  35544. this._position = newPosition;
  35545. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  35546. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  35547. }
  35548. };
  35549. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  35550. this._localDirection = newLocalDirection;
  35551. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  35552. this._updateDirection();
  35553. }
  35554. };
  35555. Sound.prototype._updateDirection = function () {
  35556. var mat = this._connectedMesh.getWorldMatrix();
  35557. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  35558. direction.normalize();
  35559. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  35560. };
  35561. Sound.prototype.updateDistanceFromListener = function () {
  35562. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation) {
  35563. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  35564. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  35565. }
  35566. };
  35567. Sound.prototype.setAttenuationFunction = function (callback) {
  35568. this._customAttenuationFunction = callback;
  35569. };
  35570. /**
  35571. * Play the sound
  35572. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  35573. * @param offset (optional) Start the sound setting it at a specific time
  35574. */
  35575. Sound.prototype.play = function (time, offset) {
  35576. var _this = this;
  35577. if (this._isReadyToPlay && this._scene.audioEnabled) {
  35578. try {
  35579. if (this._startOffset < 0) {
  35580. time = -this._startOffset;
  35581. this._startOffset = 0;
  35582. }
  35583. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  35584. if (!this._soundSource || !this._streamingSource) {
  35585. if (this.spatialSound) {
  35586. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  35587. if (this._isDirectional) {
  35588. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  35589. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  35590. this._soundPanner.coneOuterGain = this._coneOuterGain;
  35591. if (this._connectedMesh) {
  35592. this._updateDirection();
  35593. }
  35594. else {
  35595. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  35596. }
  35597. }
  35598. }
  35599. }
  35600. if (this._streaming) {
  35601. if (!this._streamingSource) {
  35602. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  35603. this._htmlAudioElement.onended = function () { _this._onended(); };
  35604. this._htmlAudioElement.playbackRate = this._playbackRate;
  35605. }
  35606. this._streamingSource.disconnect();
  35607. this._streamingSource.connect(this._inputAudioNode);
  35608. this._htmlAudioElement.play();
  35609. }
  35610. else {
  35611. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  35612. this._soundSource.buffer = this._audioBuffer;
  35613. this._soundSource.connect(this._inputAudioNode);
  35614. this._soundSource.loop = this.loop;
  35615. this._soundSource.playbackRate.value = this._playbackRate;
  35616. this._soundSource.onended = function () { _this._onended(); };
  35617. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  35618. }
  35619. this._startTime = startTime;
  35620. this.isPlaying = true;
  35621. this.isPaused = false;
  35622. }
  35623. catch (ex) {
  35624. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  35625. }
  35626. }
  35627. };
  35628. Sound.prototype._onended = function () {
  35629. this.isPlaying = false;
  35630. if (this.onended) {
  35631. this.onended();
  35632. }
  35633. };
  35634. /**
  35635. * Stop the sound
  35636. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  35637. */
  35638. Sound.prototype.stop = function (time) {
  35639. if (this.isPlaying) {
  35640. if (this._streaming) {
  35641. this._htmlAudioElement.pause();
  35642. // Test needed for Firefox or it will generate an Invalid State Error
  35643. if (this._htmlAudioElement.currentTime > 0) {
  35644. this._htmlAudioElement.currentTime = 0;
  35645. }
  35646. }
  35647. else {
  35648. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  35649. this._soundSource.stop(stopTime);
  35650. this._soundSource.onended = null;
  35651. if (!this.isPaused) {
  35652. this._startOffset = 0;
  35653. }
  35654. }
  35655. this.isPlaying = false;
  35656. }
  35657. };
  35658. Sound.prototype.pause = function () {
  35659. if (this.isPlaying) {
  35660. this.isPaused = true;
  35661. if (this._streaming) {
  35662. this._htmlAudioElement.pause();
  35663. }
  35664. else {
  35665. this.stop(0);
  35666. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  35667. }
  35668. }
  35669. };
  35670. Sound.prototype.setVolume = function (newVolume, time) {
  35671. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  35672. if (time) {
  35673. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  35674. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  35675. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  35676. }
  35677. else {
  35678. this._soundGain.gain.value = newVolume;
  35679. }
  35680. }
  35681. this._volume = newVolume;
  35682. };
  35683. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  35684. this._playbackRate = newPlaybackRate;
  35685. if (this.isPlaying) {
  35686. if (this._streaming) {
  35687. this._htmlAudioElement.playbackRate = this._playbackRate;
  35688. }
  35689. else {
  35690. this._soundSource.playbackRate.value = this._playbackRate;
  35691. }
  35692. }
  35693. };
  35694. Sound.prototype.getVolume = function () {
  35695. return this._volume;
  35696. };
  35697. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  35698. var _this = this;
  35699. if (this._connectedMesh) {
  35700. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  35701. this._registerFunc = null;
  35702. }
  35703. this._connectedMesh = meshToConnectTo;
  35704. if (!this.spatialSound) {
  35705. this.spatialSound = true;
  35706. this._createSpatialParameters();
  35707. if (this.isPlaying && this.loop) {
  35708. this.stop();
  35709. this.play();
  35710. }
  35711. }
  35712. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  35713. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  35714. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  35715. };
  35716. Sound.prototype.detachFromMesh = function () {
  35717. if (this._connectedMesh) {
  35718. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  35719. this._registerFunc = null;
  35720. this._connectedMesh = null;
  35721. }
  35722. };
  35723. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  35724. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  35725. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  35726. this._updateDirection();
  35727. }
  35728. };
  35729. Sound.prototype.clone = function () {
  35730. var _this = this;
  35731. if (!this._streaming) {
  35732. var setBufferAndRun = function () {
  35733. if (_this._isReadyToPlay) {
  35734. clonedSound._audioBuffer = _this.getAudioBuffer();
  35735. clonedSound._isReadyToPlay = true;
  35736. if (clonedSound.autoplay) {
  35737. clonedSound.play();
  35738. }
  35739. }
  35740. else {
  35741. window.setTimeout(setBufferAndRun, 300);
  35742. }
  35743. };
  35744. var currentOptions = {
  35745. autoplay: this.autoplay, loop: this.loop,
  35746. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  35747. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  35748. refDistance: this.refDistance, distanceModel: this.distanceModel
  35749. };
  35750. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  35751. if (this.useCustomAttenuation) {
  35752. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  35753. }
  35754. clonedSound.setPosition(this._position);
  35755. clonedSound.setPlaybackRate(this._playbackRate);
  35756. setBufferAndRun();
  35757. return clonedSound;
  35758. }
  35759. else {
  35760. return null;
  35761. }
  35762. };
  35763. Sound.prototype.getAudioBuffer = function () {
  35764. return this._audioBuffer;
  35765. };
  35766. Sound.prototype.serialize = function () {
  35767. var serializationObject = {
  35768. name: this.name,
  35769. url: this.name,
  35770. autoplay: this.autoplay,
  35771. loop: this.loop,
  35772. volume: this._volume,
  35773. spatialSound: this.spatialSound,
  35774. maxDistance: this.maxDistance,
  35775. rolloffFactor: this.rolloffFactor,
  35776. refDistance: this.refDistance,
  35777. distanceModel: this.distanceModel,
  35778. playbackRate: this._playbackRate,
  35779. panningModel: this._panningModel,
  35780. soundTrackId: this.soundTrackId
  35781. };
  35782. if (this.spatialSound) {
  35783. if (this._connectedMesh)
  35784. serializationObject.connectedMeshId = this._connectedMesh.id;
  35785. serializationObject.position = this._position.asArray();
  35786. serializationObject.refDistance = this.refDistance;
  35787. serializationObject.distanceModel = this.distanceModel;
  35788. serializationObject.isDirectional = this._isDirectional;
  35789. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  35790. serializationObject.coneInnerAngle = this._coneInnerAngle;
  35791. serializationObject.coneOuterAngle = this._coneOuterAngle;
  35792. serializationObject.coneOuterGain = this._coneOuterGain;
  35793. }
  35794. return serializationObject;
  35795. };
  35796. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  35797. var soundName = parsedSound.name;
  35798. var soundUrl;
  35799. if (parsedSound.url) {
  35800. soundUrl = rootUrl + parsedSound.url;
  35801. }
  35802. else {
  35803. soundUrl = rootUrl + soundName;
  35804. }
  35805. var options = {
  35806. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  35807. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  35808. rolloffFactor: parsedSound.rolloffFactor,
  35809. refDistance: parsedSound.refDistance,
  35810. distanceModel: parsedSound.distanceModel,
  35811. playbackRate: parsedSound.playbackRate
  35812. };
  35813. var newSound;
  35814. if (!sourceSound) {
  35815. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  35816. scene._addPendingData(newSound);
  35817. }
  35818. else {
  35819. var setBufferAndRun = function () {
  35820. if (sourceSound._isReadyToPlay) {
  35821. newSound._audioBuffer = sourceSound.getAudioBuffer();
  35822. newSound._isReadyToPlay = true;
  35823. if (newSound.autoplay) {
  35824. newSound.play();
  35825. }
  35826. }
  35827. else {
  35828. window.setTimeout(setBufferAndRun, 300);
  35829. }
  35830. };
  35831. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  35832. setBufferAndRun();
  35833. }
  35834. if (parsedSound.position) {
  35835. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  35836. newSound.setPosition(soundPosition);
  35837. }
  35838. if (parsedSound.isDirectional) {
  35839. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  35840. if (parsedSound.localDirectionToMesh) {
  35841. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  35842. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  35843. }
  35844. }
  35845. if (parsedSound.connectedMeshId) {
  35846. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  35847. if (connectedMesh) {
  35848. newSound.attachToMesh(connectedMesh);
  35849. }
  35850. }
  35851. return newSound;
  35852. };
  35853. return Sound;
  35854. })();
  35855. BABYLON.Sound = Sound;
  35856. })(BABYLON || (BABYLON = {}));
  35857. var BABYLON;
  35858. (function (BABYLON) {
  35859. var SoundTrack = (function () {
  35860. function SoundTrack(scene, options) {
  35861. this.id = -1;
  35862. this._isMainTrack = false;
  35863. this._isInitialized = false;
  35864. this._scene = scene;
  35865. this.soundCollection = new Array();
  35866. this._options = options;
  35867. if (!this._isMainTrack) {
  35868. this._scene.soundTracks.push(this);
  35869. this.id = this._scene.soundTracks.length - 1;
  35870. }
  35871. }
  35872. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  35873. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  35874. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  35875. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  35876. if (this._options) {
  35877. if (this._options.volume) {
  35878. this._outputAudioNode.gain.value = this._options.volume;
  35879. }
  35880. if (this._options.mainTrack) {
  35881. this._isMainTrack = this._options.mainTrack;
  35882. }
  35883. }
  35884. this._isInitialized = true;
  35885. }
  35886. };
  35887. SoundTrack.prototype.dispose = function () {
  35888. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  35889. if (this._connectedAnalyser) {
  35890. this._connectedAnalyser.stopDebugCanvas();
  35891. }
  35892. while (this.soundCollection.length) {
  35893. this.soundCollection[0].dispose();
  35894. }
  35895. if (this._outputAudioNode) {
  35896. this._outputAudioNode.disconnect();
  35897. }
  35898. this._outputAudioNode = null;
  35899. }
  35900. };
  35901. SoundTrack.prototype.AddSound = function (sound) {
  35902. if (!this._isInitialized) {
  35903. this._initializeSoundTrackAudioGraph();
  35904. }
  35905. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  35906. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  35907. }
  35908. if (sound.soundTrackId) {
  35909. if (sound.soundTrackId === -1) {
  35910. this._scene.mainSoundTrack.RemoveSound(sound);
  35911. }
  35912. else {
  35913. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  35914. }
  35915. }
  35916. this.soundCollection.push(sound);
  35917. sound.soundTrackId = this.id;
  35918. };
  35919. SoundTrack.prototype.RemoveSound = function (sound) {
  35920. var index = this.soundCollection.indexOf(sound);
  35921. if (index !== -1) {
  35922. this.soundCollection.splice(index, 1);
  35923. }
  35924. };
  35925. SoundTrack.prototype.setVolume = function (newVolume) {
  35926. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  35927. this._outputAudioNode.gain.value = newVolume;
  35928. }
  35929. };
  35930. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  35931. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  35932. for (var i = 0; i < this.soundCollection.length; i++) {
  35933. this.soundCollection[i].switchPanningModelToHRTF();
  35934. }
  35935. }
  35936. };
  35937. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  35938. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  35939. for (var i = 0; i < this.soundCollection.length; i++) {
  35940. this.soundCollection[i].switchPanningModelToEqualPower();
  35941. }
  35942. }
  35943. };
  35944. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  35945. if (this._connectedAnalyser) {
  35946. this._connectedAnalyser.stopDebugCanvas();
  35947. }
  35948. this._connectedAnalyser = analyser;
  35949. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  35950. this._outputAudioNode.disconnect();
  35951. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  35952. }
  35953. };
  35954. return SoundTrack;
  35955. })();
  35956. BABYLON.SoundTrack = SoundTrack;
  35957. })(BABYLON || (BABYLON = {}));
  35958. var BABYLON;
  35959. (function (BABYLON) {
  35960. var DebugLayer = (function () {
  35961. function DebugLayer(scene) {
  35962. var _this = this;
  35963. this._transformationMatrix = BABYLON.Matrix.Identity();
  35964. this._enabled = false;
  35965. this._labelsEnabled = false;
  35966. this._displayStatistics = true;
  35967. this._displayTree = false;
  35968. this._displayLogs = false;
  35969. this._skeletonViewers = new Array();
  35970. this._identityMatrix = BABYLON.Matrix.Identity();
  35971. this.axisRatio = 0.02;
  35972. this.accentColor = "orange";
  35973. this._scene = scene;
  35974. this._syncPositions = function () {
  35975. var engine = _this._scene.getEngine();
  35976. var canvasRect = engine.getRenderingCanvasClientRect();
  35977. if (_this._showUI) {
  35978. _this._statsDiv.style.left = (canvasRect.width - 410) + "px";
  35979. _this._statsDiv.style.top = (canvasRect.height - 290) + "px";
  35980. _this._statsDiv.style.width = "400px";
  35981. _this._statsDiv.style.height = "auto";
  35982. _this._statsSubsetDiv.style.maxHeight = "240px";
  35983. _this._optionsDiv.style.left = "0px";
  35984. _this._optionsDiv.style.top = "10px";
  35985. _this._optionsDiv.style.width = "200px";
  35986. _this._optionsDiv.style.height = "auto";
  35987. _this._optionsSubsetDiv.style.maxHeight = (canvasRect.height - 225) + "px";
  35988. _this._logDiv.style.left = "0px";
  35989. _this._logDiv.style.top = (canvasRect.height - 170) + "px";
  35990. _this._logDiv.style.width = "600px";
  35991. _this._logDiv.style.height = "160px";
  35992. _this._treeDiv.style.left = (canvasRect.width - 310) + "px";
  35993. _this._treeDiv.style.top = "10px";
  35994. _this._treeDiv.style.width = "300px";
  35995. _this._treeDiv.style.height = "auto";
  35996. _this._treeSubsetDiv.style.maxHeight = (canvasRect.height - 340) + "px";
  35997. }
  35998. _this._globalDiv.style.left = canvasRect.left + "px";
  35999. _this._globalDiv.style.top = canvasRect.top + "px";
  36000. _this._drawingCanvas.style.left = "0px";
  36001. _this._drawingCanvas.style.top = "0px";
  36002. _this._drawingCanvas.style.width = engine.getRenderWidth() + "px";
  36003. _this._drawingCanvas.style.height = engine.getRenderHeight() + "px";
  36004. var devicePixelRatio = window.devicePixelRatio || 1;
  36005. var context = _this._drawingContext;
  36006. var backingStoreRatio = context.webkitBackingStorePixelRatio ||
  36007. context.mozBackingStorePixelRatio ||
  36008. context.msBackingStorePixelRatio ||
  36009. context.oBackingStorePixelRatio ||
  36010. context.backingStorePixelRatio || 1;
  36011. _this._ratio = devicePixelRatio / backingStoreRatio;
  36012. _this._drawingCanvas.width = engine.getRenderWidth() * _this._ratio;
  36013. _this._drawingCanvas.height = engine.getRenderHeight() * _this._ratio;
  36014. };
  36015. this._onCanvasClick = function (evt) {
  36016. _this._clickPosition = {
  36017. x: evt.clientX * _this._ratio,
  36018. y: evt.clientY * _this._ratio
  36019. };
  36020. };
  36021. this._syncUI = function () {
  36022. if (_this._showUI) {
  36023. if (_this._displayStatistics) {
  36024. _this._displayStats();
  36025. _this._statsDiv.style.display = "";
  36026. }
  36027. else {
  36028. _this._statsDiv.style.display = "none";
  36029. }
  36030. if (_this._displayLogs) {
  36031. _this._logDiv.style.display = "";
  36032. }
  36033. else {
  36034. _this._logDiv.style.display = "none";
  36035. }
  36036. if (_this._displayTree) {
  36037. _this._treeDiv.style.display = "";
  36038. if (_this._needToRefreshMeshesTree) {
  36039. _this._needToRefreshMeshesTree = false;
  36040. _this._refreshMeshesTreeContent();
  36041. }
  36042. }
  36043. else {
  36044. _this._treeDiv.style.display = "none";
  36045. }
  36046. }
  36047. };
  36048. this._syncData = function () {
  36049. if (_this._labelsEnabled || !_this._showUI) {
  36050. _this._camera.getViewMatrix().multiplyToRef(_this._camera.getProjectionMatrix(), _this._transformationMatrix);
  36051. _this._drawingContext.clearRect(0, 0, _this._drawingCanvas.width, _this._drawingCanvas.height);
  36052. var engine = _this._scene.getEngine();
  36053. var viewport = _this._camera.viewport;
  36054. var globalViewport = viewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  36055. // Meshes
  36056. var meshes = _this._camera.getActiveMeshes();
  36057. var index;
  36058. var projectedPosition;
  36059. for (index = 0; index < meshes.length; index++) {
  36060. var mesh = meshes.data[index];
  36061. var position = mesh.getBoundingInfo().boundingSphere.center;
  36062. projectedPosition = BABYLON.Vector3.Project(position, mesh.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  36063. if (mesh.renderOverlay || _this.shouldDisplayAxis && _this.shouldDisplayAxis(mesh)) {
  36064. _this._renderAxis(projectedPosition, mesh, globalViewport);
  36065. }
  36066. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(mesh)) {
  36067. _this._renderLabel(mesh.name, projectedPosition, 12, function () { mesh.renderOverlay = !mesh.renderOverlay; }, function () { return mesh.renderOverlay ? 'red' : 'black'; });
  36068. }
  36069. }
  36070. // Cameras
  36071. var cameras = _this._scene.cameras;
  36072. for (index = 0; index < cameras.length; index++) {
  36073. var camera = cameras[index];
  36074. if (camera === _this._camera) {
  36075. continue;
  36076. }
  36077. projectedPosition = BABYLON.Vector3.Project(BABYLON.Vector3.Zero(), camera.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  36078. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(camera)) {
  36079. _this._renderLabel(camera.name, projectedPosition, 12, function () {
  36080. _this._camera.detachControl(engine.getRenderingCanvas());
  36081. _this._camera = camera;
  36082. _this._camera.attachControl(engine.getRenderingCanvas());
  36083. }, function () { return "purple"; });
  36084. }
  36085. }
  36086. // Lights
  36087. var lights = _this._scene.lights;
  36088. for (index = 0; index < lights.length; index++) {
  36089. var light = lights[index];
  36090. if (light.position) {
  36091. projectedPosition = BABYLON.Vector3.Project(light.getAbsolutePosition(), _this._identityMatrix, _this._transformationMatrix, globalViewport);
  36092. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(light)) {
  36093. _this._renderLabel(light.name, projectedPosition, -20, function () {
  36094. light.setEnabled(!light.isEnabled());
  36095. }, function () { return light.isEnabled() ? "orange" : "gray"; });
  36096. }
  36097. }
  36098. }
  36099. }
  36100. _this._clickPosition = undefined;
  36101. };
  36102. }
  36103. DebugLayer.prototype._refreshMeshesTreeContent = function () {
  36104. while (this._treeSubsetDiv.hasChildNodes()) {
  36105. this._treeSubsetDiv.removeChild(this._treeSubsetDiv.lastChild);
  36106. }
  36107. // Add meshes
  36108. var sortedArray = this._scene.meshes.slice(0, this._scene.meshes.length);
  36109. sortedArray.sort(function (a, b) {
  36110. if (a.name === b.name) {
  36111. return 0;
  36112. }
  36113. return (a.name > b.name) ? 1 : -1;
  36114. });
  36115. for (var index = 0; index < sortedArray.length; index++) {
  36116. var mesh = sortedArray[index];
  36117. if (!mesh.isEnabled()) {
  36118. continue;
  36119. }
  36120. this._generateAdvancedCheckBox(this._treeSubsetDiv, mesh.name, mesh.getTotalVertices() + " verts", mesh.isVisible, function (element, m) {
  36121. m.isVisible = element.checked;
  36122. }, mesh);
  36123. }
  36124. };
  36125. DebugLayer.prototype._renderSingleAxis = function (zero, unit, unitText, label, color) {
  36126. this._drawingContext.beginPath();
  36127. this._drawingContext.moveTo(zero.x, zero.y);
  36128. this._drawingContext.lineTo(unit.x, unit.y);
  36129. this._drawingContext.strokeStyle = color;
  36130. this._drawingContext.lineWidth = 4;
  36131. this._drawingContext.stroke();
  36132. this._drawingContext.font = "normal 14px Segoe UI";
  36133. this._drawingContext.fillStyle = color;
  36134. this._drawingContext.fillText(label, unitText.x, unitText.y);
  36135. };
  36136. DebugLayer.prototype._renderAxis = function (projectedPosition, mesh, globalViewport) {
  36137. var position = mesh.getBoundingInfo().boundingSphere.center;
  36138. var worldMatrix = mesh.getWorldMatrix();
  36139. var unprojectedVector = BABYLON.Vector3.UnprojectFromTransform(projectedPosition.add(new BABYLON.Vector3(this._drawingCanvas.width * this.axisRatio, 0, 0)), globalViewport.width, globalViewport.height, worldMatrix, this._transformationMatrix);
  36140. var unit = (unprojectedVector.subtract(position)).length();
  36141. var xAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  36142. var xAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit * 1.5, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  36143. this._renderSingleAxis(projectedPosition, xAxis, xAxisText, "x", "#FF0000");
  36144. var yAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  36145. var yAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit * 1.5, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  36146. this._renderSingleAxis(projectedPosition, yAxis, yAxisText, "y", "#00FF00");
  36147. var zAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit)), worldMatrix, this._transformationMatrix, globalViewport);
  36148. var zAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit * 1.5)), worldMatrix, this._transformationMatrix, globalViewport);
  36149. this._renderSingleAxis(projectedPosition, zAxis, zAxisText, "z", "#0000FF");
  36150. };
  36151. DebugLayer.prototype._renderLabel = function (text, projectedPosition, labelOffset, onClick, getFillStyle) {
  36152. if (projectedPosition.z > 0 && projectedPosition.z < 1.0) {
  36153. this._drawingContext.font = "normal 12px Segoe UI";
  36154. var textMetrics = this._drawingContext.measureText(text);
  36155. var centerX = projectedPosition.x - textMetrics.width / 2;
  36156. var centerY = projectedPosition.y;
  36157. var clientRect = this._drawingCanvas.getBoundingClientRect();
  36158. if (this._showUI && this._isClickInsideRect(clientRect.left * this._ratio + centerX - 5, clientRect.top * this._ratio + centerY - labelOffset - 12, textMetrics.width + 10, 17)) {
  36159. onClick();
  36160. }
  36161. this._drawingContext.beginPath();
  36162. this._drawingContext.rect(centerX - 5, centerY - labelOffset - 12, textMetrics.width + 10, 17);
  36163. this._drawingContext.fillStyle = getFillStyle();
  36164. this._drawingContext.globalAlpha = 0.5;
  36165. this._drawingContext.fill();
  36166. this._drawingContext.globalAlpha = 1.0;
  36167. this._drawingContext.strokeStyle = '#FFFFFF';
  36168. this._drawingContext.lineWidth = 1;
  36169. this._drawingContext.stroke();
  36170. this._drawingContext.fillStyle = "#FFFFFF";
  36171. this._drawingContext.fillText(text, centerX, centerY - labelOffset);
  36172. this._drawingContext.beginPath();
  36173. this._drawingContext.arc(projectedPosition.x, centerY, 5, 0, 2 * Math.PI, false);
  36174. this._drawingContext.fill();
  36175. }
  36176. };
  36177. DebugLayer.prototype._isClickInsideRect = function (x, y, width, height) {
  36178. if (!this._clickPosition) {
  36179. return false;
  36180. }
  36181. if (this._clickPosition.x < x || this._clickPosition.x > x + width) {
  36182. return false;
  36183. }
  36184. if (this._clickPosition.y < y || this._clickPosition.y > y + height) {
  36185. return false;
  36186. }
  36187. return true;
  36188. };
  36189. DebugLayer.prototype.isVisible = function () {
  36190. return this._enabled;
  36191. };
  36192. DebugLayer.prototype.hide = function () {
  36193. if (!this._enabled) {
  36194. return;
  36195. }
  36196. this._enabled = false;
  36197. var engine = this._scene.getEngine();
  36198. this._scene.unregisterBeforeRender(this._syncData);
  36199. this._scene.unregisterAfterRender(this._syncUI);
  36200. this._rootElement.removeChild(this._globalDiv);
  36201. this._scene.forceShowBoundingBoxes = false;
  36202. this._scene.forceWireframe = false;
  36203. BABYLON.StandardMaterial.DiffuseTextureEnabled = true;
  36204. BABYLON.StandardMaterial.AmbientTextureEnabled = true;
  36205. BABYLON.StandardMaterial.SpecularTextureEnabled = true;
  36206. BABYLON.StandardMaterial.EmissiveTextureEnabled = true;
  36207. BABYLON.StandardMaterial.BumpTextureEnabled = true;
  36208. BABYLON.StandardMaterial.OpacityTextureEnabled = true;
  36209. BABYLON.StandardMaterial.ReflectionTextureEnabled = true;
  36210. BABYLON.StandardMaterial.LightmapTextureEnabled = true;
  36211. BABYLON.StandardMaterial.RefractionTextureEnabled = true;
  36212. BABYLON.StandardMaterial.ColorGradingTextureEnabled = true;
  36213. this._scene.shadowsEnabled = true;
  36214. this._scene.particlesEnabled = true;
  36215. this._scene.postProcessesEnabled = true;
  36216. this._scene.collisionsEnabled = true;
  36217. this._scene.lightsEnabled = true;
  36218. this._scene.texturesEnabled = true;
  36219. this._scene.lensFlaresEnabled = true;
  36220. this._scene.proceduralTexturesEnabled = true;
  36221. this._scene.renderTargetsEnabled = true;
  36222. this._scene.probesEnabled = true;
  36223. engine.getRenderingCanvas().removeEventListener("click", this._onCanvasClick);
  36224. this._clearSkeletonViewers();
  36225. };
  36226. DebugLayer.prototype._clearSkeletonViewers = function () {
  36227. for (var index = 0; index < this._skeletonViewers.length; index++) {
  36228. this._skeletonViewers[index].dispose();
  36229. }
  36230. this._skeletonViewers = [];
  36231. };
  36232. DebugLayer.prototype.show = function (showUI, camera, rootElement) {
  36233. if (showUI === void 0) { showUI = true; }
  36234. if (camera === void 0) { camera = null; }
  36235. if (rootElement === void 0) { rootElement = null; }
  36236. if (this._enabled) {
  36237. return;
  36238. }
  36239. this._enabled = true;
  36240. if (camera) {
  36241. this._camera = camera;
  36242. }
  36243. else {
  36244. this._camera = this._scene.activeCamera;
  36245. }
  36246. this._showUI = showUI;
  36247. var engine = this._scene.getEngine();
  36248. this._globalDiv = document.createElement("div");
  36249. this._rootElement = rootElement || document.body;
  36250. this._rootElement.appendChild(this._globalDiv);
  36251. this._generateDOMelements();
  36252. engine.getRenderingCanvas().addEventListener("click", this._onCanvasClick);
  36253. this._syncPositions();
  36254. this._scene.registerBeforeRender(this._syncData);
  36255. this._scene.registerAfterRender(this._syncUI);
  36256. };
  36257. DebugLayer.prototype._clearLabels = function () {
  36258. this._drawingContext.clearRect(0, 0, this._drawingCanvas.width, this._drawingCanvas.height);
  36259. for (var index = 0; index < this._scene.meshes.length; index++) {
  36260. var mesh = this._scene.meshes[index];
  36261. mesh.renderOverlay = false;
  36262. }
  36263. };
  36264. DebugLayer.prototype._generateheader = function (root, text) {
  36265. var header = document.createElement("div");
  36266. header.innerHTML = text + "&nbsp;";
  36267. header.style.textAlign = "right";
  36268. header.style.width = "100%";
  36269. header.style.color = "white";
  36270. header.style.backgroundColor = "Black";
  36271. header.style.padding = "5px 5px 4px 0px";
  36272. header.style.marginLeft = "-5px";
  36273. header.style.fontWeight = "bold";
  36274. root.appendChild(header);
  36275. };
  36276. DebugLayer.prototype._generateTexBox = function (root, title, color) {
  36277. var label = document.createElement("label");
  36278. label.style.display = "inline";
  36279. label.innerHTML = title;
  36280. label.style.color = color;
  36281. root.appendChild(label);
  36282. root.appendChild(document.createElement("br"));
  36283. };
  36284. DebugLayer.prototype._generateAdvancedCheckBox = function (root, leftTitle, rightTitle, initialState, task, tag) {
  36285. if (tag === void 0) { tag = null; }
  36286. var label = document.createElement("label");
  36287. label.style.display = "inline";
  36288. var boundingBoxesCheckbox = document.createElement("input");
  36289. boundingBoxesCheckbox.type = "checkbox";
  36290. boundingBoxesCheckbox.checked = initialState;
  36291. boundingBoxesCheckbox.style.display = "inline";
  36292. boundingBoxesCheckbox.style.margin = "0px 5px 0px 0px";
  36293. boundingBoxesCheckbox.style.verticalAlign = "sub";
  36294. boundingBoxesCheckbox.addEventListener("change", function (evt) {
  36295. task(evt.target, tag);
  36296. });
  36297. label.appendChild(boundingBoxesCheckbox);
  36298. var container = document.createElement("span");
  36299. var leftPart = document.createElement("span");
  36300. var rightPart = document.createElement("span");
  36301. rightPart.style.cssFloat = "right";
  36302. leftPart.innerHTML = leftTitle;
  36303. rightPart.innerHTML = rightTitle;
  36304. rightPart.style.fontSize = "12px";
  36305. rightPart.style.maxWidth = "200px";
  36306. container.appendChild(leftPart);
  36307. container.appendChild(rightPart);
  36308. label.appendChild(container);
  36309. root.appendChild(label);
  36310. root.appendChild(document.createElement("br"));
  36311. };
  36312. DebugLayer.prototype._generateCheckBox = function (root, title, initialState, task, tag) {
  36313. if (tag === void 0) { tag = null; }
  36314. var label = document.createElement("label");
  36315. label.style.display = "inline";
  36316. var checkBox = document.createElement("input");
  36317. checkBox.type = "checkbox";
  36318. checkBox.checked = initialState;
  36319. checkBox.style.display = "inline";
  36320. checkBox.style.margin = "0px 5px 0px 0px";
  36321. checkBox.style.verticalAlign = "sub";
  36322. checkBox.addEventListener("change", function (evt) {
  36323. task(evt.target, tag);
  36324. });
  36325. label.appendChild(checkBox);
  36326. label.appendChild(document.createTextNode(title));
  36327. root.appendChild(label);
  36328. root.appendChild(document.createElement("br"));
  36329. };
  36330. DebugLayer.prototype._generateButton = function (root, title, task, tag) {
  36331. if (tag === void 0) { tag = null; }
  36332. var button = document.createElement("button");
  36333. button.innerHTML = title;
  36334. button.style.height = "24px";
  36335. button.style.width = "150px";
  36336. button.style.marginBottom = "5px";
  36337. button.style.color = "#444444";
  36338. button.style.border = "1px solid white";
  36339. button.className = "debugLayerButton";
  36340. button.addEventListener("click", function (evt) {
  36341. task(evt.target, tag);
  36342. });
  36343. root.appendChild(button);
  36344. root.appendChild(document.createElement("br"));
  36345. };
  36346. DebugLayer.prototype._generateRadio = function (root, title, name, initialState, task, tag) {
  36347. if (tag === void 0) { tag = null; }
  36348. var label = document.createElement("label");
  36349. label.style.display = "inline";
  36350. var boundingBoxesRadio = document.createElement("input");
  36351. boundingBoxesRadio.type = "radio";
  36352. boundingBoxesRadio.name = name;
  36353. boundingBoxesRadio.checked = initialState;
  36354. boundingBoxesRadio.style.display = "inline";
  36355. boundingBoxesRadio.style.margin = "0px 5px 0px 0px";
  36356. boundingBoxesRadio.style.verticalAlign = "sub";
  36357. boundingBoxesRadio.addEventListener("change", function (evt) {
  36358. task(evt.target, tag);
  36359. });
  36360. label.appendChild(boundingBoxesRadio);
  36361. label.appendChild(document.createTextNode(title));
  36362. root.appendChild(label);
  36363. root.appendChild(document.createElement("br"));
  36364. };
  36365. DebugLayer.prototype._generateDOMelements = function () {
  36366. var _this = this;
  36367. this._globalDiv.id = "DebugLayer";
  36368. this._globalDiv.style.position = "absolute";
  36369. this._globalDiv.style.fontFamily = "Segoe UI, Arial";
  36370. this._globalDiv.style.fontSize = "14px";
  36371. this._globalDiv.style.color = "white";
  36372. // Drawing canvas
  36373. this._drawingCanvas = document.createElement("canvas");
  36374. this._drawingCanvas.id = "DebugLayerDrawingCanvas";
  36375. this._drawingCanvas.style.position = "absolute";
  36376. this._drawingCanvas.style.pointerEvents = "none";
  36377. this._drawingCanvas.style.backgroundColor = "transparent";
  36378. this._drawingContext = this._drawingCanvas.getContext("2d");
  36379. this._globalDiv.appendChild(this._drawingCanvas);
  36380. if (this._showUI) {
  36381. var background = "rgba(128, 128, 128, 0.4)";
  36382. var border = "rgb(180, 180, 180) solid 1px";
  36383. // Stats
  36384. this._statsDiv = document.createElement("div");
  36385. this._statsDiv.id = "DebugLayerStats";
  36386. this._statsDiv.style.border = border;
  36387. this._statsDiv.style.position = "absolute";
  36388. this._statsDiv.style.background = background;
  36389. this._statsDiv.style.padding = "0px 0px 0px 5px";
  36390. this._generateheader(this._statsDiv, "STATISTICS");
  36391. this._statsSubsetDiv = document.createElement("div");
  36392. this._statsSubsetDiv.style.paddingTop = "5px";
  36393. this._statsSubsetDiv.style.paddingBottom = "5px";
  36394. this._statsSubsetDiv.style.overflowY = "auto";
  36395. this._statsDiv.appendChild(this._statsSubsetDiv);
  36396. // Tree
  36397. this._treeDiv = document.createElement("div");
  36398. this._treeDiv.id = "DebugLayerTree";
  36399. this._treeDiv.style.border = border;
  36400. this._treeDiv.style.position = "absolute";
  36401. this._treeDiv.style.background = background;
  36402. this._treeDiv.style.padding = "0px 0px 0px 5px";
  36403. this._treeDiv.style.display = "none";
  36404. this._generateheader(this._treeDiv, "MESHES TREE");
  36405. this._treeSubsetDiv = document.createElement("div");
  36406. this._treeSubsetDiv.style.paddingTop = "5px";
  36407. this._treeSubsetDiv.style.paddingRight = "5px";
  36408. this._treeSubsetDiv.style.overflowY = "auto";
  36409. this._treeSubsetDiv.style.maxHeight = "300px";
  36410. this._treeDiv.appendChild(this._treeSubsetDiv);
  36411. this._needToRefreshMeshesTree = true;
  36412. // Logs
  36413. this._logDiv = document.createElement("div");
  36414. this._logDiv.style.border = border;
  36415. this._logDiv.id = "DebugLayerLogs";
  36416. this._logDiv.style.position = "absolute";
  36417. this._logDiv.style.background = background;
  36418. this._logDiv.style.padding = "0px 0px 0px 5px";
  36419. this._logDiv.style.display = "none";
  36420. this._generateheader(this._logDiv, "LOGS");
  36421. this._logSubsetDiv = document.createElement("div");
  36422. this._logSubsetDiv.style.height = "127px";
  36423. this._logSubsetDiv.style.paddingTop = "5px";
  36424. this._logSubsetDiv.style.overflowY = "auto";
  36425. this._logSubsetDiv.style.fontSize = "12px";
  36426. this._logSubsetDiv.style.fontFamily = "consolas";
  36427. this._logSubsetDiv.innerHTML = BABYLON.Tools.LogCache;
  36428. this._logDiv.appendChild(this._logSubsetDiv);
  36429. BABYLON.Tools.OnNewCacheEntry = function (entry) {
  36430. _this._logSubsetDiv.innerHTML = entry + _this._logSubsetDiv.innerHTML;
  36431. };
  36432. // Options
  36433. this._optionsDiv = document.createElement("div");
  36434. this._optionsDiv.id = "DebugLayerOptions";
  36435. this._optionsDiv.style.border = border;
  36436. this._optionsDiv.style.position = "absolute";
  36437. this._optionsDiv.style.background = background;
  36438. this._optionsDiv.style.padding = "0px 0px 0px 5px";
  36439. this._optionsDiv.style.overflowY = "auto";
  36440. this._generateheader(this._optionsDiv, "OPTIONS");
  36441. this._optionsSubsetDiv = document.createElement("div");
  36442. this._optionsSubsetDiv.style.paddingTop = "5px";
  36443. this._optionsSubsetDiv.style.paddingBottom = "5px";
  36444. this._optionsSubsetDiv.style.overflowY = "auto";
  36445. this._optionsSubsetDiv.style.maxHeight = "200px";
  36446. this._optionsDiv.appendChild(this._optionsSubsetDiv);
  36447. this._generateTexBox(this._optionsSubsetDiv, "<b>Windows:</b>", this.accentColor);
  36448. this._generateCheckBox(this._optionsSubsetDiv, "Statistics", this._displayStatistics, function (element) { _this._displayStatistics = element.checked; });
  36449. this._generateCheckBox(this._optionsSubsetDiv, "Logs", this._displayLogs, function (element) { _this._displayLogs = element.checked; });
  36450. this._generateCheckBox(this._optionsSubsetDiv, "Meshes tree", this._displayTree, function (element) {
  36451. _this._displayTree = element.checked;
  36452. _this._needToRefreshMeshesTree = true;
  36453. });
  36454. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  36455. this._generateTexBox(this._optionsSubsetDiv, "<b>General:</b>", this.accentColor);
  36456. this._generateCheckBox(this._optionsSubsetDiv, "Bounding boxes", this._scene.forceShowBoundingBoxes, function (element) { _this._scene.forceShowBoundingBoxes = element.checked; });
  36457. this._generateCheckBox(this._optionsSubsetDiv, "Clickable labels", this._labelsEnabled, function (element) {
  36458. _this._labelsEnabled = element.checked;
  36459. if (!_this._labelsEnabled) {
  36460. _this._clearLabels();
  36461. }
  36462. });
  36463. this._generateCheckBox(this._optionsSubsetDiv, "Generate user marks (F12)", BABYLON.Tools.PerformanceLogLevel === BABYLON.Tools.PerformanceUserMarkLogLevel, function (element) {
  36464. if (element.checked) {
  36465. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceUserMarkLogLevel;
  36466. }
  36467. else {
  36468. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceNoneLogLevel;
  36469. }
  36470. });
  36471. ;
  36472. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  36473. this._generateTexBox(this._optionsSubsetDiv, "<b>Rendering mode:</b>", this.accentColor);
  36474. this._generateRadio(this._optionsSubsetDiv, "Solid", "renderMode", !this._scene.forceWireframe && !this._scene.forcePointsCloud, function (element) {
  36475. if (element.checked) {
  36476. _this._scene.forceWireframe = false;
  36477. _this._scene.forcePointsCloud = false;
  36478. }
  36479. });
  36480. this._generateRadio(this._optionsSubsetDiv, "Wireframe", "renderMode", this._scene.forceWireframe, function (element) {
  36481. if (element.checked) {
  36482. _this._scene.forceWireframe = true;
  36483. _this._scene.forcePointsCloud = false;
  36484. }
  36485. });
  36486. this._generateRadio(this._optionsSubsetDiv, "Point", "renderMode", this._scene.forcePointsCloud, function (element) {
  36487. if (element.checked) {
  36488. _this._scene.forceWireframe = false;
  36489. _this._scene.forcePointsCloud = true;
  36490. }
  36491. });
  36492. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  36493. this._generateTexBox(this._optionsSubsetDiv, "<b>Texture channels:</b>", this.accentColor);
  36494. this._generateCheckBox(this._optionsSubsetDiv, "Diffuse", BABYLON.StandardMaterial.DiffuseTextureEnabled, function (element) { BABYLON.StandardMaterial.DiffuseTextureEnabled = element.checked; });
  36495. this._generateCheckBox(this._optionsSubsetDiv, "Ambient", BABYLON.StandardMaterial.AmbientTextureEnabled, function (element) { BABYLON.StandardMaterial.AmbientTextureEnabled = element.checked; });
  36496. this._generateCheckBox(this._optionsSubsetDiv, "Specular", BABYLON.StandardMaterial.SpecularTextureEnabled, function (element) { BABYLON.StandardMaterial.SpecularTextureEnabled = element.checked; });
  36497. this._generateCheckBox(this._optionsSubsetDiv, "Emissive", BABYLON.StandardMaterial.EmissiveTextureEnabled, function (element) { BABYLON.StandardMaterial.EmissiveTextureEnabled = element.checked; });
  36498. this._generateCheckBox(this._optionsSubsetDiv, "Bump", BABYLON.StandardMaterial.BumpTextureEnabled, function (element) { BABYLON.StandardMaterial.BumpTextureEnabled = element.checked; });
  36499. this._generateCheckBox(this._optionsSubsetDiv, "Opacity", BABYLON.StandardMaterial.OpacityTextureEnabled, function (element) { BABYLON.StandardMaterial.OpacityTextureEnabled = element.checked; });
  36500. this._generateCheckBox(this._optionsSubsetDiv, "Reflection", BABYLON.StandardMaterial.ReflectionTextureEnabled, function (element) { BABYLON.StandardMaterial.ReflectionTextureEnabled = element.checked; });
  36501. this._generateCheckBox(this._optionsSubsetDiv, "Refraction", BABYLON.StandardMaterial.RefractionTextureEnabled, function (element) { BABYLON.StandardMaterial.RefractionTextureEnabled = element.checked; });
  36502. this._generateCheckBox(this._optionsSubsetDiv, "ColorGrading", BABYLON.StandardMaterial.ColorGradingTextureEnabled, function (element) { BABYLON.StandardMaterial.ColorGradingTextureEnabled = element.checked; });
  36503. this._generateCheckBox(this._optionsSubsetDiv, "Lightmap", BABYLON.StandardMaterial.LightmapTextureEnabled, function (element) { BABYLON.StandardMaterial.LightmapTextureEnabled = element.checked; });
  36504. this._generateCheckBox(this._optionsSubsetDiv, "Fresnel", BABYLON.StandardMaterial.FresnelEnabled, function (element) { BABYLON.StandardMaterial.FresnelEnabled = element.checked; });
  36505. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  36506. this._generateTexBox(this._optionsSubsetDiv, "<b>Options:</b>", this.accentColor);
  36507. this._generateCheckBox(this._optionsSubsetDiv, "Animations", this._scene.animationsEnabled, function (element) { _this._scene.animationsEnabled = element.checked; });
  36508. this._generateCheckBox(this._optionsSubsetDiv, "Collisions", this._scene.collisionsEnabled, function (element) { _this._scene.collisionsEnabled = element.checked; });
  36509. this._generateCheckBox(this._optionsSubsetDiv, "Fog", this._scene.fogEnabled, function (element) { _this._scene.fogEnabled = element.checked; });
  36510. this._generateCheckBox(this._optionsSubsetDiv, "Lens flares", this._scene.lensFlaresEnabled, function (element) { _this._scene.lensFlaresEnabled = element.checked; });
  36511. this._generateCheckBox(this._optionsSubsetDiv, "Lights", this._scene.lightsEnabled, function (element) { _this._scene.lightsEnabled = element.checked; });
  36512. this._generateCheckBox(this._optionsSubsetDiv, "Particles", this._scene.particlesEnabled, function (element) { _this._scene.particlesEnabled = element.checked; });
  36513. this._generateCheckBox(this._optionsSubsetDiv, "Post-processes", this._scene.postProcessesEnabled, function (element) { _this._scene.postProcessesEnabled = element.checked; });
  36514. this._generateCheckBox(this._optionsSubsetDiv, "Probes", this._scene.probesEnabled, function (element) { _this._scene.probesEnabled = element.checked; });
  36515. this._generateCheckBox(this._optionsSubsetDiv, "Procedural textures", this._scene.proceduralTexturesEnabled, function (element) { _this._scene.proceduralTexturesEnabled = element.checked; });
  36516. this._generateCheckBox(this._optionsSubsetDiv, "Render targets", this._scene.renderTargetsEnabled, function (element) { _this._scene.renderTargetsEnabled = element.checked; });
  36517. this._generateCheckBox(this._optionsSubsetDiv, "Shadows", this._scene.shadowsEnabled, function (element) { _this._scene.shadowsEnabled = element.checked; });
  36518. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", this._scene.skeletonsEnabled, function (element) { _this._scene.skeletonsEnabled = element.checked; });
  36519. this._generateCheckBox(this._optionsSubsetDiv, "Sprites", this._scene.spritesEnabled, function (element) { _this._scene.spritesEnabled = element.checked; });
  36520. this._generateCheckBox(this._optionsSubsetDiv, "Textures", this._scene.texturesEnabled, function (element) { _this._scene.texturesEnabled = element.checked; });
  36521. if (BABYLON.AudioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  36522. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  36523. this._generateTexBox(this._optionsSubsetDiv, "<b>Audio:</b>", this.accentColor);
  36524. this._generateRadio(this._optionsSubsetDiv, "Headphones", "panningModel", this._scene.headphone, function (element) {
  36525. if (element.checked) {
  36526. _this._scene.headphone = true;
  36527. }
  36528. });
  36529. this._generateRadio(this._optionsSubsetDiv, "Normal Speakers", "panningModel", !this._scene.headphone, function (element) {
  36530. if (element.checked) {
  36531. _this._scene.headphone = false;
  36532. }
  36533. });
  36534. this._generateCheckBox(this._optionsSubsetDiv, "Disable audio", !this._scene.audioEnabled, function (element) {
  36535. _this._scene.audioEnabled = !element.checked;
  36536. });
  36537. }
  36538. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  36539. this._generateTexBox(this._optionsSubsetDiv, "<b>Viewers:</b>", this.accentColor);
  36540. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", false, function (element) {
  36541. if (!element.checked) {
  36542. _this._clearSkeletonViewers();
  36543. return;
  36544. }
  36545. for (var index = 0; index < _this._scene.meshes.length; index++) {
  36546. var mesh = _this._scene.meshes[index];
  36547. if (mesh.skeleton) {
  36548. var found = false;
  36549. for (var sIndex = 0; sIndex < _this._skeletonViewers.length; sIndex++) {
  36550. if (_this._skeletonViewers[sIndex].skeleton === mesh.skeleton) {
  36551. found = true;
  36552. break;
  36553. }
  36554. }
  36555. if (found) {
  36556. continue;
  36557. }
  36558. var viewer = new BABYLON.Debug.SkeletonViewer(mesh.skeleton, mesh, _this._scene);
  36559. viewer.isEnabled = true;
  36560. _this._skeletonViewers.push(viewer);
  36561. }
  36562. }
  36563. });
  36564. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  36565. this._generateTexBox(this._optionsSubsetDiv, "<b>Tools:</b>", this.accentColor);
  36566. this._generateButton(this._optionsSubsetDiv, "Dump rendertargets", function (element) { _this._scene.dumpNextRenderTargets = true; });
  36567. this._generateButton(this._optionsSubsetDiv, "Run SceneOptimizer", function (element) { BABYLON.SceneOptimizer.OptimizeAsync(_this._scene); });
  36568. this._generateButton(this._optionsSubsetDiv, "Log camera object", function (element) {
  36569. if (_this._camera) {
  36570. console.log(_this._camera);
  36571. }
  36572. else {
  36573. console.warn("No camera defined, or debug layer created before camera creation!");
  36574. }
  36575. });
  36576. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  36577. this._globalDiv.appendChild(this._statsDiv);
  36578. this._globalDiv.appendChild(this._logDiv);
  36579. this._globalDiv.appendChild(this._optionsDiv);
  36580. this._globalDiv.appendChild(this._treeDiv);
  36581. }
  36582. };
  36583. DebugLayer.prototype._displayStats = function () {
  36584. var scene = this._scene;
  36585. var engine = scene.getEngine();
  36586. var glInfo = engine.getGlInfo();
  36587. this._statsSubsetDiv.innerHTML = "Babylon.js v" + BABYLON.Engine.Version + " - <b>" + BABYLON.Tools.Format(engine.getFps(), 0) + " fps</b><br><br>"
  36588. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  36589. + "<b>Count</b><br>"
  36590. + "Total meshes: " + scene.meshes.length + "<br>"
  36591. + "Total lights: " + scene.lights.length + "<br>"
  36592. + "Total vertices: " + scene.getTotalVertices() + "<br>"
  36593. + "Total materials: " + scene.materials.length + "<br>"
  36594. + "Total textures: " + scene.textures.length + "<br>"
  36595. + "Active meshes: " + scene.getActiveMeshes().length + "<br>"
  36596. + "Active indices: " + scene.getActiveIndices() + "<br>"
  36597. + "Active bones: " + scene.getActiveBones() + "<br>"
  36598. + "Active particles: " + scene.getActiveParticles() + "<br>"
  36599. + "<b>Draw calls: " + engine.drawCalls + "</b><br><br>"
  36600. + "<b>Duration</b><br>"
  36601. + "Meshes selection:</i> " + BABYLON.Tools.Format(scene.getEvaluateActiveMeshesDuration()) + " ms<br>"
  36602. + "Render Targets: " + BABYLON.Tools.Format(scene.getRenderTargetsDuration()) + " ms<br>"
  36603. + "Particles: " + BABYLON.Tools.Format(scene.getParticlesDuration()) + " ms<br>"
  36604. + "Sprites: " + BABYLON.Tools.Format(scene.getSpritesDuration()) + " ms<br><br>"
  36605. + "Render: <b>" + BABYLON.Tools.Format(scene.getRenderDuration()) + " ms</b><br>"
  36606. + "Frame: " + BABYLON.Tools.Format(scene.getLastFrameDuration()) + " ms<br>"
  36607. + "Potential FPS: " + BABYLON.Tools.Format(1000.0 / scene.getLastFrameDuration(), 0) + "<br>"
  36608. + "Resolution: " + engine.getRenderWidth() + "x" + engine.getRenderHeight() + "<br><br>"
  36609. + "</div>"
  36610. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  36611. + "<b>Extensions</b><br>"
  36612. + "Std derivatives: " + (engine.getCaps().standardDerivatives ? "Yes" : "No") + "<br>"
  36613. + "Compressed textures: " + (engine.getCaps().s3tc ? "Yes" : "No") + "<br>"
  36614. + "Hardware instances: " + (engine.getCaps().instancedArrays ? "Yes" : "No") + "<br>"
  36615. + "Texture float: " + (engine.getCaps().textureFloat ? "Yes" : "No") + "<br><br>"
  36616. + "32bits indices: " + (engine.getCaps().uintIndices ? "Yes" : "No") + "<br>"
  36617. + "Fragment depth: " + (engine.getCaps().fragmentDepthSupported ? "Yes" : "No") + "<br>"
  36618. + "High precision shaders: " + (engine.getCaps().highPrecisionShaderSupported ? "Yes" : "No") + "<br>"
  36619. + "Draw buffers: " + (engine.getCaps().drawBuffersExtension ? "Yes" : "No") + "<br>"
  36620. + "</div><br>"
  36621. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  36622. + "<b>Caps.</b><br>"
  36623. + "Max textures units: " + engine.getCaps().maxTexturesImageUnits + "<br>"
  36624. + "Max textures size: " + engine.getCaps().maxTextureSize + "<br>"
  36625. + "Max anisotropy: " + engine.getCaps().maxAnisotropy + "<br>"
  36626. + "<b>Info</b><br>"
  36627. + "WebGL feature level: " + engine.webGLVersion + "<br>"
  36628. + glInfo.version + "<br>"
  36629. + "</div><br>"
  36630. + glInfo.renderer + "<br>";
  36631. if (this.customStatsFunction) {
  36632. this._statsSubsetDiv.innerHTML += this.customStatsFunction();
  36633. }
  36634. };
  36635. return DebugLayer;
  36636. })();
  36637. BABYLON.DebugLayer = DebugLayer;
  36638. })(BABYLON || (BABYLON = {}));
  36639. var BABYLON;
  36640. (function (BABYLON) {
  36641. var SIMDVector3 = (function () {
  36642. function SIMDVector3() {
  36643. }
  36644. SIMDVector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  36645. var v = SIMD.float32x4.loadXYZ(vector._data, 0);
  36646. var m0 = SIMD.float32x4.load(transformation.m, 0);
  36647. var m1 = SIMD.float32x4.load(transformation.m, 4);
  36648. var m2 = SIMD.float32x4.load(transformation.m, 8);
  36649. var m3 = SIMD.float32x4.load(transformation.m, 12);
  36650. 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));
  36651. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  36652. SIMD.float32x4.storeXYZ(result._data, 0, r);
  36653. };
  36654. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  36655. var v0 = SIMD.float32x4.splat(x);
  36656. var v1 = SIMD.float32x4.splat(y);
  36657. var v2 = SIMD.float32x4.splat(z);
  36658. var m0 = SIMD.float32x4.load(transformation.m, 0);
  36659. var m1 = SIMD.float32x4.load(transformation.m, 4);
  36660. var m2 = SIMD.float32x4.load(transformation.m, 8);
  36661. var m3 = SIMD.float32x4.load(transformation.m, 12);
  36662. 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));
  36663. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  36664. SIMD.float32x4.storeXYZ(result._data, 0, r);
  36665. };
  36666. return SIMDVector3;
  36667. })();
  36668. BABYLON.SIMDVector3 = SIMDVector3;
  36669. var SIMDMatrix = (function () {
  36670. function SIMDMatrix() {
  36671. }
  36672. SIMDMatrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  36673. if (offset === void 0) { offset = 0; }
  36674. var tm = this.m;
  36675. var om = other.m;
  36676. var om0 = SIMD.float32x4.load(om, 0);
  36677. var om1 = SIMD.float32x4.load(om, 4);
  36678. var om2 = SIMD.float32x4.load(om, 8);
  36679. var om3 = SIMD.float32x4.load(om, 12);
  36680. var tm0 = SIMD.float32x4.load(tm, 0);
  36681. 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)))));
  36682. var tm1 = SIMD.float32x4.load(tm, 4);
  36683. 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)))));
  36684. var tm2 = SIMD.float32x4.load(tm, 8);
  36685. 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)))));
  36686. var tm3 = SIMD.float32x4.load(tm, 12);
  36687. 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)))));
  36688. };
  36689. SIMDMatrix.prototype.invertToRefSIMD = function (other) {
  36690. var src = this.m;
  36691. var dest = other.m;
  36692. var row0, row1, row2, row3;
  36693. var tmp1;
  36694. var minor0, minor1, minor2, minor3;
  36695. var det;
  36696. // Load the 4 rows
  36697. var src0 = SIMD.float32x4.load(src, 0);
  36698. var src1 = SIMD.float32x4.load(src, 4);
  36699. var src2 = SIMD.float32x4.load(src, 8);
  36700. var src3 = SIMD.float32x4.load(src, 12);
  36701. // Transpose the source matrix. Sort of. Not a true transpose operation
  36702. tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  36703. row1 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  36704. row0 = SIMD.float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  36705. row1 = SIMD.float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  36706. tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  36707. row3 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  36708. row2 = SIMD.float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  36709. row3 = SIMD.float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  36710. // This is a true transposition, but it will lead to an incorrect result
  36711. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  36712. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  36713. //row0 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  36714. //row1 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  36715. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  36716. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  36717. //row2 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  36718. //row3 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  36719. // ----
  36720. tmp1 = SIMD.float32x4.mul(row2, row3);
  36721. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  36722. minor0 = SIMD.float32x4.mul(row1, tmp1);
  36723. minor1 = SIMD.float32x4.mul(row0, tmp1);
  36724. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  36725. minor0 = SIMD.float32x4.sub(SIMD.float32x4.mul(row1, tmp1), minor0);
  36726. minor1 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor1);
  36727. minor1 = SIMD.float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  36728. // ----
  36729. tmp1 = SIMD.float32x4.mul(row1, row2);
  36730. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  36731. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor0);
  36732. minor3 = SIMD.float32x4.mul(row0, tmp1);
  36733. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  36734. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row3, tmp1));
  36735. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor3);
  36736. minor3 = SIMD.float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  36737. // ----
  36738. tmp1 = SIMD.float32x4.mul(SIMD.float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  36739. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  36740. row2 = SIMD.float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  36741. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor0);
  36742. minor2 = SIMD.float32x4.mul(row0, tmp1);
  36743. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  36744. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row2, tmp1));
  36745. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor2);
  36746. minor2 = SIMD.float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  36747. // ----
  36748. tmp1 = SIMD.float32x4.mul(row0, row1);
  36749. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  36750. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor2);
  36751. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row2, tmp1), minor3);
  36752. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  36753. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row3, tmp1), minor2);
  36754. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row2, tmp1));
  36755. // ----
  36756. tmp1 = SIMD.float32x4.mul(row0, row3);
  36757. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  36758. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row2, tmp1));
  36759. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor2);
  36760. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  36761. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor1);
  36762. minor2 = SIMD.float32x4.sub(minor2, SIMD.float32x4.mul(row1, tmp1));
  36763. // ----
  36764. tmp1 = SIMD.float32x4.mul(row0, row2);
  36765. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  36766. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor1);
  36767. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row1, tmp1));
  36768. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  36769. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row3, tmp1));
  36770. minor3 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor3);
  36771. // Compute determinant
  36772. det = SIMD.float32x4.mul(row0, minor0);
  36773. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  36774. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  36775. tmp1 = SIMD.float32x4.reciprocalApproximation(det);
  36776. det = SIMD.float32x4.sub(SIMD.float32x4.add(tmp1, tmp1), SIMD.float32x4.mul(det, SIMD.float32x4.mul(tmp1, tmp1)));
  36777. det = SIMD.float32x4.swizzle(det, 0, 0, 0, 0);
  36778. // These shuffles aren't necessary if the faulty transposition is done
  36779. // up at the top of this function.
  36780. //minor0 = SIMD.float32x4.swizzle(minor0, 2, 1, 0, 3);
  36781. //minor1 = SIMD.float32x4.swizzle(minor1, 2, 1, 0, 3);
  36782. //minor2 = SIMD.float32x4.swizzle(minor2, 2, 1, 0, 3);
  36783. //minor3 = SIMD.float32x4.swizzle(minor3, 2, 1, 0, 3);
  36784. // Compute final values by multiplying with 1/det
  36785. minor0 = SIMD.float32x4.mul(det, minor0);
  36786. minor1 = SIMD.float32x4.mul(det, minor1);
  36787. minor2 = SIMD.float32x4.mul(det, minor2);
  36788. minor3 = SIMD.float32x4.mul(det, minor3);
  36789. SIMD.float32x4.store(dest, 0, minor0);
  36790. SIMD.float32x4.store(dest, 4, minor1);
  36791. SIMD.float32x4.store(dest, 8, minor2);
  36792. SIMD.float32x4.store(dest, 12, minor3);
  36793. return this;
  36794. };
  36795. SIMDMatrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  36796. var out = result.m;
  36797. var center = SIMD.float32x4(targetRef.x, targetRef.y, targetRef.z, 0);
  36798. var eye = SIMD.float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0);
  36799. var up = SIMD.float32x4(upRef.x, upRef.y, upRef.z, 0);
  36800. // cc.kmVec3Subtract(f, pCenter, pEye);
  36801. var f = SIMD.float32x4.sub(center, eye);
  36802. // cc.kmVec3Normalize(f, f);
  36803. var tmp = SIMD.float32x4.mul(f, f);
  36804. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  36805. f = SIMD.float32x4.mul(f, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  36806. // cc.kmVec3Assign(up, pUp);
  36807. // cc.kmVec3Normalize(up, up);
  36808. tmp = SIMD.float32x4.mul(up, up);
  36809. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  36810. up = SIMD.float32x4.mul(up, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  36811. // cc.kmVec3Cross(s, f, up);
  36812. 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)));
  36813. // cc.kmVec3Normalize(s, s);
  36814. tmp = SIMD.float32x4.mul(s, s);
  36815. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  36816. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  36817. // cc.kmVec3Cross(u, s, f);
  36818. 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)));
  36819. // cc.kmVec3Normalize(s, s);
  36820. tmp = SIMD.float32x4.mul(s, s);
  36821. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  36822. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  36823. var zero = SIMD.float32x4.splat(0.0);
  36824. s = SIMD.float32x4.neg(s);
  36825. var tmp01 = SIMD.float32x4.shuffle(s, u, 0, 1, 4, 5);
  36826. var tmp23 = SIMD.float32x4.shuffle(f, zero, 0, 1, 4, 5);
  36827. var a0 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  36828. var a1 = SIMD.float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  36829. tmp01 = SIMD.float32x4.shuffle(s, u, 2, 3, 6, 7);
  36830. tmp23 = SIMD.float32x4.shuffle(f, zero, 2, 3, 6, 7);
  36831. var a2 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  36832. var a3 = SIMD.float32x4(0.0, 0.0, 0.0, 1.0);
  36833. var b0 = SIMD.float32x4(1.0, 0.0, 0.0, 0.0);
  36834. var b1 = SIMD.float32x4(0.0, 1.0, 0.0, 0.0);
  36835. var b2 = SIMD.float32x4(0.0, 0.0, 1.0, 0.0);
  36836. var b3 = SIMD.float32x4.neg(eye);
  36837. b3 = SIMD.float32x4.withW(b3, 1.0);
  36838. 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)))));
  36839. 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)))));
  36840. 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)))));
  36841. 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)))));
  36842. };
  36843. return SIMDMatrix;
  36844. })();
  36845. BABYLON.SIMDMatrix = SIMDMatrix;
  36846. var previousMultiplyToArray = BABYLON.Matrix.prototype.multiplyToArray;
  36847. var previousInvertToRef = BABYLON.Matrix.prototype.invertToRef;
  36848. var previousLookAtLHToRef = BABYLON.Matrix.LookAtLHToRef;
  36849. var previousTransformCoordinatesToRef = BABYLON.Vector3.TransformCoordinatesToRef;
  36850. var previousTransformCoordinatesFromFloatsToRef = BABYLON.Vector3.TransformCoordinatesFromFloatsToRef;
  36851. var SIMDHelper = (function () {
  36852. function SIMDHelper() {
  36853. }
  36854. Object.defineProperty(SIMDHelper, "IsEnabled", {
  36855. get: function () {
  36856. return SIMDHelper._isEnabled;
  36857. },
  36858. enumerable: true,
  36859. configurable: true
  36860. });
  36861. SIMDHelper.DisableSIMD = function () {
  36862. // Replace functions
  36863. BABYLON.Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  36864. BABYLON.Matrix.prototype.invertToRef = previousInvertToRef;
  36865. BABYLON.Matrix.LookAtLHToRef = previousLookAtLHToRef;
  36866. BABYLON.Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  36867. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  36868. SIMDHelper._isEnabled = false;
  36869. };
  36870. SIMDHelper.EnableSIMD = function () {
  36871. if (window.SIMD === undefined) {
  36872. return;
  36873. }
  36874. // Replace functions
  36875. BABYLON.Matrix.prototype.multiplyToArray = SIMDMatrix.prototype.multiplyToArraySIMD;
  36876. BABYLON.Matrix.prototype.invertToRef = SIMDMatrix.prototype.invertToRefSIMD;
  36877. BABYLON.Matrix.LookAtLHToRef = SIMDMatrix.LookAtLHToRefSIMD;
  36878. BABYLON.Vector3.TransformCoordinatesToRef = SIMDVector3.TransformCoordinatesToRefSIMD;
  36879. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD;
  36880. Object.defineProperty(BABYLON.Vector3.prototype, "x", {
  36881. get: function () { return this._data[0]; },
  36882. set: function (value) {
  36883. if (!this._data) {
  36884. this._data = new Float32Array(3);
  36885. }
  36886. this._data[0] = value;
  36887. }
  36888. });
  36889. Object.defineProperty(BABYLON.Vector3.prototype, "y", {
  36890. get: function () { return this._data[1]; },
  36891. set: function (value) {
  36892. this._data[1] = value;
  36893. }
  36894. });
  36895. Object.defineProperty(BABYLON.Vector3.prototype, "z", {
  36896. get: function () { return this._data[2]; },
  36897. set: function (value) {
  36898. this._data[2] = value;
  36899. }
  36900. });
  36901. SIMDHelper._isEnabled = true;
  36902. };
  36903. SIMDHelper._isEnabled = false;
  36904. return SIMDHelper;
  36905. })();
  36906. BABYLON.SIMDHelper = SIMDHelper;
  36907. })(BABYLON || (BABYLON = {}));
  36908. var BABYLON;
  36909. (function (BABYLON) {
  36910. /**
  36911. * This class describe a rectangle that were added to the map.
  36912. * You have access to its coordinates either in pixel or normalized (UV)
  36913. */
  36914. var PackedRect = (function () {
  36915. function PackedRect(root, parent, pos, size) {
  36916. this._pos = pos;
  36917. this._size = size;
  36918. this._root = root;
  36919. this._parent = parent;
  36920. }
  36921. Object.defineProperty(PackedRect.prototype, "pos", {
  36922. /**
  36923. * @returns the position of this node into the map
  36924. */
  36925. get: function () {
  36926. return this._pos;
  36927. },
  36928. enumerable: true,
  36929. configurable: true
  36930. });
  36931. Object.defineProperty(PackedRect.prototype, "contentSize", {
  36932. /**
  36933. * @returns the size of the rectangle this node handles
  36934. */
  36935. get: function () {
  36936. return this._contentSize;
  36937. },
  36938. enumerable: true,
  36939. configurable: true
  36940. });
  36941. Object.defineProperty(PackedRect.prototype, "UVs", {
  36942. /**
  36943. * Compute the UV of the top/left, top/right, bottom/right, bottom/left points of the rectangle this node handles into the map
  36944. * @returns And array of 4 Vector2, containing UV coordinates for the four corners of the Rectangle into the map
  36945. */
  36946. get: function () {
  36947. return this.getUVsForCustomSize(this._root._size);
  36948. },
  36949. enumerable: true,
  36950. configurable: true
  36951. });
  36952. /**
  36953. * 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.
  36954. * This method will return the UVs for this part by given the custom size of what you really use
  36955. * @param customSize must be less/equal to the allocated size, UV will be compute from this
  36956. */
  36957. PackedRect.prototype.getUVsForCustomSize = function (customSize) {
  36958. var mainWidth = this._root._size.width;
  36959. var mainHeight = this._root._size.height;
  36960. var topLeft = new BABYLON.Vector2(this._pos.x / mainWidth, this._pos.y / mainHeight);
  36961. var rightBottom = new BABYLON.Vector2((this._pos.x + customSize.width - 1) / mainWidth, (this._pos.y + customSize.height - 1) / mainHeight);
  36962. var uvs = new Array();
  36963. uvs.push(topLeft);
  36964. uvs.push(new BABYLON.Vector2(rightBottom.x, topLeft.y));
  36965. uvs.push(rightBottom);
  36966. uvs.push(new BABYLON.Vector2(topLeft.x, rightBottom.y));
  36967. return uvs;
  36968. };
  36969. /**
  36970. * Free this rectangle from the map.
  36971. * Call this method when you no longer need the rectangle to be in the map.
  36972. */
  36973. PackedRect.prototype.freeContent = function () {
  36974. if (!this.contentSize) {
  36975. return;
  36976. }
  36977. this._contentSize = null;
  36978. // If everything below is also free, reset the whole node, and attempt to reset parents if they also become free
  36979. this.attemptDefrag();
  36980. };
  36981. Object.defineProperty(PackedRect.prototype, "isUsed", {
  36982. get: function () {
  36983. return this._contentSize != null || this._leftNode != null;
  36984. },
  36985. enumerable: true,
  36986. configurable: true
  36987. });
  36988. PackedRect.prototype.findAndSplitNode = function (contentSize) {
  36989. var node = this.findNode(contentSize);
  36990. // Not enough space...
  36991. if (!node) {
  36992. return null;
  36993. }
  36994. node.splitNode(contentSize);
  36995. return node;
  36996. };
  36997. PackedRect.prototype.findNode = function (size) {
  36998. var resNode = null;
  36999. // If this node is used, recurse to each of his subNodes to find an available one in its branch
  37000. if (this.isUsed) {
  37001. if (this._leftNode) {
  37002. resNode = this._leftNode.findNode(size);
  37003. }
  37004. if (!resNode && this._rightNode) {
  37005. resNode = this._rightNode.findNode(size);
  37006. }
  37007. if (!resNode && this._bottomNode) {
  37008. resNode = this._bottomNode.findNode(size);
  37009. }
  37010. }
  37011. else if (this._initialSize && (size.width <= this._initialSize.width) && (size.height <= this._initialSize.height)) {
  37012. resNode = this;
  37013. }
  37014. else if ((size.width <= this._size.width) && (size.height <= this._size.height)) {
  37015. resNode = this;
  37016. }
  37017. return resNode;
  37018. };
  37019. PackedRect.prototype.splitNode = function (contentSize) {
  37020. // 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)
  37021. if (!this._contentSize && this._initialSize) {
  37022. 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));
  37023. return this._leftNode.splitNode(contentSize);
  37024. }
  37025. else {
  37026. this._contentSize = contentSize.clone();
  37027. this._initialSize = contentSize.clone();
  37028. if (contentSize.width !== this._size.width) {
  37029. 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));
  37030. }
  37031. if (contentSize.height !== this._size.height) {
  37032. 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));
  37033. }
  37034. return this;
  37035. }
  37036. };
  37037. PackedRect.prototype.attemptDefrag = function () {
  37038. if (!this.isUsed && this.isRecursiveFree) {
  37039. this.clearNode();
  37040. if (this._parent) {
  37041. this._parent.attemptDefrag();
  37042. }
  37043. }
  37044. };
  37045. PackedRect.prototype.clearNode = function () {
  37046. this._initialSize = null;
  37047. this._rightNode = null;
  37048. this._bottomNode = null;
  37049. };
  37050. Object.defineProperty(PackedRect.prototype, "isRecursiveFree", {
  37051. get: function () {
  37052. return !this.contentSize && (!this._leftNode || this._leftNode.isRecursiveFree) && (!this._rightNode || this._rightNode.isRecursiveFree) && (!this._bottomNode || this._bottomNode.isRecursiveFree);
  37053. },
  37054. enumerable: true,
  37055. configurable: true
  37056. });
  37057. PackedRect.prototype.evalFreeSize = function (size) {
  37058. var levelSize = 0;
  37059. if (!this.isUsed) {
  37060. if (this._initialSize) {
  37061. levelSize = this._initialSize.surface;
  37062. }
  37063. else {
  37064. levelSize = this._size.surface;
  37065. }
  37066. }
  37067. if (this._rightNode) {
  37068. levelSize += this._rightNode.evalFreeSize(0);
  37069. }
  37070. if (this._bottomNode) {
  37071. levelSize += this._bottomNode.evalFreeSize(0);
  37072. }
  37073. return levelSize + size;
  37074. };
  37075. return PackedRect;
  37076. })();
  37077. BABYLON.PackedRect = PackedRect;
  37078. /**
  37079. * The purpose of this class is to pack several Rectangles into a big map, while trying to fit everything as optimally as possible.
  37080. * This class is typically used to build lightmaps, sprite map or to pack several little textures into a big one.
  37081. * 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.
  37082. */
  37083. var RectPackingMap = (function (_super) {
  37084. __extends(RectPackingMap, _super);
  37085. /**
  37086. * Create an instance of the object with a dimension using the given size
  37087. * @param size The dimension of the rectangle that will contain all the sub ones.
  37088. */
  37089. function RectPackingMap(size) {
  37090. _super.call(this, null, null, BABYLON.Vector2.Zero(), size);
  37091. this._root = this;
  37092. }
  37093. /**
  37094. * Add a rectangle, finding the best location to store it into the map
  37095. * @param size the dimension of the rectangle to store
  37096. * @return the Node containing the rectangle information, or null if we couldn't find a free spot
  37097. */
  37098. RectPackingMap.prototype.addRect = function (size) {
  37099. var node = this.findAndSplitNode(size);
  37100. return node;
  37101. };
  37102. Object.defineProperty(RectPackingMap.prototype, "freeSpace", {
  37103. /**
  37104. * Return the current space free normalized between [0;1]
  37105. * @returns {}
  37106. */
  37107. get: function () {
  37108. var freeSize = 0;
  37109. freeSize = this.evalFreeSize(freeSize);
  37110. return freeSize / (this._size.width * this._size.height);
  37111. },
  37112. enumerable: true,
  37113. configurable: true
  37114. });
  37115. return RectPackingMap;
  37116. })(PackedRect);
  37117. BABYLON.RectPackingMap = RectPackingMap;
  37118. })(BABYLON || (BABYLON = {}));
  37119. var BABYLON;
  37120. (function (BABYLON) {
  37121. var DynamicFloatArrayElementInfo = (function () {
  37122. function DynamicFloatArrayElementInfo() {
  37123. }
  37124. return DynamicFloatArrayElementInfo;
  37125. })();
  37126. BABYLON.DynamicFloatArrayElementInfo = DynamicFloatArrayElementInfo;
  37127. /**
  37128. * 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.
  37129. * The intent is to maintain through time data that will be bound to a WebGlBuffer with the ability to change add/remove elements.
  37130. * It was first built to efficiently maintain the WebGlBuffer that contain instancing based data.
  37131. * 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.
  37132. * 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.
  37133. * 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".
  37134. */
  37135. var DynamicFloatArray = (function () {
  37136. /**
  37137. * Construct an instance of the dynamic float array
  37138. * @param stride size of one element in float (i.e. not bytes!)
  37139. * @param initialElementCount the number of available entries at construction
  37140. */
  37141. function DynamicFloatArray(stride, initialElementCount) {
  37142. this.compareValueOffset = null;
  37143. this.sortingAscending = true;
  37144. this._stride = stride;
  37145. this.buffer = new Float32Array(stride * initialElementCount);
  37146. this._lastUsed = 0;
  37147. this._firstFree = 0;
  37148. this._allEntries = new Array(initialElementCount);
  37149. this._freeEntries = new Array(initialElementCount);
  37150. for (var i = 0; i < initialElementCount; i++) {
  37151. var element = new DynamicFloatArrayElementInfo();
  37152. element.offset = i * stride;
  37153. this._allEntries[i] = element;
  37154. this._freeEntries[initialElementCount - i - 1] = element;
  37155. }
  37156. }
  37157. /**
  37158. * Allocate an element in the array.
  37159. * @return the element info instance that contains the offset into the main buffer of the element's location.
  37160. * Beware, this offset may change when you call pack()
  37161. */
  37162. DynamicFloatArray.prototype.allocElement = function () {
  37163. if (this._freeEntries.length === 0) {
  37164. this._growBuffer();
  37165. }
  37166. var el = this._freeEntries.pop();
  37167. this._lastUsed = Math.max(el.offset, this._lastUsed);
  37168. if (el.offset === this._firstFree) {
  37169. if (this._freeEntries.length > 0) {
  37170. this._firstFree = this._freeEntries[this._freeEntries.length - 1].offset;
  37171. }
  37172. else {
  37173. this._firstFree += this._stride;
  37174. }
  37175. }
  37176. return el;
  37177. };
  37178. /**
  37179. * Free the element corresponding to the given element info
  37180. * @param elInfo the element that describe the allocated element
  37181. */
  37182. DynamicFloatArray.prototype.freeElement = function (elInfo) {
  37183. this._firstFree = Math.min(elInfo.offset, this._firstFree);
  37184. this._freeEntries.push(elInfo);
  37185. };
  37186. /**
  37187. * This method will pack all the used elements into a linear sequence and put all the free space at the end.
  37188. * 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().
  37189. * @return the subArray that is the view of the used elements area, you can use it as a source to update a WebGLBuffer
  37190. */
  37191. DynamicFloatArray.prototype.pack = function () {
  37192. // no free slot? no need to pack
  37193. if (this._freeEntries.length === 0) {
  37194. return this.buffer;
  37195. }
  37196. // If the buffer is already packed the last used will always be lower than the first free
  37197. // 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.
  37198. if (this._lastUsed < this._firstFree) {
  37199. var elementsBuffer_1 = this.buffer.subarray(0, this._lastUsed + this._stride);
  37200. return elementsBuffer_1;
  37201. }
  37202. var s = this._stride;
  37203. // 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
  37204. var lastFree = new DynamicFloatArrayElementInfo();
  37205. lastFree.offset = this.totalElementCount * s;
  37206. this._freeEntries.push(lastFree);
  37207. var sortedFree = this._freeEntries.sort(function (a, b) { return a.offset - b.offset; });
  37208. var sortedAll = this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  37209. var firstFreeSlotOffset = sortedFree[0].offset;
  37210. var freeZoneSize = 1;
  37211. var occupiedZoneSize = (this.usedElementCount + 1) * s;
  37212. var prevOffset = sortedFree[0].offset;
  37213. for (var i = 1; i < sortedFree.length; i++) {
  37214. // 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
  37215. if (firstFreeSlotOffset >= occupiedZoneSize) {
  37216. break;
  37217. }
  37218. var curFree = sortedFree[i];
  37219. var curOffset = curFree.offset;
  37220. // Compute the distance between this offset and the previous
  37221. var distance = curOffset - prevOffset;
  37222. // If the distance is the stride size, they are adjacent, it good, move to the next
  37223. if (distance === s) {
  37224. // Free zone is one element bigger
  37225. ++freeZoneSize;
  37226. // as we're about to iterate to the next, the cur becomes the previous...
  37227. prevOffset = curOffset;
  37228. continue;
  37229. }
  37230. // Distance is bigger, which means there's x element between the previous free and this one
  37231. var usedRange = (distance / s) - 1;
  37232. // Two cases the free zone is smaller than the data to move or bigger
  37233. // Copy what can fit in the free zone
  37234. var curMoveOffset = curOffset - s;
  37235. var copyCount = Math.min(freeZoneSize, usedRange);
  37236. for (var j = 0; j < copyCount; j++) {
  37237. var freeI = firstFreeSlotOffset / s;
  37238. var curI = curMoveOffset / s;
  37239. var moveEl = sortedAll[curI];
  37240. this._moveElement(moveEl, firstFreeSlotOffset);
  37241. var replacedEl = sortedAll[freeI];
  37242. // set the offset of the element we replaced with a value that will make it discard at the end of the method
  37243. replacedEl.offset = curMoveOffset;
  37244. // Swap the element we moved and the one it replaced in the sorted array to reflect the action we've made
  37245. sortedAll[freeI] = moveEl;
  37246. sortedAll[curI] = replacedEl;
  37247. curMoveOffset -= s;
  37248. firstFreeSlotOffset += s;
  37249. }
  37250. // Free Zone is smaller or equal so it's no longer a free zone, set the new one to the current location
  37251. if (freeZoneSize <= usedRange) {
  37252. firstFreeSlotOffset = curMoveOffset + s;
  37253. freeZoneSize = 1 + copyCount;
  37254. }
  37255. else {
  37256. freeZoneSize = ((curOffset - firstFreeSlotOffset) / s) + 1;
  37257. }
  37258. // as we're about to iterate to the next, the cur becomes the previous...
  37259. prevOffset = curOffset;
  37260. }
  37261. var elementsBuffer = this.buffer.subarray(0, firstFreeSlotOffset);
  37262. this._lastUsed = firstFreeSlotOffset - s;
  37263. this._firstFree = firstFreeSlotOffset;
  37264. sortedFree.pop(); // Remove the last free because that's the one we added at the start of the method
  37265. this._freeEntries = sortedFree.sort(function (a, b) { return b.offset - a.offset; });
  37266. this._allEntries = sortedAll;
  37267. return elementsBuffer;
  37268. };
  37269. DynamicFloatArray.prototype._moveElement = function (element, destOffset) {
  37270. for (var i = 0; i < this._stride; i++) {
  37271. this.buffer[destOffset + i] = this.buffer[element.offset + i];
  37272. }
  37273. element.offset = destOffset;
  37274. };
  37275. DynamicFloatArray.prototype._growBuffer = function () {
  37276. // Allocate the new buffer with 50% more entries, copy the content of the current one
  37277. var newElCount = Math.floor(this.totalElementCount * 1.5);
  37278. var newBuffer = new Float32Array(newElCount * this._stride);
  37279. newBuffer.set(this.buffer);
  37280. var curCount = this.totalElementCount;
  37281. var addedCount = newElCount - this.totalElementCount;
  37282. for (var i = 0; i < addedCount; i++) {
  37283. var element = new DynamicFloatArrayElementInfo();
  37284. element.offset = (curCount + i) * this.stride;
  37285. this._allEntries.push(element);
  37286. this._freeEntries[addedCount - i - 1] = element;
  37287. }
  37288. this._firstFree = curCount * this.stride;
  37289. this.buffer = newBuffer;
  37290. };
  37291. Object.defineProperty(DynamicFloatArray.prototype, "totalElementCount", {
  37292. /**
  37293. * Get the total count of entries that can fit in the current buffer
  37294. * @returns the elements count
  37295. */
  37296. get: function () {
  37297. return this._allEntries.length;
  37298. },
  37299. enumerable: true,
  37300. configurable: true
  37301. });
  37302. Object.defineProperty(DynamicFloatArray.prototype, "freeElementCount", {
  37303. /**
  37304. * Get the count of free entries that can still be allocated without resizing the buffer
  37305. * @returns the free elements count
  37306. */
  37307. get: function () {
  37308. return this._freeEntries.length;
  37309. },
  37310. enumerable: true,
  37311. configurable: true
  37312. });
  37313. Object.defineProperty(DynamicFloatArray.prototype, "usedElementCount", {
  37314. /**
  37315. * Get the count of allocated elements
  37316. * @returns the allocated elements count
  37317. */
  37318. get: function () {
  37319. return this._allEntries.length - this._freeEntries.length;
  37320. },
  37321. enumerable: true,
  37322. configurable: true
  37323. });
  37324. Object.defineProperty(DynamicFloatArray.prototype, "stride", {
  37325. /**
  37326. * Return the size of one element in float
  37327. * @returns the size in float
  37328. */
  37329. get: function () {
  37330. return this._stride;
  37331. },
  37332. enumerable: true,
  37333. configurable: true
  37334. });
  37335. DynamicFloatArray.prototype.sort = function () {
  37336. var _this = this;
  37337. if (!this.compareValueOffset) {
  37338. throw new Error("The DynamicFloatArray.sort() method needs a valid 'compareValueOffset' property");
  37339. }
  37340. var count = this.usedElementCount;
  37341. // Do we have to (re)create the sort table?
  37342. if (!this._sortTable || this._sortTable.length < count) {
  37343. // 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...
  37344. var newCount = Math.min(this.totalElementCount, count * 2);
  37345. this._sortTable = new Array(newCount);
  37346. }
  37347. if (!this._sortedTable || this._sortedTable.length !== count) {
  37348. this._sortedTable = new Array(count);
  37349. }
  37350. // Because, you know...
  37351. this.pack();
  37352. //let stride = this.stride;
  37353. //for (let i = 0; i < count; i++) {
  37354. // let si = this._sortTable[i];
  37355. // if (!si) {
  37356. // si = new SortInfo();
  37357. // this._sortTable[i] = si;
  37358. // }
  37359. // si.entry = this._allEntries[i];
  37360. // si.compareData = this.buffer[si.entry.offset + this.compareValueOffset];
  37361. // si.swapedOffset = null;
  37362. // this._sortedTable[i] = si;
  37363. //}
  37364. var curOffset = 0;
  37365. var stride = this.stride;
  37366. for (var i = 0; i < count; i++, curOffset += stride) {
  37367. var si = this._sortTable[i];
  37368. if (!si) {
  37369. si = new SortInfo();
  37370. this._sortTable[i] = si;
  37371. }
  37372. si.compareData = this.buffer[curOffset + this.compareValueOffset];
  37373. si.offset = curOffset;
  37374. si.swapedOffset = null;
  37375. this._sortedTable[i] = si;
  37376. }
  37377. // Let's sort the sorted table, we want to keep a track of the original one (that's why we have two buffers)
  37378. if (this.sortingAscending) {
  37379. this._sortedTable.sort(function (a, b) { return a.compareData - b.compareData; });
  37380. }
  37381. else {
  37382. this._sortedTable.sort(function (a, b) { return b.compareData - a.compareData; });
  37383. }
  37384. var swapElements = function (src, dst) {
  37385. for (var i = 0; i < stride; i++) {
  37386. var tps = _this.buffer[dst + i];
  37387. _this.buffer[dst + i] = _this.buffer[src + i];
  37388. _this.buffer[src + i] = tps;
  37389. }
  37390. };
  37391. // 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:
  37392. // 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),
  37393. // and I still want something with a good algorithm complexity.
  37394. // 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,
  37395. // we need sortTable for that, it contains the original layout of SortInfo object, not the sorted one.
  37396. // The best way is to use an extra field in SortInfo, because potentially every element can be replaced.
  37397. // 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
  37398. // until we find a SortInfo object without a swapedOffset which means we got the right location
  37399. // 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
  37400. // than a double allocation of the whole float32Array or a O(n²/2) typical algorithm.
  37401. for (var i = 0; i < count; i++) {
  37402. // Get the element to move
  37403. var sourceSI = this._sortedTable[i];
  37404. var destSI = this._sortTable[i];
  37405. var sourceOff = sourceSI.offset;
  37406. // If the source changed location, find the new one
  37407. if (sourceSI.swapedOffset) {
  37408. // Follow the swapedOffset until there's none, it will mean that curSI contains the new location in its offset member
  37409. var curSI = sourceSI;
  37410. while (curSI.swapedOffset) {
  37411. curSI = this._sortTable[curSI.swapedOffset / stride];
  37412. }
  37413. // Finally get the right location
  37414. sourceOff = curSI.offset;
  37415. }
  37416. // Tag the element being replaced with its new location
  37417. destSI.swapedOffset = sourceOff;
  37418. // Swap elements (only if needed)
  37419. if (sourceOff !== destSI.offset) {
  37420. swapElements(sourceOff, destSI.offset);
  37421. }
  37422. // Update the offset in the corresponding DFAE
  37423. //sourceSI.entry.offset = destSI.entry.offset;
  37424. this._allEntries[sourceSI.offset / stride].offset = destSI.offset;
  37425. }
  37426. this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  37427. return true;
  37428. };
  37429. return DynamicFloatArray;
  37430. })();
  37431. BABYLON.DynamicFloatArray = DynamicFloatArray;
  37432. var SortInfo = (function () {
  37433. function SortInfo() {
  37434. this.compareData = this.offset = this.swapedOffset = null;
  37435. }
  37436. return SortInfo;
  37437. })();
  37438. })(BABYLON || (BABYLON = {}));
  37439. var BABYLON;
  37440. (function (BABYLON) {
  37441. /**
  37442. * This class given information about a given character.
  37443. */
  37444. var CharInfo = (function () {
  37445. function CharInfo() {
  37446. }
  37447. return CharInfo;
  37448. })();
  37449. BABYLON.CharInfo = CharInfo;
  37450. var FontTexture = (function (_super) {
  37451. __extends(FontTexture, _super);
  37452. /**
  37453. * Create a new instance of the FontTexture class
  37454. * @param name the name of the texture
  37455. * @param font the font to use, use the W3C CSS notation
  37456. * @param scene the scene that owns the texture
  37457. * @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
  37458. * @param samplingMode the texture sampling mode
  37459. * @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.
  37460. */
  37461. function FontTexture(name, font, scene, maxCharCount, samplingMode, superSample) {
  37462. if (maxCharCount === void 0) { maxCharCount = 200; }
  37463. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  37464. if (superSample === void 0) { superSample = false; }
  37465. _super.call(this, null, scene, true, false, samplingMode);
  37466. this._charInfos = {};
  37467. this._curCharCount = 0;
  37468. this._lastUpdateCharCount = -1;
  37469. this._usedCounter = 1;
  37470. this.name = name;
  37471. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  37472. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  37473. this._superSample = false;
  37474. if (superSample) {
  37475. var sfont = this.getSuperSampleFont(font);
  37476. if (sfont) {
  37477. this._superSample = true;
  37478. font = sfont;
  37479. }
  37480. }
  37481. // First canvas creation to determine the size of the texture to create
  37482. this._canvas = document.createElement("canvas");
  37483. this._context = this._canvas.getContext("2d");
  37484. this._context.font = font;
  37485. this._context.fillStyle = "white";
  37486. this._cachedFontId = null;
  37487. var res = this.getFontHeight(font);
  37488. this._lineHeightSuper = res.height;
  37489. this._lineHeight = this._superSample ? (this._lineHeightSuper / 2) : this._lineHeightSuper;
  37490. this._offset = res.offset - 1;
  37491. var maxCharWidth = this._context.measureText("W").width;
  37492. this._spaceWidthSuper = this._context.measureText(" ").width;
  37493. this._spaceWidth = this._superSample ? (this._spaceWidthSuper / 2) : this._spaceWidthSuper;
  37494. // This is an approximate size, but should always be able to fit at least the maxCharCount
  37495. var totalEstSurface = this._lineHeightSuper * maxCharWidth * maxCharCount;
  37496. var edge = Math.sqrt(totalEstSurface);
  37497. var textSize = Math.pow(2, Math.ceil(Math.log(edge) / Math.log(2)));
  37498. // Create the texture that will store the font characters
  37499. this._texture = scene.getEngine().createDynamicTexture(textSize, textSize, false, samplingMode);
  37500. var textureSize = this.getSize();
  37501. this.hasAlpha = true;
  37502. // Recreate a new canvas with the final size: the one matching the texture (resizing the previous one doesn't work as one would expect...)
  37503. this._canvas = document.createElement("canvas");
  37504. this._canvas.width = textureSize.width;
  37505. this._canvas.height = textureSize.height;
  37506. this._context = this._canvas.getContext("2d");
  37507. this._context.textBaseline = "top";
  37508. this._context.font = font;
  37509. this._context.fillStyle = "white";
  37510. this._context.imageSmoothingEnabled = false;
  37511. this._currentFreePosition = BABYLON.Vector2.Zero();
  37512. // Add the basic ASCII based characters
  37513. for (var i = 0x20; i < 0x7F; i++) {
  37514. var c = String.fromCharCode(i);
  37515. this.getChar(c);
  37516. }
  37517. this.update();
  37518. }
  37519. Object.defineProperty(FontTexture.prototype, "isSuperSampled", {
  37520. get: function () {
  37521. return this._superSample;
  37522. },
  37523. enumerable: true,
  37524. configurable: true
  37525. });
  37526. Object.defineProperty(FontTexture.prototype, "spaceWidth", {
  37527. get: function () {
  37528. return this._spaceWidth;
  37529. },
  37530. enumerable: true,
  37531. configurable: true
  37532. });
  37533. Object.defineProperty(FontTexture.prototype, "lineHeight", {
  37534. get: function () {
  37535. return this._lineHeight;
  37536. },
  37537. enumerable: true,
  37538. configurable: true
  37539. });
  37540. FontTexture.GetCachedFontTexture = function (scene, fontName, supersample) {
  37541. if (supersample === void 0) { supersample = false; }
  37542. var s = scene;
  37543. if (!s.__fontTextureCache__) {
  37544. s.__fontTextureCache__ = new BABYLON.StringDictionary();
  37545. }
  37546. var dic = s.__fontTextureCache__;
  37547. var lfn = fontName.toLocaleLowerCase() + (supersample ? "_+SS" : "_-SS");
  37548. var ft = dic.get(lfn);
  37549. if (ft) {
  37550. ++ft._usedCounter;
  37551. return ft;
  37552. }
  37553. ft = new FontTexture(null, fontName, scene, supersample ? 100 : 200, BABYLON.Texture.BILINEAR_SAMPLINGMODE, supersample);
  37554. ft._cachedFontId = lfn;
  37555. dic.add(lfn, ft);
  37556. return ft;
  37557. };
  37558. FontTexture.ReleaseCachedFontTexture = function (scene, fontName, supersample) {
  37559. if (supersample === void 0) { supersample = false; }
  37560. var s = scene;
  37561. var dic = s.__fontTextureCache__;
  37562. if (!dic) {
  37563. return;
  37564. }
  37565. var lfn = fontName.toLocaleLowerCase() + (supersample ? "_+SS" : "_-SS");
  37566. var font = dic.get(lfn);
  37567. if (--font._usedCounter === 0) {
  37568. dic.remove(lfn);
  37569. font.dispose();
  37570. }
  37571. };
  37572. /**
  37573. * Make sure the given char is present in the font map.
  37574. * @param char the character to get or add
  37575. * @return the CharInfo instance corresponding to the given character
  37576. */
  37577. FontTexture.prototype.getChar = function (char) {
  37578. if (char.length !== 1) {
  37579. return null;
  37580. }
  37581. var info = this._charInfos[char];
  37582. if (info) {
  37583. return info;
  37584. }
  37585. info = new CharInfo();
  37586. var measure = this._context.measureText(char);
  37587. var textureSize = this.getSize();
  37588. // we reached the end of the current line?
  37589. var width = Math.round(measure.width);
  37590. var xMargin = 1 + Math.ceil(this._lineHeightSuper / 15); // Right now this empiric formula seems to work...
  37591. var yMargin = xMargin;
  37592. if (this._currentFreePosition.x + width + xMargin > textureSize.width) {
  37593. this._currentFreePosition.x = 0;
  37594. this._currentFreePosition.y += this._lineHeightSuper + yMargin;
  37595. // No more room?
  37596. if (this._currentFreePosition.y > textureSize.height) {
  37597. return this.getChar("!");
  37598. }
  37599. }
  37600. // Draw the character in the texture
  37601. this._context.fillText(char, this._currentFreePosition.x, this._currentFreePosition.y - this._offset);
  37602. // Fill the CharInfo object
  37603. info.topLeftUV = new BABYLON.Vector2(this._currentFreePosition.x / textureSize.width, this._currentFreePosition.y / textureSize.height);
  37604. info.bottomRightUV = new BABYLON.Vector2((this._currentFreePosition.x + width) / textureSize.width, info.topLeftUV.y + ((this._lineHeightSuper + 2) / textureSize.height));
  37605. info.charWidth = this._superSample ? (width / 2) : width;
  37606. // Add the info structure
  37607. this._charInfos[char] = info;
  37608. this._curCharCount++;
  37609. // Set the next position
  37610. this._currentFreePosition.x += width + xMargin;
  37611. return info;
  37612. };
  37613. FontTexture.prototype.measureText = function (text, tabulationSize) {
  37614. if (tabulationSize === void 0) { tabulationSize = 4; }
  37615. var maxWidth = 0;
  37616. var curWidth = 0;
  37617. var lineCount = 1;
  37618. var charxpos = 0;
  37619. // Parse each char of the string
  37620. for (var _i = 0; _i < text.length; _i++) {
  37621. var char = text[_i];
  37622. // Next line feed?
  37623. if (char === "\n") {
  37624. maxWidth = Math.max(maxWidth, curWidth);
  37625. charxpos = 0;
  37626. curWidth = 0;
  37627. ++lineCount;
  37628. continue;
  37629. }
  37630. // Tabulation ?
  37631. if (char === "\t") {
  37632. var nextPos = charxpos + tabulationSize;
  37633. nextPos = nextPos - (nextPos % tabulationSize);
  37634. curWidth += (nextPos - charxpos) * this.spaceWidth;
  37635. charxpos = nextPos;
  37636. continue;
  37637. }
  37638. if (char < " ") {
  37639. continue;
  37640. }
  37641. curWidth += this.getChar(char).charWidth;
  37642. ++charxpos;
  37643. }
  37644. maxWidth = Math.max(maxWidth, curWidth);
  37645. return new BABYLON.Size(maxWidth, lineCount * this.lineHeight);
  37646. };
  37647. FontTexture.prototype.getSuperSampleFont = function (font) {
  37648. // Eternal thank to http://stackoverflow.com/a/10136041/802124
  37649. 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*$/;
  37650. var res = font.toLocaleLowerCase().match(regex);
  37651. if (res == null) {
  37652. return null;
  37653. }
  37654. var size = parseInt(res[4]);
  37655. res[4] = (size * 2).toString() + (res[4].match(/\D+/) || []).pop();
  37656. var newFont = "";
  37657. for (var j = 1; j < res.length; j++) {
  37658. if (res[j] != null) {
  37659. newFont += res[j] + " ";
  37660. }
  37661. }
  37662. return newFont;
  37663. };
  37664. // More info here: https://videlais.com/2014/03/16/the-many-and-varied-problems-with-measuring-font-height-for-html5-canvas/
  37665. FontTexture.prototype.getFontHeight = function (font) {
  37666. var fontDraw = document.createElement("canvas");
  37667. var ctx = fontDraw.getContext('2d');
  37668. ctx.fillRect(0, 0, fontDraw.width, fontDraw.height);
  37669. ctx.textBaseline = 'top';
  37670. ctx.fillStyle = 'white';
  37671. ctx.font = font;
  37672. ctx.fillText('jH|', 0, 0);
  37673. var pixels = ctx.getImageData(0, 0, fontDraw.width, fontDraw.height).data;
  37674. var start = -1;
  37675. var end = -1;
  37676. for (var row = 0; row < fontDraw.height; row++) {
  37677. for (var column = 0; column < fontDraw.width; column++) {
  37678. var index = (row * fontDraw.width + column) * 4;
  37679. if (pixels[index] === 0) {
  37680. if (column === fontDraw.width - 1 && start !== -1) {
  37681. end = row;
  37682. row = fontDraw.height;
  37683. break;
  37684. }
  37685. continue;
  37686. }
  37687. else {
  37688. if (start === -1) {
  37689. start = row;
  37690. }
  37691. break;
  37692. }
  37693. }
  37694. }
  37695. return { height: (end - start) + 1, offset: start - 1 };
  37696. };
  37697. Object.defineProperty(FontTexture.prototype, "canRescale", {
  37698. get: function () {
  37699. return false;
  37700. },
  37701. enumerable: true,
  37702. configurable: true
  37703. });
  37704. FontTexture.prototype.getContext = function () {
  37705. return this._context;
  37706. };
  37707. /**
  37708. * Call this method when you've call getChar() at least one time, this will update the texture if needed.
  37709. * Don't be afraid to call it, if no new character was added, this method simply does nothing.
  37710. */
  37711. FontTexture.prototype.update = function () {
  37712. // Update only if there's new char added since the previous update
  37713. if (this._lastUpdateCharCount < this._curCharCount) {
  37714. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, false, true);
  37715. this._lastUpdateCharCount = this._curCharCount;
  37716. }
  37717. };
  37718. // cloning should be prohibited, there's no point to duplicate this texture at all
  37719. FontTexture.prototype.clone = function () {
  37720. return null;
  37721. };
  37722. /**
  37723. * For FontTexture retrieved using GetCachedFontTexture, use this method when you transfer this object's lifetime to another party in order to share this resource.
  37724. * When the other party is done with this object, decCachedFontTextureCounter must be called.
  37725. */
  37726. FontTexture.prototype.incCachedFontTextureCounter = function () {
  37727. ++this._usedCounter;
  37728. };
  37729. /**
  37730. * Use this method only in conjunction with incCachedFontTextureCounter, call it when you no longer need to use this shared resource.
  37731. */
  37732. FontTexture.prototype.decCachedFontTextureCounter = function () {
  37733. var s = this.getScene();
  37734. var dic = s.__fontTextureCache__;
  37735. if (!dic) {
  37736. return;
  37737. }
  37738. if (--this._usedCounter === 0) {
  37739. dic.remove(this._cachedFontId);
  37740. this.dispose();
  37741. }
  37742. };
  37743. return FontTexture;
  37744. })(BABYLON.Texture);
  37745. BABYLON.FontTexture = FontTexture;
  37746. })(BABYLON || (BABYLON = {}));
  37747. var BABYLON;
  37748. (function (BABYLON) {
  37749. var MapTexture = (function (_super) {
  37750. __extends(MapTexture, _super);
  37751. function MapTexture(name, scene, size, samplingMode, useMipMap) {
  37752. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  37753. if (useMipMap === void 0) { useMipMap = false; }
  37754. _super.call(this, null, scene, !useMipMap, false, samplingMode);
  37755. this.name = name;
  37756. this._size = size;
  37757. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  37758. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  37759. // Create the rectPackMap that will allocate portion of the texture
  37760. this._rectPackingMap = new BABYLON.RectPackingMap(new BABYLON.Size(size.width, size.height));
  37761. // Create the texture that will store the content
  37762. this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: !this.noMipmap, type: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT });
  37763. }
  37764. /**
  37765. * Allocate a rectangle of a given size in the texture map
  37766. * @param size the size of the rectangle to allocation
  37767. * @return the PackedRect instance corresponding to the allocated rect or null is there was not enough space to allocate it.
  37768. */
  37769. MapTexture.prototype.allocateRect = function (size) {
  37770. return this._rectPackingMap.addRect(size);
  37771. };
  37772. /**
  37773. * Free a given rectangle from the texture map
  37774. * @param rectInfo the instance corresponding to the rect to free.
  37775. */
  37776. MapTexture.prototype.freeRect = function (rectInfo) {
  37777. if (rectInfo) {
  37778. rectInfo.freeContent();
  37779. }
  37780. };
  37781. Object.defineProperty(MapTexture.prototype, "freeSpace", {
  37782. /**
  37783. * Return the available space in the range of [O;1]. 0 being not space left at all, 1 being an empty texture map.
  37784. * This is the cumulated space, not the biggest available surface. Due to fragmentation you may not allocate a rect corresponding to this surface.
  37785. * @returns {}
  37786. */
  37787. get: function () {
  37788. return this._rectPackingMap.freeSpace;
  37789. },
  37790. enumerable: true,
  37791. configurable: true
  37792. });
  37793. /**
  37794. * Bind the texture to the rendering engine to render in the zone of a given rectangle.
  37795. * Use this method when you want to render into the texture map with a clipspace set to the location and size of the given rect.
  37796. * Don't forget to call unbindTexture when you're done rendering
  37797. * @param rect the zone to render to
  37798. * @param clear true to clear the portion's color/depth data
  37799. */
  37800. MapTexture.prototype.bindTextureForRect = function (rect, clear) {
  37801. return this.bindTextureForPosSize(rect.pos, rect.contentSize, clear);
  37802. };
  37803. /**
  37804. * Bind the texture to the rendering engine to render in the zone of the given size at the given position.
  37805. * 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.
  37806. * Don't forget to call unbindTexture when you're done rendering
  37807. * @param pos the position into the texture
  37808. * @param size the portion to fit the clip space to
  37809. * @param clear true to clear the portion's color/depth data
  37810. */
  37811. MapTexture.prototype.bindTextureForPosSize = function (pos, size, clear) {
  37812. var engine = this.getScene().getEngine();
  37813. engine.bindFramebuffer(this._texture);
  37814. this._replacedViewport = engine.setDirectViewport(pos.x, pos.y, size.width, size.height);
  37815. if (clear) {
  37816. // We only want to clear the part of the texture we're binding to, only the scissor can help us to achieve that
  37817. engine.scissorClear(pos.x, pos.y, size.width, size.height, new BABYLON.Color4(0, 0, 0, 0));
  37818. }
  37819. };
  37820. /**
  37821. * Unbind the texture map from the rendering engine.
  37822. * Call this method when you're done rendering. A previous call to bindTextureForRect has to be made.
  37823. * @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.
  37824. */
  37825. MapTexture.prototype.unbindTexture = function (dumpForDebug) {
  37826. // Dump ?
  37827. if (dumpForDebug) {
  37828. BABYLON.Tools.DumpFramebuffer(this._size.width, this._size.height, this.getScene().getEngine());
  37829. }
  37830. var engine = this.getScene().getEngine();
  37831. if (this._replacedViewport) {
  37832. engine.setViewport(this._replacedViewport);
  37833. this._replacedViewport = null;
  37834. }
  37835. engine.unBindFramebuffer(this._texture);
  37836. };
  37837. Object.defineProperty(MapTexture.prototype, "canRescale", {
  37838. get: function () {
  37839. return false;
  37840. },
  37841. enumerable: true,
  37842. configurable: true
  37843. });
  37844. // Note, I don't know what behavior this method should have: clone the underlying texture/rectPackingMap or just reference them?
  37845. // Anyway, there's not much point to use this method for this kind of texture I guess
  37846. MapTexture.prototype.clone = function () {
  37847. return null;
  37848. };
  37849. return MapTexture;
  37850. })(BABYLON.Texture);
  37851. BABYLON.MapTexture = MapTexture;
  37852. })(BABYLON || (BABYLON = {}));
  37853. var BABYLON;
  37854. (function (BABYLON) {
  37855. /**
  37856. * Stores 2D Bounding Information.
  37857. * This class handles a circle area and a bounding rectangle one.
  37858. */
  37859. var BoundingInfo2D = (function () {
  37860. function BoundingInfo2D() {
  37861. this.radius = 0;
  37862. this.center = BABYLON.Vector2.Zero();
  37863. this.extent = BABYLON.Vector2.Zero();
  37864. }
  37865. /**
  37866. * Create a BoundingInfo2D object from a given size
  37867. * @param size the size that will be used to set the extend, radius will be computed from it.
  37868. */
  37869. BoundingInfo2D.CreateFromSize = function (size) {
  37870. var r = new BoundingInfo2D();
  37871. BoundingInfo2D.CreateFromSizeToRef(size, r);
  37872. return r;
  37873. };
  37874. /**
  37875. * Create a BoundingInfo2D object from a given radius
  37876. * @param radius the radius to use, the extent will be computed from it.
  37877. */
  37878. BoundingInfo2D.CreateFromRadius = function (radius) {
  37879. var r = new BoundingInfo2D();
  37880. BoundingInfo2D.CreateFromRadiusToRef(radius, r);
  37881. return r;
  37882. };
  37883. /**
  37884. * Create a BoundingInfo2D object from a list of points.
  37885. * The resulted object will be the smallest bounding area that includes all the given points.
  37886. * @param points an array of points to compute the bounding object from.
  37887. */
  37888. BoundingInfo2D.CreateFromPoints = function (points) {
  37889. var r = new BoundingInfo2D();
  37890. BoundingInfo2D.CreateFromPointsToRef(points, r);
  37891. return r;
  37892. };
  37893. /**
  37894. * Update a BoundingInfo2D object using the given Size as input
  37895. * @param size the bounding data will be computed from this size.
  37896. * @param b must be a valid/allocated object, it will contain the result of the operation
  37897. */
  37898. BoundingInfo2D.CreateFromSizeToRef = function (size, b) {
  37899. if (!size) {
  37900. size = BABYLON.Size.Zero();
  37901. }
  37902. b.center.x = +size.width / 2;
  37903. b.center.y = +size.height / 2;
  37904. b.extent.x = b.center.x;
  37905. b.extent.y = b.center.y;
  37906. b.radius = b.extent.length();
  37907. };
  37908. /**
  37909. * Update a BoundingInfo2D object using the given radius as input
  37910. * @param radius the bounding data will be computed from this radius
  37911. * @param b must be a valid/allocated object, it will contain the result of the operation
  37912. */
  37913. BoundingInfo2D.CreateFromRadiusToRef = function (radius, b) {
  37914. b.center.x = b.center.y = 0;
  37915. var r = +radius;
  37916. b.extent.x = r;
  37917. b.extent.y = r;
  37918. b.radius = r;
  37919. };
  37920. /**
  37921. * Update a BoundingInfo2D object using the given points array as input
  37922. * @param points the point array to use to update the bounding data
  37923. * @param b must be a valid/allocated object, it will contain the result of the operation
  37924. */
  37925. BoundingInfo2D.CreateFromPointsToRef = function (points, b) {
  37926. var xmin = Number.MAX_VALUE, ymin = Number.MAX_VALUE, xmax = Number.MIN_VALUE, ymax = Number.MIN_VALUE;
  37927. for (var _i = 0; _i < points.length; _i++) {
  37928. var p = points[_i];
  37929. xmin = Math.min(p.x, xmin);
  37930. xmax = Math.max(p.x, xmax);
  37931. ymin = Math.min(p.y, ymin);
  37932. ymax = Math.max(p.y, ymax);
  37933. }
  37934. BoundingInfo2D.CreateFromMinMaxToRef(xmin, xmax, ymin, ymax, b);
  37935. };
  37936. /**
  37937. * Update a BoundingInfo2D object using the given min/max values as input
  37938. * @param xmin the smallest x coordinate
  37939. * @param xmax the biggest x coordinate
  37940. * @param ymin the smallest y coordinate
  37941. * @param ymax the buggest y coordinate
  37942. * @param b must be a valid/allocated object, it will contain the result of the operation
  37943. */
  37944. BoundingInfo2D.CreateFromMinMaxToRef = function (xmin, xmax, ymin, ymax, b) {
  37945. var w = xmax - xmin;
  37946. var h = ymax - ymin;
  37947. b.center = new BABYLON.Vector2(xmin + w / 2, ymin + h / 2);
  37948. b.extent = new BABYLON.Vector2(xmax - b.center.x, ymax - b.center.y);
  37949. b.radius = b.extent.length();
  37950. };
  37951. /**
  37952. * Duplicate this instance and return a new one
  37953. * @return the duplicated instance
  37954. */
  37955. BoundingInfo2D.prototype.clone = function () {
  37956. var r = new BoundingInfo2D();
  37957. r.center = this.center.clone();
  37958. r.radius = this.radius;
  37959. r.extent = this.extent.clone();
  37960. return r;
  37961. };
  37962. BoundingInfo2D.prototype.clear = function () {
  37963. this.center.copyFromFloats(0, 0);
  37964. this.radius = 0;
  37965. this.extent.copyFromFloats(0, 0);
  37966. };
  37967. BoundingInfo2D.prototype.copyFrom = function (src) {
  37968. this.center.copyFrom(src.center);
  37969. this.radius = src.radius;
  37970. this.extent.copyFrom(src.extent);
  37971. };
  37972. /**
  37973. * return the max extend of the bounding info
  37974. */
  37975. BoundingInfo2D.prototype.max = function () {
  37976. var r = BABYLON.Vector2.Zero();
  37977. this.maxToRef(r);
  37978. return r;
  37979. };
  37980. /**
  37981. * Update a vector2 with the max extend of the bounding info
  37982. * @param result must be a valid/allocated vector2 that will contain the result of the operation
  37983. */
  37984. BoundingInfo2D.prototype.maxToRef = function (result) {
  37985. result.x = this.center.x + this.extent.x;
  37986. result.y = this.center.y + this.extent.y;
  37987. };
  37988. /**
  37989. * Apply a transformation matrix to this BoundingInfo2D and return a new instance containing the result
  37990. * @param matrix the transformation matrix to apply
  37991. * @return the new instance containing the result of the transformation applied on this BoundingInfo2D
  37992. */
  37993. BoundingInfo2D.prototype.transform = function (matrix) {
  37994. var r = new BoundingInfo2D();
  37995. this.transformToRef(matrix, r);
  37996. return r;
  37997. };
  37998. /**
  37999. * Compute the union of this BoundingInfo2D with a given one, returns a new BoundingInfo2D as a result
  38000. * @param other the second BoundingInfo2D to compute the union with this one
  38001. * @return a new instance containing the result of the union
  38002. */
  38003. BoundingInfo2D.prototype.union = function (other) {
  38004. var r = new BoundingInfo2D();
  38005. this.unionToRef(other, r);
  38006. return r;
  38007. };
  38008. /**
  38009. * Transform this BoundingInfo2D with a given matrix and store the result in an existing BoundingInfo2D instance.
  38010. * 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.
  38011. * @param matrix The matrix to use to compute the transformation
  38012. * @param result A VALID (i.e. allocated) BoundingInfo2D object where the result will be stored
  38013. */
  38014. BoundingInfo2D.prototype.transformToRef = function (matrix, result) {
  38015. // Construct a bounding box based on the extent values
  38016. var p = BoundingInfo2D._transform;
  38017. p[0].x = this.center.x + this.extent.x;
  38018. p[0].y = this.center.y + this.extent.y;
  38019. p[1].x = this.center.x + this.extent.x;
  38020. p[1].y = this.center.y - this.extent.y;
  38021. p[2].x = this.center.x - this.extent.x;
  38022. p[2].y = this.center.y - this.extent.y;
  38023. p[3].x = this.center.x - this.extent.x;
  38024. p[3].y = this.center.y + this.extent.y;
  38025. // Transform the four points of the bounding box with the matrix
  38026. for (var i = 0; i < 4; i++) {
  38027. BABYLON.Vector2.TransformToRef(p[i], matrix, p[i]);
  38028. }
  38029. BoundingInfo2D.CreateFromPointsToRef(p, result);
  38030. };
  38031. /**
  38032. * Compute the union of this BoundingInfo2D with another one and store the result in a third valid BoundingInfo2D object
  38033. * 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.
  38034. * @param other the second object used to compute the union
  38035. * @param result a VALID BoundingInfo2D instance (i.e. allocated) where the result will be stored
  38036. */
  38037. BoundingInfo2D.prototype.unionToRef = function (other, result) {
  38038. var xmax = Math.max(this.center.x + this.extent.x, other.center.x + other.extent.x);
  38039. var ymax = Math.max(this.center.y + this.extent.y, other.center.y + other.extent.y);
  38040. var xmin = Math.min(this.center.x - this.extent.x, other.center.x - other.extent.x);
  38041. var ymin = Math.min(this.center.y - this.extent.y, other.center.y - other.extent.y);
  38042. BoundingInfo2D.CreateFromMinMaxToRef(xmin, xmax, ymin, ymax, result);
  38043. };
  38044. /**
  38045. * Check if the given point is inside the BoundingInfo.
  38046. * The test is first made on the radius, then inside the rectangle described by the extent
  38047. * @param pickPosition the position to test
  38048. * @return true if the point is inside, false otherwise
  38049. */
  38050. BoundingInfo2D.prototype.doesIntersect = function (pickPosition) {
  38051. // is it inside the radius?
  38052. var pickLocal = pickPosition.subtract(this.center);
  38053. if (pickLocal.lengthSquared() <= (this.radius * this.radius)) {
  38054. // is it inside the rectangle?
  38055. return ((Math.abs(pickLocal.x) <= this.extent.x) && (Math.abs(pickLocal.y) <= this.extent.y));
  38056. }
  38057. return false;
  38058. };
  38059. BoundingInfo2D._transform = new Array(BABYLON.Vector2.Zero(), BABYLON.Vector2.Zero(), BABYLON.Vector2.Zero(), BABYLON.Vector2.Zero());
  38060. return BoundingInfo2D;
  38061. })();
  38062. BABYLON.BoundingInfo2D = BoundingInfo2D;
  38063. })(BABYLON || (BABYLON = {}));
  38064. var BABYLON;
  38065. (function (BABYLON) {
  38066. /**
  38067. * Base class implementing the ILocable interface.
  38068. * The particularity of this class is to call the protected onLock() method when the instance is about to be locked for good.
  38069. */
  38070. var LockableBase = (function () {
  38071. function LockableBase() {
  38072. }
  38073. LockableBase.prototype.isLocked = function () {
  38074. return this._isLocked;
  38075. };
  38076. LockableBase.prototype.lock = function () {
  38077. if (this._isLocked) {
  38078. return true;
  38079. }
  38080. this.onLock();
  38081. this._isLocked = true;
  38082. return false;
  38083. };
  38084. /**
  38085. * Protected handler that will be called when the instance is about to be locked.
  38086. */
  38087. LockableBase.prototype.onLock = function () {
  38088. };
  38089. return LockableBase;
  38090. })();
  38091. BABYLON.LockableBase = LockableBase;
  38092. var SolidColorBrush2D = (function (_super) {
  38093. __extends(SolidColorBrush2D, _super);
  38094. function SolidColorBrush2D(color, lock) {
  38095. if (lock === void 0) { lock = false; }
  38096. _super.call(this);
  38097. this._color = color;
  38098. if (lock) {
  38099. {
  38100. this.lock();
  38101. }
  38102. }
  38103. }
  38104. /**
  38105. * Return true if the brush is transparent, false if it's totally opaque
  38106. */
  38107. SolidColorBrush2D.prototype.isTransparent = function () {
  38108. return this._color && this._color.a < 1.0;
  38109. };
  38110. Object.defineProperty(SolidColorBrush2D.prototype, "color", {
  38111. /**
  38112. * The color used by this instance to render
  38113. * @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.
  38114. */
  38115. get: function () {
  38116. return this._color;
  38117. },
  38118. set: function (value) {
  38119. if (this.isLocked()) {
  38120. return;
  38121. }
  38122. this._color = value;
  38123. },
  38124. enumerable: true,
  38125. configurable: true
  38126. });
  38127. /**
  38128. * Return a unique identifier of the instance, which is simply the hexadecimal representation (CSS Style) of the solid color.
  38129. */
  38130. SolidColorBrush2D.prototype.toString = function () {
  38131. return this._color.toHexString();
  38132. };
  38133. SolidColorBrush2D = __decorate([
  38134. BABYLON.className("SolidColorBrush2D")
  38135. ], SolidColorBrush2D);
  38136. return SolidColorBrush2D;
  38137. })(LockableBase);
  38138. BABYLON.SolidColorBrush2D = SolidColorBrush2D;
  38139. var GradientColorBrush2D = (function (_super) {
  38140. __extends(GradientColorBrush2D, _super);
  38141. function GradientColorBrush2D(color1, color2, translation, rotation, scale, lock) {
  38142. if (translation === void 0) { translation = BABYLON.Vector2.Zero(); }
  38143. if (rotation === void 0) { rotation = 0; }
  38144. if (scale === void 0) { scale = 1; }
  38145. if (lock === void 0) { lock = false; }
  38146. _super.call(this);
  38147. this._color1 = color1;
  38148. this._color2 = color2;
  38149. this._translation = translation;
  38150. this._rotation = rotation;
  38151. this._scale = scale;
  38152. if (lock) {
  38153. this.lock();
  38154. }
  38155. }
  38156. /**
  38157. * Return true if the brush is transparent, false if it's totally opaque
  38158. */
  38159. GradientColorBrush2D.prototype.isTransparent = function () {
  38160. return (this._color1 && this._color1.a < 1.0) || (this._color2 && this._color2.a < 1.0);
  38161. };
  38162. Object.defineProperty(GradientColorBrush2D.prototype, "color1", {
  38163. /**
  38164. * First color, the blend will start from this color
  38165. */
  38166. get: function () {
  38167. return this._color1;
  38168. },
  38169. set: function (value) {
  38170. if (this.isLocked()) {
  38171. return;
  38172. }
  38173. this._color1 = value;
  38174. },
  38175. enumerable: true,
  38176. configurable: true
  38177. });
  38178. Object.defineProperty(GradientColorBrush2D.prototype, "color2", {
  38179. /**
  38180. * Second color, the blend will end to this color
  38181. */
  38182. get: function () {
  38183. return this._color2;
  38184. },
  38185. set: function (value) {
  38186. if (this.isLocked()) {
  38187. return;
  38188. }
  38189. this._color2 = value;
  38190. },
  38191. enumerable: true,
  38192. configurable: true
  38193. });
  38194. Object.defineProperty(GradientColorBrush2D.prototype, "translation", {
  38195. /**
  38196. * Translation vector to apply on the blend
  38197. * Default is [0;0]
  38198. */
  38199. get: function () {
  38200. return this._translation;
  38201. },
  38202. set: function (value) {
  38203. if (this.isLocked()) {
  38204. return;
  38205. }
  38206. this._translation = value;
  38207. },
  38208. enumerable: true,
  38209. configurable: true
  38210. });
  38211. Object.defineProperty(GradientColorBrush2D.prototype, "rotation", {
  38212. /**
  38213. * Rotation in radian to apply to the brush
  38214. * Default direction of the brush is vertical, you can change this using this property.
  38215. * Default is 0.
  38216. */
  38217. get: function () {
  38218. return this._rotation;
  38219. },
  38220. set: function (value) {
  38221. if (this.isLocked()) {
  38222. return;
  38223. }
  38224. this._rotation = value;
  38225. },
  38226. enumerable: true,
  38227. configurable: true
  38228. });
  38229. Object.defineProperty(GradientColorBrush2D.prototype, "scale", {
  38230. /**
  38231. * Scale factor to apply to the gradient.
  38232. * Default is 1: no scale.
  38233. */
  38234. get: function () {
  38235. return this._scale;
  38236. },
  38237. set: function (value) {
  38238. if (this.isLocked()) {
  38239. return;
  38240. }
  38241. this._scale = value;
  38242. },
  38243. enumerable: true,
  38244. configurable: true
  38245. });
  38246. /**
  38247. * Return a string describing the brush
  38248. */
  38249. GradientColorBrush2D.prototype.toString = function () {
  38250. return "C1:" + this._color1 + ";C2:" + this._color2 + ";T:" + this._translation.toString() + ";R:" + this._rotation + ";S:" + this._scale + ";";
  38251. };
  38252. /**
  38253. * Build a unique key string for the given parameters
  38254. */
  38255. GradientColorBrush2D.BuildKey = function (color1, color2, translation, rotation, scale) {
  38256. return "C1:" + color1 + ";C2:" + color2 + ";T:" + translation.toString() + ";R:" + rotation + ";S:" + scale + ";";
  38257. };
  38258. GradientColorBrush2D = __decorate([
  38259. BABYLON.className("GradientColorBrush2D")
  38260. ], GradientColorBrush2D);
  38261. return GradientColorBrush2D;
  38262. })(LockableBase);
  38263. BABYLON.GradientColorBrush2D = GradientColorBrush2D;
  38264. })(BABYLON || (BABYLON = {}));
  38265. var BABYLON;
  38266. (function (BABYLON) {
  38267. var Prim2DClassInfo = (function () {
  38268. function Prim2DClassInfo() {
  38269. }
  38270. return Prim2DClassInfo;
  38271. })();
  38272. BABYLON.Prim2DClassInfo = Prim2DClassInfo;
  38273. var Prim2DPropInfo = (function () {
  38274. function Prim2DPropInfo() {
  38275. }
  38276. Prim2DPropInfo.PROPKIND_MODEL = 1;
  38277. Prim2DPropInfo.PROPKIND_INSTANCE = 2;
  38278. Prim2DPropInfo.PROPKIND_DYNAMIC = 3;
  38279. return Prim2DPropInfo;
  38280. })();
  38281. BABYLON.Prim2DPropInfo = Prim2DPropInfo;
  38282. /**
  38283. * Custom type of the propertyChanged observable
  38284. */
  38285. var PropertyChangedInfo = (function () {
  38286. function PropertyChangedInfo() {
  38287. }
  38288. return PropertyChangedInfo;
  38289. })();
  38290. BABYLON.PropertyChangedInfo = PropertyChangedInfo;
  38291. var ClassTreeInfo = (function () {
  38292. function ClassTreeInfo(baseClass, type, classContentFactory) {
  38293. this._baseClass = baseClass;
  38294. this._type = type;
  38295. this._subClasses = new Array();
  38296. this._levelContent = new BABYLON.StringDictionary();
  38297. this._classContentFactory = classContentFactory;
  38298. }
  38299. Object.defineProperty(ClassTreeInfo.prototype, "classContent", {
  38300. get: function () {
  38301. if (!this._classContent) {
  38302. this._classContent = this._classContentFactory(this._baseClass ? this._baseClass.classContent : null);
  38303. }
  38304. return this._classContent;
  38305. },
  38306. enumerable: true,
  38307. configurable: true
  38308. });
  38309. Object.defineProperty(ClassTreeInfo.prototype, "type", {
  38310. get: function () {
  38311. return this._type;
  38312. },
  38313. enumerable: true,
  38314. configurable: true
  38315. });
  38316. Object.defineProperty(ClassTreeInfo.prototype, "levelContent", {
  38317. get: function () {
  38318. return this._levelContent;
  38319. },
  38320. enumerable: true,
  38321. configurable: true
  38322. });
  38323. Object.defineProperty(ClassTreeInfo.prototype, "fullContent", {
  38324. get: function () {
  38325. if (!this._fullContent) {
  38326. var dic = new BABYLON.StringDictionary();
  38327. var curLevel = this;
  38328. while (curLevel) {
  38329. curLevel.levelContent.forEach(function (k, v) { return dic.add(k, v); });
  38330. curLevel = curLevel._baseClass;
  38331. }
  38332. this._fullContent = dic;
  38333. }
  38334. return this._fullContent;
  38335. },
  38336. enumerable: true,
  38337. configurable: true
  38338. });
  38339. ClassTreeInfo.prototype.getLevelOf = function (type) {
  38340. // Are we already there?
  38341. if (type === this._type) {
  38342. return this;
  38343. }
  38344. var baseProto = Object.getPrototypeOf(type);
  38345. var curProtoContent = this.getOrAddType(Object.getPrototypeOf(baseProto), baseProto);
  38346. if (!curProtoContent) {
  38347. this.getLevelOf(baseProto);
  38348. }
  38349. return this.getOrAddType(baseProto, type);
  38350. };
  38351. ClassTreeInfo.prototype.getOrAddType = function (baseType, type) {
  38352. // Are we at the level corresponding to the baseType?
  38353. // If so, get or add the level we're looking for
  38354. if (baseType === this._type) {
  38355. for (var _i = 0, _a = this._subClasses; _i < _a.length; _i++) {
  38356. var subType = _a[_i];
  38357. if (subType.type === type) {
  38358. return subType.node;
  38359. }
  38360. }
  38361. var node = new ClassTreeInfo(this, type, this._classContentFactory);
  38362. var info = { type: type, node: node };
  38363. this._subClasses.push(info);
  38364. return info.node;
  38365. }
  38366. // Recurse down to keep looking for the node corresponding to the baseTypeName
  38367. for (var _b = 0, _c = this._subClasses; _b < _c.length; _b++) {
  38368. var subType = _c[_b];
  38369. var info = subType.node.getOrAddType(baseType, type);
  38370. if (info) {
  38371. return info;
  38372. }
  38373. }
  38374. return null;
  38375. };
  38376. ClassTreeInfo.get = function (type) {
  38377. var dic = type["__classTreeInfo"];
  38378. if (!dic) {
  38379. return null;
  38380. }
  38381. return dic.getLevelOf(type);
  38382. };
  38383. ClassTreeInfo.getOrRegister = function (type, classContentFactory) {
  38384. var dic = type["__classTreeInfo"];
  38385. if (!dic) {
  38386. dic = new ClassTreeInfo(null, type, classContentFactory);
  38387. type["__classTreeInfo"] = dic;
  38388. }
  38389. return dic;
  38390. };
  38391. return ClassTreeInfo;
  38392. })();
  38393. BABYLON.ClassTreeInfo = ClassTreeInfo;
  38394. var SmartPropertyPrim = (function () {
  38395. function SmartPropertyPrim() {
  38396. this._flags = 0;
  38397. this._modelKey = null;
  38398. this._instanceDirtyFlags = 0;
  38399. this._levelBoundingInfo = new BABYLON.BoundingInfo2D();
  38400. this.animations = new Array();
  38401. }
  38402. Object.defineProperty(SmartPropertyPrim.prototype, "isDisposed", {
  38403. /**
  38404. * Check if the object is disposed or not.
  38405. * @returns true if the object is dispose, false otherwise.
  38406. */
  38407. get: function () {
  38408. return this._isFlagSet(SmartPropertyPrim.flagIsDisposed);
  38409. },
  38410. enumerable: true,
  38411. configurable: true
  38412. });
  38413. /**
  38414. * Disposable pattern, this method must be overloaded by derived types in order to clean up hardware related resources.
  38415. * @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.
  38416. */
  38417. SmartPropertyPrim.prototype.dispose = function () {
  38418. if (this.isDisposed) {
  38419. return false;
  38420. }
  38421. // Don't set to null, it may upset somebody...
  38422. this.animations.splice(0);
  38423. this._setFlags(SmartPropertyPrim.flagIsDisposed);
  38424. return true;
  38425. };
  38426. /**
  38427. * Returns as a new array populated with the Animatable used by the primitive. Must be overloaded by derived primitives.
  38428. * Look at Sprite2D for more information
  38429. */
  38430. SmartPropertyPrim.prototype.getAnimatables = function () {
  38431. return new Array();
  38432. };
  38433. Object.defineProperty(SmartPropertyPrim.prototype, "modelKey", {
  38434. /**
  38435. * Property giving the Model Key associated to the property.
  38436. * This value is constructed from the type of the primitive and all the name/value of its properties declared with the modelLevelProperty decorator
  38437. * @returns the model key string.
  38438. */
  38439. get: function () {
  38440. var _this = this;
  38441. // No need to compute it?
  38442. if (!this._isFlagSet(SmartPropertyPrim.flagModelDirty) && this._modelKey) {
  38443. return this._modelKey;
  38444. }
  38445. var modelKey = "Class:" + BABYLON.Tools.getClassName(this) + ";";
  38446. var propDic = this.propDic;
  38447. propDic.forEach(function (k, v) {
  38448. if (v.kind === Prim2DPropInfo.PROPKIND_MODEL) {
  38449. var propVal = _this[v.name];
  38450. // 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
  38451. if (propVal && propVal.constructor === Array) {
  38452. var firstVal = propVal[0];
  38453. if (!firstVal) {
  38454. propVal = 0;
  38455. }
  38456. else {
  38457. propVal = BABYLON.Tools.hashCodeFromStream(BABYLON.Tools.arrayOrStringFeeder(propVal));
  38458. }
  38459. }
  38460. modelKey += v.name + ":" + ((propVal != null) ? ((v.typeLevelCompare) ? BABYLON.Tools.getClassName(propVal) : propVal.toString()) : "[null]") + ";";
  38461. }
  38462. });
  38463. this._clearFlags(SmartPropertyPrim.flagModelDirty);
  38464. this._modelKey = modelKey;
  38465. return modelKey;
  38466. },
  38467. enumerable: true,
  38468. configurable: true
  38469. });
  38470. Object.defineProperty(SmartPropertyPrim.prototype, "isDirty", {
  38471. /**
  38472. * States if the Primitive is dirty and should be rendered again next time.
  38473. * @returns true is dirty, false otherwise
  38474. */
  38475. get: function () {
  38476. return (this._instanceDirtyFlags !== 0) || this._areSomeFlagsSet(SmartPropertyPrim.flagModelDirty | SmartPropertyPrim.flagPositioningDirty | SmartPropertyPrim.flagLayoutDirty);
  38477. },
  38478. enumerable: true,
  38479. configurable: true
  38480. });
  38481. Object.defineProperty(SmartPropertyPrim.prototype, "propDic", {
  38482. /**
  38483. * Access the dictionary of properties metadata. Only properties decorated with XXXXLevelProperty are concerned
  38484. * @returns the dictionary, the key is the property name as declared in Javascript, the value is the metadata object
  38485. */
  38486. get: function () {
  38487. if (!this._propInfo) {
  38488. var cti = ClassTreeInfo.get(Object.getPrototypeOf(this));
  38489. if (!cti) {
  38490. throw new Error("Can't access the propDic member in class definition, is this class SmartPropertyPrim based?");
  38491. }
  38492. this._propInfo = cti.fullContent;
  38493. }
  38494. return this._propInfo;
  38495. },
  38496. enumerable: true,
  38497. configurable: true
  38498. });
  38499. SmartPropertyPrim._createPropInfo = function (target, propName, propId, dirtyBoundingInfo, dirtyParentBoundingBox, typeLevelCompare, kind) {
  38500. var dic = ClassTreeInfo.getOrRegister(target, function () { return new Prim2DClassInfo(); });
  38501. var node = dic.getLevelOf(target);
  38502. var propInfo = node.levelContent.get(propId.toString());
  38503. if (propInfo) {
  38504. throw new Error("The ID " + propId + " is already taken by another property declaration named: " + propInfo.name);
  38505. }
  38506. // Create, setup and add the PropInfo object to our prop dictionary
  38507. propInfo = new Prim2DPropInfo();
  38508. propInfo.id = propId;
  38509. propInfo.flagId = Math.pow(2, propId);
  38510. propInfo.kind = kind;
  38511. propInfo.name = propName;
  38512. propInfo.dirtyBoundingInfo = dirtyBoundingInfo;
  38513. propInfo.dirtyParentBoundingInfo = dirtyParentBoundingBox;
  38514. propInfo.typeLevelCompare = typeLevelCompare;
  38515. node.levelContent.add(propName, propInfo);
  38516. return propInfo;
  38517. };
  38518. SmartPropertyPrim._checkUnchanged = function (curValue, newValue) {
  38519. // Nothing to nothing: nothing to do!
  38520. if ((curValue === null && newValue === null) || (curValue === undefined && newValue === undefined)) {
  38521. return true;
  38522. }
  38523. // Check value unchanged
  38524. if ((curValue != null) && (newValue != null)) {
  38525. if (typeof (curValue.equals) == "function") {
  38526. if (curValue.equals(newValue)) {
  38527. return true;
  38528. }
  38529. }
  38530. else {
  38531. if (curValue === newValue) {
  38532. return true;
  38533. }
  38534. }
  38535. }
  38536. return false;
  38537. };
  38538. SmartPropertyPrim.prototype.markAsDirty = function (propertyName) {
  38539. if (this.isDisposed) {
  38540. return;
  38541. }
  38542. var i = propertyName.indexOf(".");
  38543. if (i !== -1) {
  38544. propertyName = propertyName.substr(0, i);
  38545. }
  38546. var propInfo = this.propDic.get(propertyName);
  38547. if (!propInfo) {
  38548. return;
  38549. }
  38550. var newValue = this[propertyName];
  38551. this._handlePropChanged(undefined, newValue, propertyName, propInfo, propInfo.typeLevelCompare);
  38552. };
  38553. SmartPropertyPrim.prototype._boundingBoxDirty = function () {
  38554. this._setFlags(SmartPropertyPrim.flagLevelBoundingInfoDirty);
  38555. // Escalate the dirty flag in the instance hierarchy, stop when a renderable group is found or at the end
  38556. if (this instanceof BABYLON.Prim2DBase) {
  38557. var curprim = this;
  38558. while (curprim) {
  38559. curprim._setFlags(SmartPropertyPrim.flagBoundingInfoDirty);
  38560. if (curprim.isSizeAuto) {
  38561. curprim.onPrimitivePropertyDirty(BABYLON.Prim2DBase.sizeProperty.flagId);
  38562. curprim._setFlags(SmartPropertyPrim.flagPositioningDirty);
  38563. }
  38564. if (curprim instanceof BABYLON.Group2D) {
  38565. if (curprim.isRenderableGroup) {
  38566. break;
  38567. }
  38568. }
  38569. curprim = curprim.parent;
  38570. }
  38571. }
  38572. };
  38573. SmartPropertyPrim.prototype._handlePropChanged = function (curValue, newValue, propName, propInfo, typeLevelCompare) {
  38574. // If the property change also dirty the boundingInfo, update the boundingInfo dirty flags
  38575. if (propInfo.dirtyBoundingInfo) {
  38576. this._boundingBoxDirty();
  38577. }
  38578. else if (propInfo.dirtyParentBoundingInfo) {
  38579. var p = this._parent;
  38580. if (p != null) {
  38581. p._boundingBoxDirty();
  38582. }
  38583. }
  38584. // Trigger property changed
  38585. var info = SmartPropertyPrim.propChangedInfo;
  38586. info.oldValue = curValue;
  38587. info.newValue = newValue;
  38588. info.propertyName = propName;
  38589. var propMask = propInfo.flagId;
  38590. this.propertyChanged.notifyObservers(info, propMask);
  38591. // If the property belong to a group, check if it's a cached one, and dirty its render sprite accordingly
  38592. if (this instanceof BABYLON.Group2D) {
  38593. this.handleGroupChanged(propInfo);
  38594. }
  38595. // Check for parent layout dirty
  38596. if (this instanceof BABYLON.Prim2DBase) {
  38597. var p = this._parent;
  38598. if (p != null && p.layoutEngine && (p.layoutEngine.layoutDirtyOnPropertyChangedMask & propInfo.flagId) !== 0) {
  38599. p._setLayoutDirty();
  38600. }
  38601. }
  38602. // For type level compare, if there's a change of type it's a change of model, otherwise we issue an instance change
  38603. var instanceDirty = false;
  38604. if (typeLevelCompare && curValue != null && newValue != null) {
  38605. var cvProto = curValue.__proto__;
  38606. var nvProto = newValue.__proto__;
  38607. instanceDirty = (cvProto === nvProto);
  38608. }
  38609. // Set the dirty flags
  38610. if (!instanceDirty && (propInfo.kind === Prim2DPropInfo.PROPKIND_MODEL)) {
  38611. if (!this.isDirty) {
  38612. this._setFlags(SmartPropertyPrim.flagModelDirty);
  38613. }
  38614. }
  38615. else if (instanceDirty || (propInfo.kind === Prim2DPropInfo.PROPKIND_INSTANCE) || (propInfo.kind === Prim2DPropInfo.PROPKIND_DYNAMIC)) {
  38616. this.onPrimitivePropertyDirty(propMask);
  38617. }
  38618. };
  38619. SmartPropertyPrim.prototype.onPrimitivePropertyDirty = function (propFlagId) {
  38620. this.onPrimBecomesDirty();
  38621. this._instanceDirtyFlags |= propFlagId;
  38622. };
  38623. SmartPropertyPrim.prototype.handleGroupChanged = function (prop) {
  38624. };
  38625. /**
  38626. * Check if a given set of properties are dirty or not.
  38627. * @param flags a ORed combination of Prim2DPropInfo.flagId values
  38628. * @return true if at least one property is dirty, false if none of them are.
  38629. */
  38630. SmartPropertyPrim.prototype.checkPropertiesDirty = function (flags) {
  38631. return (this._instanceDirtyFlags & flags) !== 0;
  38632. };
  38633. /**
  38634. * Clear a given set of properties.
  38635. * @param flags a ORed combination of Prim2DPropInfo.flagId values
  38636. * @return the new set of property still marked as dirty
  38637. */
  38638. SmartPropertyPrim.prototype.clearPropertiesDirty = function (flags) {
  38639. this._instanceDirtyFlags &= ~flags;
  38640. return this._instanceDirtyFlags;
  38641. };
  38642. SmartPropertyPrim.prototype._resetPropertiesDirty = function () {
  38643. this._instanceDirtyFlags = 0;
  38644. this._clearFlags(SmartPropertyPrim.flagPrimInDirtyList);
  38645. };
  38646. Object.defineProperty(SmartPropertyPrim.prototype, "levelBoundingInfo", {
  38647. /**
  38648. * Retrieve the boundingInfo for this Primitive, computed based on the primitive itself and NOT its children
  38649. */
  38650. get: function () {
  38651. if (this._isFlagSet(SmartPropertyPrim.flagLevelBoundingInfoDirty)) {
  38652. this.updateLevelBoundingInfo();
  38653. this._clearFlags(SmartPropertyPrim.flagLevelBoundingInfoDirty);
  38654. }
  38655. return this._levelBoundingInfo;
  38656. },
  38657. enumerable: true,
  38658. configurable: true
  38659. });
  38660. /**
  38661. * This method must be overridden by a given Primitive implementation to compute its boundingInfo
  38662. */
  38663. SmartPropertyPrim.prototype.updateLevelBoundingInfo = function () {
  38664. };
  38665. /**
  38666. * Property method called when the Primitive becomes dirty
  38667. */
  38668. SmartPropertyPrim.prototype.onPrimBecomesDirty = function () {
  38669. };
  38670. SmartPropertyPrim._hookProperty = function (propId, piStore, typeLevelCompare, dirtyBoundingInfo, dirtyParentBoundingBox, kind) {
  38671. return function (target, propName, descriptor) {
  38672. var propInfo = SmartPropertyPrim._createPropInfo(target, propName, propId, dirtyBoundingInfo, dirtyParentBoundingBox, typeLevelCompare, kind);
  38673. if (piStore) {
  38674. piStore(propInfo);
  38675. }
  38676. var getter = descriptor.get, setter = descriptor.set;
  38677. // Overload the property setter implementation to add our own logic
  38678. descriptor.set = function (val) {
  38679. // check for disposed first, do nothing
  38680. if (this.isDisposed) {
  38681. return;
  38682. }
  38683. var curVal = getter.call(this);
  38684. if (SmartPropertyPrim._checkUnchanged(curVal, val)) {
  38685. return;
  38686. }
  38687. // Cast the object we're working one
  38688. var prim = this;
  38689. // Change the value
  38690. setter.call(this, val);
  38691. // Notify change, dirty flags update
  38692. prim._handlePropChanged(curVal, val, propName, propInfo, typeLevelCompare);
  38693. };
  38694. };
  38695. };
  38696. /**
  38697. * Add an externally attached data from its key.
  38698. * This method call will fail and return false, if such key already exists.
  38699. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  38700. * @param key the unique key that identifies the data
  38701. * @param data the data object to associate to the key for this Engine instance
  38702. * @return true if no such key were already present and the data was added successfully, false otherwise
  38703. */
  38704. SmartPropertyPrim.prototype.addExternalData = function (key, data) {
  38705. if (!this._externalData) {
  38706. this._externalData = new BABYLON.StringDictionary();
  38707. }
  38708. return this._externalData.add(key, data);
  38709. };
  38710. /**
  38711. * Get an externally attached data from its key
  38712. * @param key the unique key that identifies the data
  38713. * @return the associated data, if present (can be null), or undefined if not present
  38714. */
  38715. SmartPropertyPrim.prototype.getExternalData = function (key) {
  38716. if (!this._externalData) {
  38717. return null;
  38718. }
  38719. return this._externalData.get(key);
  38720. };
  38721. /**
  38722. * Get an externally attached data from its key, create it using a factory if it's not already present
  38723. * @param key the unique key that identifies the data
  38724. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  38725. * @return the associated data, can be null if the factory returned null.
  38726. */
  38727. SmartPropertyPrim.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  38728. if (!this._externalData) {
  38729. this._externalData = new BABYLON.StringDictionary();
  38730. }
  38731. return this._externalData.getOrAddWithFactory(key, factory);
  38732. };
  38733. /**
  38734. * Remove an externally attached data from the Engine instance
  38735. * @param key the unique key that identifies the data
  38736. * @return true if the data was successfully removed, false if it doesn't exist
  38737. */
  38738. SmartPropertyPrim.prototype.removeExternalData = function (key) {
  38739. if (!this._externalData) {
  38740. return false;
  38741. }
  38742. return this._externalData.remove(key);
  38743. };
  38744. /**
  38745. * Check if a given flag is set
  38746. * @param flag the flag value
  38747. * @return true if set, false otherwise
  38748. */
  38749. SmartPropertyPrim.prototype._isFlagSet = function (flag) {
  38750. return (this._flags & flag) !== 0;
  38751. };
  38752. /**
  38753. * Check if all given flags are set
  38754. * @param flags the flags ORed
  38755. * @return true if all the flags are set, false otherwise
  38756. */
  38757. SmartPropertyPrim.prototype._areAllFlagsSet = function (flags) {
  38758. return (this._flags & flags) === flags;
  38759. };
  38760. /**
  38761. * Check if at least one flag of the given flags is set
  38762. * @param flags the flags ORed
  38763. * @return true if at least one flag is set, false otherwise
  38764. */
  38765. SmartPropertyPrim.prototype._areSomeFlagsSet = function (flags) {
  38766. return (this._flags & flags) !== 0;
  38767. };
  38768. /**
  38769. * Clear the given flags
  38770. * @param flags the flags to clear
  38771. */
  38772. SmartPropertyPrim.prototype._clearFlags = function (flags) {
  38773. this._flags &= ~flags;
  38774. };
  38775. /**
  38776. * Set the given flags to true state
  38777. * @param flags the flags ORed to set
  38778. * @return the flags state before this call
  38779. */
  38780. SmartPropertyPrim.prototype._setFlags = function (flags) {
  38781. var cur = this._flags;
  38782. this._flags |= flags;
  38783. return cur;
  38784. };
  38785. /**
  38786. * Change the state of the given flags
  38787. * @param flags the flags ORed to change
  38788. * @param state true to set them, false to clear them
  38789. */
  38790. SmartPropertyPrim.prototype._changeFlags = function (flags, state) {
  38791. if (state) {
  38792. this._flags |= flags;
  38793. }
  38794. else {
  38795. this._flags &= ~flags;
  38796. }
  38797. };
  38798. SmartPropertyPrim.propChangedInfo = new PropertyChangedInfo();
  38799. SmartPropertyPrim.flagIsDisposed = 0x0000001; // set if the object is already disposed
  38800. SmartPropertyPrim.flagLevelBoundingInfoDirty = 0x0000002; // set if the primitive's level bounding box (not including children) is dirty
  38801. SmartPropertyPrim.flagModelDirty = 0x0000004; // set if the model must be changed
  38802. SmartPropertyPrim.flagLayoutDirty = 0x0000008; // set if the layout must be computed
  38803. SmartPropertyPrim.flagLevelVisible = 0x0000010; // set if the primitive is set as visible for its level only
  38804. SmartPropertyPrim.flagBoundingInfoDirty = 0x0000020; // set if the primitive's overall bounding box (including children) is dirty
  38805. SmartPropertyPrim.flagIsPickable = 0x0000040; // set if the primitive can be picked during interaction
  38806. SmartPropertyPrim.flagIsVisible = 0x0000080; // set if the primitive is concretely visible (use the levelVisible of parents)
  38807. SmartPropertyPrim.flagVisibilityChanged = 0x0000100; // set if there was a transition between visible/hidden status
  38808. SmartPropertyPrim.flagPositioningDirty = 0x0000200; // set if the primitive positioning must be computed
  38809. SmartPropertyPrim.flagTrackedGroup = 0x0000400; // set if the group2D is tracking a scene node
  38810. SmartPropertyPrim.flagWorldCacheChanged = 0x0000800; // set if the cached bitmap of a world space canvas changed
  38811. SmartPropertyPrim.flagChildrenFlatZOrder = 0x0001000; // set if all the children (direct and indirect) will share the same Z-Order
  38812. SmartPropertyPrim.flagZOrderDirty = 0x0002000; // set if the Z-Order for this prim and its children must be recomputed
  38813. SmartPropertyPrim.flagActualOpacityDirty = 0x0004000; // set if the actualOpactity should be recomputed
  38814. SmartPropertyPrim.flagPrimInDirtyList = 0x0008000; // set if the primitive is in the primDirtyList
  38815. SmartPropertyPrim = __decorate([
  38816. BABYLON.className("SmartPropertyPrim")
  38817. ], SmartPropertyPrim);
  38818. return SmartPropertyPrim;
  38819. })();
  38820. BABYLON.SmartPropertyPrim = SmartPropertyPrim;
  38821. function modelLevelProperty(propId, piStore, typeLevelCompare, dirtyBoundingInfo, dirtyParentBoundingBox) {
  38822. if (typeLevelCompare === void 0) { typeLevelCompare = false; }
  38823. if (dirtyBoundingInfo === void 0) { dirtyBoundingInfo = false; }
  38824. if (dirtyParentBoundingBox === void 0) { dirtyParentBoundingBox = false; }
  38825. return SmartPropertyPrim._hookProperty(propId, piStore, typeLevelCompare, dirtyBoundingInfo, dirtyParentBoundingBox, Prim2DPropInfo.PROPKIND_MODEL);
  38826. }
  38827. BABYLON.modelLevelProperty = modelLevelProperty;
  38828. function instanceLevelProperty(propId, piStore, typeLevelCompare, dirtyBoundingInfo, dirtyParentBoundingBox) {
  38829. if (typeLevelCompare === void 0) { typeLevelCompare = false; }
  38830. if (dirtyBoundingInfo === void 0) { dirtyBoundingInfo = false; }
  38831. if (dirtyParentBoundingBox === void 0) { dirtyParentBoundingBox = false; }
  38832. return SmartPropertyPrim._hookProperty(propId, piStore, typeLevelCompare, dirtyBoundingInfo, dirtyParentBoundingBox, Prim2DPropInfo.PROPKIND_INSTANCE);
  38833. }
  38834. BABYLON.instanceLevelProperty = instanceLevelProperty;
  38835. function dynamicLevelProperty(propId, piStore, typeLevelCompare, dirtyBoundingInfo, dirtyParentBoundingBox) {
  38836. if (typeLevelCompare === void 0) { typeLevelCompare = false; }
  38837. if (dirtyBoundingInfo === void 0) { dirtyBoundingInfo = false; }
  38838. if (dirtyParentBoundingBox === void 0) { dirtyParentBoundingBox = false; }
  38839. return SmartPropertyPrim._hookProperty(propId, piStore, typeLevelCompare, dirtyBoundingInfo, dirtyParentBoundingBox, Prim2DPropInfo.PROPKIND_DYNAMIC);
  38840. }
  38841. BABYLON.dynamicLevelProperty = dynamicLevelProperty;
  38842. })(BABYLON || (BABYLON = {}));
  38843. var BABYLON;
  38844. (function (BABYLON) {
  38845. var PrepareRender2DContext = (function () {
  38846. function PrepareRender2DContext() {
  38847. this.forceRefreshPrimitive = false;
  38848. }
  38849. return PrepareRender2DContext;
  38850. })();
  38851. BABYLON.PrepareRender2DContext = PrepareRender2DContext;
  38852. var Render2DContext = (function () {
  38853. function Render2DContext(renderMode) {
  38854. this._renderMode = renderMode;
  38855. this.useInstancing = false;
  38856. this.groupInfoPartData = null;
  38857. this.partDataStartIndex = this.partDataEndIndex = null;
  38858. this.instancedBuffers = null;
  38859. }
  38860. Object.defineProperty(Render2DContext.prototype, "renderMode", {
  38861. /**
  38862. * Define which render Mode should be used to render the primitive: one of Render2DContext.RenderModeXxxx property
  38863. */
  38864. get: function () {
  38865. return this._renderMode;
  38866. },
  38867. enumerable: true,
  38868. configurable: true
  38869. });
  38870. Object.defineProperty(Render2DContext, "RenderModeOpaque", {
  38871. /**
  38872. * The set of primitives to render is opaque.
  38873. * This is the first rendering pass. All Opaque primitives are rendered. Depth Compare and Write are both enabled.
  38874. */
  38875. get: function () {
  38876. return Render2DContext._renderModeOpaque;
  38877. },
  38878. enumerable: true,
  38879. configurable: true
  38880. });
  38881. Object.defineProperty(Render2DContext, "RenderModeAlphaTest", {
  38882. /**
  38883. * The set of primitives to render is using Alpha Test (aka masking).
  38884. * 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.
  38885. */
  38886. get: function () {
  38887. return Render2DContext._renderModeAlphaTest;
  38888. },
  38889. enumerable: true,
  38890. configurable: true
  38891. });
  38892. Object.defineProperty(Render2DContext, "RenderModeTransparent", {
  38893. /**
  38894. * The set of primitives to render is transparent.
  38895. * 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.
  38896. */
  38897. get: function () {
  38898. return Render2DContext._renderModeTransparent;
  38899. },
  38900. enumerable: true,
  38901. configurable: true
  38902. });
  38903. Render2DContext._renderModeOpaque = 1;
  38904. Render2DContext._renderModeAlphaTest = 2;
  38905. Render2DContext._renderModeTransparent = 3;
  38906. return Render2DContext;
  38907. })();
  38908. BABYLON.Render2DContext = Render2DContext;
  38909. /**
  38910. * This class store information for the pointerEventObservable Observable.
  38911. * 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.
  38912. */
  38913. var PrimitivePointerInfo = (function () {
  38914. function PrimitivePointerInfo() {
  38915. this.primitivePointerPos = BABYLON.Vector2.Zero();
  38916. this.tilt = BABYLON.Vector2.Zero();
  38917. this.cancelBubble = false;
  38918. }
  38919. Object.defineProperty(PrimitivePointerInfo, "PointerOver", {
  38920. // 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.
  38921. /**
  38922. * This event type is raised when a pointing device is moved into the hit test boundaries of a primitive.
  38923. * Bubbles: yes
  38924. */
  38925. get: function () {
  38926. return PrimitivePointerInfo._pointerOver;
  38927. },
  38928. enumerable: true,
  38929. configurable: true
  38930. });
  38931. Object.defineProperty(PrimitivePointerInfo, "PointerEnter", {
  38932. /**
  38933. * This event type is raised when a pointing device is moved into the hit test boundaries of a primitive or one of its descendants.
  38934. * Bubbles: no
  38935. */
  38936. get: function () {
  38937. return PrimitivePointerInfo._pointerEnter;
  38938. },
  38939. enumerable: true,
  38940. configurable: true
  38941. });
  38942. Object.defineProperty(PrimitivePointerInfo, "PointerDown", {
  38943. /**
  38944. * 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.
  38945. * Bubbles: yes
  38946. */
  38947. get: function () {
  38948. return PrimitivePointerInfo._pointerDown;
  38949. },
  38950. enumerable: true,
  38951. configurable: true
  38952. });
  38953. Object.defineProperty(PrimitivePointerInfo, "PointerMouseWheel", {
  38954. /**
  38955. * This event type is raised when the pointer is a mouse and it's wheel is rolling
  38956. * Bubbles: yes
  38957. */
  38958. get: function () {
  38959. return PrimitivePointerInfo._pointerMouseWheel;
  38960. },
  38961. enumerable: true,
  38962. configurable: true
  38963. });
  38964. Object.defineProperty(PrimitivePointerInfo, "PointerMove", {
  38965. /**
  38966. * 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.
  38967. * Bubbles: yes
  38968. */
  38969. get: function () {
  38970. return PrimitivePointerInfo._pointerMove;
  38971. },
  38972. enumerable: true,
  38973. configurable: true
  38974. });
  38975. Object.defineProperty(PrimitivePointerInfo, "PointerUp", {
  38976. /**
  38977. * 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.
  38978. * Bubbles: yes
  38979. */
  38980. get: function () {
  38981. return PrimitivePointerInfo._pointerUp;
  38982. },
  38983. enumerable: true,
  38984. configurable: true
  38985. });
  38986. Object.defineProperty(PrimitivePointerInfo, "PointerOut", {
  38987. /**
  38988. * This event type is raised when a pointing device is moved out of the hit test the boundaries of a primitive.
  38989. * Bubbles: yes
  38990. */
  38991. get: function () {
  38992. return PrimitivePointerInfo._pointerOut;
  38993. },
  38994. enumerable: true,
  38995. configurable: true
  38996. });
  38997. Object.defineProperty(PrimitivePointerInfo, "PointerLeave", {
  38998. /**
  38999. * This event type is raised when a pointing device is moved out of the hit test boundaries of a primitive and all its descendants.
  39000. * Bubbles: no
  39001. */
  39002. get: function () {
  39003. return PrimitivePointerInfo._pointerLeave;
  39004. },
  39005. enumerable: true,
  39006. configurable: true
  39007. });
  39008. Object.defineProperty(PrimitivePointerInfo, "PointerGotCapture", {
  39009. /**
  39010. * 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.
  39011. * Bubbles: yes
  39012. */
  39013. get: function () {
  39014. return PrimitivePointerInfo._pointerGotCapture;
  39015. },
  39016. enumerable: true,
  39017. configurable: true
  39018. });
  39019. Object.defineProperty(PrimitivePointerInfo, "PointerLostCapture", {
  39020. /**
  39021. * This event type is raised after pointer capture is released for a pointer.
  39022. * Bubbles: yes
  39023. */
  39024. get: function () {
  39025. return PrimitivePointerInfo._pointerLostCapture;
  39026. },
  39027. enumerable: true,
  39028. configurable: true
  39029. });
  39030. Object.defineProperty(PrimitivePointerInfo, "MouseWheelPrecision", {
  39031. get: function () {
  39032. return PrimitivePointerInfo._mouseWheelPrecision;
  39033. },
  39034. enumerable: true,
  39035. configurable: true
  39036. });
  39037. PrimitivePointerInfo.prototype.updateRelatedTarget = function (prim, primPointerPos) {
  39038. this.relatedTarget = prim;
  39039. this.relatedTargetPointerPos = primPointerPos;
  39040. };
  39041. PrimitivePointerInfo.getEventTypeName = function (mask) {
  39042. switch (mask) {
  39043. case PrimitivePointerInfo.PointerOver: return "PointerOver";
  39044. case PrimitivePointerInfo.PointerEnter: return "PointerEnter";
  39045. case PrimitivePointerInfo.PointerDown: return "PointerDown";
  39046. case PrimitivePointerInfo.PointerMouseWheel: return "PointerMouseWheel";
  39047. case PrimitivePointerInfo.PointerMove: return "PointerMove";
  39048. case PrimitivePointerInfo.PointerUp: return "PointerUp";
  39049. case PrimitivePointerInfo.PointerOut: return "PointerOut";
  39050. case PrimitivePointerInfo.PointerLeave: return "PointerLeave";
  39051. case PrimitivePointerInfo.PointerGotCapture: return "PointerGotCapture";
  39052. case PrimitivePointerInfo.PointerLostCapture: return "PointerLostCapture";
  39053. }
  39054. };
  39055. PrimitivePointerInfo._pointerOver = 0x0001;
  39056. PrimitivePointerInfo._pointerEnter = 0x0002;
  39057. PrimitivePointerInfo._pointerDown = 0x0004;
  39058. PrimitivePointerInfo._pointerMouseWheel = 0x0008;
  39059. PrimitivePointerInfo._pointerMove = 0x0010;
  39060. PrimitivePointerInfo._pointerUp = 0x0020;
  39061. PrimitivePointerInfo._pointerOut = 0x0040;
  39062. PrimitivePointerInfo._pointerLeave = 0x0080;
  39063. PrimitivePointerInfo._pointerGotCapture = 0x0100;
  39064. PrimitivePointerInfo._pointerLostCapture = 0x0200;
  39065. PrimitivePointerInfo._mouseWheelPrecision = 3.0;
  39066. return PrimitivePointerInfo;
  39067. })();
  39068. BABYLON.PrimitivePointerInfo = PrimitivePointerInfo;
  39069. /**
  39070. * Defines the horizontal and vertical alignment information for a Primitive.
  39071. */
  39072. var PrimitiveAlignment = (function () {
  39073. function PrimitiveAlignment(changeCallback) {
  39074. this._changedCallback = changeCallback;
  39075. this._horizontal = PrimitiveAlignment.AlignLeft;
  39076. this._vertical = PrimitiveAlignment.AlignBottom;
  39077. }
  39078. Object.defineProperty(PrimitiveAlignment, "AlignLeft", {
  39079. /**
  39080. * Alignment is made relative to the left edge of the Primitive. Valid for horizontal alignment only.
  39081. */
  39082. get: function () { return PrimitiveAlignment._AlignLeft; },
  39083. enumerable: true,
  39084. configurable: true
  39085. });
  39086. Object.defineProperty(PrimitiveAlignment, "AlignTop", {
  39087. /**
  39088. * Alignment is made relative to the top edge of the Primitive. Valid for vertical alignment only.
  39089. */
  39090. get: function () { return PrimitiveAlignment._AlignTop; },
  39091. enumerable: true,
  39092. configurable: true
  39093. });
  39094. Object.defineProperty(PrimitiveAlignment, "AlignRight", {
  39095. /**
  39096. * Alignment is made relative to the right edge of the Primitive. Valid for horizontal alignment only.
  39097. */
  39098. get: function () { return PrimitiveAlignment._AlignRight; },
  39099. enumerable: true,
  39100. configurable: true
  39101. });
  39102. Object.defineProperty(PrimitiveAlignment, "AlignBottom", {
  39103. /**
  39104. * Alignment is made relative to the bottom edge of the Primitive. Valid for vertical alignment only.
  39105. */
  39106. get: function () { return PrimitiveAlignment._AlignBottom; },
  39107. enumerable: true,
  39108. configurable: true
  39109. });
  39110. Object.defineProperty(PrimitiveAlignment, "AlignCenter", {
  39111. /**
  39112. * Alignment is made to center the content from equal distance to the opposite edges of the Primitive
  39113. */
  39114. get: function () { return PrimitiveAlignment._AlignCenter; },
  39115. enumerable: true,
  39116. configurable: true
  39117. });
  39118. Object.defineProperty(PrimitiveAlignment, "AlignStretch", {
  39119. /**
  39120. * The content is stretched toward the opposite edges of the Primitive
  39121. */
  39122. get: function () { return PrimitiveAlignment._AlignStretch; },
  39123. enumerable: true,
  39124. configurable: true
  39125. });
  39126. Object.defineProperty(PrimitiveAlignment.prototype, "horizontal", {
  39127. /**
  39128. * Get/set the horizontal alignment. Use one of the AlignXXX static properties of this class
  39129. */
  39130. get: function () {
  39131. return this._horizontal;
  39132. },
  39133. set: function (value) {
  39134. if (this._horizontal === value) {
  39135. return;
  39136. }
  39137. this._horizontal = value;
  39138. this._changedCallback();
  39139. },
  39140. enumerable: true,
  39141. configurable: true
  39142. });
  39143. Object.defineProperty(PrimitiveAlignment.prototype, "vertical", {
  39144. /**
  39145. * Get/set the vertical alignment. Use one of the AlignXXX static properties of this class
  39146. */
  39147. get: function () {
  39148. return this._vertical;
  39149. },
  39150. set: function (value) {
  39151. if (this._vertical === value) {
  39152. return;
  39153. }
  39154. this._vertical = value;
  39155. this._changedCallback();
  39156. },
  39157. enumerable: true,
  39158. configurable: true
  39159. });
  39160. /**
  39161. * Set the horizontal alignment from a string value.
  39162. * @param text can be either: 'left','right','center','stretch'
  39163. */
  39164. PrimitiveAlignment.prototype.setHorizontal = function (text) {
  39165. var v = text.trim().toLocaleLowerCase();
  39166. switch (v) {
  39167. case "left":
  39168. this.horizontal = PrimitiveAlignment.AlignLeft;
  39169. return;
  39170. case "right":
  39171. this.horizontal = PrimitiveAlignment.AlignRight;
  39172. return;
  39173. case "center":
  39174. this.horizontal = PrimitiveAlignment.AlignCenter;
  39175. return;
  39176. case "stretch":
  39177. this.horizontal = PrimitiveAlignment.AlignStretch;
  39178. return;
  39179. }
  39180. };
  39181. /**
  39182. * Set the vertical alignment from a string value.
  39183. * @param text can be either: 'top','bottom','center','stretch'
  39184. */
  39185. PrimitiveAlignment.prototype.setVertical = function (text) {
  39186. var v = text.trim().toLocaleLowerCase();
  39187. switch (v) {
  39188. case "top":
  39189. this.vertical = PrimitiveAlignment.AlignTop;
  39190. return;
  39191. case "bottom":
  39192. this.vertical = PrimitiveAlignment.AlignBottom;
  39193. return;
  39194. case "center":
  39195. this.vertical = PrimitiveAlignment.AlignCenter;
  39196. return;
  39197. case "stretch":
  39198. this.vertical = PrimitiveAlignment.AlignStretch;
  39199. return;
  39200. }
  39201. };
  39202. /**
  39203. * Set the horizontal and or vertical alignments from a string value.
  39204. * @param text can be: [<h:|horizontal:><left|right|center|stretch>], [<v:|vertical:><top|bottom|center|stretch>]
  39205. */
  39206. PrimitiveAlignment.prototype.fromString = function (value) {
  39207. var m = value.trim().split(",");
  39208. for (var _i = 0; _i < m.length; _i++) {
  39209. var v = m[_i];
  39210. v = v.toLocaleLowerCase().trim();
  39211. // Horizontal
  39212. var i = v.indexOf("h:");
  39213. if (i === -1) {
  39214. i = v.indexOf("horizontal:");
  39215. }
  39216. if (i !== -1) {
  39217. v = v.substr(v.indexOf(":") + 1);
  39218. this.setHorizontal(v);
  39219. continue;
  39220. }
  39221. // Vertical
  39222. i = v.indexOf("v:");
  39223. if (i === -1) {
  39224. i = v.indexOf("vertical:");
  39225. }
  39226. if (i !== -1) {
  39227. v = v.substr(v.indexOf(":") + 1);
  39228. this.setVertical(v);
  39229. continue;
  39230. }
  39231. }
  39232. };
  39233. PrimitiveAlignment._AlignLeft = 1;
  39234. PrimitiveAlignment._AlignTop = 1; // Same as left
  39235. PrimitiveAlignment._AlignRight = 2;
  39236. PrimitiveAlignment._AlignBottom = 2; // Same as right
  39237. PrimitiveAlignment._AlignCenter = 3;
  39238. PrimitiveAlignment._AlignStretch = 4;
  39239. return PrimitiveAlignment;
  39240. })();
  39241. BABYLON.PrimitiveAlignment = PrimitiveAlignment;
  39242. /**
  39243. * Stores information about a Primitive that was intersected
  39244. */
  39245. var PrimitiveIntersectedInfo = (function () {
  39246. function PrimitiveIntersectedInfo(prim, intersectionLocation) {
  39247. this.prim = prim;
  39248. this.intersectionLocation = intersectionLocation;
  39249. }
  39250. return PrimitiveIntersectedInfo;
  39251. })();
  39252. BABYLON.PrimitiveIntersectedInfo = PrimitiveIntersectedInfo;
  39253. /**
  39254. * Define a thickness toward every edges of a Primitive to allow margin and padding.
  39255. * The thickness can be expressed as pixels, percentages, inherit the value of the parent primitive or be auto.
  39256. */
  39257. var PrimitiveThickness = (function () {
  39258. function PrimitiveThickness(parentAccess, changedCallback) {
  39259. this._parentAccess = parentAccess;
  39260. this._changedCallback = changedCallback;
  39261. this._pixels = new Array(4);
  39262. this._percentages = new Array(4);
  39263. this._setType(0, PrimitiveThickness.Auto);
  39264. this._setType(1, PrimitiveThickness.Auto);
  39265. this._setType(2, PrimitiveThickness.Auto);
  39266. this._setType(3, PrimitiveThickness.Auto);
  39267. this._pixels[0] = 0;
  39268. this._pixels[1] = 0;
  39269. this._pixels[2] = 0;
  39270. this._pixels[3] = 0;
  39271. }
  39272. /**
  39273. * Set the thickness from a string value
  39274. * @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.
  39275. * Values are: 'auto', 'inherit', 'XX%' for percentage, 'XXpx' or 'XX' for pixels.
  39276. */
  39277. PrimitiveThickness.prototype.fromString = function (thickness) {
  39278. this._clear();
  39279. var m = thickness.trim().split(",");
  39280. // Special case, one value to apply to all edges
  39281. if (m.length === 1 && thickness.indexOf(":") === -1) {
  39282. this._setStringValue(m[0], 0, false);
  39283. this._setStringValue(m[0], 1, false);
  39284. this._setStringValue(m[0], 2, false);
  39285. this._setStringValue(m[0], 3, false);
  39286. this._changedCallback();
  39287. return;
  39288. }
  39289. var res = false;
  39290. for (var _i = 0; _i < m.length; _i++) {
  39291. var cm = m[_i];
  39292. res = this._extractString(cm, false) || res;
  39293. }
  39294. if (!res) {
  39295. throw new Error("Can't parse the string to create a PrimitiveMargin object, format must be: 'top: <value>, left:<value>, right:<value>, bottom:<value>");
  39296. }
  39297. // Check the margin that weren't set and set them in auto
  39298. if ((this._flags & 0x000F) === 0)
  39299. this._flags |= PrimitiveThickness.Pixel << 0;
  39300. if ((this._flags & 0x00F0) === 0)
  39301. this._flags |= PrimitiveThickness.Pixel << 4;
  39302. if ((this._flags & 0x0F00) === 0)
  39303. this._flags |= PrimitiveThickness.Pixel << 8;
  39304. if ((this._flags & 0xF000) === 0)
  39305. this._flags |= PrimitiveThickness.Pixel << 12;
  39306. this._changedCallback();
  39307. };
  39308. /**
  39309. * Set the thickness from multiple string
  39310. * Possible values are: 'auto', 'inherit', 'XX%' for percentage, 'XXpx' or 'XX' for pixels.
  39311. * @param top the top thickness to set
  39312. * @param left the left thickness to set
  39313. * @param right the right thickness to set
  39314. * @param bottom the bottom thickness to set
  39315. */
  39316. PrimitiveThickness.prototype.fromStrings = function (top, left, right, bottom) {
  39317. this._clear();
  39318. this._setStringValue(top, 0, false);
  39319. this._setStringValue(left, 1, false);
  39320. this._setStringValue(right, 2, false);
  39321. this._setStringValue(bottom, 3, false);
  39322. this._changedCallback();
  39323. return this;
  39324. };
  39325. /**
  39326. * Set the thickness from pixel values
  39327. * @param top the top thickness in pixels to set
  39328. * @param left the left thickness in pixels to set
  39329. * @param right the right thickness in pixels to set
  39330. * @param bottom the bottom thickness in pixels to set
  39331. */
  39332. PrimitiveThickness.prototype.fromPixels = function (top, left, right, bottom) {
  39333. this._clear();
  39334. this._pixels[0] = top;
  39335. this._pixels[1] = left;
  39336. this._pixels[2] = right;
  39337. this._pixels[3] = bottom;
  39338. this._changedCallback();
  39339. return this;
  39340. };
  39341. /**
  39342. * Apply the same pixel value to all edges
  39343. * @param margin the value to set, in pixels.
  39344. */
  39345. PrimitiveThickness.prototype.fromUniformPixels = function (margin) {
  39346. this._clear();
  39347. this._pixels[0] = margin;
  39348. this._pixels[1] = margin;
  39349. this._pixels[2] = margin;
  39350. this._pixels[3] = margin;
  39351. this._changedCallback();
  39352. return this;
  39353. };
  39354. /**
  39355. * Set all edges in auto
  39356. */
  39357. PrimitiveThickness.prototype.auto = function () {
  39358. this._clear();
  39359. this._flags = (PrimitiveThickness.Auto << 0) | (PrimitiveThickness.Auto << 4) | (PrimitiveThickness.Auto << 8) | (PrimitiveThickness.Auto << 12);
  39360. this._pixels[0] = 0;
  39361. this._pixels[1] = 0;
  39362. this._pixels[2] = 0;
  39363. this._pixels[3] = 0;
  39364. this._changedCallback();
  39365. return this;
  39366. };
  39367. PrimitiveThickness.prototype._clear = function () {
  39368. this._flags = 0;
  39369. this._pixels[0] = 0;
  39370. this._pixels[1] = 0;
  39371. this._pixels[2] = 0;
  39372. this._pixels[3] = 0;
  39373. this._percentages[0] = null;
  39374. this._percentages[1] = null;
  39375. this._percentages[2] = null;
  39376. this._percentages[3] = null;
  39377. };
  39378. PrimitiveThickness.prototype._extractString = function (value, emitChanged) {
  39379. var v = value.trim().toLocaleLowerCase();
  39380. if (v.indexOf("top:") === 0) {
  39381. v = v.substr(4).trim();
  39382. return this._setStringValue(v, 0, emitChanged);
  39383. }
  39384. if (v.indexOf("left:") === 0) {
  39385. v = v.substr(5).trim();
  39386. return this._setStringValue(v, 1, emitChanged);
  39387. }
  39388. if (v.indexOf("right:") === 0) {
  39389. v = v.substr(6).trim();
  39390. return this._setStringValue(v, 2, emitChanged);
  39391. }
  39392. if (v.indexOf("bottom:") === 0) {
  39393. v = v.substr(7).trim();
  39394. return this._setStringValue(v, 3, emitChanged);
  39395. }
  39396. return false;
  39397. };
  39398. PrimitiveThickness.prototype._setStringValue = function (value, index, emitChanged) {
  39399. // Check for auto
  39400. var v = value.trim().toLocaleLowerCase();
  39401. if (v === "auto") {
  39402. if (this._isType(index, PrimitiveThickness.Auto)) {
  39403. return true;
  39404. }
  39405. this._setType(index, PrimitiveThickness.Auto);
  39406. this._pixels[index] = 0;
  39407. if (emitChanged) {
  39408. this._changedCallback();
  39409. }
  39410. }
  39411. else if (v === "inherit") {
  39412. if (this._isType(index, PrimitiveThickness.Inherit)) {
  39413. return true;
  39414. }
  39415. this._setType(index, PrimitiveThickness.Inherit);
  39416. this._pixels[index] = null;
  39417. if (emitChanged) {
  39418. this._changedCallback();
  39419. }
  39420. }
  39421. else {
  39422. var pI = v.indexOf("%");
  39423. // Check for percentage
  39424. if (pI !== -1) {
  39425. var n_1 = v.substr(0, pI);
  39426. var number_1 = Math.round(Number(n_1)) / 100; // Normalize the percentage to [0;1] with a 0.01 precision
  39427. if (this._isType(index, PrimitiveThickness.Percentage) && (this._percentages[index] === number_1)) {
  39428. return true;
  39429. }
  39430. this._setType(index, PrimitiveThickness.Percentage);
  39431. if (isNaN(number_1)) {
  39432. return false;
  39433. }
  39434. this._percentages[index] = number_1;
  39435. if (emitChanged) {
  39436. this._changedCallback();
  39437. }
  39438. return true;
  39439. }
  39440. // Check for pixel
  39441. var n;
  39442. pI = v.indexOf("px");
  39443. if (pI !== -1) {
  39444. n = v.substr(0, pI).trim();
  39445. }
  39446. else {
  39447. n = v;
  39448. }
  39449. var number = Number(n);
  39450. if (this._isType(index, PrimitiveThickness.Pixel) && (this._pixels[index] === number)) {
  39451. return true;
  39452. }
  39453. if (isNaN(number)) {
  39454. return false;
  39455. }
  39456. this._pixels[index] = number;
  39457. this._setType(index, PrimitiveThickness.Pixel);
  39458. if (emitChanged) {
  39459. this._changedCallback();
  39460. }
  39461. return true;
  39462. }
  39463. };
  39464. PrimitiveThickness.prototype._setPixels = function (value, index, emitChanged) {
  39465. // 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
  39466. value = Math.round(value);
  39467. if (this._isType(index, PrimitiveThickness.Pixel) && this._pixels[index] === value) {
  39468. return;
  39469. }
  39470. this._setType(index, PrimitiveThickness.Pixel);
  39471. this._pixels[index] = value;
  39472. if (emitChanged) {
  39473. this._changedCallback();
  39474. }
  39475. };
  39476. PrimitiveThickness.prototype._setPercentage = function (value, index, emitChanged) {
  39477. // Clip Value to bounds
  39478. value = Math.min(1, value);
  39479. value = Math.max(0, value);
  39480. value = Math.round(value * 100) / 100; // 0.01 precision
  39481. if (this._isType(index, PrimitiveThickness.Percentage) && this._percentages[index] === value) {
  39482. return;
  39483. }
  39484. this._setType(index, PrimitiveThickness.Percentage);
  39485. this._percentages[index] = value;
  39486. if (emitChanged) {
  39487. this._changedCallback();
  39488. }
  39489. };
  39490. PrimitiveThickness.prototype._getStringValue = function (index) {
  39491. var f = (this._flags >> (index * 4)) & 0xF;
  39492. switch (f) {
  39493. case PrimitiveThickness.Auto:
  39494. return "auto";
  39495. case PrimitiveThickness.Pixel:
  39496. return this._pixels[index] + "px";
  39497. case PrimitiveThickness.Percentage:
  39498. return this._percentages[index] * 100 + "%";
  39499. case PrimitiveThickness.Inherit:
  39500. return "inherit";
  39501. }
  39502. return "";
  39503. };
  39504. PrimitiveThickness.prototype._isType = function (index, type) {
  39505. var f = (this._flags >> (index * 4)) & 0xF;
  39506. return f === type;
  39507. };
  39508. PrimitiveThickness.prototype._getType = function (index, processInherit) {
  39509. var t = (this._flags >> (index * 4)) & 0xF;
  39510. if (processInherit && (t === PrimitiveThickness.Inherit)) {
  39511. var p = this._parentAccess();
  39512. if (p) {
  39513. return p._getType(index, true);
  39514. }
  39515. return PrimitiveThickness.Auto;
  39516. }
  39517. return t;
  39518. };
  39519. PrimitiveThickness.prototype._setType = function (index, type) {
  39520. this._flags &= ~(0xF << (index * 4));
  39521. this._flags |= type << (index * 4);
  39522. };
  39523. PrimitiveThickness.prototype.setTop = function (value) {
  39524. if (typeof value === "string") {
  39525. this._setStringValue(value, 0, true);
  39526. }
  39527. else {
  39528. this.topPixels = value;
  39529. }
  39530. };
  39531. PrimitiveThickness.prototype.setLeft = function (value) {
  39532. if (typeof value === "string") {
  39533. this._setStringValue(value, 1, true);
  39534. }
  39535. else {
  39536. this.leftPixels = value;
  39537. }
  39538. };
  39539. PrimitiveThickness.prototype.setRight = function (value) {
  39540. if (typeof value === "string") {
  39541. this._setStringValue(value, 2, true);
  39542. }
  39543. else {
  39544. this.rightPixels = value;
  39545. }
  39546. };
  39547. PrimitiveThickness.prototype.setBottom = function (value) {
  39548. if (typeof value === "string") {
  39549. this._setStringValue(value, 3, true);
  39550. }
  39551. else {
  39552. this.bottomPixels = value;
  39553. }
  39554. };
  39555. Object.defineProperty(PrimitiveThickness.prototype, "top", {
  39556. /**
  39557. * Get/set the top thickness. Possible values are: 'auto', 'inherit', 'XX%' for percentage, 'XXpx' or 'XX' for pixels.
  39558. */
  39559. get: function () {
  39560. return this._getStringValue(0);
  39561. },
  39562. set: function (value) {
  39563. this._setStringValue(value, 0, true);
  39564. },
  39565. enumerable: true,
  39566. configurable: true
  39567. });
  39568. Object.defineProperty(PrimitiveThickness.prototype, "left", {
  39569. /**
  39570. * Get/set the left thickness. Possible values are: 'auto', 'inherit', 'XX%' for percentage, 'XXpx' or 'XX' for pixels.
  39571. */
  39572. get: function () {
  39573. return this._getStringValue(1);
  39574. },
  39575. set: function (value) {
  39576. this._setStringValue(value, 1, true);
  39577. },
  39578. enumerable: true,
  39579. configurable: true
  39580. });
  39581. Object.defineProperty(PrimitiveThickness.prototype, "right", {
  39582. /**
  39583. * Get/set the right thickness. Possible values are: 'auto', 'inherit', 'XX%' for percentage, 'XXpx' or 'XX' for pixels.
  39584. */
  39585. get: function () {
  39586. return this._getStringValue(2);
  39587. },
  39588. set: function (value) {
  39589. this._setStringValue(value, 2, true);
  39590. },
  39591. enumerable: true,
  39592. configurable: true
  39593. });
  39594. Object.defineProperty(PrimitiveThickness.prototype, "bottom", {
  39595. /**
  39596. * Get/set the bottom thickness. Possible values are: 'auto', 'inherit', 'XX%' for percentage, 'XXpx' or 'XX' for pixels.
  39597. */
  39598. get: function () {
  39599. return this._getStringValue(3);
  39600. },
  39601. set: function (value) {
  39602. this._setStringValue(value, 3, true);
  39603. },
  39604. enumerable: true,
  39605. configurable: true
  39606. });
  39607. Object.defineProperty(PrimitiveThickness.prototype, "topPixels", {
  39608. /**
  39609. * Get/set the top thickness in pixel.
  39610. */
  39611. get: function () {
  39612. return this._pixels[0];
  39613. },
  39614. set: function (value) {
  39615. this._setPixels(value, 0, true);
  39616. },
  39617. enumerable: true,
  39618. configurable: true
  39619. });
  39620. Object.defineProperty(PrimitiveThickness.prototype, "leftPixels", {
  39621. /**
  39622. * Get/set the left thickness in pixel.
  39623. */
  39624. get: function () {
  39625. return this._pixels[1];
  39626. },
  39627. set: function (value) {
  39628. this._setPixels(value, 1, true);
  39629. },
  39630. enumerable: true,
  39631. configurable: true
  39632. });
  39633. Object.defineProperty(PrimitiveThickness.prototype, "rightPixels", {
  39634. /**
  39635. * Get/set the right thickness in pixel.
  39636. */
  39637. get: function () {
  39638. return this._pixels[2];
  39639. },
  39640. set: function (value) {
  39641. this._setPixels(value, 2, true);
  39642. },
  39643. enumerable: true,
  39644. configurable: true
  39645. });
  39646. Object.defineProperty(PrimitiveThickness.prototype, "bottomPixels", {
  39647. /**
  39648. * Get/set the bottom thickness in pixel.
  39649. */
  39650. get: function () {
  39651. return this._pixels[3];
  39652. },
  39653. set: function (value) {
  39654. this._setPixels(value, 3, true);
  39655. },
  39656. enumerable: true,
  39657. configurable: true
  39658. });
  39659. Object.defineProperty(PrimitiveThickness.prototype, "topPercentage", {
  39660. /**
  39661. * Get/set the top thickness in percentage.
  39662. * The get will return a valid value only if the edge type is percentage.
  39663. * The Set will change the edge mode if needed
  39664. */
  39665. get: function () {
  39666. return this._percentages[0];
  39667. },
  39668. set: function (value) {
  39669. this._setPercentage(value, 0, true);
  39670. },
  39671. enumerable: true,
  39672. configurable: true
  39673. });
  39674. Object.defineProperty(PrimitiveThickness.prototype, "leftPercentage", {
  39675. /**
  39676. * Get/set the left thickness in percentage.
  39677. * The get will return a valid value only if the edge mode is percentage.
  39678. * The Set will change the edge mode if needed
  39679. */
  39680. get: function () {
  39681. return this._percentages[1];
  39682. },
  39683. set: function (value) {
  39684. this._setPercentage(value, 1, true);
  39685. },
  39686. enumerable: true,
  39687. configurable: true
  39688. });
  39689. Object.defineProperty(PrimitiveThickness.prototype, "rightPercentage", {
  39690. /**
  39691. * Get/set the right thickness in percentage.
  39692. * The get will return a valid value only if the edge mode is percentage.
  39693. * The Set will change the edge mode if needed
  39694. */
  39695. get: function () {
  39696. return this._percentages[2];
  39697. },
  39698. set: function (value) {
  39699. this._setPercentage(value, 2, true);
  39700. },
  39701. enumerable: true,
  39702. configurable: true
  39703. });
  39704. Object.defineProperty(PrimitiveThickness.prototype, "bottomPercentage", {
  39705. /**
  39706. * Get/set the bottom thickness in percentage.
  39707. * The get will return a valid value only if the edge mode is percentage.
  39708. * The Set will change the edge mode if needed
  39709. */
  39710. get: function () {
  39711. return this._percentages[3];
  39712. },
  39713. set: function (value) {
  39714. this._setPercentage(value, 3, true);
  39715. },
  39716. enumerable: true,
  39717. configurable: true
  39718. });
  39719. Object.defineProperty(PrimitiveThickness.prototype, "topMode", {
  39720. /**
  39721. * Get/set the top mode. The setter shouldn't be used, other setters with value should be preferred
  39722. */
  39723. get: function () {
  39724. return this._getType(0, false);
  39725. },
  39726. set: function (mode) {
  39727. this._setType(0, mode);
  39728. },
  39729. enumerable: true,
  39730. configurable: true
  39731. });
  39732. Object.defineProperty(PrimitiveThickness.prototype, "leftMode", {
  39733. /**
  39734. * Get/set the left mode. The setter shouldn't be used, other setters with value should be preferred
  39735. */
  39736. get: function () {
  39737. return this._getType(1, false);
  39738. },
  39739. set: function (mode) {
  39740. this._setType(1, mode);
  39741. },
  39742. enumerable: true,
  39743. configurable: true
  39744. });
  39745. Object.defineProperty(PrimitiveThickness.prototype, "rightMode", {
  39746. /**
  39747. * Get/set the right mode. The setter shouldn't be used, other setters with value should be preferred
  39748. */
  39749. get: function () {
  39750. return this._getType(2, false);
  39751. },
  39752. set: function (mode) {
  39753. this._setType(2, mode);
  39754. },
  39755. enumerable: true,
  39756. configurable: true
  39757. });
  39758. Object.defineProperty(PrimitiveThickness.prototype, "bottomMode", {
  39759. /**
  39760. * Get/set the bottom mode. The setter shouldn't be used, other setters with value should be preferred
  39761. */
  39762. get: function () {
  39763. return this._getType(3, false);
  39764. },
  39765. set: function (mode) {
  39766. this._setType(3, mode);
  39767. },
  39768. enumerable: true,
  39769. configurable: true
  39770. });
  39771. PrimitiveThickness.prototype._computePixels = function (index, sourceArea, emitChanged) {
  39772. var type = this._getType(index, false);
  39773. if (type === PrimitiveThickness.Inherit) {
  39774. this._parentAccess()._computePixels(index, sourceArea, emitChanged);
  39775. return;
  39776. }
  39777. if (type !== PrimitiveThickness.Percentage) {
  39778. return;
  39779. }
  39780. var pixels = ((index === 0 || index === 3) ? sourceArea.height : sourceArea.width) * this._percentages[index];
  39781. this._pixels[index] = pixels;
  39782. if (emitChanged) {
  39783. this._changedCallback();
  39784. }
  39785. };
  39786. /**
  39787. * Compute the positioning/size of an area considering the thickness of this object and a given alignment
  39788. * @param sourceArea the source area
  39789. * @param contentSize the content size to position/resize
  39790. * @param alignment the alignment setting
  39791. * @param dstOffset the position of the content
  39792. * @param dstArea the new size of the content
  39793. */
  39794. PrimitiveThickness.prototype.computeWithAlignment = function (sourceArea, contentSize, alignment, dstOffset, dstArea) {
  39795. // Fetch some data
  39796. var topType = this._getType(0, true);
  39797. var leftType = this._getType(1, true);
  39798. var rightType = this._getType(2, true);
  39799. var bottomType = this._getType(3, true);
  39800. var hasWidth = contentSize && (contentSize.width != null);
  39801. var hasHeight = contentSize && (contentSize.height != null);
  39802. var width = hasWidth ? contentSize.width : 0;
  39803. var height = hasHeight ? contentSize.height : 0;
  39804. var isTopAuto = topType === PrimitiveThickness.Auto;
  39805. var isLeftAuto = leftType === PrimitiveThickness.Auto;
  39806. var isRightAuto = rightType === PrimitiveThickness.Auto;
  39807. var isBottomAuto = bottomType === PrimitiveThickness.Auto;
  39808. switch (alignment.horizontal) {
  39809. case PrimitiveAlignment.AlignLeft:
  39810. {
  39811. if (isLeftAuto) {
  39812. dstOffset.x = 0;
  39813. }
  39814. else {
  39815. this._computePixels(1, sourceArea, true);
  39816. dstOffset.x = this.leftPixels;
  39817. }
  39818. dstArea.width = width;
  39819. break;
  39820. }
  39821. case PrimitiveAlignment.AlignRight:
  39822. {
  39823. if (isRightAuto) {
  39824. dstOffset.x = Math.round(sourceArea.width - width);
  39825. }
  39826. else {
  39827. this._computePixels(2, sourceArea, true);
  39828. dstOffset.x = Math.round(sourceArea.width - (width + this.rightPixels));
  39829. }
  39830. dstArea.width = width;
  39831. break;
  39832. }
  39833. case PrimitiveAlignment.AlignStretch:
  39834. {
  39835. if (isLeftAuto) {
  39836. dstOffset.x = 0;
  39837. }
  39838. else {
  39839. this._computePixels(1, sourceArea, true);
  39840. dstOffset.x = this.leftPixels;
  39841. }
  39842. var right = 0;
  39843. if (!isRightAuto) {
  39844. this._computePixels(2, sourceArea, true);
  39845. right = this.rightPixels;
  39846. }
  39847. dstArea.width = sourceArea.width - (dstOffset.x + right);
  39848. break;
  39849. }
  39850. case PrimitiveAlignment.AlignCenter:
  39851. {
  39852. if (!isLeftAuto) {
  39853. this._computePixels(1, sourceArea, true);
  39854. }
  39855. if (!isRightAuto) {
  39856. this._computePixels(2, sourceArea, true);
  39857. }
  39858. var offset = (isLeftAuto ? 0 : this.leftPixels) - (isRightAuto ? 0 : this.rightPixels);
  39859. dstOffset.x = Math.round(((sourceArea.width - width) / 2) + offset);
  39860. dstArea.width = width;
  39861. break;
  39862. }
  39863. }
  39864. switch (alignment.vertical) {
  39865. case PrimitiveAlignment.AlignTop:
  39866. {
  39867. if (isTopAuto) {
  39868. dstOffset.y = sourceArea.height - height;
  39869. }
  39870. else {
  39871. this._computePixels(0, sourceArea, true);
  39872. dstOffset.y = Math.round(sourceArea.height - (height + this.topPixels));
  39873. }
  39874. dstArea.height = height;
  39875. break;
  39876. }
  39877. case PrimitiveAlignment.AlignBottom:
  39878. {
  39879. if (isBottomAuto) {
  39880. dstOffset.y = 0;
  39881. }
  39882. else {
  39883. this._computePixels(3, sourceArea, true);
  39884. dstOffset.y = this.bottomPixels;
  39885. }
  39886. dstArea.height = height;
  39887. break;
  39888. }
  39889. case PrimitiveAlignment.AlignStretch:
  39890. {
  39891. if (isBottomAuto) {
  39892. dstOffset.y = 0;
  39893. }
  39894. else {
  39895. this._computePixels(3, sourceArea, true);
  39896. dstOffset.y = this.bottomPixels;
  39897. }
  39898. var top_1 = 0;
  39899. if (!isTopAuto) {
  39900. this._computePixels(0, sourceArea, true);
  39901. top_1 = this.topPixels;
  39902. }
  39903. dstArea.height = sourceArea.height - (dstOffset.y + top_1);
  39904. break;
  39905. }
  39906. case PrimitiveAlignment.AlignCenter:
  39907. {
  39908. if (!isTopAuto) {
  39909. this._computePixels(0, sourceArea, true);
  39910. }
  39911. if (!isBottomAuto) {
  39912. this._computePixels(3, sourceArea, true);
  39913. }
  39914. var offset = (isBottomAuto ? 0 : this.bottomPixels) - (isTopAuto ? 0 : this.topPixels);
  39915. dstOffset.y = Math.round(((sourceArea.height - height) / 2) + offset);
  39916. dstArea.height = height;
  39917. break;
  39918. }
  39919. }
  39920. };
  39921. /**
  39922. * Compute an area and its position considering this thickness properties based on a given source area
  39923. * @param sourceArea the source area
  39924. * @param dstOffset the position of the resulting area
  39925. * @param dstArea the size of the resulting area
  39926. */
  39927. PrimitiveThickness.prototype.compute = function (sourceArea, dstOffset, dstArea) {
  39928. this._computePixels(0, sourceArea, true);
  39929. this._computePixels(1, sourceArea, true);
  39930. this._computePixels(2, sourceArea, true);
  39931. this._computePixels(3, sourceArea, true);
  39932. dstOffset.x = this.leftPixels;
  39933. dstArea.width = sourceArea.width - (dstOffset.x + this.rightPixels);
  39934. dstOffset.y = this.bottomPixels;
  39935. dstArea.height = sourceArea.height - (dstOffset.y + this.topPixels);
  39936. };
  39937. /**
  39938. * Compute an area considering this thickness properties based on a given source area
  39939. * @param sourceArea the source area
  39940. * @param result the resulting area
  39941. */
  39942. PrimitiveThickness.prototype.computeArea = function (sourceArea, result) {
  39943. this._computePixels(0, sourceArea, true);
  39944. this._computePixels(1, sourceArea, true);
  39945. this._computePixels(2, sourceArea, true);
  39946. this._computePixels(3, sourceArea, true);
  39947. result.width = this.leftPixels + sourceArea.width + this.rightPixels;
  39948. result.height = this.bottomPixels + sourceArea.height + this.topPixels;
  39949. };
  39950. PrimitiveThickness.prototype.enlarge = function (sourceArea, dstOffset, enlargedArea) {
  39951. this._computePixels(0, sourceArea, true);
  39952. this._computePixels(1, sourceArea, true);
  39953. this._computePixels(2, sourceArea, true);
  39954. this._computePixels(3, sourceArea, true);
  39955. dstOffset.x = this.leftPixels;
  39956. enlargedArea.width = sourceArea.width + (dstOffset.x + this.rightPixels);
  39957. dstOffset.y = this.bottomPixels;
  39958. enlargedArea.height = sourceArea.height + (dstOffset.y + this.topPixels);
  39959. };
  39960. PrimitiveThickness.Auto = 0x1;
  39961. PrimitiveThickness.Inherit = 0x2;
  39962. PrimitiveThickness.Percentage = 0x4;
  39963. PrimitiveThickness.Pixel = 0x8;
  39964. return PrimitiveThickness;
  39965. })();
  39966. BABYLON.PrimitiveThickness = PrimitiveThickness;
  39967. /**
  39968. * Main class used for the Primitive Intersection API
  39969. */
  39970. var IntersectInfo2D = (function () {
  39971. function IntersectInfo2D() {
  39972. this.findFirstOnly = false;
  39973. this.intersectHidden = false;
  39974. this.pickPosition = BABYLON.Vector2.Zero();
  39975. }
  39976. Object.defineProperty(IntersectInfo2D.prototype, "isIntersected", {
  39977. /**
  39978. * true if at least one primitive intersected during the test
  39979. */
  39980. get: function () {
  39981. return this.intersectedPrimitives && this.intersectedPrimitives.length > 0;
  39982. },
  39983. enumerable: true,
  39984. configurable: true
  39985. });
  39986. IntersectInfo2D.prototype.isPrimIntersected = function (prim) {
  39987. for (var _i = 0, _a = this.intersectedPrimitives; _i < _a.length; _i++) {
  39988. var cur = _a[_i];
  39989. if (cur.prim === prim) {
  39990. return cur.intersectionLocation;
  39991. }
  39992. }
  39993. return null;
  39994. };
  39995. // Internals, don't use
  39996. IntersectInfo2D.prototype._exit = function (firstLevel) {
  39997. if (firstLevel) {
  39998. this._globalPickPosition = null;
  39999. }
  40000. };
  40001. return IntersectInfo2D;
  40002. })();
  40003. BABYLON.IntersectInfo2D = IntersectInfo2D;
  40004. var Prim2DBase = (function (_super) {
  40005. __extends(Prim2DBase, _super);
  40006. function Prim2DBase(settings) {
  40007. // Avoid checking every time if the object exists
  40008. if (settings == null) {
  40009. settings = {};
  40010. }
  40011. // BASE CLASS CALL
  40012. _super.call(this);
  40013. // Fetch the owner, parent. There're many ways to do it and we can end up with nothing for both
  40014. var owner;
  40015. var parent;
  40016. if (Prim2DBase._isCanvasInit) {
  40017. owner = this;
  40018. parent = null;
  40019. this._canvasPreInit(settings);
  40020. }
  40021. else {
  40022. if (settings.parent != null) {
  40023. parent = settings.parent;
  40024. owner = settings.parent.owner;
  40025. if (!owner) {
  40026. throw new Error("Parent " + parent.id + " of " + settings.id + " doesn't have a valid owner!");
  40027. }
  40028. 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)) {
  40029. 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");
  40030. }
  40031. }
  40032. }
  40033. // Fields initialization
  40034. this._layoutEngine = BABYLON.CanvasLayoutEngine.Singleton;
  40035. this._size = null; //Size.Zero();
  40036. this._scale = new BABYLON.Vector2(1, 1);
  40037. this._actualSize = null;
  40038. this._boundingSize = BABYLON.Size.Zero();
  40039. this._layoutArea = BABYLON.Size.Zero();
  40040. this._layoutAreaPos = BABYLON.Vector2.Zero();
  40041. this._marginOffset = BABYLON.Vector2.Zero();
  40042. this._paddingOffset = BABYLON.Vector2.Zero();
  40043. this._parentPaddingOffset = BABYLON.Vector2.Zero();
  40044. this._parentContentArea = BABYLON.Size.Zero();
  40045. this._lastAutoSizeArea = BABYLON.Size.Zero();
  40046. this._contentArea = new BABYLON.Size(null, null);
  40047. this._pointerEventObservable = new BABYLON.Observable();
  40048. this._boundingInfo = new BABYLON.BoundingInfo2D();
  40049. this._owner = owner;
  40050. this._parent = null;
  40051. this._margin = null;
  40052. this._padding = null;
  40053. this._marginAlignment = null;
  40054. this._id = settings.id;
  40055. this.propertyChanged = new BABYLON.Observable();
  40056. this._children = new Array();
  40057. this._localTransform = new BABYLON.Matrix();
  40058. this._globalTransform = null;
  40059. this._invGlobalTransform = null;
  40060. this._globalTransformProcessStep = 0;
  40061. this._globalTransformStep = 0;
  40062. this._renderGroup = null;
  40063. this._primLinearPosition = 0;
  40064. this._manualZOrder = null;
  40065. this._zOrder = 0;
  40066. this._zMax = 0;
  40067. this._firstZDirtyIndex = Prim2DBase._bigInt;
  40068. this._setFlags(BABYLON.SmartPropertyPrim.flagIsPickable | BABYLON.SmartPropertyPrim.flagBoundingInfoDirty | BABYLON.SmartPropertyPrim.flagActualOpacityDirty);
  40069. if (settings.opacity != null) {
  40070. this._opacity = settings.opacity;
  40071. }
  40072. else {
  40073. this._opacity = 1;
  40074. }
  40075. this._updateRenderMode();
  40076. if (settings.childrenFlatZOrder) {
  40077. this._setFlags(BABYLON.SmartPropertyPrim.flagChildrenFlatZOrder);
  40078. }
  40079. // If the parent is given, initialize the hierarchy/owner related data
  40080. if (parent != null) {
  40081. parent.addChild(this);
  40082. this._hierarchyDepth = parent._hierarchyDepth + 1;
  40083. this._patchHierarchy(parent.owner);
  40084. }
  40085. // If it's a group, detect its own states
  40086. if (this.owner && this instanceof BABYLON.Group2D) {
  40087. var group = this;
  40088. group.detectGroupStates();
  40089. }
  40090. // Time to insert children if some are specified
  40091. if (settings.children != null) {
  40092. for (var _i = 0, _a = settings.children; _i < _a.length; _i++) {
  40093. var child = _a[_i];
  40094. this.addChild(child);
  40095. // Good time to patch the hierarchy, it won't go very far if there's no need to
  40096. if (this.owner != null) {
  40097. child._patchHierarchy(this.owner);
  40098. }
  40099. }
  40100. }
  40101. if (settings.zOrder != null) {
  40102. this.zOrder = settings.zOrder;
  40103. }
  40104. // Set the model related properties
  40105. if (settings.position != null) {
  40106. this.position = settings.position;
  40107. }
  40108. else if (settings.x != null || settings.y != null) {
  40109. this.position = new BABYLON.Vector2(settings.x || 0, settings.y || 0);
  40110. }
  40111. else {
  40112. this._position = null;
  40113. }
  40114. this.rotation = (settings.rotation == null) ? 0 : settings.rotation;
  40115. if (settings.scale != null) {
  40116. this.scale = settings.scale;
  40117. }
  40118. else {
  40119. if (settings.scaleX != null) {
  40120. this.scaleX = settings.scaleX;
  40121. }
  40122. if (settings.scaleY != null) {
  40123. this.scaleY = settings.scaleY;
  40124. }
  40125. }
  40126. this.levelVisible = (settings.isVisible == null) ? true : settings.isVisible;
  40127. this.origin = settings.origin || new BABYLON.Vector2(0.5, 0.5);
  40128. // Layout Engine
  40129. if (settings.layoutEngine != null) {
  40130. if (typeof settings.layoutEngine === "string") {
  40131. var name_1 = settings.layoutEngine.toLocaleLowerCase().trim();
  40132. if (name_1 === "canvas" || name_1 === "canvaslayoutengine") {
  40133. this.layoutEngine = BABYLON.CanvasLayoutEngine.Singleton;
  40134. }
  40135. else if (name_1.indexOf("stackpanel") === 0 || name_1.indexOf("horizontalstackpanel") === 0) {
  40136. this.layoutEngine = BABYLON.StackPanelLayoutEngine.Horizontal;
  40137. }
  40138. else if (name_1.indexOf("verticalstackpanel") === 0) {
  40139. this.layoutEngine = BABYLON.StackPanelLayoutEngine.Vertical;
  40140. }
  40141. }
  40142. else if (settings.layoutEngine instanceof BABYLON.LayoutEngineBase) {
  40143. this.layoutEngine = settings.layoutEngine;
  40144. }
  40145. }
  40146. // Set the layout/margin stuffs
  40147. if (settings.marginTop) {
  40148. this.margin.setTop(settings.marginTop);
  40149. }
  40150. if (settings.marginLeft) {
  40151. this.margin.setLeft(settings.marginLeft);
  40152. }
  40153. if (settings.marginRight) {
  40154. this.margin.setRight(settings.marginRight);
  40155. }
  40156. if (settings.marginBottom) {
  40157. this.margin.setBottom(settings.marginBottom);
  40158. }
  40159. if (settings.margin) {
  40160. if (typeof settings.margin === "string") {
  40161. this.margin.fromString(settings.margin);
  40162. }
  40163. else {
  40164. this.margin.fromUniformPixels(settings.margin);
  40165. }
  40166. }
  40167. if (settings.marginHAlignment) {
  40168. this.marginAlignment.horizontal = settings.marginHAlignment;
  40169. }
  40170. if (settings.marginVAlignment) {
  40171. this.marginAlignment.vertical = settings.marginVAlignment;
  40172. }
  40173. if (settings.marginAlignment) {
  40174. this.marginAlignment.fromString(settings.marginAlignment);
  40175. }
  40176. if (settings.paddingTop) {
  40177. this.padding.setTop(settings.paddingTop);
  40178. }
  40179. if (settings.paddingLeft) {
  40180. this.padding.setLeft(settings.paddingLeft);
  40181. }
  40182. if (settings.paddingRight) {
  40183. this.padding.setRight(settings.paddingRight);
  40184. }
  40185. if (settings.paddingBottom) {
  40186. this.padding.setBottom(settings.paddingBottom);
  40187. }
  40188. if (settings.padding) {
  40189. this.padding.fromString(settings.padding);
  40190. }
  40191. // Dirty layout and positioning
  40192. this._parentLayoutDirty();
  40193. this._positioningDirty();
  40194. }
  40195. Object.defineProperty(Prim2DBase.prototype, "actionManager", {
  40196. get: function () {
  40197. if (!this._actionManager) {
  40198. this._actionManager = new BABYLON.ActionManager(this.owner.scene);
  40199. }
  40200. return this._actionManager;
  40201. },
  40202. enumerable: true,
  40203. configurable: true
  40204. });
  40205. /**
  40206. * From 'this' primitive, traverse up (from parent to parent) until the given predicate is true
  40207. * @param predicate the predicate to test on each parent
  40208. * @return the first primitive where the predicate was successful
  40209. */
  40210. Prim2DBase.prototype.traverseUp = function (predicate) {
  40211. var p = this;
  40212. while (p != null) {
  40213. if (predicate(p)) {
  40214. return p;
  40215. }
  40216. p = p._parent;
  40217. }
  40218. return null;
  40219. };
  40220. Object.defineProperty(Prim2DBase.prototype, "owner", {
  40221. /**
  40222. * Retrieve the owner Canvas2D
  40223. */
  40224. get: function () {
  40225. return this._owner;
  40226. },
  40227. enumerable: true,
  40228. configurable: true
  40229. });
  40230. Object.defineProperty(Prim2DBase.prototype, "parent", {
  40231. /**
  40232. * Get the parent primitive (can be the Canvas, only the Canvas has no parent)
  40233. */
  40234. get: function () {
  40235. return this._parent;
  40236. },
  40237. enumerable: true,
  40238. configurable: true
  40239. });
  40240. Object.defineProperty(Prim2DBase.prototype, "children", {
  40241. /**
  40242. * The array of direct children primitives
  40243. */
  40244. get: function () {
  40245. return this._children;
  40246. },
  40247. enumerable: true,
  40248. configurable: true
  40249. });
  40250. Object.defineProperty(Prim2DBase.prototype, "id", {
  40251. /**
  40252. * The identifier of this primitive, may not be unique, it's for information purpose only
  40253. */
  40254. get: function () {
  40255. return this._id;
  40256. },
  40257. enumerable: true,
  40258. configurable: true
  40259. });
  40260. Object.defineProperty(Prim2DBase.prototype, "actualPosition", {
  40261. get: function () {
  40262. if (this._actualPosition != null) {
  40263. return this._actualPosition;
  40264. }
  40265. if (this._position != null) {
  40266. return this._position;
  40267. }
  40268. // At least return 0,0, we can't return null on actualPosition
  40269. return Prim2DBase._nullPosition;
  40270. },
  40271. /**
  40272. * DO NOT INVOKE for internal purpose only
  40273. */
  40274. set: function (val) {
  40275. this._actualPosition = val;
  40276. },
  40277. enumerable: true,
  40278. configurable: true
  40279. });
  40280. Object.defineProperty(Prim2DBase.prototype, "actualX", {
  40281. /**
  40282. * Shortcut to actualPosition.x
  40283. */
  40284. get: function () {
  40285. return this.actualPosition.x;
  40286. },
  40287. enumerable: true,
  40288. configurable: true
  40289. });
  40290. Object.defineProperty(Prim2DBase.prototype, "actualY", {
  40291. /**
  40292. * Shortcut to actualPosition.y
  40293. */
  40294. get: function () {
  40295. return this.actualPosition.y;
  40296. },
  40297. enumerable: true,
  40298. configurable: true
  40299. });
  40300. Object.defineProperty(Prim2DBase.prototype, "position", {
  40301. /**
  40302. * Position of the primitive, relative to its parent.
  40303. * BEWARE: if you change only position.x or y it won't trigger a property change and you won't have the expected behavior.
  40304. * Use this property to set a new Vector2 object, otherwise to change only the x/y use Prim2DBase.x or y properties.
  40305. * Setting this property may have no effect is specific alignment are in effect.
  40306. */
  40307. get: function () {
  40308. return this._position || Prim2DBase._nullPosition;
  40309. },
  40310. set: function (value) {
  40311. if (!this._checkPositionChange()) {
  40312. return;
  40313. }
  40314. this._position = value;
  40315. this.markAsDirty("actualPosition");
  40316. },
  40317. enumerable: true,
  40318. configurable: true
  40319. });
  40320. Object.defineProperty(Prim2DBase.prototype, "x", {
  40321. /**
  40322. * Direct access to the position.x value of the primitive
  40323. * Use this property when you only want to change one component of the position property
  40324. */
  40325. get: function () {
  40326. if (!this._position) {
  40327. return null;
  40328. }
  40329. return this._position.x;
  40330. },
  40331. set: function (value) {
  40332. if (!this._checkPositionChange()) {
  40333. return;
  40334. }
  40335. if (!this._position) {
  40336. this._position = BABYLON.Vector2.Zero();
  40337. }
  40338. if (this._position.x === value) {
  40339. return;
  40340. }
  40341. this._position.x = value;
  40342. this.markAsDirty("position");
  40343. this.markAsDirty("actualPosition");
  40344. },
  40345. enumerable: true,
  40346. configurable: true
  40347. });
  40348. Object.defineProperty(Prim2DBase.prototype, "y", {
  40349. /**
  40350. * Direct access to the position.y value of the primitive
  40351. * Use this property when you only want to change one component of the position property
  40352. */
  40353. get: function () {
  40354. if (!this._position) {
  40355. return null;
  40356. }
  40357. return this._position.y;
  40358. },
  40359. set: function (value) {
  40360. if (!this._checkPositionChange()) {
  40361. return;
  40362. }
  40363. if (!this._position) {
  40364. this._position = BABYLON.Vector2.Zero();
  40365. }
  40366. if (this._position.y === value) {
  40367. return;
  40368. }
  40369. this._position.y = value;
  40370. this.markAsDirty("position");
  40371. this.markAsDirty("actualPosition");
  40372. },
  40373. enumerable: true,
  40374. configurable: true
  40375. });
  40376. Object.defineProperty(Prim2DBase.prototype, "size", {
  40377. /**
  40378. * Size of the primitive or its bounding area
  40379. * BEWARE: if you change only size.width or height it won't trigger a property change and you won't have the expected behavior.
  40380. * Use this property to set a new Size object, otherwise to change only the width/height use Prim2DBase.width or height properties.
  40381. */
  40382. get: function () {
  40383. if (!this._size || this._size.width == null || this._size.height == null) {
  40384. if (Prim2DBase.boundinbBoxReentrency) {
  40385. return Prim2DBase.nullSize;
  40386. }
  40387. if (!this._isFlagSet(BABYLON.SmartPropertyPrim.flagBoundingInfoDirty)) {
  40388. return this._boundingSize;
  40389. }
  40390. Prim2DBase.boundinbBoxReentrency = true;
  40391. var b = this.boundingInfo;
  40392. Prim2DBase.boundinbBoxReentrency = false;
  40393. return this._boundingSize;
  40394. }
  40395. return this._size;
  40396. },
  40397. set: function (value) {
  40398. this._size = value;
  40399. },
  40400. enumerable: true,
  40401. configurable: true
  40402. });
  40403. Object.defineProperty(Prim2DBase.prototype, "width", {
  40404. /**
  40405. * Direct access to the size.width value of the primitive
  40406. * Use this property when you only want to change one component of the size property
  40407. */
  40408. get: function () {
  40409. if (!this.size) {
  40410. return null;
  40411. }
  40412. return this.size.width;
  40413. },
  40414. set: function (value) {
  40415. if (!this.size) {
  40416. this.size = new BABYLON.Size(value, 0);
  40417. return;
  40418. }
  40419. if (this.size.width === value) {
  40420. return;
  40421. }
  40422. this.size.width = value;
  40423. this.markAsDirty("size");
  40424. this._positioningDirty();
  40425. },
  40426. enumerable: true,
  40427. configurable: true
  40428. });
  40429. Object.defineProperty(Prim2DBase.prototype, "height", {
  40430. /**
  40431. * Direct access to the size.height value of the primitive
  40432. * Use this property when you only want to change one component of the size property
  40433. */
  40434. get: function () {
  40435. if (!this.size) {
  40436. return null;
  40437. }
  40438. return this.size.height;
  40439. },
  40440. set: function (value) {
  40441. if (!this.size) {
  40442. this.size = new BABYLON.Size(0, value);
  40443. return;
  40444. }
  40445. if (this.size.height === value) {
  40446. return;
  40447. }
  40448. this.size.height = value;
  40449. this.markAsDirty("size");
  40450. this._positioningDirty();
  40451. },
  40452. enumerable: true,
  40453. configurable: true
  40454. });
  40455. Object.defineProperty(Prim2DBase.prototype, "rotation", {
  40456. get: function () {
  40457. return this._rotation;
  40458. },
  40459. set: function (value) {
  40460. this._rotation = value;
  40461. },
  40462. enumerable: true,
  40463. configurable: true
  40464. });
  40465. Object.defineProperty(Prim2DBase.prototype, "scale", {
  40466. get: function () {
  40467. return this._scale.x;
  40468. },
  40469. set: function (value) {
  40470. this._scale.x = this._scale.y = value;
  40471. },
  40472. enumerable: true,
  40473. configurable: true
  40474. });
  40475. Object.defineProperty(Prim2DBase.prototype, "actualSize", {
  40476. /**
  40477. * Return the size of the primitive as it's being rendered into the target.
  40478. * 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.
  40479. * BEWARE: don't use the setter, it's for internal purpose only
  40480. * Note to implementers: you have to override this property and declare if necessary a @xxxxInstanceLevel decorator
  40481. */
  40482. get: function () {
  40483. if (this._actualSize) {
  40484. return this._actualSize;
  40485. }
  40486. return this._size;
  40487. },
  40488. set: function (value) {
  40489. if (this._actualSize.equals(value)) {
  40490. return;
  40491. }
  40492. this._actualSize = value;
  40493. },
  40494. enumerable: true,
  40495. configurable: true
  40496. });
  40497. Object.defineProperty(Prim2DBase.prototype, "actualZOffset", {
  40498. get: function () {
  40499. if (this._manualZOrder != null) {
  40500. return this._manualZOrder;
  40501. }
  40502. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagZOrderDirty)) {
  40503. this._updateZOrder();
  40504. }
  40505. return (1 - this._zOrder);
  40506. },
  40507. enumerable: true,
  40508. configurable: true
  40509. });
  40510. Object.defineProperty(Prim2DBase.prototype, "minSize", {
  40511. /**
  40512. * Get or set the minimal size the Layout Engine should respect when computing the primitive's actualSize.
  40513. * The Primitive's size won't be less than specified.
  40514. * The default value depends of the Primitive type
  40515. */
  40516. get: function () {
  40517. return this._minSize;
  40518. },
  40519. set: function (value) {
  40520. if (this._minSize && value && this._minSize.equals(value)) {
  40521. return;
  40522. }
  40523. this._minSize = value;
  40524. this._parentLayoutDirty();
  40525. },
  40526. enumerable: true,
  40527. configurable: true
  40528. });
  40529. Object.defineProperty(Prim2DBase.prototype, "maxSize", {
  40530. /**
  40531. * Get or set the maximal size the Layout Engine should respect when computing the primitive's actualSize.
  40532. * The Primitive's size won't be more than specified.
  40533. * The default value depends of the Primitive type
  40534. */
  40535. get: function () {
  40536. return this._maxSize;
  40537. },
  40538. set: function (value) {
  40539. if (this._maxSize && value && this._maxSize.equals(value)) {
  40540. return;
  40541. }
  40542. this._maxSize = value;
  40543. this._parentLayoutDirty();
  40544. },
  40545. enumerable: true,
  40546. configurable: true
  40547. });
  40548. Object.defineProperty(Prim2DBase.prototype, "origin", {
  40549. /**
  40550. * The origin defines the normalized coordinate of the center of the primitive, from the bottom/left corner.
  40551. * The origin is used only to compute transformation of the primitive, it has no meaning in the primitive local frame of reference
  40552. * For instance:
  40553. * 0,0 means the center is bottom/left. Which is the default for Canvas2D instances
  40554. * 0.5,0.5 means the center is at the center of the primitive, which is default of all types of Primitives
  40555. * 0,1 means the center is top/left
  40556. * @returns The normalized center.
  40557. */
  40558. get: function () {
  40559. return this._origin;
  40560. },
  40561. set: function (value) {
  40562. this._origin = value;
  40563. },
  40564. enumerable: true,
  40565. configurable: true
  40566. });
  40567. Object.defineProperty(Prim2DBase.prototype, "levelVisible", {
  40568. get: function () {
  40569. return this._isFlagSet(BABYLON.SmartPropertyPrim.flagLevelVisible);
  40570. },
  40571. set: function (value) {
  40572. this._changeFlags(BABYLON.SmartPropertyPrim.flagLevelVisible, value);
  40573. },
  40574. enumerable: true,
  40575. configurable: true
  40576. });
  40577. Object.defineProperty(Prim2DBase.prototype, "isVisible", {
  40578. get: function () {
  40579. return this._isFlagSet(BABYLON.SmartPropertyPrim.flagIsVisible);
  40580. },
  40581. set: function (value) {
  40582. this._changeFlags(BABYLON.SmartPropertyPrim.flagIsVisible, value);
  40583. },
  40584. enumerable: true,
  40585. configurable: true
  40586. });
  40587. Object.defineProperty(Prim2DBase.prototype, "zOrder", {
  40588. get: function () {
  40589. return this._manualZOrder;
  40590. },
  40591. set: function (value) {
  40592. if (this._manualZOrder === value) {
  40593. return;
  40594. }
  40595. this._manualZOrder = value;
  40596. this.onZOrderChanged();
  40597. if (this._actualZOrderChangedObservable && this._actualZOrderChangedObservable.hasObservers()) {
  40598. this._actualZOrderChangedObservable.notifyObservers(value);
  40599. }
  40600. },
  40601. enumerable: true,
  40602. configurable: true
  40603. });
  40604. Object.defineProperty(Prim2DBase.prototype, "isManualZOrder", {
  40605. get: function () {
  40606. return this._manualZOrder != null;
  40607. },
  40608. enumerable: true,
  40609. configurable: true
  40610. });
  40611. Object.defineProperty(Prim2DBase.prototype, "margin", {
  40612. get: function () {
  40613. var _this = this;
  40614. if (!this._margin) {
  40615. this._margin = new PrimitiveThickness(function () {
  40616. if (!_this.parent) {
  40617. return null;
  40618. }
  40619. return _this.parent.margin;
  40620. }, function () { return _this._positioningDirty(); });
  40621. }
  40622. return this._margin;
  40623. },
  40624. enumerable: true,
  40625. configurable: true
  40626. });
  40627. Object.defineProperty(Prim2DBase.prototype, "_hasMargin", {
  40628. get: function () {
  40629. return (this._margin !== null) || (this._marginAlignment !== null);
  40630. },
  40631. enumerable: true,
  40632. configurable: true
  40633. });
  40634. Object.defineProperty(Prim2DBase.prototype, "padding", {
  40635. get: function () {
  40636. var _this = this;
  40637. if (!this._padding) {
  40638. this._padding = new PrimitiveThickness(function () {
  40639. if (!_this.parent) {
  40640. return null;
  40641. }
  40642. return _this.parent.padding;
  40643. }, function () { return _this._positioningDirty(); });
  40644. }
  40645. return this._padding;
  40646. },
  40647. enumerable: true,
  40648. configurable: true
  40649. });
  40650. Object.defineProperty(Prim2DBase.prototype, "_hasPadding", {
  40651. get: function () {
  40652. return this._padding !== null;
  40653. },
  40654. enumerable: true,
  40655. configurable: true
  40656. });
  40657. Object.defineProperty(Prim2DBase.prototype, "marginAlignment", {
  40658. get: function () {
  40659. var _this = this;
  40660. if (!this._marginAlignment) {
  40661. this._marginAlignment = new PrimitiveAlignment(function () { return _this._positioningDirty(); });
  40662. }
  40663. return this._marginAlignment;
  40664. },
  40665. enumerable: true,
  40666. configurable: true
  40667. });
  40668. Object.defineProperty(Prim2DBase.prototype, "opacity", {
  40669. get: function () {
  40670. return this._opacity;
  40671. },
  40672. set: function (value) {
  40673. if (value < 0) {
  40674. value = 0;
  40675. }
  40676. else if (value > 1) {
  40677. value = 1;
  40678. }
  40679. if (this._opacity === value) {
  40680. return;
  40681. }
  40682. this._opacity = value;
  40683. this._updateRenderMode();
  40684. this._setFlags(BABYLON.SmartPropertyPrim.flagActualOpacityDirty);
  40685. this._spreadActualOpacityChanged();
  40686. },
  40687. enumerable: true,
  40688. configurable: true
  40689. });
  40690. Object.defineProperty(Prim2DBase.prototype, "scaleX", {
  40691. get: function () {
  40692. return this._scale.x;
  40693. },
  40694. set: function (value) {
  40695. this._scale.x = value;
  40696. },
  40697. enumerable: true,
  40698. configurable: true
  40699. });
  40700. Object.defineProperty(Prim2DBase.prototype, "scaleY", {
  40701. get: function () {
  40702. return this._scale.y;
  40703. },
  40704. set: function (value) {
  40705. this._scale.y = value;
  40706. },
  40707. enumerable: true,
  40708. configurable: true
  40709. });
  40710. Object.defineProperty(Prim2DBase.prototype, "actualOpacity", {
  40711. get: function () {
  40712. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagActualOpacityDirty)) {
  40713. var cur = this.parent;
  40714. var op = this.opacity;
  40715. while (cur) {
  40716. op *= cur.opacity;
  40717. cur = cur.parent;
  40718. }
  40719. this._actualOpacity = op;
  40720. this._clearFlags(BABYLON.SmartPropertyPrim.flagActualOpacityDirty);
  40721. }
  40722. return this._actualOpacity;
  40723. },
  40724. enumerable: true,
  40725. configurable: true
  40726. });
  40727. Object.defineProperty(Prim2DBase.prototype, "layoutEngine", {
  40728. /**
  40729. * Get/set the layout engine to use for this primitive.
  40730. * The default layout engine is the CanvasLayoutEngine.
  40731. */
  40732. get: function () {
  40733. if (!this._layoutEngine) {
  40734. this._layoutEngine = BABYLON.CanvasLayoutEngine.Singleton;
  40735. }
  40736. return this._layoutEngine;
  40737. },
  40738. set: function (value) {
  40739. if (this._layoutEngine === value) {
  40740. return;
  40741. }
  40742. this._changeLayoutEngine(value);
  40743. },
  40744. enumerable: true,
  40745. configurable: true
  40746. });
  40747. Object.defineProperty(Prim2DBase.prototype, "layoutArea", {
  40748. /**
  40749. * Get/set the layout are of this primitive.
  40750. * The Layout area is the zone allocated by the Layout Engine for this particular primitive. Margins/Alignment will be computed based on this area.
  40751. * The setter should only be called by a Layout Engine class.
  40752. */
  40753. get: function () {
  40754. return this._layoutArea;
  40755. },
  40756. set: function (val) {
  40757. if (this._layoutArea.equals(val)) {
  40758. return;
  40759. }
  40760. this._positioningDirty();
  40761. this._layoutArea = val;
  40762. },
  40763. enumerable: true,
  40764. configurable: true
  40765. });
  40766. Object.defineProperty(Prim2DBase.prototype, "layoutAreaPos", {
  40767. /**
  40768. * Get/set the layout area position (relative to the parent primitive).
  40769. * The setter should only be called by a Layout Engine class.
  40770. */
  40771. get: function () {
  40772. return this._layoutAreaPos;
  40773. },
  40774. set: function (val) {
  40775. if (this._layoutAreaPos.equals(val)) {
  40776. return;
  40777. }
  40778. this._positioningDirty();
  40779. this._layoutAreaPos = val;
  40780. },
  40781. enumerable: true,
  40782. configurable: true
  40783. });
  40784. Object.defineProperty(Prim2DBase.prototype, "isPickable", {
  40785. /**
  40786. * Define if the Primitive can be subject to intersection test or not (default is true)
  40787. */
  40788. get: function () {
  40789. return this._isFlagSet(BABYLON.SmartPropertyPrim.flagIsPickable);
  40790. },
  40791. set: function (value) {
  40792. this._changeFlags(BABYLON.SmartPropertyPrim.flagIsPickable, value);
  40793. },
  40794. enumerable: true,
  40795. configurable: true
  40796. });
  40797. Object.defineProperty(Prim2DBase.prototype, "hierarchyDepth", {
  40798. /**
  40799. * Return the depth level of the Primitive into the Canvas' Graph. A Canvas will be 0, its direct children 1, and so on.
  40800. */
  40801. get: function () {
  40802. return this._hierarchyDepth;
  40803. },
  40804. enumerable: true,
  40805. configurable: true
  40806. });
  40807. Object.defineProperty(Prim2DBase.prototype, "renderGroup", {
  40808. /**
  40809. * Retrieve the Group that is responsible to render this primitive
  40810. */
  40811. get: function () {
  40812. return this._renderGroup;
  40813. },
  40814. enumerable: true,
  40815. configurable: true
  40816. });
  40817. Object.defineProperty(Prim2DBase.prototype, "globalTransform", {
  40818. /**
  40819. * Get the global transformation matrix of the primitive
  40820. */
  40821. get: function () {
  40822. return this._globalTransform;
  40823. },
  40824. enumerable: true,
  40825. configurable: true
  40826. });
  40827. /**
  40828. * return the global position of the primitive, relative to its canvas
  40829. */
  40830. Prim2DBase.prototype.getGlobalPosition = function () {
  40831. var v = new BABYLON.Vector2(0, 0);
  40832. this.getGlobalPositionByRef(v);
  40833. return v;
  40834. };
  40835. /**
  40836. * return the global position of the primitive, relative to its canvas
  40837. * @param v the valid Vector2 object where the global position will be stored
  40838. */
  40839. Prim2DBase.prototype.getGlobalPositionByRef = function (v) {
  40840. v.x = this.globalTransform.m[12];
  40841. v.y = this.globalTransform.m[13];
  40842. };
  40843. Object.defineProperty(Prim2DBase.prototype, "invGlobalTransform", {
  40844. /**
  40845. * Get invert of the global transformation matrix of the primitive
  40846. */
  40847. get: function () {
  40848. return this._invGlobalTransform;
  40849. },
  40850. enumerable: true,
  40851. configurable: true
  40852. });
  40853. Object.defineProperty(Prim2DBase.prototype, "localTransform", {
  40854. /**
  40855. * Get the local transformation of the primitive
  40856. */
  40857. get: function () {
  40858. this._updateLocalTransform();
  40859. return this._localTransform;
  40860. },
  40861. enumerable: true,
  40862. configurable: true
  40863. });
  40864. Object.defineProperty(Prim2DBase.prototype, "boundingInfo", {
  40865. /**
  40866. * Get the boundingInfo associated to the primitive and its children.
  40867. * The value is supposed to be always up to date
  40868. */
  40869. get: function () {
  40870. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagBoundingInfoDirty)) {
  40871. if (this.owner) {
  40872. this.owner.boundingInfoRecomputeCounter.addCount(1, false);
  40873. }
  40874. if (this.isSizedByContent) {
  40875. this._boundingInfo.clear();
  40876. }
  40877. else {
  40878. this._boundingInfo.copyFrom(this.levelBoundingInfo);
  40879. }
  40880. var bi = this._boundingInfo;
  40881. var tps = new BABYLON.BoundingInfo2D();
  40882. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  40883. var curChild = _a[_i];
  40884. curChild.boundingInfo.transformToRef(curChild.localTransform, tps);
  40885. bi.unionToRef(tps, bi);
  40886. }
  40887. this._boundingInfo.maxToRef(Prim2DBase._bMax);
  40888. 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);
  40889. this._clearFlags(BABYLON.SmartPropertyPrim.flagBoundingInfoDirty);
  40890. }
  40891. return this._boundingInfo;
  40892. },
  40893. enumerable: true,
  40894. configurable: true
  40895. });
  40896. Object.defineProperty(Prim2DBase.prototype, "isSizeAuto", {
  40897. /**
  40898. * Determine if the size is automatically computed or fixed because manually specified.
  40899. * Use the actualSize property to get the final/real size of the primitive
  40900. * @returns true if the size is automatically computed, false if it were manually specified.
  40901. */
  40902. get: function () {
  40903. return this._size == null;
  40904. },
  40905. enumerable: true,
  40906. configurable: true
  40907. });
  40908. Object.defineProperty(Prim2DBase.prototype, "isSizedByContent", {
  40909. /**
  40910. * Return true if this prim has an auto size which is set by the children's global bounding box
  40911. */
  40912. get: function () {
  40913. return (this._size == null) && (this._children.length > 0);
  40914. },
  40915. enumerable: true,
  40916. configurable: true
  40917. });
  40918. Object.defineProperty(Prim2DBase.prototype, "isPositionAuto", {
  40919. /**
  40920. * Determine if the position is automatically computed or fixed because manually specified.
  40921. * Use the actualPosition property to get the final/real position of the primitive
  40922. * @returns true if the position is automatically computed, false if it were manually specified.
  40923. */
  40924. get: function () {
  40925. return this._position == null;
  40926. },
  40927. enumerable: true,
  40928. configurable: true
  40929. });
  40930. Object.defineProperty(Prim2DBase.prototype, "pointerEventObservable", {
  40931. /**
  40932. * Interaction with the primitive can be create using this Observable. See the PrimitivePointerInfo class for more information
  40933. */
  40934. get: function () {
  40935. return this._pointerEventObservable;
  40936. },
  40937. enumerable: true,
  40938. configurable: true
  40939. });
  40940. Object.defineProperty(Prim2DBase.prototype, "zActualOrderChangedObservable", {
  40941. get: function () {
  40942. if (!this._actualZOrderChangedObservable) {
  40943. this._actualZOrderChangedObservable = new BABYLON.Observable();
  40944. }
  40945. return this._actualZOrderChangedObservable;
  40946. },
  40947. enumerable: true,
  40948. configurable: true
  40949. });
  40950. Prim2DBase.prototype.findById = function (id) {
  40951. if (this._id === id) {
  40952. return this;
  40953. }
  40954. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  40955. var child = _a[_i];
  40956. var r = child.findById(id);
  40957. if (r != null) {
  40958. return r;
  40959. }
  40960. }
  40961. };
  40962. Prim2DBase.prototype.onZOrderChanged = function () {
  40963. };
  40964. Prim2DBase.prototype.levelIntersect = function (intersectInfo) {
  40965. return false;
  40966. };
  40967. /**
  40968. * Capture all the Events of the given PointerId for this primitive.
  40969. * Don't forget to call releasePointerEventsCapture when done.
  40970. * @param pointerId the Id of the pointer to capture the events from.
  40971. */
  40972. Prim2DBase.prototype.setPointerEventCapture = function (pointerId) {
  40973. return this.owner._setPointerCapture(pointerId, this);
  40974. };
  40975. /**
  40976. * Release a captured pointer made with setPointerEventCapture.
  40977. * @param pointerId the Id of the pointer to release the capture from.
  40978. */
  40979. Prim2DBase.prototype.releasePointerEventsCapture = function (pointerId) {
  40980. return this.owner._releasePointerCapture(pointerId, this);
  40981. };
  40982. /**
  40983. * Make an intersection test with the primitive, all inputs/outputs are stored in the IntersectInfo2D class, see its documentation for more information.
  40984. * @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.
  40985. */
  40986. Prim2DBase.prototype.intersect = function (intersectInfo) {
  40987. if (!intersectInfo) {
  40988. return false;
  40989. }
  40990. // If this is null it means this method is call for the first level, initialize stuffs
  40991. var firstLevel = !intersectInfo._globalPickPosition;
  40992. if (firstLevel) {
  40993. // 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).
  40994. intersectInfo._globalPickPosition = BABYLON.Vector2.Zero();
  40995. BABYLON.Vector2.TransformToRef(intersectInfo.pickPosition, this.globalTransform, intersectInfo._globalPickPosition);
  40996. intersectInfo._localPickPosition = intersectInfo.pickPosition.clone();
  40997. intersectInfo.intersectedPrimitives = new Array();
  40998. intersectInfo.topMostIntersectedPrimitive = null;
  40999. }
  41000. if (!intersectInfo.intersectHidden && !this.isVisible) {
  41001. return false;
  41002. }
  41003. // Fast rejection test with boundingInfo
  41004. if (this.isPickable && !this.boundingInfo.doesIntersect(intersectInfo._localPickPosition)) {
  41005. // Important to call this before each return to allow a good recursion next time this intersectInfo is reused
  41006. intersectInfo._exit(firstLevel);
  41007. return false;
  41008. }
  41009. // We hit the boundingInfo that bounds this primitive and its children, now we have to test on the primitive of this level
  41010. var levelIntersectRes = false;
  41011. if (this.isPickable) {
  41012. levelIntersectRes = this.levelIntersect(intersectInfo);
  41013. if (levelIntersectRes) {
  41014. var pii = new PrimitiveIntersectedInfo(this, intersectInfo._localPickPosition.clone());
  41015. intersectInfo.intersectedPrimitives.push(pii);
  41016. if (!intersectInfo.topMostIntersectedPrimitive || (intersectInfo.topMostIntersectedPrimitive.prim.actualZOffset > pii.prim.actualZOffset)) {
  41017. intersectInfo.topMostIntersectedPrimitive = pii;
  41018. }
  41019. // If we must stop at the first intersection, we're done, quit!
  41020. if (intersectInfo.findFirstOnly) {
  41021. intersectInfo._exit(firstLevel);
  41022. return true;
  41023. }
  41024. }
  41025. }
  41026. // Recurse to children if needed
  41027. if (!levelIntersectRes || !intersectInfo.findFirstOnly) {
  41028. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  41029. var curChild = _a[_i];
  41030. // Don't test primitive not pick able or if it's hidden and we don't test hidden ones
  41031. if (!curChild.isPickable || (!intersectInfo.intersectHidden && !curChild.isVisible)) {
  41032. continue;
  41033. }
  41034. // Must compute the localPickLocation for the children level
  41035. BABYLON.Vector2.TransformToRef(intersectInfo._globalPickPosition, curChild.invGlobalTransform, intersectInfo._localPickPosition);
  41036. // If we got an intersection with the child and we only need to find the first one, quit!
  41037. if (curChild.intersect(intersectInfo) && intersectInfo.findFirstOnly) {
  41038. intersectInfo._exit(firstLevel);
  41039. return true;
  41040. }
  41041. }
  41042. }
  41043. intersectInfo._exit(firstLevel);
  41044. return intersectInfo.isIntersected;
  41045. };
  41046. Prim2DBase.prototype.moveChild = function (child, previous) {
  41047. if (child.parent !== this) {
  41048. return false;
  41049. }
  41050. var childIndex = this._children.indexOf(child);
  41051. var prevIndex = previous ? this._children.indexOf(previous) : -1;
  41052. if (!this._isFlagSet(BABYLON.SmartPropertyPrim.flagChildrenFlatZOrder)) {
  41053. this._setFlags(BABYLON.SmartPropertyPrim.flagZOrderDirty);
  41054. this._firstZDirtyIndex = Math.min(this._firstZDirtyIndex, prevIndex + 1);
  41055. }
  41056. this._children.splice(prevIndex + 1, 0, this._children.splice(childIndex, 1)[0]);
  41057. };
  41058. Prim2DBase.prototype.addChild = function (child) {
  41059. child._parent = this;
  41060. this._boundingBoxDirty();
  41061. var flat = this._isFlagSet(BABYLON.SmartPropertyPrim.flagChildrenFlatZOrder);
  41062. if (flat) {
  41063. child._setFlags(BABYLON.SmartPropertyPrim.flagChildrenFlatZOrder);
  41064. child._setZOrder(this._zOrder, true);
  41065. child._zMax = this._zOrder;
  41066. }
  41067. else {
  41068. this._setFlags(BABYLON.SmartPropertyPrim.flagZOrderDirty);
  41069. }
  41070. var length = this._children.push(child);
  41071. this._firstZDirtyIndex = Math.min(this._firstZDirtyIndex, length - 1);
  41072. };
  41073. /**
  41074. * Dispose the primitive, remove it from its parent.
  41075. */
  41076. Prim2DBase.prototype.dispose = function () {
  41077. if (!_super.prototype.dispose.call(this)) {
  41078. return false;
  41079. }
  41080. if (this._actionManager) {
  41081. this._actionManager.dispose();
  41082. this._actionManager = null;
  41083. }
  41084. // If there's a parent, remove this object from its parent list
  41085. if (this._parent) {
  41086. var i = this._parent._children.indexOf(this);
  41087. if (i !== undefined) {
  41088. this._parent._children.splice(i, 1);
  41089. }
  41090. this._parent = null;
  41091. }
  41092. // Recurse dispose to children
  41093. if (this._children) {
  41094. while (this._children.length > 0) {
  41095. this._children[this._children.length - 1].dispose();
  41096. }
  41097. }
  41098. return true;
  41099. };
  41100. Prim2DBase.prototype.onPrimBecomesDirty = function () {
  41101. if (this._renderGroup && !this._isFlagSet(BABYLON.SmartPropertyPrim.flagPrimInDirtyList)) {
  41102. this._renderGroup._addPrimToDirtyList(this);
  41103. this._setFlags(BABYLON.SmartPropertyPrim.flagPrimInDirtyList);
  41104. }
  41105. };
  41106. Prim2DBase.prototype._needPrepare = function () {
  41107. return this._areSomeFlagsSet(BABYLON.SmartPropertyPrim.flagVisibilityChanged | BABYLON.SmartPropertyPrim.flagModelDirty) || (this._instanceDirtyFlags !== 0) || (this._globalTransformProcessStep !== this._globalTransformStep);
  41108. };
  41109. Prim2DBase.prototype._prepareRender = function (context) {
  41110. this._prepareRenderPre(context);
  41111. this._prepareRenderPost(context);
  41112. };
  41113. Prim2DBase.prototype._prepareRenderPre = function (context) {
  41114. };
  41115. Prim2DBase.prototype._prepareRenderPost = function (context) {
  41116. // Don't recurse if it's a renderable group, the content will be processed by the group itself
  41117. if (this instanceof BABYLON.Group2D) {
  41118. var self = this;
  41119. if (self.isRenderableGroup) {
  41120. return;
  41121. }
  41122. }
  41123. // Check if we need to recurse the prepare to children primitives
  41124. // - must have children
  41125. // - the global transform of this level have changed, or
  41126. // - the visible state of primitive has changed
  41127. if (this._children.length > 0 && ((this._globalTransformProcessStep !== this._globalTransformStep) ||
  41128. this.checkPropertiesDirty(Prim2DBase.isVisibleProperty.flagId))) {
  41129. this._children.forEach(function (c) {
  41130. // As usual stop the recursion if we meet a renderable group
  41131. if (!(c instanceof BABYLON.Group2D && c.isRenderableGroup)) {
  41132. c._prepareRender(context);
  41133. }
  41134. });
  41135. }
  41136. // Finally reset the dirty flags as we've processed everything
  41137. this._clearFlags(BABYLON.SmartPropertyPrim.flagModelDirty);
  41138. this._instanceDirtyFlags = 0;
  41139. };
  41140. Prim2DBase.prototype._canvasPreInit = function (settings) {
  41141. };
  41142. Prim2DBase.CheckParent = function (parent) {
  41143. //if (!Prim2DBase._isCanvasInit && !parent) {
  41144. // 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)");
  41145. //}
  41146. };
  41147. Prim2DBase.prototype.updateCachedStatesOf = function (list, recurse) {
  41148. for (var _i = 0; _i < list.length; _i++) {
  41149. var cur = list[_i];
  41150. cur.updateCachedStates(recurse);
  41151. }
  41152. };
  41153. Prim2DBase.prototype._parentLayoutDirty = function () {
  41154. if (!this._parent || this._parent.isDisposed) {
  41155. return;
  41156. }
  41157. this._parent._setLayoutDirty();
  41158. };
  41159. Prim2DBase.prototype._setLayoutDirty = function () {
  41160. this.onPrimBecomesDirty();
  41161. this._setFlags(BABYLON.SmartPropertyPrim.flagLayoutDirty);
  41162. };
  41163. Prim2DBase.prototype._checkPositionChange = function () {
  41164. if (this.parent && this.parent.layoutEngine.isChildPositionAllowed === false) {
  41165. console.log("Can't manually set the position of " + this.id + ", the Layout Engine of its parent doesn't allow it");
  41166. return false;
  41167. }
  41168. return true;
  41169. };
  41170. Prim2DBase.prototype._positioningDirty = function () {
  41171. this.onPrimBecomesDirty();
  41172. this._setFlags(BABYLON.SmartPropertyPrim.flagPositioningDirty);
  41173. };
  41174. Prim2DBase.prototype._spreadActualOpacityChanged = function () {
  41175. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  41176. var child = _a[_i];
  41177. child._setFlags(BABYLON.SmartPropertyPrim.flagActualOpacityDirty);
  41178. child._spreadActualOpacityChanged();
  41179. }
  41180. };
  41181. Prim2DBase.prototype._changeLayoutEngine = function (engine) {
  41182. this._layoutEngine = engine;
  41183. };
  41184. Prim2DBase.prototype._updateLocalTransform = function () {
  41185. var tflags = Prim2DBase.actualPositionProperty.flagId | Prim2DBase.rotationProperty.flagId | Prim2DBase.scaleProperty.flagId | Prim2DBase.scaleXProperty.flagId | Prim2DBase.scaleYProperty.flagId | Prim2DBase.originProperty.flagId;
  41186. if (this.checkPropertiesDirty(tflags)) {
  41187. if (this.owner) {
  41188. this.owner.addupdateLocalTransformCounter(1);
  41189. }
  41190. var rot = BABYLON.Quaternion.RotationAxis(new BABYLON.Vector3(0, 0, 1), this._rotation);
  41191. var local;
  41192. var pos = this.position;
  41193. if (this._origin.x === 0 && this._origin.y === 0) {
  41194. local = BABYLON.Matrix.Compose(new BABYLON.Vector3(this._scale.x, this._scale.y, 1), rot, new BABYLON.Vector3(pos.x, pos.y, 0));
  41195. this._localTransform = local;
  41196. }
  41197. else {
  41198. // -Origin offset
  41199. var as = this.actualSize;
  41200. BABYLON.Matrix.TranslationToRef((-as.width * this._origin.x), (-as.height * this._origin.y), 0, Prim2DBase._t0);
  41201. // -Origin * rotation
  41202. rot.toRotationMatrix(Prim2DBase._t1);
  41203. Prim2DBase._t0.multiplyToRef(Prim2DBase._t1, Prim2DBase._t2);
  41204. // -Origin * rotation * scale
  41205. BABYLON.Matrix.ScalingToRef(this._scale.x, this._scale.y, 1, Prim2DBase._t0);
  41206. Prim2DBase._t2.multiplyToRef(Prim2DBase._t0, Prim2DBase._t1);
  41207. // -Origin * rotation * scale * (Origin + Position)
  41208. BABYLON.Matrix.TranslationToRef((as.width * this._origin.x) + pos.x, (as.height * this._origin.y) + pos.y, 0, Prim2DBase._t2);
  41209. Prim2DBase._t1.multiplyToRef(Prim2DBase._t2, this._localTransform);
  41210. }
  41211. this.clearPropertiesDirty(tflags);
  41212. return true;
  41213. }
  41214. return false;
  41215. };
  41216. Prim2DBase.prototype.updateCachedStates = function (recurse) {
  41217. if (this.isDisposed) {
  41218. return;
  41219. }
  41220. this.owner.addCachedGroupRenderCounter(1);
  41221. // Check if the parent is synced
  41222. if (this._parent && ((this._parent._globalTransformProcessStep !== this.owner._globalTransformProcessStep) || this._parent._areSomeFlagsSet(BABYLON.SmartPropertyPrim.flagLayoutDirty | BABYLON.SmartPropertyPrim.flagPositioningDirty | BABYLON.SmartPropertyPrim.flagZOrderDirty))) {
  41223. this._parent.updateCachedStates(false);
  41224. }
  41225. // Update Z-Order if needed
  41226. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagZOrderDirty)) {
  41227. this._updateZOrder();
  41228. }
  41229. // Update actualSize only if there' not positioning to recompute and the size changed
  41230. // Otherwise positioning will take care of it.
  41231. var sizeDirty = this.checkPropertiesDirty(Prim2DBase.sizeProperty.flagId);
  41232. if (!this._isFlagSet(BABYLON.SmartPropertyPrim.flagLayoutDirty) && !this._isFlagSet(BABYLON.SmartPropertyPrim.flagPositioningDirty) && sizeDirty) {
  41233. var size = this.size;
  41234. if (size) {
  41235. if (this.size.width != null) {
  41236. this.actualSize.width = this.size.width;
  41237. }
  41238. if (this.size.height != null) {
  41239. this.actualSize.height = this.size.height;
  41240. }
  41241. this.clearPropertiesDirty(Prim2DBase.sizeProperty.flagId);
  41242. }
  41243. }
  41244. // Check for layout update
  41245. var positioningDirty = this._isFlagSet(BABYLON.SmartPropertyPrim.flagPositioningDirty);
  41246. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagLayoutDirty)) {
  41247. this.owner.addUpdateLayoutCounter(1);
  41248. this._layoutEngine.updateLayout(this);
  41249. this._clearFlags(BABYLON.SmartPropertyPrim.flagLayoutDirty);
  41250. }
  41251. var positioningComputed = positioningDirty && !this._isFlagSet(BABYLON.SmartPropertyPrim.flagPositioningDirty);
  41252. var autoContentChanged = false;
  41253. if (this.isSizeAuto) {
  41254. if (!this._lastAutoSizeArea) {
  41255. autoContentChanged = this.size !== null;
  41256. }
  41257. else {
  41258. autoContentChanged = (!this._lastAutoSizeArea.equals(this.size));
  41259. }
  41260. }
  41261. // Check for positioning update
  41262. if (!positioningComputed && (autoContentChanged || sizeDirty || this._isFlagSet(BABYLON.SmartPropertyPrim.flagPositioningDirty) || (this._parent && !this._parent.contentArea.equals(this._parentContentArea)))) {
  41263. this._updatePositioning();
  41264. this._clearFlags(BABYLON.SmartPropertyPrim.flagPositioningDirty);
  41265. if (sizeDirty) {
  41266. this.clearPropertiesDirty(Prim2DBase.sizeProperty.flagId);
  41267. }
  41268. positioningComputed = true;
  41269. }
  41270. if (positioningComputed && this._parent) {
  41271. this._parentContentArea.copyFrom(this._parent.contentArea);
  41272. }
  41273. // Check if we must update this prim
  41274. if (this === this.owner || this._globalTransformProcessStep !== this.owner._globalTransformProcessStep) {
  41275. this.owner.addUpdateGlobalTransformCounter(1);
  41276. var curVisibleState = this.isVisible;
  41277. this.isVisible = (!this._parent || this._parent.isVisible) && this.levelVisible;
  41278. // Detect a change of visibility
  41279. this._changeFlags(BABYLON.SmartPropertyPrim.flagVisibilityChanged, curVisibleState !== this.isVisible);
  41280. // Get/compute the localTransform
  41281. var localDirty = this._updateLocalTransform();
  41282. var parentPaddingChanged = false;
  41283. var parentPaddingOffset = Prim2DBase._v0;
  41284. if (this._parent) {
  41285. parentPaddingOffset = this._parent._paddingOffset;
  41286. parentPaddingChanged = !parentPaddingOffset.equals(this._parentPaddingOffset);
  41287. }
  41288. // Check if there are changes in the parent that will force us to update the global matrix
  41289. var parentDirty = (this._parent != null) ? (this._parent._globalTransformStep !== this._parentTransformStep) : false;
  41290. // Check if we have to update the globalTransform
  41291. if (!this._globalTransform || localDirty || parentDirty || parentPaddingChanged) {
  41292. var globalTransform = this._parent ? this._parent._globalTransform : null;
  41293. var localTransform;
  41294. Prim2DBase._transMtx.copyFrom(this._localTransform);
  41295. Prim2DBase._transMtx.m[12] += this._layoutAreaPos.x + this._marginOffset.x + parentPaddingOffset.x;
  41296. Prim2DBase._transMtx.m[13] += this._layoutAreaPos.y + this._marginOffset.y + parentPaddingOffset.y;
  41297. localTransform = Prim2DBase._transMtx;
  41298. this._globalTransform = this._parent ? localTransform.multiply(globalTransform) : localTransform.clone();
  41299. this._invGlobalTransform = BABYLON.Matrix.Invert(this._globalTransform);
  41300. this._globalTransformStep = this.owner._globalTransformProcessStep + 1;
  41301. this._parentTransformStep = this._parent ? this._parent._globalTransformStep : 0;
  41302. }
  41303. this._globalTransformProcessStep = this.owner._globalTransformProcessStep;
  41304. }
  41305. if (recurse) {
  41306. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  41307. var child = _a[_i];
  41308. // Stop the recursion if we meet a renderable group
  41309. child.updateCachedStates(!(child instanceof BABYLON.Group2D && child.isRenderableGroup));
  41310. }
  41311. }
  41312. };
  41313. Prim2DBase.prototype._updatePositioning = function () {
  41314. if (this.owner) {
  41315. this.owner.addUpdatePositioningCounter(1);
  41316. }
  41317. // From this point we assume that the primitive layoutArea is computed and up to date.
  41318. // We know have to :
  41319. // 1. Determine the PaddingArea and the ActualPosition based on the margin/marginAlignment properties, which will also set the size property of the primitive
  41320. // 2. Determine the contentArea based on the padding property.
  41321. // 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
  41322. if (!this._hasMargin && (this.actualSize.width == null || this.actualSize.height == null)) {
  41323. if (this.actualSize.width == null) {
  41324. this.marginAlignment.horizontal = PrimitiveAlignment.AlignStretch;
  41325. }
  41326. if (this.actualSize.height == null) {
  41327. this.marginAlignment.vertical = PrimitiveAlignment.AlignStretch;
  41328. }
  41329. }
  41330. // Apply margin
  41331. if (this._hasMargin) {
  41332. this.margin.computeWithAlignment(this.layoutArea, this.size, this.marginAlignment, this._marginOffset, Prim2DBase._size);
  41333. this.actualSize = Prim2DBase._size.clone();
  41334. }
  41335. var isSizeAuto = this.isSizeAuto;
  41336. if (this._hasPadding) {
  41337. // Two cases from here: the size of the Primitive is Auto, its content can't be shrink, so me resize the primitive itself
  41338. if (isSizeAuto) {
  41339. var content = this.size.clone();
  41340. this._getActualSizeFromContentToRef(content, Prim2DBase._icArea);
  41341. this.padding.enlarge(Prim2DBase._icArea, this._paddingOffset, Prim2DBase._size);
  41342. this._contentArea.copyFrom(content);
  41343. this.actualSize = Prim2DBase._size.clone();
  41344. // Changing the padding has resize the prim, which forces us to recompute margin again
  41345. if (this._hasMargin) {
  41346. this.margin.computeWithAlignment(this.layoutArea, Prim2DBase._size, this.marginAlignment, this._marginOffset, Prim2DBase._size);
  41347. }
  41348. }
  41349. else {
  41350. this._getInitialContentAreaToRef(this.actualSize, Prim2DBase._icPos, Prim2DBase._icArea);
  41351. Prim2DBase._icArea.width = Math.max(0, Prim2DBase._icArea.width);
  41352. Prim2DBase._icArea.height = Math.max(0, Prim2DBase._icArea.height);
  41353. this.padding.compute(Prim2DBase._icArea, this._paddingOffset, Prim2DBase._size);
  41354. this._paddingOffset.x += Prim2DBase._icPos.x;
  41355. this._paddingOffset.y += Prim2DBase._icPos.y;
  41356. this._contentArea.copyFrom(Prim2DBase._size);
  41357. }
  41358. }
  41359. else {
  41360. this._getInitialContentAreaToRef(this.actualSize, Prim2DBase._icPos, Prim2DBase._icArea);
  41361. Prim2DBase._icArea.width = Math.max(0, Prim2DBase._icArea.width);
  41362. Prim2DBase._icArea.height = Math.max(0, Prim2DBase._icArea.height);
  41363. this._paddingOffset.copyFrom(Prim2DBase._icPos);
  41364. this._contentArea.copyFrom(Prim2DBase._icArea);
  41365. }
  41366. if (!this._position) {
  41367. var aPos = new BABYLON.Vector2(this._layoutAreaPos.x + this._marginOffset.x, this._layoutAreaPos.y + this._marginOffset.y);
  41368. this.actualPosition = aPos;
  41369. }
  41370. if (isSizeAuto) {
  41371. this._lastAutoSizeArea = this.size;
  41372. }
  41373. };
  41374. Object.defineProperty(Prim2DBase.prototype, "contentArea", {
  41375. /**
  41376. * Get the content are of this primitive, this area is computed using the padding property and also possibly the primitive type itself.
  41377. * Children of this primitive will be positioned relative to the bottom/left corner of this area.
  41378. */
  41379. get: function () {
  41380. // Check for positioning update
  41381. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagPositioningDirty)) {
  41382. this._updatePositioning();
  41383. this._clearFlags(BABYLON.SmartPropertyPrim.flagPositioningDirty);
  41384. }
  41385. return this._contentArea;
  41386. },
  41387. enumerable: true,
  41388. configurable: true
  41389. });
  41390. Prim2DBase.prototype._patchHierarchy = function (owner) {
  41391. this._owner = owner;
  41392. // The only place we initialize the _renderGroup is this method, if it's set, we already been there, no need to execute more
  41393. if (this._renderGroup != null) {
  41394. return;
  41395. }
  41396. if (this instanceof BABYLON.Group2D) {
  41397. var group = this;
  41398. group.detectGroupStates();
  41399. if (group._trackedNode && !group._isFlagSet(BABYLON.SmartPropertyPrim.flagTrackedGroup)) {
  41400. group.owner._registerTrackedNode(this);
  41401. }
  41402. }
  41403. this._renderGroup = this.traverseUp(function (p) { return p instanceof BABYLON.Group2D && p.isRenderableGroup; });
  41404. if (this._parent) {
  41405. this._parentLayoutDirty();
  41406. }
  41407. // Make sure the prim is in the dirtyList if it should be
  41408. if (this._renderGroup && this.isDirty) {
  41409. var list = this._renderGroup._renderableData._primDirtyList;
  41410. var i = list.indexOf(this);
  41411. if (i === -1) {
  41412. list.push(this);
  41413. }
  41414. }
  41415. // Recurse
  41416. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  41417. var child = _a[_i];
  41418. child._hierarchyDepth = this._hierarchyDepth + 1;
  41419. child._patchHierarchy(owner);
  41420. }
  41421. };
  41422. Prim2DBase.prototype._updateZOrder = function () {
  41423. var prevLinPos = this._primLinearPosition;
  41424. var startI = 0;
  41425. var startZ = this._zOrder;
  41426. // 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
  41427. var childrenCount = this._children.length;
  41428. if (this._firstZDirtyIndex > 0) {
  41429. if ((this._firstZDirtyIndex - 1) < childrenCount) {
  41430. var prevPrim = this._children[this._firstZDirtyIndex - 1];
  41431. prevLinPos = prevPrim._primLinearPosition;
  41432. startI = this._firstZDirtyIndex - 1;
  41433. startZ = prevPrim._zOrder;
  41434. }
  41435. }
  41436. var startPos = prevLinPos;
  41437. // Update the linear position of the primitive from the first one to the last inside this primitive, compute the total number of prim traversed
  41438. Prim2DBase._totalCount = 0;
  41439. for (var i = startI; i < childrenCount; i++) {
  41440. var child = this._children[i];
  41441. prevLinPos = child._updatePrimitiveLinearPosition(prevLinPos);
  41442. }
  41443. // Compute the new Z-Order for all the primitives
  41444. // Add 20% to the current total count to reserve space for future insertions, except if we're rebuilding due to a zMinDelta reached
  41445. var zDelta = (this._zMax - startZ) / (Prim2DBase._totalCount * (Prim2DBase._zRebuildReentrency ? 1 : 1.2));
  41446. // 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.
  41447. if (zDelta < BABYLON.Canvas2D._zMinDelta) {
  41448. // 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...
  41449. if (Prim2DBase._zRebuildReentrency) {
  41450. var p = this._parent;
  41451. if (p == null) {
  41452. // 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...)
  41453. console.log("Can't compute Z-Order for " + this.id + "'s children, zDelta is too small, Z-Order is now in an unstable state");
  41454. Prim2DBase._zRebuildReentrency = false;
  41455. return;
  41456. }
  41457. p._firstZDirtyIndex = 0;
  41458. return p._updateZOrder();
  41459. }
  41460. Prim2DBase._zRebuildReentrency = true;
  41461. this._firstZDirtyIndex = 0;
  41462. this._updateZOrder();
  41463. Prim2DBase._zRebuildReentrency = false;
  41464. }
  41465. for (var i = startI; i < childrenCount; i++) {
  41466. var child = this._children[i];
  41467. child._updatePrimitiveZOrder(startPos, startZ, zDelta);
  41468. }
  41469. // Notify the Observers that we found during the Z change (we do it after to avoid any kind of re-entrance)
  41470. for (var _i = 0, _a = Prim2DBase._zOrderChangedNotifList; _i < _a.length; _i++) {
  41471. var p = _a[_i];
  41472. p._actualZOrderChangedObservable.notifyObservers(p.actualZOffset);
  41473. }
  41474. Prim2DBase._zOrderChangedNotifList.splice(0);
  41475. this._firstZDirtyIndex = Prim2DBase._bigInt;
  41476. this._clearFlags(BABYLON.SmartPropertyPrim.flagZOrderDirty);
  41477. };
  41478. Prim2DBase.prototype._updatePrimitiveLinearPosition = function (prevLinPos) {
  41479. if (this.isManualZOrder) {
  41480. return prevLinPos;
  41481. }
  41482. this._primLinearPosition = ++prevLinPos;
  41483. Prim2DBase._totalCount++;
  41484. // Check for the FlatZOrder, which means the children won't have a dedicated Z-Order but will all share the same (unique) one.
  41485. if (!this._isFlagSet(BABYLON.SmartPropertyPrim.flagChildrenFlatZOrder)) {
  41486. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  41487. var child = _a[_i];
  41488. prevLinPos = child._updatePrimitiveLinearPosition(prevLinPos);
  41489. }
  41490. }
  41491. return prevLinPos;
  41492. };
  41493. Prim2DBase.prototype._updatePrimitiveZOrder = function (startPos, startZ, deltaZ) {
  41494. if (this.isManualZOrder) {
  41495. return null;
  41496. }
  41497. var newZ = startZ + ((this._primLinearPosition - startPos) * deltaZ);
  41498. var isFlat = this._isFlagSet(BABYLON.SmartPropertyPrim.flagChildrenFlatZOrder);
  41499. this._setZOrder(newZ, false);
  41500. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagZOrderDirty)) {
  41501. this._firstZDirtyIndex = Prim2DBase._bigInt;
  41502. this._clearFlags(BABYLON.SmartPropertyPrim.flagZOrderDirty);
  41503. }
  41504. var curZ = newZ;
  41505. // Check for the FlatZOrder, which means the children won't have a dedicated Z-Order but will all share the same (unique) one.
  41506. if (isFlat) {
  41507. if (this._children.length > 0) {
  41508. //let childrenZOrder = startZ + ((this._children[0]._primLinearPosition - startPos) * deltaZ);
  41509. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  41510. var child = _a[_i];
  41511. child._updatePrimitiveFlatZOrder(this._zOrder);
  41512. }
  41513. }
  41514. }
  41515. else {
  41516. for (var _b = 0, _c = this._children; _b < _c.length; _b++) {
  41517. var child = _c[_b];
  41518. var r = child._updatePrimitiveZOrder(startPos, startZ, deltaZ);
  41519. if (r != null) {
  41520. curZ = r;
  41521. }
  41522. }
  41523. }
  41524. this._zMax = isFlat ? newZ : (curZ + deltaZ);
  41525. return curZ;
  41526. };
  41527. Prim2DBase.prototype._updatePrimitiveFlatZOrder = function (newZ) {
  41528. if (this.isManualZOrder) {
  41529. return;
  41530. }
  41531. this._setZOrder(newZ, false);
  41532. this._zMax = newZ;
  41533. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagZOrderDirty)) {
  41534. this._firstZDirtyIndex = Prim2DBase._bigInt;
  41535. this._clearFlags(BABYLON.SmartPropertyPrim.flagZOrderDirty);
  41536. }
  41537. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  41538. var child = _a[_i];
  41539. child._updatePrimitiveFlatZOrder(newZ);
  41540. }
  41541. };
  41542. Prim2DBase.prototype._setZOrder = function (newZ, directEmit) {
  41543. if (newZ !== this._zOrder) {
  41544. this._zOrder = newZ;
  41545. this.onPrimBecomesDirty();
  41546. this.onZOrderChanged();
  41547. if (this._actualZOrderChangedObservable && this._actualZOrderChangedObservable.hasObservers()) {
  41548. if (directEmit) {
  41549. this._actualZOrderChangedObservable.notifyObservers(newZ);
  41550. }
  41551. else {
  41552. Prim2DBase._zOrderChangedNotifList.push(this);
  41553. }
  41554. }
  41555. }
  41556. };
  41557. Prim2DBase.prototype._updateRenderMode = function () {
  41558. };
  41559. /**
  41560. * This method is used to alter the contentArea of the Primitive before margin is applied.
  41561. * 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.
  41562. * @param primSize the current size of the primitive
  41563. * @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!
  41564. * @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!
  41565. */
  41566. Prim2DBase.prototype._getInitialContentAreaToRef = function (primSize, initialContentPosition, initialContentArea) {
  41567. initialContentArea.copyFrom(primSize);
  41568. initialContentPosition.x = initialContentPosition.y = 0;
  41569. };
  41570. /**
  41571. * This method is used to calculate the new size of the primitive based on the content which must stay the same
  41572. * Check the Rectangle2D implementation for a concrete application.
  41573. * @param primSize the current size of the primitive
  41574. * @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!
  41575. */
  41576. Prim2DBase.prototype._getActualSizeFromContentToRef = function (primSize, newPrimSize) {
  41577. newPrimSize.copyFrom(primSize);
  41578. };
  41579. Prim2DBase.PRIM2DBASE_PROPCOUNT = 16;
  41580. Prim2DBase._bigInt = Math.pow(2, 30);
  41581. Prim2DBase._nullPosition = BABYLON.Vector2.Zero();
  41582. Prim2DBase.boundinbBoxReentrency = false;
  41583. Prim2DBase.nullSize = BABYLON.Size.Zero();
  41584. Prim2DBase._bMax = BABYLON.Vector2.Zero();
  41585. Prim2DBase._isCanvasInit = false;
  41586. Prim2DBase._t0 = new BABYLON.Matrix();
  41587. Prim2DBase._t1 = new BABYLON.Matrix();
  41588. Prim2DBase._t2 = new BABYLON.Matrix();
  41589. Prim2DBase._v0 = BABYLON.Vector2.Zero(); // Must stay with the value 0,0
  41590. Prim2DBase._transMtx = BABYLON.Matrix.Zero();
  41591. Prim2DBase._icPos = BABYLON.Vector2.Zero();
  41592. Prim2DBase._icArea = BABYLON.Size.Zero();
  41593. Prim2DBase._size = BABYLON.Size.Zero();
  41594. Prim2DBase._zOrderChangedNotifList = new Array();
  41595. Prim2DBase._zRebuildReentrency = false;
  41596. Prim2DBase._totalCount = 0;
  41597. __decorate([
  41598. BABYLON.instanceLevelProperty(1, function (pi) { return Prim2DBase.actualPositionProperty = pi; }, false, false, true)
  41599. ], Prim2DBase.prototype, "actualPosition", null);
  41600. __decorate([
  41601. BABYLON.dynamicLevelProperty(2, function (pi) { return Prim2DBase.positionProperty = pi; }, false, false, true)
  41602. ], Prim2DBase.prototype, "position", null);
  41603. __decorate([
  41604. BABYLON.dynamicLevelProperty(3, function (pi) { return Prim2DBase.sizeProperty = pi; }, false, true)
  41605. ], Prim2DBase.prototype, "size", null);
  41606. __decorate([
  41607. BABYLON.instanceLevelProperty(4, function (pi) { return Prim2DBase.rotationProperty = pi; }, false, true)
  41608. ], Prim2DBase.prototype, "rotation", null);
  41609. __decorate([
  41610. BABYLON.instanceLevelProperty(5, function (pi) { return Prim2DBase.scaleProperty = pi; }, false, true)
  41611. ], Prim2DBase.prototype, "scale", null);
  41612. __decorate([
  41613. BABYLON.dynamicLevelProperty(6, function (pi) { return Prim2DBase.originProperty = pi; }, false, true)
  41614. ], Prim2DBase.prototype, "origin", null);
  41615. __decorate([
  41616. BABYLON.dynamicLevelProperty(7, function (pi) { return Prim2DBase.levelVisibleProperty = pi; })
  41617. ], Prim2DBase.prototype, "levelVisible", null);
  41618. __decorate([
  41619. BABYLON.instanceLevelProperty(8, function (pi) { return Prim2DBase.isVisibleProperty = pi; })
  41620. ], Prim2DBase.prototype, "isVisible", null);
  41621. __decorate([
  41622. BABYLON.instanceLevelProperty(9, function (pi) { return Prim2DBase.zOrderProperty = pi; })
  41623. ], Prim2DBase.prototype, "zOrder", null);
  41624. __decorate([
  41625. BABYLON.dynamicLevelProperty(10, function (pi) { return Prim2DBase.marginProperty = pi; })
  41626. ], Prim2DBase.prototype, "margin", null);
  41627. __decorate([
  41628. BABYLON.dynamicLevelProperty(11, function (pi) { return Prim2DBase.paddingProperty = pi; })
  41629. ], Prim2DBase.prototype, "padding", null);
  41630. __decorate([
  41631. BABYLON.dynamicLevelProperty(12, function (pi) { return Prim2DBase.marginAlignmentProperty = pi; })
  41632. ], Prim2DBase.prototype, "marginAlignment", null);
  41633. __decorate([
  41634. BABYLON.instanceLevelProperty(13, function (pi) { return Prim2DBase.opacityProperty = pi; })
  41635. ], Prim2DBase.prototype, "opacity", null);
  41636. __decorate([
  41637. BABYLON.instanceLevelProperty(14, function (pi) { return Prim2DBase.scaleXProperty = pi; }, false, true)
  41638. ], Prim2DBase.prototype, "scaleX", null);
  41639. __decorate([
  41640. BABYLON.instanceLevelProperty(15, function (pi) { return Prim2DBase.scaleYProperty = pi; }, false, true)
  41641. ], Prim2DBase.prototype, "scaleY", null);
  41642. Prim2DBase = __decorate([
  41643. BABYLON.className("Prim2DBase")
  41644. ], Prim2DBase);
  41645. return Prim2DBase;
  41646. })(BABYLON.SmartPropertyPrim);
  41647. BABYLON.Prim2DBase = Prim2DBase;
  41648. })(BABYLON || (BABYLON = {}));
  41649. var BABYLON;
  41650. (function (BABYLON) {
  41651. var GroupInstanceInfo = (function () {
  41652. function GroupInstanceInfo(owner, mrc, partCount) {
  41653. this._partCount = partCount;
  41654. this.owner = owner;
  41655. this.modelRenderCache = mrc;
  41656. this.modelRenderCache.addRef();
  41657. this.partIndexFromId = new BABYLON.StringDictionary();
  41658. this._usedShaderCategories = new Array(partCount);
  41659. this._strides = new Array(partCount);
  41660. this._opaqueData = null;
  41661. this._alphaTestData = null;
  41662. this._transparentData = null;
  41663. this.opaqueDirty = this.alphaTestDirty = this.transparentDirty = this.transparentOrderDirty = false;
  41664. }
  41665. GroupInstanceInfo.prototype.dispose = function () {
  41666. if (this._isDisposed) {
  41667. return false;
  41668. }
  41669. if (this.modelRenderCache) {
  41670. this.modelRenderCache.dispose();
  41671. this.modelRenderCache = null;
  41672. }
  41673. var engine = this.owner.owner.engine;
  41674. if (this._opaqueData) {
  41675. this._opaqueData.forEach(function (d) { return d.dispose(engine); });
  41676. this._opaqueData = null;
  41677. }
  41678. if (this._alphaTestData) {
  41679. this._alphaTestData.forEach(function (d) { return d.dispose(engine); });
  41680. this._alphaTestData = null;
  41681. }
  41682. if (this._transparentData) {
  41683. this._transparentData.forEach(function (d) { return d.dispose(engine); });
  41684. this._transparentData = null;
  41685. }
  41686. this.partIndexFromId = null;
  41687. this._isDisposed = true;
  41688. return true;
  41689. };
  41690. Object.defineProperty(GroupInstanceInfo.prototype, "hasOpaqueData", {
  41691. get: function () {
  41692. return this._opaqueData != null;
  41693. },
  41694. enumerable: true,
  41695. configurable: true
  41696. });
  41697. Object.defineProperty(GroupInstanceInfo.prototype, "hasAlphaTestData", {
  41698. get: function () {
  41699. return this._alphaTestData != null;
  41700. },
  41701. enumerable: true,
  41702. configurable: true
  41703. });
  41704. Object.defineProperty(GroupInstanceInfo.prototype, "hasTransparentData", {
  41705. get: function () {
  41706. return this._transparentData != null;
  41707. },
  41708. enumerable: true,
  41709. configurable: true
  41710. });
  41711. Object.defineProperty(GroupInstanceInfo.prototype, "opaqueData", {
  41712. get: function () {
  41713. if (!this._opaqueData) {
  41714. this._opaqueData = new Array(this._partCount);
  41715. for (var i = 0; i < this._partCount; i++) {
  41716. this._opaqueData[i] = new GroupInfoPartData(this._strides[i]);
  41717. }
  41718. }
  41719. return this._opaqueData;
  41720. },
  41721. enumerable: true,
  41722. configurable: true
  41723. });
  41724. Object.defineProperty(GroupInstanceInfo.prototype, "alphaTestData", {
  41725. get: function () {
  41726. if (!this._alphaTestData) {
  41727. this._alphaTestData = new Array(this._partCount);
  41728. for (var i = 0; i < this._partCount; i++) {
  41729. this._alphaTestData[i] = new GroupInfoPartData(this._strides[i]);
  41730. }
  41731. }
  41732. return this._alphaTestData;
  41733. },
  41734. enumerable: true,
  41735. configurable: true
  41736. });
  41737. Object.defineProperty(GroupInstanceInfo.prototype, "transparentData", {
  41738. get: function () {
  41739. if (!this._transparentData) {
  41740. this._transparentData = new Array(this._partCount);
  41741. for (var i = 0; i < this._partCount; i++) {
  41742. var zoff = this.modelRenderCache._partData[i]._zBiasOffset;
  41743. this._transparentData[i] = new TransparentGroupInfoPartData(this._strides[i], zoff);
  41744. }
  41745. }
  41746. return this._transparentData;
  41747. },
  41748. enumerable: true,
  41749. configurable: true
  41750. });
  41751. GroupInstanceInfo.prototype.sortTransparentData = function () {
  41752. if (!this.transparentOrderDirty) {
  41753. return;
  41754. }
  41755. for (var i = 0; i < this._transparentData.length; i++) {
  41756. var td = this._transparentData[i];
  41757. td._partData.sort();
  41758. }
  41759. this.transparentOrderDirty = false;
  41760. };
  41761. Object.defineProperty(GroupInstanceInfo.prototype, "usedShaderCategories", {
  41762. get: function () {
  41763. return this._usedShaderCategories;
  41764. },
  41765. enumerable: true,
  41766. configurable: true
  41767. });
  41768. Object.defineProperty(GroupInstanceInfo.prototype, "strides", {
  41769. get: function () {
  41770. return this._strides;
  41771. },
  41772. enumerable: true,
  41773. configurable: true
  41774. });
  41775. return GroupInstanceInfo;
  41776. })();
  41777. BABYLON.GroupInstanceInfo = GroupInstanceInfo;
  41778. var TransparentSegment = (function () {
  41779. function TransparentSegment() {
  41780. this.groupInsanceInfo = null;
  41781. this.startZ = 0;
  41782. this.endZ = 0;
  41783. this.startDataIndex = BABYLON.Prim2DBase._bigInt;
  41784. this.endDataIndex = 0;
  41785. this.partBuffers = null;
  41786. }
  41787. TransparentSegment.prototype.dispose = function (engine) {
  41788. if (this.partBuffers) {
  41789. this.partBuffers.forEach(function (b) { return engine._releaseBuffer(b); });
  41790. this.partBuffers.splice(0);
  41791. this.partBuffers = null;
  41792. }
  41793. };
  41794. return TransparentSegment;
  41795. })();
  41796. BABYLON.TransparentSegment = TransparentSegment;
  41797. var GroupInfoPartData = (function () {
  41798. function GroupInfoPartData(stride) {
  41799. this._partData = null;
  41800. this._partBuffer = null;
  41801. this._partBufferSize = 0;
  41802. this._partData = new BABYLON.DynamicFloatArray(stride / 4, 50);
  41803. this._isDisposed = false;
  41804. }
  41805. GroupInfoPartData.prototype.dispose = function (engine) {
  41806. if (this._isDisposed) {
  41807. return false;
  41808. }
  41809. if (this._partBuffer) {
  41810. engine._releaseBuffer(this._partBuffer);
  41811. this._partBuffer = null;
  41812. }
  41813. this._partData = null;
  41814. this._isDisposed = true;
  41815. };
  41816. return GroupInfoPartData;
  41817. })();
  41818. BABYLON.GroupInfoPartData = GroupInfoPartData;
  41819. var TransparentGroupInfoPartData = (function (_super) {
  41820. __extends(TransparentGroupInfoPartData, _super);
  41821. function TransparentGroupInfoPartData(stride, zoff) {
  41822. _super.call(this, stride);
  41823. this._partData.compareValueOffset = zoff;
  41824. this._partData.sortingAscending = false;
  41825. }
  41826. return TransparentGroupInfoPartData;
  41827. })(GroupInfoPartData);
  41828. BABYLON.TransparentGroupInfoPartData = TransparentGroupInfoPartData;
  41829. var ModelRenderCache = (function () {
  41830. function ModelRenderCache(engine, modelKey) {
  41831. this._engine = engine;
  41832. this._modelKey = modelKey;
  41833. this._nextKey = 1;
  41834. this._refCounter = 1;
  41835. this._partData = null;
  41836. }
  41837. ModelRenderCache.prototype.dispose = function () {
  41838. if (--this._refCounter !== 0) {
  41839. return false;
  41840. }
  41841. // Remove the Model Render Cache from the global dictionary
  41842. var edata = this._engine.getExternalData("__BJSCANVAS2D__");
  41843. if (edata) {
  41844. edata.DisposeModelRenderCache(this);
  41845. }
  41846. return true;
  41847. };
  41848. Object.defineProperty(ModelRenderCache.prototype, "isDisposed", {
  41849. get: function () {
  41850. return this._refCounter <= 0;
  41851. },
  41852. enumerable: true,
  41853. configurable: true
  41854. });
  41855. ModelRenderCache.prototype.addRef = function () {
  41856. return ++this._refCounter;
  41857. };
  41858. Object.defineProperty(ModelRenderCache.prototype, "modelKey", {
  41859. get: function () {
  41860. return this._modelKey;
  41861. },
  41862. enumerable: true,
  41863. configurable: true
  41864. });
  41865. /**
  41866. * Render the model instances
  41867. * @param instanceInfo
  41868. * @param context
  41869. * @return must return true is the rendering succeed, false if the rendering couldn't be done (asset's not yet ready, like Effect)
  41870. */
  41871. ModelRenderCache.prototype.render = function (instanceInfo, context) {
  41872. return true;
  41873. };
  41874. ModelRenderCache.prototype.getPartIndexFromId = function (partId) {
  41875. for (var i = 0; i < this._partData.length; i++) {
  41876. if (this._partData[i]._partId === partId) {
  41877. return i;
  41878. }
  41879. }
  41880. return null;
  41881. };
  41882. ModelRenderCache.prototype.loadInstancingAttributes = function (partId, effect) {
  41883. var i = this.getPartIndexFromId(partId);
  41884. if (i === null) {
  41885. return null;
  41886. }
  41887. var ci = this._partsClassInfo[i];
  41888. var categories = this._partData[i]._partUsedCategories;
  41889. var res = ci.classContent.getInstancingAttributeInfos(effect, categories);
  41890. return res;
  41891. };
  41892. ModelRenderCache.prototype.setupUniforms = function (effect, partIndex, data, elementCount) {
  41893. var pd = this._partData[partIndex];
  41894. var offset = (pd._partDataStride / 4) * elementCount;
  41895. var pci = this._partsClassInfo[partIndex];
  41896. var self = this;
  41897. pci.fullContent.forEach(function (k, v) {
  41898. if (!v.category || pd._partUsedCategories.indexOf(v.category) !== -1) {
  41899. switch (v.dataType) {
  41900. case 4 /* float */:
  41901. {
  41902. var attribOffset = v.instanceOffset.get(pd._partJoinedUsedCategories);
  41903. effect.setFloat(v.attributeName, data.buffer[offset + attribOffset]);
  41904. break;
  41905. }
  41906. case 0 /* Vector2 */:
  41907. {
  41908. var attribOffset = v.instanceOffset.get(pd._partJoinedUsedCategories);
  41909. ModelRenderCache.v2.x = data.buffer[offset + attribOffset + 0];
  41910. ModelRenderCache.v2.y = data.buffer[offset + attribOffset + 1];
  41911. effect.setVector2(v.attributeName, ModelRenderCache.v2);
  41912. break;
  41913. }
  41914. case 5 /* Color3 */:
  41915. case 1 /* Vector3 */:
  41916. {
  41917. var attribOffset = v.instanceOffset.get(pd._partJoinedUsedCategories);
  41918. ModelRenderCache.v3.x = data.buffer[offset + attribOffset + 0];
  41919. ModelRenderCache.v3.y = data.buffer[offset + attribOffset + 1];
  41920. ModelRenderCache.v3.z = data.buffer[offset + attribOffset + 2];
  41921. effect.setVector3(v.attributeName, ModelRenderCache.v3);
  41922. break;
  41923. }
  41924. case 6 /* Color4 */:
  41925. case 2 /* Vector4 */:
  41926. {
  41927. var attribOffset = v.instanceOffset.get(pd._partJoinedUsedCategories);
  41928. ModelRenderCache.v4.x = data.buffer[offset + attribOffset + 0];
  41929. ModelRenderCache.v4.y = data.buffer[offset + attribOffset + 1];
  41930. ModelRenderCache.v4.z = data.buffer[offset + attribOffset + 2];
  41931. ModelRenderCache.v4.w = data.buffer[offset + attribOffset + 3];
  41932. effect.setVector4(v.attributeName, ModelRenderCache.v4);
  41933. break;
  41934. }
  41935. default:
  41936. }
  41937. }
  41938. });
  41939. };
  41940. //setupUniformsLocation(effect: Effect, uniforms: string[], partId: number) {
  41941. // let i = this.getPartIndexFromId(partId);
  41942. // if (i === null) {
  41943. // return null;
  41944. // }
  41945. // let pci = this._partsClassInfo[i];
  41946. // pci.fullContent.forEach((k, v) => {
  41947. // if (uniforms.indexOf(v.attributeName) !== -1) {
  41948. // v.uniformLocation = effect.getUniform(v.attributeName);
  41949. // }
  41950. // });
  41951. //}
  41952. ModelRenderCache.v2 = BABYLON.Vector2.Zero();
  41953. ModelRenderCache.v3 = BABYLON.Vector3.Zero();
  41954. ModelRenderCache.v4 = BABYLON.Vector4.Zero();
  41955. return ModelRenderCache;
  41956. })();
  41957. BABYLON.ModelRenderCache = ModelRenderCache;
  41958. var ModelRenderCachePartData = (function () {
  41959. function ModelRenderCachePartData() {
  41960. }
  41961. return ModelRenderCachePartData;
  41962. })();
  41963. BABYLON.ModelRenderCachePartData = ModelRenderCachePartData;
  41964. })(BABYLON || (BABYLON = {}));
  41965. var BABYLON;
  41966. (function (BABYLON) {
  41967. var InstanceClassInfo = (function () {
  41968. function InstanceClassInfo(base) {
  41969. this._baseInfo = base;
  41970. this._nextOffset = new BABYLON.StringDictionary();
  41971. this._attributes = new Array();
  41972. }
  41973. InstanceClassInfo.prototype.mapProperty = function (propInfo, push) {
  41974. var curOff = this._nextOffset.getOrAdd(InstanceClassInfo._CurCategories, 0);
  41975. propInfo.instanceOffset.add(InstanceClassInfo._CurCategories, this._getBaseOffset(InstanceClassInfo._CurCategories) + curOff);
  41976. //console.log(`[${InstanceClassInfo._CurCategories}] New PropInfo. Category: ${propInfo.category}, Name: ${propInfo.attributeName}, Offset: ${propInfo.instanceOffset.get(InstanceClassInfo._CurCategories)}, Size: ${propInfo.size / 4}`);
  41977. this._nextOffset.set(InstanceClassInfo._CurCategories, curOff + (propInfo.size / 4));
  41978. if (push) {
  41979. this._attributes.push(propInfo);
  41980. }
  41981. };
  41982. InstanceClassInfo.prototype.getInstancingAttributeInfos = function (effect, categories) {
  41983. var catInline = ";" + categories.join(";") + ";";
  41984. var res = new Array();
  41985. var curInfo = this;
  41986. while (curInfo) {
  41987. for (var _i = 0, _a = curInfo._attributes; _i < _a.length; _i++) {
  41988. var attrib = _a[_i];
  41989. // 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
  41990. if (!attrib.category || categories.indexOf(attrib.category) !== -1) {
  41991. var index = effect.getAttributeLocationByName(attrib.attributeName);
  41992. var iai = new BABYLON.InstancingAttributeInfo();
  41993. iai.index = index;
  41994. 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)
  41995. iai.offset = attrib.instanceOffset.get(catInline) * 4; // attrib.instanceOffset is in float, iai.offset must be in bytes
  41996. iai.attributeName = attrib.attributeName;
  41997. res.push(iai);
  41998. }
  41999. }
  42000. curInfo = curInfo._baseInfo;
  42001. }
  42002. return res;
  42003. };
  42004. InstanceClassInfo.prototype.getShaderAttributes = function (categories) {
  42005. var res = new Array();
  42006. var curInfo = this;
  42007. while (curInfo) {
  42008. for (var _i = 0, _a = curInfo._attributes; _i < _a.length; _i++) {
  42009. var attrib = _a[_i];
  42010. // 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
  42011. if (!attrib.category || categories.indexOf(attrib.category) !== -1) {
  42012. res.push(attrib.attributeName);
  42013. }
  42014. }
  42015. curInfo = curInfo._baseInfo;
  42016. }
  42017. return res;
  42018. };
  42019. InstanceClassInfo.prototype._getBaseOffset = function (categories) {
  42020. var curOffset = 0;
  42021. var curBase = this._baseInfo;
  42022. while (curBase) {
  42023. curOffset += curBase._nextOffset.getOrAdd(categories, 0);
  42024. curBase = curBase._baseInfo;
  42025. }
  42026. return curOffset;
  42027. };
  42028. return InstanceClassInfo;
  42029. })();
  42030. BABYLON.InstanceClassInfo = InstanceClassInfo;
  42031. var InstancePropInfo = (function () {
  42032. function InstancePropInfo() {
  42033. this.instanceOffset = new BABYLON.StringDictionary();
  42034. }
  42035. InstancePropInfo.prototype.setSize = function (val) {
  42036. if (val instanceof BABYLON.Vector2) {
  42037. this.size = 8;
  42038. this.dataType = 0 /* Vector2 */;
  42039. return;
  42040. }
  42041. if (val instanceof BABYLON.Vector3) {
  42042. this.size = 12;
  42043. this.dataType = 1 /* Vector3 */;
  42044. return;
  42045. }
  42046. if (val instanceof BABYLON.Vector4) {
  42047. this.size = 16;
  42048. this.dataType = 2 /* Vector4 */;
  42049. return;
  42050. }
  42051. if (val instanceof BABYLON.Matrix) {
  42052. throw new Error("Matrix type is not supported by WebGL Instance Buffer, you have to use four Vector4 properties instead");
  42053. }
  42054. if (typeof (val) === "number") {
  42055. this.size = 4;
  42056. this.dataType = 4 /* float */;
  42057. return;
  42058. }
  42059. if (val instanceof BABYLON.Color3) {
  42060. this.size = 12;
  42061. this.dataType = 5 /* Color3 */;
  42062. return;
  42063. }
  42064. if (val instanceof BABYLON.Color4) {
  42065. this.size = 16;
  42066. this.dataType = 6 /* Color4 */;
  42067. return;
  42068. }
  42069. if (val instanceof BABYLON.Size) {
  42070. this.size = 8;
  42071. this.dataType = 7 /* Size */;
  42072. return;
  42073. }
  42074. return;
  42075. };
  42076. InstancePropInfo.prototype.writeData = function (array, offset, val) {
  42077. switch (this.dataType) {
  42078. case 0 /* Vector2 */:
  42079. {
  42080. var v = val;
  42081. array[offset + 0] = v.x;
  42082. array[offset + 1] = v.y;
  42083. break;
  42084. }
  42085. case 1 /* Vector3 */:
  42086. {
  42087. var v = val;
  42088. array[offset + 0] = v.x;
  42089. array[offset + 1] = v.y;
  42090. array[offset + 2] = v.z;
  42091. break;
  42092. }
  42093. case 2 /* Vector4 */:
  42094. {
  42095. var v = val;
  42096. array[offset + 0] = v.x;
  42097. array[offset + 1] = v.y;
  42098. array[offset + 2] = v.z;
  42099. array[offset + 3] = v.w;
  42100. break;
  42101. }
  42102. case 5 /* Color3 */:
  42103. {
  42104. var v = val;
  42105. array[offset + 0] = v.r;
  42106. array[offset + 1] = v.g;
  42107. array[offset + 2] = v.b;
  42108. break;
  42109. }
  42110. case 6 /* Color4 */:
  42111. {
  42112. var v = val;
  42113. array[offset + 0] = v.r;
  42114. array[offset + 1] = v.g;
  42115. array[offset + 2] = v.b;
  42116. array[offset + 3] = v.a;
  42117. break;
  42118. }
  42119. case 4 /* float */:
  42120. {
  42121. var v = val;
  42122. array[offset] = v;
  42123. break;
  42124. }
  42125. case 3 /* Matrix */:
  42126. {
  42127. var v = val;
  42128. for (var i = 0; i < 16; i++) {
  42129. array[offset + i] = v.m[i];
  42130. }
  42131. break;
  42132. }
  42133. case 7 /* Size */:
  42134. {
  42135. var s = val;
  42136. array[offset + 0] = s.width;
  42137. array[offset + 1] = s.height;
  42138. break;
  42139. }
  42140. }
  42141. };
  42142. return InstancePropInfo;
  42143. })();
  42144. BABYLON.InstancePropInfo = InstancePropInfo;
  42145. function instanceData(category, shaderAttributeName) {
  42146. return function (target, propName, descriptor) {
  42147. var dic = BABYLON.ClassTreeInfo.getOrRegister(target, function (base) { return new InstanceClassInfo(base); });
  42148. var node = dic.getLevelOf(target);
  42149. var instanceDataName = propName;
  42150. shaderAttributeName = shaderAttributeName || instanceDataName;
  42151. var info = node.levelContent.get(instanceDataName);
  42152. if (info) {
  42153. throw new Error("The ID " + instanceDataName + " is already taken by another instance data");
  42154. }
  42155. info = new InstancePropInfo();
  42156. info.attributeName = shaderAttributeName;
  42157. info.category = category || null;
  42158. if (info.category) {
  42159. info.delimitedCategory = ";" + info.category + ";";
  42160. }
  42161. node.levelContent.add(instanceDataName, info);
  42162. descriptor.get = function () {
  42163. return null;
  42164. };
  42165. descriptor.set = function (val) {
  42166. // Check that we're not trying to set a property that belongs to a category that is not allowed (current)
  42167. // Quit if it's the case, otherwise we could overwrite data somewhere...
  42168. if (info.category && InstanceClassInfo._CurCategories.indexOf(info.delimitedCategory) === -1) {
  42169. return;
  42170. }
  42171. if (!info.size) {
  42172. info.setSize(val);
  42173. node.classContent.mapProperty(info, true);
  42174. }
  42175. else if (!info.instanceOffset.contains(InstanceClassInfo._CurCategories)) {
  42176. node.classContent.mapProperty(info, false);
  42177. }
  42178. var obj = this;
  42179. if (obj.dataBuffer && obj.dataElements) {
  42180. var offset = obj.dataElements[obj.curElement].offset + info.instanceOffset.get(InstanceClassInfo._CurCategories);
  42181. info.writeData(obj.dataBuffer.buffer, offset, val);
  42182. }
  42183. };
  42184. };
  42185. }
  42186. BABYLON.instanceData = instanceData;
  42187. var InstanceDataBase = (function () {
  42188. function InstanceDataBase(partId, dataElementCount) {
  42189. this.id = partId;
  42190. this.curElement = 0;
  42191. this._dataElementCount = dataElementCount;
  42192. this.renderMode = 0;
  42193. this.arrayLengthChanged = false;
  42194. }
  42195. Object.defineProperty(InstanceDataBase.prototype, "zBias", {
  42196. get: function () {
  42197. return null;
  42198. },
  42199. enumerable: true,
  42200. configurable: true
  42201. });
  42202. Object.defineProperty(InstanceDataBase.prototype, "transformX", {
  42203. get: function () {
  42204. return null;
  42205. },
  42206. enumerable: true,
  42207. configurable: true
  42208. });
  42209. Object.defineProperty(InstanceDataBase.prototype, "transformY", {
  42210. get: function () {
  42211. return null;
  42212. },
  42213. enumerable: true,
  42214. configurable: true
  42215. });
  42216. Object.defineProperty(InstanceDataBase.prototype, "opacity", {
  42217. get: function () {
  42218. return null;
  42219. },
  42220. enumerable: true,
  42221. configurable: true
  42222. });
  42223. InstanceDataBase.prototype.getClassTreeInfo = function () {
  42224. if (!this.typeInfo) {
  42225. this.typeInfo = BABYLON.ClassTreeInfo.get(Object.getPrototypeOf(this));
  42226. }
  42227. return this.typeInfo;
  42228. };
  42229. InstanceDataBase.prototype.allocElements = function () {
  42230. if (!this.dataBuffer || this.dataElements) {
  42231. return;
  42232. }
  42233. var res = new Array(this.dataElementCount);
  42234. for (var i = 0; i < this.dataElementCount; i++) {
  42235. res[i] = this.dataBuffer.allocElement();
  42236. }
  42237. this.dataElements = res;
  42238. };
  42239. InstanceDataBase.prototype.freeElements = function () {
  42240. if (!this.dataElements) {
  42241. return;
  42242. }
  42243. for (var _i = 0, _a = this.dataElements; _i < _a.length; _i++) {
  42244. var ei = _a[_i];
  42245. this.dataBuffer.freeElement(ei);
  42246. }
  42247. this.dataElements = null;
  42248. };
  42249. Object.defineProperty(InstanceDataBase.prototype, "dataElementCount", {
  42250. get: function () {
  42251. return this._dataElementCount;
  42252. },
  42253. set: function (value) {
  42254. if (value === this._dataElementCount) {
  42255. return;
  42256. }
  42257. this.arrayLengthChanged = true;
  42258. this.freeElements();
  42259. this._dataElementCount = value;
  42260. this.allocElements();
  42261. },
  42262. enumerable: true,
  42263. configurable: true
  42264. });
  42265. __decorate([
  42266. instanceData()
  42267. ], InstanceDataBase.prototype, "zBias", null);
  42268. __decorate([
  42269. instanceData()
  42270. ], InstanceDataBase.prototype, "transformX", null);
  42271. __decorate([
  42272. instanceData()
  42273. ], InstanceDataBase.prototype, "transformY", null);
  42274. __decorate([
  42275. instanceData()
  42276. ], InstanceDataBase.prototype, "opacity", null);
  42277. return InstanceDataBase;
  42278. })();
  42279. BABYLON.InstanceDataBase = InstanceDataBase;
  42280. var RenderablePrim2D = (function (_super) {
  42281. __extends(RenderablePrim2D, _super);
  42282. function RenderablePrim2D(settings) {
  42283. _super.call(this, settings);
  42284. this._transparentPrimitiveInfo = null;
  42285. }
  42286. Object.defineProperty(RenderablePrim2D.prototype, "isAlphaTest", {
  42287. get: function () {
  42288. return this._useTextureAlpha() || this._isPrimAlphaTest();
  42289. },
  42290. enumerable: true,
  42291. configurable: true
  42292. });
  42293. Object.defineProperty(RenderablePrim2D.prototype, "isTransparent", {
  42294. get: function () {
  42295. return (this._opacity < 1) || this._shouldUseAlphaFromTexture() || this._isPrimTransparent();
  42296. },
  42297. enumerable: true,
  42298. configurable: true
  42299. });
  42300. Object.defineProperty(RenderablePrim2D.prototype, "renderMode", {
  42301. get: function () {
  42302. return this._renderMode;
  42303. },
  42304. enumerable: true,
  42305. configurable: true
  42306. });
  42307. /**
  42308. * Dispose the primitive and its resources, remove it from its parent
  42309. */
  42310. RenderablePrim2D.prototype.dispose = function () {
  42311. if (!_super.prototype.dispose.call(this)) {
  42312. return false;
  42313. }
  42314. if (this.renderGroup) {
  42315. this.renderGroup._setCacheGroupDirty();
  42316. }
  42317. if (this._transparentPrimitiveInfo) {
  42318. this.renderGroup._renderableData.removeTransparentPrimitiveInfo(this._transparentPrimitiveInfo);
  42319. this._transparentPrimitiveInfo = null;
  42320. }
  42321. if (this._instanceDataParts) {
  42322. this._cleanupInstanceDataParts();
  42323. }
  42324. if (this._modelRenderCache) {
  42325. this._modelRenderCache.dispose();
  42326. this._modelRenderCache = null;
  42327. }
  42328. if (this._instanceDataParts) {
  42329. this._instanceDataParts.forEach(function (p) {
  42330. p.freeElements();
  42331. });
  42332. this._instanceDataParts = null;
  42333. }
  42334. return true;
  42335. };
  42336. RenderablePrim2D.prototype._cleanupInstanceDataParts = function () {
  42337. var gii = null;
  42338. for (var _i = 0, _a = this._instanceDataParts; _i < _a.length; _i++) {
  42339. var part = _a[_i];
  42340. part.freeElements();
  42341. gii = part.groupInstanceInfo;
  42342. }
  42343. if (gii) {
  42344. var usedCount = 0;
  42345. if (gii.hasOpaqueData) {
  42346. var od = gii.opaqueData[0];
  42347. usedCount += od._partData.usedElementCount;
  42348. }
  42349. if (gii.hasAlphaTestData) {
  42350. var atd = gii.alphaTestData[0];
  42351. usedCount += atd._partData.usedElementCount;
  42352. }
  42353. if (gii.hasTransparentData) {
  42354. var td = gii.transparentData[0];
  42355. usedCount += td._partData.usedElementCount;
  42356. }
  42357. if (usedCount === 0) {
  42358. this.renderGroup._renderableData._renderGroupInstancesInfo.remove(gii.modelRenderCache.modelKey);
  42359. gii.dispose();
  42360. }
  42361. if (this._modelRenderCache) {
  42362. this._modelRenderCache.dispose();
  42363. this._modelRenderCache = null;
  42364. }
  42365. }
  42366. this._instanceDataParts = null;
  42367. };
  42368. RenderablePrim2D.prototype._prepareRenderPre = function (context) {
  42369. _super.prototype._prepareRenderPre.call(this, context);
  42370. // If the model changed and we have already an instance, we must remove this instance from the obsolete model
  42371. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagModelDirty) && this._instanceDataParts) {
  42372. this._cleanupInstanceDataParts();
  42373. }
  42374. // Need to create the model?
  42375. var setupModelRenderCache = false;
  42376. if (!this._modelRenderCache || this._isFlagSet(BABYLON.SmartPropertyPrim.flagModelDirty)) {
  42377. setupModelRenderCache = this._createModelRenderCache();
  42378. }
  42379. var gii = null;
  42380. var newInstance = false;
  42381. // Need to create the instance data parts?
  42382. if (!this._instanceDataParts) {
  42383. // Yes, flag it for later, more processing will have to be done
  42384. newInstance = true;
  42385. gii = this._createModelDataParts();
  42386. }
  42387. // If the ModelRenderCache is brand new, now is the time to call the implementation's specific setup method to create the rendering resources
  42388. if (setupModelRenderCache) {
  42389. this.setupModelRenderCache(this._modelRenderCache);
  42390. }
  42391. // 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.
  42392. // 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.
  42393. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagVisibilityChanged) || context.forceRefreshPrimitive || newInstance || (this._instanceDirtyFlags !== 0) || (this._globalTransformProcessStep !== this._globalTransformStep) || this._mustUpdateInstance()) {
  42394. this._updateInstanceDataParts(gii);
  42395. }
  42396. };
  42397. RenderablePrim2D.prototype._createModelRenderCache = function () {
  42398. var _this = this;
  42399. var setupModelRenderCache = false;
  42400. if (this._modelRenderCache) {
  42401. this._modelRenderCache.dispose();
  42402. }
  42403. this._modelRenderCache = this.owner._engineData.GetOrAddModelCache(this.modelKey, function (key) {
  42404. var mrc = _this.createModelRenderCache(key);
  42405. setupModelRenderCache = true;
  42406. return mrc;
  42407. });
  42408. this._clearFlags(BABYLON.SmartPropertyPrim.flagModelDirty);
  42409. // if this is still false it means the MRC already exists, so we add a reference to it
  42410. if (!setupModelRenderCache) {
  42411. this._modelRenderCache.addRef();
  42412. }
  42413. return setupModelRenderCache;
  42414. };
  42415. RenderablePrim2D.prototype._createModelDataParts = function () {
  42416. var _this = this;
  42417. // Create the instance data parts of the primitive and store them
  42418. var parts = this.createInstanceDataParts();
  42419. this._instanceDataParts = parts;
  42420. // Check if the ModelRenderCache for this particular instance is also brand new, initialize it if it's the case
  42421. if (!this._modelRenderCache._partData) {
  42422. this._setupModelRenderCache(parts);
  42423. }
  42424. // The Rendering resources (Effect, VB, IB, Textures) are stored in the ModelRenderCache
  42425. // But it's the RenderGroup that will store all the Instanced related data to render all the primitive it owns.
  42426. // So for a given ModelKey we getOrAdd a GroupInstanceInfo that will store all these data
  42427. var gii = this.renderGroup._renderableData._renderGroupInstancesInfo.getOrAddWithFactory(this.modelKey, function (k) {
  42428. var res = new BABYLON.GroupInstanceInfo(_this.renderGroup, _this._modelRenderCache, _this._modelRenderCache._partData.length);
  42429. for (var j = 0; j < _this._modelRenderCache._partData.length; j++) {
  42430. var part = _this._instanceDataParts[j];
  42431. res.partIndexFromId.add(part.id.toString(), j);
  42432. res.usedShaderCategories[j] = ";" + _this.getUsedShaderCategories(part).join(";") + ";";
  42433. res.strides[j] = _this._modelRenderCache._partData[j]._partDataStride;
  42434. }
  42435. return res;
  42436. });
  42437. // Get the GroupInfoDataPart corresponding to the render category of the part
  42438. var rm = 0;
  42439. var gipd = null;
  42440. if (this.isTransparent) {
  42441. gipd = gii.transparentData;
  42442. rm = BABYLON.Render2DContext.RenderModeTransparent;
  42443. }
  42444. else if (this.isAlphaTest) {
  42445. gipd = gii.alphaTestData;
  42446. rm = BABYLON.Render2DContext.RenderModeAlphaTest;
  42447. }
  42448. else {
  42449. gipd = gii.opaqueData;
  42450. rm = BABYLON.Render2DContext.RenderModeOpaque;
  42451. }
  42452. // For each instance data part of the primitive, allocate the instanced element it needs for render
  42453. for (var i = 0; i < parts.length; i++) {
  42454. var part = parts[i];
  42455. part.dataBuffer = gipd[i]._partData;
  42456. part.allocElements();
  42457. part.renderMode = rm;
  42458. part.groupInstanceInfo = gii;
  42459. }
  42460. return gii;
  42461. };
  42462. RenderablePrim2D.prototype._setupModelRenderCache = function (parts) {
  42463. var ctiArray = new Array();
  42464. this._modelRenderCache._partData = new Array();
  42465. for (var _i = 0; _i < parts.length; _i++) {
  42466. var dataPart = parts[_i];
  42467. var pd = new BABYLON.ModelRenderCachePartData();
  42468. this._modelRenderCache._partData.push(pd);
  42469. var cat = this.getUsedShaderCategories(dataPart);
  42470. var cti = dataPart.getClassTreeInfo();
  42471. // Make sure the instance is visible other the properties won't be set and their size/offset wont be computed
  42472. var curVisible = this.isVisible;
  42473. this.isVisible = true;
  42474. // 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.
  42475. //console.log("Build Prop Layout for " + Tools.getClassName(this._instanceDataParts[0]));
  42476. var joinCat = ";" + cat.join(";") + ";";
  42477. pd._partJoinedUsedCategories = joinCat;
  42478. InstanceClassInfo._CurCategories = joinCat;
  42479. var obj = this.beforeRefreshForLayoutConstruction(dataPart);
  42480. if (!this.refreshInstanceDataPart(dataPart)) {
  42481. console.log("Layout construction for " + BABYLON.Tools.getClassName(this._instanceDataParts[0]) + " failed because refresh returned false");
  42482. }
  42483. this.afterRefreshForLayoutConstruction(dataPart, obj);
  42484. this.isVisible = curVisible;
  42485. var size = 0;
  42486. cti.fullContent.forEach(function (k, v) {
  42487. if (!v.category || cat.indexOf(v.category) !== -1) {
  42488. if (v.attributeName === "zBias") {
  42489. pd._zBiasOffset = v.instanceOffset.get(joinCat);
  42490. }
  42491. if (!v.size) {
  42492. console.log("ERROR: Couldn't detect the size of the Property " + v.attributeName + " from type " + BABYLON.Tools.getClassName(cti.type) + ". Property is ignored.");
  42493. }
  42494. else {
  42495. size += v.size;
  42496. }
  42497. }
  42498. });
  42499. pd._partDataStride = size;
  42500. pd._partUsedCategories = cat;
  42501. pd._partId = dataPart.id;
  42502. ctiArray.push(cti);
  42503. }
  42504. this._modelRenderCache._partsClassInfo = ctiArray;
  42505. };
  42506. RenderablePrim2D.prototype.onZOrderChanged = function () {
  42507. if (this.isTransparent && this._transparentPrimitiveInfo) {
  42508. this.renderGroup._renderableData.transparentPrimitiveZChanged(this._transparentPrimitiveInfo);
  42509. var gii = this.renderGroup._renderableData._renderGroupInstancesInfo.get(this.modelKey);
  42510. // Flag the transparentData dirty has will have to sort it again
  42511. gii.transparentOrderDirty = true;
  42512. }
  42513. };
  42514. RenderablePrim2D.prototype._mustUpdateInstance = function () {
  42515. return false;
  42516. };
  42517. RenderablePrim2D.prototype._useTextureAlpha = function () {
  42518. return false;
  42519. };
  42520. RenderablePrim2D.prototype._shouldUseAlphaFromTexture = function () {
  42521. return false;
  42522. };
  42523. RenderablePrim2D.prototype._isPrimAlphaTest = function () {
  42524. return false;
  42525. };
  42526. RenderablePrim2D.prototype._isPrimTransparent = function () {
  42527. return false;
  42528. };
  42529. RenderablePrim2D.prototype._updateInstanceDataParts = function (gii) {
  42530. // Fetch the GroupInstanceInfo if we don't already have it
  42531. var rd = this.renderGroup._renderableData;
  42532. if (!gii) {
  42533. gii = rd._renderGroupInstancesInfo.get(this.modelKey);
  42534. }
  42535. var isTransparent = this.isTransparent;
  42536. var isAlphaTest = this.isAlphaTest;
  42537. var wereTransparent = false;
  42538. // Check a render mode change
  42539. var rmChanged = false;
  42540. if (this._instanceDataParts.length > 0) {
  42541. var firstPart = this._instanceDataParts[0];
  42542. var partRM = firstPart.renderMode;
  42543. var curRM = this.renderMode;
  42544. if (partRM !== curRM) {
  42545. wereTransparent = partRM === BABYLON.Render2DContext.RenderModeTransparent;
  42546. rmChanged = true;
  42547. var gipd;
  42548. switch (curRM) {
  42549. case BABYLON.Render2DContext.RenderModeTransparent:
  42550. gipd = gii.transparentData;
  42551. break;
  42552. case BABYLON.Render2DContext.RenderModeAlphaTest:
  42553. gipd = gii.alphaTestData;
  42554. break;
  42555. default:
  42556. gipd = gii.opaqueData;
  42557. }
  42558. for (var i = 0; i < this._instanceDataParts.length; i++) {
  42559. var part = this._instanceDataParts[i];
  42560. part.freeElements();
  42561. part.dataBuffer = gipd[i]._partData;
  42562. part.renderMode = curRM;
  42563. }
  42564. }
  42565. }
  42566. // Handle changes related to ZOffset
  42567. var visChanged = this._isFlagSet(BABYLON.SmartPropertyPrim.flagVisibilityChanged);
  42568. if (isTransparent || wereTransparent) {
  42569. // Handle visibility change, which is also triggered when the primitive just got created
  42570. if (visChanged || rmChanged) {
  42571. if (this.isVisible && !wereTransparent) {
  42572. if (!this._transparentPrimitiveInfo) {
  42573. // Add the primitive to the list of transparent ones in the group that render is
  42574. this._transparentPrimitiveInfo = rd.addNewTransparentPrimitiveInfo(this, gii);
  42575. }
  42576. }
  42577. else {
  42578. if (this._transparentPrimitiveInfo) {
  42579. rd.removeTransparentPrimitiveInfo(this._transparentPrimitiveInfo);
  42580. this._transparentPrimitiveInfo = null;
  42581. }
  42582. }
  42583. gii.transparentOrderDirty = true;
  42584. }
  42585. }
  42586. var rebuildTrans = false;
  42587. // For each Instance Data part, refresh it to update the data in the DynamicFloatArray
  42588. for (var _i = 0, _a = this._instanceDataParts; _i < _a.length; _i++) {
  42589. var part = _a[_i];
  42590. var justAllocated = false;
  42591. // Check if we need to allocate data elements (hidden prim which becomes visible again)
  42592. if (!part.dataElements && (visChanged || rmChanged || this.isVisible)) {
  42593. part.allocElements();
  42594. justAllocated = true;
  42595. }
  42596. InstanceClassInfo._CurCategories = gii.usedShaderCategories[gii.partIndexFromId.get(part.id.toString())];
  42597. // Will return false if the instance should not be rendered (not visible or other any reasons)
  42598. part.arrayLengthChanged = false;
  42599. if (!this.refreshInstanceDataPart(part)) {
  42600. // Free the data element
  42601. if (part.dataElements) {
  42602. part.freeElements();
  42603. }
  42604. }
  42605. rebuildTrans = rebuildTrans || part.arrayLengthChanged || justAllocated;
  42606. }
  42607. this._instanceDirtyFlags = 0;
  42608. // Make the appropriate data dirty
  42609. if (isTransparent) {
  42610. gii.transparentDirty = true;
  42611. if (rebuildTrans) {
  42612. rd._transparentListChanged = true;
  42613. }
  42614. }
  42615. else if (isAlphaTest) {
  42616. gii.alphaTestDirty = true;
  42617. }
  42618. else {
  42619. gii.opaqueDirty = true;
  42620. }
  42621. this._clearFlags(BABYLON.SmartPropertyPrim.flagVisibilityChanged); // Reset the flag as we've handled the case
  42622. };
  42623. RenderablePrim2D.prototype._updateTransparentSegmentIndices = function (ts) {
  42624. var minOff = BABYLON.Prim2DBase._bigInt;
  42625. var maxOff = 0;
  42626. for (var _i = 0, _a = this._instanceDataParts; _i < _a.length; _i++) {
  42627. var part = _a[_i];
  42628. if (part && part.dataElements) {
  42629. part.dataBuffer.pack();
  42630. for (var _b = 0, _c = part.dataElements; _b < _c.length; _b++) {
  42631. var el = _c[_b];
  42632. minOff = Math.min(minOff, el.offset);
  42633. maxOff = Math.max(maxOff, el.offset);
  42634. }
  42635. ts.startDataIndex = Math.min(ts.startDataIndex, minOff / part.dataBuffer.stride);
  42636. ts.endDataIndex = Math.max(ts.endDataIndex, (maxOff / part.dataBuffer.stride) + 1); // +1 for exclusive
  42637. }
  42638. }
  42639. };
  42640. // This internal method is mainly used for transparency processing
  42641. RenderablePrim2D.prototype._getNextPrimZOrder = function () {
  42642. var length = this._instanceDataParts.length;
  42643. for (var i = 0; i < length; i++) {
  42644. var part = this._instanceDataParts[i];
  42645. if (part) {
  42646. var stride = part.dataBuffer.stride;
  42647. var lastElementOffset = part.dataElements[part.dataElements.length - 1].offset;
  42648. // check if it's the last in the DFA
  42649. if (part.dataBuffer.totalElementCount * stride <= lastElementOffset) {
  42650. return null;
  42651. }
  42652. // Return the Z of the next primitive that lies in the DFA
  42653. return part.dataBuffer[lastElementOffset + stride + this.modelRenderCache._partData[i]._zBiasOffset];
  42654. }
  42655. }
  42656. return null;
  42657. };
  42658. // This internal method is mainly used for transparency processing
  42659. RenderablePrim2D.prototype._getPrevPrimZOrder = function () {
  42660. var length = this._instanceDataParts.length;
  42661. for (var i = 0; i < length; i++) {
  42662. var part = this._instanceDataParts[i];
  42663. if (part) {
  42664. var stride = part.dataBuffer.stride;
  42665. var firstElementOffset = part.dataElements[0].offset;
  42666. // check if it's the first in the DFA
  42667. if (firstElementOffset === 0) {
  42668. return null;
  42669. }
  42670. // Return the Z of the previous primitive that lies in the DFA
  42671. return part.dataBuffer[firstElementOffset - stride + this.modelRenderCache._partData[i]._zBiasOffset];
  42672. }
  42673. }
  42674. return null;
  42675. };
  42676. /**
  42677. * Transform a given point using the Primitive's origin setting.
  42678. * This method requires the Primitive's actualSize to be accurate
  42679. * @param p the point to transform
  42680. * @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.
  42681. * @param res an allocated Vector2 that will receive the transformed content
  42682. */
  42683. RenderablePrim2D.prototype.transformPointWithOriginByRef = function (p, originOffset, res) {
  42684. var actualSize = this.actualSize;
  42685. res.x = p.x - ((this.origin.x + (originOffset ? originOffset.x : 0)) * actualSize.width);
  42686. res.y = p.y - ((this.origin.y + (originOffset ? originOffset.y : 0)) * actualSize.height);
  42687. };
  42688. RenderablePrim2D.prototype.transformPointWithOriginToRef = function (p, originOffset, res) {
  42689. this.transformPointWithOriginByRef(p, originOffset, res);
  42690. return res;
  42691. };
  42692. /**
  42693. * Get the info for a given effect based on the dataPart metadata
  42694. * @param dataPartId partId in part list to get the info
  42695. * @param vertexBufferAttributes vertex buffer attributes to manually add
  42696. * @param uniforms uniforms to manually add
  42697. * @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
  42698. */
  42699. RenderablePrim2D.prototype.getDataPartEffectInfo = function (dataPartId, vertexBufferAttributes, uniforms, useInstanced) {
  42700. if (uniforms === void 0) { uniforms = null; }
  42701. if (useInstanced === void 0) { useInstanced = null; }
  42702. var dataPart = BABYLON.Tools.first(this._instanceDataParts, function (i) { return i.id === dataPartId; });
  42703. if (!dataPart) {
  42704. return null;
  42705. }
  42706. var instancedArray = this.owner.supportInstancedArray;
  42707. if (useInstanced != null) {
  42708. // Check if the caller ask for Instanced Array and the engine does not support it, return null if it's the case
  42709. if (useInstanced && instancedArray === false) {
  42710. return null;
  42711. }
  42712. // Use the caller's setting
  42713. instancedArray = useInstanced;
  42714. }
  42715. var cti = dataPart.getClassTreeInfo();
  42716. var categories = this.getUsedShaderCategories(dataPart);
  42717. var att = cti.classContent.getShaderAttributes(categories);
  42718. var defines = "";
  42719. categories.forEach(function (c) { defines += "#define " + c + "\n"; });
  42720. if (instancedArray) {
  42721. defines += "#define Instanced\n";
  42722. }
  42723. return {
  42724. attributes: instancedArray ? vertexBufferAttributes.concat(att) : vertexBufferAttributes,
  42725. uniforms: instancedArray ? (uniforms != null ? uniforms : []) : ((uniforms != null) ? att.concat(uniforms) : (att != null ? att : [])),
  42726. defines: defines
  42727. };
  42728. };
  42729. Object.defineProperty(RenderablePrim2D.prototype, "modelRenderCache", {
  42730. get: function () {
  42731. return this._modelRenderCache;
  42732. },
  42733. enumerable: true,
  42734. configurable: true
  42735. });
  42736. RenderablePrim2D.prototype.createModelRenderCache = function (modelKey) {
  42737. return null;
  42738. };
  42739. RenderablePrim2D.prototype.setupModelRenderCache = function (modelRenderCache) {
  42740. };
  42741. RenderablePrim2D.prototype.createInstanceDataParts = function () {
  42742. return null;
  42743. };
  42744. RenderablePrim2D.prototype.getUsedShaderCategories = function (dataPart) {
  42745. return [];
  42746. };
  42747. RenderablePrim2D.prototype.beforeRefreshForLayoutConstruction = function (part) {
  42748. };
  42749. RenderablePrim2D.prototype.afterRefreshForLayoutConstruction = function (part, obj) {
  42750. };
  42751. RenderablePrim2D.prototype.refreshInstanceDataPart = function (part) {
  42752. if (!this.isVisible) {
  42753. return false;
  42754. }
  42755. part.isVisible = this.isVisible;
  42756. // 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)
  42757. if (part.dataElementCount === 1) {
  42758. part.curElement = 0;
  42759. this.updateInstanceDataPart(part);
  42760. }
  42761. return true;
  42762. };
  42763. /**
  42764. * Update the instanceDataBase level properties of a part
  42765. * @param part the part to update
  42766. * @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).
  42767. */
  42768. RenderablePrim2D.prototype.updateInstanceDataPart = function (part, positionOffset) {
  42769. if (positionOffset === void 0) { positionOffset = null; }
  42770. var t = this._globalTransform.multiply(this.renderGroup.invGlobalTransform);
  42771. var size = this.renderGroup.viewportSize;
  42772. var zBias = this.actualZOffset;
  42773. var offX = 0;
  42774. var offY = 0;
  42775. // If there's an offset, apply the global transformation matrix on it to get a global offset
  42776. if (positionOffset) {
  42777. offX = positionOffset.x * t.m[0] + positionOffset.y * t.m[4];
  42778. offY = positionOffset.x * t.m[1] + positionOffset.y * t.m[5];
  42779. }
  42780. // 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
  42781. // Current coordinates are expressed in renderGroup coordinates ([0, renderGroup.actualSize.width|height]) with 0,0 being at the left/top corner
  42782. // So for X:
  42783. // - tx.x = value * 2 / width: is to switch from [0, renderGroup.width] to [0, 2]
  42784. // - 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].
  42785. var w = size.width;
  42786. var h = size.height;
  42787. var invZBias = 1 / zBias;
  42788. 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);
  42789. 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);
  42790. part.transformX = tx;
  42791. part.transformY = ty;
  42792. part.opacity = this.actualOpacity;
  42793. // 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)
  42794. part.zBias = new BABYLON.Vector2(zBias, invZBias);
  42795. };
  42796. RenderablePrim2D.prototype._updateRenderMode = function () {
  42797. if (this.isTransparent) {
  42798. this._renderMode = BABYLON.Render2DContext.RenderModeTransparent;
  42799. }
  42800. else if (this.isAlphaTest) {
  42801. this._renderMode = BABYLON.Render2DContext.RenderModeAlphaTest;
  42802. }
  42803. else {
  42804. this._renderMode = BABYLON.Render2DContext.RenderModeOpaque;
  42805. }
  42806. };
  42807. RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT = BABYLON.Prim2DBase.PRIM2DBASE_PROPCOUNT + 5;
  42808. __decorate([
  42809. BABYLON.dynamicLevelProperty(BABYLON.Prim2DBase.PRIM2DBASE_PROPCOUNT + 0, function (pi) { return RenderablePrim2D.isAlphaTestProperty = pi; })
  42810. ], RenderablePrim2D.prototype, "isAlphaTest", null);
  42811. __decorate([
  42812. BABYLON.dynamicLevelProperty(BABYLON.Prim2DBase.PRIM2DBASE_PROPCOUNT + 1, function (pi) { return RenderablePrim2D.isTransparentProperty = pi; })
  42813. ], RenderablePrim2D.prototype, "isTransparent", null);
  42814. RenderablePrim2D = __decorate([
  42815. BABYLON.className("RenderablePrim2D")
  42816. ], RenderablePrim2D);
  42817. return RenderablePrim2D;
  42818. })(BABYLON.Prim2DBase);
  42819. BABYLON.RenderablePrim2D = RenderablePrim2D;
  42820. })(BABYLON || (BABYLON = {}));
  42821. var BABYLON;
  42822. (function (BABYLON) {
  42823. var Shape2D = (function (_super) {
  42824. __extends(Shape2D, _super);
  42825. function Shape2D(settings) {
  42826. _super.call(this, settings);
  42827. if (!settings) {
  42828. settings = {};
  42829. }
  42830. var borderBrush = null;
  42831. if (settings.border) {
  42832. if (typeof (settings.border) === "string") {
  42833. borderBrush = BABYLON.Canvas2D.GetBrushFromString(settings.border);
  42834. }
  42835. else {
  42836. borderBrush = settings.border;
  42837. }
  42838. }
  42839. var fillBrush = null;
  42840. if (settings.fill) {
  42841. if (typeof (settings.fill) === "string") {
  42842. fillBrush = BABYLON.Canvas2D.GetBrushFromString(settings.fill);
  42843. }
  42844. else {
  42845. fillBrush = settings.fill;
  42846. }
  42847. }
  42848. this._isTransparent = false;
  42849. this._oldTransparent = false;
  42850. this.border = borderBrush;
  42851. this.fill = fillBrush;
  42852. this._updateTransparencyStatus();
  42853. this.borderThickness = settings.borderThickness;
  42854. }
  42855. Object.defineProperty(Shape2D.prototype, "border", {
  42856. get: function () {
  42857. return this._border;
  42858. },
  42859. set: function (value) {
  42860. this._border = value;
  42861. this._updateTransparencyStatus();
  42862. },
  42863. enumerable: true,
  42864. configurable: true
  42865. });
  42866. Object.defineProperty(Shape2D.prototype, "fill", {
  42867. /**
  42868. * Get/set the brush to render the Fill part of the Primitive
  42869. */
  42870. get: function () {
  42871. return this._fill;
  42872. },
  42873. set: function (value) {
  42874. this._fill = value;
  42875. this._updateTransparencyStatus();
  42876. },
  42877. enumerable: true,
  42878. configurable: true
  42879. });
  42880. Object.defineProperty(Shape2D.prototype, "borderThickness", {
  42881. get: function () {
  42882. return this._borderThickness;
  42883. },
  42884. set: function (value) {
  42885. this._borderThickness = value;
  42886. },
  42887. enumerable: true,
  42888. configurable: true
  42889. });
  42890. Shape2D.prototype.getUsedShaderCategories = function (dataPart) {
  42891. var cat = _super.prototype.getUsedShaderCategories.call(this, dataPart);
  42892. // Fill Part
  42893. if (dataPart.id === Shape2D.SHAPE2D_FILLPARTID) {
  42894. var fill = this.fill;
  42895. if (fill instanceof BABYLON.SolidColorBrush2D) {
  42896. cat.push(Shape2D.SHAPE2D_CATEGORY_FILLSOLID);
  42897. }
  42898. if (fill instanceof BABYLON.GradientColorBrush2D) {
  42899. cat.push(Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT);
  42900. }
  42901. }
  42902. // Border Part
  42903. if (dataPart.id === Shape2D.SHAPE2D_BORDERPARTID) {
  42904. cat.push(Shape2D.SHAPE2D_CATEGORY_BORDER);
  42905. var border = this.border;
  42906. if (border instanceof BABYLON.SolidColorBrush2D) {
  42907. cat.push(Shape2D.SHAPE2D_CATEGORY_BORDERSOLID);
  42908. }
  42909. if (border instanceof BABYLON.GradientColorBrush2D) {
  42910. cat.push(Shape2D.SHAPE2D_CATEGORY_BORDERGRADIENT);
  42911. }
  42912. }
  42913. return cat;
  42914. };
  42915. Shape2D.prototype.refreshInstanceDataPart = function (part) {
  42916. if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
  42917. return false;
  42918. }
  42919. // Fill Part
  42920. if (part.id === Shape2D.SHAPE2D_FILLPARTID) {
  42921. var d = part;
  42922. if (this.fill) {
  42923. var fill = this.fill;
  42924. if (fill instanceof BABYLON.SolidColorBrush2D) {
  42925. d.fillSolidColor = fill.color;
  42926. }
  42927. else if (fill instanceof BABYLON.GradientColorBrush2D) {
  42928. d.fillGradientColor1 = fill.color1;
  42929. d.fillGradientColor2 = fill.color2;
  42930. 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));
  42931. var ty = new BABYLON.Vector4(t.m[1], t.m[5], t.m[9], t.m[13]);
  42932. d.fillGradientTY = ty;
  42933. }
  42934. }
  42935. }
  42936. else if (part.id === Shape2D.SHAPE2D_BORDERPARTID) {
  42937. var d = part;
  42938. if (this.border) {
  42939. d.borderThickness = this.borderThickness;
  42940. var border = this.border;
  42941. if (border instanceof BABYLON.SolidColorBrush2D) {
  42942. d.borderSolidColor = border.color;
  42943. }
  42944. else if (border instanceof BABYLON.GradientColorBrush2D) {
  42945. d.borderGradientColor1 = border.color1;
  42946. d.borderGradientColor2 = border.color2;
  42947. 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));
  42948. var ty = new BABYLON.Vector4(t.m[1], t.m[5], t.m[9], t.m[13]);
  42949. d.borderGradientTY = ty;
  42950. }
  42951. }
  42952. }
  42953. return true;
  42954. };
  42955. Shape2D.prototype._updateTransparencyStatus = function () {
  42956. this._isTransparent = (this._border && this._border.isTransparent()) || (this._fill && this._fill.isTransparent()) || (this.actualOpacity < 1);
  42957. if (this._isTransparent !== this._oldTransparent) {
  42958. this._oldTransparent = this._isTransparent;
  42959. this._updateRenderMode();
  42960. }
  42961. };
  42962. Shape2D.prototype._mustUpdateInstance = function () {
  42963. var res = this._oldTransparent !== this._isTransparent;
  42964. if (res) {
  42965. this._updateRenderMode();
  42966. this._oldTransparent = this._isTransparent;
  42967. }
  42968. return res;
  42969. };
  42970. Shape2D.prototype._isPrimTransparent = function () {
  42971. return this._isTransparent;
  42972. };
  42973. Shape2D.SHAPE2D_BORDERPARTID = 1;
  42974. Shape2D.SHAPE2D_FILLPARTID = 2;
  42975. Shape2D.SHAPE2D_CATEGORY_BORDER = "Border";
  42976. Shape2D.SHAPE2D_CATEGORY_BORDERSOLID = "BorderSolid";
  42977. Shape2D.SHAPE2D_CATEGORY_BORDERGRADIENT = "BorderGradient";
  42978. Shape2D.SHAPE2D_CATEGORY_FILLSOLID = "FillSolid";
  42979. Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT = "FillGradient";
  42980. Shape2D.SHAPE2D_PROPCOUNT = BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 5;
  42981. __decorate([
  42982. BABYLON.modelLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 1, function (pi) { return Shape2D.borderProperty = pi; }, true)
  42983. ], Shape2D.prototype, "border", null);
  42984. __decorate([
  42985. BABYLON.modelLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 2, function (pi) { return Shape2D.fillProperty = pi; }, true)
  42986. ], Shape2D.prototype, "fill", null);
  42987. __decorate([
  42988. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 3, function (pi) { return Shape2D.borderThicknessProperty = pi; })
  42989. ], Shape2D.prototype, "borderThickness", null);
  42990. Shape2D = __decorate([
  42991. BABYLON.className("Shape2D")
  42992. ], Shape2D);
  42993. return Shape2D;
  42994. })(BABYLON.RenderablePrim2D);
  42995. BABYLON.Shape2D = Shape2D;
  42996. var Shape2DInstanceData = (function (_super) {
  42997. __extends(Shape2DInstanceData, _super);
  42998. function Shape2DInstanceData() {
  42999. _super.apply(this, arguments);
  43000. }
  43001. Object.defineProperty(Shape2DInstanceData.prototype, "fillSolidColor", {
  43002. // FILL ATTRIBUTES
  43003. get: function () {
  43004. return null;
  43005. },
  43006. enumerable: true,
  43007. configurable: true
  43008. });
  43009. Object.defineProperty(Shape2DInstanceData.prototype, "fillGradientColor1", {
  43010. get: function () {
  43011. return null;
  43012. },
  43013. enumerable: true,
  43014. configurable: true
  43015. });
  43016. Object.defineProperty(Shape2DInstanceData.prototype, "fillGradientColor2", {
  43017. get: function () {
  43018. return null;
  43019. },
  43020. enumerable: true,
  43021. configurable: true
  43022. });
  43023. Object.defineProperty(Shape2DInstanceData.prototype, "fillGradientTY", {
  43024. get: function () {
  43025. return null;
  43026. },
  43027. enumerable: true,
  43028. configurable: true
  43029. });
  43030. Object.defineProperty(Shape2DInstanceData.prototype, "borderThickness", {
  43031. // BORDER ATTRIBUTES
  43032. get: function () {
  43033. return null;
  43034. },
  43035. enumerable: true,
  43036. configurable: true
  43037. });
  43038. Object.defineProperty(Shape2DInstanceData.prototype, "borderSolidColor", {
  43039. get: function () {
  43040. return null;
  43041. },
  43042. enumerable: true,
  43043. configurable: true
  43044. });
  43045. Object.defineProperty(Shape2DInstanceData.prototype, "borderGradientColor1", {
  43046. get: function () {
  43047. return null;
  43048. },
  43049. enumerable: true,
  43050. configurable: true
  43051. });
  43052. Object.defineProperty(Shape2DInstanceData.prototype, "borderGradientColor2", {
  43053. get: function () {
  43054. return null;
  43055. },
  43056. enumerable: true,
  43057. configurable: true
  43058. });
  43059. Object.defineProperty(Shape2DInstanceData.prototype, "borderGradientTY", {
  43060. get: function () {
  43061. return null;
  43062. },
  43063. enumerable: true,
  43064. configurable: true
  43065. });
  43066. __decorate([
  43067. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_FILLSOLID)
  43068. ], Shape2DInstanceData.prototype, "fillSolidColor", null);
  43069. __decorate([
  43070. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT)
  43071. ], Shape2DInstanceData.prototype, "fillGradientColor1", null);
  43072. __decorate([
  43073. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT)
  43074. ], Shape2DInstanceData.prototype, "fillGradientColor2", null);
  43075. __decorate([
  43076. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT)
  43077. ], Shape2DInstanceData.prototype, "fillGradientTY", null);
  43078. __decorate([
  43079. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_BORDER)
  43080. ], Shape2DInstanceData.prototype, "borderThickness", null);
  43081. __decorate([
  43082. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_BORDERSOLID)
  43083. ], Shape2DInstanceData.prototype, "borderSolidColor", null);
  43084. __decorate([
  43085. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_BORDERGRADIENT)
  43086. ], Shape2DInstanceData.prototype, "borderGradientColor1", null);
  43087. __decorate([
  43088. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_BORDERGRADIENT)
  43089. ], Shape2DInstanceData.prototype, "borderGradientColor2", null);
  43090. __decorate([
  43091. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_BORDERGRADIENT)
  43092. ], Shape2DInstanceData.prototype, "borderGradientTY", null);
  43093. return Shape2DInstanceData;
  43094. })(BABYLON.InstanceDataBase);
  43095. BABYLON.Shape2DInstanceData = Shape2DInstanceData;
  43096. })(BABYLON || (BABYLON = {}));
  43097. var BABYLON;
  43098. (function (BABYLON) {
  43099. var Group2D = (function (_super) {
  43100. __extends(Group2D, _super);
  43101. /**
  43102. * Create an Logical or Renderable Group.
  43103. * @param settings a combination of settings, possible ones are
  43104. * - 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)
  43105. * - children: an array of direct children
  43106. * - id a text identifier, for information purpose
  43107. * - position: the X & Y positions relative to its parent. Alternatively the x and y properties can be set. Default is [0;0]
  43108. * - rotation: the initial rotation (in radian) of the primitive. default is 0
  43109. * - scale: the initial scale of the primitive. default is 1. You can alternatively use scaleX &| scaleY to apply non uniform scale
  43110. * - opacity: set the overall opacity of the primitive, 1 to be opaque (default), less than 1 to be transparent.
  43111. * - zOrder: override the zOrder with the specified value
  43112. * - origin: define the normalized origin point location, default [0.5;0.5]
  43113. * - 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.
  43114. * - cacheBehavior: Define how the group should behave regarding the Canvas's cache strategy, default is Group2D.GROUPCACHEBEHAVIOR_FOLLOWCACHESTRATEGY
  43115. * - 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).
  43116. * - isVisible: true if the group must be visible, false for hidden. Default is true.
  43117. * - 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!
  43118. * - marginTop: top margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  43119. * - marginLeft: left margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  43120. * - marginRight: right margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  43121. * - marginBottom: bottom margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  43122. * - margin: top, left, right and bottom margin formatted as a single string (see PrimitiveThickness.fromString)
  43123. * - marginHAlignment: one value of the PrimitiveAlignment type's static properties
  43124. * - marginVAlignment: one value of the PrimitiveAlignment type's static properties
  43125. * - marginAlignment: a string defining the alignment, see PrimitiveAlignment.fromString
  43126. * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  43127. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  43128. * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  43129. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  43130. * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
  43131. */
  43132. function Group2D(settings) {
  43133. if (settings == null) {
  43134. settings = {};
  43135. }
  43136. if (settings.origin == null) {
  43137. settings.origin = new BABYLON.Vector2(0, 0);
  43138. }
  43139. _super.call(this, settings);
  43140. var size = (!settings.size && !settings.width && !settings.height) ? null : (settings.size || (new BABYLON.Size(settings.width || 0, settings.height || 0)));
  43141. this._trackedNode = (settings.trackNode == null) ? null : settings.trackNode;
  43142. if (this._trackedNode && this.owner) {
  43143. this.owner._registerTrackedNode(this);
  43144. }
  43145. this._cacheBehavior = (settings.cacheBehavior == null) ? Group2D.GROUPCACHEBEHAVIOR_FOLLOWCACHESTRATEGY : settings.cacheBehavior;
  43146. this.size = size;
  43147. this._viewportPosition = BABYLON.Vector2.Zero();
  43148. }
  43149. Group2D._createCachedCanvasGroup = function (owner) {
  43150. var g = new Group2D({ parent: owner, id: "__cachedCanvasGroup__", position: BABYLON.Vector2.Zero(), origin: BABYLON.Vector2.Zero(), size: null, isVisible: true });
  43151. return g;
  43152. };
  43153. Group2D.prototype.applyCachedTexture = function (vertexData, material) {
  43154. this._bindCacheTarget();
  43155. if (vertexData) {
  43156. var uv = vertexData.uvs;
  43157. var nodeuv = this._renderableData._cacheNodeUVs;
  43158. for (var i = 0; i < 4; i++) {
  43159. uv[i * 2 + 0] = nodeuv[i].x;
  43160. uv[i * 2 + 1] = nodeuv[i].y;
  43161. }
  43162. }
  43163. if (material) {
  43164. material.diffuseTexture = this._renderableData._cacheTexture;
  43165. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  43166. }
  43167. this._renderableData._cacheTexture.hasAlpha = true;
  43168. this._unbindCacheTarget();
  43169. };
  43170. Object.defineProperty(Group2D.prototype, "cachedRect", {
  43171. /**
  43172. * Allow you to access the information regarding the cached rectangle of the Group2D into the MapTexture.
  43173. * 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.
  43174. */
  43175. get: function () {
  43176. if (!this._renderableData) {
  43177. return null;
  43178. }
  43179. return this._renderableData._cacheNode;
  43180. },
  43181. enumerable: true,
  43182. configurable: true
  43183. });
  43184. Object.defineProperty(Group2D.prototype, "cachedUVs", {
  43185. /**
  43186. * The UVs into the MapTexture that map the cached group
  43187. */
  43188. get: function () {
  43189. if (!this._renderableData) {
  43190. return null;
  43191. }
  43192. return this._renderableData._cacheNodeUVs;
  43193. },
  43194. enumerable: true,
  43195. configurable: true
  43196. });
  43197. Object.defineProperty(Group2D.prototype, "cachedUVsChanged", {
  43198. get: function () {
  43199. if (!this._renderableData) {
  43200. return null;
  43201. }
  43202. if (!this._renderableData._cacheNodeUVsChangedObservable) {
  43203. this._renderableData._cacheNodeUVsChangedObservable = new BABYLON.Observable();
  43204. }
  43205. return this._renderableData._cacheNodeUVsChangedObservable;
  43206. },
  43207. enumerable: true,
  43208. configurable: true
  43209. });
  43210. Object.defineProperty(Group2D.prototype, "cacheTexture", {
  43211. /**
  43212. * Access the texture that maintains a cached version of the Group2D.
  43213. * This is useful only if you're not using a WorldSpaceNode for your WorldSpace Canvas and therefore need to perform the rendering yourself.
  43214. */
  43215. get: function () {
  43216. if (!this._renderableData) {
  43217. return null;
  43218. }
  43219. return this._renderableData._cacheTexture;
  43220. },
  43221. enumerable: true,
  43222. configurable: true
  43223. });
  43224. /**
  43225. * Call this method to remove this Group and its children from the Canvas
  43226. */
  43227. Group2D.prototype.dispose = function () {
  43228. if (!_super.prototype.dispose.call(this)) {
  43229. return false;
  43230. }
  43231. if (this._trackedNode != null) {
  43232. this.owner._unregisterTrackedNode(this);
  43233. this._trackedNode = null;
  43234. }
  43235. if (this._renderableData) {
  43236. this._renderableData.dispose(this.owner.engine);
  43237. this._renderableData = null;
  43238. }
  43239. return true;
  43240. };
  43241. Object.defineProperty(Group2D.prototype, "isRenderableGroup", {
  43242. /**
  43243. * @returns Returns true if the Group render content, false if it's a logical group only
  43244. */
  43245. get: function () {
  43246. return this._isRenderableGroup;
  43247. },
  43248. enumerable: true,
  43249. configurable: true
  43250. });
  43251. Object.defineProperty(Group2D.prototype, "isCachedGroup", {
  43252. /**
  43253. * @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
  43254. */
  43255. get: function () {
  43256. return this._isCachedGroup;
  43257. },
  43258. enumerable: true,
  43259. configurable: true
  43260. });
  43261. Object.defineProperty(Group2D.prototype, "size", {
  43262. get: function () {
  43263. return this._size;
  43264. },
  43265. /**
  43266. * Get/Set the size of the group. If null the size of the group will be determine from its content.
  43267. * 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.
  43268. */
  43269. set: function (val) {
  43270. this._size = val;
  43271. },
  43272. enumerable: true,
  43273. configurable: true
  43274. });
  43275. Object.defineProperty(Group2D.prototype, "viewportSize", {
  43276. get: function () {
  43277. return this._viewportSize;
  43278. },
  43279. enumerable: true,
  43280. configurable: true
  43281. });
  43282. Object.defineProperty(Group2D.prototype, "actualSize", {
  43283. get: function () {
  43284. // The computed size will be floor on both width and height
  43285. var actualSize;
  43286. // Return the size if set by the user
  43287. if (this._size) {
  43288. actualSize = new BABYLON.Size(Math.ceil(this._size.width), Math.ceil(this._size.height));
  43289. }
  43290. else {
  43291. var m = this.boundingInfo.max();
  43292. actualSize = new BABYLON.Size(Math.ceil(m.x), Math.ceil(m.y));
  43293. }
  43294. // 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)
  43295. if (!actualSize.equals(this._actualSize)) {
  43296. this.onPrimitivePropertyDirty(Group2D.actualSizeProperty.flagId);
  43297. this._actualSize = actualSize;
  43298. this.handleGroupChanged(Group2D.actualSizeProperty);
  43299. }
  43300. return actualSize;
  43301. },
  43302. enumerable: true,
  43303. configurable: true
  43304. });
  43305. Object.defineProperty(Group2D.prototype, "cacheBehavior", {
  43306. /**
  43307. * 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.
  43308. * 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.
  43309. */
  43310. get: function () {
  43311. return this._cacheBehavior;
  43312. },
  43313. enumerable: true,
  43314. configurable: true
  43315. });
  43316. Group2D.prototype._addPrimToDirtyList = function (prim) {
  43317. this._renderableData._primDirtyList.push(prim);
  43318. };
  43319. Group2D.prototype._renderCachedCanvas = function () {
  43320. this.owner._addGroupRenderCount(1);
  43321. this.updateCachedStates(true);
  43322. var context = new BABYLON.PrepareRender2DContext();
  43323. this._prepareGroupRender(context);
  43324. this._groupRender();
  43325. };
  43326. Object.defineProperty(Group2D.prototype, "trackedNode", {
  43327. /**
  43328. * Get/set the Scene's Node that should be tracked, the group's position will follow the projected position of the Node.
  43329. */
  43330. get: function () {
  43331. return this._trackedNode;
  43332. },
  43333. set: function (val) {
  43334. if (val != null) {
  43335. if (!this._isFlagSet(BABYLON.SmartPropertyPrim.flagTrackedGroup)) {
  43336. this.owner._registerTrackedNode(this);
  43337. }
  43338. this._trackedNode = val;
  43339. }
  43340. else {
  43341. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagTrackedGroup)) {
  43342. this.owner._unregisterTrackedNode(this);
  43343. }
  43344. this._trackedNode = null;
  43345. }
  43346. },
  43347. enumerable: true,
  43348. configurable: true
  43349. });
  43350. Group2D.prototype.levelIntersect = function (intersectInfo) {
  43351. // 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
  43352. return true;
  43353. };
  43354. Group2D.prototype.updateLevelBoundingInfo = function () {
  43355. var size;
  43356. // If the size is set by the user, the boundingInfo is computed from this value
  43357. if (this.size) {
  43358. size = this.size;
  43359. }
  43360. else {
  43361. size = new BABYLON.Size(0, 0);
  43362. }
  43363. BABYLON.BoundingInfo2D.CreateFromSizeToRef(size, this._levelBoundingInfo);
  43364. };
  43365. // Method called only on renderable groups to prepare the rendering
  43366. Group2D.prototype._prepareGroupRender = function (context) {
  43367. var sortedDirtyList = null;
  43368. // Update the Global Transformation and visibility status of the changed primitives
  43369. if ((this._renderableData._primDirtyList.length > 0) || context.forceRefreshPrimitive) {
  43370. sortedDirtyList = this._renderableData._primDirtyList.sort(function (a, b) { return a.hierarchyDepth - b.hierarchyDepth; });
  43371. this.updateCachedStatesOf(sortedDirtyList, true);
  43372. }
  43373. // Setup the size of the rendering viewport
  43374. // 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
  43375. if (!this._isCachedGroup) {
  43376. // Compute the WebGL viewport's location/size
  43377. var t = this._globalTransform.getTranslation();
  43378. var s = this.actualSize.clone();
  43379. var rs = this.owner._renderingSize;
  43380. s.height = Math.min(s.height, rs.height - t.y);
  43381. s.width = Math.min(s.width, rs.width - t.x);
  43382. var x = t.x;
  43383. var y = t.y;
  43384. // 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
  43385. this._viewportPosition.x = x;
  43386. this._viewportPosition.y = y;
  43387. var vw = s.width;
  43388. var vh = s.height;
  43389. if (!this._viewportSize) {
  43390. this._viewportSize = new BABYLON.Size(vw, vh);
  43391. }
  43392. else {
  43393. if (this._viewportSize.width !== vw || this._viewportSize.height !== vh) {
  43394. context.forceRefreshPrimitive = true;
  43395. }
  43396. this._viewportSize.width = vw;
  43397. this._viewportSize.height = vh;
  43398. }
  43399. }
  43400. else {
  43401. var newSize = this.actualSize.clone();
  43402. if (!newSize.equals(this._viewportSize)) {
  43403. context.forceRefreshPrimitive = true;
  43404. }
  43405. this._viewportSize = newSize;
  43406. }
  43407. if ((this._renderableData._primDirtyList.length > 0) || context.forceRefreshPrimitive) {
  43408. // If the group is cached, set the dirty flag to true because of the incoming changes
  43409. this._cacheGroupDirty = this._isCachedGroup;
  43410. // If it's a force refresh, prepare all the children
  43411. if (context.forceRefreshPrimitive) {
  43412. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  43413. var p = _a[_i];
  43414. p._prepareRender(context);
  43415. }
  43416. }
  43417. else {
  43418. // Each primitive that changed at least once was added into the primDirtyList, we have to sort this level using
  43419. // the hierarchyDepth in order to prepare primitives from top to bottom
  43420. if (!sortedDirtyList) {
  43421. sortedDirtyList = this._renderableData._primDirtyList.sort(function (a, b) { return a.hierarchyDepth - b.hierarchyDepth; });
  43422. }
  43423. sortedDirtyList.forEach(function (p) {
  43424. // 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.
  43425. // 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.
  43426. if (!p.isDisposed && p._needPrepare()) {
  43427. p._prepareRender(context);
  43428. }
  43429. });
  43430. }
  43431. // Everything is updated, clear the dirty list
  43432. this._renderableData._primDirtyList.forEach(function (p) { return p._resetPropertiesDirty(); });
  43433. this._renderableData._primDirtyList.splice(0);
  43434. }
  43435. // A renderable group has a list of direct children that are also renderable groups, we recurse on them to also prepare them
  43436. this._renderableData._childrenRenderableGroups.forEach(function (g) {
  43437. g._prepareGroupRender(context);
  43438. });
  43439. };
  43440. Group2D.prototype._groupRender = function () {
  43441. var _this = this;
  43442. var engine = this.owner.engine;
  43443. var failedCount = 0;
  43444. // First recurse to children render group to render them (in their cache or on screen)
  43445. for (var _i = 0, _a = this._renderableData._childrenRenderableGroups; _i < _a.length; _i++) {
  43446. var childGroup = _a[_i];
  43447. childGroup._groupRender();
  43448. }
  43449. // Render the primitives if needed: either if we don't cache the content or if the content is cached but has changed
  43450. if (!this.isCachedGroup || this._cacheGroupDirty) {
  43451. this.owner._addGroupRenderCount(1);
  43452. if (this.isCachedGroup) {
  43453. this._bindCacheTarget();
  43454. }
  43455. else {
  43456. var curVP = engine.setDirectViewport(this._viewportPosition.x, this._viewportPosition.y, this._viewportSize.width, this._viewportSize.height);
  43457. }
  43458. var curAlphaTest = engine.getAlphaTesting() === true;
  43459. var curDepthWrite = engine.getDepthWrite() === true;
  43460. // ===================================================================
  43461. // First pass, update the InstancedArray and render Opaque primitives
  43462. // Disable Alpha Testing, Enable Depth Write
  43463. engine.setAlphaTesting(false);
  43464. engine.setDepthWrite(true);
  43465. // For each different model of primitive to render
  43466. var context = new BABYLON.Render2DContext(BABYLON.Render2DContext.RenderModeOpaque);
  43467. this._renderableData._renderGroupInstancesInfo.forEach(function (k, v) {
  43468. // Prepare the context object, update the WebGL Instanced Array buffer if needed
  43469. var renderCount = _this._prepareContext(engine, context, v);
  43470. // If null is returned, there's no opaque data to render
  43471. if (renderCount === null) {
  43472. return;
  43473. }
  43474. // Submit render only if we have something to render (everything may be hidden and the floatarray empty)
  43475. if (!_this.owner.supportInstancedArray || renderCount > 0) {
  43476. // render all the instances of this model, if the render method returns true then our instances are no longer dirty
  43477. var renderFailed = !v.modelRenderCache.render(v, context);
  43478. // Update dirty flag/related
  43479. v.opaqueDirty = renderFailed;
  43480. failedCount += renderFailed ? 1 : 0;
  43481. }
  43482. });
  43483. // =======================================================================
  43484. // Second pass, update the InstancedArray and render AlphaTest primitives
  43485. // Enable Alpha Testing, Enable Depth Write
  43486. engine.setAlphaTesting(true);
  43487. engine.setDepthWrite(true);
  43488. // For each different model of primitive to render
  43489. context = new BABYLON.Render2DContext(BABYLON.Render2DContext.RenderModeAlphaTest);
  43490. this._renderableData._renderGroupInstancesInfo.forEach(function (k, v) {
  43491. // Prepare the context object, update the WebGL Instanced Array buffer if needed
  43492. var renderCount = _this._prepareContext(engine, context, v);
  43493. // If null is returned, there's no opaque data to render
  43494. if (renderCount === null) {
  43495. return;
  43496. }
  43497. // Submit render only if we have something to render (everything may be hidden and the floatarray empty)
  43498. if (!_this.owner.supportInstancedArray || renderCount > 0) {
  43499. // render all the instances of this model, if the render method returns true then our instances are no longer dirty
  43500. var renderFailed = !v.modelRenderCache.render(v, context);
  43501. // Update dirty flag/related
  43502. v.opaqueDirty = renderFailed;
  43503. failedCount += renderFailed ? 1 : 0;
  43504. }
  43505. });
  43506. // =======================================================================
  43507. // Third pass, transparent primitive rendering
  43508. // Enable Alpha Testing, Disable Depth Write
  43509. engine.setAlphaTesting(true);
  43510. engine.setDepthWrite(false);
  43511. // First Check if the transparent List change so we can update the TransparentSegment and PartData (sort if needed)
  43512. if (this._renderableData._transparentListChanged) {
  43513. this._updateTransparentData();
  43514. }
  43515. // From this point on we have up to date data to render, so let's go
  43516. failedCount += this._renderTransparentData();
  43517. // =======================================================================
  43518. // Unbind target/restore viewport setting, clear dirty flag, and quit
  43519. // The group's content is no longer dirty
  43520. this._cacheGroupDirty = failedCount !== 0;
  43521. if (this.isCachedGroup) {
  43522. this._unbindCacheTarget();
  43523. }
  43524. else {
  43525. if (curVP) {
  43526. engine.setViewport(curVP);
  43527. }
  43528. }
  43529. // Restore saved states
  43530. engine.setAlphaTesting(curAlphaTest);
  43531. engine.setDepthWrite(curDepthWrite);
  43532. }
  43533. };
  43534. Group2D.prototype._setCacheGroupDirty = function () {
  43535. this._cacheGroupDirty = true;
  43536. };
  43537. Group2D.prototype._updateTransparentData = function () {
  43538. this.owner._addUpdateTransparentDataCount(1);
  43539. var rd = this._renderableData;
  43540. // Sort all the primitive from their depth, max (bottom) to min (top)
  43541. rd._transparentPrimitives.sort(function (a, b) { return b._primitive.actualZOffset - a._primitive.actualZOffset; });
  43542. var checkAndAddPrimInSegment = function (seg, tpiI) {
  43543. var tpi = rd._transparentPrimitives[tpiI];
  43544. // Fast rejection: if gii are different
  43545. if (seg.groupInsanceInfo !== tpi._groupInstanceInfo) {
  43546. return false;
  43547. }
  43548. //let tpiZ = tpi._primitive.actualZOffset;
  43549. // We've made it so far, the tpi can be part of the segment, add it
  43550. tpi._transparentSegment = seg;
  43551. tpi._primitive._updateTransparentSegmentIndices(seg);
  43552. return true;
  43553. };
  43554. // Free the existing TransparentSegments
  43555. for (var _i = 0, _a = rd._transparentSegments; _i < _a.length; _i++) {
  43556. var ts = _a[_i];
  43557. ts.dispose(this.owner.engine);
  43558. }
  43559. rd._transparentSegments.splice(0);
  43560. var prevSeg = null;
  43561. for (var tpiI = 0; tpiI < rd._transparentPrimitives.length; tpiI++) {
  43562. var tpi = rd._transparentPrimitives[tpiI];
  43563. // Check if the Data in which the primitive is stored is not sorted properly
  43564. if (tpi._groupInstanceInfo.transparentOrderDirty) {
  43565. tpi._groupInstanceInfo.sortTransparentData();
  43566. }
  43567. // Reset the segment, we have to create/rebuild it
  43568. tpi._transparentSegment = null;
  43569. // If there's a previous valid segment, check if this prim can be part of it
  43570. if (prevSeg) {
  43571. checkAndAddPrimInSegment(prevSeg, tpiI);
  43572. }
  43573. // If we couldn't insert in the adjacent segments, he have to create one
  43574. if (!tpi._transparentSegment) {
  43575. var ts = new BABYLON.TransparentSegment();
  43576. ts.groupInsanceInfo = tpi._groupInstanceInfo;
  43577. var prim = tpi._primitive;
  43578. ts.startZ = prim.actualZOffset;
  43579. prim._updateTransparentSegmentIndices(ts);
  43580. ts.endZ = ts.startZ;
  43581. tpi._transparentSegment = ts;
  43582. rd._transparentSegments.push(ts);
  43583. }
  43584. // Update prevSeg
  43585. prevSeg = tpi._transparentSegment;
  43586. }
  43587. //rd._firstChangedPrim = null;
  43588. rd._transparentListChanged = false;
  43589. };
  43590. Group2D.prototype._renderTransparentData = function () {
  43591. var failedCount = 0;
  43592. var context = new BABYLON.Render2DContext(BABYLON.Render2DContext.RenderModeTransparent);
  43593. var rd = this._renderableData;
  43594. var useInstanced = this.owner.supportInstancedArray;
  43595. var length = rd._transparentSegments.length;
  43596. for (var i = 0; i < length; i++) {
  43597. context.instancedBuffers = null;
  43598. var ts = rd._transparentSegments[i];
  43599. var gii = ts.groupInsanceInfo;
  43600. var mrc = gii.modelRenderCache;
  43601. var engine = this.owner.engine;
  43602. var count = ts.endDataIndex - ts.startDataIndex;
  43603. // Use Instanced Array if it's supported and if there's at least 5 prims to draw.
  43604. // We don't want to create an Instanced Buffer for less that 5 prims
  43605. if (useInstanced && count >= 5) {
  43606. if (!ts.partBuffers) {
  43607. var buffers = new Array();
  43608. for (var j = 0; j < gii.transparentData.length; j++) {
  43609. var gitd = gii.transparentData[j];
  43610. var dfa = gitd._partData;
  43611. var data = dfa.pack();
  43612. var stride = dfa.stride;
  43613. var neededSize = count * stride * 4;
  43614. var buffer = engine.createInstancesBuffer(neededSize); // Create + bind
  43615. var segData = data.subarray(ts.startDataIndex * stride, ts.endDataIndex * stride);
  43616. engine.updateArrayBuffer(segData);
  43617. buffers.push(buffer);
  43618. }
  43619. ts.partBuffers = buffers;
  43620. }
  43621. else if (gii.transparentDirty) {
  43622. for (var j = 0; j < gii.transparentData.length; j++) {
  43623. var gitd = gii.transparentData[j];
  43624. var dfa = gitd._partData;
  43625. var data = dfa.pack();
  43626. var stride = dfa.stride;
  43627. var buffer = ts.partBuffers[j];
  43628. var segData = data.subarray(ts.startDataIndex * stride, ts.endDataIndex * stride);
  43629. engine.bindArrayBuffer(buffer);
  43630. engine.updateArrayBuffer(segData);
  43631. }
  43632. }
  43633. context.useInstancing = true;
  43634. context.instancesCount = count;
  43635. context.instancedBuffers = ts.partBuffers;
  43636. context.groupInfoPartData = gii.transparentData;
  43637. var renderFailed = !mrc.render(gii, context);
  43638. failedCount += renderFailed ? 1 : 0;
  43639. }
  43640. else {
  43641. context.useInstancing = false;
  43642. context.partDataStartIndex = ts.startDataIndex;
  43643. context.partDataEndIndex = ts.endDataIndex;
  43644. context.groupInfoPartData = gii.transparentData;
  43645. var renderFailed = !mrc.render(gii, context);
  43646. failedCount += renderFailed ? 1 : 0;
  43647. }
  43648. }
  43649. return failedCount;
  43650. };
  43651. Group2D.prototype._prepareContext = function (engine, context, gii) {
  43652. var gipd = null;
  43653. var setDirty;
  43654. var getDirty;
  43655. // Render Mode specifics
  43656. switch (context.renderMode) {
  43657. case BABYLON.Render2DContext.RenderModeOpaque:
  43658. {
  43659. if (!gii.hasOpaqueData) {
  43660. return null;
  43661. }
  43662. setDirty = function (dirty) { gii.opaqueDirty = dirty; };
  43663. getDirty = function () { return gii.opaqueDirty; };
  43664. context.groupInfoPartData = gii.opaqueData;
  43665. gipd = gii.opaqueData;
  43666. break;
  43667. }
  43668. case BABYLON.Render2DContext.RenderModeAlphaTest:
  43669. {
  43670. if (!gii.hasAlphaTestData) {
  43671. return null;
  43672. }
  43673. setDirty = function (dirty) { gii.alphaTestDirty = dirty; };
  43674. getDirty = function () { return gii.alphaTestDirty; };
  43675. context.groupInfoPartData = gii.alphaTestData;
  43676. gipd = gii.alphaTestData;
  43677. break;
  43678. }
  43679. default:
  43680. throw new Error("_prepareContext is only for opaque or alphaTest");
  43681. }
  43682. var renderCount = 0;
  43683. // This part will pack the dynamicfloatarray and update the instanced array WebGLBufffer
  43684. // Skip it if instanced arrays are not supported
  43685. if (this.owner.supportInstancedArray) {
  43686. // Flag for instancing
  43687. context.useInstancing = true;
  43688. // Make sure all the WebGLBuffers of the Instanced Array are created/up to date for the parts to render.
  43689. for (var i = 0; i < gipd.length; i++) {
  43690. var pid = gipd[i];
  43691. // If the instances of the model was changed, pack the data
  43692. var array = pid._partData;
  43693. var instanceData_1 = array.pack();
  43694. renderCount += array.usedElementCount;
  43695. // Compute the size the instance buffer should have
  43696. var neededSize = array.usedElementCount * array.stride * 4;
  43697. // Check if we have to (re)create the instancesBuffer because there's none or the size is too small
  43698. if (!pid._partBuffer || (pid._partBufferSize < neededSize)) {
  43699. if (pid._partBuffer) {
  43700. engine.deleteInstancesBuffer(pid._partBuffer);
  43701. }
  43702. pid._partBuffer = engine.createInstancesBuffer(neededSize); // Create + bind
  43703. pid._partBufferSize = neededSize;
  43704. setDirty(false);
  43705. // Update the WebGL buffer to match the new content of the instances data
  43706. engine.updateArrayBuffer(instanceData_1);
  43707. }
  43708. else if (getDirty()) {
  43709. // Update the WebGL buffer to match the new content of the instances data
  43710. engine.bindArrayBuffer(pid._partBuffer);
  43711. engine.updateArrayBuffer(instanceData_1);
  43712. }
  43713. }
  43714. setDirty(false);
  43715. }
  43716. else {
  43717. context.partDataStartIndex = 0;
  43718. // Find the first valid object to get the count
  43719. if (context.groupInfoPartData.length > 0) {
  43720. var i = 0;
  43721. while (!context.groupInfoPartData[i]) {
  43722. i++;
  43723. }
  43724. context.partDataEndIndex = context.groupInfoPartData[i]._partData.usedElementCount;
  43725. }
  43726. }
  43727. return renderCount;
  43728. };
  43729. Group2D.prototype._setRenderingScale = function (scale) {
  43730. if (this._renderableData._renderingScale === scale) {
  43731. return;
  43732. }
  43733. this._renderableData._renderingScale = scale;
  43734. };
  43735. Group2D.prototype._bindCacheTarget = function () {
  43736. var curWidth;
  43737. var curHeight;
  43738. var rd = this._renderableData;
  43739. var rs = rd._renderingScale;
  43740. Group2D._s.width = Math.ceil(this.actualSize.width * rs);
  43741. Group2D._s.height = Math.ceil(this.actualSize.height * rs);
  43742. var sizeChanged = !Group2D._s.equals(rd._cacheSize);
  43743. if (rd._cacheNode) {
  43744. var size = rd._cacheNode.contentSize;
  43745. // Check if we have to deallocate because the size is too small
  43746. if ((size.width < Group2D._s.width) || (size.height < Group2D._s.height)) {
  43747. // For Screen space: over-provisioning of 7% more to avoid frequent resizing for few pixels...
  43748. // For World space: no over-provisioning
  43749. var overprovisioning = this.owner.isScreenSpace ? 1.07 : 1;
  43750. curWidth = Math.floor(Group2D._s.width * overprovisioning);
  43751. curHeight = Math.floor(Group2D._s.height * overprovisioning);
  43752. //console.log(`[${this._globalTransformProcessStep}] Resize group ${this.id}, width: ${curWidth}, height: ${curHeight}`);
  43753. rd._cacheTexture.freeRect(rd._cacheNode);
  43754. rd._cacheNode = null;
  43755. }
  43756. }
  43757. if (!rd._cacheNode) {
  43758. // Check if we have to allocate a rendering zone in the global cache texture
  43759. var res = this.owner._allocateGroupCache(this, this.parent && this.parent.renderGroup, curWidth ? new BABYLON.Size(curWidth, curHeight) : null, rd._useMipMap, rd._anisotropicLevel);
  43760. rd._cacheNode = res.node;
  43761. rd._cacheTexture = res.texture;
  43762. rd._cacheRenderSprite = res.sprite;
  43763. sizeChanged = true;
  43764. }
  43765. if (sizeChanged) {
  43766. rd._cacheSize.copyFrom(Group2D._s);
  43767. rd._cacheNodeUVs = rd._cacheNode.getUVsForCustomSize(rd._cacheSize);
  43768. this.scale = this._renderableData._renderingScale;
  43769. if (rd._cacheNodeUVsChangedObservable && rd._cacheNodeUVsChangedObservable.hasObservers()) {
  43770. rd._cacheNodeUVsChangedObservable.notifyObservers(rd._cacheNodeUVs);
  43771. }
  43772. this._setFlags(BABYLON.SmartPropertyPrim.flagWorldCacheChanged);
  43773. }
  43774. var n = rd._cacheNode;
  43775. rd._cacheTexture.bindTextureForPosSize(n.pos, Group2D._s, true);
  43776. };
  43777. Group2D.prototype._unbindCacheTarget = function () {
  43778. if (this._renderableData._cacheTexture) {
  43779. this._renderableData._cacheTexture.unbindTexture();
  43780. }
  43781. };
  43782. Group2D.prototype.handleGroupChanged = function (prop) {
  43783. // This method is only for cachedGroup
  43784. var rd = this._renderableData;
  43785. if (!this.isCachedGroup || !rd._cacheRenderSprite) {
  43786. return;
  43787. }
  43788. // For now we only support these property changes
  43789. // TODO: add more! :)
  43790. if (prop.id === BABYLON.Prim2DBase.actualPositionProperty.id) {
  43791. rd._cacheRenderSprite.actualPosition = this.actualPosition.clone();
  43792. }
  43793. else if (prop.id === BABYLON.Prim2DBase.rotationProperty.id) {
  43794. rd._cacheRenderSprite.rotation = this.rotation;
  43795. }
  43796. else if (prop.id === BABYLON.Prim2DBase.scaleProperty.id) {
  43797. rd._cacheRenderSprite.scale = this.scale;
  43798. }
  43799. else if (prop.id === BABYLON.Prim2DBase.originProperty.id) {
  43800. rd._cacheRenderSprite.origin = this.origin.clone();
  43801. }
  43802. else if (prop.id === Group2D.actualSizeProperty.id) {
  43803. rd._cacheRenderSprite.size = this.actualSize.clone();
  43804. }
  43805. };
  43806. Group2D.prototype.detectGroupStates = function () {
  43807. var isCanvas = this instanceof BABYLON.Canvas2D;
  43808. var canvasStrat = this.owner.cachingStrategy;
  43809. // In Don't Cache mode, only the canvas is renderable, all the other groups are logical. There are not a single cached group.
  43810. if (canvasStrat === BABYLON.Canvas2D.CACHESTRATEGY_DONTCACHE) {
  43811. this._isRenderableGroup = isCanvas;
  43812. this._isCachedGroup = false;
  43813. }
  43814. else if (canvasStrat === BABYLON.Canvas2D.CACHESTRATEGY_CANVAS) {
  43815. if (isCanvas) {
  43816. this._isRenderableGroup = true;
  43817. this._isCachedGroup = true;
  43818. }
  43819. else {
  43820. this._isRenderableGroup = this.id === "__cachedCanvasGroup__";
  43821. this._isCachedGroup = false;
  43822. }
  43823. }
  43824. else if (canvasStrat === BABYLON.Canvas2D.CACHESTRATEGY_TOPLEVELGROUPS) {
  43825. if (isCanvas) {
  43826. this._isRenderableGroup = true;
  43827. this._isCachedGroup = false;
  43828. }
  43829. else {
  43830. if (this.hierarchyDepth === 1) {
  43831. this._isRenderableGroup = true;
  43832. this._isCachedGroup = true;
  43833. }
  43834. else {
  43835. this._isRenderableGroup = false;
  43836. this._isCachedGroup = false;
  43837. }
  43838. }
  43839. }
  43840. else if (canvasStrat === BABYLON.Canvas2D.CACHESTRATEGY_ALLGROUPS) {
  43841. var gcb = this.cacheBehavior;
  43842. if ((gcb === Group2D.GROUPCACHEBEHAVIOR_DONTCACHEOVERRIDE) || (gcb === Group2D.GROUPCACHEBEHAVIOR_CACHEINPARENTGROUP)) {
  43843. this._isRenderableGroup = gcb === Group2D.GROUPCACHEBEHAVIOR_DONTCACHEOVERRIDE;
  43844. this._isCachedGroup = false;
  43845. }
  43846. if (gcb === Group2D.GROUPCACHEBEHAVIOR_FOLLOWCACHESTRATEGY) {
  43847. this._isRenderableGroup = true;
  43848. this._isCachedGroup = true;
  43849. }
  43850. }
  43851. if (this._isRenderableGroup) {
  43852. // Yes, we do need that check, trust me, unfortunately we can call _detectGroupStates many time on the same object...
  43853. if (!this._renderableData) {
  43854. this._renderableData = new RenderableGroupData();
  43855. }
  43856. }
  43857. // If the group is tagged as renderable we add it to the renderable tree
  43858. if (this._isCachedGroup) {
  43859. var cur = this.parent;
  43860. while (cur) {
  43861. if (cur instanceof Group2D && cur._isRenderableGroup) {
  43862. if (cur._renderableData._childrenRenderableGroups.indexOf(this) === -1) {
  43863. cur._renderableData._childrenRenderableGroups.push(this);
  43864. }
  43865. break;
  43866. }
  43867. cur = cur.parent;
  43868. }
  43869. }
  43870. };
  43871. Group2D.GROUP2D_PROPCOUNT = BABYLON.Prim2DBase.PRIM2DBASE_PROPCOUNT + 5;
  43872. /**
  43873. * Default behavior, the group will use the caching strategy defined at the Canvas Level
  43874. */
  43875. Group2D.GROUPCACHEBEHAVIOR_FOLLOWCACHESTRATEGY = 0;
  43876. /**
  43877. * When used, this group's content won't be cached, no matter which strategy used.
  43878. * If the group is part of a WorldSpace Canvas, its content will be drawn in the Canvas cache bitmap.
  43879. */
  43880. Group2D.GROUPCACHEBEHAVIOR_DONTCACHEOVERRIDE = 1;
  43881. /**
  43882. * When used, the group's content will be cached in the nearest cached parent group/canvas
  43883. */
  43884. Group2D.GROUPCACHEBEHAVIOR_CACHEINPARENTGROUP = 2;
  43885. Group2D._s = BABYLON.Size.Zero();
  43886. __decorate([
  43887. BABYLON.instanceLevelProperty(BABYLON.Prim2DBase.PRIM2DBASE_PROPCOUNT + 1, function (pi) { return Group2D.sizeProperty = pi; }, false, true)
  43888. ], Group2D.prototype, "size", null);
  43889. __decorate([
  43890. BABYLON.instanceLevelProperty(BABYLON.Prim2DBase.PRIM2DBASE_PROPCOUNT + 2, function (pi) { return Group2D.actualSizeProperty = pi; })
  43891. ], Group2D.prototype, "actualSize", null);
  43892. Group2D = __decorate([
  43893. BABYLON.className("Group2D")
  43894. ], Group2D);
  43895. return Group2D;
  43896. })(BABYLON.Prim2DBase);
  43897. BABYLON.Group2D = Group2D;
  43898. var RenderableGroupData = (function () {
  43899. function RenderableGroupData() {
  43900. this._primDirtyList = new Array();
  43901. this._childrenRenderableGroups = new Array();
  43902. this._renderGroupInstancesInfo = new BABYLON.StringDictionary();
  43903. this._transparentPrimitives = new Array();
  43904. this._transparentSegments = new Array();
  43905. this._transparentListChanged = false;
  43906. this._cacheNode = null;
  43907. this._cacheTexture = null;
  43908. this._cacheRenderSprite = null;
  43909. this._renderingScale = 1;
  43910. this._cacheNodeUVs = null;
  43911. this._cacheNodeUVsChangedObservable = null;
  43912. this._cacheSize = BABYLON.Size.Zero();
  43913. this._useMipMap = false;
  43914. this._anisotropicLevel = 1;
  43915. }
  43916. RenderableGroupData.prototype.dispose = function (engine) {
  43917. if (this._cacheRenderSprite) {
  43918. this._cacheRenderSprite.dispose();
  43919. this._cacheRenderSprite = null;
  43920. }
  43921. if (this._cacheTexture && this._cacheNode) {
  43922. this._cacheTexture.freeRect(this._cacheNode);
  43923. this._cacheTexture = null;
  43924. this._cacheNode = null;
  43925. }
  43926. if (this._primDirtyList) {
  43927. this._primDirtyList.splice(0);
  43928. this._primDirtyList = null;
  43929. }
  43930. if (this._renderGroupInstancesInfo) {
  43931. this._renderGroupInstancesInfo.forEach(function (k, v) {
  43932. v.dispose();
  43933. });
  43934. this._renderGroupInstancesInfo = null;
  43935. }
  43936. if (this._cacheNodeUVsChangedObservable) {
  43937. this._cacheNodeUVsChangedObservable.clear();
  43938. this._cacheNodeUVsChangedObservable = null;
  43939. }
  43940. if (this._transparentSegments) {
  43941. for (var _i = 0, _a = this._transparentSegments; _i < _a.length; _i++) {
  43942. var ts = _a[_i];
  43943. ts.dispose(engine);
  43944. }
  43945. this._transparentSegments.splice(0);
  43946. this._transparentSegments = null;
  43947. }
  43948. };
  43949. RenderableGroupData.prototype.addNewTransparentPrimitiveInfo = function (prim, gii) {
  43950. var tpi = new TransparentPrimitiveInfo();
  43951. tpi._primitive = prim;
  43952. tpi._groupInstanceInfo = gii;
  43953. tpi._transparentSegment = null;
  43954. this._transparentPrimitives.push(tpi);
  43955. this._transparentListChanged = true;
  43956. return tpi;
  43957. };
  43958. RenderableGroupData.prototype.removeTransparentPrimitiveInfo = function (tpi) {
  43959. var index = this._transparentPrimitives.indexOf(tpi);
  43960. if (index !== -1) {
  43961. this._transparentPrimitives.splice(index, 1);
  43962. this._transparentListChanged = true;
  43963. }
  43964. };
  43965. RenderableGroupData.prototype.transparentPrimitiveZChanged = function (tpi) {
  43966. this._transparentListChanged = true;
  43967. //this.updateSmallestZChangedPrim(tpi);
  43968. };
  43969. return RenderableGroupData;
  43970. })();
  43971. BABYLON.RenderableGroupData = RenderableGroupData;
  43972. var TransparentPrimitiveInfo = (function () {
  43973. function TransparentPrimitiveInfo() {
  43974. }
  43975. return TransparentPrimitiveInfo;
  43976. })();
  43977. BABYLON.TransparentPrimitiveInfo = TransparentPrimitiveInfo;
  43978. })(BABYLON || (BABYLON = {}));
  43979. var BABYLON;
  43980. (function (BABYLON) {
  43981. var Rectangle2DRenderCache = (function (_super) {
  43982. __extends(Rectangle2DRenderCache, _super);
  43983. function Rectangle2DRenderCache(engine, modelKey) {
  43984. _super.call(this, engine, modelKey);
  43985. this.effectsReady = false;
  43986. this.fillVB = null;
  43987. this.fillIB = null;
  43988. this.fillIndicesCount = 0;
  43989. this.instancingFillAttributes = null;
  43990. this.effectFill = null;
  43991. this.effectFillInstanced = null;
  43992. this.borderVB = null;
  43993. this.borderIB = null;
  43994. this.borderIndicesCount = 0;
  43995. this.instancingBorderAttributes = null;
  43996. this.effectBorder = null;
  43997. this.effectBorderInstanced = null;
  43998. }
  43999. Rectangle2DRenderCache.prototype.render = function (instanceInfo, context) {
  44000. // Do nothing if the shader is still loading/preparing
  44001. if (!this.effectsReady) {
  44002. if ((this.effectFill && (!this.effectFill.isReady() || (this.effectFillInstanced && !this.effectFillInstanced.isReady()))) ||
  44003. (this.effectBorder && (!this.effectBorder.isReady() || (this.effectBorderInstanced && !this.effectBorderInstanced.isReady())))) {
  44004. return false;
  44005. }
  44006. this.effectsReady = true;
  44007. }
  44008. var canvas = instanceInfo.owner.owner;
  44009. var engine = canvas.engine;
  44010. var depthFunction = 0;
  44011. if (this.effectFill && this.effectBorder) {
  44012. depthFunction = engine.getDepthFunction();
  44013. engine.setDepthFunctionToLessOrEqual();
  44014. }
  44015. var curAlphaMode = engine.getAlphaMode();
  44016. if (this.effectFill) {
  44017. var partIndex = instanceInfo.partIndexFromId.get(BABYLON.Shape2D.SHAPE2D_FILLPARTID.toString());
  44018. var pid = context.groupInfoPartData[partIndex];
  44019. if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
  44020. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE, true);
  44021. }
  44022. var effect = context.useInstancing ? this.effectFillInstanced : this.effectFill;
  44023. engine.enableEffect(effect);
  44024. engine.bindBuffersDirectly(this.fillVB, this.fillIB, [1], 4, effect);
  44025. if (context.useInstancing) {
  44026. if (!this.instancingFillAttributes) {
  44027. this.instancingFillAttributes = this.loadInstancingAttributes(BABYLON.Shape2D.SHAPE2D_FILLPARTID, effect);
  44028. }
  44029. var glBuffer = context.instancedBuffers ? context.instancedBuffers[partIndex] : pid._partBuffer;
  44030. var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
  44031. canvas._addDrawCallCount(1, context.renderMode);
  44032. engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingFillAttributes);
  44033. engine.draw(true, 0, this.fillIndicesCount, count);
  44034. engine.unbindInstanceAttributes();
  44035. }
  44036. else {
  44037. canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
  44038. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  44039. this.setupUniforms(effect, partIndex, pid._partData, i);
  44040. engine.draw(true, 0, this.fillIndicesCount);
  44041. }
  44042. }
  44043. }
  44044. if (this.effectBorder) {
  44045. var partIndex = instanceInfo.partIndexFromId.get(BABYLON.Shape2D.SHAPE2D_BORDERPARTID.toString());
  44046. var pid = context.groupInfoPartData[partIndex];
  44047. if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
  44048. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE, true);
  44049. }
  44050. var effect = context.useInstancing ? this.effectBorderInstanced : this.effectBorder;
  44051. engine.enableEffect(effect);
  44052. engine.bindBuffersDirectly(this.borderVB, this.borderIB, [1], 4, effect);
  44053. if (context.useInstancing) {
  44054. if (!this.instancingBorderAttributes) {
  44055. this.instancingBorderAttributes = this.loadInstancingAttributes(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, effect);
  44056. }
  44057. var glBuffer = context.instancedBuffers ? context.instancedBuffers[partIndex] : pid._partBuffer;
  44058. var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
  44059. canvas._addDrawCallCount(1, context.renderMode);
  44060. engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingBorderAttributes);
  44061. engine.draw(true, 0, this.borderIndicesCount, count);
  44062. engine.unbindInstanceAttributes();
  44063. }
  44064. else {
  44065. canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
  44066. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  44067. this.setupUniforms(effect, partIndex, pid._partData, i);
  44068. engine.draw(true, 0, this.borderIndicesCount);
  44069. }
  44070. }
  44071. }
  44072. engine.setAlphaMode(curAlphaMode, true);
  44073. if (this.effectFill && this.effectBorder) {
  44074. engine.setDepthFunction(depthFunction);
  44075. }
  44076. return true;
  44077. };
  44078. Rectangle2DRenderCache.prototype.dispose = function () {
  44079. if (!_super.prototype.dispose.call(this)) {
  44080. return false;
  44081. }
  44082. if (this.fillVB) {
  44083. this._engine._releaseBuffer(this.fillVB);
  44084. this.fillVB = null;
  44085. }
  44086. if (this.fillIB) {
  44087. this._engine._releaseBuffer(this.fillIB);
  44088. this.fillIB = null;
  44089. }
  44090. this.effectFill = null;
  44091. this.effectFillInstanced = null;
  44092. this.effectBorder = null;
  44093. this.effectBorderInstanced = null;
  44094. if (this.borderVB) {
  44095. this._engine._releaseBuffer(this.borderVB);
  44096. this.borderVB = null;
  44097. }
  44098. if (this.borderIB) {
  44099. this._engine._releaseBuffer(this.borderIB);
  44100. this.borderIB = null;
  44101. }
  44102. return true;
  44103. };
  44104. return Rectangle2DRenderCache;
  44105. })(BABYLON.ModelRenderCache);
  44106. BABYLON.Rectangle2DRenderCache = Rectangle2DRenderCache;
  44107. var Rectangle2DInstanceData = (function (_super) {
  44108. __extends(Rectangle2DInstanceData, _super);
  44109. function Rectangle2DInstanceData(partId) {
  44110. _super.call(this, partId, 1);
  44111. }
  44112. Object.defineProperty(Rectangle2DInstanceData.prototype, "properties", {
  44113. get: function () {
  44114. return null;
  44115. },
  44116. enumerable: true,
  44117. configurable: true
  44118. });
  44119. __decorate([
  44120. BABYLON.instanceData()
  44121. ], Rectangle2DInstanceData.prototype, "properties", null);
  44122. return Rectangle2DInstanceData;
  44123. })(BABYLON.Shape2DInstanceData);
  44124. BABYLON.Rectangle2DInstanceData = Rectangle2DInstanceData;
  44125. var Rectangle2D = (function (_super) {
  44126. __extends(Rectangle2D, _super);
  44127. /**
  44128. * Create an Rectangle 2D Shape primitive. May be a sharp rectangle (with sharp corners), or a rounded one.
  44129. * @param settings a combination of settings, possible ones are
  44130. * - 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)
  44131. * - children: an array of direct children
  44132. * - id a text identifier, for information purpose
  44133. * - position: the X & Y positions relative to its parent. Alternatively the x and y settings can be set. Default is [0;0]
  44134. * - rotation: the initial rotation (in radian) of the primitive. default is 0
  44135. * - scale: the initial scale of the primitive. default is 1. You can alternatively use scaleX &| scaleY to apply non uniform scale
  44136. * - opacity: set the overall opacity of the primitive, 1 to be opaque (default), less than 1 to be transparent.
  44137. * - zOrder: override the zOrder with the specified value
  44138. * - origin: define the normalized origin point location, default [0.5;0.5]
  44139. * - size: the size of the group. Alternatively the width and height settings can be set. Default will be [10;10].
  44140. * - roundRadius: if the rectangle has rounded corner, set their radius, default is 0 (to get a sharp edges rectangle).
  44141. * - 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)
  44142. * - 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)
  44143. * - borderThickness: the thickness of the drawn border, default is 1.
  44144. * - isVisible: true if the primitive must be visible, false for hidden. Default is true.
  44145. * - 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!
  44146. * - marginTop: top margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44147. * - marginLeft: left margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44148. * - marginRight: right margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44149. * - marginBottom: bottom margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44150. * - margin: top, left, right and bottom margin formatted as a single string (see PrimitiveThickness.fromString)
  44151. * - marginHAlignment: one value of the PrimitiveAlignment type's static properties
  44152. * - marginVAlignment: one value of the PrimitiveAlignment type's static properties
  44153. * - marginAlignment: a string defining the alignment, see PrimitiveAlignment.fromString
  44154. * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44155. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44156. * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44157. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44158. * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
  44159. */
  44160. function Rectangle2D(settings) {
  44161. // Avoid checking every time if the object exists
  44162. if (settings == null) {
  44163. settings = {};
  44164. }
  44165. _super.call(this, settings);
  44166. if (settings.size != null) {
  44167. this.size = settings.size;
  44168. }
  44169. else if (settings.width || settings.height) {
  44170. var size = new BABYLON.Size(settings.width, settings.height);
  44171. this.size = size;
  44172. }
  44173. //let size = settings.size || (new Size((settings.width === null) ? null : (settings.width || 10), (settings.height === null) ? null : (settings.height || 10)));
  44174. var roundRadius = (settings.roundRadius == null) ? 0 : settings.roundRadius;
  44175. var borderThickness = (settings.borderThickness == null) ? 1 : settings.borderThickness;
  44176. //this.size = size;
  44177. this.roundRadius = roundRadius;
  44178. this.borderThickness = borderThickness;
  44179. }
  44180. Object.defineProperty(Rectangle2D.prototype, "actualSize", {
  44181. get: function () {
  44182. if (this._actualSize) {
  44183. return this._actualSize;
  44184. }
  44185. return this.size;
  44186. },
  44187. set: function (value) {
  44188. this._actualSize = value;
  44189. },
  44190. enumerable: true,
  44191. configurable: true
  44192. });
  44193. Object.defineProperty(Rectangle2D.prototype, "notRounded", {
  44194. get: function () {
  44195. return this._notRounded;
  44196. },
  44197. set: function (value) {
  44198. this._notRounded = value;
  44199. },
  44200. enumerable: true,
  44201. configurable: true
  44202. });
  44203. Object.defineProperty(Rectangle2D.prototype, "roundRadius", {
  44204. get: function () {
  44205. return this._roundRadius;
  44206. },
  44207. set: function (value) {
  44208. this._roundRadius = value;
  44209. this.notRounded = value === 0;
  44210. this._positioningDirty();
  44211. },
  44212. enumerable: true,
  44213. configurable: true
  44214. });
  44215. Rectangle2D.prototype.levelIntersect = function (intersectInfo) {
  44216. // If we got there it mean the boundingInfo intersection succeed, if the rectangle has not roundRadius, it means it succeed!
  44217. if (this.notRounded) {
  44218. return true;
  44219. }
  44220. // 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.
  44221. // 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)
  44222. // 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.
  44223. // First let remove the origin out the equation, to have the rectangle with an origin at bottom/left
  44224. var size = this.size;
  44225. Rectangle2D._i0.x = intersectInfo._localPickPosition.x;
  44226. Rectangle2D._i0.y = intersectInfo._localPickPosition.y;
  44227. var rr = this.roundRadius;
  44228. var rrs = rr * rr;
  44229. // Check if the point is in the bottom/left quarter area
  44230. Rectangle2D._i1.x = rr;
  44231. Rectangle2D._i1.y = rr;
  44232. if (Rectangle2D._i0.x <= Rectangle2D._i1.x && Rectangle2D._i0.y <= Rectangle2D._i1.y) {
  44233. // Compute the intersection point in the quarter local space
  44234. Rectangle2D._i2.x = Rectangle2D._i0.x - Rectangle2D._i1.x;
  44235. Rectangle2D._i2.y = Rectangle2D._i0.y - Rectangle2D._i1.y;
  44236. // It's a hit if the squared distance is less/equal to the squared radius of the round circle
  44237. return Rectangle2D._i2.lengthSquared() <= rrs;
  44238. }
  44239. // Check if the point is in the top/left quarter area
  44240. Rectangle2D._i1.x = rr;
  44241. Rectangle2D._i1.y = size.height - rr;
  44242. if (Rectangle2D._i0.x <= Rectangle2D._i1.x && Rectangle2D._i0.y >= Rectangle2D._i1.y) {
  44243. // Compute the intersection point in the quarter local space
  44244. Rectangle2D._i2.x = Rectangle2D._i0.x - Rectangle2D._i1.x;
  44245. Rectangle2D._i2.y = Rectangle2D._i0.y - Rectangle2D._i1.y;
  44246. // It's a hit if the squared distance is less/equal to the squared radius of the round circle
  44247. return Rectangle2D._i2.lengthSquared() <= rrs;
  44248. }
  44249. // Check if the point is in the top/right quarter area
  44250. Rectangle2D._i1.x = size.width - rr;
  44251. Rectangle2D._i1.y = size.height - rr;
  44252. if (Rectangle2D._i0.x >= Rectangle2D._i1.x && Rectangle2D._i0.y >= Rectangle2D._i1.y) {
  44253. // Compute the intersection point in the quarter local space
  44254. Rectangle2D._i2.x = Rectangle2D._i0.x - Rectangle2D._i1.x;
  44255. Rectangle2D._i2.y = Rectangle2D._i0.y - Rectangle2D._i1.y;
  44256. // It's a hit if the squared distance is less/equal to the squared radius of the round circle
  44257. return Rectangle2D._i2.lengthSquared() <= rrs;
  44258. }
  44259. // Check if the point is in the bottom/right quarter area
  44260. Rectangle2D._i1.x = size.width - rr;
  44261. Rectangle2D._i1.y = rr;
  44262. if (Rectangle2D._i0.x >= Rectangle2D._i1.x && Rectangle2D._i0.y <= Rectangle2D._i1.y) {
  44263. // Compute the intersection point in the quarter local space
  44264. Rectangle2D._i2.x = Rectangle2D._i0.x - Rectangle2D._i1.x;
  44265. Rectangle2D._i2.y = Rectangle2D._i0.y - Rectangle2D._i1.y;
  44266. // It's a hit if the squared distance is less/equal to the squared radius of the round circle
  44267. return Rectangle2D._i2.lengthSquared() <= rrs;
  44268. }
  44269. // At any other locations the point is guarantied to be inside
  44270. return true;
  44271. };
  44272. Rectangle2D.prototype.updateLevelBoundingInfo = function () {
  44273. BABYLON.BoundingInfo2D.CreateFromSizeToRef(this.actualSize, this._levelBoundingInfo);
  44274. };
  44275. Rectangle2D.prototype.createModelRenderCache = function (modelKey) {
  44276. var renderCache = new Rectangle2DRenderCache(this.owner.engine, modelKey);
  44277. return renderCache;
  44278. };
  44279. Rectangle2D.prototype.setupModelRenderCache = function (modelRenderCache) {
  44280. var renderCache = modelRenderCache;
  44281. var engine = this.owner.engine;
  44282. // Need to create WebGL resources for fill part?
  44283. if (this.fill) {
  44284. var vbSize = ((this.notRounded ? 1 : Rectangle2D.roundSubdivisions) * 4) + 1;
  44285. var vb = new Float32Array(vbSize);
  44286. for (var i = 0; i < vbSize; i++) {
  44287. vb[i] = i;
  44288. }
  44289. renderCache.fillVB = engine.createVertexBuffer(vb);
  44290. var triCount = vbSize - 1;
  44291. var ib = new Float32Array(triCount * 3);
  44292. for (var i = 0; i < triCount; i++) {
  44293. ib[i * 3 + 0] = 0;
  44294. ib[i * 3 + 2] = i + 1;
  44295. ib[i * 3 + 1] = i + 2;
  44296. }
  44297. ib[triCount * 3 - 2] = 1;
  44298. renderCache.fillIB = engine.createIndexBuffer(ib);
  44299. renderCache.fillIndicesCount = triCount * 3;
  44300. // 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
  44301. var ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_FILLPARTID, ["index"], null, true);
  44302. if (ei) {
  44303. renderCache.effectFillInstanced = engine.createEffect("rect2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  44304. }
  44305. // Get the non instanced version
  44306. ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_FILLPARTID, ["index"], null, false);
  44307. renderCache.effectFill = engine.createEffect("rect2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  44308. }
  44309. // Need to create WebGL resource for border part?
  44310. if (this.border) {
  44311. var vbSize = (this.notRounded ? 1 : Rectangle2D.roundSubdivisions) * 4 * 2;
  44312. var vb = new Float32Array(vbSize);
  44313. for (var i = 0; i < vbSize; i++) {
  44314. vb[i] = i;
  44315. }
  44316. renderCache.borderVB = engine.createVertexBuffer(vb);
  44317. var triCount = vbSize;
  44318. var rs = triCount / 2;
  44319. var ib = new Float32Array(triCount * 3);
  44320. for (var i = 0; i < rs; i++) {
  44321. var r0 = i;
  44322. var r1 = (i + 1) % rs;
  44323. ib[i * 6 + 0] = rs + r1;
  44324. ib[i * 6 + 1] = rs + r0;
  44325. ib[i * 6 + 2] = r0;
  44326. ib[i * 6 + 3] = r1;
  44327. ib[i * 6 + 4] = rs + r1;
  44328. ib[i * 6 + 5] = r0;
  44329. }
  44330. renderCache.borderIB = engine.createIndexBuffer(ib);
  44331. renderCache.borderIndicesCount = triCount * 3;
  44332. // 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
  44333. var ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, ["index"], null, true);
  44334. if (ei) {
  44335. renderCache.effectBorderInstanced = engine.createEffect("rect2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  44336. }
  44337. // Get the non instanced version
  44338. ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, ["index"], null, false);
  44339. renderCache.effectBorder = engine.createEffect("rect2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  44340. }
  44341. return renderCache;
  44342. };
  44343. // 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
  44344. Rectangle2D.prototype._getInitialContentAreaToRef = function (primSize, initialContentPosition, initialContentArea) {
  44345. // Fall back to default implementation if there's no round Radius
  44346. if (this._notRounded) {
  44347. _super.prototype._getInitialContentAreaToRef.call(this, primSize, initialContentPosition, initialContentArea);
  44348. }
  44349. else {
  44350. var rr = Math.round((this.roundRadius - (this.roundRadius / Math.sqrt(2))) * 1.3);
  44351. initialContentPosition.x = initialContentPosition.y = rr;
  44352. initialContentArea.width = Math.max(0, primSize.width - (rr * 2));
  44353. initialContentArea.height = Math.max(0, primSize.height - (rr * 2));
  44354. }
  44355. };
  44356. Rectangle2D.prototype._getActualSizeFromContentToRef = function (primSize, newPrimSize) {
  44357. // Fall back to default implementation if there's no round Radius
  44358. if (this._notRounded) {
  44359. _super.prototype._getActualSizeFromContentToRef.call(this, primSize, newPrimSize);
  44360. }
  44361. else {
  44362. var rr = Math.round((this.roundRadius - (this.roundRadius / Math.sqrt(2))) * 1.3);
  44363. newPrimSize.copyFrom(primSize);
  44364. newPrimSize.width += rr * 2;
  44365. newPrimSize.height += rr * 2;
  44366. }
  44367. };
  44368. Rectangle2D.prototype.createInstanceDataParts = function () {
  44369. var res = new Array();
  44370. if (this.border) {
  44371. res.push(new Rectangle2DInstanceData(BABYLON.Shape2D.SHAPE2D_BORDERPARTID));
  44372. }
  44373. if (this.fill) {
  44374. res.push(new Rectangle2DInstanceData(BABYLON.Shape2D.SHAPE2D_FILLPARTID));
  44375. }
  44376. return res;
  44377. };
  44378. Rectangle2D.prototype.refreshInstanceDataPart = function (part) {
  44379. if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
  44380. return false;
  44381. }
  44382. if (part.id === BABYLON.Shape2D.SHAPE2D_BORDERPARTID) {
  44383. var d = part;
  44384. var size = this.actualSize;
  44385. d.properties = new BABYLON.Vector3(size.width, size.height, this.roundRadius || 0);
  44386. }
  44387. else if (part.id === BABYLON.Shape2D.SHAPE2D_FILLPARTID) {
  44388. var d = part;
  44389. var size = this.actualSize;
  44390. d.properties = new BABYLON.Vector3(size.width, size.height, this.roundRadius || 0);
  44391. }
  44392. return true;
  44393. };
  44394. Rectangle2D._i0 = BABYLON.Vector2.Zero();
  44395. Rectangle2D._i1 = BABYLON.Vector2.Zero();
  44396. Rectangle2D._i2 = BABYLON.Vector2.Zero();
  44397. Rectangle2D.roundSubdivisions = 16;
  44398. __decorate([
  44399. BABYLON.instanceLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 1, function (pi) { return Rectangle2D.actualSizeProperty = pi; }, false, true)
  44400. ], Rectangle2D.prototype, "actualSize", null);
  44401. __decorate([
  44402. BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 2, function (pi) { return Rectangle2D.notRoundedProperty = pi; })
  44403. ], Rectangle2D.prototype, "notRounded", null);
  44404. __decorate([
  44405. BABYLON.instanceLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 3, function (pi) { return Rectangle2D.roundRadiusProperty = pi; })
  44406. ], Rectangle2D.prototype, "roundRadius", null);
  44407. Rectangle2D = __decorate([
  44408. BABYLON.className("Rectangle2D")
  44409. ], Rectangle2D);
  44410. return Rectangle2D;
  44411. })(BABYLON.Shape2D);
  44412. BABYLON.Rectangle2D = Rectangle2D;
  44413. })(BABYLON || (BABYLON = {}));
  44414. var BABYLON;
  44415. (function (BABYLON) {
  44416. var Ellipse2DRenderCache = (function (_super) {
  44417. __extends(Ellipse2DRenderCache, _super);
  44418. function Ellipse2DRenderCache(engine, modelKey) {
  44419. _super.call(this, engine, modelKey);
  44420. this.effectsReady = false;
  44421. this.fillVB = null;
  44422. this.fillIB = null;
  44423. this.fillIndicesCount = 0;
  44424. this.instancingFillAttributes = null;
  44425. this.effectFillInstanced = null;
  44426. this.effectFill = null;
  44427. this.borderVB = null;
  44428. this.borderIB = null;
  44429. this.borderIndicesCount = 0;
  44430. this.instancingBorderAttributes = null;
  44431. this.effectBorderInstanced = null;
  44432. this.effectBorder = null;
  44433. }
  44434. Ellipse2DRenderCache.prototype.render = function (instanceInfo, context) {
  44435. // Do nothing if the shader is still loading/preparing
  44436. if (!this.effectsReady) {
  44437. if ((this.effectFill && (!this.effectFill.isReady() || (this.effectFillInstanced && !this.effectFillInstanced.isReady()))) ||
  44438. (this.effectBorder && (!this.effectBorder.isReady() || (this.effectBorderInstanced && !this.effectBorderInstanced.isReady())))) {
  44439. return false;
  44440. }
  44441. this.effectsReady = true;
  44442. }
  44443. var canvas = instanceInfo.owner.owner;
  44444. var engine = canvas.engine;
  44445. var depthFunction = 0;
  44446. if (this.effectFill && this.effectBorder) {
  44447. depthFunction = engine.getDepthFunction();
  44448. engine.setDepthFunctionToLessOrEqual();
  44449. }
  44450. var curAlphaMode = engine.getAlphaMode();
  44451. if (this.effectFill) {
  44452. var partIndex = instanceInfo.partIndexFromId.get(BABYLON.Shape2D.SHAPE2D_FILLPARTID.toString());
  44453. var pid = context.groupInfoPartData[partIndex];
  44454. if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
  44455. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE, true);
  44456. }
  44457. var effect = context.useInstancing ? this.effectFillInstanced : this.effectFill;
  44458. engine.enableEffect(effect);
  44459. engine.bindBuffersDirectly(this.fillVB, this.fillIB, [1], 4, effect);
  44460. if (context.useInstancing) {
  44461. if (!this.instancingFillAttributes) {
  44462. this.instancingFillAttributes = this.loadInstancingAttributes(BABYLON.Shape2D.SHAPE2D_FILLPARTID, effect);
  44463. }
  44464. var glBuffer = context.instancedBuffers ? context.instancedBuffers[partIndex] : pid._partBuffer;
  44465. var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
  44466. canvas._addDrawCallCount(1, context.renderMode);
  44467. engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingFillAttributes);
  44468. engine.draw(true, 0, this.fillIndicesCount, count);
  44469. engine.unbindInstanceAttributes();
  44470. }
  44471. else {
  44472. canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
  44473. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  44474. this.setupUniforms(effect, partIndex, pid._partData, i);
  44475. engine.draw(true, 0, this.fillIndicesCount);
  44476. }
  44477. }
  44478. }
  44479. if (this.effectBorder) {
  44480. var partIndex = instanceInfo.partIndexFromId.get(BABYLON.Shape2D.SHAPE2D_BORDERPARTID.toString());
  44481. var pid = context.groupInfoPartData[partIndex];
  44482. if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
  44483. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE, true);
  44484. }
  44485. var effect = context.useInstancing ? this.effectBorderInstanced : this.effectBorder;
  44486. engine.enableEffect(effect);
  44487. engine.bindBuffersDirectly(this.borderVB, this.borderIB, [1], 4, effect);
  44488. if (context.useInstancing) {
  44489. if (!this.instancingBorderAttributes) {
  44490. this.instancingBorderAttributes = this.loadInstancingAttributes(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, effect);
  44491. }
  44492. var glBuffer = context.instancedBuffers ? context.instancedBuffers[partIndex] : pid._partBuffer;
  44493. var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
  44494. canvas._addDrawCallCount(1, context.renderMode);
  44495. engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingBorderAttributes);
  44496. engine.draw(true, 0, this.borderIndicesCount, count);
  44497. engine.unbindInstanceAttributes();
  44498. }
  44499. else {
  44500. canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
  44501. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  44502. this.setupUniforms(effect, partIndex, pid._partData, i);
  44503. engine.draw(true, 0, this.borderIndicesCount);
  44504. }
  44505. }
  44506. }
  44507. engine.setAlphaMode(curAlphaMode, true);
  44508. if (this.effectFill && this.effectBorder) {
  44509. engine.setDepthFunction(depthFunction);
  44510. }
  44511. return true;
  44512. };
  44513. Ellipse2DRenderCache.prototype.dispose = function () {
  44514. if (!_super.prototype.dispose.call(this)) {
  44515. return false;
  44516. }
  44517. if (this.fillVB) {
  44518. this._engine._releaseBuffer(this.fillVB);
  44519. this.fillVB = null;
  44520. }
  44521. if (this.fillIB) {
  44522. this._engine._releaseBuffer(this.fillIB);
  44523. this.fillIB = null;
  44524. }
  44525. this.effectFill = null;
  44526. this.effectFillInstanced = null;
  44527. this.effectBorder = null;
  44528. this.effectBorderInstanced = null;
  44529. if (this.borderVB) {
  44530. this._engine._releaseBuffer(this.borderVB);
  44531. this.borderVB = null;
  44532. }
  44533. if (this.borderIB) {
  44534. this._engine._releaseBuffer(this.borderIB);
  44535. this.borderIB = null;
  44536. }
  44537. return true;
  44538. };
  44539. return Ellipse2DRenderCache;
  44540. })(BABYLON.ModelRenderCache);
  44541. BABYLON.Ellipse2DRenderCache = Ellipse2DRenderCache;
  44542. var Ellipse2DInstanceData = (function (_super) {
  44543. __extends(Ellipse2DInstanceData, _super);
  44544. function Ellipse2DInstanceData(partId) {
  44545. _super.call(this, partId, 1);
  44546. }
  44547. Object.defineProperty(Ellipse2DInstanceData.prototype, "properties", {
  44548. get: function () {
  44549. return null;
  44550. },
  44551. enumerable: true,
  44552. configurable: true
  44553. });
  44554. __decorate([
  44555. BABYLON.instanceData()
  44556. ], Ellipse2DInstanceData.prototype, "properties", null);
  44557. return Ellipse2DInstanceData;
  44558. })(BABYLON.Shape2DInstanceData);
  44559. BABYLON.Ellipse2DInstanceData = Ellipse2DInstanceData;
  44560. var Ellipse2D = (function (_super) {
  44561. __extends(Ellipse2D, _super);
  44562. /**
  44563. * Create an Ellipse 2D Shape primitive
  44564. * @param settings a combination of settings, possible ones are
  44565. * - 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)
  44566. * - children: an array of direct children
  44567. * - id: a text identifier, for information purpose
  44568. * - position: the X & Y positions relative to its parent. Alternatively the x and y properties can be set. Default is [0;0]
  44569. * - rotation: the initial rotation (in radian) of the primitive. default is 0
  44570. * - scale: the initial scale of the primitive. default is 1. You can alternatively use scaleX &| scaleY to apply non uniform scale
  44571. * - opacity: set the overall opacity of the primitive, 1 to be opaque (default), less than 1 to be transparent.
  44572. * - zOrder: override the zOrder with the specified value
  44573. * - origin: define the normalized origin point location, default [0.5;0.5]
  44574. * - size: the size of the group. Alternatively the width and height properties can be set. Default will be [10;10].
  44575. * - subdivision: the number of subdivision to create the ellipse perimeter, default is 64.
  44576. * - 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)
  44577. * - 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)
  44578. * - borderThickness: the thickness of the drawn border, default is 1.
  44579. * - isVisible: true if the group must be visible, false for hidden. Default is true.
  44580. * - 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!
  44581. * - marginTop: top margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44582. * - marginLeft: left margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44583. * - marginRight: right margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44584. * - marginBottom: bottom margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44585. * - margin: top, left, right and bottom margin formatted as a single string (see PrimitiveThickness.fromString)
  44586. * - marginHAlignment: one value of the PrimitiveAlignment type's static properties
  44587. * - marginVAlignment: one value of the PrimitiveAlignment type's static properties
  44588. * - marginAlignment: a string defining the alignment, see PrimitiveAlignment.fromString
  44589. * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44590. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44591. * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44592. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44593. * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
  44594. */
  44595. function Ellipse2D(settings) {
  44596. // Avoid checking every time if the object exists
  44597. if (settings == null) {
  44598. settings = {};
  44599. }
  44600. _super.call(this, settings);
  44601. if (settings.size != null) {
  44602. this.size = settings.size;
  44603. }
  44604. else if (settings.width || settings.height) {
  44605. var size = new BABYLON.Size(settings.width, settings.height);
  44606. this.size = size;
  44607. }
  44608. var sub = (settings.subdivisions == null) ? 64 : settings.subdivisions;
  44609. this.subdivisions = sub;
  44610. }
  44611. Object.defineProperty(Ellipse2D.prototype, "actualSize", {
  44612. get: function () {
  44613. if (this._actualSize) {
  44614. return this._actualSize;
  44615. }
  44616. return this.size;
  44617. },
  44618. set: function (value) {
  44619. this._actualSize = value;
  44620. },
  44621. enumerable: true,
  44622. configurable: true
  44623. });
  44624. Object.defineProperty(Ellipse2D.prototype, "subdivisions", {
  44625. get: function () {
  44626. return this._subdivisions;
  44627. },
  44628. set: function (value) {
  44629. this._subdivisions = value;
  44630. },
  44631. enumerable: true,
  44632. configurable: true
  44633. });
  44634. Ellipse2D.prototype.levelIntersect = function (intersectInfo) {
  44635. var w = this.size.width / 2;
  44636. var h = this.size.height / 2;
  44637. var x = intersectInfo._localPickPosition.x - w;
  44638. var y = intersectInfo._localPickPosition.y - h;
  44639. return ((x * x) / (w * w) + (y * y) / (h * h)) <= 1;
  44640. };
  44641. Ellipse2D.prototype.updateLevelBoundingInfo = function () {
  44642. BABYLON.BoundingInfo2D.CreateFromSizeToRef(this.actualSize, this._levelBoundingInfo);
  44643. };
  44644. Ellipse2D.prototype.createModelRenderCache = function (modelKey) {
  44645. var renderCache = new Ellipse2DRenderCache(this.owner.engine, modelKey);
  44646. return renderCache;
  44647. };
  44648. Ellipse2D.prototype.setupModelRenderCache = function (modelRenderCache) {
  44649. var renderCache = modelRenderCache;
  44650. var engine = this.owner.engine;
  44651. // Need to create WebGL resources for fill part?
  44652. if (this.fill) {
  44653. var vbSize = this.subdivisions + 1;
  44654. var vb = new Float32Array(vbSize);
  44655. for (var i = 0; i < vbSize; i++) {
  44656. vb[i] = i;
  44657. }
  44658. renderCache.fillVB = engine.createVertexBuffer(vb);
  44659. var triCount = vbSize - 1;
  44660. var ib = new Float32Array(triCount * 3);
  44661. for (var i = 0; i < triCount; i++) {
  44662. ib[i * 3 + 0] = 0;
  44663. ib[i * 3 + 2] = i + 1;
  44664. ib[i * 3 + 1] = i + 2;
  44665. }
  44666. ib[triCount * 3 - 2] = 1;
  44667. renderCache.fillIB = engine.createIndexBuffer(ib);
  44668. renderCache.fillIndicesCount = triCount * 3;
  44669. // 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
  44670. var ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_FILLPARTID, ["index"], null, true);
  44671. if (ei) {
  44672. renderCache.effectFillInstanced = engine.createEffect({ vertex: "ellipse2d", fragment: "ellipse2d" }, ei.attributes, ei.uniforms, [], ei.defines, null);
  44673. }
  44674. // Get the non instanced version
  44675. ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_FILLPARTID, ["index"], null, false);
  44676. renderCache.effectFill = engine.createEffect({ vertex: "ellipse2d", fragment: "ellipse2d" }, ei.attributes, ei.uniforms, [], ei.defines, null);
  44677. }
  44678. // Need to create WebGL resource for border part?
  44679. if (this.border) {
  44680. var vbSize = this.subdivisions * 2;
  44681. var vb = new Float32Array(vbSize);
  44682. for (var i = 0; i < vbSize; i++) {
  44683. vb[i] = i;
  44684. }
  44685. renderCache.borderVB = engine.createVertexBuffer(vb);
  44686. var triCount = vbSize;
  44687. var rs = triCount / 2;
  44688. var ib = new Float32Array(triCount * 3);
  44689. for (var i = 0; i < rs; i++) {
  44690. var r0 = i;
  44691. var r1 = (i + 1) % rs;
  44692. ib[i * 6 + 0] = rs + r1;
  44693. ib[i * 6 + 1] = rs + r0;
  44694. ib[i * 6 + 2] = r0;
  44695. ib[i * 6 + 3] = r1;
  44696. ib[i * 6 + 4] = rs + r1;
  44697. ib[i * 6 + 5] = r0;
  44698. }
  44699. renderCache.borderIB = engine.createIndexBuffer(ib);
  44700. renderCache.borderIndicesCount = (triCount * 3);
  44701. // 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
  44702. var ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, ["index"], null, true);
  44703. if (ei) {
  44704. renderCache.effectBorderInstanced = engine.createEffect("ellipse2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  44705. }
  44706. // Get the non instanced version
  44707. ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, ["index"], null, false);
  44708. renderCache.effectBorder = engine.createEffect("ellipse2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  44709. }
  44710. return renderCache;
  44711. };
  44712. Ellipse2D.prototype.createInstanceDataParts = function () {
  44713. var res = new Array();
  44714. if (this.border) {
  44715. res.push(new Ellipse2DInstanceData(BABYLON.Shape2D.SHAPE2D_BORDERPARTID));
  44716. }
  44717. if (this.fill) {
  44718. res.push(new Ellipse2DInstanceData(BABYLON.Shape2D.SHAPE2D_FILLPARTID));
  44719. }
  44720. return res;
  44721. };
  44722. Ellipse2D.prototype.refreshInstanceDataPart = function (part) {
  44723. if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
  44724. return false;
  44725. }
  44726. if (part.id === BABYLON.Shape2D.SHAPE2D_BORDERPARTID) {
  44727. var d = part;
  44728. var size = this.actualSize;
  44729. d.properties = new BABYLON.Vector3(size.width, size.height, this.subdivisions);
  44730. }
  44731. else if (part.id === BABYLON.Shape2D.SHAPE2D_FILLPARTID) {
  44732. var d = part;
  44733. var size = this.actualSize;
  44734. d.properties = new BABYLON.Vector3(size.width, size.height, this.subdivisions);
  44735. }
  44736. return true;
  44737. };
  44738. __decorate([
  44739. BABYLON.instanceLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 1, function (pi) { return Ellipse2D.acutalSizeProperty = pi; }, false, true)
  44740. ], Ellipse2D.prototype, "actualSize", null);
  44741. __decorate([
  44742. BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 2, function (pi) { return Ellipse2D.subdivisionsProperty = pi; })
  44743. ], Ellipse2D.prototype, "subdivisions", null);
  44744. Ellipse2D = __decorate([
  44745. BABYLON.className("Ellipse2D")
  44746. ], Ellipse2D);
  44747. return Ellipse2D;
  44748. })(BABYLON.Shape2D);
  44749. BABYLON.Ellipse2D = Ellipse2D;
  44750. })(BABYLON || (BABYLON = {}));
  44751. var BABYLON;
  44752. (function (BABYLON) {
  44753. var Sprite2DRenderCache = (function (_super) {
  44754. __extends(Sprite2DRenderCache, _super);
  44755. function Sprite2DRenderCache() {
  44756. _super.apply(this, arguments);
  44757. this.effectsReady = false;
  44758. this.vb = null;
  44759. this.ib = null;
  44760. this.instancingAttributes = null;
  44761. this.texture = null;
  44762. this.effect = null;
  44763. this.effectInstanced = null;
  44764. }
  44765. Sprite2DRenderCache.prototype.render = function (instanceInfo, context) {
  44766. // Do nothing if the shader is still loading/preparing
  44767. if (!this.effectsReady) {
  44768. if ((this.effect && (!this.effect.isReady() || (this.effectInstanced && !this.effectInstanced.isReady())))) {
  44769. return false;
  44770. }
  44771. this.effectsReady = true;
  44772. }
  44773. // Compute the offset locations of the attributes in the vertex shader that will be mapped to the instance buffer data
  44774. var canvas = instanceInfo.owner.owner;
  44775. var engine = canvas.engine;
  44776. var cur = engine.getAlphaMode();
  44777. var effect = context.useInstancing ? this.effectInstanced : this.effect;
  44778. engine.enableEffect(effect);
  44779. effect.setTexture("diffuseSampler", this.texture);
  44780. engine.bindBuffersDirectly(this.vb, this.ib, [1], 4, effect);
  44781. if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
  44782. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE, true);
  44783. }
  44784. effect.setBool("alphaTest", context.renderMode === BABYLON.Render2DContext.RenderModeAlphaTest);
  44785. var pid = context.groupInfoPartData[0];
  44786. if (context.useInstancing) {
  44787. if (!this.instancingAttributes) {
  44788. this.instancingAttributes = this.loadInstancingAttributes(Sprite2D.SPRITE2D_MAINPARTID, effect);
  44789. }
  44790. var glBuffer = context.instancedBuffers ? context.instancedBuffers[0] : pid._partBuffer;
  44791. var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
  44792. canvas._addDrawCallCount(1, context.renderMode);
  44793. engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingAttributes);
  44794. engine.draw(true, 0, 6, count);
  44795. engine.unbindInstanceAttributes();
  44796. }
  44797. else {
  44798. canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
  44799. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  44800. this.setupUniforms(effect, 0, pid._partData, i);
  44801. engine.draw(true, 0, 6);
  44802. }
  44803. }
  44804. engine.setAlphaMode(cur, true);
  44805. return true;
  44806. };
  44807. Sprite2DRenderCache.prototype.dispose = function () {
  44808. if (!_super.prototype.dispose.call(this)) {
  44809. return false;
  44810. }
  44811. if (this.vb) {
  44812. this._engine._releaseBuffer(this.vb);
  44813. this.vb = null;
  44814. }
  44815. if (this.ib) {
  44816. this._engine._releaseBuffer(this.ib);
  44817. this.ib = null;
  44818. }
  44819. if (this.texture) {
  44820. this.texture.dispose();
  44821. this.texture = null;
  44822. }
  44823. this.effect = null;
  44824. this.effectInstanced = null;
  44825. return true;
  44826. };
  44827. return Sprite2DRenderCache;
  44828. })(BABYLON.ModelRenderCache);
  44829. BABYLON.Sprite2DRenderCache = Sprite2DRenderCache;
  44830. var Sprite2DInstanceData = (function (_super) {
  44831. __extends(Sprite2DInstanceData, _super);
  44832. function Sprite2DInstanceData(partId) {
  44833. _super.call(this, partId, 1);
  44834. }
  44835. Object.defineProperty(Sprite2DInstanceData.prototype, "topLeftUV", {
  44836. get: function () {
  44837. return null;
  44838. },
  44839. enumerable: true,
  44840. configurable: true
  44841. });
  44842. Object.defineProperty(Sprite2DInstanceData.prototype, "sizeUV", {
  44843. get: function () {
  44844. return null;
  44845. },
  44846. enumerable: true,
  44847. configurable: true
  44848. });
  44849. Object.defineProperty(Sprite2DInstanceData.prototype, "scaleFactor", {
  44850. get: function () {
  44851. return null;
  44852. },
  44853. enumerable: true,
  44854. configurable: true
  44855. });
  44856. Object.defineProperty(Sprite2DInstanceData.prototype, "textureSize", {
  44857. get: function () {
  44858. return null;
  44859. },
  44860. enumerable: true,
  44861. configurable: true
  44862. });
  44863. Object.defineProperty(Sprite2DInstanceData.prototype, "properties", {
  44864. // 3 floats being:
  44865. // - x: frame number to display
  44866. // - y: invertY setting
  44867. // - z: alignToPixel setting
  44868. get: function () {
  44869. return null;
  44870. },
  44871. enumerable: true,
  44872. configurable: true
  44873. });
  44874. __decorate([
  44875. BABYLON.instanceData()
  44876. ], Sprite2DInstanceData.prototype, "topLeftUV", null);
  44877. __decorate([
  44878. BABYLON.instanceData()
  44879. ], Sprite2DInstanceData.prototype, "sizeUV", null);
  44880. __decorate([
  44881. BABYLON.instanceData()
  44882. ], Sprite2DInstanceData.prototype, "scaleFactor", null);
  44883. __decorate([
  44884. BABYLON.instanceData()
  44885. ], Sprite2DInstanceData.prototype, "textureSize", null);
  44886. __decorate([
  44887. BABYLON.instanceData()
  44888. ], Sprite2DInstanceData.prototype, "properties", null);
  44889. return Sprite2DInstanceData;
  44890. })(BABYLON.InstanceDataBase);
  44891. BABYLON.Sprite2DInstanceData = Sprite2DInstanceData;
  44892. var Sprite2D = (function (_super) {
  44893. __extends(Sprite2D, _super);
  44894. /**
  44895. * Create an 2D Sprite primitive
  44896. * @param texture the texture that stores the sprite to render
  44897. * @param settings a combination of settings, possible ones are
  44898. * - 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)
  44899. * - children: an array of direct children
  44900. * - id a text identifier, for information purpose
  44901. * - position: the X & Y positions relative to its parent. Alternatively the x and y properties can be set. Default is [0;0]
  44902. * - rotation: the initial rotation (in radian) of the primitive. default is 0
  44903. * - scale: the initial scale of the primitive. default is 1. You can alternatively use scaleX &| scaleY to apply non uniform scale
  44904. * - opacity: set the overall opacity of the primitive, 1 to be opaque (default), less than 1 to be transparent.
  44905. * - zOrder: override the zOrder with the specified value
  44906. * - origin: define the normalized origin point location, default [0.5;0.5]
  44907. * - spriteSize: the size of the sprite (in pixels), if null the size of the given texture will be used, default is null.
  44908. * - spriteLocation: the location (in pixels) in the texture of the top/left corner of the Sprite to display, default is null (0,0)
  44909. * - spriteScaleFactor: say you want to display a sprite twice as big as its bitmap which is 64,64, you set the spriteSize to 128,128 and have to set the spriteScaleFactory to 0.5,0.5 in order to address only the 64,64 pixels of the bitmaps. Default is 1,1.
  44910. * - invertY: if true the texture Y will be inverted, default is false.
  44911. * - 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.
  44912. * - isVisible: true if the sprite must be visible, false for hidden. Default is true.
  44913. * - 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!
  44914. * - marginTop: top margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44915. * - marginLeft: left margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44916. * - marginRight: right margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44917. * - marginBottom: bottom margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44918. * - margin: top, left, right and bottom margin formatted as a single string (see PrimitiveThickness.fromString)
  44919. * - marginHAlignment: one value of the PrimitiveAlignment type's static properties
  44920. * - marginVAlignment: one value of the PrimitiveAlignment type's static properties
  44921. * - marginAlignment: a string defining the alignment, see PrimitiveAlignment.fromString
  44922. * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44923. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44924. * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44925. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44926. * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
  44927. */
  44928. function Sprite2D(texture, settings) {
  44929. var _this = this;
  44930. if (!settings) {
  44931. settings = {};
  44932. }
  44933. _super.call(this, settings);
  44934. this.texture = texture;
  44935. this.texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  44936. this.texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  44937. this.size = settings.spriteSize;
  44938. this.spriteLocation = settings.spriteLocation || new BABYLON.Vector2(0, 0);
  44939. this.spriteScaleFactor = settings.spriteScaleFactor || new BABYLON.Vector2(1, 1);
  44940. this.spriteFrame = 0;
  44941. this.invertY = (settings.invertY == null) ? false : settings.invertY;
  44942. this.alignToPixel = (settings.alignToPixel == null) ? true : settings.alignToPixel;
  44943. this.useAlphaFromTexture = true;
  44944. if (settings.spriteSize == null || !texture.isReady()) {
  44945. if (texture.isReady()) {
  44946. this.size = texture.getBaseSize();
  44947. }
  44948. else {
  44949. texture.onLoadObservable.add(function () {
  44950. if (settings.spriteSize == null) {
  44951. _this.size = texture.getBaseSize();
  44952. }
  44953. _this._positioningDirty();
  44954. _this._instanceDirtyFlags |= Sprite2D.textureProperty.flagId; // To make sure the sprite is issued again for render
  44955. });
  44956. }
  44957. }
  44958. }
  44959. Object.defineProperty(Sprite2D.prototype, "texture", {
  44960. get: function () {
  44961. return this._texture;
  44962. },
  44963. set: function (value) {
  44964. this._texture = value;
  44965. this._oldTextureHasAlpha = this._texture && this.texture.hasAlpha;
  44966. },
  44967. enumerable: true,
  44968. configurable: true
  44969. });
  44970. Object.defineProperty(Sprite2D.prototype, "useAlphaFromTexture", {
  44971. get: function () {
  44972. return this._useAlphaFromTexture;
  44973. },
  44974. set: function (value) {
  44975. if (this._useAlphaFromTexture === value) {
  44976. return;
  44977. }
  44978. this._useAlphaFromTexture = value;
  44979. this._updateRenderMode();
  44980. },
  44981. enumerable: true,
  44982. configurable: true
  44983. });
  44984. Object.defineProperty(Sprite2D.prototype, "actualSize", {
  44985. get: function () {
  44986. if (this._actualSize) {
  44987. return this._actualSize;
  44988. }
  44989. return this.size;
  44990. },
  44991. set: function (value) {
  44992. this._actualSize = value;
  44993. },
  44994. enumerable: true,
  44995. configurable: true
  44996. });
  44997. Object.defineProperty(Sprite2D.prototype, "spriteLocation", {
  44998. get: function () {
  44999. return this._location;
  45000. },
  45001. set: function (value) {
  45002. this._location = value;
  45003. },
  45004. enumerable: true,
  45005. configurable: true
  45006. });
  45007. Object.defineProperty(Sprite2D.prototype, "spriteFrame", {
  45008. get: function () {
  45009. return this._spriteFrame;
  45010. },
  45011. set: function (value) {
  45012. this._spriteFrame = value;
  45013. },
  45014. enumerable: true,
  45015. configurable: true
  45016. });
  45017. Object.defineProperty(Sprite2D.prototype, "invertY", {
  45018. get: function () {
  45019. return this._invertY;
  45020. },
  45021. set: function (value) {
  45022. this._invertY = value;
  45023. },
  45024. enumerable: true,
  45025. configurable: true
  45026. });
  45027. Object.defineProperty(Sprite2D.prototype, "spriteScaleFactor", {
  45028. get: function () {
  45029. return this._spriteScaleFactor;
  45030. },
  45031. set: function (value) {
  45032. this._spriteScaleFactor = value;
  45033. },
  45034. enumerable: true,
  45035. configurable: true
  45036. });
  45037. Object.defineProperty(Sprite2D.prototype, "alignToPixel", {
  45038. /**
  45039. * Get/set if the sprite rendering should be aligned to the target rendering device pixel or not
  45040. */
  45041. get: function () {
  45042. return this._alignToPixel;
  45043. },
  45044. set: function (value) {
  45045. this._alignToPixel = value;
  45046. },
  45047. enumerable: true,
  45048. configurable: true
  45049. });
  45050. Sprite2D.prototype.updateLevelBoundingInfo = function () {
  45051. BABYLON.BoundingInfo2D.CreateFromSizeToRef(this.size, this._levelBoundingInfo);
  45052. };
  45053. /**
  45054. * Get the animatable array (see http://doc.babylonjs.com/tutorials/Animations)
  45055. */
  45056. Sprite2D.prototype.getAnimatables = function () {
  45057. var res = new Array();
  45058. if (this.texture && this.texture.animations && this.texture.animations.length > 0) {
  45059. res.push(this.texture);
  45060. }
  45061. return res;
  45062. };
  45063. Sprite2D.prototype.levelIntersect = function (intersectInfo) {
  45064. // 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
  45065. return true;
  45066. };
  45067. Sprite2D._createCachedCanvasSprite = function (owner, texture, size, pos) {
  45068. var sprite = new Sprite2D(texture, { parent: owner, id: "__cachedCanvasSprite__", position: BABYLON.Vector2.Zero(), origin: BABYLON.Vector2.Zero(), spriteSize: size, spriteLocation: pos, alignToPixel: true });
  45069. return sprite;
  45070. };
  45071. Sprite2D.prototype.createModelRenderCache = function (modelKey) {
  45072. var renderCache = new Sprite2DRenderCache(this.owner.engine, modelKey);
  45073. return renderCache;
  45074. };
  45075. Sprite2D.prototype.setupModelRenderCache = function (modelRenderCache) {
  45076. var renderCache = modelRenderCache;
  45077. var engine = this.owner.engine;
  45078. var vb = new Float32Array(4);
  45079. for (var i = 0; i < 4; i++) {
  45080. vb[i] = i;
  45081. }
  45082. renderCache.vb = engine.createVertexBuffer(vb);
  45083. var ib = new Float32Array(6);
  45084. ib[0] = 0;
  45085. ib[1] = 2;
  45086. ib[2] = 1;
  45087. ib[3] = 0;
  45088. ib[4] = 3;
  45089. ib[5] = 2;
  45090. renderCache.ib = engine.createIndexBuffer(ib);
  45091. renderCache.texture = this.texture;
  45092. // 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
  45093. var ei = this.getDataPartEffectInfo(Sprite2D.SPRITE2D_MAINPARTID, ["index"], ["alphaTest"], true);
  45094. if (ei) {
  45095. renderCache.effectInstanced = engine.createEffect("sprite2d", ei.attributes, ei.uniforms, ["diffuseSampler"], ei.defines, null);
  45096. }
  45097. ei = this.getDataPartEffectInfo(Sprite2D.SPRITE2D_MAINPARTID, ["index"], ["alphaTest"], false);
  45098. renderCache.effect = engine.createEffect("sprite2d", ei.attributes, ei.uniforms, ["diffuseSampler"], ei.defines, null);
  45099. return renderCache;
  45100. };
  45101. Sprite2D.prototype.createInstanceDataParts = function () {
  45102. return [new Sprite2DInstanceData(Sprite2D.SPRITE2D_MAINPARTID)];
  45103. };
  45104. Sprite2D.prototype.beforeRefreshForLayoutConstruction = function (part) {
  45105. Sprite2D.layoutConstructMode = true;
  45106. };
  45107. // if obj contains something, we restore the _text property
  45108. Sprite2D.prototype.afterRefreshForLayoutConstruction = function (part, obj) {
  45109. Sprite2D.layoutConstructMode = false;
  45110. };
  45111. Sprite2D.prototype.refreshInstanceDataPart = function (part) {
  45112. if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
  45113. return false;
  45114. }
  45115. if (!this.texture.isReady() && !Sprite2D.layoutConstructMode) {
  45116. return false;
  45117. }
  45118. if (part.id === Sprite2D.SPRITE2D_MAINPARTID) {
  45119. var d = this._instanceDataParts[0];
  45120. if (Sprite2D.layoutConstructMode) {
  45121. d.topLeftUV = BABYLON.Vector2.Zero();
  45122. d.sizeUV = BABYLON.Vector2.Zero();
  45123. d.properties = BABYLON.Vector3.Zero();
  45124. d.textureSize = BABYLON.Vector2.Zero();
  45125. d.scaleFactor = BABYLON.Vector2.Zero();
  45126. }
  45127. else {
  45128. var ts = this.texture.getBaseSize();
  45129. var sl = this.spriteLocation;
  45130. var ss = this.actualSize;
  45131. var ssf = this.spriteScaleFactor;
  45132. d.topLeftUV = new BABYLON.Vector2(sl.x / ts.width, sl.y / ts.height);
  45133. var suv = new BABYLON.Vector2(ss.width / ts.width, ss.height / ts.height);
  45134. d.sizeUV = suv;
  45135. d.scaleFactor = ssf;
  45136. Sprite2D._prop.x = this.spriteFrame;
  45137. Sprite2D._prop.y = this.invertY ? 1 : 0;
  45138. Sprite2D._prop.z = this.alignToPixel ? 1 : 0;
  45139. d.properties = Sprite2D._prop;
  45140. d.textureSize = new BABYLON.Vector2(ts.width, ts.height);
  45141. }
  45142. }
  45143. return true;
  45144. };
  45145. Sprite2D.prototype._mustUpdateInstance = function () {
  45146. var res = this._oldTextureHasAlpha !== (this.texture != null && this.texture.hasAlpha);
  45147. this._oldTextureHasAlpha = this.texture != null && this.texture.hasAlpha;
  45148. if (res) {
  45149. this._updateRenderMode();
  45150. }
  45151. return res;
  45152. };
  45153. Sprite2D.prototype._useTextureAlpha = function () {
  45154. return this.texture != null && this.texture.hasAlpha;
  45155. };
  45156. Sprite2D.prototype._shouldUseAlphaFromTexture = function () {
  45157. return this.texture != null && this.texture.hasAlpha && this.useAlphaFromTexture;
  45158. };
  45159. Sprite2D.SPRITE2D_MAINPARTID = 1;
  45160. Sprite2D._prop = BABYLON.Vector3.Zero();
  45161. Sprite2D.layoutConstructMode = false;
  45162. __decorate([
  45163. BABYLON.modelLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 1, function (pi) { return Sprite2D.textureProperty = pi; })
  45164. ], Sprite2D.prototype, "texture", null);
  45165. __decorate([
  45166. BABYLON.dynamicLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 2, function (pi) { return Sprite2D.useAlphaFromTextureProperty = pi; })
  45167. ], Sprite2D.prototype, "useAlphaFromTexture", null);
  45168. __decorate([
  45169. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 3, function (pi) { return Sprite2D.actualSizeProperty = pi; }, false, true)
  45170. ], Sprite2D.prototype, "actualSize", null);
  45171. __decorate([
  45172. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 4, function (pi) { return Sprite2D.spriteLocationProperty = pi; })
  45173. ], Sprite2D.prototype, "spriteLocation", null);
  45174. __decorate([
  45175. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 5, function (pi) { return Sprite2D.spriteFrameProperty = pi; })
  45176. ], Sprite2D.prototype, "spriteFrame", null);
  45177. __decorate([
  45178. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 6, function (pi) { return Sprite2D.invertYProperty = pi; })
  45179. ], Sprite2D.prototype, "invertY", null);
  45180. __decorate([
  45181. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 7, function (pi) { return Sprite2D.spriteScaleFactorProperty = pi; })
  45182. ], Sprite2D.prototype, "spriteScaleFactor", null);
  45183. Sprite2D = __decorate([
  45184. BABYLON.className("Sprite2D")
  45185. ], Sprite2D);
  45186. return Sprite2D;
  45187. })(BABYLON.RenderablePrim2D);
  45188. BABYLON.Sprite2D = Sprite2D;
  45189. })(BABYLON || (BABYLON = {}));
  45190. var BABYLON;
  45191. (function (BABYLON) {
  45192. var Text2DRenderCache = (function (_super) {
  45193. __extends(Text2DRenderCache, _super);
  45194. function Text2DRenderCache() {
  45195. _super.apply(this, arguments);
  45196. this.effectsReady = false;
  45197. this.vb = null;
  45198. this.ib = null;
  45199. this.instancingAttributes = null;
  45200. this.fontTexture = null;
  45201. this.effect = null;
  45202. this.effectInstanced = null;
  45203. }
  45204. Text2DRenderCache.prototype.render = function (instanceInfo, context) {
  45205. // Do nothing if the shader is still loading/preparing
  45206. if (!this.effectsReady) {
  45207. if ((this.effect && (!this.effect.isReady() || (this.effectInstanced && !this.effectInstanced.isReady())))) {
  45208. return false;
  45209. }
  45210. this.effectsReady = true;
  45211. }
  45212. var canvas = instanceInfo.owner.owner;
  45213. var engine = canvas.engine;
  45214. this.fontTexture.update();
  45215. var effect = context.useInstancing ? this.effectInstanced : this.effect;
  45216. engine.enableEffect(effect);
  45217. effect.setTexture("diffuseSampler", this.fontTexture);
  45218. engine.bindBuffersDirectly(this.vb, this.ib, [1], 4, effect);
  45219. var curAlphaMode = engine.getAlphaMode();
  45220. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE, true);
  45221. var pid = context.groupInfoPartData[0];
  45222. if (context.useInstancing) {
  45223. if (!this.instancingAttributes) {
  45224. this.instancingAttributes = this.loadInstancingAttributes(Text2D.TEXT2D_MAINPARTID, effect);
  45225. }
  45226. var glBuffer = context.instancedBuffers ? context.instancedBuffers[0] : pid._partBuffer;
  45227. var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
  45228. canvas._addDrawCallCount(1, context.renderMode);
  45229. engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingAttributes);
  45230. engine.draw(true, 0, 6, count);
  45231. engine.unbindInstanceAttributes();
  45232. }
  45233. else {
  45234. canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
  45235. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  45236. this.setupUniforms(effect, 0, pid._partData, i);
  45237. engine.draw(true, 0, 6);
  45238. }
  45239. }
  45240. engine.setAlphaMode(curAlphaMode, true);
  45241. return true;
  45242. };
  45243. Text2DRenderCache.prototype.dispose = function () {
  45244. if (!_super.prototype.dispose.call(this)) {
  45245. return false;
  45246. }
  45247. if (this.vb) {
  45248. this._engine._releaseBuffer(this.vb);
  45249. this.vb = null;
  45250. }
  45251. if (this.ib) {
  45252. this._engine._releaseBuffer(this.ib);
  45253. this.ib = null;
  45254. }
  45255. if (this.fontTexture) {
  45256. this.fontTexture.decCachedFontTextureCounter();
  45257. this.fontTexture = null;
  45258. }
  45259. this.effect = null;
  45260. this.effectInstanced = null;
  45261. return true;
  45262. };
  45263. return Text2DRenderCache;
  45264. })(BABYLON.ModelRenderCache);
  45265. BABYLON.Text2DRenderCache = Text2DRenderCache;
  45266. var Text2DInstanceData = (function (_super) {
  45267. __extends(Text2DInstanceData, _super);
  45268. function Text2DInstanceData(partId, dataElementCount) {
  45269. _super.call(this, partId, dataElementCount);
  45270. }
  45271. Object.defineProperty(Text2DInstanceData.prototype, "topLeftUV", {
  45272. get: function () {
  45273. return null;
  45274. },
  45275. enumerable: true,
  45276. configurable: true
  45277. });
  45278. Object.defineProperty(Text2DInstanceData.prototype, "sizeUV", {
  45279. get: function () {
  45280. return null;
  45281. },
  45282. enumerable: true,
  45283. configurable: true
  45284. });
  45285. Object.defineProperty(Text2DInstanceData.prototype, "textureSize", {
  45286. get: function () {
  45287. return null;
  45288. },
  45289. enumerable: true,
  45290. configurable: true
  45291. });
  45292. Object.defineProperty(Text2DInstanceData.prototype, "color", {
  45293. get: function () {
  45294. return null;
  45295. },
  45296. enumerable: true,
  45297. configurable: true
  45298. });
  45299. Object.defineProperty(Text2DInstanceData.prototype, "superSampleFactor", {
  45300. get: function () {
  45301. return null;
  45302. },
  45303. enumerable: true,
  45304. configurable: true
  45305. });
  45306. __decorate([
  45307. BABYLON.instanceData()
  45308. ], Text2DInstanceData.prototype, "topLeftUV", null);
  45309. __decorate([
  45310. BABYLON.instanceData()
  45311. ], Text2DInstanceData.prototype, "sizeUV", null);
  45312. __decorate([
  45313. BABYLON.instanceData()
  45314. ], Text2DInstanceData.prototype, "textureSize", null);
  45315. __decorate([
  45316. BABYLON.instanceData()
  45317. ], Text2DInstanceData.prototype, "color", null);
  45318. __decorate([
  45319. BABYLON.instanceData()
  45320. ], Text2DInstanceData.prototype, "superSampleFactor", null);
  45321. return Text2DInstanceData;
  45322. })(BABYLON.InstanceDataBase);
  45323. BABYLON.Text2DInstanceData = Text2DInstanceData;
  45324. var Text2D = (function (_super) {
  45325. __extends(Text2D, _super);
  45326. /**
  45327. * Create a Text primitive
  45328. * @param text the text to display
  45329. * @param settings a combination of settings, possible ones are
  45330. * - 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)
  45331. * - children: an array of direct children
  45332. * - id a text identifier, for information purpose
  45333. * - position: the X & Y positions relative to its parent. Alternatively the x and y properties can be set. Default is [0;0]
  45334. * - rotation: the initial rotation (in radian) of the primitive. default is 0
  45335. * - scale: the initial scale of the primitive. default is 1. You can alternatively use scaleX &| scaleY to apply non uniform scale
  45336. * - opacity: set the overall opacity of the primitive, 1 to be opaque (default), less than 1 to be transparent.
  45337. * - zOrder: override the zOrder with the specified value
  45338. * - origin: define the normalized origin point location, default [0.5;0.5]
  45339. * - fontName: the name/size/style of the font to use, following the CSS notation. Default is "12pt Arial".
  45340. * - 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.
  45341. * - defaultFontColor: the color by default to apply on each letter of the text to display, default is plain white.
  45342. * - areaSize: the size of the area in which to display the text, default is auto-fit from text content.
  45343. * - tabulationSize: number of space character to insert when a tabulation is encountered, default is 4
  45344. * - isVisible: true if the text must be visible, false for hidden. Default is true.
  45345. * - 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!
  45346. * - marginTop: top margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  45347. * - marginLeft: left margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  45348. * - marginRight: right margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  45349. * - marginBottom: bottom margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  45350. * - margin: top, left, right and bottom margin formatted as a single string (see PrimitiveThickness.fromString)
  45351. * - marginHAlignment: one value of the PrimitiveAlignment type's static properties
  45352. * - marginVAlignment: one value of the PrimitiveAlignment type's static properties
  45353. * - marginAlignment: a string defining the alignment, see PrimitiveAlignment.fromString
  45354. * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  45355. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  45356. * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  45357. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  45358. * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
  45359. */
  45360. function Text2D(text, settings) {
  45361. if (!settings) {
  45362. settings = {};
  45363. }
  45364. _super.call(this, settings);
  45365. this.fontName = (settings.fontName == null) ? "12pt Arial" : settings.fontName;
  45366. this._fontSuperSample = (settings.fontSuperSample != null && settings.fontSuperSample);
  45367. this.defaultFontColor = (settings.defaultFontColor == null) ? new BABYLON.Color4(1, 1, 1, 1) : settings.defaultFontColor;
  45368. this._tabulationSize = (settings.tabulationSize == null) ? 4 : settings.tabulationSize;
  45369. this._textSize = null;
  45370. this.text = text;
  45371. this.size = (settings.size == null) ? null : settings.size;
  45372. this._updateRenderMode();
  45373. }
  45374. Object.defineProperty(Text2D.prototype, "fontName", {
  45375. get: function () {
  45376. return this._fontName;
  45377. },
  45378. set: function (value) {
  45379. if (this._fontName) {
  45380. throw new Error("Font Name change is not supported right now.");
  45381. }
  45382. this._fontName = value;
  45383. },
  45384. enumerable: true,
  45385. configurable: true
  45386. });
  45387. Object.defineProperty(Text2D.prototype, "defaultFontColor", {
  45388. get: function () {
  45389. return this._defaultFontColor;
  45390. },
  45391. set: function (value) {
  45392. this._defaultFontColor = value;
  45393. },
  45394. enumerable: true,
  45395. configurable: true
  45396. });
  45397. Object.defineProperty(Text2D.prototype, "text", {
  45398. get: function () {
  45399. return this._text;
  45400. },
  45401. set: function (value) {
  45402. this._text = value;
  45403. this._textSize = null; // A change of text will reset the TextSize which will be recomputed next time it's used
  45404. this._size = null;
  45405. this._updateCharCount();
  45406. // Trigger a textSize to for a sizeChange if necessary, which is needed for layout to recompute
  45407. var s = this.textSize;
  45408. },
  45409. enumerable: true,
  45410. configurable: true
  45411. });
  45412. Object.defineProperty(Text2D.prototype, "size", {
  45413. get: function () {
  45414. if (this._size != null) {
  45415. return this._size;
  45416. }
  45417. return this.textSize;
  45418. },
  45419. set: function (value) {
  45420. this._size = value;
  45421. },
  45422. enumerable: true,
  45423. configurable: true
  45424. });
  45425. Object.defineProperty(Text2D.prototype, "actualSize", {
  45426. /**
  45427. * Get the actual size of the Text2D primitive
  45428. */
  45429. get: function () {
  45430. if (this._actualSize) {
  45431. return this._actualSize;
  45432. }
  45433. return this.size;
  45434. },
  45435. enumerable: true,
  45436. configurable: true
  45437. });
  45438. Object.defineProperty(Text2D.prototype, "textSize", {
  45439. /**
  45440. * Get the area that bounds the text associated to the primitive
  45441. */
  45442. get: function () {
  45443. if (!this._textSize) {
  45444. if (this.owner) {
  45445. var newSize = this.fontTexture.measureText(this._text, this._tabulationSize);
  45446. if (!newSize.equals(this._textSize)) {
  45447. this.onPrimitivePropertyDirty(BABYLON.Prim2DBase.sizeProperty.flagId);
  45448. this._positioningDirty();
  45449. }
  45450. this._textSize = newSize;
  45451. }
  45452. else {
  45453. return Text2D.nullSize;
  45454. }
  45455. }
  45456. return this._textSize;
  45457. },
  45458. enumerable: true,
  45459. configurable: true
  45460. });
  45461. Object.defineProperty(Text2D.prototype, "fontTexture", {
  45462. get: function () {
  45463. if (this._fontTexture) {
  45464. return this._fontTexture;
  45465. }
  45466. if (this.fontName == null || this.owner == null || this.owner.scene == null) {
  45467. return null;
  45468. }
  45469. this._fontTexture = BABYLON.FontTexture.GetCachedFontTexture(this.owner.scene, this.fontName, this._fontSuperSample);
  45470. return this._fontTexture;
  45471. },
  45472. enumerable: true,
  45473. configurable: true
  45474. });
  45475. /**
  45476. * Dispose the primitive, remove it from its parent
  45477. */
  45478. Text2D.prototype.dispose = function () {
  45479. if (!_super.prototype.dispose.call(this)) {
  45480. return false;
  45481. }
  45482. if (this._fontTexture) {
  45483. BABYLON.FontTexture.ReleaseCachedFontTexture(this.owner.scene, this.fontName, this._fontSuperSample);
  45484. this._fontTexture = null;
  45485. }
  45486. return true;
  45487. };
  45488. Text2D.prototype.updateLevelBoundingInfo = function () {
  45489. BABYLON.BoundingInfo2D.CreateFromSizeToRef(this.actualSize, this._levelBoundingInfo);
  45490. };
  45491. Text2D.prototype.levelIntersect = function (intersectInfo) {
  45492. // 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...
  45493. return true;
  45494. };
  45495. Text2D.prototype.createModelRenderCache = function (modelKey) {
  45496. var renderCache = new Text2DRenderCache(this.owner.engine, modelKey);
  45497. return renderCache;
  45498. };
  45499. Text2D.prototype.setupModelRenderCache = function (modelRenderCache) {
  45500. var renderCache = modelRenderCache;
  45501. var engine = this.owner.engine;
  45502. renderCache.fontTexture = this.fontTexture;
  45503. renderCache.fontTexture.incCachedFontTextureCounter();
  45504. var vb = new Float32Array(4);
  45505. for (var i = 0; i < 4; i++) {
  45506. vb[i] = i;
  45507. }
  45508. renderCache.vb = engine.createVertexBuffer(vb);
  45509. var ib = new Float32Array(6);
  45510. ib[0] = 0;
  45511. ib[1] = 2;
  45512. ib[2] = 1;
  45513. ib[3] = 0;
  45514. ib[4] = 3;
  45515. ib[5] = 2;
  45516. renderCache.ib = engine.createIndexBuffer(ib);
  45517. // 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
  45518. var ei = this.getDataPartEffectInfo(Text2D.TEXT2D_MAINPARTID, ["index"], null, true);
  45519. if (ei) {
  45520. renderCache.effectInstanced = engine.createEffect("text2d", ei.attributes, ei.uniforms, ["diffuseSampler"], ei.defines, null);
  45521. }
  45522. ei = this.getDataPartEffectInfo(Text2D.TEXT2D_MAINPARTID, ["index"], null, false);
  45523. renderCache.effect = engine.createEffect("text2d", ei.attributes, ei.uniforms, ["diffuseSampler"], ei.defines, null);
  45524. return renderCache;
  45525. };
  45526. Text2D.prototype.createInstanceDataParts = function () {
  45527. return [new Text2DInstanceData(Text2D.TEXT2D_MAINPARTID, this._charCount)];
  45528. };
  45529. // Looks like a hack!? Yes! Because that's what it is!
  45530. // 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
  45531. // 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)
  45532. Text2D.prototype.beforeRefreshForLayoutConstruction = function (part) {
  45533. if (!this._charCount) {
  45534. var curText = this._text;
  45535. this.text = "A";
  45536. return curText;
  45537. }
  45538. };
  45539. // if obj contains something, we restore the _text property
  45540. Text2D.prototype.afterRefreshForLayoutConstruction = function (part, obj) {
  45541. if (obj !== undefined) {
  45542. this.text = obj;
  45543. }
  45544. };
  45545. Text2D.prototype.refreshInstanceDataPart = function (part) {
  45546. if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
  45547. return false;
  45548. }
  45549. if (part.id === Text2D.TEXT2D_MAINPARTID) {
  45550. var d = part;
  45551. var texture = this.fontTexture;
  45552. var superSampleFactor = texture.isSuperSampled ? 0.5 : 1;
  45553. var ts = texture.getSize();
  45554. var offset = BABYLON.Vector2.Zero();
  45555. var lh = this.fontTexture.lineHeight;
  45556. 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
  45557. var charxpos = 0;
  45558. d.dataElementCount = this._charCount;
  45559. d.curElement = 0;
  45560. for (var _i = 0, _a = this.text; _i < _a.length; _i++) {
  45561. var char = _a[_i];
  45562. // Line feed
  45563. if (char === "\n") {
  45564. offset.x = 0;
  45565. offset.y -= texture.lineHeight;
  45566. }
  45567. // Tabulation ?
  45568. if (char === "\t") {
  45569. var nextPos = charxpos + this._tabulationSize;
  45570. nextPos = nextPos - (nextPos % this._tabulationSize);
  45571. offset.x += (nextPos - charxpos) * texture.spaceWidth;
  45572. charxpos = nextPos;
  45573. continue;
  45574. }
  45575. if (char < " ") {
  45576. continue;
  45577. }
  45578. this.updateInstanceDataPart(d, offset);
  45579. var ci = texture.getChar(char);
  45580. offset.x += ci.charWidth;
  45581. d.topLeftUV = ci.topLeftUV;
  45582. var suv = ci.bottomRightUV.subtract(ci.topLeftUV);
  45583. d.sizeUV = suv;
  45584. d.textureSize = new BABYLON.Vector2(ts.width, ts.height);
  45585. d.color = this.defaultFontColor;
  45586. d.superSampleFactor = superSampleFactor;
  45587. ++d.curElement;
  45588. }
  45589. }
  45590. return true;
  45591. };
  45592. Text2D.prototype._updateCharCount = function () {
  45593. var count = 0;
  45594. for (var _i = 0, _a = this._text; _i < _a.length; _i++) {
  45595. var char = _a[_i];
  45596. if (char === "\r" || char === "\n" || char === "\t" || char < " ") {
  45597. continue;
  45598. }
  45599. ++count;
  45600. }
  45601. this._charCount = count;
  45602. };
  45603. Text2D.prototype._useTextureAlpha = function () {
  45604. return this.fontTexture != null && this.fontTexture.hasAlpha;
  45605. };
  45606. Text2D.prototype._shouldUseAlphaFromTexture = function () {
  45607. return true;
  45608. };
  45609. Text2D.TEXT2D_MAINPARTID = 1;
  45610. __decorate([
  45611. BABYLON.modelLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 1, function (pi) { return Text2D.fontProperty = pi; }, false, true)
  45612. ], Text2D.prototype, "fontName", null);
  45613. __decorate([
  45614. BABYLON.dynamicLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 2, function (pi) { return Text2D.defaultFontColorProperty = pi; })
  45615. ], Text2D.prototype, "defaultFontColor", null);
  45616. __decorate([
  45617. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 3, function (pi) { return Text2D.textProperty = pi; }, false, true)
  45618. ], Text2D.prototype, "text", null);
  45619. __decorate([
  45620. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 4, function (pi) { return Text2D.sizeProperty = pi; })
  45621. ], Text2D.prototype, "size", null);
  45622. Text2D = __decorate([
  45623. BABYLON.className("Text2D")
  45624. ], Text2D);
  45625. return Text2D;
  45626. })(BABYLON.RenderablePrim2D);
  45627. BABYLON.Text2D = Text2D;
  45628. })(BABYLON || (BABYLON = {}));
  45629. var BABYLON;
  45630. (function (BABYLON) {
  45631. var Lines2DRenderCache = (function (_super) {
  45632. __extends(Lines2DRenderCache, _super);
  45633. function Lines2DRenderCache(engine, modelKey) {
  45634. _super.call(this, engine, modelKey);
  45635. this.effectsReady = false;
  45636. this.fillVB = null;
  45637. this.fillIB = null;
  45638. this.fillIndicesCount = 0;
  45639. this.instancingFillAttributes = null;
  45640. this.effectFill = null;
  45641. this.effectFillInstanced = null;
  45642. this.borderVB = null;
  45643. this.borderIB = null;
  45644. this.borderIndicesCount = 0;
  45645. this.instancingBorderAttributes = null;
  45646. this.effectBorder = null;
  45647. this.effectBorderInstanced = null;
  45648. }
  45649. Lines2DRenderCache.prototype.render = function (instanceInfo, context) {
  45650. // Do nothing if the shader is still loading/preparing
  45651. if (!this.effectsReady) {
  45652. if ((this.effectFill && (!this.effectFill.isReady() || (this.effectFillInstanced && !this.effectFillInstanced.isReady()))) ||
  45653. (this.effectBorder && (!this.effectBorder.isReady() || (this.effectBorderInstanced && !this.effectBorderInstanced.isReady())))) {
  45654. return false;
  45655. }
  45656. this.effectsReady = true;
  45657. }
  45658. var canvas = instanceInfo.owner.owner;
  45659. var engine = canvas.engine;
  45660. var depthFunction = 0;
  45661. if (this.effectFill && this.effectBorder) {
  45662. depthFunction = engine.getDepthFunction();
  45663. engine.setDepthFunctionToLessOrEqual();
  45664. }
  45665. var curAlphaMode = engine.getAlphaMode();
  45666. if (this.effectFill) {
  45667. var partIndex = instanceInfo.partIndexFromId.get(BABYLON.Shape2D.SHAPE2D_FILLPARTID.toString());
  45668. var pid = context.groupInfoPartData[partIndex];
  45669. if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
  45670. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE, true);
  45671. }
  45672. var effect = context.useInstancing ? this.effectFillInstanced : this.effectFill;
  45673. engine.enableEffect(effect);
  45674. engine.bindBuffersDirectly(this.fillVB, this.fillIB, [2], 2 * 4, effect);
  45675. if (context.useInstancing) {
  45676. if (!this.instancingFillAttributes) {
  45677. this.instancingFillAttributes = this.loadInstancingAttributes(BABYLON.Shape2D.SHAPE2D_FILLPARTID, effect);
  45678. }
  45679. var glBuffer = context.instancedBuffers ? context.instancedBuffers[partIndex] : pid._partBuffer;
  45680. var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
  45681. canvas._addDrawCallCount(1, context.renderMode);
  45682. engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingFillAttributes);
  45683. engine.draw(true, 0, this.fillIndicesCount, count);
  45684. engine.unbindInstanceAttributes();
  45685. }
  45686. else {
  45687. canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
  45688. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  45689. this.setupUniforms(effect, partIndex, pid._partData, i);
  45690. engine.draw(true, 0, this.fillIndicesCount);
  45691. }
  45692. }
  45693. }
  45694. if (this.effectBorder) {
  45695. var partIndex = instanceInfo.partIndexFromId.get(BABYLON.Shape2D.SHAPE2D_BORDERPARTID.toString());
  45696. var pid = context.groupInfoPartData[partIndex];
  45697. if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
  45698. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE, true);
  45699. }
  45700. var effect = context.useInstancing ? this.effectBorderInstanced : this.effectBorder;
  45701. engine.enableEffect(effect);
  45702. engine.bindBuffersDirectly(this.borderVB, this.borderIB, [2], 2 * 4, effect);
  45703. if (context.useInstancing) {
  45704. if (!this.instancingBorderAttributes) {
  45705. this.instancingBorderAttributes = this.loadInstancingAttributes(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, effect);
  45706. }
  45707. var glBuffer = context.instancedBuffers ? context.instancedBuffers[partIndex] : pid._partBuffer;
  45708. var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
  45709. canvas._addDrawCallCount(1, context.renderMode);
  45710. engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingBorderAttributes);
  45711. engine.draw(true, 0, this.borderIndicesCount, count);
  45712. engine.unbindInstanceAttributes();
  45713. }
  45714. else {
  45715. canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
  45716. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  45717. this.setupUniforms(effect, partIndex, pid._partData, i);
  45718. engine.draw(true, 0, this.borderIndicesCount);
  45719. }
  45720. }
  45721. }
  45722. engine.setAlphaMode(curAlphaMode, true);
  45723. if (this.effectFill && this.effectBorder) {
  45724. engine.setDepthFunction(depthFunction);
  45725. }
  45726. return true;
  45727. };
  45728. Lines2DRenderCache.prototype.dispose = function () {
  45729. if (!_super.prototype.dispose.call(this)) {
  45730. return false;
  45731. }
  45732. if (this.fillVB) {
  45733. this._engine._releaseBuffer(this.fillVB);
  45734. this.fillVB = null;
  45735. }
  45736. if (this.fillIB) {
  45737. this._engine._releaseBuffer(this.fillIB);
  45738. this.fillIB = null;
  45739. }
  45740. this.effectFill = null;
  45741. this.effectFillInstanced = null;
  45742. this.effectBorder = null;
  45743. this.effectBorderInstanced = null;
  45744. if (this.borderVB) {
  45745. this._engine._releaseBuffer(this.borderVB);
  45746. this.borderVB = null;
  45747. }
  45748. if (this.borderIB) {
  45749. this._engine._releaseBuffer(this.borderIB);
  45750. this.borderIB = null;
  45751. }
  45752. return true;
  45753. };
  45754. return Lines2DRenderCache;
  45755. })(BABYLON.ModelRenderCache);
  45756. BABYLON.Lines2DRenderCache = Lines2DRenderCache;
  45757. var Lines2DInstanceData = (function (_super) {
  45758. __extends(Lines2DInstanceData, _super);
  45759. function Lines2DInstanceData(partId) {
  45760. _super.call(this, partId, 1);
  45761. }
  45762. Object.defineProperty(Lines2DInstanceData.prototype, "boundingMin", {
  45763. get: function () {
  45764. return null;
  45765. },
  45766. enumerable: true,
  45767. configurable: true
  45768. });
  45769. Object.defineProperty(Lines2DInstanceData.prototype, "boundingMax", {
  45770. get: function () {
  45771. return null;
  45772. },
  45773. enumerable: true,
  45774. configurable: true
  45775. });
  45776. __decorate([
  45777. BABYLON.instanceData(BABYLON.Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT)
  45778. ], Lines2DInstanceData.prototype, "boundingMin", null);
  45779. __decorate([
  45780. BABYLON.instanceData(BABYLON.Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT)
  45781. ], Lines2DInstanceData.prototype, "boundingMax", null);
  45782. return Lines2DInstanceData;
  45783. })(BABYLON.Shape2DInstanceData);
  45784. BABYLON.Lines2DInstanceData = Lines2DInstanceData;
  45785. var Lines2D = (function (_super) {
  45786. __extends(Lines2D, _super);
  45787. /**
  45788. * Create an 2D Lines Shape primitive. The defined lines may be opened or closed (see below)
  45789. * @param points an array that describe the points to use to draw the line, must contain at least two entries.
  45790. * @param settings a combination of settings, possible ones are
  45791. * - 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)
  45792. * - children: an array of direct children
  45793. * - id a text identifier, for information purpose
  45794. * - position: the X & Y positions relative to its parent. Alternatively the x and y properties can be set. Default is [0;0]
  45795. * - rotation: the initial rotation (in radian) of the primitive. default is 0
  45796. * - scale: the initial scale of the primitive. default is 1. You can alternatively use scaleX &| scaleY to apply non uniform scale
  45797. * - opacity: set the overall opacity of the primitive, 1 to be opaque (default), less than 1 to be transparent.
  45798. * - zOrder: override the zOrder with the specified value
  45799. * - origin: define the normalized origin point location, default [0.5;0.5]
  45800. * - 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.
  45801. * - 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.
  45802. * - 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.
  45803. * - 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.
  45804. * - 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)
  45805. * - 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)
  45806. * - borderThickness: the thickness of the drawn border, default is 1.
  45807. * - isVisible: true if the primitive must be visible, false for hidden. Default is true.
  45808. * - 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!
  45809. * - marginTop: top margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  45810. * - marginLeft: left margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  45811. * - marginRight: right margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  45812. * - marginBottom: bottom margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  45813. * - margin: top, left, right and bottom margin formatted as a single string (see PrimitiveThickness.fromString)
  45814. * - marginHAlignment: one value of the PrimitiveAlignment type's static properties
  45815. * - marginVAlignment: one value of the PrimitiveAlignment type's static properties
  45816. * - marginAlignment: a string defining the alignment, see PrimitiveAlignment.fromString
  45817. * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  45818. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  45819. * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  45820. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  45821. * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
  45822. */
  45823. function Lines2D(points, settings) {
  45824. if (!settings) {
  45825. settings = {};
  45826. }
  45827. _super.call(this, settings);
  45828. this._fillVB = null;
  45829. this._fillIB = null;
  45830. this._borderVB = null;
  45831. this._borderIB = null;
  45832. this._size = BABYLON.Size.Zero();
  45833. this._boundingMin = null;
  45834. this._boundingMax = null;
  45835. var fillThickness = (settings.fillThickness == null) ? 1 : settings.fillThickness;
  45836. var startCap = (settings.startCap == null) ? 0 : settings.startCap;
  45837. var endCap = (settings.endCap == null) ? 0 : settings.endCap;
  45838. var closed = (settings.closed == null) ? false : settings.closed;
  45839. this.points = points;
  45840. this.fillThickness = fillThickness;
  45841. this.startCap = startCap;
  45842. this.endCap = endCap;
  45843. this.closed = closed;
  45844. }
  45845. Object.defineProperty(Lines2D, "NoCap", {
  45846. /**
  45847. * No Cap to apply on the extremity
  45848. */
  45849. get: function () { return Lines2D._noCap; },
  45850. enumerable: true,
  45851. configurable: true
  45852. });
  45853. Object.defineProperty(Lines2D, "RoundCap", {
  45854. /**
  45855. * A round cap, will use the line thickness as diameter
  45856. */
  45857. get: function () { return Lines2D._roundCap; },
  45858. enumerable: true,
  45859. configurable: true
  45860. });
  45861. Object.defineProperty(Lines2D, "TriangleCap", {
  45862. /**
  45863. * Creates a triangle at the extremity.
  45864. */
  45865. get: function () { return Lines2D._triangleCap; },
  45866. enumerable: true,
  45867. configurable: true
  45868. });
  45869. Object.defineProperty(Lines2D, "SquareAnchorCap", {
  45870. /**
  45871. * Creates a Square anchor at the extremity, the square size is twice the thickness of the line
  45872. */
  45873. get: function () { return Lines2D._squareAnchorCap; },
  45874. enumerable: true,
  45875. configurable: true
  45876. });
  45877. Object.defineProperty(Lines2D, "RoundAnchorCap", {
  45878. /**
  45879. * Creates a round anchor at the extremity, the diameter is twice the thickness of the line
  45880. */
  45881. get: function () { return Lines2D._roundAnchorCap; },
  45882. enumerable: true,
  45883. configurable: true
  45884. });
  45885. Object.defineProperty(Lines2D, "DiamondAnchorCap", {
  45886. /**
  45887. * Creates a diamond anchor at the extremity.
  45888. */
  45889. get: function () { return Lines2D._diamondAnchorCap; },
  45890. enumerable: true,
  45891. configurable: true
  45892. });
  45893. Object.defineProperty(Lines2D, "ArrowCap", {
  45894. /**
  45895. * Creates an arrow anchor at the extremity. the arrow base size is twice the thickness of the line
  45896. */
  45897. get: function () { return Lines2D._arrowCap; },
  45898. enumerable: true,
  45899. configurable: true
  45900. });
  45901. Object.defineProperty(Lines2D.prototype, "points", {
  45902. get: function () {
  45903. return this._points;
  45904. },
  45905. set: function (value) {
  45906. this._points = value;
  45907. this._contour = null;
  45908. this._boundingBoxDirty();
  45909. },
  45910. enumerable: true,
  45911. configurable: true
  45912. });
  45913. Object.defineProperty(Lines2D.prototype, "fillThickness", {
  45914. get: function () {
  45915. return this._fillThickness;
  45916. },
  45917. set: function (value) {
  45918. this._fillThickness = value;
  45919. },
  45920. enumerable: true,
  45921. configurable: true
  45922. });
  45923. Object.defineProperty(Lines2D.prototype, "closed", {
  45924. get: function () {
  45925. return this._closed;
  45926. },
  45927. set: function (value) {
  45928. this._closed = value;
  45929. },
  45930. enumerable: true,
  45931. configurable: true
  45932. });
  45933. Object.defineProperty(Lines2D.prototype, "startCap", {
  45934. get: function () {
  45935. return this._startCap;
  45936. },
  45937. set: function (value) {
  45938. this._startCap = value;
  45939. },
  45940. enumerable: true,
  45941. configurable: true
  45942. });
  45943. Object.defineProperty(Lines2D.prototype, "endCap", {
  45944. get: function () {
  45945. return this._endCap;
  45946. },
  45947. set: function (value) {
  45948. this._endCap = value;
  45949. },
  45950. enumerable: true,
  45951. configurable: true
  45952. });
  45953. Lines2D.prototype.levelIntersect = function (intersectInfo) {
  45954. var _this = this;
  45955. if (this._contour == null) {
  45956. this._computeLines2D();
  45957. }
  45958. var pl = this.points.length;
  45959. var l = this.closed ? pl + 1 : pl;
  45960. var p = intersectInfo._localPickPosition;
  45961. this.transformPointWithOriginToRef(this._contour[0], null, Lines2D._prevA);
  45962. this.transformPointWithOriginToRef(this._contour[1], null, Lines2D._prevB);
  45963. for (var i = 1; i < l; i++) {
  45964. this.transformPointWithOriginToRef(this._contour[(i % pl) * 2 + 0], null, Lines2D._curA);
  45965. this.transformPointWithOriginToRef(this._contour[(i % pl) * 2 + 1], null, Lines2D._curB);
  45966. if (BABYLON.Vector2.PointInTriangle(p, Lines2D._prevA, Lines2D._prevB, Lines2D._curA)) {
  45967. return true;
  45968. }
  45969. if (BABYLON.Vector2.PointInTriangle(p, Lines2D._curA, Lines2D._prevB, Lines2D._curB)) {
  45970. return true;
  45971. }
  45972. Lines2D._prevA.x = Lines2D._curA.x;
  45973. Lines2D._prevA.y = Lines2D._curA.y;
  45974. Lines2D._prevB.x = Lines2D._curB.x;
  45975. Lines2D._prevB.y = Lines2D._curB.y;
  45976. }
  45977. var capIntersect = function (tri, points) {
  45978. var l = tri.length;
  45979. for (var i = 0; i < l; i += 3) {
  45980. Lines2D._curA.x = points[tri[i + 0] * 2 + 0];
  45981. Lines2D._curA.y = points[tri[i + 0] * 2 + 1];
  45982. _this.transformPointWithOriginToRef(Lines2D._curA, null, Lines2D._curB);
  45983. Lines2D._curA.x = points[tri[i + 1] * 2 + 0];
  45984. Lines2D._curA.y = points[tri[i + 1] * 2 + 1];
  45985. _this.transformPointWithOriginToRef(Lines2D._curA, null, Lines2D._prevA);
  45986. Lines2D._curA.x = points[tri[i + 2] * 2 + 0];
  45987. Lines2D._curA.y = points[tri[i + 2] * 2 + 1];
  45988. _this.transformPointWithOriginToRef(Lines2D._curA, null, Lines2D._prevB);
  45989. if (BABYLON.Vector2.PointInTriangle(p, Lines2D._prevA, Lines2D._prevB, Lines2D._curB)) {
  45990. return true;
  45991. }
  45992. }
  45993. return false;
  45994. };
  45995. if (this._startCapTriIndices) {
  45996. if (this._startCapTriIndices && capIntersect(this._startCapTriIndices, this._startCapContour)) {
  45997. return true;
  45998. }
  45999. if (this._endCapTriIndices && capIntersect(this._endCapTriIndices, this._endCapContour)) {
  46000. return true;
  46001. }
  46002. }
  46003. return false;
  46004. };
  46005. Object.defineProperty(Lines2D.prototype, "boundingMin", {
  46006. get: function () {
  46007. if (!this._boundingMin) {
  46008. this._computeLines2D();
  46009. }
  46010. return this._boundingMin;
  46011. },
  46012. enumerable: true,
  46013. configurable: true
  46014. });
  46015. Object.defineProperty(Lines2D.prototype, "boundingMax", {
  46016. get: function () {
  46017. if (!this._boundingMax) {
  46018. this._computeLines2D();
  46019. }
  46020. return this._boundingMax;
  46021. },
  46022. enumerable: true,
  46023. configurable: true
  46024. });
  46025. Lines2D.prototype.getUsedShaderCategories = function (dataPart) {
  46026. var res = _super.prototype.getUsedShaderCategories.call(this, dataPart);
  46027. // Remove the BORDER category, we don't use it in the VertexShader
  46028. var i = res.indexOf(BABYLON.Shape2D.SHAPE2D_CATEGORY_BORDER);
  46029. if (i !== -1) {
  46030. res.splice(i, 1);
  46031. }
  46032. return res;
  46033. };
  46034. Lines2D.prototype.updateLevelBoundingInfo = function () {
  46035. if (!this._boundingMin) {
  46036. this._computeLines2D();
  46037. }
  46038. BABYLON.BoundingInfo2D.CreateFromMinMaxToRef(this._boundingMin.x, this._boundingMax.x, this._boundingMin.y, this._boundingMax.y, this._levelBoundingInfo);
  46039. };
  46040. Lines2D.prototype.createModelRenderCache = function (modelKey) {
  46041. var renderCache = new Lines2DRenderCache(this.owner.engine, modelKey);
  46042. return renderCache;
  46043. };
  46044. ///////////////////////////////////////////////////////////////////////////////////
  46045. // Methods for Lines building
  46046. Lines2D.prototype._perp = function (v, res) {
  46047. res.x = v.y;
  46048. res.y = -v.x;
  46049. };
  46050. ;
  46051. Lines2D.prototype._direction = function (a, b, res) {
  46052. a.subtractToRef(b, res);
  46053. res.normalize();
  46054. };
  46055. Lines2D.prototype._computeMiter = function (tangent, miter, a, b) {
  46056. a.addToRef(b, tangent);
  46057. tangent.normalize();
  46058. miter.x = -tangent.y;
  46059. miter.y = tangent.x;
  46060. Lines2D._miterTps.x = -a.y;
  46061. Lines2D._miterTps.y = a.x;
  46062. return 1 / BABYLON.Vector2.Dot(miter, Lines2D._miterTps);
  46063. };
  46064. Lines2D.prototype._intersect = function (x1, y1, x2, y2, x3, y3, x4, y4) {
  46065. var d = (x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4);
  46066. if (d === 0)
  46067. return false;
  46068. var xi = ((x3 - x4) * (x1 * y2 - y1 * x2) - (x1 - x2) * (x3 * y4 - y3 * x4)) / d; // Intersection point is xi/yi, just in case...
  46069. //let yi = ((y3 - y4) * (x1 * y2 - y1 * x2) - (y1 - y2) * (x3 * y4 - y3 * x4)) / d; // That's why I left it commented
  46070. if (xi < Math.min(x1, x2) || xi > Math.max(x1, x2))
  46071. return false;
  46072. if (xi < Math.min(x3, x4) || xi > Math.max(x3, x4))
  46073. return false;
  46074. return true;
  46075. };
  46076. Lines2D.prototype._updateMinMax = function (array, offset) {
  46077. if (offset >= array.length) {
  46078. return;
  46079. }
  46080. this._boundingMin.x = Math.min(this._boundingMin.x, array[offset]);
  46081. this._boundingMax.x = Math.max(this._boundingMax.x, array[offset]);
  46082. this._boundingMin.y = Math.min(this._boundingMin.y, array[offset + 1]);
  46083. this._boundingMax.y = Math.max(this._boundingMax.y, array[offset + 1]);
  46084. };
  46085. Lines2D.prototype._store = function (array, contour, index, max, p, n, halfThickness, borderThickness, detectFlip) {
  46086. var borderMode = borderThickness != null && !isNaN(borderThickness);
  46087. var off = index * (borderMode ? 8 : 4);
  46088. // 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)
  46089. if (off >= array.length) {
  46090. return;
  46091. }
  46092. // Store start/end normal, we need it for the cap construction
  46093. if (index === 0) {
  46094. this._perp(n, Lines2D._startDir);
  46095. }
  46096. else if (index === max - 1) {
  46097. this._perp(n, Lines2D._endDir);
  46098. Lines2D._endDir.x *= -1;
  46099. Lines2D._endDir.y *= -1;
  46100. }
  46101. var swap = false;
  46102. array[off + 0] = p.x + n.x * halfThickness;
  46103. array[off + 1] = p.y + n.y * halfThickness;
  46104. array[off + 2] = p.x + n.x * -halfThickness;
  46105. array[off + 3] = p.y + n.y * -halfThickness;
  46106. this._updateMinMax(array, off);
  46107. this._updateMinMax(array, off + 2);
  46108. // If an index is given we check if the two segments formed between [index+0;detectFlip+0] and [index+2;detectFlip+2] intersect themselves.
  46109. // 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
  46110. if (detectFlip !== undefined) {
  46111. // Flip if intersect
  46112. var flipOff = detectFlip * (borderMode ? 8 : 4);
  46113. 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])) {
  46114. swap = true;
  46115. var tps = array[off + 0];
  46116. array[off + 0] = array[off + 2];
  46117. array[off + 2] = tps;
  46118. tps = array[off + 1];
  46119. array[off + 1] = array[off + 3];
  46120. array[off + 3] = tps;
  46121. }
  46122. }
  46123. if (borderMode) {
  46124. var t = halfThickness + borderThickness;
  46125. array[off + 4] = p.x + n.x * (swap ? -t : t);
  46126. array[off + 5] = p.y + n.y * (swap ? -t : t);
  46127. array[off + 6] = p.x + n.x * (swap ? t : -t);
  46128. array[off + 7] = p.y + n.y * (swap ? t : -t);
  46129. this._updateMinMax(array, off + 4);
  46130. this._updateMinMax(array, off + 6);
  46131. }
  46132. if (contour) {
  46133. off += borderMode ? 4 : 0;
  46134. contour.push(new BABYLON.Vector2(array[off + 0], array[off + 1]));
  46135. contour.push(new BABYLON.Vector2(array[off + 2], array[off + 3]));
  46136. }
  46137. };
  46138. Lines2D.prototype._getCapSize = function (type, border) {
  46139. if (border === void 0) { border = false; }
  46140. var sd = Lines2D._roundCapSubDiv;
  46141. // If no array given, we call this to get the size
  46142. var vbsize = 0, ibsize = 0;
  46143. switch (type) {
  46144. case Lines2D.NoCap:
  46145. {
  46146. // If the line is not close and we're computing border, we add the size to generate the edge border
  46147. if (!this.closed && border) {
  46148. vbsize = 4;
  46149. ibsize = 6;
  46150. }
  46151. else {
  46152. vbsize = ibsize = 0;
  46153. }
  46154. break;
  46155. }
  46156. case Lines2D.RoundCap:
  46157. {
  46158. if (border) {
  46159. vbsize = sd;
  46160. ibsize = (sd - 2) * 3;
  46161. }
  46162. else {
  46163. vbsize = (sd / 2) + 1;
  46164. ibsize = (sd / 2) * 3;
  46165. }
  46166. break;
  46167. }
  46168. case Lines2D.ArrowCap:
  46169. {
  46170. if (border) {
  46171. vbsize = 12;
  46172. ibsize = 24;
  46173. }
  46174. else {
  46175. vbsize = 3;
  46176. ibsize = 3;
  46177. }
  46178. break;
  46179. }
  46180. case Lines2D.TriangleCap:
  46181. {
  46182. if (border) {
  46183. vbsize = 6;
  46184. ibsize = 12;
  46185. }
  46186. else {
  46187. vbsize = 3;
  46188. ibsize = 3;
  46189. }
  46190. break;
  46191. }
  46192. case Lines2D.DiamondAnchorCap:
  46193. {
  46194. if (border) {
  46195. vbsize = 10;
  46196. ibsize = 24;
  46197. }
  46198. else {
  46199. vbsize = 5;
  46200. ibsize = 9;
  46201. }
  46202. break;
  46203. }
  46204. case Lines2D.SquareAnchorCap:
  46205. {
  46206. if (border) {
  46207. vbsize = 12;
  46208. ibsize = 30;
  46209. }
  46210. else {
  46211. vbsize = 4;
  46212. ibsize = 6;
  46213. }
  46214. break;
  46215. }
  46216. case Lines2D.RoundAnchorCap:
  46217. {
  46218. if (border) {
  46219. vbsize = sd * 2;
  46220. ibsize = (sd - 1) * 6;
  46221. }
  46222. else {
  46223. vbsize = sd + 1;
  46224. ibsize = (sd + 1) * 3;
  46225. }
  46226. break;
  46227. }
  46228. }
  46229. return { vbsize: vbsize * 2, ibsize: ibsize };
  46230. };
  46231. Lines2D.prototype._storeVertex = function (vb, baseOffset, index, basePos, rotation, vertex, contour) {
  46232. var c = Math.cos(rotation);
  46233. var s = Math.sin(rotation);
  46234. Lines2D._tpsV.x = (c * vertex.x) + (-s * vertex.y) + basePos.x;
  46235. Lines2D._tpsV.y = (s * vertex.x) + (c * vertex.y) + basePos.y;
  46236. var offset = baseOffset + (index * 2);
  46237. vb[offset + 0] = Lines2D._tpsV.x;
  46238. vb[offset + 1] = Lines2D._tpsV.y;
  46239. if (contour) {
  46240. contour.push(Lines2D._tpsV.x);
  46241. contour.push(Lines2D._tpsV.y);
  46242. }
  46243. this._updateMinMax(vb, offset);
  46244. return (baseOffset + index * 2) / 2;
  46245. };
  46246. Lines2D.prototype._storeIndex = function (ib, baseOffset, index, vertexIndex) {
  46247. ib[baseOffset + index] = vertexIndex;
  46248. };
  46249. Lines2D.prototype._buildCap = function (vb, vbi, ib, ibi, pos, thickness, borderThickness, type, capDir, contour) {
  46250. // 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
  46251. var sd = Lines2D._roundCapSubDiv;
  46252. var dir = new BABYLON.Vector2(1, 0);
  46253. var angle = Math.atan2(capDir.y, capDir.x) - Math.atan2(dir.y, dir.x);
  46254. var ht = thickness / 2;
  46255. var t = thickness;
  46256. var borderMode = borderThickness != null;
  46257. var bt = borderThickness;
  46258. switch (type) {
  46259. case Lines2D.NoCap:
  46260. if (borderMode && !this.closed) {
  46261. var vi = 0;
  46262. var ii = 0;
  46263. var v1 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, ht + bt), contour);
  46264. var v2 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(bt, ht + bt), contour);
  46265. var v3 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(bt, -(ht + bt)), contour);
  46266. var v4 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, -(ht + bt)), contour);
  46267. this._storeIndex(ib, ibi, ii++, v1);
  46268. this._storeIndex(ib, ibi, ii++, v2);
  46269. this._storeIndex(ib, ibi, ii++, v3);
  46270. this._storeIndex(ib, ibi, ii++, v1);
  46271. this._storeIndex(ib, ibi, ii++, v3);
  46272. this._storeIndex(ib, ibi, ii++, v4);
  46273. }
  46274. break;
  46275. case Lines2D.ArrowCap:
  46276. ht *= 2;
  46277. case Lines2D.TriangleCap:
  46278. {
  46279. if (borderMode) {
  46280. var f = type === Lines2D.TriangleCap ? bt : Math.sqrt(bt * bt * 2);
  46281. var v1 = this._storeVertex(vb, vbi, 0, pos, angle, new BABYLON.Vector2(0, ht), null);
  46282. var v2 = this._storeVertex(vb, vbi, 1, pos, angle, new BABYLON.Vector2(ht, 0), null);
  46283. var v3 = this._storeVertex(vb, vbi, 2, pos, angle, new BABYLON.Vector2(0, -ht), null);
  46284. var v4 = this._storeVertex(vb, vbi, 3, pos, angle, new BABYLON.Vector2(0, ht + f), contour);
  46285. var v5 = this._storeVertex(vb, vbi, 4, pos, angle, new BABYLON.Vector2(ht + f, 0), contour);
  46286. var v6 = this._storeVertex(vb, vbi, 5, pos, angle, new BABYLON.Vector2(0, -(ht + f)), contour);
  46287. var ii = 0;
  46288. this._storeIndex(ib, ibi, ii++, v1);
  46289. this._storeIndex(ib, ibi, ii++, v4);
  46290. this._storeIndex(ib, ibi, ii++, v5);
  46291. this._storeIndex(ib, ibi, ii++, v1);
  46292. this._storeIndex(ib, ibi, ii++, v5);
  46293. this._storeIndex(ib, ibi, ii++, v2);
  46294. this._storeIndex(ib, ibi, ii++, v6);
  46295. this._storeIndex(ib, ibi, ii++, v3);
  46296. this._storeIndex(ib, ibi, ii++, v2);
  46297. this._storeIndex(ib, ibi, ii++, v6);
  46298. this._storeIndex(ib, ibi, ii++, v2);
  46299. this._storeIndex(ib, ibi, ii++, v5);
  46300. if (type === Lines2D.ArrowCap) {
  46301. var rht = thickness / 2;
  46302. var v10 = this._storeVertex(vb, vbi, 9, pos, angle, new BABYLON.Vector2(0, -(rht + bt)), null);
  46303. var v12 = this._storeVertex(vb, vbi, 11, pos, angle, new BABYLON.Vector2(-bt, -(ht + f)), contour);
  46304. var v11 = this._storeVertex(vb, vbi, 10, pos, angle, new BABYLON.Vector2(-bt, -(rht + bt)), contour);
  46305. var v7 = this._storeVertex(vb, vbi, 6, pos, angle, new BABYLON.Vector2(0, rht + bt), null);
  46306. var v8 = this._storeVertex(vb, vbi, 7, pos, angle, new BABYLON.Vector2(-bt, rht + bt), contour);
  46307. var v9 = this._storeVertex(vb, vbi, 8, pos, angle, new BABYLON.Vector2(-bt, ht + f), contour);
  46308. this._storeIndex(ib, ibi, ii++, v7);
  46309. this._storeIndex(ib, ibi, ii++, v8);
  46310. this._storeIndex(ib, ibi, ii++, v9);
  46311. this._storeIndex(ib, ibi, ii++, v7);
  46312. this._storeIndex(ib, ibi, ii++, v9);
  46313. this._storeIndex(ib, ibi, ii++, v4);
  46314. this._storeIndex(ib, ibi, ii++, v10);
  46315. this._storeIndex(ib, ibi, ii++, v12);
  46316. this._storeIndex(ib, ibi, ii++, v11);
  46317. this._storeIndex(ib, ibi, ii++, v10);
  46318. this._storeIndex(ib, ibi, ii++, v6);
  46319. this._storeIndex(ib, ibi, ii++, v12);
  46320. }
  46321. }
  46322. else {
  46323. var v1 = this._storeVertex(vb, vbi, 0, pos, angle, new BABYLON.Vector2(0, ht), contour);
  46324. var v2 = this._storeVertex(vb, vbi, 1, pos, angle, new BABYLON.Vector2(ht, 0), contour);
  46325. var v3 = this._storeVertex(vb, vbi, 2, pos, angle, new BABYLON.Vector2(0, -ht), contour);
  46326. this._storeIndex(ib, ibi, 0, v1);
  46327. this._storeIndex(ib, ibi, 1, v2);
  46328. this._storeIndex(ib, ibi, 2, v3);
  46329. }
  46330. break;
  46331. }
  46332. case Lines2D.RoundCap:
  46333. {
  46334. if (borderMode) {
  46335. var curA = -Math.PI / 2;
  46336. var incA = Math.PI / (sd / 2 - 1);
  46337. var ii = 0;
  46338. for (var i = 0; i < (sd / 2); i++) {
  46339. var v1 = this._storeVertex(vb, vbi, i * 2 + 0, pos, angle, new BABYLON.Vector2(Math.cos(curA) * ht, Math.sin(curA) * ht), null);
  46340. 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);
  46341. if (i > 0) {
  46342. this._storeIndex(ib, ibi, ii++, v1 - 2);
  46343. this._storeIndex(ib, ibi, ii++, v2 - 2);
  46344. this._storeIndex(ib, ibi, ii++, v2);
  46345. this._storeIndex(ib, ibi, ii++, v1 - 2);
  46346. this._storeIndex(ib, ibi, ii++, v2);
  46347. this._storeIndex(ib, ibi, ii++, v1);
  46348. }
  46349. curA += incA;
  46350. }
  46351. }
  46352. else {
  46353. var c = this._storeVertex(vb, vbi, 0, pos, angle, new BABYLON.Vector2(0, 0), null);
  46354. var curA = -Math.PI / 2;
  46355. var incA = Math.PI / (sd / 2 - 1);
  46356. this._storeVertex(vb, vbi, 1, pos, angle, new BABYLON.Vector2(Math.cos(curA) * ht, Math.sin(curA) * ht), null);
  46357. curA += incA;
  46358. for (var i = 1; i < (sd / 2); i++) {
  46359. var v2 = this._storeVertex(vb, vbi, i + 1, pos, angle, new BABYLON.Vector2(Math.cos(curA) * ht, Math.sin(curA) * ht), contour);
  46360. this._storeIndex(ib, ibi, i * 3 + 0, c);
  46361. this._storeIndex(ib, ibi, i * 3 + 1, v2 - 1);
  46362. this._storeIndex(ib, ibi, i * 3 + 2, v2);
  46363. curA += incA;
  46364. }
  46365. }
  46366. break;
  46367. }
  46368. case Lines2D.SquareAnchorCap:
  46369. {
  46370. var vi = 0;
  46371. var c = borderMode ? null : contour;
  46372. var v1 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, t), c);
  46373. var v2 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(t * 2, t), c);
  46374. var v3 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(t * 2, -t), c);
  46375. var v4 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, -t), c);
  46376. if (borderMode) {
  46377. var v5 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, ht + bt), null);
  46378. var v6 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(-bt, ht + bt), contour);
  46379. var v7 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(-bt, t + bt), contour);
  46380. var v8 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(t * 2 + bt, t + bt), contour);
  46381. var v9 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(t * 2 + bt, -(t + bt)), contour);
  46382. var v10 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(-bt, -(t + bt)), contour);
  46383. var v11 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(-bt, -(ht + bt)), contour);
  46384. var v12 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, -(ht + bt)), null);
  46385. var ii = 0;
  46386. this._storeIndex(ib, ibi, ii++, v6);
  46387. this._storeIndex(ib, ibi, ii++, v1);
  46388. this._storeIndex(ib, ibi, ii++, v5);
  46389. this._storeIndex(ib, ibi, ii++, v6);
  46390. this._storeIndex(ib, ibi, ii++, v7);
  46391. this._storeIndex(ib, ibi, ii++, v1);
  46392. this._storeIndex(ib, ibi, ii++, v1);
  46393. this._storeIndex(ib, ibi, ii++, v7);
  46394. this._storeIndex(ib, ibi, ii++, v8);
  46395. this._storeIndex(ib, ibi, ii++, v1);
  46396. this._storeIndex(ib, ibi, ii++, v8);
  46397. this._storeIndex(ib, ibi, ii++, v2);
  46398. this._storeIndex(ib, ibi, ii++, v2);
  46399. this._storeIndex(ib, ibi, ii++, v8);
  46400. this._storeIndex(ib, ibi, ii++, v9);
  46401. this._storeIndex(ib, ibi, ii++, v2);
  46402. this._storeIndex(ib, ibi, ii++, v9);
  46403. this._storeIndex(ib, ibi, ii++, v3);
  46404. this._storeIndex(ib, ibi, ii++, v3);
  46405. this._storeIndex(ib, ibi, ii++, v9);
  46406. this._storeIndex(ib, ibi, ii++, v10);
  46407. this._storeIndex(ib, ibi, ii++, v3);
  46408. this._storeIndex(ib, ibi, ii++, v10);
  46409. this._storeIndex(ib, ibi, ii++, v4);
  46410. this._storeIndex(ib, ibi, ii++, v10);
  46411. this._storeIndex(ib, ibi, ii++, v11);
  46412. this._storeIndex(ib, ibi, ii++, v4);
  46413. this._storeIndex(ib, ibi, ii++, v11);
  46414. this._storeIndex(ib, ibi, ii++, v12);
  46415. this._storeIndex(ib, ibi, ii++, v4);
  46416. }
  46417. else {
  46418. this._storeIndex(ib, ibi, 0, v1);
  46419. this._storeIndex(ib, ibi, 1, v2);
  46420. this._storeIndex(ib, ibi, 2, v3);
  46421. this._storeIndex(ib, ibi, 3, v1);
  46422. this._storeIndex(ib, ibi, 4, v3);
  46423. this._storeIndex(ib, ibi, 5, v4);
  46424. }
  46425. break;
  46426. }
  46427. case Lines2D.RoundAnchorCap:
  46428. {
  46429. var cpos = Math.sqrt(t * t - ht * ht);
  46430. var center = new BABYLON.Vector2(cpos, 0);
  46431. var curA = BABYLON.Tools.ToRadians(-150);
  46432. var incA = BABYLON.Tools.ToRadians(300) / (sd - 1);
  46433. if (borderMode) {
  46434. var ii = 0;
  46435. for (var i = 0; i < sd; i++) {
  46436. var v1 = this._storeVertex(vb, vbi, i * 2 + 0, pos, angle, new BABYLON.Vector2(cpos + Math.cos(curA) * t, Math.sin(curA) * t), null);
  46437. 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);
  46438. if (i > 0) {
  46439. this._storeIndex(ib, ibi, ii++, v1 - 2);
  46440. this._storeIndex(ib, ibi, ii++, v2 - 2);
  46441. this._storeIndex(ib, ibi, ii++, v2);
  46442. this._storeIndex(ib, ibi, ii++, v1 - 2);
  46443. this._storeIndex(ib, ibi, ii++, v2);
  46444. this._storeIndex(ib, ibi, ii++, v1);
  46445. }
  46446. curA += incA;
  46447. }
  46448. }
  46449. else {
  46450. var c = this._storeVertex(vb, vbi, 0, pos, angle, center, null);
  46451. this._storeVertex(vb, vbi, 1, pos, angle, new BABYLON.Vector2(cpos + Math.cos(curA) * t, Math.sin(curA) * t), null);
  46452. curA += incA;
  46453. for (var i = 1; i < sd; i++) {
  46454. var v2 = this._storeVertex(vb, vbi, i + 1, pos, angle, new BABYLON.Vector2(cpos + Math.cos(curA) * t, Math.sin(curA) * t), contour);
  46455. this._storeIndex(ib, ibi, i * 3 + 0, c);
  46456. this._storeIndex(ib, ibi, i * 3 + 1, v2 - 1);
  46457. this._storeIndex(ib, ibi, i * 3 + 2, v2);
  46458. curA += incA;
  46459. }
  46460. this._storeIndex(ib, ibi, sd * 3 + 0, c);
  46461. this._storeIndex(ib, ibi, sd * 3 + 1, c + 1);
  46462. this._storeIndex(ib, ibi, sd * 3 + 2, c + sd);
  46463. }
  46464. break;
  46465. }
  46466. case Lines2D.DiamondAnchorCap:
  46467. {
  46468. var vi = 0;
  46469. var c = borderMode ? null : contour;
  46470. var v1 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, ht), c);
  46471. var v2 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(ht, t), c);
  46472. var v3 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(ht * 3, 0), c);
  46473. var v4 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(ht, -t), c);
  46474. var v5 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, -ht), c);
  46475. if (borderMode) {
  46476. var f = Math.sqrt(bt * bt * 2);
  46477. var v6 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(-f, ht), contour);
  46478. var v7 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(ht, t + f), contour);
  46479. var v8 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(ht * 3 + f, 0), contour);
  46480. var v9 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(ht, -(t + f)), contour);
  46481. var v10 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(-f, -ht), contour);
  46482. var ii = 0;
  46483. this._storeIndex(ib, ibi, ii++, v6);
  46484. this._storeIndex(ib, ibi, ii++, v7);
  46485. this._storeIndex(ib, ibi, ii++, v1);
  46486. this._storeIndex(ib, ibi, ii++, v1);
  46487. this._storeIndex(ib, ibi, ii++, v7);
  46488. this._storeIndex(ib, ibi, ii++, v2);
  46489. this._storeIndex(ib, ibi, ii++, v2);
  46490. this._storeIndex(ib, ibi, ii++, v7);
  46491. this._storeIndex(ib, ibi, ii++, v8);
  46492. this._storeIndex(ib, ibi, ii++, v2);
  46493. this._storeIndex(ib, ibi, ii++, v8);
  46494. this._storeIndex(ib, ibi, ii++, v3);
  46495. this._storeIndex(ib, ibi, ii++, v3);
  46496. this._storeIndex(ib, ibi, ii++, v8);
  46497. this._storeIndex(ib, ibi, ii++, v9);
  46498. this._storeIndex(ib, ibi, ii++, v3);
  46499. this._storeIndex(ib, ibi, ii++, v9);
  46500. this._storeIndex(ib, ibi, ii++, v4);
  46501. this._storeIndex(ib, ibi, ii++, v4);
  46502. this._storeIndex(ib, ibi, ii++, v9);
  46503. this._storeIndex(ib, ibi, ii++, v10);
  46504. this._storeIndex(ib, ibi, ii++, v4);
  46505. this._storeIndex(ib, ibi, ii++, v10);
  46506. this._storeIndex(ib, ibi, ii++, v5);
  46507. }
  46508. else {
  46509. this._storeIndex(ib, ibi, 0, v1);
  46510. this._storeIndex(ib, ibi, 1, v2);
  46511. this._storeIndex(ib, ibi, 2, v3);
  46512. this._storeIndex(ib, ibi, 3, v1);
  46513. this._storeIndex(ib, ibi, 4, v3);
  46514. this._storeIndex(ib, ibi, 5, v5);
  46515. this._storeIndex(ib, ibi, 6, v5);
  46516. this._storeIndex(ib, ibi, 7, v3);
  46517. this._storeIndex(ib, ibi, 8, v4);
  46518. }
  46519. break;
  46520. }
  46521. }
  46522. return null;
  46523. };
  46524. Lines2D.prototype._buildLine = function (vb, contour, ht, bt) {
  46525. var lineA = BABYLON.Vector2.Zero();
  46526. var lineB = BABYLON.Vector2.Zero();
  46527. var tangent = BABYLON.Vector2.Zero();
  46528. var miter = BABYLON.Vector2.Zero();
  46529. var curNormal = null;
  46530. if (this.closed) {
  46531. this.points.push(this.points[0]);
  46532. }
  46533. var total = this.points.length;
  46534. for (var i = 1; i < total; i++) {
  46535. var last = this.points[i - 1];
  46536. var cur = this.points[i];
  46537. var next = (i < (this.points.length - 1)) ? this.points[i + 1] : null;
  46538. this._direction(cur, last, lineA);
  46539. if (!curNormal) {
  46540. curNormal = BABYLON.Vector2.Zero();
  46541. this._perp(lineA, curNormal);
  46542. }
  46543. if (i === 1) {
  46544. this._store(vb, contour, 0, total, this.points[0], curNormal, ht, bt);
  46545. }
  46546. if (!next) {
  46547. this._perp(lineA, curNormal);
  46548. this._store(vb, contour, i, total, this.points[i], curNormal, ht, bt, i - 1);
  46549. }
  46550. else {
  46551. this._direction(next, cur, lineB);
  46552. var miterLen = this._computeMiter(tangent, miter, lineA, lineB);
  46553. this._store(vb, contour, i, total, this.points[i], miter, miterLen * ht, miterLen * bt, i - 1);
  46554. }
  46555. }
  46556. if (this.points.length > 2 && this.closed) {
  46557. var last2 = this.points[total - 2];
  46558. var cur2 = this.points[0];
  46559. var next2 = this.points[1];
  46560. this._direction(cur2, last2, lineA);
  46561. this._direction(next2, cur2, lineB);
  46562. this._perp(lineA, curNormal);
  46563. var miterLen2 = this._computeMiter(tangent, miter, lineA, lineB);
  46564. this._store(vb, null, 0, total, this.points[0], miter, miterLen2 * ht, miterLen2 * bt, 1);
  46565. // Patch contour
  46566. if (contour) {
  46567. var off = (bt == null) ? 0 : 4;
  46568. contour[0].x = vb[off + 0];
  46569. contour[0].y = vb[off + 1];
  46570. contour[1].x = vb[off + 2];
  46571. contour[1].y = vb[off + 3];
  46572. }
  46573. }
  46574. // Remove the point we added at the beginning
  46575. if (this.closed) {
  46576. this.points.splice(total - 1);
  46577. }
  46578. };
  46579. // Methods for Lines building
  46580. ///////////////////////////////////////////////////////////////////////////////////
  46581. Lines2D.prototype.setupModelRenderCache = function (modelRenderCache) {
  46582. var renderCache = modelRenderCache;
  46583. var engine = this.owner.engine;
  46584. if (this._fillVB === null) {
  46585. this._computeLines2D();
  46586. }
  46587. // Need to create WebGL resources for fill part?
  46588. if (this.fill) {
  46589. renderCache.fillVB = engine.createVertexBuffer(this._fillVB);
  46590. renderCache.fillIB = engine.createIndexBuffer(this._fillIB);
  46591. renderCache.fillIndicesCount = this._fillIB.length;
  46592. // 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
  46593. var ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_FILLPARTID, ["position"], null, true);
  46594. if (ei) {
  46595. renderCache.effectFillInstanced = engine.createEffect("lines2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  46596. }
  46597. // Get the non instanced version
  46598. ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_FILLPARTID, ["position"], null, false);
  46599. renderCache.effectFill = engine.createEffect("lines2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  46600. }
  46601. // Need to create WebGL resources for border part?
  46602. if (this.border) {
  46603. renderCache.borderVB = engine.createVertexBuffer(this._borderVB);
  46604. renderCache.borderIB = engine.createIndexBuffer(this._borderIB);
  46605. renderCache.borderIndicesCount = this._borderIB.length;
  46606. // 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
  46607. var ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, ["position"], null, true);
  46608. if (ei) {
  46609. renderCache.effectBorderInstanced = engine.createEffect({ vertex: "lines2d", fragment: "lines2d" }, ei.attributes, ei.uniforms, [], ei.defines, null);
  46610. }
  46611. // Get the non instanced version
  46612. ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, ["position"], null, false);
  46613. renderCache.effectBorder = engine.createEffect({ vertex: "lines2d", fragment: "lines2d" }, ei.attributes, ei.uniforms, [], ei.defines, null);
  46614. }
  46615. this._fillVB = null;
  46616. this._fillIB = null;
  46617. this._borderVB = null;
  46618. this._borderIB = null;
  46619. return renderCache;
  46620. };
  46621. Lines2D.prototype._computeLines2D = function () {
  46622. // Init min/max because their being computed here
  46623. this._boundingMin = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  46624. this._boundingMax = new BABYLON.Vector2(Number.MIN_VALUE, Number.MIN_VALUE);
  46625. var contour = new Array();
  46626. var startCapContour = new Array();
  46627. var endCapContour = new Array();
  46628. // Need to create WebGL resources for fill part?
  46629. if (this.fill) {
  46630. var startCapInfo = this._getCapSize(this.startCap);
  46631. var endCapInfo = this._getCapSize(this.endCap);
  46632. var count = this.points.length;
  46633. var vbSize = (count * 2 * 2) + startCapInfo.vbsize + endCapInfo.vbsize;
  46634. this._fillVB = new Float32Array(vbSize);
  46635. var vb = this._fillVB;
  46636. var ht = this.fillThickness / 2;
  46637. var total = this.points.length;
  46638. this._buildLine(vb, this.border ? null : contour, ht);
  46639. var max = total * 2;
  46640. var triCount = (count - (this.closed ? 0 : 1)) * 2;
  46641. this._fillIB = new Float32Array(triCount * 3 + startCapInfo.ibsize + endCapInfo.ibsize);
  46642. var ib = this._fillIB;
  46643. for (var i = 0; i < triCount; i += 2) {
  46644. ib[i * 3 + 0] = i + 0;
  46645. ib[i * 3 + 1] = i + 1;
  46646. ib[i * 3 + 2] = (i + 2) % max;
  46647. ib[i * 3 + 3] = i + 1;
  46648. ib[i * 3 + 4] = (i + 3) % max;
  46649. ib[i * 3 + 5] = (i + 2) % max;
  46650. }
  46651. this._buildCap(vb, count * 2 * 2, ib, triCount * 3, this.points[0], this.fillThickness, null, this.startCap, Lines2D._startDir, this.border ? null : startCapContour);
  46652. 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);
  46653. }
  46654. // Need to create WebGL resources for border part?
  46655. if (this.border) {
  46656. var startCapInfo = this._getCapSize(this.startCap, true);
  46657. var endCapInfo = this._getCapSize(this.endCap, true);
  46658. var count = this.points.length;
  46659. var vbSize = (count * 2 * 2 * 2) + startCapInfo.vbsize + endCapInfo.vbsize;
  46660. this._borderVB = new Float32Array(vbSize);
  46661. var vb = this._borderVB;
  46662. var ht = this.fillThickness / 2;
  46663. var bt = this.borderThickness;
  46664. var total = this.points.length;
  46665. this._buildLine(vb, contour, ht, bt);
  46666. var max = total * 2 * 2;
  46667. var triCount = (count - (this.closed ? 0 : 1)) * 2 * 2;
  46668. this._borderIB = new Float32Array(triCount * 3 + startCapInfo.ibsize + endCapInfo.ibsize);
  46669. var ib = this._borderIB;
  46670. for (var i = 0; i < triCount; i += 4) {
  46671. ib[i * 3 + 0] = i + 0;
  46672. ib[i * 3 + 1] = i + 2;
  46673. ib[i * 3 + 2] = (i + 6) % max;
  46674. ib[i * 3 + 3] = i + 0;
  46675. ib[i * 3 + 4] = (i + 6) % max;
  46676. ib[i * 3 + 5] = (i + 4) % max;
  46677. ib[i * 3 + 6] = i + 3;
  46678. ib[i * 3 + 7] = i + 1;
  46679. ib[i * 3 + 8] = (i + 5) % max;
  46680. ib[i * 3 + 9] = i + 3;
  46681. ib[i * 3 + 10] = (i + 5) % max;
  46682. ib[i * 3 + 11] = (i + 7) % max;
  46683. }
  46684. this._buildCap(vb, count * 2 * 2 * 2, ib, triCount * 3, this.points[0], this.fillThickness, this.borderThickness, this.startCap, Lines2D._startDir, startCapContour);
  46685. 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);
  46686. }
  46687. this._contour = contour;
  46688. if (startCapContour.length > 0) {
  46689. var startCapTri = Earcut.earcut(startCapContour, null, 2);
  46690. this._startCapTriIndices = startCapTri;
  46691. this._startCapContour = startCapContour;
  46692. }
  46693. else {
  46694. this._startCapTriIndices = null;
  46695. this._startCapContour = null;
  46696. }
  46697. if (endCapContour.length > 0) {
  46698. var endCapTri = Earcut.earcut(endCapContour, null, 2);
  46699. this._endCapContour = endCapContour;
  46700. this._endCapTriIndices = endCapTri;
  46701. }
  46702. else {
  46703. this._endCapContour = null;
  46704. this._endCapTriIndices = null;
  46705. }
  46706. var bs = this._boundingMax.subtract(this._boundingMin);
  46707. this._size.width = bs.x;
  46708. this._size.height = bs.y;
  46709. };
  46710. Object.defineProperty(Lines2D.prototype, "size", {
  46711. get: function () {
  46712. if (this._size == null) {
  46713. this._computeLines2D();
  46714. }
  46715. return this._size;
  46716. },
  46717. enumerable: true,
  46718. configurable: true
  46719. });
  46720. Lines2D.prototype.createInstanceDataParts = function () {
  46721. var res = new Array();
  46722. if (this.border) {
  46723. res.push(new Lines2DInstanceData(BABYLON.Shape2D.SHAPE2D_BORDERPARTID));
  46724. }
  46725. if (this.fill) {
  46726. res.push(new Lines2DInstanceData(BABYLON.Shape2D.SHAPE2D_FILLPARTID));
  46727. }
  46728. return res;
  46729. };
  46730. Lines2D.prototype.refreshInstanceDataPart = function (part) {
  46731. if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
  46732. return false;
  46733. }
  46734. if (part.id === BABYLON.Shape2D.SHAPE2D_BORDERPARTID) {
  46735. var d = part;
  46736. if (this.border instanceof BABYLON.GradientColorBrush2D) {
  46737. d.boundingMin = this.boundingMin;
  46738. d.boundingMax = this.boundingMax;
  46739. }
  46740. }
  46741. else if (part.id === BABYLON.Shape2D.SHAPE2D_FILLPARTID) {
  46742. var d = part;
  46743. if (this.fill instanceof BABYLON.GradientColorBrush2D) {
  46744. d.boundingMin = this.boundingMin;
  46745. d.boundingMax = this.boundingMax;
  46746. }
  46747. }
  46748. return true;
  46749. };
  46750. Lines2D._prevA = BABYLON.Vector2.Zero();
  46751. Lines2D._prevB = BABYLON.Vector2.Zero();
  46752. Lines2D._curA = BABYLON.Vector2.Zero();
  46753. Lines2D._curB = BABYLON.Vector2.Zero();
  46754. Lines2D._miterTps = BABYLON.Vector2.Zero();
  46755. Lines2D._startDir = BABYLON.Vector2.Zero();
  46756. Lines2D._endDir = BABYLON.Vector2.Zero();
  46757. Lines2D._tpsV = BABYLON.Vector2.Zero();
  46758. Lines2D._noCap = 0;
  46759. Lines2D._roundCap = 1;
  46760. Lines2D._triangleCap = 2;
  46761. Lines2D._squareAnchorCap = 3;
  46762. Lines2D._roundAnchorCap = 4;
  46763. Lines2D._diamondAnchorCap = 5;
  46764. Lines2D._arrowCap = 6;
  46765. Lines2D._roundCapSubDiv = 36;
  46766. __decorate([
  46767. BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 1, function (pi) { return Lines2D.pointsProperty = pi; })
  46768. ], Lines2D.prototype, "points", null);
  46769. __decorate([
  46770. BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 2, function (pi) { return Lines2D.fillThicknessProperty = pi; })
  46771. ], Lines2D.prototype, "fillThickness", null);
  46772. __decorate([
  46773. BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 3, function (pi) { return Lines2D.closedProperty = pi; })
  46774. ], Lines2D.prototype, "closed", null);
  46775. __decorate([
  46776. BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 4, function (pi) { return Lines2D.startCapProperty = pi; })
  46777. ], Lines2D.prototype, "startCap", null);
  46778. __decorate([
  46779. BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 5, function (pi) { return Lines2D.endCapProperty = pi; })
  46780. ], Lines2D.prototype, "endCap", null);
  46781. Lines2D = __decorate([
  46782. BABYLON.className("Lines2D")
  46783. ], Lines2D);
  46784. return Lines2D;
  46785. })(BABYLON.Shape2D);
  46786. BABYLON.Lines2D = Lines2D;
  46787. })(BABYLON || (BABYLON = {}));
  46788. var BABYLON;
  46789. (function (BABYLON) {
  46790. // This class contains data that lifetime is bounding to the Babylon Engine object
  46791. var Canvas2DEngineBoundData = (function () {
  46792. function Canvas2DEngineBoundData() {
  46793. this._modelCache = new BABYLON.StringDictionary();
  46794. }
  46795. Canvas2DEngineBoundData.prototype.GetOrAddModelCache = function (key, factory) {
  46796. return this._modelCache.getOrAddWithFactory(key, factory);
  46797. };
  46798. Canvas2DEngineBoundData.prototype.DisposeModelRenderCache = function (modelRenderCache) {
  46799. if (!modelRenderCache.isDisposed) {
  46800. return false;
  46801. }
  46802. this._modelCache.remove(modelRenderCache.modelKey);
  46803. return true;
  46804. };
  46805. return Canvas2DEngineBoundData;
  46806. })();
  46807. BABYLON.Canvas2DEngineBoundData = Canvas2DEngineBoundData;
  46808. var Canvas2D = (function (_super) {
  46809. __extends(Canvas2D, _super);
  46810. function Canvas2D(scene, settings) {
  46811. var _this = this;
  46812. _super.call(this, settings);
  46813. /**
  46814. * 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.
  46815. * Beware that you have to take under consideration the origin in your calculations! Good luck!
  46816. */
  46817. this.worldSpaceToNodeLocal = function (worldPos) {
  46818. var node = _this._worldSpaceNode;
  46819. if (!node) {
  46820. return;
  46821. }
  46822. var mtx = node.getWorldMatrix().clone();
  46823. mtx.invert();
  46824. var v = BABYLON.Vector3.TransformCoordinates(worldPos, mtx);
  46825. var res = new BABYLON.Vector2(v.x, v.y);
  46826. var size = _this.actualSize;
  46827. res.x += size.width * 0.5; // res is centered, make it relative to bottom/left
  46828. res.y += size.height * 0.5;
  46829. return res;
  46830. };
  46831. /**
  46832. * 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
  46833. */
  46834. this.worldSpaceCacheChanged = function () {
  46835. var plane = _this.worldSpaceCanvasNode;
  46836. var vd = BABYLON.VertexData.ExtractFromMesh(plane); //new VertexData();
  46837. vd.uvs = new Float32Array(8);
  46838. var material = plane.material;
  46839. var tex = _this._renderableData._cacheTexture;
  46840. if (material.diffuseTexture !== tex) {
  46841. material.diffuseTexture = tex;
  46842. tex.hasAlpha = true;
  46843. }
  46844. var nodeuv = _this._renderableData._cacheNodeUVs;
  46845. for (var i = 0; i < 4; i++) {
  46846. vd.uvs[i * 2 + 0] = nodeuv[i].x;
  46847. vd.uvs[i * 2 + 1] = nodeuv[i].y;
  46848. }
  46849. vd.applyToMesh(plane);
  46850. };
  46851. this._notifDebugMode = false;
  46852. this._mapCounter = 0;
  46853. this._drawCallsOpaqueCounter = new BABYLON.PerfCounter();
  46854. this._drawCallsAlphaTestCounter = new BABYLON.PerfCounter();
  46855. this._drawCallsTransparentCounter = new BABYLON.PerfCounter();
  46856. this._groupRenderCounter = new BABYLON.PerfCounter();
  46857. this._updateTransparentDataCounter = new BABYLON.PerfCounter();
  46858. this._cachedGroupRenderCounter = new BABYLON.PerfCounter();
  46859. this._updateCachedStateCounter = new BABYLON.PerfCounter();
  46860. this._updateLayoutCounter = new BABYLON.PerfCounter();
  46861. this._updatePositioningCounter = new BABYLON.PerfCounter();
  46862. this._updateLocalTransformCounter = new BABYLON.PerfCounter();
  46863. this._updateGlobalTransformCounter = new BABYLON.PerfCounter();
  46864. this._boundingInfoRecomputeCounter = new BABYLON.PerfCounter();
  46865. this._profileInfoText = null;
  46866. BABYLON.Prim2DBase._isCanvasInit = false;
  46867. if (!settings) {
  46868. settings = {};
  46869. }
  46870. if (this._cachingStrategy !== Canvas2D.CACHESTRATEGY_TOPLEVELGROUPS) {
  46871. this._background = new BABYLON.Rectangle2D({ parent: this, id: "###CANVAS BACKGROUND###", size: settings.size }); //TODO CHECK when size is null
  46872. this._background.zOrder = 1.0;
  46873. this._background.isPickable = false;
  46874. this._background.origin = BABYLON.Vector2.Zero();
  46875. this._background.levelVisible = false;
  46876. if (settings.backgroundRoundRadius != null) {
  46877. this.backgroundRoundRadius = settings.backgroundRoundRadius;
  46878. }
  46879. if (settings.backgroundBorder != null) {
  46880. if (typeof (settings.backgroundBorder) === "string") {
  46881. this.backgroundBorder = Canvas2D.GetBrushFromString(settings.backgroundBorder);
  46882. }
  46883. else {
  46884. this.backgroundBorder = settings.backgroundBorder;
  46885. }
  46886. }
  46887. if (settings.backgroundBorderThickNess != null) {
  46888. this.backgroundBorderThickness = settings.backgroundBorderThickNess;
  46889. }
  46890. if (settings.backgroundFill != null) {
  46891. if (typeof (settings.backgroundFill) === "string") {
  46892. this.backgroundFill = Canvas2D.GetBrushFromString(settings.backgroundFill);
  46893. }
  46894. else {
  46895. this.backgroundFill = settings.backgroundFill;
  46896. }
  46897. }
  46898. this._background._patchHierarchy(this);
  46899. }
  46900. var engine = scene.getEngine();
  46901. this.__engineData = engine.getOrAddExternalDataWithFactory("__BJSCANVAS2D__", function (k) { return new Canvas2DEngineBoundData(); });
  46902. this._primPointerInfo = new BABYLON.PrimitivePointerInfo();
  46903. this._capturedPointers = new BABYLON.StringDictionary();
  46904. this._pickStartingPosition = BABYLON.Vector2.Zero();
  46905. this._hierarchyLevelMaxSiblingCount = 50;
  46906. this._hierarchyDepth = 0;
  46907. this._zOrder = 0;
  46908. this._zMax = 1;
  46909. this._scene = scene;
  46910. this._engine = engine;
  46911. this._renderingSize = new BABYLON.Size(0, 0);
  46912. this._trackedGroups = new Array();
  46913. this._maxAdaptiveWorldSpaceCanvasSize = null;
  46914. this._groupCacheMaps = new BABYLON.StringDictionary();
  46915. this._patchHierarchy(this);
  46916. var enableInteraction = (settings.enableInteraction == null) ? true : settings.enableInteraction;
  46917. this._fitRenderingDevice = !settings.size;
  46918. if (!settings.size) {
  46919. settings.size = new BABYLON.Size(engine.getRenderWidth(), engine.getRenderHeight());
  46920. }
  46921. // Register scene dispose to also dispose the canvas when it'll happens
  46922. scene.onDisposeObservable.add(function (d, s) {
  46923. _this.dispose();
  46924. });
  46925. if (this._isScreenSpace) {
  46926. this._afterRenderObserver = this._scene.onAfterRenderObservable.add(function (d, s) {
  46927. _this._engine.clear(null, false, true, true);
  46928. _this._render();
  46929. });
  46930. }
  46931. else {
  46932. this._beforeRenderObserver = this._scene.onBeforeRenderObservable.add(function (d, s) {
  46933. _this._render();
  46934. });
  46935. }
  46936. this._supprtInstancedArray = this._engine.getCaps().instancedArrays !== null;
  46937. //this._supprtInstancedArray = false; // TODO REMOVE!!!
  46938. this._setupInteraction(enableInteraction);
  46939. }
  46940. Object.defineProperty(Canvas2D.prototype, "drawCallsOpaqueCounter", {
  46941. get: function () {
  46942. return this._drawCallsOpaqueCounter;
  46943. },
  46944. enumerable: true,
  46945. configurable: true
  46946. });
  46947. Object.defineProperty(Canvas2D.prototype, "drawCallsAlphaTestCounter", {
  46948. get: function () {
  46949. return this._drawCallsAlphaTestCounter;
  46950. },
  46951. enumerable: true,
  46952. configurable: true
  46953. });
  46954. Object.defineProperty(Canvas2D.prototype, "drawCallsTransparentCounter", {
  46955. get: function () {
  46956. return this._drawCallsTransparentCounter;
  46957. },
  46958. enumerable: true,
  46959. configurable: true
  46960. });
  46961. Object.defineProperty(Canvas2D.prototype, "groupRenderCounter", {
  46962. get: function () {
  46963. return this._groupRenderCounter;
  46964. },
  46965. enumerable: true,
  46966. configurable: true
  46967. });
  46968. Object.defineProperty(Canvas2D.prototype, "updateTransparentDataCounter", {
  46969. get: function () {
  46970. return this._updateTransparentDataCounter;
  46971. },
  46972. enumerable: true,
  46973. configurable: true
  46974. });
  46975. Object.defineProperty(Canvas2D.prototype, "cachedGroupRenderCounter", {
  46976. get: function () {
  46977. return this._cachedGroupRenderCounter;
  46978. },
  46979. enumerable: true,
  46980. configurable: true
  46981. });
  46982. Object.defineProperty(Canvas2D.prototype, "updateCachedStateCounter", {
  46983. get: function () {
  46984. return this._updateCachedStateCounter;
  46985. },
  46986. enumerable: true,
  46987. configurable: true
  46988. });
  46989. Object.defineProperty(Canvas2D.prototype, "updateLayoutCounter", {
  46990. get: function () {
  46991. return this._updateLayoutCounter;
  46992. },
  46993. enumerable: true,
  46994. configurable: true
  46995. });
  46996. Object.defineProperty(Canvas2D.prototype, "updatePositioningCounter", {
  46997. get: function () {
  46998. return this._updatePositioningCounter;
  46999. },
  47000. enumerable: true,
  47001. configurable: true
  47002. });
  47003. Object.defineProperty(Canvas2D.prototype, "updateLocalTransformCounter", {
  47004. get: function () {
  47005. return this._updateLocalTransformCounter;
  47006. },
  47007. enumerable: true,
  47008. configurable: true
  47009. });
  47010. Object.defineProperty(Canvas2D.prototype, "updateGlobalTransformCounter", {
  47011. get: function () {
  47012. return this._updateGlobalTransformCounter;
  47013. },
  47014. enumerable: true,
  47015. configurable: true
  47016. });
  47017. Object.defineProperty(Canvas2D.prototype, "boundingInfoRecomputeCounter", {
  47018. get: function () {
  47019. return this._boundingInfoRecomputeCounter;
  47020. },
  47021. enumerable: true,
  47022. configurable: true
  47023. });
  47024. Canvas2D.prototype._canvasPreInit = function (settings) {
  47025. var cachingStrategy = (settings.cachingStrategy == null) ? Canvas2D.CACHESTRATEGY_DONTCACHE : settings.cachingStrategy;
  47026. this._cachingStrategy = cachingStrategy;
  47027. this._isScreenSpace = (settings.isScreenSpace == null) ? true : settings.isScreenSpace;
  47028. };
  47029. Canvas2D.prototype._setupInteraction = function (enable) {
  47030. var _this = this;
  47031. // No change detection
  47032. if (enable === this._interactionEnabled) {
  47033. return;
  47034. }
  47035. // Set the new state
  47036. this._interactionEnabled = enable;
  47037. // ScreenSpace mode
  47038. if (this._isScreenSpace) {
  47039. // Disable interaction
  47040. if (!enable) {
  47041. if (this._scenePrePointerObserver) {
  47042. this.scene.onPrePointerObservable.remove(this._scenePrePointerObserver);
  47043. this._scenePrePointerObserver = null;
  47044. }
  47045. return;
  47046. }
  47047. // Enable Interaction
  47048. // Register the observable
  47049. this._scenePrePointerObserver = this.scene.onPrePointerObservable.add(function (e, s) {
  47050. if (_this.isVisible === false) {
  47051. return;
  47052. }
  47053. var hs = 1 / _this.engine.getHardwareScalingLevel();
  47054. var localPos = e.localPosition.multiplyByFloats(hs, hs);
  47055. _this._handlePointerEventForInteraction(e, localPos, s);
  47056. });
  47057. }
  47058. else {
  47059. var scene = this.scene;
  47060. if (enable) {
  47061. scene.constantlyUpdateMeshUnderPointer = true;
  47062. this._scenePointerObserver = scene.onPointerObservable.add(function (e, s) {
  47063. if (_this.isVisible === false) {
  47064. return;
  47065. }
  47066. if (e.pickInfo.hit && e.pickInfo.pickedMesh === _this._worldSpaceNode && _this.worldSpaceToNodeLocal) {
  47067. var localPos = _this.worldSpaceToNodeLocal(e.pickInfo.pickedPoint);
  47068. _this._handlePointerEventForInteraction(e, localPos, s);
  47069. }
  47070. });
  47071. }
  47072. else {
  47073. if (this._scenePointerObserver) {
  47074. this.scene.onPointerObservable.remove(this._scenePointerObserver);
  47075. this._scenePointerObserver = null;
  47076. }
  47077. }
  47078. }
  47079. };
  47080. /**
  47081. * Internal method, you should use the Prim2DBase version instead
  47082. */
  47083. Canvas2D.prototype._setPointerCapture = function (pointerId, primitive) {
  47084. if (this.isPointerCaptured(pointerId)) {
  47085. return false;
  47086. }
  47087. // Try to capture the pointer on the HTML side
  47088. try {
  47089. this.engine.getRenderingCanvas().setPointerCapture(pointerId);
  47090. }
  47091. catch (e) {
  47092. }
  47093. this._primPointerInfo.updateRelatedTarget(primitive, BABYLON.Vector2.Zero());
  47094. this._bubbleNotifyPrimPointerObserver(primitive, BABYLON.PrimitivePointerInfo.PointerGotCapture, null);
  47095. this._capturedPointers.add(pointerId.toString(), primitive);
  47096. return true;
  47097. };
  47098. /**
  47099. * Internal method, you should use the Prim2DBase version instead
  47100. */
  47101. Canvas2D.prototype._releasePointerCapture = function (pointerId, primitive) {
  47102. if (this._capturedPointers.get(pointerId.toString()) !== primitive) {
  47103. return false;
  47104. }
  47105. // Try to release the pointer on the HTML side
  47106. try {
  47107. this.engine.getRenderingCanvas().releasePointerCapture(pointerId);
  47108. }
  47109. catch (e) {
  47110. }
  47111. this._primPointerInfo.updateRelatedTarget(primitive, BABYLON.Vector2.Zero());
  47112. this._bubbleNotifyPrimPointerObserver(primitive, BABYLON.PrimitivePointerInfo.PointerLostCapture, null);
  47113. this._capturedPointers.remove(pointerId.toString());
  47114. return true;
  47115. };
  47116. /**
  47117. * Determine if the given pointer is captured or not
  47118. * @param pointerId the Id of the pointer
  47119. * @return true if it's captured, false otherwise
  47120. */
  47121. Canvas2D.prototype.isPointerCaptured = function (pointerId) {
  47122. return this._capturedPointers.contains(pointerId.toString());
  47123. };
  47124. Canvas2D.prototype.getCapturedPrimitive = function (pointerId) {
  47125. // Avoid unnecessary lookup
  47126. if (this._capturedPointers.count === 0) {
  47127. return null;
  47128. }
  47129. return this._capturedPointers.get(pointerId.toString());
  47130. };
  47131. Canvas2D.prototype._handlePointerEventForInteraction = function (eventData, localPosition, eventState) {
  47132. // Dispose check
  47133. if (this.isDisposed) {
  47134. return;
  47135. }
  47136. // Update the this._primPointerInfo structure we'll send to observers using the PointerEvent data
  47137. this._updatePointerInfo(eventData, localPosition);
  47138. var capturedPrim = this.getCapturedPrimitive(this._primPointerInfo.pointerId);
  47139. // 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.
  47140. // 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.
  47141. this._updateIntersectionList(this._primPointerInfo.canvasPointerPos, capturedPrim !== null);
  47142. // 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
  47143. this._updateOverStatus();
  47144. // Check if we have nothing to raise
  47145. if (!this._actualOverPrimitive && !capturedPrim) {
  47146. return;
  47147. }
  47148. // Update the relatedTarget info with the over primitive or the captured one (if any)
  47149. var targetPrim = capturedPrim || this._actualOverPrimitive.prim;
  47150. var targetPointerPos = capturedPrim ? this._primPointerInfo.canvasPointerPos.subtract(new BABYLON.Vector2(targetPrim.globalTransform.m[12], targetPrim.globalTransform.m[13])) : this._actualOverPrimitive.intersectionLocation;
  47151. this._primPointerInfo.updateRelatedTarget(targetPrim, targetPointerPos);
  47152. // Analyze the pointer event type and fire proper events on the primitive
  47153. if (eventData.type === BABYLON.PointerEventTypes.POINTERWHEEL) {
  47154. this._bubbleNotifyPrimPointerObserver(targetPrim, BABYLON.PrimitivePointerInfo.PointerMouseWheel, eventData.event);
  47155. }
  47156. else if (eventData.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  47157. this._bubbleNotifyPrimPointerObserver(targetPrim, BABYLON.PrimitivePointerInfo.PointerMove, eventData.event);
  47158. }
  47159. else if (eventData.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  47160. this._bubbleNotifyPrimPointerObserver(targetPrim, BABYLON.PrimitivePointerInfo.PointerDown, eventData.event);
  47161. }
  47162. else if (eventData.type === BABYLON.PointerEventTypes.POINTERUP) {
  47163. this._bubbleNotifyPrimPointerObserver(targetPrim, BABYLON.PrimitivePointerInfo.PointerUp, eventData.event);
  47164. }
  47165. };
  47166. Canvas2D.prototype._updatePointerInfo = function (eventData, localPosition) {
  47167. var pii = this._primPointerInfo;
  47168. if (!pii.canvasPointerPos) {
  47169. pii.canvasPointerPos = BABYLON.Vector2.Zero();
  47170. }
  47171. var camera = this._scene.cameraToUseForPointers || this._scene.activeCamera;
  47172. var engine = this._scene.getEngine();
  47173. if (this._isScreenSpace) {
  47174. var cameraViewport = camera.viewport;
  47175. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  47176. // Moving coordinates to local viewport world
  47177. var x = localPosition.x - viewport.x;
  47178. var y = localPosition.y - viewport.y;
  47179. pii.canvasPointerPos.x = x - this.actualPosition.x;
  47180. pii.canvasPointerPos.y = engine.getRenderHeight() - y - this.actualPosition.y;
  47181. }
  47182. else {
  47183. pii.canvasPointerPos.x = localPosition.x;
  47184. pii.canvasPointerPos.y = localPosition.y;
  47185. }
  47186. pii.mouseWheelDelta = 0;
  47187. if (eventData.type === BABYLON.PointerEventTypes.POINTERWHEEL) {
  47188. var event = eventData.event;
  47189. if (event.wheelDelta) {
  47190. pii.mouseWheelDelta = event.wheelDelta / (BABYLON.PrimitivePointerInfo.MouseWheelPrecision * 40);
  47191. }
  47192. else if (event.detail) {
  47193. pii.mouseWheelDelta = -event.detail / BABYLON.PrimitivePointerInfo.MouseWheelPrecision;
  47194. }
  47195. }
  47196. else {
  47197. var pe = eventData.event;
  47198. pii.ctrlKey = pe.ctrlKey;
  47199. pii.altKey = pe.altKey;
  47200. pii.shiftKey = pe.shiftKey;
  47201. pii.metaKey = pe.metaKey;
  47202. pii.button = pe.button;
  47203. pii.buttons = pe.buttons;
  47204. pii.pointerId = pe.pointerId;
  47205. pii.width = pe.width;
  47206. pii.height = pe.height;
  47207. pii.presssure = pe.pressure;
  47208. pii.tilt.x = pe.tiltX;
  47209. pii.tilt.y = pe.tiltY;
  47210. pii.isCaptured = this.getCapturedPrimitive(pe.pointerId) !== null;
  47211. }
  47212. };
  47213. Canvas2D.prototype._updateIntersectionList = function (mouseLocalPos, isCapture) {
  47214. if (this.scene.getRenderId() === this._intersectionRenderId) {
  47215. return;
  47216. }
  47217. // 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
  47218. if (!this._globalTransform) {
  47219. this.updateCachedStates(true);
  47220. }
  47221. var ii = Canvas2D._interInfo;
  47222. ii.pickPosition.x = mouseLocalPos.x;
  47223. ii.pickPosition.y = mouseLocalPos.y;
  47224. ii.findFirstOnly = false;
  47225. // Fast rejection: test if the mouse pointer is outside the canvas's bounding Info
  47226. if (!isCapture && !this.levelBoundingInfo.doesIntersect(ii.pickPosition)) {
  47227. this._previousIntersectionList = this._actualIntersectionList;
  47228. this._actualIntersectionList = null;
  47229. this._previousOverPrimitive = this._actualOverPrimitive;
  47230. this._actualOverPrimitive = null;
  47231. return;
  47232. }
  47233. this.intersect(ii);
  47234. this._previousIntersectionList = this._actualIntersectionList;
  47235. this._actualIntersectionList = ii.intersectedPrimitives;
  47236. this._previousOverPrimitive = this._actualOverPrimitive;
  47237. this._actualOverPrimitive = ii.topMostIntersectedPrimitive;
  47238. this._intersectionRenderId = this.scene.getRenderId();
  47239. };
  47240. // Based on the previousIntersectionList and the actualInstersectionList we can determined which primitives are being hover state or loosing it
  47241. Canvas2D.prototype._updateOverStatus = function () {
  47242. if ((this.scene.getRenderId() === this._hoverStatusRenderId) || !this._previousIntersectionList || !this._actualIntersectionList) {
  47243. return;
  47244. }
  47245. // Detect a change of over
  47246. var prevPrim = this._previousOverPrimitive ? this._previousOverPrimitive.prim : null;
  47247. var actualPrim = this._actualOverPrimitive ? this._actualOverPrimitive.prim : null;
  47248. if (prevPrim !== actualPrim) {
  47249. // Detect if the current pointer is captured, only fire event if they belong to the capture primitive
  47250. var capturedPrim = this.getCapturedPrimitive(this._primPointerInfo.pointerId);
  47251. // Notify the previous "over" prim that the pointer is no longer over it
  47252. if ((capturedPrim && capturedPrim === prevPrim) || (!capturedPrim && prevPrim)) {
  47253. this._primPointerInfo.updateRelatedTarget(prevPrim, this._previousOverPrimitive.intersectionLocation);
  47254. this._bubbleNotifyPrimPointerObserver(prevPrim, BABYLON.PrimitivePointerInfo.PointerOut, null);
  47255. }
  47256. // Notify the new "over" prim that the pointer is over it
  47257. if ((capturedPrim && capturedPrim === actualPrim) || (!capturedPrim && actualPrim)) {
  47258. this._primPointerInfo.updateRelatedTarget(actualPrim, this._actualOverPrimitive.intersectionLocation);
  47259. this._bubbleNotifyPrimPointerObserver(actualPrim, BABYLON.PrimitivePointerInfo.PointerOver, null);
  47260. }
  47261. }
  47262. this._hoverStatusRenderId = this.scene.getRenderId();
  47263. };
  47264. Canvas2D.prototype._updatePrimPointerPos = function (prim) {
  47265. if (this._primPointerInfo.isCaptured) {
  47266. this._primPointerInfo.primitivePointerPos = this._primPointerInfo.relatedTargetPointerPos;
  47267. }
  47268. else {
  47269. for (var _i = 0, _a = this._actualIntersectionList; _i < _a.length; _i++) {
  47270. var pii = _a[_i];
  47271. if (pii.prim === prim) {
  47272. this._primPointerInfo.primitivePointerPos = pii.intersectionLocation;
  47273. return;
  47274. }
  47275. }
  47276. }
  47277. };
  47278. Canvas2D.prototype._debugExecObserver = function (prim, mask) {
  47279. if (!this._notifDebugMode) {
  47280. return;
  47281. }
  47282. var debug = "";
  47283. for (var i = 0; i < prim.hierarchyDepth; i++) {
  47284. debug += " ";
  47285. }
  47286. var pii = this._primPointerInfo;
  47287. 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();
  47288. console.log(debug);
  47289. };
  47290. Canvas2D.prototype._bubbleNotifyPrimPointerObserver = function (prim, mask, eventData) {
  47291. var ppi = this._primPointerInfo;
  47292. // In case of PointerOver/Out we will first notify the parent with PointerEnter/Leave
  47293. if ((mask & (BABYLON.PrimitivePointerInfo.PointerOver | BABYLON.PrimitivePointerInfo.PointerOut)) !== 0) {
  47294. this._notifParents(prim, mask);
  47295. }
  47296. var bubbleCancelled = false;
  47297. var cur = prim;
  47298. while (cur) {
  47299. // Only trigger the observers if the primitive is intersected (except for out)
  47300. if (!bubbleCancelled) {
  47301. this._updatePrimPointerPos(cur);
  47302. // Exec the observers
  47303. this._debugExecObserver(cur, mask);
  47304. cur._pointerEventObservable.notifyObservers(ppi, mask);
  47305. this._triggerActionManager(cur, ppi, mask, eventData);
  47306. // Bubble canceled? If we're not executing PointerOver or PointerOut, quit immediately
  47307. // If it's PointerOver/Out we have to trigger PointerEnter/Leave no matter what
  47308. if (ppi.cancelBubble) {
  47309. if ((mask & (BABYLON.PrimitivePointerInfo.PointerOver | BABYLON.PrimitivePointerInfo.PointerOut)) === 0) {
  47310. return;
  47311. }
  47312. // We're dealing with PointerOver/Out, let's keep looping to fire PointerEnter/Leave, but not Over/Out anymore
  47313. bubbleCancelled = true;
  47314. }
  47315. }
  47316. // If bubble is cancel we didn't update the Primitive Pointer Pos yet, let's do it
  47317. if (bubbleCancelled) {
  47318. this._updatePrimPointerPos(cur);
  47319. }
  47320. // Trigger a PointerEnter corresponding to the PointerOver
  47321. if (mask === BABYLON.PrimitivePointerInfo.PointerOver) {
  47322. this._debugExecObserver(cur, BABYLON.PrimitivePointerInfo.PointerEnter);
  47323. cur._pointerEventObservable.notifyObservers(ppi, BABYLON.PrimitivePointerInfo.PointerEnter);
  47324. }
  47325. else if (mask === BABYLON.PrimitivePointerInfo.PointerOut) {
  47326. this._debugExecObserver(cur, BABYLON.PrimitivePointerInfo.PointerLeave);
  47327. cur._pointerEventObservable.notifyObservers(ppi, BABYLON.PrimitivePointerInfo.PointerLeave);
  47328. }
  47329. // Loop to the parent
  47330. cur = cur.parent;
  47331. }
  47332. };
  47333. Canvas2D.prototype._triggerActionManager = function (prim, ppi, mask, eventData) {
  47334. var _this = this;
  47335. // 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
  47336. if (!this._globalTransform) {
  47337. this.updateCachedStates(true);
  47338. }
  47339. // Process Trigger related to PointerDown
  47340. if ((mask & BABYLON.PrimitivePointerInfo.PointerDown) !== 0) {
  47341. // On pointer down, record the current position and time to be able to trick PickTrigger and LongPressTrigger
  47342. this._pickStartingPosition = ppi.primitivePointerPos.clone();
  47343. this._pickStartingTime = new Date().getTime();
  47344. this._pickedDownPrim = null;
  47345. if (prim.actionManager) {
  47346. this._pickedDownPrim = prim;
  47347. if (prim.actionManager.hasPickTriggers) {
  47348. var actionEvent = BABYLON.ActionEvent.CreateNewFromPrimitive(prim, ppi.primitivePointerPos, eventData);
  47349. switch (eventData.button) {
  47350. case 0:
  47351. prim.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, actionEvent);
  47352. break;
  47353. case 1:
  47354. prim.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, actionEvent);
  47355. break;
  47356. case 2:
  47357. prim.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, actionEvent);
  47358. break;
  47359. }
  47360. prim.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, actionEvent);
  47361. }
  47362. if (prim.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  47363. window.setTimeout(function () {
  47364. var ppi = _this._primPointerInfo;
  47365. var capturedPrim = _this.getCapturedPrimitive(ppi.pointerId);
  47366. _this._updateIntersectionList(ppi.canvasPointerPos, capturedPrim !== null);
  47367. var ii = new BABYLON.IntersectInfo2D();
  47368. ii.pickPosition = ppi.canvasPointerPos.clone();
  47369. ii.findFirstOnly = false;
  47370. _this.intersect(ii);
  47371. if (ii.isPrimIntersected(prim) !== null) {
  47372. if (prim.actionManager) {
  47373. 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)) {
  47374. _this._pickStartingTime = 0;
  47375. prim.actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNewFromPrimitive(prim, ppi.primitivePointerPos, eventData));
  47376. }
  47377. }
  47378. }
  47379. }, BABYLON.ActionManager.LongPressDelay);
  47380. }
  47381. }
  47382. }
  47383. else if ((mask & BABYLON.PrimitivePointerInfo.PointerUp) !== 0) {
  47384. this._pickStartingTime = 0;
  47385. var actionEvent = BABYLON.ActionEvent.CreateNewFromPrimitive(prim, ppi.primitivePointerPos, eventData);
  47386. if (prim.actionManager) {
  47387. // OnPickUpTrigger
  47388. prim.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, actionEvent);
  47389. // OnPickTrigger
  47390. if (Math.abs(this._pickStartingPosition.x - ppi.canvasPointerPos.x) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(this._pickStartingPosition.y - ppi.canvasPointerPos.y) < BABYLON.ActionManager.DragMovementThreshold) {
  47391. prim.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, actionEvent);
  47392. }
  47393. }
  47394. // OnPickOutTrigger
  47395. if (this._pickedDownPrim && this._pickedDownPrim.actionManager && (this._pickedDownPrim !== prim)) {
  47396. this._pickedDownPrim.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, actionEvent);
  47397. }
  47398. }
  47399. else if ((mask & BABYLON.PrimitivePointerInfo.PointerOver) !== 0) {
  47400. if (prim.actionManager) {
  47401. var actionEvent = BABYLON.ActionEvent.CreateNewFromPrimitive(prim, ppi.primitivePointerPos, eventData);
  47402. prim.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, actionEvent);
  47403. }
  47404. }
  47405. else if ((mask & BABYLON.PrimitivePointerInfo.PointerOut) !== 0) {
  47406. if (prim.actionManager) {
  47407. var actionEvent = BABYLON.ActionEvent.CreateNewFromPrimitive(prim, ppi.primitivePointerPos, eventData);
  47408. prim.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, actionEvent);
  47409. }
  47410. }
  47411. };
  47412. Canvas2D.prototype._notifParents = function (prim, mask) {
  47413. var pii = this._primPointerInfo;
  47414. var curPrim = this;
  47415. while (curPrim) {
  47416. this._updatePrimPointerPos(curPrim);
  47417. // Fire the proper notification
  47418. if (mask === BABYLON.PrimitivePointerInfo.PointerOver) {
  47419. this._debugExecObserver(curPrim, BABYLON.PrimitivePointerInfo.PointerEnter);
  47420. curPrim._pointerEventObservable.notifyObservers(pii, BABYLON.PrimitivePointerInfo.PointerEnter);
  47421. }
  47422. else if (mask === BABYLON.PrimitivePointerInfo.PointerOut) {
  47423. this._debugExecObserver(curPrim, BABYLON.PrimitivePointerInfo.PointerLeave);
  47424. curPrim._pointerEventObservable.notifyObservers(pii, BABYLON.PrimitivePointerInfo.PointerLeave);
  47425. }
  47426. curPrim = curPrim.parent;
  47427. }
  47428. };
  47429. /**
  47430. * Don't forget to call the dispose method when you're done with the Canvas instance.
  47431. * But don't worry, if you dispose its scene, the canvas will be automatically disposed too.
  47432. */
  47433. Canvas2D.prototype.dispose = function () {
  47434. if (!_super.prototype.dispose.call(this)) {
  47435. return false;
  47436. }
  47437. if (this._profilingCanvas) {
  47438. this._profilingCanvas.dispose();
  47439. this._profilingCanvas = null;
  47440. }
  47441. if (this.interactionEnabled) {
  47442. this._setupInteraction(false);
  47443. }
  47444. if (this._beforeRenderObserver) {
  47445. this._scene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  47446. this._beforeRenderObserver = null;
  47447. }
  47448. if (this._afterRenderObserver) {
  47449. this._scene.onAfterRenderObservable.remove(this._afterRenderObserver);
  47450. this._afterRenderObserver = null;
  47451. }
  47452. if (this._groupCacheMaps) {
  47453. this._groupCacheMaps.forEach(function (k, m) { return m.forEach(function (e) { return e.dispose(); }); });
  47454. this._groupCacheMaps = null;
  47455. }
  47456. };
  47457. Object.defineProperty(Canvas2D.prototype, "scene", {
  47458. /**
  47459. * Accessor to the Scene that owns the Canvas
  47460. * @returns The instance of the Scene object
  47461. */
  47462. get: function () {
  47463. return this._scene;
  47464. },
  47465. enumerable: true,
  47466. configurable: true
  47467. });
  47468. Object.defineProperty(Canvas2D.prototype, "engine", {
  47469. /**
  47470. * Accessor to the Engine that drives the Scene used by this Canvas
  47471. * @returns The instance of the Engine object
  47472. */
  47473. get: function () {
  47474. return this._engine;
  47475. },
  47476. enumerable: true,
  47477. configurable: true
  47478. });
  47479. Object.defineProperty(Canvas2D.prototype, "cachingStrategy", {
  47480. /**
  47481. * Accessor of the Caching Strategy used by this Canvas.
  47482. * See Canvas2D.CACHESTRATEGY_xxxx static members for more information
  47483. * @returns the value corresponding to the used strategy.
  47484. */
  47485. get: function () {
  47486. return this._cachingStrategy;
  47487. },
  47488. enumerable: true,
  47489. configurable: true
  47490. });
  47491. Object.defineProperty(Canvas2D.prototype, "isScreenSpace", {
  47492. /**
  47493. * Return true if the Canvas is a Screen Space one, false if it's a World Space one.
  47494. * @returns {}
  47495. */
  47496. get: function () {
  47497. return this._isScreenSpace;
  47498. },
  47499. enumerable: true,
  47500. configurable: true
  47501. });
  47502. Object.defineProperty(Canvas2D.prototype, "worldSpaceCanvasNode", {
  47503. /**
  47504. * Only valid for World Space Canvas, returns the scene node that displays the canvas
  47505. */
  47506. get: function () {
  47507. return this._worldSpaceNode;
  47508. },
  47509. set: function (val) {
  47510. this._worldSpaceNode = val;
  47511. },
  47512. enumerable: true,
  47513. configurable: true
  47514. });
  47515. Object.defineProperty(Canvas2D.prototype, "supportInstancedArray", {
  47516. /**
  47517. * Check if the WebGL Instanced Array extension is supported or not
  47518. */
  47519. get: function () {
  47520. return this._supprtInstancedArray;
  47521. },
  47522. enumerable: true,
  47523. configurable: true
  47524. });
  47525. Object.defineProperty(Canvas2D.prototype, "backgroundFill", {
  47526. /**
  47527. * Property that defines the fill object used to draw the background of the Canvas.
  47528. * Note that Canvas with a Caching Strategy of
  47529. * @returns If the background is not set, null will be returned, otherwise a valid fill object is returned.
  47530. */
  47531. get: function () {
  47532. if (!this._background || !this._background.isVisible) {
  47533. return null;
  47534. }
  47535. return this._background.fill;
  47536. },
  47537. set: function (value) {
  47538. this.checkBackgroundAvailability();
  47539. if (value === this._background.fill) {
  47540. return;
  47541. }
  47542. this._background.fill = value;
  47543. this._background.levelVisible = true;
  47544. },
  47545. enumerable: true,
  47546. configurable: true
  47547. });
  47548. Object.defineProperty(Canvas2D.prototype, "backgroundBorder", {
  47549. /**
  47550. * Property that defines the border object used to draw the background of the Canvas.
  47551. * @returns If the background is not set, null will be returned, otherwise a valid border object is returned.
  47552. */
  47553. get: function () {
  47554. if (!this._background || !this._background.isVisible) {
  47555. return null;
  47556. }
  47557. return this._background.border;
  47558. },
  47559. set: function (value) {
  47560. this.checkBackgroundAvailability();
  47561. if (value === this._background.border) {
  47562. return;
  47563. }
  47564. this._background.border = value;
  47565. this._background.levelVisible = true;
  47566. },
  47567. enumerable: true,
  47568. configurable: true
  47569. });
  47570. Object.defineProperty(Canvas2D.prototype, "backgroundBorderThickness", {
  47571. /**
  47572. * Property that defines the thickness of the border object used to draw the background of the Canvas.
  47573. * @returns If the background is not set, null will be returned, otherwise a valid number matching the thickness is returned.
  47574. */
  47575. get: function () {
  47576. if (!this._background || !this._background.isVisible) {
  47577. return null;
  47578. }
  47579. return this._background.borderThickness;
  47580. },
  47581. set: function (value) {
  47582. this.checkBackgroundAvailability();
  47583. if (value === this._background.borderThickness) {
  47584. return;
  47585. }
  47586. this._background.borderThickness = value;
  47587. },
  47588. enumerable: true,
  47589. configurable: true
  47590. });
  47591. Object.defineProperty(Canvas2D.prototype, "backgroundRoundRadius", {
  47592. /**
  47593. * You can set the roundRadius of the background
  47594. * @returns The current roundRadius
  47595. */
  47596. get: function () {
  47597. if (!this._background || !this._background.isVisible) {
  47598. return null;
  47599. }
  47600. return this._background.roundRadius;
  47601. },
  47602. set: function (value) {
  47603. this.checkBackgroundAvailability();
  47604. if (value === this._background.roundRadius) {
  47605. return;
  47606. }
  47607. this._background.roundRadius = value;
  47608. this._background.levelVisible = true;
  47609. },
  47610. enumerable: true,
  47611. configurable: true
  47612. });
  47613. Object.defineProperty(Canvas2D.prototype, "interactionEnabled", {
  47614. /**
  47615. * Enable/Disable interaction for this Canvas
  47616. * When enabled the Prim2DBase.pointerEventObservable property will notified when appropriate events occur
  47617. */
  47618. get: function () {
  47619. return this._interactionEnabled;
  47620. },
  47621. set: function (enable) {
  47622. this._setupInteraction(enable);
  47623. },
  47624. enumerable: true,
  47625. configurable: true
  47626. });
  47627. Object.defineProperty(Canvas2D.prototype, "_engineData", {
  47628. /**
  47629. * Access the babylon.js' engine bound data, do not invoke this method, it's for internal purpose only
  47630. * @returns {}
  47631. */
  47632. get: function () {
  47633. return this.__engineData;
  47634. },
  47635. enumerable: true,
  47636. configurable: true
  47637. });
  47638. Canvas2D.prototype.createCanvasProfileInfoCanvas = function () {
  47639. if (this._profilingCanvas) {
  47640. return this._profilingCanvas;
  47641. }
  47642. var canvas = new ScreenSpaceCanvas2D(this.scene, {
  47643. id: "ProfileInfoCanvas", cachingStrategy: Canvas2D.CACHESTRATEGY_DONTCACHE, children: [
  47644. new BABYLON.Rectangle2D({
  47645. id: "ProfileBorder", border: "#FFFFFFFF", borderThickness: 2, roundRadius: 5, fill: "#C04040C0", marginAlignment: "h: left, v: top", margin: "10", padding: "10", children: [
  47646. new BABYLON.Text2D("Stats", { id: "ProfileInfoText", marginAlignment: "h: left, v: top", fontName: "10pt Lucida Console" })
  47647. ]
  47648. })
  47649. ]
  47650. });
  47651. this._profileInfoText = canvas.findById("ProfileInfoText");
  47652. this._profilingCanvas = canvas;
  47653. return canvas;
  47654. };
  47655. Canvas2D.prototype.checkBackgroundAvailability = function () {
  47656. if (this._cachingStrategy === Canvas2D.CACHESTRATEGY_TOPLEVELGROUPS) {
  47657. throw Error("Can't use Canvas Background with the caching strategy TOPLEVELGROUPS");
  47658. }
  47659. };
  47660. Canvas2D.prototype._initPerfMetrics = function () {
  47661. this._drawCallsOpaqueCounter.fetchNewFrame();
  47662. this._drawCallsAlphaTestCounter.fetchNewFrame();
  47663. this._drawCallsTransparentCounter.fetchNewFrame();
  47664. this._groupRenderCounter.fetchNewFrame();
  47665. this._updateTransparentDataCounter.fetchNewFrame();
  47666. this._cachedGroupRenderCounter.fetchNewFrame();
  47667. this._updateCachedStateCounter.fetchNewFrame();
  47668. this._updateLayoutCounter.fetchNewFrame();
  47669. this._updatePositioningCounter.fetchNewFrame();
  47670. this._updateLocalTransformCounter.fetchNewFrame();
  47671. this._updateGlobalTransformCounter.fetchNewFrame();
  47672. this._boundingInfoRecomputeCounter.fetchNewFrame();
  47673. };
  47674. Canvas2D.prototype._fetchPerfMetrics = function () {
  47675. this._drawCallsOpaqueCounter.addCount(0, true);
  47676. this._drawCallsAlphaTestCounter.addCount(0, true);
  47677. this._drawCallsTransparentCounter.addCount(0, true);
  47678. this._groupRenderCounter.addCount(0, true);
  47679. this._updateTransparentDataCounter.addCount(0, true);
  47680. this._cachedGroupRenderCounter.addCount(0, true);
  47681. this._updateCachedStateCounter.addCount(0, true);
  47682. this._updateLayoutCounter.addCount(0, true);
  47683. this._updatePositioningCounter.addCount(0, true);
  47684. this._updateLocalTransformCounter.addCount(0, true);
  47685. this._updateGlobalTransformCounter.addCount(0, true);
  47686. this._boundingInfoRecomputeCounter.addCount(0, true);
  47687. };
  47688. Canvas2D.prototype._updateProfileCanvas = function () {
  47689. if (this._profileInfoText == null) {
  47690. return;
  47691. }
  47692. var format = function (v) { return (Math.round(v * 100) / 100).toString(); };
  47693. var p = "Draw Calls:\n" +
  47694. (" - Opaque: " + format(this.drawCallsOpaqueCounter.current) + ", (avg:" + format(this.drawCallsOpaqueCounter.lastSecAverage) + ", t:" + format(this.drawCallsOpaqueCounter.total) + ")\n") +
  47695. (" - AlphaTest: " + format(this.drawCallsAlphaTestCounter.current) + ", (avg:" + format(this.drawCallsAlphaTestCounter.lastSecAverage) + ", t:" + format(this.drawCallsAlphaTestCounter.total) + ")\n") +
  47696. (" - Transparent: " + format(this.drawCallsTransparentCounter.current) + ", (avg:" + format(this.drawCallsTransparentCounter.lastSecAverage) + ", t:" + format(this.drawCallsTransparentCounter.total) + ")\n") +
  47697. ("Group Render: " + this.groupRenderCounter.current + ", (avg:" + format(this.groupRenderCounter.lastSecAverage) + ", t:" + format(this.groupRenderCounter.total) + ")\n") +
  47698. ("Update Transparent Data: " + this.updateTransparentDataCounter.current + ", (avg:" + format(this.updateTransparentDataCounter.lastSecAverage) + ", t:" + format(this.updateTransparentDataCounter.total) + ")\n") +
  47699. ("Cached Group Render: " + this.cachedGroupRenderCounter.current + ", (avg:" + format(this.cachedGroupRenderCounter.lastSecAverage) + ", t:" + format(this.cachedGroupRenderCounter.total) + ")\n") +
  47700. ("Update Cached States: " + this.updateCachedStateCounter.current + ", (avg:" + format(this.updateCachedStateCounter.lastSecAverage) + ", t:" + format(this.updateCachedStateCounter.total) + ")\n") +
  47701. (" - Update Layout: " + this.updateLayoutCounter.current + ", (avg:" + format(this.updateLayoutCounter.lastSecAverage) + ", t:" + format(this.updateLayoutCounter.total) + ")\n") +
  47702. (" - Update Positioning: " + this.updatePositioningCounter.current + ", (avg:" + format(this.updatePositioningCounter.lastSecAverage) + ", t:" + format(this.updatePositioningCounter.total) + ")\n") +
  47703. (" - Update Local Trans: " + this.updateLocalTransformCounter.current + ", (avg:" + format(this.updateLocalTransformCounter.lastSecAverage) + ", t:" + format(this.updateLocalTransformCounter.total) + ")\n") +
  47704. (" - Update Global Trans: " + this.updateGlobalTransformCounter.current + ", (avg:" + format(this.updateGlobalTransformCounter.lastSecAverage) + ", t:" + format(this.updateGlobalTransformCounter.total) + ")\n") +
  47705. (" - BoundingInfo Recompute: " + this.boundingInfoRecomputeCounter.current + ", (avg:" + format(this.boundingInfoRecomputeCounter.lastSecAverage) + ", t:" + format(this.boundingInfoRecomputeCounter.total) + ")\n");
  47706. this._profileInfoText.text = p;
  47707. };
  47708. Canvas2D.prototype._addDrawCallCount = function (count, renderMode) {
  47709. switch (renderMode) {
  47710. case BABYLON.Render2DContext.RenderModeOpaque:
  47711. this._drawCallsOpaqueCounter.addCount(count, false);
  47712. return;
  47713. case BABYLON.Render2DContext.RenderModeAlphaTest:
  47714. this._drawCallsAlphaTestCounter.addCount(count, false);
  47715. return;
  47716. case BABYLON.Render2DContext.RenderModeTransparent:
  47717. this._drawCallsTransparentCounter.addCount(count, false);
  47718. return;
  47719. }
  47720. };
  47721. Canvas2D.prototype._addGroupRenderCount = function (count) {
  47722. this._groupRenderCounter.addCount(count, false);
  47723. };
  47724. Canvas2D.prototype._addUpdateTransparentDataCount = function (count) {
  47725. this._updateTransparentDataCounter.addCount(count, false);
  47726. };
  47727. Canvas2D.prototype.addCachedGroupRenderCounter = function (count) {
  47728. this._cachedGroupRenderCounter.addCount(count, false);
  47729. };
  47730. Canvas2D.prototype.addUpdateCachedStateCounter = function (count) {
  47731. this._updateCachedStateCounter.addCount(count, false);
  47732. };
  47733. Canvas2D.prototype.addUpdateLayoutCounter = function (count) {
  47734. this._updateLayoutCounter.addCount(count, false);
  47735. };
  47736. Canvas2D.prototype.addUpdatePositioningCounter = function (count) {
  47737. this._updatePositioningCounter.addCount(count, false);
  47738. };
  47739. Canvas2D.prototype.addupdateLocalTransformCounter = function (count) {
  47740. this._updateLocalTransformCounter.addCount(count, false);
  47741. };
  47742. Canvas2D.prototype.addUpdateGlobalTransformCounter = function (count) {
  47743. this._updateGlobalTransformCounter.addCount(count, false);
  47744. };
  47745. Canvas2D.prototype._updateTrackedNodes = function () {
  47746. var cam = this.scene.cameraToUseForPointers || this.scene.activeCamera;
  47747. cam.getViewMatrix().multiplyToRef(cam.getProjectionMatrix(), Canvas2D._m);
  47748. var rh = this.engine.getRenderHeight();
  47749. var v = cam.viewport.toGlobal(this.engine.getRenderWidth(), rh);
  47750. for (var _i = 0, _a = this._trackedGroups; _i < _a.length; _i++) {
  47751. var group = _a[_i];
  47752. if (group.isDisposed || !group.isVisible) {
  47753. continue;
  47754. }
  47755. var node = group.trackedNode;
  47756. var worldMtx = node.getWorldMatrix();
  47757. var proj = BABYLON.Vector3.Project(Canvas2D._v, worldMtx, Canvas2D._m, v);
  47758. group.x = Math.round(proj.x);
  47759. group.y = Math.round(rh - proj.y);
  47760. }
  47761. };
  47762. /**
  47763. * Call this method change you want to have layout related data computed and up to date (layout area, primitive area, local/global transformation matrices)
  47764. */
  47765. Canvas2D.prototype.updateCanvasLayout = function (forceRecompute) {
  47766. this._updateCanvasState(forceRecompute);
  47767. };
  47768. Canvas2D.prototype._updateAdaptiveSizeWorldCanvas = function () {
  47769. if (this._globalTransformStep < 2) {
  47770. return;
  47771. }
  47772. var n = this.worldSpaceCanvasNode;
  47773. var bi = n.getBoundingInfo().boundingBox;
  47774. var v = bi.vectorsWorld;
  47775. var cam = this.scene.cameraToUseForPointers || this.scene.activeCamera;
  47776. cam.getViewMatrix().multiplyToRef(cam.getProjectionMatrix(), Canvas2D._m);
  47777. var vp = cam.viewport.toGlobal(this.engine.getRenderWidth(), this.engine.getRenderHeight());
  47778. var projPoints = new Array(4);
  47779. for (var i = 0; i < 4; i++) {
  47780. projPoints[i] = BABYLON.Vector3.Project(v[i], Canvas2D._mI, Canvas2D._m, vp);
  47781. }
  47782. var left = projPoints[3].subtract(projPoints[0]).length();
  47783. var top = projPoints[3].subtract(projPoints[1]).length();
  47784. var right = projPoints[1].subtract(projPoints[2]).length();
  47785. var bottom = projPoints[2].subtract(projPoints[0]).length();
  47786. var w = Math.round(Math.max(top, bottom));
  47787. var h = Math.round(Math.max(right, left));
  47788. var isW = w > h;
  47789. // Basically if it's under 256 we use 256, otherwise we take the biggest power of 2
  47790. var edge = Math.max(w, h);
  47791. if (edge < 256) {
  47792. edge = 256;
  47793. }
  47794. else {
  47795. edge = Math.pow(2, Math.ceil(Math.log(edge) / Math.log(2)));
  47796. }
  47797. // Clip values if needed
  47798. edge = Math.min(edge, this._maxAdaptiveWorldSpaceCanvasSize);
  47799. var newScale = edge / ((isW) ? this.size.width : this.size.height);
  47800. if (newScale !== this.scale) {
  47801. var scale = newScale;
  47802. // console.log(`New adaptive scale for Canvas ${this.id}, w: ${w}, h: ${h}, scale: ${scale}, edge: ${edge}, isW: ${isW}`);
  47803. this._setRenderingScale(scale);
  47804. }
  47805. };
  47806. Canvas2D.prototype._updateCanvasState = function (forceRecompute) {
  47807. // Check if the update has already been made for this render Frame
  47808. if (!forceRecompute && this.scene.getRenderId() === this._updateRenderId) {
  47809. return;
  47810. }
  47811. // Detect a change of rendering size
  47812. var renderingSizeChanged = false;
  47813. var newWidth = this.engine.getRenderWidth();
  47814. if (newWidth !== this._renderingSize.width) {
  47815. renderingSizeChanged = true;
  47816. }
  47817. this._renderingSize.width = newWidth;
  47818. var newHeight = this.engine.getRenderHeight();
  47819. if (newHeight !== this._renderingSize.height) {
  47820. renderingSizeChanged = true;
  47821. }
  47822. this._renderingSize.height = newHeight;
  47823. // If the canvas fit the rendering size and it changed, update
  47824. if (renderingSizeChanged && this._fitRenderingDevice) {
  47825. this.size = this._renderingSize;
  47826. if (this._background) {
  47827. this._background.size = this.size;
  47828. }
  47829. // Dirty the Layout at the Canvas level to recompute as the size changed
  47830. this._setLayoutDirty();
  47831. }
  47832. var context = new BABYLON.PrepareRender2DContext();
  47833. ++this._globalTransformProcessStep;
  47834. this.updateCachedStates(false);
  47835. this._prepareGroupRender(context);
  47836. this._updateRenderId = this.scene.getRenderId();
  47837. };
  47838. /**
  47839. * Method that renders the Canvas, you should not invoke
  47840. */
  47841. Canvas2D.prototype._render = function () {
  47842. this._initPerfMetrics();
  47843. this._updateTrackedNodes();
  47844. this._updateCanvasState(false);
  47845. if (!this._isScreenSpace) {
  47846. this._updateAdaptiveSizeWorldCanvas();
  47847. }
  47848. this._updateCanvasState(false);
  47849. if (this._primPointerInfo.canvasPointerPos) {
  47850. this._updateIntersectionList(this._primPointerInfo.canvasPointerPos, false);
  47851. this._updateOverStatus(); // TODO this._primPointerInfo may not be up to date!
  47852. }
  47853. this.engine.setState(false);
  47854. this._groupRender();
  47855. if (!this._isScreenSpace) {
  47856. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagWorldCacheChanged)) {
  47857. this.worldSpaceCacheChanged();
  47858. this._clearFlags(BABYLON.SmartPropertyPrim.flagWorldCacheChanged);
  47859. }
  47860. }
  47861. // If the canvas is cached at canvas level, we must manually render the sprite that will display its content
  47862. if (this._cachingStrategy === Canvas2D.CACHESTRATEGY_CANVAS && this._cachedCanvasGroup) {
  47863. this._cachedCanvasGroup._renderCachedCanvas();
  47864. }
  47865. this._fetchPerfMetrics();
  47866. this._updateProfileCanvas();
  47867. };
  47868. /**
  47869. * Internal method that allocate a cache for the given group.
  47870. * Caching is made using a collection of MapTexture where many groups have their bitmap cache stored inside.
  47871. * @param group The group to allocate the cache of.
  47872. * @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.
  47873. */
  47874. Canvas2D.prototype._allocateGroupCache = function (group, parent, minSize, useMipMap, anisotropicLevel) {
  47875. if (useMipMap === void 0) { useMipMap = false; }
  47876. if (anisotropicLevel === void 0) { anisotropicLevel = 1; }
  47877. var key = (useMipMap ? "MipMap" : "NoMipMap") + "_" + anisotropicLevel;
  47878. // Determine size
  47879. var size = group.actualSize;
  47880. size = new BABYLON.Size(Math.ceil(size.width), Math.ceil(size.height));
  47881. if (minSize) {
  47882. size.width = Math.max(minSize.width, size.width);
  47883. size.height = Math.max(minSize.height, size.height);
  47884. }
  47885. var mapArray = this._groupCacheMaps.getOrAddWithFactory(key, function () { return new Array(); });
  47886. // Try to find a spot in one of the cached texture
  47887. var res = null;
  47888. var map;
  47889. for (var _i = 0; _i < mapArray.length; _i++) {
  47890. var _map = mapArray[_i];
  47891. map = _map;
  47892. var node = map.allocateRect(size);
  47893. if (node) {
  47894. res = { node: node, texture: map };
  47895. break;
  47896. }
  47897. }
  47898. // Couldn't find a map that could fit the rect, create a new map for it
  47899. if (!res) {
  47900. var mapSize = new BABYLON.Size(Canvas2D._groupTextureCacheSize, Canvas2D._groupTextureCacheSize);
  47901. // Check if the predefined size would fit, other create a custom size using the nearest bigger power of 2
  47902. if (size.width > mapSize.width || size.height > mapSize.height) {
  47903. mapSize.width = Math.pow(2, Math.ceil(Math.log(size.width) / Math.log(2)));
  47904. mapSize.height = Math.pow(2, Math.ceil(Math.log(size.height) / Math.log(2)));
  47905. }
  47906. var id = "groupsMapChache" + this._mapCounter + "forCanvas" + this.id;
  47907. map = new BABYLON.MapTexture(id, this._scene, mapSize, useMipMap ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : BABYLON.Texture.BILINEAR_SAMPLINGMODE, useMipMap);
  47908. map.anisotropicFilteringLevel = 4;
  47909. mapArray.splice(0, 0, map);
  47910. var node = map.allocateRect(size);
  47911. res = { node: node, texture: map };
  47912. }
  47913. // Check if we have to create a Sprite that will display the content of the Canvas which is cached.
  47914. // Don't do it in case of the group being a worldspace canvas (because its texture is bound to a WorldSpaceCanvas node)
  47915. if (group !== this || this._isScreenSpace) {
  47916. var node = res.node;
  47917. // 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
  47918. if (this._cachingStrategy === Canvas2D.CACHESTRATEGY_CANVAS) {
  47919. this._cachedCanvasGroup = BABYLON.Group2D._createCachedCanvasGroup(this);
  47920. var sprite = new BABYLON.Sprite2D(map, { parent: this._cachedCanvasGroup, id: "__cachedCanvasSprite__", spriteSize: node.contentSize, spriteLocation: node.pos });
  47921. sprite.zOrder = 1;
  47922. sprite.origin = BABYLON.Vector2.Zero();
  47923. }
  47924. else {
  47925. 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 });
  47926. sprite.origin = group.origin.clone();
  47927. res.sprite = sprite;
  47928. }
  47929. }
  47930. return res;
  47931. };
  47932. /**
  47933. * Internal method used to register a Scene Node to track position for the given group
  47934. * Do not invoke this method, for internal purpose only.
  47935. * @param group the group to track its associated Scene Node
  47936. */
  47937. Canvas2D.prototype._registerTrackedNode = function (group) {
  47938. if (group._isFlagSet(BABYLON.SmartPropertyPrim.flagTrackedGroup)) {
  47939. return;
  47940. }
  47941. this._trackedGroups.push(group);
  47942. group._setFlags(BABYLON.SmartPropertyPrim.flagTrackedGroup);
  47943. };
  47944. /**
  47945. * Internal method used to unregister a tracked Scene Node
  47946. * Do not invoke this method, it's for internal purpose only.
  47947. * @param group the group to unregister its tracked Scene Node from.
  47948. */
  47949. Canvas2D.prototype._unregisterTrackedNode = function (group) {
  47950. if (!group._isFlagSet(BABYLON.SmartPropertyPrim.flagTrackedGroup)) {
  47951. return;
  47952. }
  47953. var i = this._trackedGroups.indexOf(group);
  47954. if (i !== -1) {
  47955. this._trackedGroups.splice(i, 1);
  47956. }
  47957. group._clearFlags(BABYLON.SmartPropertyPrim.flagTrackedGroup);
  47958. };
  47959. /**
  47960. * Get a Solid Color Brush instance matching the given color.
  47961. * @param color The color to retrieve
  47962. * @return A shared instance of the SolidColorBrush2D class that use the given color
  47963. */
  47964. Canvas2D.GetSolidColorBrush = function (color) {
  47965. return Canvas2D._solidColorBrushes.getOrAddWithFactory(color.toHexString(), function () { return new BABYLON.SolidColorBrush2D(color.clone(), true); });
  47966. };
  47967. /**
  47968. * Get a Solid Color Brush instance matching the given color expressed as a CSS formatted hexadecimal value.
  47969. * @param color The color to retrieve
  47970. * @return A shared instance of the SolidColorBrush2D class that uses the given color
  47971. */
  47972. Canvas2D.GetSolidColorBrushFromHex = function (hexValue) {
  47973. return Canvas2D._solidColorBrushes.getOrAddWithFactory(hexValue, function () { return new BABYLON.SolidColorBrush2D(BABYLON.Color4.FromHexString(hexValue), true); });
  47974. };
  47975. /**
  47976. * Get a Gradient Color Brush
  47977. * @param color1 starting color
  47978. * @param color2 engine color
  47979. * @param translation translation vector to apply. default is [0;0]
  47980. * @param rotation rotation in radian to apply to the brush, initial direction is top to bottom. rotation is counter clockwise. default is 0.
  47981. * @param scale scaling factor to apply. default is 1.
  47982. */
  47983. Canvas2D.GetGradientColorBrush = function (color1, color2, translation, rotation, scale) {
  47984. if (translation === void 0) { translation = BABYLON.Vector2.Zero(); }
  47985. if (rotation === void 0) { rotation = 0; }
  47986. if (scale === void 0) { scale = 1; }
  47987. return Canvas2D._gradientColorBrushes.getOrAddWithFactory(BABYLON.GradientColorBrush2D.BuildKey(color1, color2, translation, rotation, scale), function () { return new BABYLON.GradientColorBrush2D(color1, color2, translation, rotation, scale, true); });
  47988. };
  47989. /**
  47990. * Create a solid or gradient brush from a string value.
  47991. * @param brushString should be either
  47992. * - "solid: #RRGGBBAA" or "#RRGGBBAA"
  47993. * - "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.
  47994. */
  47995. Canvas2D.GetBrushFromString = function (brushString) {
  47996. // Note: yes, I hate/don't know RegEx.. Feel free to add your contribution to the cause!
  47997. brushString = brushString.trim();
  47998. var split = brushString.split(",");
  47999. // Solid, formatted as: "[solid:]#FF808080"
  48000. if (split.length === 1) {
  48001. var value = null;
  48002. if (brushString.indexOf("solid:") === 0) {
  48003. value = brushString.substr(6).trim();
  48004. }
  48005. else if (brushString.indexOf("#") === 0) {
  48006. value = brushString;
  48007. }
  48008. else {
  48009. return null;
  48010. }
  48011. return Canvas2D.GetSolidColorBrushFromHex(value);
  48012. }
  48013. else {
  48014. if (split[0].indexOf("gradient:") === 0) {
  48015. split[0] = split[0].substr(9).trim();
  48016. }
  48017. try {
  48018. var start = BABYLON.Color4.FromHexString(split[0].trim());
  48019. var end = BABYLON.Color4.FromHexString(split[1].trim());
  48020. var t = BABYLON.Vector2.Zero();
  48021. if (split.length > 2) {
  48022. var v = split[2].trim();
  48023. if (v.charAt(0) !== "[" || v.charAt(v.length - 1) !== "]") {
  48024. return null;
  48025. }
  48026. var sep = v.indexOf(":");
  48027. var x = parseFloat(v.substr(1, sep));
  48028. var y = parseFloat(v.substr(sep + 1, v.length - (sep + 1)));
  48029. t = new BABYLON.Vector2(x, y);
  48030. }
  48031. var r = 0;
  48032. if (split.length > 3) {
  48033. r = BABYLON.Tools.ToRadians(parseFloat(split[3].trim()));
  48034. }
  48035. var s = 1;
  48036. if (split.length > 4) {
  48037. s = parseFloat(split[4].trim());
  48038. }
  48039. return Canvas2D.GetGradientColorBrush(start, end, t, r, s);
  48040. }
  48041. catch (e) {
  48042. return null;
  48043. }
  48044. }
  48045. };
  48046. /**
  48047. * 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.
  48048. * This strategy doesn't allow primitives added directly as children of the Canvas.
  48049. * 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.
  48050. */
  48051. Canvas2D.CACHESTRATEGY_TOPLEVELGROUPS = 1;
  48052. /**
  48053. * In this strategy each group will have its own cache bitmap (except if a given group explicitly defines the DONTCACHEOVERRIDE or CACHEINPARENTGROUP behaviors).
  48054. * 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.
  48055. * When using this strategy, group instances can rely on the DONTCACHEOVERRIDE or CACHEINPARENTGROUP behaviors to minimize the amount of cached bitmaps.
  48056. * 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.
  48057. */
  48058. Canvas2D.CACHESTRATEGY_ALLGROUPS = 2;
  48059. /**
  48060. * 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).
  48061. */
  48062. Canvas2D.CACHESTRATEGY_CANVAS = 3;
  48063. /**
  48064. * This strategy is used to recompose/redraw the canvas entirely at each viewport render.
  48065. * 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).
  48066. * Note that you can't use this strategy for WorldSpace Canvas, they need at least a top level group caching.
  48067. */
  48068. Canvas2D.CACHESTRATEGY_DONTCACHE = 4;
  48069. Canvas2D._zMinDelta = 1 / (Math.pow(2, 24) - 1);
  48070. Canvas2D._interInfo = new BABYLON.IntersectInfo2D();
  48071. Canvas2D._v = BABYLON.Vector3.Zero(); // Must stay zero
  48072. Canvas2D._m = BABYLON.Matrix.Identity();
  48073. Canvas2D._mI = BABYLON.Matrix.Identity(); // Must stay identity
  48074. /**
  48075. * Define the default size used for both the width and height of a MapTexture to allocate.
  48076. * Note that some MapTexture might be bigger than this size if the first node to allocate is bigger in width or height
  48077. */
  48078. Canvas2D._groupTextureCacheSize = 1024;
  48079. Canvas2D._solidColorBrushes = new BABYLON.StringDictionary();
  48080. Canvas2D._gradientColorBrushes = new BABYLON.StringDictionary();
  48081. Canvas2D = __decorate([
  48082. BABYLON.className("Canvas2D")
  48083. ], Canvas2D);
  48084. return Canvas2D;
  48085. })(BABYLON.Group2D);
  48086. BABYLON.Canvas2D = Canvas2D;
  48087. var WorldSpaceCanvas2D = (function (_super) {
  48088. __extends(WorldSpaceCanvas2D, _super);
  48089. /**
  48090. * 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.
  48091. * 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.
  48092. * @param scene the Scene that owns the Canvas
  48093. * @param size the dimension of the Canvas in World Space
  48094. * @param settings a combination of settings, possible ones are
  48095. * - children: an array of direct children primitives
  48096. * - id: a text identifier, for information purpose only, default is null.
  48097. * - worldPosition the position of the Canvas in World Space, default is [0,0,0]
  48098. * - worldRotation the rotation of the Canvas in World Space, default is Quaternion.Identity()
  48099. * - sideOrientation: Unexpected behavior occur if the value is different from Mesh.DEFAULTSIDE right now, so please use this one, which is the default.
  48100. * - cachingStrategy Must be CACHESTRATEGY_CANVAS for now, which is the default.
  48101. * - 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).
  48102. * - isVisible: true if the canvas must be visible, false for hidden. Default is true.
  48103. * - backgroundRoundRadius: the round radius of the background, either backgroundFill or backgroundBorder must be specified.
  48104. * - 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.
  48105. * - 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.
  48106. * - backgroundBorderThickness: if a backgroundBorder is specified, its thickness can be set using this property
  48107. * - 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.
  48108. * - 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.
  48109. * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  48110. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  48111. * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  48112. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  48113. * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
  48114. */
  48115. function WorldSpaceCanvas2D(scene, size, settings) {
  48116. BABYLON.Prim2DBase._isCanvasInit = true;
  48117. var s = settings;
  48118. s.isScreenSpace = false;
  48119. s.size = size.clone();
  48120. settings.cachingStrategy = (settings.cachingStrategy == null) ? Canvas2D.CACHESTRATEGY_CANVAS : settings.cachingStrategy;
  48121. if (settings.cachingStrategy !== Canvas2D.CACHESTRATEGY_CANVAS) {
  48122. throw new Error("Right now only the CACHESTRATEGY_CANVAS cache Strategy is supported for WorldSpace Canvas. More will come soon!");
  48123. }
  48124. _super.call(this, scene, settings);
  48125. BABYLON.Prim2DBase._isCanvasInit = false;
  48126. this._renderableData._useMipMap = true;
  48127. this._renderableData._anisotropicLevel = 8;
  48128. //if (cachingStrategy === Canvas2D.CACHESTRATEGY_DONTCACHE) {
  48129. // throw new Error("CACHESTRATEGY_DONTCACHE cache Strategy can't be used for WorldSpace Canvas");
  48130. //}
  48131. var createWorldSpaceNode = !settings || (settings.customWorldSpaceNode == null);
  48132. var id = settings ? settings.id || null : null;
  48133. // Set the max size of texture allowed for the adaptive render of the world space canvas cached bitmap
  48134. var capMaxTextSize = this.engine.getCaps().maxRenderTextureSize;
  48135. var defaultTextSize = (Math.min(capMaxTextSize, 1024)); // Default is 4K if allowed otherwise the max allowed
  48136. if (settings.maxAdaptiveCanvasSize == null) {
  48137. this._maxAdaptiveWorldSpaceCanvasSize = defaultTextSize;
  48138. }
  48139. else {
  48140. // We still clip the given value with the max allowed, the user may not be aware of these limitations
  48141. this._maxAdaptiveWorldSpaceCanvasSize = Math.min(settings.maxAdaptiveCanvasSize, capMaxTextSize);
  48142. }
  48143. if (createWorldSpaceNode) {
  48144. var plane = new BABYLON.WorldSpaceCanvas2DNode(id, scene, this);
  48145. var vertexData = BABYLON.VertexData.CreatePlane({
  48146. width: size.width,
  48147. height: size.height,
  48148. sideOrientation: settings && settings.sideOrientation || BABYLON.Mesh.DEFAULTSIDE
  48149. });
  48150. var mtl = new BABYLON.StandardMaterial(id + "_Material", scene);
  48151. this.applyCachedTexture(vertexData, mtl);
  48152. vertexData.applyToMesh(plane, true);
  48153. mtl.specularColor = new BABYLON.Color3(0, 0, 0);
  48154. mtl.disableLighting = true;
  48155. mtl.useAlphaFromDiffuseTexture = true;
  48156. plane.position = settings && settings.worldPosition || BABYLON.Vector3.Zero();
  48157. plane.rotationQuaternion = settings && settings.worldRotation || BABYLON.Quaternion.Identity();
  48158. plane.material = mtl;
  48159. this._worldSpaceNode = plane;
  48160. }
  48161. else {
  48162. this._worldSpaceNode = settings.customWorldSpaceNode;
  48163. this.applyCachedTexture(null, null);
  48164. }
  48165. }
  48166. WorldSpaceCanvas2D = __decorate([
  48167. BABYLON.className("WorldSpaceCanvas2D")
  48168. ], WorldSpaceCanvas2D);
  48169. return WorldSpaceCanvas2D;
  48170. })(Canvas2D);
  48171. BABYLON.WorldSpaceCanvas2D = WorldSpaceCanvas2D;
  48172. var ScreenSpaceCanvas2D = (function (_super) {
  48173. __extends(ScreenSpaceCanvas2D, _super);
  48174. /**
  48175. * 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.
  48176. * 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.
  48177. * All caching strategies will be available.
  48178. * 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]
  48179. * @param scene the Scene that owns the Canvas
  48180. * @param settings a combination of settings, possible ones are
  48181. * - children: an array of direct children primitives
  48182. * - id: a text identifier, for information purpose only
  48183. * - x: the position along the x axis (horizontal), relative to the left edge of the viewport. you can alternatively use the position setting.
  48184. * - y: the position along the y axis (vertically), relative to the bottom edge of the viewport. you can alternatively use the position setting.
  48185. * - 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]
  48186. * - width: the width of the Canvas. you can alternatively use the size setting.
  48187. * - height: the height of the Canvas. you can alternatively use the size setting.
  48188. * - 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
  48189. * - cachingStrategy: either CACHESTRATEGY_TOPLEVELGROUPS, CACHESTRATEGY_ALLGROUPS, CACHESTRATEGY_CANVAS, CACHESTRATEGY_DONTCACHE. Please refer to their respective documentation for more information. Default is Canvas2D.CACHESTRATEGY_DONTCACHE
  48190. * - 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.
  48191. * - isVisible: true if the canvas must be visible, false for hidden. Default is true.
  48192. * - backgroundRoundRadius: the round radius of the background, either backgroundFill or backgroundBorder must be specified.
  48193. * - 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.
  48194. * - 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.
  48195. * - backgroundBorderThickness: if a backgroundBorder is specified, its thickness can be set using this property
  48196. * - 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.
  48197. * - paddingTop: top padding, can be a number (will be pixels) or a string (see BABYLON.PrimitiveThickness.fromString)
  48198. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see BABYLON.PrimitiveThickness.fromString)
  48199. * - paddingRight: right padding, can be a number (will be pixels) or a string (see BABYLON.PrimitiveThickness.fromString)
  48200. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see BABYLON.PrimitiveThickness.fromString)
  48201. * - padding: top, left, right and bottom padding formatted as a single string (see BABYLON.PrimitiveThickness.fromString)
  48202. */
  48203. function ScreenSpaceCanvas2D(scene, settings) {
  48204. BABYLON.Prim2DBase._isCanvasInit = true;
  48205. _super.call(this, scene, settings);
  48206. }
  48207. ScreenSpaceCanvas2D = __decorate([
  48208. BABYLON.className("ScreenSpaceCanvas2D")
  48209. ], ScreenSpaceCanvas2D);
  48210. return ScreenSpaceCanvas2D;
  48211. })(Canvas2D);
  48212. BABYLON.ScreenSpaceCanvas2D = ScreenSpaceCanvas2D;
  48213. })(BABYLON || (BABYLON = {}));
  48214. var BABYLON;
  48215. (function (BABYLON) {
  48216. /**
  48217. * This is the class that is used to display a World Space Canvas into a 3D scene
  48218. */
  48219. var WorldSpaceCanvas2DNode = (function (_super) {
  48220. __extends(WorldSpaceCanvas2DNode, _super);
  48221. function WorldSpaceCanvas2DNode(name, scene, canvas) {
  48222. _super.call(this, name, scene);
  48223. this._canvas = canvas;
  48224. }
  48225. WorldSpaceCanvas2DNode.prototype.dispose = function () {
  48226. _super.prototype.dispose.call(this);
  48227. if (this._canvas) {
  48228. this._canvas.dispose();
  48229. this._canvas = null;
  48230. }
  48231. };
  48232. return WorldSpaceCanvas2DNode;
  48233. })(BABYLON.Mesh);
  48234. BABYLON.WorldSpaceCanvas2DNode = WorldSpaceCanvas2DNode;
  48235. })(BABYLON || (BABYLON = {}));
  48236. var BABYLON;
  48237. (function (BABYLON) {
  48238. var LayoutEngineBase = (function () {
  48239. function LayoutEngineBase() {
  48240. this.layoutDirtyOnPropertyChangedMask = 0;
  48241. }
  48242. LayoutEngineBase.prototype.updateLayout = function (prim) {
  48243. };
  48244. Object.defineProperty(LayoutEngineBase.prototype, "isChildPositionAllowed", {
  48245. get: function () {
  48246. return false;
  48247. },
  48248. enumerable: true,
  48249. configurable: true
  48250. });
  48251. LayoutEngineBase.prototype.isLocked = function () {
  48252. return this._isLocked;
  48253. };
  48254. LayoutEngineBase.prototype.lock = function () {
  48255. if (this._isLocked) {
  48256. return false;
  48257. }
  48258. this._isLocked = true;
  48259. return true;
  48260. };
  48261. LayoutEngineBase = __decorate([
  48262. BABYLON.className("LayoutEngineBase")
  48263. ], LayoutEngineBase);
  48264. return LayoutEngineBase;
  48265. })();
  48266. BABYLON.LayoutEngineBase = LayoutEngineBase;
  48267. var CanvasLayoutEngine = (function (_super) {
  48268. __extends(CanvasLayoutEngine, _super);
  48269. function CanvasLayoutEngine() {
  48270. _super.apply(this, arguments);
  48271. }
  48272. // A very simple (no) layout computing...
  48273. // The Canvas and its direct children gets the Canvas' size as Layout Area
  48274. // Indirect children have their Layout Area to the actualSize (margin area) of their parent
  48275. CanvasLayoutEngine.prototype.updateLayout = function (prim) {
  48276. // If this prim is layoutDiry we update its layoutArea and also the one of its direct children
  48277. if (prim._isFlagSet(BABYLON.SmartPropertyPrim.flagLayoutDirty)) {
  48278. for (var _i = 0, _a = prim.children; _i < _a.length; _i++) {
  48279. var child = _a[_i];
  48280. this._doUpdate(child);
  48281. }
  48282. prim._clearFlags(BABYLON.SmartPropertyPrim.flagLayoutDirty);
  48283. }
  48284. };
  48285. CanvasLayoutEngine.prototype._doUpdate = function (prim) {
  48286. // Canvas ?
  48287. if (prim instanceof BABYLON.Canvas2D) {
  48288. prim.layoutArea = prim.actualSize;
  48289. }
  48290. else if (prim.parent instanceof BABYLON.Canvas2D) {
  48291. prim.layoutArea = prim.owner.actualSize;
  48292. }
  48293. else {
  48294. prim.layoutArea = prim.parent.contentArea;
  48295. }
  48296. };
  48297. Object.defineProperty(CanvasLayoutEngine.prototype, "isChildPositionAllowed", {
  48298. get: function () {
  48299. return true;
  48300. },
  48301. enumerable: true,
  48302. configurable: true
  48303. });
  48304. CanvasLayoutEngine.Singleton = new CanvasLayoutEngine();
  48305. CanvasLayoutEngine = __decorate([
  48306. BABYLON.className("CanvasLayoutEngine")
  48307. ], CanvasLayoutEngine);
  48308. return CanvasLayoutEngine;
  48309. })(LayoutEngineBase);
  48310. BABYLON.CanvasLayoutEngine = CanvasLayoutEngine;
  48311. var StackPanelLayoutEngine = (function (_super) {
  48312. __extends(StackPanelLayoutEngine, _super);
  48313. function StackPanelLayoutEngine() {
  48314. _super.call(this);
  48315. this._isHorizontal = true;
  48316. this.layoutDirtyOnPropertyChangedMask = BABYLON.Prim2DBase.sizeProperty.flagId;
  48317. }
  48318. Object.defineProperty(StackPanelLayoutEngine, "Horizontal", {
  48319. get: function () {
  48320. if (!StackPanelLayoutEngine._horizontal) {
  48321. StackPanelLayoutEngine._horizontal = new StackPanelLayoutEngine();
  48322. StackPanelLayoutEngine._horizontal.isHorizontal = true;
  48323. StackPanelLayoutEngine._horizontal.lock();
  48324. }
  48325. return StackPanelLayoutEngine._horizontal;
  48326. },
  48327. enumerable: true,
  48328. configurable: true
  48329. });
  48330. Object.defineProperty(StackPanelLayoutEngine, "Vertical", {
  48331. get: function () {
  48332. if (!StackPanelLayoutEngine._vertical) {
  48333. StackPanelLayoutEngine._vertical = new StackPanelLayoutEngine();
  48334. StackPanelLayoutEngine._vertical.isHorizontal = false;
  48335. StackPanelLayoutEngine._vertical.lock();
  48336. }
  48337. return StackPanelLayoutEngine._vertical;
  48338. },
  48339. enumerable: true,
  48340. configurable: true
  48341. });
  48342. Object.defineProperty(StackPanelLayoutEngine.prototype, "isHorizontal", {
  48343. get: function () {
  48344. return this._isHorizontal;
  48345. },
  48346. set: function (val) {
  48347. if (this.isLocked()) {
  48348. return;
  48349. }
  48350. this._isHorizontal = val;
  48351. },
  48352. enumerable: true,
  48353. configurable: true
  48354. });
  48355. StackPanelLayoutEngine.prototype.updateLayout = function (prim) {
  48356. if (prim._isFlagSet(BABYLON.SmartPropertyPrim.flagLayoutDirty)) {
  48357. var x = 0;
  48358. var y = 0;
  48359. var h = this.isHorizontal;
  48360. var max = 0;
  48361. for (var _i = 0, _a = prim.children; _i < _a.length; _i++) {
  48362. var child = _a[_i];
  48363. var layoutArea = child.layoutArea;
  48364. child.margin.computeArea(child.actualSize, layoutArea);
  48365. max = Math.max(max, h ? layoutArea.height : layoutArea.width);
  48366. }
  48367. for (var _b = 0, _c = prim.children; _b < _c.length; _b++) {
  48368. var child = _c[_b];
  48369. child.layoutAreaPos = new BABYLON.Vector2(x, y);
  48370. var layoutArea = child.layoutArea;
  48371. if (h) {
  48372. x += layoutArea.width;
  48373. child.layoutArea = new BABYLON.Size(layoutArea.width, max);
  48374. }
  48375. else {
  48376. y += layoutArea.height;
  48377. child.layoutArea = new BABYLON.Size(max, layoutArea.height);
  48378. }
  48379. }
  48380. prim._clearFlags(BABYLON.SmartPropertyPrim.flagLayoutDirty);
  48381. }
  48382. };
  48383. Object.defineProperty(StackPanelLayoutEngine.prototype, "isChildPositionAllowed", {
  48384. get: function () {
  48385. return false;
  48386. },
  48387. enumerable: true,
  48388. configurable: true
  48389. });
  48390. StackPanelLayoutEngine._horizontal = null;
  48391. StackPanelLayoutEngine._vertical = null;
  48392. StackPanelLayoutEngine = __decorate([
  48393. BABYLON.className("StackPanelLayoutEngine")
  48394. ], StackPanelLayoutEngine);
  48395. return StackPanelLayoutEngine;
  48396. })(LayoutEngineBase);
  48397. BABYLON.StackPanelLayoutEngine = StackPanelLayoutEngine;
  48398. })(BABYLON || (BABYLON = {}));
  48399. var BABYLON;
  48400. (function (BABYLON) {
  48401. var ShaderMaterial = (function (_super) {
  48402. __extends(ShaderMaterial, _super);
  48403. function ShaderMaterial(name, scene, shaderPath, options) {
  48404. _super.call(this, name, scene);
  48405. this._textures = {};
  48406. this._textureArrays = {};
  48407. this._floats = {};
  48408. this._floatsArrays = {};
  48409. this._colors3 = {};
  48410. this._colors4 = {};
  48411. this._vectors2 = {};
  48412. this._vectors3 = {};
  48413. this._vectors4 = {};
  48414. this._matrices = {};
  48415. this._matrices3x3 = {};
  48416. this._matrices2x2 = {};
  48417. this._cachedWorldViewMatrix = new BABYLON.Matrix();
  48418. this._shaderPath = shaderPath;
  48419. options.needAlphaBlending = options.needAlphaBlending || false;
  48420. options.needAlphaTesting = options.needAlphaTesting || false;
  48421. options.attributes = options.attributes || ["position", "normal", "uv"];
  48422. options.uniforms = options.uniforms || ["worldViewProjection"];
  48423. options.samplers = options.samplers || [];
  48424. options.defines = options.defines || [];
  48425. this._options = options;
  48426. }
  48427. ShaderMaterial.prototype.needAlphaBlending = function () {
  48428. return this._options.needAlphaBlending;
  48429. };
  48430. ShaderMaterial.prototype.needAlphaTesting = function () {
  48431. return this._options.needAlphaTesting;
  48432. };
  48433. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  48434. if (this._options.uniforms.indexOf(uniformName) === -1) {
  48435. this._options.uniforms.push(uniformName);
  48436. }
  48437. };
  48438. ShaderMaterial.prototype.setTexture = function (name, texture) {
  48439. if (this._options.samplers.indexOf(name) === -1) {
  48440. this._options.samplers.push(name);
  48441. }
  48442. this._textures[name] = texture;
  48443. return this;
  48444. };
  48445. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  48446. if (this._options.samplers.indexOf(name) === -1) {
  48447. this._options.samplers.push(name);
  48448. }
  48449. this._checkUniform(name);
  48450. this._textureArrays[name] = textures;
  48451. return this;
  48452. };
  48453. ShaderMaterial.prototype.setFloat = function (name, value) {
  48454. this._checkUniform(name);
  48455. this._floats[name] = value;
  48456. return this;
  48457. };
  48458. ShaderMaterial.prototype.setFloats = function (name, value) {
  48459. this._checkUniform(name);
  48460. this._floatsArrays[name] = value;
  48461. return this;
  48462. };
  48463. ShaderMaterial.prototype.setColor3 = function (name, value) {
  48464. this._checkUniform(name);
  48465. this._colors3[name] = value;
  48466. return this;
  48467. };
  48468. ShaderMaterial.prototype.setColor4 = function (name, value) {
  48469. this._checkUniform(name);
  48470. this._colors4[name] = value;
  48471. return this;
  48472. };
  48473. ShaderMaterial.prototype.setVector2 = function (name, value) {
  48474. this._checkUniform(name);
  48475. this._vectors2[name] = value;
  48476. return this;
  48477. };
  48478. ShaderMaterial.prototype.setVector3 = function (name, value) {
  48479. this._checkUniform(name);
  48480. this._vectors3[name] = value;
  48481. return this;
  48482. };
  48483. ShaderMaterial.prototype.setVector4 = function (name, value) {
  48484. this._checkUniform(name);
  48485. this._vectors4[name] = value;
  48486. return this;
  48487. };
  48488. ShaderMaterial.prototype.setMatrix = function (name, value) {
  48489. this._checkUniform(name);
  48490. this._matrices[name] = value;
  48491. return this;
  48492. };
  48493. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  48494. this._checkUniform(name);
  48495. this._matrices3x3[name] = value;
  48496. return this;
  48497. };
  48498. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  48499. this._checkUniform(name);
  48500. this._matrices2x2[name] = value;
  48501. return this;
  48502. };
  48503. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  48504. var scene = this.getScene();
  48505. var engine = scene.getEngine();
  48506. if (!this.checkReadyOnEveryCall) {
  48507. if (this._renderId === scene.getRenderId()) {
  48508. return true;
  48509. }
  48510. }
  48511. // Instances
  48512. var defines = [];
  48513. var fallbacks = new BABYLON.EffectFallbacks();
  48514. if (useInstances) {
  48515. defines.push("#define INSTANCES");
  48516. }
  48517. for (var index = 0; index < this._options.defines.length; index++) {
  48518. defines.push(this._options.defines[index]);
  48519. }
  48520. // Bones
  48521. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  48522. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  48523. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  48524. fallbacks.addCPUSkinningFallback(0, mesh);
  48525. }
  48526. // Alpha test
  48527. if (engine.getAlphaTesting()) {
  48528. defines.push("#define ALPHATEST");
  48529. }
  48530. var previousEffect = this._effect;
  48531. var join = defines.join("\n");
  48532. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, join, fallbacks, this.onCompiled, this.onError);
  48533. if (!this._effect.isReady()) {
  48534. return false;
  48535. }
  48536. if (previousEffect !== this._effect) {
  48537. scene.resetCachedMaterial();
  48538. }
  48539. this._renderId = scene.getRenderId();
  48540. return true;
  48541. };
  48542. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  48543. var scene = this.getScene();
  48544. if (this._options.uniforms.indexOf("world") !== -1) {
  48545. this._effect.setMatrix("world", world);
  48546. }
  48547. if (this._options.uniforms.indexOf("worldView") !== -1) {
  48548. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  48549. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  48550. }
  48551. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  48552. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  48553. }
  48554. };
  48555. ShaderMaterial.prototype.bind = function (world, mesh) {
  48556. // Std values
  48557. this.bindOnlyWorldMatrix(world);
  48558. if (this.getScene().getCachedMaterial() !== this) {
  48559. if (this._options.uniforms.indexOf("view") !== -1) {
  48560. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  48561. }
  48562. if (this._options.uniforms.indexOf("projection") !== -1) {
  48563. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  48564. }
  48565. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  48566. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  48567. }
  48568. // Bones
  48569. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  48570. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  48571. }
  48572. var name;
  48573. // Texture
  48574. for (name in this._textures) {
  48575. this._effect.setTexture(name, this._textures[name]);
  48576. }
  48577. // Texture arrays
  48578. for (name in this._textureArrays) {
  48579. this._effect.setTextureArray(name, this._textureArrays[name]);
  48580. }
  48581. // Float
  48582. for (name in this._floats) {
  48583. this._effect.setFloat(name, this._floats[name]);
  48584. }
  48585. // Float s
  48586. for (name in this._floatsArrays) {
  48587. this._effect.setArray(name, this._floatsArrays[name]);
  48588. }
  48589. // Color3
  48590. for (name in this._colors3) {
  48591. this._effect.setColor3(name, this._colors3[name]);
  48592. }
  48593. // Color4
  48594. for (name in this._colors4) {
  48595. var color = this._colors4[name];
  48596. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  48597. }
  48598. // Vector2
  48599. for (name in this._vectors2) {
  48600. this._effect.setVector2(name, this._vectors2[name]);
  48601. }
  48602. // Vector3
  48603. for (name in this._vectors3) {
  48604. this._effect.setVector3(name, this._vectors3[name]);
  48605. }
  48606. // Vector4
  48607. for (name in this._vectors4) {
  48608. this._effect.setVector4(name, this._vectors4[name]);
  48609. }
  48610. // Matrix
  48611. for (name in this._matrices) {
  48612. this._effect.setMatrix(name, this._matrices[name]);
  48613. }
  48614. // Matrix 3x3
  48615. for (name in this._matrices3x3) {
  48616. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  48617. }
  48618. // Matrix 2x2
  48619. for (name in this._matrices2x2) {
  48620. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  48621. }
  48622. }
  48623. _super.prototype.bind.call(this, world, mesh);
  48624. };
  48625. ShaderMaterial.prototype.clone = function (name) {
  48626. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  48627. return newShaderMaterial;
  48628. };
  48629. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  48630. if (forceDisposeTextures) {
  48631. var name;
  48632. for (name in this._textures) {
  48633. this._textures[name].dispose();
  48634. }
  48635. for (name in this._textureArrays) {
  48636. var array = this._textureArrays[name];
  48637. for (var index = 0; index < array.length; index++) {
  48638. array[index].dispose();
  48639. }
  48640. }
  48641. }
  48642. this._textures = {};
  48643. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  48644. };
  48645. ShaderMaterial.prototype.serialize = function () {
  48646. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  48647. serializationObject.customType = "BABYLON.ShaderMaterial";
  48648. serializationObject.options = this._options;
  48649. serializationObject.shaderPath = this._shaderPath;
  48650. var name;
  48651. // Texture
  48652. serializationObject.textures = {};
  48653. for (name in this._textures) {
  48654. serializationObject.textures[name] = this._textures[name].serialize();
  48655. }
  48656. // Texture arrays
  48657. serializationObject.textureArrays = {};
  48658. for (name in this._textureArrays) {
  48659. serializationObject.textureArrays[name] = [];
  48660. var array = this._textureArrays[name];
  48661. for (var index = 0; index < array.length; index++) {
  48662. serializationObject.textureArrays[name].push(array[index].serialize());
  48663. }
  48664. }
  48665. // Float
  48666. serializationObject.floats = {};
  48667. for (name in this._floats) {
  48668. serializationObject.floats[name] = this._floats[name];
  48669. }
  48670. // Float s
  48671. serializationObject.floatArrays = {};
  48672. for (name in this._floatsArrays) {
  48673. serializationObject.floatArrays[name] = this._floatsArrays[name];
  48674. }
  48675. // Color3
  48676. serializationObject.colors3 = {};
  48677. for (name in this._colors3) {
  48678. serializationObject.colors3[name] = this._colors3[name].asArray();
  48679. }
  48680. // Color4
  48681. serializationObject.colors4 = {};
  48682. for (name in this._colors4) {
  48683. serializationObject.colors4[name] = this._colors4[name].asArray();
  48684. }
  48685. // Vector2
  48686. serializationObject.vectors2 = {};
  48687. for (name in this._vectors2) {
  48688. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  48689. }
  48690. // Vector3
  48691. serializationObject.vectors3 = {};
  48692. for (name in this._vectors3) {
  48693. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  48694. }
  48695. // Vector4
  48696. serializationObject.vectors4 = {};
  48697. for (name in this._vectors4) {
  48698. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  48699. }
  48700. // Matrix
  48701. serializationObject.matrices = {};
  48702. for (name in this._matrices) {
  48703. serializationObject.matrices[name] = this._matrices[name].asArray();
  48704. }
  48705. // Matrix 3x3
  48706. serializationObject.matrices3x3 = {};
  48707. for (name in this._matrices3x3) {
  48708. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  48709. }
  48710. // Matrix 2x2
  48711. serializationObject.matrices2x2 = {};
  48712. for (name in this._matrices2x2) {
  48713. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  48714. }
  48715. return serializationObject;
  48716. };
  48717. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  48718. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  48719. var name;
  48720. // Texture
  48721. for (name in source.textures) {
  48722. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  48723. }
  48724. // Texture arrays
  48725. for (name in source.textureArrays) {
  48726. var array = source.textureArrays[name];
  48727. var textureArray = new Array();
  48728. for (var index = 0; index < array.length; index++) {
  48729. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  48730. }
  48731. material.setTextureArray(name, textureArray);
  48732. }
  48733. // Float
  48734. for (name in source.floats) {
  48735. material.setFloat(name, source.floats[name]);
  48736. }
  48737. // Float s
  48738. for (name in source.floatsArrays) {
  48739. material.setFloats(name, source.floatsArrays[name]);
  48740. }
  48741. // Color3
  48742. for (name in source.colors3) {
  48743. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  48744. }
  48745. // Color4
  48746. for (name in source.colors4) {
  48747. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  48748. }
  48749. // Vector2
  48750. for (name in source.vectors2) {
  48751. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  48752. }
  48753. // Vector3
  48754. for (name in source.vectors3) {
  48755. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  48756. }
  48757. // Vector4
  48758. for (name in source.vectors4) {
  48759. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  48760. }
  48761. // Matrix
  48762. for (name in source.matrices) {
  48763. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  48764. }
  48765. // Matrix 3x3
  48766. for (name in source.matrices3x3) {
  48767. material.setMatrix3x3(name, source.matrices3x3[name]);
  48768. }
  48769. // Matrix 2x2
  48770. for (name in source.matrices2x2) {
  48771. material.setMatrix2x2(name, source.matrices2x2[name]);
  48772. }
  48773. return material;
  48774. };
  48775. return ShaderMaterial;
  48776. })(BABYLON.Material);
  48777. BABYLON.ShaderMaterial = ShaderMaterial;
  48778. })(BABYLON || (BABYLON = {}));
  48779. var BABYLON;
  48780. (function (BABYLON) {
  48781. var Internals;
  48782. (function (Internals) {
  48783. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  48784. // All values and structures referenced from:
  48785. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  48786. var DDS_MAGIC = 0x20534444;
  48787. 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;
  48788. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  48789. 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;
  48790. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  48791. function FourCCToInt32(value) {
  48792. return value.charCodeAt(0) +
  48793. (value.charCodeAt(1) << 8) +
  48794. (value.charCodeAt(2) << 16) +
  48795. (value.charCodeAt(3) << 24);
  48796. }
  48797. function Int32ToFourCC(value) {
  48798. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  48799. }
  48800. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  48801. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  48802. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  48803. var headerLengthInt = 31; // The header length in 32 bit ints
  48804. // Offsets into the header array
  48805. var off_magic = 0;
  48806. var off_size = 1;
  48807. var off_flags = 2;
  48808. var off_height = 3;
  48809. var off_width = 4;
  48810. var off_mipmapCount = 7;
  48811. var off_pfFlags = 20;
  48812. var off_pfFourCC = 21;
  48813. var off_RGBbpp = 22;
  48814. var off_RMask = 23;
  48815. var off_GMask = 24;
  48816. var off_BMask = 25;
  48817. var off_AMask = 26;
  48818. var off_caps1 = 27;
  48819. var off_caps2 = 28;
  48820. ;
  48821. var DDSTools = (function () {
  48822. function DDSTools() {
  48823. }
  48824. DDSTools.GetDDSInfo = function (arrayBuffer) {
  48825. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  48826. var mipmapCount = 1;
  48827. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  48828. mipmapCount = Math.max(1, header[off_mipmapCount]);
  48829. }
  48830. return {
  48831. width: header[off_width],
  48832. height: header[off_height],
  48833. mipmapCount: mipmapCount,
  48834. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  48835. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  48836. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  48837. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  48838. };
  48839. };
  48840. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  48841. var byteArray = new Uint8Array(dataLength);
  48842. var srcData = new Uint8Array(arrayBuffer);
  48843. var index = 0;
  48844. for (var y = height - 1; y >= 0; y--) {
  48845. for (var x = 0; x < width; x++) {
  48846. var srcPos = dataOffset + (x + y * width) * 4;
  48847. byteArray[index + 2] = srcData[srcPos];
  48848. byteArray[index + 1] = srcData[srcPos + 1];
  48849. byteArray[index] = srcData[srcPos + 2];
  48850. byteArray[index + 3] = srcData[srcPos + 3];
  48851. index += 4;
  48852. }
  48853. }
  48854. return byteArray;
  48855. };
  48856. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  48857. var byteArray = new Uint8Array(dataLength);
  48858. var srcData = new Uint8Array(arrayBuffer);
  48859. var index = 0;
  48860. for (var y = height - 1; y >= 0; y--) {
  48861. for (var x = 0; x < width; x++) {
  48862. var srcPos = dataOffset + (x + y * width) * 3;
  48863. byteArray[index + 2] = srcData[srcPos];
  48864. byteArray[index + 1] = srcData[srcPos + 1];
  48865. byteArray[index] = srcData[srcPos + 2];
  48866. index += 3;
  48867. }
  48868. }
  48869. return byteArray;
  48870. };
  48871. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  48872. var byteArray = new Uint8Array(dataLength);
  48873. var srcData = new Uint8Array(arrayBuffer);
  48874. var index = 0;
  48875. for (var y = height - 1; y >= 0; y--) {
  48876. for (var x = 0; x < width; x++) {
  48877. var srcPos = dataOffset + (x + y * width);
  48878. byteArray[index] = srcData[srcPos];
  48879. index++;
  48880. }
  48881. }
  48882. return byteArray;
  48883. };
  48884. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  48885. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  48886. if (header[off_magic] != DDS_MAGIC) {
  48887. BABYLON.Tools.Error("Invalid magic number in DDS header");
  48888. return;
  48889. }
  48890. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  48891. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  48892. return;
  48893. }
  48894. if (info.isFourCC) {
  48895. fourCC = header[off_pfFourCC];
  48896. switch (fourCC) {
  48897. case FOURCC_DXT1:
  48898. blockBytes = 8;
  48899. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  48900. break;
  48901. case FOURCC_DXT3:
  48902. blockBytes = 16;
  48903. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  48904. break;
  48905. case FOURCC_DXT5:
  48906. blockBytes = 16;
  48907. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  48908. break;
  48909. default:
  48910. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  48911. return;
  48912. }
  48913. }
  48914. mipmapCount = 1;
  48915. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  48916. mipmapCount = Math.max(1, header[off_mipmapCount]);
  48917. }
  48918. var bpp = header[off_RGBbpp];
  48919. for (var face = 0; face < faces; face++) {
  48920. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  48921. width = header[off_width];
  48922. height = header[off_height];
  48923. dataOffset = header[off_size] + 4;
  48924. for (i = 0; i < mipmapCount; ++i) {
  48925. if (info.isRGB) {
  48926. if (bpp === 24) {
  48927. dataLength = width * height * 3;
  48928. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  48929. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  48930. }
  48931. else {
  48932. dataLength = width * height * 4;
  48933. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  48934. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  48935. }
  48936. }
  48937. else if (info.isLuminance) {
  48938. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  48939. var unpaddedRowSize = width;
  48940. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  48941. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  48942. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  48943. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  48944. }
  48945. else {
  48946. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  48947. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  48948. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  48949. }
  48950. dataOffset += dataLength;
  48951. width *= 0.5;
  48952. height *= 0.5;
  48953. width = Math.max(1.0, width);
  48954. height = Math.max(1.0, height);
  48955. }
  48956. }
  48957. };
  48958. return DDSTools;
  48959. })();
  48960. Internals.DDSTools = DDSTools;
  48961. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  48962. })(BABYLON || (BABYLON = {}));
  48963. var BABYLON;
  48964. (function (BABYLON) {
  48965. var CannonJSPlugin = (function () {
  48966. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  48967. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  48968. if (iterations === void 0) { iterations = 10; }
  48969. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  48970. this.name = "CannonJSPlugin";
  48971. this._physicsMaterials = [];
  48972. this._fixedTimeStep = 1 / 60;
  48973. //See https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  48974. this._currentCollisionGroup = 2;
  48975. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  48976. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  48977. this._tmpPosition = BABYLON.Vector3.Zero();
  48978. this._tmpQuaternion = new BABYLON.Quaternion();
  48979. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  48980. this._tmpDeltaRotation = new BABYLON.Quaternion();
  48981. this._tmpUnityRotation = new BABYLON.Quaternion();
  48982. if (!this.isSupported()) {
  48983. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  48984. return;
  48985. }
  48986. this.world = new CANNON.World();
  48987. this.world.broadphase = new CANNON.NaiveBroadphase();
  48988. this.world.solver.iterations = iterations;
  48989. }
  48990. CannonJSPlugin.prototype.setGravity = function (gravity) {
  48991. this.world.gravity.copy(gravity);
  48992. };
  48993. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  48994. this._fixedTimeStep = timeStep;
  48995. };
  48996. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  48997. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta * 1000 : 0, 3);
  48998. };
  48999. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  49000. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  49001. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  49002. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  49003. };
  49004. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  49005. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  49006. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  49007. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  49008. };
  49009. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  49010. //parent-child relationship. Does this impostor has a parent impostor?
  49011. if (impostor.parent) {
  49012. if (impostor.physicsBody) {
  49013. this.removePhysicsBody(impostor);
  49014. //TODO is that needed?
  49015. impostor.forceUpdate();
  49016. }
  49017. return;
  49018. }
  49019. //should a new body be created for this impostor?
  49020. if (impostor.isBodyInitRequired()) {
  49021. var shape = this._createShape(impostor);
  49022. //unregister events, if body is being changed
  49023. var oldBody = impostor.physicsBody;
  49024. if (oldBody) {
  49025. this.removePhysicsBody(impostor);
  49026. }
  49027. //create the body and material
  49028. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  49029. var bodyCreationObject = {
  49030. mass: impostor.getParam("mass"),
  49031. material: material
  49032. };
  49033. // A simple extend, in case native options were used.
  49034. var nativeOptions = impostor.getParam("nativeOptions");
  49035. for (var key in nativeOptions) {
  49036. if (nativeOptions.hasOwnProperty(key)) {
  49037. bodyCreationObject[key] = nativeOptions[key];
  49038. }
  49039. }
  49040. impostor.physicsBody = new CANNON.Body(bodyCreationObject);
  49041. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  49042. this.world.addEventListener("preStep", impostor.beforeStep);
  49043. this.world.addEventListener("postStep", impostor.afterStep);
  49044. impostor.physicsBody.addShape(shape);
  49045. this.world.add(impostor.physicsBody);
  49046. //try to keep the body moving in the right direction by taking old properties.
  49047. //Should be tested!
  49048. if (oldBody) {
  49049. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  49050. impostor.physicsBody[param].copy(oldBody[param]);
  49051. });
  49052. }
  49053. this._processChildMeshes(impostor);
  49054. }
  49055. //now update the body's transformation
  49056. this._updatePhysicsBodyTransformation(impostor);
  49057. };
  49058. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  49059. var _this = this;
  49060. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes() : [];
  49061. if (meshChildren.length) {
  49062. var processMesh = function (localPosition, mesh) {
  49063. var childImpostor = mesh.getPhysicsImpostor();
  49064. if (childImpostor) {
  49065. var parent = childImpostor.parent;
  49066. if (parent !== mainImpostor) {
  49067. var localPosition = mesh.position;
  49068. if (childImpostor.physicsBody) {
  49069. _this.removePhysicsBody(childImpostor);
  49070. childImpostor.physicsBody = null;
  49071. }
  49072. childImpostor.parent = mainImpostor;
  49073. childImpostor.resetUpdateFlags();
  49074. mainImpostor.physicsBody.addShape(_this._createShape(childImpostor), new CANNON.Vec3(localPosition.x, localPosition.y, localPosition.z));
  49075. //Add the mass of the children.
  49076. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  49077. }
  49078. }
  49079. mesh.getChildMeshes().forEach(processMesh.bind(_this, mesh.position));
  49080. };
  49081. meshChildren.forEach(processMesh.bind(this, BABYLON.Vector3.Zero()));
  49082. }
  49083. };
  49084. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  49085. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  49086. this.world.removeEventListener("preStep", impostor.beforeStep);
  49087. this.world.removeEventListener("postStep", impostor.afterStep);
  49088. this.world.remove(impostor.physicsBody);
  49089. };
  49090. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  49091. var mainBody = impostorJoint.mainImpostor.physicsBody;
  49092. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  49093. if (!mainBody || !connectedBody) {
  49094. return;
  49095. }
  49096. var constraint;
  49097. var jointData = impostorJoint.joint.jointData;
  49098. //TODO - https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  49099. var constraintData = {
  49100. pivotA: jointData.mainPivot ? new CANNON.Vec3().copy(jointData.mainPivot) : null,
  49101. pivotB: jointData.connectedPivot ? new CANNON.Vec3().copy(jointData.connectedPivot) : null,
  49102. axisA: jointData.mainAxis ? new CANNON.Vec3().copy(jointData.mainAxis) : null,
  49103. axisB: jointData.connectedAxis ? new CANNON.Vec3().copy(jointData.connectedAxis) : null,
  49104. maxForce: jointData.nativeParams.maxForce,
  49105. collideConnected: !!jointData.collision
  49106. };
  49107. //Not needed, Cannon has a collideConnected flag
  49108. /*if (!jointData.collision) {
  49109. //add 1st body to a collision group of its own, if it is not in 1
  49110. if (mainBody.collisionFilterGroup === 1) {
  49111. mainBody.collisionFilterGroup = this._currentCollisionGroup;
  49112. this._currentCollisionGroup <<= 1;
  49113. }
  49114. if (connectedBody.collisionFilterGroup === 1) {
  49115. connectedBody.collisionFilterGroup = this._currentCollisionGroup;
  49116. this._currentCollisionGroup <<= 1;
  49117. }
  49118. //add their mask to the collisionFilterMask of each other:
  49119. connectedBody.collisionFilterMask = connectedBody.collisionFilterMask | ~mainBody.collisionFilterGroup;
  49120. mainBody.collisionFilterMask = mainBody.collisionFilterMask | ~connectedBody.collisionFilterGroup;
  49121. }*/
  49122. switch (impostorJoint.joint.type) {
  49123. case BABYLON.PhysicsJoint.HingeJoint:
  49124. case BABYLON.PhysicsJoint.Hinge2Joint:
  49125. constraint = new CANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  49126. break;
  49127. case BABYLON.PhysicsJoint.DistanceJoint:
  49128. constraint = new CANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  49129. break;
  49130. case BABYLON.PhysicsJoint.SpringJoint:
  49131. var springData = jointData;
  49132. constraint = new CANNON.Spring(mainBody, connectedBody, {
  49133. restLength: springData.length,
  49134. stiffness: springData.stiffness,
  49135. damping: springData.damping,
  49136. localAnchorA: constraintData.pivotA,
  49137. localAnchorB: constraintData.pivotB
  49138. });
  49139. break;
  49140. case BABYLON.PhysicsJoint.LockJoint:
  49141. constraint = new CANNON.LockConstraint(mainBody, connectedBody, constraintData);
  49142. break;
  49143. case BABYLON.PhysicsJoint.PointToPointJoint:
  49144. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  49145. default:
  49146. constraint = new CANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  49147. break;
  49148. }
  49149. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  49150. constraint.collideConnected = !!jointData.collision;
  49151. impostorJoint.joint.physicsJoint = constraint;
  49152. //don't add spring as constraint, as it is not one.
  49153. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  49154. this.world.addConstraint(constraint);
  49155. }
  49156. else {
  49157. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  49158. constraint.applyForce();
  49159. });
  49160. }
  49161. };
  49162. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  49163. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  49164. };
  49165. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  49166. var index;
  49167. var mat;
  49168. for (index = 0; index < this._physicsMaterials.length; index++) {
  49169. mat = this._physicsMaterials[index];
  49170. if (mat.friction === friction && mat.restitution === restitution) {
  49171. return mat;
  49172. }
  49173. }
  49174. var currentMat = new CANNON.Material(name);
  49175. currentMat.friction = friction;
  49176. currentMat.restitution = restitution;
  49177. this._physicsMaterials.push(currentMat);
  49178. return currentMat;
  49179. };
  49180. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  49181. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  49182. };
  49183. CannonJSPlugin.prototype._createShape = function (impostor) {
  49184. var object = impostor.object;
  49185. var returnValue;
  49186. var extendSize = impostor.getObjectExtendSize();
  49187. switch (impostor.type) {
  49188. case BABYLON.PhysicsEngine.SphereImpostor:
  49189. var radiusX = extendSize.x;
  49190. var radiusY = extendSize.y;
  49191. var radiusZ = extendSize.z;
  49192. returnValue = new CANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  49193. break;
  49194. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  49195. case BABYLON.PhysicsImpostor.CylinderImpostor:
  49196. returnValue = new CANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  49197. break;
  49198. case BABYLON.PhysicsImpostor.BoxImpostor:
  49199. var box = extendSize.scale(0.5);
  49200. returnValue = new CANNON.Box(new CANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  49201. break;
  49202. case BABYLON.PhysicsImpostor.PlaneImpostor:
  49203. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  49204. returnValue = new CANNON.Plane();
  49205. break;
  49206. case BABYLON.PhysicsImpostor.MeshImpostor:
  49207. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  49208. var rawFaces = object.getIndices ? object.getIndices() : [];
  49209. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  49210. returnValue = new CANNON.Trimesh(rawVerts, rawFaces);
  49211. break;
  49212. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  49213. returnValue = this._createHeightmap(object);
  49214. break;
  49215. case BABYLON.PhysicsImpostor.ParticleImpostor:
  49216. returnValue = new CANNON.Particle();
  49217. break;
  49218. }
  49219. return returnValue;
  49220. };
  49221. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  49222. var pos = object.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  49223. var matrix = [];
  49224. //For now pointDepth will not be used and will be automatically calculated.
  49225. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  49226. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  49227. var dim = Math.min(object.getBoundingInfo().boundingBox.extendSize.x, object.getBoundingInfo().boundingBox.extendSize.z);
  49228. var elementSize = dim * 2 / arraySize;
  49229. var minY = object.getBoundingInfo().boundingBox.extendSize.y;
  49230. for (var i = 0; i < pos.length; i = i + 3) {
  49231. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  49232. var z = Math.round(((pos[i + 2]) / elementSize - arraySize / 2) * -1);
  49233. var y = pos[i + 1] + minY;
  49234. if (!matrix[x]) {
  49235. matrix[x] = [];
  49236. }
  49237. if (!matrix[x][z]) {
  49238. matrix[x][z] = y;
  49239. }
  49240. matrix[x][z] = Math.max(y, matrix[x][z]);
  49241. }
  49242. for (var x = 0; x <= arraySize; ++x) {
  49243. if (!matrix[x]) {
  49244. var loc = 1;
  49245. while (!matrix[(x + loc) % arraySize]) {
  49246. loc++;
  49247. }
  49248. matrix[x] = matrix[(x + loc) % arraySize].slice();
  49249. }
  49250. for (var z = 0; z <= arraySize; ++z) {
  49251. if (!matrix[x][z]) {
  49252. var loc = 1;
  49253. var newValue;
  49254. while (newValue === undefined) {
  49255. newValue = matrix[x][(z + loc++) % arraySize];
  49256. }
  49257. matrix[x][z] = newValue;
  49258. }
  49259. }
  49260. }
  49261. var shape = new CANNON.Heightfield(matrix, {
  49262. elementSize: elementSize
  49263. });
  49264. //For future reference, needed for body transformation
  49265. shape.minY = minY;
  49266. return shape;
  49267. };
  49268. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  49269. var object = impostor.object;
  49270. //make sure it is updated...
  49271. object.computeWorldMatrix && object.computeWorldMatrix(true);
  49272. // The delta between the mesh position and the mesh bounding box center
  49273. var center = impostor.getObjectCenter();
  49274. var extendSize = impostor.getObjectExtendSize();
  49275. this._tmpDeltaPosition.copyFrom(object.position.subtract(center));
  49276. this._tmpPosition.copyFrom(center);
  49277. var quaternion = object.rotationQuaternion;
  49278. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  49279. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  49280. //-90 DEG in X, precalculated
  49281. quaternion = quaternion.multiply(this._minus90X);
  49282. //Invert! (Precalculated, 90 deg in X)
  49283. //No need to clone. this will never change.
  49284. impostor.setDeltaRotation(this._plus90X);
  49285. }
  49286. //If it is a heightfield, if should be centered.
  49287. if (impostor.type === BABYLON.PhysicsEngine.HeightmapImpostor) {
  49288. var mesh = object;
  49289. //calculate the correct body position:
  49290. var rotationQuaternion = mesh.rotationQuaternion;
  49291. mesh.rotationQuaternion = this._tmpUnityRotation;
  49292. mesh.computeWorldMatrix(true);
  49293. //get original center with no rotation
  49294. var c = center.clone();
  49295. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  49296. //rotation is back
  49297. mesh.rotationQuaternion = rotationQuaternion;
  49298. //calculate the new center using a pivot (since Cannon.js doesn't center height maps)
  49299. var p = BABYLON.Matrix.Translation(mesh.getBoundingInfo().boundingBox.extendSize.x, 0, -mesh.getBoundingInfo().boundingBox.extendSize.z);
  49300. mesh.setPivotMatrix(p);
  49301. mesh.computeWorldMatrix(true);
  49302. //calculate the translation
  49303. var translation = mesh.getBoundingInfo().boundingBox.center.subtract(center).subtract(mesh.position).negate();
  49304. this._tmpPosition.copyFromFloats(translation.x, translation.y - mesh.getBoundingInfo().boundingBox.extendSize.y, translation.z);
  49305. //add it inverted to the delta
  49306. this._tmpDeltaPosition.copyFrom(mesh.getBoundingInfo().boundingBox.center.subtract(c));
  49307. this._tmpDeltaPosition.y += mesh.getBoundingInfo().boundingBox.extendSize.y;
  49308. mesh.setPivotMatrix(oldPivot);
  49309. mesh.computeWorldMatrix(true);
  49310. }
  49311. else if (impostor.type === BABYLON.PhysicsEngine.MeshImpostor) {
  49312. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  49313. this._tmpPosition.copyFrom(object.position);
  49314. }
  49315. impostor.setDeltaPosition(this._tmpDeltaPosition);
  49316. //Now update the impostor object
  49317. impostor.physicsBody.position.copy(this._tmpPosition);
  49318. impostor.physicsBody.quaternion.copy(quaternion);
  49319. };
  49320. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  49321. impostor.object.position.copyFrom(impostor.physicsBody.position);
  49322. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  49323. };
  49324. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  49325. impostor.physicsBody.position.copy(newPosition);
  49326. impostor.physicsBody.quaternion.copy(newRotation);
  49327. };
  49328. CannonJSPlugin.prototype.isSupported = function () {
  49329. return window.CANNON !== undefined;
  49330. };
  49331. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  49332. impostor.physicsBody.velocity.copy(velocity);
  49333. };
  49334. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  49335. impostor.physicsBody.angularVelocity.copy(velocity);
  49336. };
  49337. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  49338. var v = impostor.physicsBody.velocity;
  49339. if (!v)
  49340. return null;
  49341. return new BABYLON.Vector3(v.x, v.y, v.z);
  49342. };
  49343. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  49344. var v = impostor.physicsBody.angularVelocity;
  49345. if (!v)
  49346. return null;
  49347. return new BABYLON.Vector3(v.x, v.y, v.z);
  49348. };
  49349. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  49350. impostor.physicsBody.mass = mass;
  49351. impostor.physicsBody.updateMassProperties();
  49352. };
  49353. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  49354. impostor.physicsBody.sleep();
  49355. };
  49356. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  49357. impostor.physicsBody.wakeUp();
  49358. };
  49359. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  49360. joint.physicsJoint.distance = maxDistance;
  49361. };
  49362. CannonJSPlugin.prototype.enableMotor = function (joint, motorIndex) {
  49363. if (!motorIndex) {
  49364. joint.physicsJoint.enableMotor();
  49365. }
  49366. };
  49367. CannonJSPlugin.prototype.disableMotor = function (joint, motorIndex) {
  49368. if (!motorIndex) {
  49369. joint.physicsJoint.disableMotor();
  49370. }
  49371. };
  49372. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  49373. if (!motorIndex) {
  49374. joint.physicsJoint.enableMotor();
  49375. joint.physicsJoint.setMotorSpeed(speed);
  49376. if (maxForce) {
  49377. this.setLimit(joint, maxForce);
  49378. }
  49379. }
  49380. };
  49381. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  49382. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  49383. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  49384. };
  49385. CannonJSPlugin.prototype.dispose = function () {
  49386. //nothing to do, actually.
  49387. };
  49388. return CannonJSPlugin;
  49389. })();
  49390. BABYLON.CannonJSPlugin = CannonJSPlugin;
  49391. })(BABYLON || (BABYLON = {}));
  49392. var BABYLON;
  49393. (function (BABYLON) {
  49394. var OimoJSPlugin = (function () {
  49395. function OimoJSPlugin(iterations) {
  49396. this.name = "OimoJSPlugin";
  49397. this._tmpImpostorsArray = [];
  49398. this._tmpPositionVector = BABYLON.Vector3.Zero();
  49399. this.world = new OIMO.World(1 / 60, 2, iterations, true);
  49400. this.world.clear();
  49401. //making sure no stats are calculated
  49402. this.world.isNoStat = true;
  49403. }
  49404. OimoJSPlugin.prototype.setGravity = function (gravity) {
  49405. this.world.gravity.copy(gravity);
  49406. };
  49407. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  49408. this.world.timeStep = timeStep;
  49409. };
  49410. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  49411. var _this = this;
  49412. impostors.forEach(function (impostor) {
  49413. impostor.beforeStep();
  49414. });
  49415. this.world.step();
  49416. impostors.forEach(function (impostor) {
  49417. impostor.afterStep();
  49418. //update the ordered impostors array
  49419. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  49420. });
  49421. //check for collisions
  49422. var contact = this.world.contacts;
  49423. while (contact !== null) {
  49424. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  49425. contact = contact.next;
  49426. continue;
  49427. }
  49428. //is this body colliding with any other? get the impostor
  49429. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  49430. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  49431. if (!mainImpostor || !collidingImpostor) {
  49432. contact = contact.next;
  49433. continue;
  49434. }
  49435. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  49436. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  49437. contact = contact.next;
  49438. }
  49439. };
  49440. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  49441. var mass = impostor.physicsBody.massInfo.mass;
  49442. impostor.physicsBody.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  49443. };
  49444. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  49445. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  49446. this.applyImpulse(impostor, force, contactPoint);
  49447. };
  49448. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  49449. var _this = this;
  49450. //parent-child relationship. Does this impostor has a parent impostor?
  49451. if (impostor.parent) {
  49452. if (impostor.physicsBody) {
  49453. this.removePhysicsBody(impostor);
  49454. //TODO is that needed?
  49455. impostor.forceUpdate();
  49456. }
  49457. return;
  49458. }
  49459. if (impostor.isBodyInitRequired()) {
  49460. var bodyConfig = {
  49461. name: impostor.uniqueId,
  49462. //Oimo must have mass, also for static objects.
  49463. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  49464. size: [],
  49465. type: [],
  49466. pos: [],
  49467. rot: [],
  49468. move: impostor.getParam("mass") !== 0,
  49469. //Supporting older versions of Oimo
  49470. world: this.world
  49471. };
  49472. var impostors = [impostor];
  49473. function addToArray(parent) {
  49474. if (!parent.getChildMeshes)
  49475. return;
  49476. parent.getChildMeshes().forEach(function (m) {
  49477. if (m.physicsImpostor) {
  49478. impostors.push(m.physicsImpostor);
  49479. m.physicsImpostor._init();
  49480. }
  49481. });
  49482. }
  49483. addToArray(impostor.object);
  49484. function checkWithEpsilon(value) {
  49485. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  49486. }
  49487. impostors.forEach(function (i) {
  49488. //get the correct bounding box
  49489. var oldQuaternion = i.object.rotationQuaternion;
  49490. var rot = new OIMO.Euler().setFromQuaternion({
  49491. x: impostor.object.rotationQuaternion.x,
  49492. y: impostor.object.rotationQuaternion.y,
  49493. z: impostor.object.rotationQuaternion.z,
  49494. s: impostor.object.rotationQuaternion.w
  49495. });
  49496. var extendSize = i.getObjectExtendSize();
  49497. if (i === impostor) {
  49498. var center = impostor.getObjectCenter();
  49499. impostor.object.position.subtractToRef(center, _this._tmpPositionVector);
  49500. //Can also use Array.prototype.push.apply
  49501. bodyConfig.pos.push(center.x);
  49502. bodyConfig.pos.push(center.y);
  49503. bodyConfig.pos.push(center.z);
  49504. //tmp solution
  49505. bodyConfig.rot.push(rot.x / (OIMO.degtorad || OIMO.TO_RAD));
  49506. bodyConfig.rot.push(rot.y / (OIMO.degtorad || OIMO.TO_RAD));
  49507. bodyConfig.rot.push(rot.z / (OIMO.degtorad || OIMO.TO_RAD));
  49508. }
  49509. else {
  49510. bodyConfig.pos.push(i.object.position.x);
  49511. bodyConfig.pos.push(i.object.position.y);
  49512. bodyConfig.pos.push(i.object.position.z);
  49513. //tmp solution until https://github.com/lo-th/Oimo.js/pull/37 is merged
  49514. bodyConfig.rot.push(0);
  49515. bodyConfig.rot.push(0);
  49516. bodyConfig.rot.push(0);
  49517. }
  49518. // register mesh
  49519. switch (i.type) {
  49520. case BABYLON.PhysicsImpostor.ParticleImpostor:
  49521. BABYLON.Tools.Warn("No Particle support in Oimo.js. using SphereImpostor instead");
  49522. case BABYLON.PhysicsImpostor.SphereImpostor:
  49523. var radiusX = extendSize.x;
  49524. var radiusY = extendSize.y;
  49525. var radiusZ = extendSize.z;
  49526. var size = Math.max(checkWithEpsilon(radiusX), checkWithEpsilon(radiusY), checkWithEpsilon(radiusZ)) / 2;
  49527. bodyConfig.type.push('sphere');
  49528. //due to the way oimo works with compounds, add 3 times
  49529. bodyConfig.size.push(size);
  49530. bodyConfig.size.push(size);
  49531. bodyConfig.size.push(size);
  49532. break;
  49533. case BABYLON.PhysicsImpostor.CylinderImpostor:
  49534. var sizeX = checkWithEpsilon(extendSize.x) / 2;
  49535. var sizeY = checkWithEpsilon(extendSize.y);
  49536. bodyConfig.type.push('cylinder');
  49537. bodyConfig.size.push(sizeX);
  49538. bodyConfig.size.push(sizeY);
  49539. //due to the way oimo works with compounds, add one more value.
  49540. bodyConfig.size.push(sizeY);
  49541. break;
  49542. case BABYLON.PhysicsImpostor.PlaneImpostor:
  49543. case BABYLON.PhysicsImpostor.BoxImpostor:
  49544. default:
  49545. var sizeX = checkWithEpsilon(extendSize.x);
  49546. var sizeY = checkWithEpsilon(extendSize.y);
  49547. var sizeZ = checkWithEpsilon(extendSize.z);
  49548. bodyConfig.type.push('box');
  49549. bodyConfig.size.push(sizeX);
  49550. bodyConfig.size.push(sizeY);
  49551. bodyConfig.size.push(sizeZ);
  49552. break;
  49553. }
  49554. //actually not needed, but hey...
  49555. i.object.rotationQuaternion = oldQuaternion;
  49556. });
  49557. impostor.physicsBody = new OIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  49558. }
  49559. else {
  49560. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  49561. }
  49562. impostor.setDeltaPosition(this._tmpPositionVector);
  49563. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  49564. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  49565. };
  49566. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  49567. //impostor.physicsBody.dispose();
  49568. //Same as : (older oimo versions)
  49569. this.world.removeRigidBody(impostor.physicsBody);
  49570. };
  49571. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  49572. var mainBody = impostorJoint.mainImpostor.physicsBody;
  49573. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  49574. if (!mainBody || !connectedBody) {
  49575. return;
  49576. }
  49577. var jointData = impostorJoint.joint.jointData;
  49578. var options = jointData.nativeParams || {};
  49579. var type;
  49580. var nativeJointData = {
  49581. body1: mainBody,
  49582. body2: connectedBody,
  49583. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  49584. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  49585. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  49586. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  49587. min: options.min,
  49588. max: options.max,
  49589. collision: options.collision || jointData.collision,
  49590. spring: options.spring,
  49591. //supporting older version of Oimo
  49592. world: this.world
  49593. };
  49594. switch (impostorJoint.joint.type) {
  49595. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  49596. type = "jointBall";
  49597. break;
  49598. case BABYLON.PhysicsJoint.SpringJoint:
  49599. BABYLON.Tools.Warn("Oimo.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  49600. var springData = jointData;
  49601. nativeJointData.min = springData.length || nativeJointData.min;
  49602. //Max should also be set, just make sure it is at least min
  49603. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  49604. case BABYLON.PhysicsJoint.DistanceJoint:
  49605. type = "jointDistance";
  49606. nativeJointData.max = jointData.maxDistance;
  49607. break;
  49608. case BABYLON.PhysicsJoint.PrismaticJoint:
  49609. type = "jointPrisme";
  49610. break;
  49611. case BABYLON.PhysicsJoint.SliderJoint:
  49612. type = "jointSlide";
  49613. break;
  49614. case BABYLON.PhysicsJoint.WheelJoint:
  49615. type = "jointWheel";
  49616. break;
  49617. case BABYLON.PhysicsJoint.HingeJoint:
  49618. default:
  49619. type = "jointHinge";
  49620. break;
  49621. }
  49622. nativeJointData.type = type;
  49623. impostorJoint.joint.physicsJoint = new OIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  49624. };
  49625. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  49626. //Bug in Oimo prevents us from disposing a joint in the playground
  49627. //joint.joint.physicsJoint.dispose();
  49628. //So we will bruteforce it!
  49629. try {
  49630. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  49631. }
  49632. catch (e) {
  49633. BABYLON.Tools.Warn(e);
  49634. }
  49635. };
  49636. OimoJSPlugin.prototype.isSupported = function () {
  49637. return OIMO !== undefined;
  49638. };
  49639. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  49640. if (!impostor.physicsBody.sleeping) {
  49641. //TODO check that
  49642. if (impostor.physicsBody.shapes.next) {
  49643. var parentShape = this._getLastShape(impostor.physicsBody);
  49644. impostor.object.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  49645. impostor.object.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  49646. impostor.object.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  49647. }
  49648. else {
  49649. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  49650. }
  49651. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  49652. impostor.object.rotationQuaternion.normalize();
  49653. }
  49654. };
  49655. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  49656. var body = impostor.physicsBody;
  49657. body.position.init(newPosition.x * OIMO.INV_SCALE, newPosition.y * OIMO.INV_SCALE, newPosition.z * OIMO.INV_SCALE);
  49658. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  49659. body.syncShapes();
  49660. body.awake();
  49661. };
  49662. OimoJSPlugin.prototype._getLastShape = function (body) {
  49663. var lastShape = body.shapes;
  49664. while (lastShape.next) {
  49665. lastShape = lastShape.next;
  49666. }
  49667. return lastShape;
  49668. };
  49669. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  49670. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  49671. };
  49672. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  49673. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  49674. };
  49675. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  49676. var v = impostor.physicsBody.linearVelocity;
  49677. if (!v)
  49678. return null;
  49679. return new BABYLON.Vector3(v.x, v.y, v.z);
  49680. };
  49681. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  49682. var v = impostor.physicsBody.angularVelocity;
  49683. if (!v)
  49684. return null;
  49685. return new BABYLON.Vector3(v.x, v.y, v.z);
  49686. };
  49687. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  49688. var staticBody = mass === 0;
  49689. //this will actually set the body's density and not its mass.
  49690. //But this is how oimo treats the mass variable.
  49691. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  49692. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  49693. };
  49694. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  49695. impostor.physicsBody.sleep();
  49696. };
  49697. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  49698. impostor.physicsBody.awake();
  49699. };
  49700. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  49701. joint.physicsJoint.limitMotoe.upperLimit = maxDistance;
  49702. if (minDistance !== void 0) {
  49703. joint.physicsJoint.limitMotoe.lowerLimit = minDistance;
  49704. }
  49705. };
  49706. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  49707. //TODO separate rotational and transational motors.
  49708. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  49709. if (motor) {
  49710. motor.setMotor(speed, maxForce);
  49711. }
  49712. };
  49713. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  49714. //TODO separate rotational and transational motors.
  49715. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  49716. if (motor) {
  49717. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  49718. }
  49719. };
  49720. OimoJSPlugin.prototype.dispose = function () {
  49721. this.world.clear();
  49722. };
  49723. return OimoJSPlugin;
  49724. })();
  49725. BABYLON.OimoJSPlugin = OimoJSPlugin;
  49726. })(BABYLON || (BABYLON = {}));
  49727. var BABYLON;
  49728. (function (BABYLON) {
  49729. var DisplayPassPostProcess = (function (_super) {
  49730. __extends(DisplayPassPostProcess, _super);
  49731. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  49732. _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable);
  49733. }
  49734. return DisplayPassPostProcess;
  49735. })(BABYLON.PostProcess);
  49736. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  49737. })(BABYLON || (BABYLON = {}));
  49738. var BABYLON;
  49739. (function (BABYLON) {
  49740. var SimplificationSettings = (function () {
  49741. function SimplificationSettings(quality, distance, optimizeMesh) {
  49742. this.quality = quality;
  49743. this.distance = distance;
  49744. this.optimizeMesh = optimizeMesh;
  49745. }
  49746. return SimplificationSettings;
  49747. })();
  49748. BABYLON.SimplificationSettings = SimplificationSettings;
  49749. var SimplificationQueue = (function () {
  49750. function SimplificationQueue() {
  49751. this.running = false;
  49752. this._simplificationArray = [];
  49753. }
  49754. SimplificationQueue.prototype.addTask = function (task) {
  49755. this._simplificationArray.push(task);
  49756. };
  49757. SimplificationQueue.prototype.executeNext = function () {
  49758. var task = this._simplificationArray.pop();
  49759. if (task) {
  49760. this.running = true;
  49761. this.runSimplification(task);
  49762. }
  49763. else {
  49764. this.running = false;
  49765. }
  49766. };
  49767. SimplificationQueue.prototype.runSimplification = function (task) {
  49768. var _this = this;
  49769. if (task.parallelProcessing) {
  49770. //parallel simplifier
  49771. task.settings.forEach(function (setting) {
  49772. var simplifier = _this.getSimplifier(task);
  49773. simplifier.simplify(setting, function (newMesh) {
  49774. task.mesh.addLODLevel(setting.distance, newMesh);
  49775. newMesh.isVisible = true;
  49776. //check if it is the last
  49777. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  49778. //all done, run the success callback.
  49779. task.successCallback();
  49780. }
  49781. _this.executeNext();
  49782. });
  49783. });
  49784. }
  49785. else {
  49786. //single simplifier.
  49787. var simplifier = this.getSimplifier(task);
  49788. var runDecimation = function (setting, callback) {
  49789. simplifier.simplify(setting, function (newMesh) {
  49790. task.mesh.addLODLevel(setting.distance, newMesh);
  49791. newMesh.isVisible = true;
  49792. //run the next quality level
  49793. callback();
  49794. });
  49795. };
  49796. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  49797. runDecimation(task.settings[loop.index], function () {
  49798. loop.executeNext();
  49799. });
  49800. }, function () {
  49801. //execution ended, run the success callback.
  49802. if (task.successCallback) {
  49803. task.successCallback();
  49804. }
  49805. _this.executeNext();
  49806. });
  49807. }
  49808. };
  49809. SimplificationQueue.prototype.getSimplifier = function (task) {
  49810. switch (task.simplificationType) {
  49811. case SimplificationType.QUADRATIC:
  49812. default:
  49813. return new QuadraticErrorSimplification(task.mesh);
  49814. }
  49815. };
  49816. return SimplificationQueue;
  49817. })();
  49818. BABYLON.SimplificationQueue = SimplificationQueue;
  49819. /**
  49820. * The implemented types of simplification.
  49821. * At the moment only Quadratic Error Decimation is implemented.
  49822. */
  49823. (function (SimplificationType) {
  49824. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  49825. })(BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  49826. var SimplificationType = BABYLON.SimplificationType;
  49827. var DecimationTriangle = (function () {
  49828. function DecimationTriangle(vertices) {
  49829. this.vertices = vertices;
  49830. this.error = new Array(4);
  49831. this.deleted = false;
  49832. this.isDirty = false;
  49833. this.deletePending = false;
  49834. this.borderFactor = 0;
  49835. }
  49836. return DecimationTriangle;
  49837. })();
  49838. BABYLON.DecimationTriangle = DecimationTriangle;
  49839. var DecimationVertex = (function () {
  49840. function DecimationVertex(position, id) {
  49841. this.position = position;
  49842. this.id = id;
  49843. this.isBorder = true;
  49844. this.q = new QuadraticMatrix();
  49845. this.triangleCount = 0;
  49846. this.triangleStart = 0;
  49847. this.originalOffsets = [];
  49848. }
  49849. DecimationVertex.prototype.updatePosition = function (newPosition) {
  49850. this.position.copyFrom(newPosition);
  49851. };
  49852. return DecimationVertex;
  49853. })();
  49854. BABYLON.DecimationVertex = DecimationVertex;
  49855. var QuadraticMatrix = (function () {
  49856. function QuadraticMatrix(data) {
  49857. this.data = new Array(10);
  49858. for (var i = 0; i < 10; ++i) {
  49859. if (data && data[i]) {
  49860. this.data[i] = data[i];
  49861. }
  49862. else {
  49863. this.data[i] = 0;
  49864. }
  49865. }
  49866. }
  49867. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  49868. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  49869. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  49870. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  49871. return det;
  49872. };
  49873. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  49874. for (var i = 0; i < 10; ++i) {
  49875. this.data[i] += matrix.data[i];
  49876. }
  49877. };
  49878. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  49879. for (var i = 0; i < 10; ++i) {
  49880. this.data[i] += data[i];
  49881. }
  49882. };
  49883. QuadraticMatrix.prototype.add = function (matrix) {
  49884. var m = new QuadraticMatrix();
  49885. for (var i = 0; i < 10; ++i) {
  49886. m.data[i] = this.data[i] + matrix.data[i];
  49887. }
  49888. return m;
  49889. };
  49890. QuadraticMatrix.FromData = function (a, b, c, d) {
  49891. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  49892. };
  49893. //returning an array to avoid garbage collection
  49894. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  49895. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  49896. };
  49897. return QuadraticMatrix;
  49898. })();
  49899. BABYLON.QuadraticMatrix = QuadraticMatrix;
  49900. var Reference = (function () {
  49901. function Reference(vertexId, triangleId) {
  49902. this.vertexId = vertexId;
  49903. this.triangleId = triangleId;
  49904. }
  49905. return Reference;
  49906. })();
  49907. BABYLON.Reference = Reference;
  49908. /**
  49909. * An implementation of the Quadratic Error simplification algorithm.
  49910. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  49911. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  49912. * @author RaananW
  49913. */
  49914. var QuadraticErrorSimplification = (function () {
  49915. function QuadraticErrorSimplification(_mesh) {
  49916. this._mesh = _mesh;
  49917. this.initialized = false;
  49918. this.syncIterations = 5000;
  49919. this.aggressiveness = 7;
  49920. this.decimationIterations = 100;
  49921. this.boundingBoxEpsilon = BABYLON.Epsilon;
  49922. }
  49923. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  49924. var _this = this;
  49925. this.initDecimatedMesh();
  49926. //iterating through the submeshes array, one after the other.
  49927. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  49928. _this.initWithMesh(loop.index, function () {
  49929. _this.runDecimation(settings, loop.index, function () {
  49930. loop.executeNext();
  49931. });
  49932. }, settings.optimizeMesh);
  49933. }, function () {
  49934. setTimeout(function () {
  49935. successCallback(_this._reconstructedMesh);
  49936. }, 0);
  49937. });
  49938. };
  49939. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  49940. var _this = this;
  49941. var gCount = 0;
  49942. triangle.vertices.forEach(function (vertex) {
  49943. var count = 0;
  49944. var vPos = vertex.position;
  49945. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  49946. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  49947. ++count;
  49948. if (bbox.maximum.y === vPos.y || vPos.y === bbox.minimum.y)
  49949. ++count;
  49950. if (bbox.maximum.z === vPos.z || vPos.z === bbox.minimum.z)
  49951. ++count;
  49952. if (count > 1) {
  49953. ++gCount;
  49954. }
  49955. ;
  49956. });
  49957. if (gCount > 1) {
  49958. console.log(triangle, gCount);
  49959. }
  49960. return gCount > 1;
  49961. };
  49962. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  49963. var _this = this;
  49964. var targetCount = ~~(this.triangles.length * settings.quality);
  49965. var deletedTriangles = 0;
  49966. var triangleCount = this.triangles.length;
  49967. var iterationFunction = function (iteration, callback) {
  49968. setTimeout(function () {
  49969. if (iteration % 5 === 0) {
  49970. _this.updateMesh(iteration === 0);
  49971. }
  49972. for (var i = 0; i < _this.triangles.length; ++i) {
  49973. _this.triangles[i].isDirty = false;
  49974. }
  49975. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  49976. var trianglesIterator = function (i) {
  49977. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  49978. var t = _this.triangles[tIdx];
  49979. if (!t)
  49980. return;
  49981. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  49982. return;
  49983. }
  49984. for (var j = 0; j < 3; ++j) {
  49985. if (t.error[j] < threshold) {
  49986. var deleted0 = [];
  49987. var deleted1 = [];
  49988. var v0 = t.vertices[j];
  49989. var v1 = t.vertices[(j + 1) % 3];
  49990. if (v0.isBorder || v1.isBorder)
  49991. continue;
  49992. var p = BABYLON.Vector3.Zero();
  49993. var n = BABYLON.Vector3.Zero();
  49994. var uv = BABYLON.Vector2.Zero();
  49995. var color = new BABYLON.Color4(0, 0, 0, 1);
  49996. _this.calculateError(v0, v1, p, n, uv, color);
  49997. var delTr = [];
  49998. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  49999. continue;
  50000. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  50001. continue;
  50002. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  50003. continue;
  50004. var uniqueArray = [];
  50005. delTr.forEach(function (deletedT) {
  50006. if (uniqueArray.indexOf(deletedT) === -1) {
  50007. deletedT.deletePending = true;
  50008. uniqueArray.push(deletedT);
  50009. }
  50010. });
  50011. if (uniqueArray.length % 2 !== 0) {
  50012. continue;
  50013. }
  50014. v0.q = v1.q.add(v0.q);
  50015. v0.updatePosition(p);
  50016. var tStart = _this.references.length;
  50017. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  50018. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  50019. var tCount = _this.references.length - tStart;
  50020. if (tCount <= v0.triangleCount) {
  50021. if (tCount) {
  50022. for (var c = 0; c < tCount; c++) {
  50023. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  50024. }
  50025. }
  50026. }
  50027. else {
  50028. v0.triangleStart = tStart;
  50029. }
  50030. v0.triangleCount = tCount;
  50031. break;
  50032. }
  50033. }
  50034. };
  50035. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  50036. }, 0);
  50037. };
  50038. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  50039. if (triangleCount - deletedTriangles <= targetCount)
  50040. loop.breakLoop();
  50041. else {
  50042. iterationFunction(loop.index, function () {
  50043. loop.executeNext();
  50044. });
  50045. }
  50046. }, function () {
  50047. setTimeout(function () {
  50048. //reconstruct this part of the mesh
  50049. _this.reconstructMesh(submeshIndex);
  50050. successCallback();
  50051. }, 0);
  50052. });
  50053. };
  50054. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  50055. var _this = this;
  50056. this.vertices = [];
  50057. this.triangles = [];
  50058. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  50059. var indices = this._mesh.getIndices();
  50060. var submesh = this._mesh.subMeshes[submeshIndex];
  50061. var findInVertices = function (positionToSearch) {
  50062. if (optimizeMesh) {
  50063. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  50064. if (_this.vertices[ii].position.equals(positionToSearch)) {
  50065. return _this.vertices[ii];
  50066. }
  50067. }
  50068. }
  50069. return null;
  50070. };
  50071. var vertexReferences = [];
  50072. var vertexInit = function (i) {
  50073. var offset = i + submesh.verticesStart;
  50074. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  50075. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  50076. vertex.originalOffsets.push(offset);
  50077. if (vertex.id === _this.vertices.length) {
  50078. _this.vertices.push(vertex);
  50079. }
  50080. vertexReferences.push(vertex.id);
  50081. };
  50082. //var totalVertices = mesh.getTotalVertices();
  50083. var totalVertices = submesh.verticesCount;
  50084. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  50085. var indicesInit = function (i) {
  50086. var offset = (submesh.indexStart / 3) + i;
  50087. var pos = (offset * 3);
  50088. var i0 = indices[pos + 0];
  50089. var i1 = indices[pos + 1];
  50090. var i2 = indices[pos + 2];
  50091. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  50092. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  50093. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  50094. var triangle = new DecimationTriangle([v0, v1, v2]);
  50095. triangle.originalOffset = pos;
  50096. _this.triangles.push(triangle);
  50097. };
  50098. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  50099. _this.init(callback);
  50100. });
  50101. });
  50102. };
  50103. QuadraticErrorSimplification.prototype.init = function (callback) {
  50104. var _this = this;
  50105. var triangleInit1 = function (i) {
  50106. var t = _this.triangles[i];
  50107. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  50108. for (var j = 0; j < 3; j++) {
  50109. 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))));
  50110. }
  50111. };
  50112. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  50113. var triangleInit2 = function (i) {
  50114. var t = _this.triangles[i];
  50115. for (var j = 0; j < 3; ++j) {
  50116. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  50117. }
  50118. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  50119. };
  50120. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  50121. _this.initialized = true;
  50122. callback();
  50123. });
  50124. });
  50125. };
  50126. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  50127. var newTriangles = [];
  50128. var i;
  50129. for (i = 0; i < this.vertices.length; ++i) {
  50130. this.vertices[i].triangleCount = 0;
  50131. }
  50132. var t;
  50133. var j;
  50134. for (i = 0; i < this.triangles.length; ++i) {
  50135. if (!this.triangles[i].deleted) {
  50136. t = this.triangles[i];
  50137. for (j = 0; j < 3; ++j) {
  50138. t.vertices[j].triangleCount = 1;
  50139. }
  50140. newTriangles.push(t);
  50141. }
  50142. }
  50143. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  50144. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  50145. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  50146. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  50147. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  50148. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  50149. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  50150. var vertexCount = 0;
  50151. for (i = 0; i < this.vertices.length; ++i) {
  50152. var vertex = this.vertices[i];
  50153. vertex.id = vertexCount;
  50154. if (vertex.triangleCount) {
  50155. vertex.originalOffsets.forEach(function (originalOffset) {
  50156. newPositionData.push(vertex.position.x);
  50157. newPositionData.push(vertex.position.y);
  50158. newPositionData.push(vertex.position.z);
  50159. newNormalData.push(normalData[originalOffset * 3]);
  50160. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  50161. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  50162. if (uvs && uvs.length) {
  50163. newUVsData.push(uvs[(originalOffset * 2)]);
  50164. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  50165. }
  50166. else if (colorsData && colorsData.length) {
  50167. newColorsData.push(colorsData[(originalOffset * 4)]);
  50168. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  50169. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  50170. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  50171. }
  50172. ++vertexCount;
  50173. });
  50174. }
  50175. }
  50176. var startingIndex = this._reconstructedMesh.getTotalIndices();
  50177. var startingVertex = this._reconstructedMesh.getTotalVertices();
  50178. var submeshesArray = this._reconstructedMesh.subMeshes;
  50179. this._reconstructedMesh.subMeshes = [];
  50180. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  50181. var originalIndices = this._mesh.getIndices();
  50182. for (i = 0; i < newTriangles.length; ++i) {
  50183. t = newTriangles[i]; //now get the new referencing point for each vertex
  50184. [0, 1, 2].forEach(function (idx) {
  50185. var id = originalIndices[t.originalOffset + idx];
  50186. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  50187. if (offset < 0)
  50188. offset = 0;
  50189. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  50190. });
  50191. }
  50192. //overwriting the old vertex buffers and indices.
  50193. this._reconstructedMesh.setIndices(newIndicesArray);
  50194. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  50195. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  50196. if (newUVsData.length > 0)
  50197. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  50198. if (newColorsData.length > 0)
  50199. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  50200. //create submesh
  50201. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  50202. if (submeshIndex > 0) {
  50203. this._reconstructedMesh.subMeshes = [];
  50204. submeshesArray.forEach(function (submesh) {
  50205. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  50206. });
  50207. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  50208. }
  50209. };
  50210. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  50211. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  50212. this._reconstructedMesh.material = this._mesh.material;
  50213. this._reconstructedMesh.parent = this._mesh.parent;
  50214. this._reconstructedMesh.isVisible = false;
  50215. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  50216. };
  50217. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  50218. for (var i = 0; i < vertex1.triangleCount; ++i) {
  50219. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  50220. if (t.deleted)
  50221. continue;
  50222. var s = this.references[vertex1.triangleStart + i].vertexId;
  50223. var v1 = t.vertices[(s + 1) % 3];
  50224. var v2 = t.vertices[(s + 2) % 3];
  50225. if ((v1 === vertex2 || v2 === vertex2) /* && !this.isTriangleOnBoundingBox(t)*/) {
  50226. deletedArray[i] = true;
  50227. delTr.push(t);
  50228. continue;
  50229. }
  50230. var d1 = v1.position.subtract(point);
  50231. d1 = d1.normalize();
  50232. var d2 = v2.position.subtract(point);
  50233. d2 = d2.normalize();
  50234. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  50235. return true;
  50236. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  50237. deletedArray[i] = false;
  50238. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  50239. return true;
  50240. }
  50241. return false;
  50242. };
  50243. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  50244. var newDeleted = deletedTriangles;
  50245. for (var i = 0; i < vertex.triangleCount; ++i) {
  50246. var ref = this.references[vertex.triangleStart + i];
  50247. var t = this.triangles[ref.triangleId];
  50248. if (t.deleted)
  50249. continue;
  50250. if (deletedArray[i] && t.deletePending) {
  50251. t.deleted = true;
  50252. newDeleted++;
  50253. continue;
  50254. }
  50255. t.vertices[ref.vertexId] = origVertex;
  50256. t.isDirty = true;
  50257. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  50258. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  50259. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  50260. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  50261. this.references.push(ref);
  50262. }
  50263. return newDeleted;
  50264. };
  50265. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  50266. for (var i = 0; i < this.vertices.length; ++i) {
  50267. var vCount = [];
  50268. var vId = [];
  50269. var v = this.vertices[i];
  50270. var j;
  50271. for (j = 0; j < v.triangleCount; ++j) {
  50272. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  50273. for (var ii = 0; ii < 3; ii++) {
  50274. var ofs = 0;
  50275. var vv = triangle.vertices[ii];
  50276. while (ofs < vCount.length) {
  50277. if (vId[ofs] === vv.id)
  50278. break;
  50279. ++ofs;
  50280. }
  50281. if (ofs === vCount.length) {
  50282. vCount.push(1);
  50283. vId.push(vv.id);
  50284. }
  50285. else {
  50286. vCount[ofs]++;
  50287. }
  50288. }
  50289. }
  50290. for (j = 0; j < vCount.length; ++j) {
  50291. if (vCount[j] === 1) {
  50292. this.vertices[vId[j]].isBorder = true;
  50293. }
  50294. else {
  50295. this.vertices[vId[j]].isBorder = false;
  50296. }
  50297. }
  50298. }
  50299. };
  50300. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  50301. if (identifyBorders === void 0) { identifyBorders = false; }
  50302. var i;
  50303. if (!identifyBorders) {
  50304. var newTrianglesVector = [];
  50305. for (i = 0; i < this.triangles.length; ++i) {
  50306. if (!this.triangles[i].deleted) {
  50307. newTrianglesVector.push(this.triangles[i]);
  50308. }
  50309. }
  50310. this.triangles = newTrianglesVector;
  50311. }
  50312. for (i = 0; i < this.vertices.length; ++i) {
  50313. this.vertices[i].triangleCount = 0;
  50314. this.vertices[i].triangleStart = 0;
  50315. }
  50316. var t;
  50317. var j;
  50318. var v;
  50319. for (i = 0; i < this.triangles.length; ++i) {
  50320. t = this.triangles[i];
  50321. for (j = 0; j < 3; ++j) {
  50322. v = t.vertices[j];
  50323. v.triangleCount++;
  50324. }
  50325. }
  50326. var tStart = 0;
  50327. for (i = 0; i < this.vertices.length; ++i) {
  50328. this.vertices[i].triangleStart = tStart;
  50329. tStart += this.vertices[i].triangleCount;
  50330. this.vertices[i].triangleCount = 0;
  50331. }
  50332. var newReferences = new Array(this.triangles.length * 3);
  50333. for (i = 0; i < this.triangles.length; ++i) {
  50334. t = this.triangles[i];
  50335. for (j = 0; j < 3; ++j) {
  50336. v = t.vertices[j];
  50337. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  50338. v.triangleCount++;
  50339. }
  50340. }
  50341. this.references = newReferences;
  50342. if (identifyBorders) {
  50343. this.identifyBorder();
  50344. }
  50345. };
  50346. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  50347. var x = point.x;
  50348. var y = point.y;
  50349. var z = point.z;
  50350. 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
  50351. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  50352. };
  50353. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  50354. var q = vertex1.q.add(vertex2.q);
  50355. var border = vertex1.isBorder && vertex2.isBorder;
  50356. var error = 0;
  50357. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  50358. if (qDet !== 0 && !border) {
  50359. if (!pointResult) {
  50360. pointResult = BABYLON.Vector3.Zero();
  50361. }
  50362. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  50363. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  50364. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  50365. error = this.vertexError(q, pointResult);
  50366. }
  50367. else {
  50368. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  50369. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  50370. var error1 = this.vertexError(q, vertex1.position);
  50371. var error2 = this.vertexError(q, vertex2.position);
  50372. var error3 = this.vertexError(q, p3);
  50373. error = Math.min(error1, error2, error3);
  50374. if (error === error1) {
  50375. if (pointResult) {
  50376. pointResult.copyFrom(vertex1.position);
  50377. }
  50378. }
  50379. else if (error === error2) {
  50380. if (pointResult) {
  50381. pointResult.copyFrom(vertex2.position);
  50382. }
  50383. }
  50384. else {
  50385. if (pointResult) {
  50386. pointResult.copyFrom(p3);
  50387. }
  50388. }
  50389. }
  50390. return error;
  50391. };
  50392. return QuadraticErrorSimplification;
  50393. })();
  50394. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  50395. })(BABYLON || (BABYLON = {}));
  50396. var BABYLON;
  50397. (function (BABYLON) {
  50398. var serializedGeometries = [];
  50399. var serializeGeometry = function (geometry, serializationGeometries) {
  50400. if (serializedGeometries[geometry.id]) {
  50401. return;
  50402. }
  50403. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  50404. serializationGeometries.boxes.push(geometry.serialize());
  50405. }
  50406. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  50407. serializationGeometries.spheres.push(geometry.serialize());
  50408. }
  50409. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  50410. serializationGeometries.cylinders.push(geometry.serialize());
  50411. }
  50412. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  50413. serializationGeometries.toruses.push(geometry.serialize());
  50414. }
  50415. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  50416. serializationGeometries.grounds.push(geometry.serialize());
  50417. }
  50418. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  50419. serializationGeometries.planes.push(geometry.serialize());
  50420. }
  50421. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  50422. serializationGeometries.torusKnots.push(geometry.serialize());
  50423. }
  50424. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  50425. throw new Error("Unknown primitive type");
  50426. }
  50427. else {
  50428. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  50429. }
  50430. serializedGeometries[geometry.id] = true;
  50431. };
  50432. var serializeMesh = function (mesh, serializationScene) {
  50433. var serializationObject = {};
  50434. serializationObject.name = mesh.name;
  50435. serializationObject.id = mesh.id;
  50436. if (BABYLON.Tags.HasTags(mesh)) {
  50437. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  50438. }
  50439. serializationObject.position = mesh.position.asArray();
  50440. if (mesh.rotationQuaternion) {
  50441. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  50442. }
  50443. else if (mesh.rotation) {
  50444. serializationObject.rotation = mesh.rotation.asArray();
  50445. }
  50446. serializationObject.scaling = mesh.scaling.asArray();
  50447. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  50448. serializationObject.isEnabled = mesh.isEnabled();
  50449. serializationObject.isVisible = mesh.isVisible;
  50450. serializationObject.infiniteDistance = mesh.infiniteDistance;
  50451. serializationObject.pickable = mesh.isPickable;
  50452. serializationObject.receiveShadows = mesh.receiveShadows;
  50453. serializationObject.billboardMode = mesh.billboardMode;
  50454. serializationObject.visibility = mesh.visibility;
  50455. serializationObject.checkCollisions = mesh.checkCollisions;
  50456. // Parent
  50457. if (mesh.parent) {
  50458. serializationObject.parentId = mesh.parent.id;
  50459. }
  50460. // Geometry
  50461. var geometry = mesh._geometry;
  50462. if (geometry) {
  50463. var geometryId = geometry.id;
  50464. serializationObject.geometryId = geometryId;
  50465. if (!mesh.getScene().getGeometryByID(geometryId)) {
  50466. // 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
  50467. serializeGeometry(geometry, serializationScene.geometries);
  50468. }
  50469. // SubMeshes
  50470. serializationObject.subMeshes = [];
  50471. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  50472. var subMesh = mesh.subMeshes[subIndex];
  50473. serializationObject.subMeshes.push({
  50474. materialIndex: subMesh.materialIndex,
  50475. verticesStart: subMesh.verticesStart,
  50476. verticesCount: subMesh.verticesCount,
  50477. indexStart: subMesh.indexStart,
  50478. indexCount: subMesh.indexCount
  50479. });
  50480. }
  50481. }
  50482. // Material
  50483. if (mesh.material) {
  50484. serializationObject.materialId = mesh.material.id;
  50485. }
  50486. else {
  50487. mesh.material = null;
  50488. }
  50489. // Skeleton
  50490. if (mesh.skeleton) {
  50491. serializationObject.skeletonId = mesh.skeleton.id;
  50492. }
  50493. // Physics
  50494. //TODO implement correct serialization for physics impostors.
  50495. if (mesh.getPhysicsImpostor()) {
  50496. serializationObject.physicsMass = mesh.getPhysicsMass();
  50497. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  50498. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  50499. serializationObject.physicsImpostor = mesh.getPhysicsImpostor().type;
  50500. }
  50501. // Instances
  50502. serializationObject.instances = [];
  50503. for (var index = 0; index < mesh.instances.length; index++) {
  50504. var instance = mesh.instances[index];
  50505. var serializationInstance = {
  50506. name: instance.name,
  50507. position: instance.position.asArray(),
  50508. scaling: instance.scaling.asArray()
  50509. };
  50510. if (instance.rotationQuaternion) {
  50511. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  50512. }
  50513. else if (instance.rotation) {
  50514. serializationInstance.rotation = instance.rotation.asArray();
  50515. }
  50516. serializationObject.instances.push(serializationInstance);
  50517. // Animations
  50518. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  50519. serializationInstance.ranges = instance.serializeAnimationRanges();
  50520. }
  50521. // Animations
  50522. BABYLON.Animation.AppendSerializedAnimations(mesh, serializationObject);
  50523. serializationObject.ranges = mesh.serializeAnimationRanges();
  50524. // Layer mask
  50525. serializationObject.layerMask = mesh.layerMask;
  50526. // Action Manager
  50527. if (mesh.actionManager) {
  50528. serializationObject.actions = mesh.actionManager.serialize(mesh.name);
  50529. }
  50530. return serializationObject;
  50531. };
  50532. var finalizeSingleMesh = function (mesh, serializationObject) {
  50533. //only works if the mesh is already loaded
  50534. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  50535. //serialize material
  50536. if (mesh.material) {
  50537. if (mesh.material instanceof BABYLON.StandardMaterial) {
  50538. serializationObject.materials = serializationObject.materials || [];
  50539. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  50540. serializationObject.materials.push(mesh.material.serialize());
  50541. }
  50542. }
  50543. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  50544. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  50545. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  50546. serializationObject.multiMaterials.push(mesh.material.serialize());
  50547. }
  50548. }
  50549. }
  50550. //serialize geometry
  50551. var geometry = mesh._geometry;
  50552. if (geometry) {
  50553. if (!serializationObject.geometries) {
  50554. serializationObject.geometries = {};
  50555. serializationObject.geometries.boxes = [];
  50556. serializationObject.geometries.spheres = [];
  50557. serializationObject.geometries.cylinders = [];
  50558. serializationObject.geometries.toruses = [];
  50559. serializationObject.geometries.grounds = [];
  50560. serializationObject.geometries.planes = [];
  50561. serializationObject.geometries.torusKnots = [];
  50562. serializationObject.geometries.vertexData = [];
  50563. }
  50564. serializeGeometry(geometry, serializationObject.geometries);
  50565. }
  50566. // Skeletons
  50567. if (mesh.skeleton) {
  50568. serializationObject.skeletons = serializationObject.skeletons || [];
  50569. serializationObject.skeletons.push(mesh.skeleton.serialize());
  50570. }
  50571. //serialize the actual mesh
  50572. serializationObject.meshes = serializationObject.meshes || [];
  50573. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  50574. }
  50575. };
  50576. var SceneSerializer = (function () {
  50577. function SceneSerializer() {
  50578. }
  50579. SceneSerializer.ClearCache = function () {
  50580. serializedGeometries = [];
  50581. };
  50582. SceneSerializer.Serialize = function (scene) {
  50583. var serializationObject = {};
  50584. // Scene
  50585. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  50586. serializationObject.autoClear = scene.autoClear;
  50587. serializationObject.clearColor = scene.clearColor.asArray();
  50588. serializationObject.ambientColor = scene.ambientColor.asArray();
  50589. serializationObject.gravity = scene.gravity.asArray();
  50590. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  50591. serializationObject.workerCollisions = scene.workerCollisions;
  50592. // Fog
  50593. if (scene.fogMode && scene.fogMode !== 0) {
  50594. serializationObject.fogMode = scene.fogMode;
  50595. serializationObject.fogColor = scene.fogColor.asArray();
  50596. serializationObject.fogStart = scene.fogStart;
  50597. serializationObject.fogEnd = scene.fogEnd;
  50598. serializationObject.fogDensity = scene.fogDensity;
  50599. }
  50600. //Physics
  50601. if (scene.isPhysicsEnabled()) {
  50602. serializationObject.physicsEnabled = true;
  50603. serializationObject.physicsGravity = scene.getPhysicsEngine().gravity.asArray();
  50604. serializationObject.physicsEngine = scene.getPhysicsEngine().getPhysicsPluginName();
  50605. }
  50606. // Lights
  50607. serializationObject.lights = [];
  50608. var index;
  50609. var light;
  50610. for (index = 0; index < scene.lights.length; index++) {
  50611. light = scene.lights[index];
  50612. serializationObject.lights.push(light.serialize());
  50613. }
  50614. // Cameras
  50615. serializationObject.cameras = [];
  50616. for (index = 0; index < scene.cameras.length; index++) {
  50617. var camera = scene.cameras[index];
  50618. serializationObject.cameras.push(camera.serialize());
  50619. }
  50620. if (scene.activeCamera) {
  50621. serializationObject.activeCameraID = scene.activeCamera.id;
  50622. }
  50623. // Animations
  50624. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  50625. // Materials
  50626. serializationObject.materials = [];
  50627. serializationObject.multiMaterials = [];
  50628. var material;
  50629. for (index = 0; index < scene.materials.length; index++) {
  50630. material = scene.materials[index];
  50631. serializationObject.materials.push(material.serialize());
  50632. }
  50633. // MultiMaterials
  50634. serializationObject.multiMaterials = [];
  50635. for (index = 0; index < scene.multiMaterials.length; index++) {
  50636. var multiMaterial = scene.multiMaterials[index];
  50637. serializationObject.multiMaterials.push(multiMaterial.serialize());
  50638. }
  50639. // Skeletons
  50640. serializationObject.skeletons = [];
  50641. for (index = 0; index < scene.skeletons.length; index++) {
  50642. serializationObject.skeletons.push(scene.skeletons[index].serialize());
  50643. }
  50644. // Geometries
  50645. serializationObject.geometries = {};
  50646. serializationObject.geometries.boxes = [];
  50647. serializationObject.geometries.spheres = [];
  50648. serializationObject.geometries.cylinders = [];
  50649. serializationObject.geometries.toruses = [];
  50650. serializationObject.geometries.grounds = [];
  50651. serializationObject.geometries.planes = [];
  50652. serializationObject.geometries.torusKnots = [];
  50653. serializationObject.geometries.vertexData = [];
  50654. serializedGeometries = [];
  50655. var geometries = scene.getGeometries();
  50656. for (index = 0; index < geometries.length; index++) {
  50657. var geometry = geometries[index];
  50658. if (geometry.isReady()) {
  50659. serializeGeometry(geometry, serializationObject.geometries);
  50660. }
  50661. }
  50662. // Meshes
  50663. serializationObject.meshes = [];
  50664. for (index = 0; index < scene.meshes.length; index++) {
  50665. var abstractMesh = scene.meshes[index];
  50666. if (abstractMesh instanceof BABYLON.Mesh) {
  50667. var mesh = abstractMesh;
  50668. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  50669. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  50670. }
  50671. }
  50672. }
  50673. // Particles Systems
  50674. serializationObject.particleSystems = [];
  50675. for (index = 0; index < scene.particleSystems.length; index++) {
  50676. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  50677. }
  50678. // Lens flares
  50679. serializationObject.lensFlareSystems = [];
  50680. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  50681. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  50682. }
  50683. // Shadows
  50684. serializationObject.shadowGenerators = [];
  50685. for (index = 0; index < scene.lights.length; index++) {
  50686. light = scene.lights[index];
  50687. var shadowGenerator = light.getShadowGenerator();
  50688. // Only support serialization for official generator so far.
  50689. if (shadowGenerator && shadowGenerator instanceof BABYLON.ShadowGenerator) {
  50690. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  50691. }
  50692. }
  50693. // Action Manager
  50694. if (scene.actionManager) {
  50695. serializationObject.actions = scene.actionManager.serialize("scene");
  50696. }
  50697. // Audio
  50698. serializationObject.sounds = [];
  50699. for (index = 0; index < scene.soundTracks.length; index++) {
  50700. var soundtrack = scene.soundTracks[index];
  50701. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  50702. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  50703. }
  50704. }
  50705. return serializationObject;
  50706. };
  50707. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  50708. if (withParents === void 0) { withParents = false; }
  50709. if (withChildren === void 0) { withChildren = false; }
  50710. var serializationObject = {};
  50711. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  50712. if (withParents || withChildren) {
  50713. //deliberate for loop! not for each, appended should be processed as well.
  50714. for (var i = 0; i < toSerialize.length; ++i) {
  50715. if (withChildren) {
  50716. toSerialize[i].getDescendants().forEach(function (node) {
  50717. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  50718. toSerialize.push(node);
  50719. }
  50720. });
  50721. }
  50722. //make sure the array doesn't contain the object already
  50723. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  50724. toSerialize.push(toSerialize[i].parent);
  50725. }
  50726. }
  50727. }
  50728. toSerialize.forEach(function (mesh) {
  50729. finalizeSingleMesh(mesh, serializationObject);
  50730. });
  50731. return serializationObject;
  50732. };
  50733. return SceneSerializer;
  50734. })();
  50735. BABYLON.SceneSerializer = SceneSerializer;
  50736. })(BABYLON || (BABYLON = {}));
  50737. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  50738. // Huge respect for a such great lib.
  50739. // Earcut license:
  50740. // Copyright (c) 2016, Mapbox
  50741. //
  50742. // Permission to use, copy, modify, and/or distribute this software for any purpose
  50743. // with or without fee is hereby granted, provided that the above copyright notice
  50744. // and this permission notice appear in all copies.
  50745. //
  50746. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  50747. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  50748. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  50749. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  50750. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  50751. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  50752. // THIS SOFTWARE.
  50753. var Earcut;
  50754. (function (Earcut) {
  50755. /**
  50756. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  50757. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  50758. * @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).
  50759. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  50760. */
  50761. function earcut(data, holeIndices, dim) {
  50762. dim = dim || 2;
  50763. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = [];
  50764. if (!outerNode)
  50765. return triangles;
  50766. var minX, minY, maxX, maxY, x, y, size;
  50767. if (hasHoles)
  50768. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  50769. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  50770. if (data.length > 80 * dim) {
  50771. minX = maxX = data[0];
  50772. minY = maxY = data[1];
  50773. for (var i = dim; i < outerLen; i += dim) {
  50774. x = data[i];
  50775. y = data[i + 1];
  50776. if (x < minX)
  50777. minX = x;
  50778. if (y < minY)
  50779. minY = y;
  50780. if (x > maxX)
  50781. maxX = x;
  50782. if (y > maxY)
  50783. maxY = y;
  50784. }
  50785. // minX, minY and size are later used to transform coords into integers for z-order calculation
  50786. size = Math.max(maxX - minX, maxY - minY);
  50787. }
  50788. earcutLinked(outerNode, triangles, dim, minX, minY, size, undefined);
  50789. return triangles;
  50790. }
  50791. Earcut.earcut = earcut;
  50792. // create a circular doubly linked list from polygon points in the specified winding order
  50793. function linkedList(data, start, end, dim, clockwise) {
  50794. var i, last;
  50795. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  50796. for (i = start; i < end; i += dim)
  50797. last = insertNode(i, data[i], data[i + 1], last);
  50798. }
  50799. else {
  50800. for (i = end - dim; i >= start; i -= dim)
  50801. last = insertNode(i, data[i], data[i + 1], last);
  50802. }
  50803. if (last && equals(last, last.next)) {
  50804. removeNode(last);
  50805. last = last.next;
  50806. }
  50807. return last;
  50808. }
  50809. // eliminate colinear or duplicate points
  50810. function filterPoints(start, end) {
  50811. if (!start)
  50812. return start;
  50813. if (!end)
  50814. end = start;
  50815. var p = start, again;
  50816. do {
  50817. again = false;
  50818. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  50819. removeNode(p);
  50820. p = end = p.prev;
  50821. if (p === p.next)
  50822. return null;
  50823. again = true;
  50824. }
  50825. else {
  50826. p = p.next;
  50827. }
  50828. } while (again || p !== end);
  50829. return end;
  50830. }
  50831. // main ear slicing loop which triangulates a polygon (given as a linked list)
  50832. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  50833. if (!ear)
  50834. return;
  50835. // interlink polygon nodes in z-order
  50836. if (!pass && size)
  50837. indexCurve(ear, minX, minY, size);
  50838. var stop = ear, prev, next;
  50839. // iterate through ears, slicing them one by one
  50840. while (ear.prev !== ear.next) {
  50841. prev = ear.prev;
  50842. next = ear.next;
  50843. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  50844. // cut off the triangle
  50845. triangles.push(prev.i / dim);
  50846. triangles.push(ear.i / dim);
  50847. triangles.push(next.i / dim);
  50848. removeNode(ear);
  50849. // skipping the next vertice leads to less sliver triangles
  50850. ear = next.next;
  50851. stop = next.next;
  50852. continue;
  50853. }
  50854. ear = next;
  50855. // if we looped through the whole remaining polygon and can't find any more ears
  50856. if (ear === stop) {
  50857. // try filtering points and slicing again
  50858. if (!pass) {
  50859. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  50860. }
  50861. else if (pass === 1) {
  50862. ear = cureLocalIntersections(ear, triangles, dim);
  50863. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  50864. }
  50865. else if (pass === 2) {
  50866. splitEarcut(ear, triangles, dim, minX, minY, size);
  50867. }
  50868. break;
  50869. }
  50870. }
  50871. }
  50872. // check whether a polygon node forms a valid ear with adjacent nodes
  50873. function isEar(ear) {
  50874. var a = ear.prev, b = ear, c = ear.next;
  50875. if (area(a, b, c) >= 0)
  50876. return false; // reflex, can't be an ear
  50877. // now make sure we don't have other points inside the potential ear
  50878. var p = ear.next.next;
  50879. while (p !== ear.prev) {
  50880. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  50881. area(p.prev, p, p.next) >= 0)
  50882. return false;
  50883. p = p.next;
  50884. }
  50885. return true;
  50886. }
  50887. function isEarHashed(ear, minX, minY, size) {
  50888. var a = ear.prev, b = ear, c = ear.next;
  50889. if (area(a, b, c) >= 0)
  50890. return false; // reflex, can't be an ear
  50891. // triangle bbox; min & max are calculated like this for speed
  50892. 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);
  50893. // z-order range for the current triangle bbox;
  50894. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  50895. // first look for points inside the triangle in increasing z-order
  50896. var p = ear.nextZ;
  50897. while (p && p.z <= maxZ) {
  50898. if (p !== ear.prev &&
  50899. p !== ear.next &&
  50900. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  50901. area(p.prev, p, p.next) >= 0)
  50902. return false;
  50903. p = p.nextZ;
  50904. }
  50905. // then look for points in decreasing z-order
  50906. p = ear.prevZ;
  50907. while (p && p.z >= minZ) {
  50908. if (p !== ear.prev &&
  50909. p !== ear.next &&
  50910. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  50911. area(p.prev, p, p.next) >= 0)
  50912. return false;
  50913. p = p.prevZ;
  50914. }
  50915. return true;
  50916. }
  50917. // go through all polygon nodes and cure small local self-intersections
  50918. function cureLocalIntersections(start, triangles, dim) {
  50919. var p = start;
  50920. do {
  50921. var a = p.prev, b = p.next.next;
  50922. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  50923. triangles.push(a.i / dim);
  50924. triangles.push(p.i / dim);
  50925. triangles.push(b.i / dim);
  50926. // remove two nodes involved
  50927. removeNode(p);
  50928. removeNode(p.next);
  50929. p = start = b;
  50930. }
  50931. p = p.next;
  50932. } while (p !== start);
  50933. return p;
  50934. }
  50935. // try splitting polygon into two and triangulate them independently
  50936. function splitEarcut(start, triangles, dim, minX, minY, size) {
  50937. // look for a valid diagonal that divides the polygon into two
  50938. var a = start;
  50939. do {
  50940. var b = a.next.next;
  50941. while (b !== a.prev) {
  50942. if (a.i !== b.i && isValidDiagonal(a, b)) {
  50943. // split the polygon in two by the diagonal
  50944. var c = splitPolygon(a, b);
  50945. // filter colinear points around the cuts
  50946. a = filterPoints(a, a.next);
  50947. c = filterPoints(c, c.next);
  50948. // run earcut on each half
  50949. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  50950. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  50951. return;
  50952. }
  50953. b = b.next;
  50954. }
  50955. a = a.next;
  50956. } while (a !== start);
  50957. }
  50958. // link every hole into the outer loop, producing a single-ring polygon without holes
  50959. function eliminateHoles(data, holeIndices, outerNode, dim) {
  50960. var queue = [], i, len, start, end, list;
  50961. for (i = 0, len = holeIndices.length; i < len; i++) {
  50962. start = holeIndices[i] * dim;
  50963. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  50964. list = linkedList(data, start, end, dim, false);
  50965. if (list === list.next)
  50966. list.steiner = true;
  50967. queue.push(getLeftmost(list));
  50968. }
  50969. queue.sort(compareX);
  50970. // process holes from left to right
  50971. for (i = 0; i < queue.length; i++) {
  50972. eliminateHole(queue[i], outerNode);
  50973. outerNode = filterPoints(outerNode, outerNode.next);
  50974. }
  50975. return outerNode;
  50976. }
  50977. function compareX(a, b) {
  50978. return a.x - b.x;
  50979. }
  50980. // find a bridge between vertices that connects hole with an outer ring and and link it
  50981. function eliminateHole(hole, outerNode) {
  50982. outerNode = findHoleBridge(hole, outerNode);
  50983. if (outerNode) {
  50984. var b = splitPolygon(outerNode, hole);
  50985. filterPoints(b, b.next);
  50986. }
  50987. }
  50988. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  50989. function findHoleBridge(hole, outerNode) {
  50990. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  50991. // find a segment intersected by a ray from the hole's leftmost point to the left;
  50992. // segment's endpoint with lesser x will be potential connection point
  50993. do {
  50994. if (hy <= p.y && hy >= p.next.y) {
  50995. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  50996. if (x <= hx && x > qx) {
  50997. qx = x;
  50998. if (x === hx) {
  50999. if (hy === p.y)
  51000. return p;
  51001. if (hy === p.next.y)
  51002. return p.next;
  51003. }
  51004. m = p.x < p.next.x ? p : p.next;
  51005. }
  51006. }
  51007. p = p.next;
  51008. } while (p !== outerNode);
  51009. if (!m)
  51010. return null;
  51011. if (hx === qx)
  51012. return m.prev; // hole touches outer segment; pick lower endpoint
  51013. // look for points inside the triangle of hole point, segment intersection and endpoint;
  51014. // if there are no points found, we have a valid connection;
  51015. // otherwise choose the point of the minimum angle with the ray as connection point
  51016. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  51017. p = m.next;
  51018. while (p !== stop) {
  51019. if (hx >= p.x &&
  51020. p.x >= mx &&
  51021. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  51022. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  51023. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  51024. m = p;
  51025. tanMin = tan;
  51026. }
  51027. }
  51028. p = p.next;
  51029. }
  51030. return m;
  51031. }
  51032. // interlink polygon nodes in z-order
  51033. function indexCurve(start, minX, minY, size) {
  51034. var p = start;
  51035. do {
  51036. if (p.z === null)
  51037. p.z = zOrder(p.x, p.y, minX, minY, size);
  51038. p.prevZ = p.prev;
  51039. p.nextZ = p.next;
  51040. p = p.next;
  51041. } while (p !== start);
  51042. p.prevZ.nextZ = null;
  51043. p.prevZ = null;
  51044. sortLinked(p);
  51045. }
  51046. // Simon Tatham's linked list merge sort algorithm
  51047. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  51048. function sortLinked(list) {
  51049. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  51050. do {
  51051. p = list;
  51052. list = null;
  51053. tail = null;
  51054. numMerges = 0;
  51055. while (p) {
  51056. numMerges++;
  51057. q = p;
  51058. pSize = 0;
  51059. for (i = 0; i < inSize; i++) {
  51060. pSize++;
  51061. q = q.nextZ;
  51062. if (!q)
  51063. break;
  51064. }
  51065. qSize = inSize;
  51066. while (pSize > 0 || (qSize > 0 && q)) {
  51067. if (pSize === 0) {
  51068. e = q;
  51069. q = q.nextZ;
  51070. qSize--;
  51071. }
  51072. else if (qSize === 0 || !q) {
  51073. e = p;
  51074. p = p.nextZ;
  51075. pSize--;
  51076. }
  51077. else if (p.z <= q.z) {
  51078. e = p;
  51079. p = p.nextZ;
  51080. pSize--;
  51081. }
  51082. else {
  51083. e = q;
  51084. q = q.nextZ;
  51085. qSize--;
  51086. }
  51087. if (tail)
  51088. tail.nextZ = e;
  51089. else
  51090. list = e;
  51091. e.prevZ = tail;
  51092. tail = e;
  51093. }
  51094. p = q;
  51095. }
  51096. tail.nextZ = null;
  51097. inSize *= 2;
  51098. } while (numMerges > 1);
  51099. return list;
  51100. }
  51101. // z-order of a point given coords and size of the data bounding box
  51102. function zOrder(x, y, minX, minY, size) {
  51103. // coords are transformed into non-negative 15-bit integer range
  51104. x = 32767 * (x - minX) / size;
  51105. y = 32767 * (y - minY) / size;
  51106. x = (x | (x << 8)) & 0x00FF00FF;
  51107. x = (x | (x << 4)) & 0x0F0F0F0F;
  51108. x = (x | (x << 2)) & 0x33333333;
  51109. x = (x | (x << 1)) & 0x55555555;
  51110. y = (y | (y << 8)) & 0x00FF00FF;
  51111. y = (y | (y << 4)) & 0x0F0F0F0F;
  51112. y = (y | (y << 2)) & 0x33333333;
  51113. y = (y | (y << 1)) & 0x55555555;
  51114. return x | (y << 1);
  51115. }
  51116. // find the leftmost node of a polygon ring
  51117. function getLeftmost(start) {
  51118. var p = start, leftmost = start;
  51119. do {
  51120. if (p.x < leftmost.x)
  51121. leftmost = p;
  51122. p = p.next;
  51123. } while (p !== start);
  51124. return leftmost;
  51125. }
  51126. // check if a point lies within a convex triangle
  51127. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  51128. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  51129. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  51130. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  51131. }
  51132. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  51133. function isValidDiagonal(a, b) {
  51134. return a.next.i !== b.i &&
  51135. a.prev.i !== b.i &&
  51136. !intersectsPolygon(a, b) &&
  51137. locallyInside(a, b) &&
  51138. locallyInside(b, a) &&
  51139. middleInside(a, b);
  51140. }
  51141. // signed area of a triangle
  51142. function area(p, q, r) {
  51143. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  51144. }
  51145. // check if two points are equal
  51146. function equals(p1, p2) {
  51147. return p1.x === p2.x && p1.y === p2.y;
  51148. }
  51149. // check if two segments intersect
  51150. function intersects(p1, q1, p2, q2) {
  51151. if ((equals(p1, q1) && equals(p2, q2)) ||
  51152. (equals(p1, q2) && equals(p2, q1)))
  51153. return true;
  51154. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  51155. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  51156. }
  51157. // check if a polygon diagonal intersects any polygon segments
  51158. function intersectsPolygon(a, b) {
  51159. var p = a;
  51160. do {
  51161. if (p.i !== a.i &&
  51162. p.next.i !== a.i &&
  51163. p.i !== b.i &&
  51164. p.next.i !== b.i &&
  51165. intersects(p, p.next, a, b))
  51166. return true;
  51167. p = p.next;
  51168. } while (p !== a);
  51169. return false;
  51170. }
  51171. // check if a polygon diagonal is locally inside the polygon
  51172. function locallyInside(a, b) {
  51173. return area(a.prev, a, a.next) < 0
  51174. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  51175. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  51176. }
  51177. // check if the middle point of a polygon diagonal is inside the polygon
  51178. function middleInside(a, b) {
  51179. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  51180. do {
  51181. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  51182. inside = !inside;
  51183. p = p.next;
  51184. } while (p !== a);
  51185. return inside;
  51186. }
  51187. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  51188. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  51189. function splitPolygon(a, b) {
  51190. 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;
  51191. a.next = b;
  51192. b.prev = a;
  51193. a2.next = an;
  51194. an.prev = a2;
  51195. b2.next = a2;
  51196. a2.prev = b2;
  51197. bp.next = b2;
  51198. b2.prev = bp;
  51199. return b2;
  51200. }
  51201. // create a node and optionally link it with previous one (in a circular doubly linked list)
  51202. function insertNode(i, x, y, last) {
  51203. var p = new Node(i, x, y);
  51204. if (!last) {
  51205. p.prev = p;
  51206. p.next = p;
  51207. }
  51208. else {
  51209. p.next = last.next;
  51210. p.prev = last;
  51211. last.next.prev = p;
  51212. last.next = p;
  51213. }
  51214. return p;
  51215. }
  51216. function removeNode(p) {
  51217. p.next.prev = p.prev;
  51218. p.prev.next = p.next;
  51219. if (p.prevZ)
  51220. p.prevZ.nextZ = p.nextZ;
  51221. if (p.nextZ)
  51222. p.nextZ.prevZ = p.prevZ;
  51223. }
  51224. function Node(i, x, y) {
  51225. // vertice index in coordinates array
  51226. this.i = i;
  51227. // vertex coordinates
  51228. this.x = x;
  51229. this.y = y;
  51230. // previous and next vertice nodes in a polygon ring
  51231. this.prev = null;
  51232. this.next = null;
  51233. // z-order curve value
  51234. this.z = null;
  51235. // previous and next nodes in z-order
  51236. this.prevZ = null;
  51237. this.nextZ = null;
  51238. // indicates whether this is a steiner point
  51239. this.steiner = false;
  51240. }
  51241. /**
  51242. * return a percentage difference between the polygon area and its triangulation area;
  51243. * used to verify correctness of triangulation
  51244. */
  51245. function deviation(data, holeIndices, dim, triangles) {
  51246. var hasHoles = holeIndices && holeIndices.length;
  51247. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  51248. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  51249. if (hasHoles) {
  51250. for (var i = 0, len = holeIndices.length; i < len; i++) {
  51251. var start = holeIndices[i] * dim;
  51252. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  51253. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  51254. }
  51255. }
  51256. var trianglesArea = 0;
  51257. for (i = 0; i < triangles.length; i += 3) {
  51258. var a = triangles[i] * dim;
  51259. var b = triangles[i + 1] * dim;
  51260. var c = triangles[i + 2] * dim;
  51261. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  51262. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  51263. }
  51264. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  51265. }
  51266. Earcut.deviation = deviation;
  51267. ;
  51268. function signedArea(data, start, end, dim) {
  51269. var sum = 0;
  51270. for (var i = start, j = end - dim; i < end; i += dim) {
  51271. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  51272. j = i;
  51273. }
  51274. return sum;
  51275. }
  51276. /**
  51277. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  51278. */
  51279. function flatten(data) {
  51280. var dim = data[0][0].length, result = { vertices: [], holes: [], dimensions: dim }, holeIndex = 0;
  51281. for (var i = 0; i < data.length; i++) {
  51282. for (var j = 0; j < data[i].length; j++) {
  51283. for (var d = 0; d < dim; d++)
  51284. result.vertices.push(data[i][j][d]);
  51285. }
  51286. if (i > 0) {
  51287. holeIndex += data[i - 1].length;
  51288. result.holes.push(holeIndex);
  51289. }
  51290. }
  51291. return result;
  51292. }
  51293. Earcut.flatten = flatten;
  51294. ;
  51295. })(Earcut || (Earcut = {}));
  51296. var BABYLON;
  51297. (function (BABYLON) {
  51298. // Unique ID when we import meshes from Babylon to CSG
  51299. var currentCSGMeshId = 0;
  51300. // # class Vertex
  51301. // Represents a vertex of a polygon. Use your own vertex class instead of this
  51302. // one to provide additional features like texture coordinates and vertex
  51303. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  51304. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  51305. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  51306. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  51307. // is not used anywhere else.
  51308. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  51309. var Vertex = (function () {
  51310. function Vertex(pos, normal, uv) {
  51311. this.pos = pos;
  51312. this.normal = normal;
  51313. this.uv = uv;
  51314. }
  51315. Vertex.prototype.clone = function () {
  51316. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  51317. };
  51318. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  51319. // orientation of a polygon is flipped.
  51320. Vertex.prototype.flip = function () {
  51321. this.normal = this.normal.scale(-1);
  51322. };
  51323. // Create a new vertex between this vertex and `other` by linearly
  51324. // interpolating all properties using a parameter of `t`. Subclasses should
  51325. // override this to interpolate additional properties.
  51326. Vertex.prototype.interpolate = function (other, t) {
  51327. 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));
  51328. };
  51329. return Vertex;
  51330. })();
  51331. // # class Plane
  51332. // Represents a plane in 3D space.
  51333. var Plane = (function () {
  51334. function Plane(normal, w) {
  51335. this.normal = normal;
  51336. this.w = w;
  51337. }
  51338. Plane.FromPoints = function (a, b, c) {
  51339. var v0 = c.subtract(a);
  51340. var v1 = b.subtract(a);
  51341. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  51342. return null;
  51343. }
  51344. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  51345. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  51346. };
  51347. Plane.prototype.clone = function () {
  51348. return new Plane(this.normal.clone(), this.w);
  51349. };
  51350. Plane.prototype.flip = function () {
  51351. this.normal.scaleInPlace(-1);
  51352. this.w = -this.w;
  51353. };
  51354. // Split `polygon` by this plane if needed, then put the polygon or polygon
  51355. // fragments in the appropriate lists. Coplanar polygons go into either
  51356. // `coplanarFront` or `coplanarBack` depending on their orientation with
  51357. // respect to this plane. Polygons in front or in back of this plane go into
  51358. // either `front` or `back`.
  51359. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  51360. var COPLANAR = 0;
  51361. var FRONT = 1;
  51362. var BACK = 2;
  51363. var SPANNING = 3;
  51364. // Classify each point as well as the entire polygon into one of the above
  51365. // four classes.
  51366. var polygonType = 0;
  51367. var types = [];
  51368. var i;
  51369. var t;
  51370. for (i = 0; i < polygon.vertices.length; i++) {
  51371. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  51372. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  51373. polygonType |= type;
  51374. types.push(type);
  51375. }
  51376. // Put the polygon in the correct list, splitting it when necessary.
  51377. switch (polygonType) {
  51378. case COPLANAR:
  51379. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  51380. break;
  51381. case FRONT:
  51382. front.push(polygon);
  51383. break;
  51384. case BACK:
  51385. back.push(polygon);
  51386. break;
  51387. case SPANNING:
  51388. var f = [], b = [];
  51389. for (i = 0; i < polygon.vertices.length; i++) {
  51390. var j = (i + 1) % polygon.vertices.length;
  51391. var ti = types[i], tj = types[j];
  51392. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  51393. if (ti !== BACK)
  51394. f.push(vi);
  51395. if (ti !== FRONT)
  51396. b.push(ti !== BACK ? vi.clone() : vi);
  51397. if ((ti | tj) === SPANNING) {
  51398. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  51399. var v = vi.interpolate(vj, t);
  51400. f.push(v);
  51401. b.push(v.clone());
  51402. }
  51403. }
  51404. var poly;
  51405. if (f.length >= 3) {
  51406. poly = new Polygon(f, polygon.shared);
  51407. if (poly.plane)
  51408. front.push(poly);
  51409. }
  51410. if (b.length >= 3) {
  51411. poly = new Polygon(b, polygon.shared);
  51412. if (poly.plane)
  51413. back.push(poly);
  51414. }
  51415. break;
  51416. }
  51417. };
  51418. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  51419. // point is on the plane.
  51420. Plane.EPSILON = 1e-5;
  51421. return Plane;
  51422. })();
  51423. // # class Polygon
  51424. // Represents a convex polygon. The vertices used to initialize a polygon must
  51425. // be coplanar and form a convex loop.
  51426. //
  51427. // Each convex polygon has a `shared` property, which is shared between all
  51428. // polygons that are clones of each other or were split from the same polygon.
  51429. // This can be used to define per-polygon properties (such as surface color).
  51430. var Polygon = (function () {
  51431. function Polygon(vertices, shared) {
  51432. this.vertices = vertices;
  51433. this.shared = shared;
  51434. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  51435. }
  51436. Polygon.prototype.clone = function () {
  51437. var vertices = this.vertices.map(function (v) { return v.clone(); });
  51438. return new Polygon(vertices, this.shared);
  51439. };
  51440. Polygon.prototype.flip = function () {
  51441. this.vertices.reverse().map(function (v) { v.flip(); });
  51442. this.plane.flip();
  51443. };
  51444. return Polygon;
  51445. })();
  51446. // # class Node
  51447. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  51448. // by picking a polygon to split along. That polygon (and all other coplanar
  51449. // polygons) are added directly to that node and the other polygons are added to
  51450. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  51451. // no distinction between internal and leaf nodes.
  51452. var Node = (function () {
  51453. function Node(polygons) {
  51454. this.plane = null;
  51455. this.front = null;
  51456. this.back = null;
  51457. this.polygons = [];
  51458. if (polygons) {
  51459. this.build(polygons);
  51460. }
  51461. }
  51462. Node.prototype.clone = function () {
  51463. var node = new Node();
  51464. node.plane = this.plane && this.plane.clone();
  51465. node.front = this.front && this.front.clone();
  51466. node.back = this.back && this.back.clone();
  51467. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  51468. return node;
  51469. };
  51470. // Convert solid space to empty space and empty space to solid space.
  51471. Node.prototype.invert = function () {
  51472. for (var i = 0; i < this.polygons.length; i++) {
  51473. this.polygons[i].flip();
  51474. }
  51475. if (this.plane) {
  51476. this.plane.flip();
  51477. }
  51478. if (this.front) {
  51479. this.front.invert();
  51480. }
  51481. if (this.back) {
  51482. this.back.invert();
  51483. }
  51484. var temp = this.front;
  51485. this.front = this.back;
  51486. this.back = temp;
  51487. };
  51488. // Recursively remove all polygons in `polygons` that are inside this BSP
  51489. // tree.
  51490. Node.prototype.clipPolygons = function (polygons) {
  51491. if (!this.plane)
  51492. return polygons.slice();
  51493. var front = [], back = [];
  51494. for (var i = 0; i < polygons.length; i++) {
  51495. this.plane.splitPolygon(polygons[i], front, back, front, back);
  51496. }
  51497. if (this.front) {
  51498. front = this.front.clipPolygons(front);
  51499. }
  51500. if (this.back) {
  51501. back = this.back.clipPolygons(back);
  51502. }
  51503. else {
  51504. back = [];
  51505. }
  51506. return front.concat(back);
  51507. };
  51508. // Remove all polygons in this BSP tree that are inside the other BSP tree
  51509. // `bsp`.
  51510. Node.prototype.clipTo = function (bsp) {
  51511. this.polygons = bsp.clipPolygons(this.polygons);
  51512. if (this.front)
  51513. this.front.clipTo(bsp);
  51514. if (this.back)
  51515. this.back.clipTo(bsp);
  51516. };
  51517. // Return a list of all polygons in this BSP tree.
  51518. Node.prototype.allPolygons = function () {
  51519. var polygons = this.polygons.slice();
  51520. if (this.front)
  51521. polygons = polygons.concat(this.front.allPolygons());
  51522. if (this.back)
  51523. polygons = polygons.concat(this.back.allPolygons());
  51524. return polygons;
  51525. };
  51526. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  51527. // new polygons are filtered down to the bottom of the tree and become new
  51528. // nodes there. Each set of polygons is partitioned using the first polygon
  51529. // (no heuristic is used to pick a good split).
  51530. Node.prototype.build = function (polygons) {
  51531. if (!polygons.length)
  51532. return;
  51533. if (!this.plane)
  51534. this.plane = polygons[0].plane.clone();
  51535. var front = [], back = [];
  51536. for (var i = 0; i < polygons.length; i++) {
  51537. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  51538. }
  51539. if (front.length) {
  51540. if (!this.front)
  51541. this.front = new Node();
  51542. this.front.build(front);
  51543. }
  51544. if (back.length) {
  51545. if (!this.back)
  51546. this.back = new Node();
  51547. this.back.build(back);
  51548. }
  51549. };
  51550. return Node;
  51551. })();
  51552. var CSG = (function () {
  51553. function CSG() {
  51554. this.polygons = new Array();
  51555. }
  51556. // Convert BABYLON.Mesh to BABYLON.CSG
  51557. CSG.FromMesh = function (mesh) {
  51558. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  51559. var matrix, meshPosition, meshRotation, meshRotationQuaternion, meshScaling;
  51560. if (mesh instanceof BABYLON.Mesh) {
  51561. mesh.computeWorldMatrix(true);
  51562. matrix = mesh.getWorldMatrix();
  51563. meshPosition = mesh.position.clone();
  51564. meshRotation = mesh.rotation.clone();
  51565. if (mesh.rotationQuaternion) {
  51566. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  51567. }
  51568. meshScaling = mesh.scaling.clone();
  51569. }
  51570. else {
  51571. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  51572. }
  51573. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  51574. var subMeshes = mesh.subMeshes;
  51575. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  51576. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  51577. vertices = [];
  51578. for (var j = 0; j < 3; j++) {
  51579. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  51580. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  51581. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  51582. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  51583. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  51584. vertex = new Vertex(position, normal, uv);
  51585. vertices.push(vertex);
  51586. }
  51587. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  51588. // To handle the case of degenerated triangle
  51589. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  51590. if (polygon.plane)
  51591. polygons.push(polygon);
  51592. }
  51593. }
  51594. var csg = CSG.FromPolygons(polygons);
  51595. csg.matrix = matrix;
  51596. csg.position = meshPosition;
  51597. csg.rotation = meshRotation;
  51598. csg.scaling = meshScaling;
  51599. csg.rotationQuaternion = meshRotationQuaternion;
  51600. currentCSGMeshId++;
  51601. return csg;
  51602. };
  51603. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  51604. CSG.FromPolygons = function (polygons) {
  51605. var csg = new CSG();
  51606. csg.polygons = polygons;
  51607. return csg;
  51608. };
  51609. CSG.prototype.clone = function () {
  51610. var csg = new CSG();
  51611. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  51612. csg.copyTransformAttributes(this);
  51613. return csg;
  51614. };
  51615. CSG.prototype.toPolygons = function () {
  51616. return this.polygons;
  51617. };
  51618. CSG.prototype.union = function (csg) {
  51619. var a = new Node(this.clone().polygons);
  51620. var b = new Node(csg.clone().polygons);
  51621. a.clipTo(b);
  51622. b.clipTo(a);
  51623. b.invert();
  51624. b.clipTo(a);
  51625. b.invert();
  51626. a.build(b.allPolygons());
  51627. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  51628. };
  51629. CSG.prototype.unionInPlace = function (csg) {
  51630. var a = new Node(this.polygons);
  51631. var b = new Node(csg.polygons);
  51632. a.clipTo(b);
  51633. b.clipTo(a);
  51634. b.invert();
  51635. b.clipTo(a);
  51636. b.invert();
  51637. a.build(b.allPolygons());
  51638. this.polygons = a.allPolygons();
  51639. };
  51640. CSG.prototype.subtract = function (csg) {
  51641. var a = new Node(this.clone().polygons);
  51642. var b = new Node(csg.clone().polygons);
  51643. a.invert();
  51644. a.clipTo(b);
  51645. b.clipTo(a);
  51646. b.invert();
  51647. b.clipTo(a);
  51648. b.invert();
  51649. a.build(b.allPolygons());
  51650. a.invert();
  51651. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  51652. };
  51653. CSG.prototype.subtractInPlace = function (csg) {
  51654. var a = new Node(this.polygons);
  51655. var b = new Node(csg.polygons);
  51656. a.invert();
  51657. a.clipTo(b);
  51658. b.clipTo(a);
  51659. b.invert();
  51660. b.clipTo(a);
  51661. b.invert();
  51662. a.build(b.allPolygons());
  51663. a.invert();
  51664. this.polygons = a.allPolygons();
  51665. };
  51666. CSG.prototype.intersect = function (csg) {
  51667. var a = new Node(this.clone().polygons);
  51668. var b = new Node(csg.clone().polygons);
  51669. a.invert();
  51670. b.clipTo(a);
  51671. b.invert();
  51672. a.clipTo(b);
  51673. b.clipTo(a);
  51674. a.build(b.allPolygons());
  51675. a.invert();
  51676. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  51677. };
  51678. CSG.prototype.intersectInPlace = function (csg) {
  51679. var a = new Node(this.polygons);
  51680. var b = new Node(csg.polygons);
  51681. a.invert();
  51682. b.clipTo(a);
  51683. b.invert();
  51684. a.clipTo(b);
  51685. b.clipTo(a);
  51686. a.build(b.allPolygons());
  51687. a.invert();
  51688. this.polygons = a.allPolygons();
  51689. };
  51690. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  51691. // not modified.
  51692. CSG.prototype.inverse = function () {
  51693. var csg = this.clone();
  51694. csg.inverseInPlace();
  51695. return csg;
  51696. };
  51697. CSG.prototype.inverseInPlace = function () {
  51698. this.polygons.map(function (p) { p.flip(); });
  51699. };
  51700. // This is used to keep meshes transformations so they can be restored
  51701. // when we build back a Babylon Mesh
  51702. // NB : All CSG operations are performed in world coordinates
  51703. CSG.prototype.copyTransformAttributes = function (csg) {
  51704. this.matrix = csg.matrix;
  51705. this.position = csg.position;
  51706. this.rotation = csg.rotation;
  51707. this.scaling = csg.scaling;
  51708. this.rotationQuaternion = csg.rotationQuaternion;
  51709. return this;
  51710. };
  51711. // Build Raw mesh from CSG
  51712. // Coordinates here are in world space
  51713. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  51714. var matrix = this.matrix.clone();
  51715. matrix.invert();
  51716. 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;
  51717. if (keepSubMeshes) {
  51718. // Sort Polygons, since subMeshes are indices range
  51719. polygons.sort(function (a, b) {
  51720. if (a.shared.meshId === b.shared.meshId) {
  51721. return a.shared.subMeshId - b.shared.subMeshId;
  51722. }
  51723. else {
  51724. return a.shared.meshId - b.shared.meshId;
  51725. }
  51726. });
  51727. }
  51728. for (var i = 0, il = polygons.length; i < il; i++) {
  51729. polygon = polygons[i];
  51730. // Building SubMeshes
  51731. if (!subMesh_dict[polygon.shared.meshId]) {
  51732. subMesh_dict[polygon.shared.meshId] = {};
  51733. }
  51734. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  51735. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  51736. indexStart: +Infinity,
  51737. indexEnd: -Infinity,
  51738. materialIndex: polygon.shared.materialIndex
  51739. };
  51740. }
  51741. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  51742. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  51743. polygonIndices[0] = 0;
  51744. polygonIndices[1] = j - 1;
  51745. polygonIndices[2] = j;
  51746. for (var k = 0; k < 3; k++) {
  51747. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  51748. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  51749. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  51750. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  51751. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  51752. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  51753. // Check if 2 points can be merged
  51754. if (!(typeof vertex_idx !== 'undefined' &&
  51755. normals[vertex_idx * 3] === localNormal.x &&
  51756. normals[vertex_idx * 3 + 1] === localNormal.y &&
  51757. normals[vertex_idx * 3 + 2] === localNormal.z &&
  51758. uvs[vertex_idx * 2] === uv.x &&
  51759. uvs[vertex_idx * 2 + 1] === uv.y)) {
  51760. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  51761. uvs.push(uv.x, uv.y);
  51762. normals.push(normal.x, normal.y, normal.z);
  51763. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  51764. }
  51765. indices.push(vertex_idx);
  51766. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  51767. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  51768. currentIndex++;
  51769. }
  51770. }
  51771. }
  51772. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  51773. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  51774. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  51775. mesh.setIndices(indices);
  51776. if (keepSubMeshes) {
  51777. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  51778. var materialIndexOffset = 0, materialMaxIndex;
  51779. mesh.subMeshes = new Array();
  51780. for (var m in subMesh_dict) {
  51781. materialMaxIndex = -1;
  51782. for (var sm in subMesh_dict[m]) {
  51783. subMesh_obj = subMesh_dict[m][sm];
  51784. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  51785. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  51786. }
  51787. materialIndexOffset += ++materialMaxIndex;
  51788. }
  51789. }
  51790. return mesh;
  51791. };
  51792. // Build Mesh from CSG taking material and transforms into account
  51793. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  51794. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  51795. mesh.material = material;
  51796. mesh.position.copyFrom(this.position);
  51797. mesh.rotation.copyFrom(this.rotation);
  51798. if (this.rotationQuaternion) {
  51799. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  51800. }
  51801. mesh.scaling.copyFrom(this.scaling);
  51802. mesh.computeWorldMatrix(true);
  51803. return mesh;
  51804. };
  51805. return CSG;
  51806. })();
  51807. BABYLON.CSG = CSG;
  51808. })(BABYLON || (BABYLON = {}));
  51809. var BABYLON;
  51810. (function (BABYLON) {
  51811. var VRDistortionCorrectionPostProcess = (function (_super) {
  51812. __extends(VRDistortionCorrectionPostProcess, _super);
  51813. //ANY
  51814. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  51815. var _this = this;
  51816. _super.call(this, name, "vrDistortionCorrection", [
  51817. 'LensCenter',
  51818. 'Scale',
  51819. 'ScaleIn',
  51820. 'HmdWarpParam'
  51821. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
  51822. this._isRightEye = isRightEye;
  51823. this._distortionFactors = vrMetrics.distortionK;
  51824. this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  51825. this._lensCenterOffset = vrMetrics.lensCenterOffset;
  51826. this.onSizeChangedObservable.add(function () {
  51827. _this.aspectRatio = _this.width * .5 / _this.height;
  51828. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  51829. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  51830. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  51831. });
  51832. this.onApplyObservable.add(function (effect) {
  51833. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  51834. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  51835. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  51836. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  51837. });
  51838. }
  51839. return VRDistortionCorrectionPostProcess;
  51840. })(BABYLON.PostProcess);
  51841. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  51842. })(BABYLON || (BABYLON = {}));
  51843. // Mainly based on these 2 articles :
  51844. // 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
  51845. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  51846. var BABYLON;
  51847. (function (BABYLON) {
  51848. (function (JoystickAxis) {
  51849. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  51850. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  51851. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  51852. })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  51853. var JoystickAxis = BABYLON.JoystickAxis;
  51854. var VirtualJoystick = (function () {
  51855. function VirtualJoystick(leftJoystick) {
  51856. var _this = this;
  51857. if (leftJoystick) {
  51858. this._leftJoystick = true;
  51859. }
  51860. else {
  51861. this._leftJoystick = false;
  51862. }
  51863. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  51864. VirtualJoystick._globalJoystickIndex++;
  51865. // By default left & right arrow keys are moving the X
  51866. // and up & down keys are moving the Y
  51867. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  51868. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  51869. this.reverseLeftRight = false;
  51870. this.reverseUpDown = false;
  51871. // collections of pointers
  51872. this._touches = new BABYLON.StringDictionary();
  51873. this.deltaPosition = BABYLON.Vector3.Zero();
  51874. this._joystickSensibility = 25;
  51875. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  51876. this._rotationSpeed = 25;
  51877. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  51878. this._rotateOnAxisRelativeToMesh = false;
  51879. this._onResize = function (evt) {
  51880. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  51881. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  51882. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  51883. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  51884. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  51885. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  51886. };
  51887. // injecting a canvas element on top of the canvas 3D game
  51888. if (!VirtualJoystick.vjCanvas) {
  51889. window.addEventListener("resize", this._onResize, false);
  51890. VirtualJoystick.vjCanvas = document.createElement("canvas");
  51891. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  51892. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  51893. VirtualJoystick.vjCanvas.width = window.innerWidth;
  51894. VirtualJoystick.vjCanvas.height = window.innerHeight;
  51895. VirtualJoystick.vjCanvas.style.width = "100%";
  51896. VirtualJoystick.vjCanvas.style.height = "100%";
  51897. VirtualJoystick.vjCanvas.style.position = "absolute";
  51898. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  51899. VirtualJoystick.vjCanvas.style.top = "0px";
  51900. VirtualJoystick.vjCanvas.style.left = "0px";
  51901. VirtualJoystick.vjCanvas.style.zIndex = "5";
  51902. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  51903. // Support for jQuery PEP polyfill
  51904. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  51905. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  51906. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  51907. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  51908. document.body.appendChild(VirtualJoystick.vjCanvas);
  51909. }
  51910. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  51911. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  51912. this.pressed = false;
  51913. // default joystick color
  51914. this._joystickColor = "cyan";
  51915. this._joystickPointerID = -1;
  51916. // current joystick position
  51917. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  51918. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  51919. // origin joystick position
  51920. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  51921. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  51922. this._onPointerDownHandlerRef = function (evt) {
  51923. _this._onPointerDown(evt);
  51924. };
  51925. this._onPointerMoveHandlerRef = function (evt) {
  51926. _this._onPointerMove(evt);
  51927. };
  51928. this._onPointerOutHandlerRef = function (evt) {
  51929. _this._onPointerUp(evt);
  51930. };
  51931. this._onPointerUpHandlerRef = function (evt) {
  51932. _this._onPointerUp(evt);
  51933. };
  51934. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  51935. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  51936. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  51937. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  51938. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  51939. evt.preventDefault(); // Disables system menu
  51940. }, false);
  51941. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  51942. }
  51943. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  51944. this._joystickSensibility = newJoystickSensibility;
  51945. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  51946. };
  51947. VirtualJoystick.prototype._onPointerDown = function (e) {
  51948. var positionOnScreenCondition;
  51949. e.preventDefault();
  51950. if (this._leftJoystick === true) {
  51951. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  51952. }
  51953. else {
  51954. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  51955. }
  51956. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  51957. // First contact will be dedicated to the virtual joystick
  51958. this._joystickPointerID = e.pointerId;
  51959. this._joystickPointerStartPos.x = e.clientX;
  51960. this._joystickPointerStartPos.y = e.clientY;
  51961. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  51962. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  51963. this._deltaJoystickVector.x = 0;
  51964. this._deltaJoystickVector.y = 0;
  51965. this.pressed = true;
  51966. this._touches.add(e.pointerId.toString(), e);
  51967. }
  51968. else {
  51969. // You can only trigger the action buttons with a joystick declared
  51970. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  51971. this._action();
  51972. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  51973. }
  51974. }
  51975. };
  51976. VirtualJoystick.prototype._onPointerMove = function (e) {
  51977. // If the current pointer is the one associated to the joystick (first touch contact)
  51978. if (this._joystickPointerID == e.pointerId) {
  51979. this._joystickPointerPos.x = e.clientX;
  51980. this._joystickPointerPos.y = e.clientY;
  51981. this._deltaJoystickVector = this._joystickPointerPos.clone();
  51982. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  51983. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  51984. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  51985. switch (this._axisTargetedByLeftAndRight) {
  51986. case JoystickAxis.X:
  51987. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  51988. break;
  51989. case JoystickAxis.Y:
  51990. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  51991. break;
  51992. case JoystickAxis.Z:
  51993. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  51994. break;
  51995. }
  51996. var directionUpDown = this.reverseUpDown ? 1 : -1;
  51997. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  51998. switch (this._axisTargetedByUpAndDown) {
  51999. case JoystickAxis.X:
  52000. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  52001. break;
  52002. case JoystickAxis.Y:
  52003. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  52004. break;
  52005. case JoystickAxis.Z:
  52006. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  52007. break;
  52008. }
  52009. }
  52010. else {
  52011. var data = this._touches.get(e.pointerId.toString());
  52012. if (data) {
  52013. data.x = e.clientX;
  52014. data.y = e.clientY;
  52015. }
  52016. }
  52017. };
  52018. VirtualJoystick.prototype._onPointerUp = function (e) {
  52019. if (this._joystickPointerID == e.pointerId) {
  52020. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 63, this._joystickPointerStartPos.y - 63, 126, 126);
  52021. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 41, this._joystickPreviousPointerPos.y - 41, 82, 82);
  52022. this._joystickPointerID = -1;
  52023. this.pressed = false;
  52024. }
  52025. else {
  52026. var touch = this._touches.get(e.pointerId.toString());
  52027. if (touch) {
  52028. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  52029. }
  52030. }
  52031. this._deltaJoystickVector.x = 0;
  52032. this._deltaJoystickVector.y = 0;
  52033. this._touches.remove(e.pointerId.toString());
  52034. };
  52035. /**
  52036. * Change the color of the virtual joystick
  52037. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  52038. */
  52039. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  52040. this._joystickColor = newColor;
  52041. };
  52042. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  52043. this._action = action;
  52044. };
  52045. // Define which axis you'd like to control for left & right
  52046. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  52047. switch (axis) {
  52048. case JoystickAxis.X:
  52049. case JoystickAxis.Y:
  52050. case JoystickAxis.Z:
  52051. this._axisTargetedByLeftAndRight = axis;
  52052. break;
  52053. default:
  52054. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  52055. break;
  52056. }
  52057. };
  52058. // Define which axis you'd like to control for up & down
  52059. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  52060. switch (axis) {
  52061. case JoystickAxis.X:
  52062. case JoystickAxis.Y:
  52063. case JoystickAxis.Z:
  52064. this._axisTargetedByUpAndDown = axis;
  52065. break;
  52066. default:
  52067. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  52068. break;
  52069. }
  52070. };
  52071. VirtualJoystick.prototype._clearCanvas = function () {
  52072. if (this._leftJoystick) {
  52073. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  52074. }
  52075. else {
  52076. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  52077. }
  52078. };
  52079. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  52080. var _this = this;
  52081. if (this.pressed) {
  52082. this._touches.forEach(function (touch) {
  52083. if (touch.pointerId === _this._joystickPointerID) {
  52084. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 63, _this._joystickPointerStartPos.y - 63, 126, 126);
  52085. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 41, _this._joystickPreviousPointerPos.y - 41, 82, 82);
  52086. VirtualJoystick.vjCanvasContext.beginPath();
  52087. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  52088. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  52089. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  52090. VirtualJoystick.vjCanvasContext.stroke();
  52091. VirtualJoystick.vjCanvasContext.closePath();
  52092. VirtualJoystick.vjCanvasContext.beginPath();
  52093. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  52094. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  52095. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  52096. VirtualJoystick.vjCanvasContext.stroke();
  52097. VirtualJoystick.vjCanvasContext.closePath();
  52098. VirtualJoystick.vjCanvasContext.beginPath();
  52099. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  52100. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  52101. VirtualJoystick.vjCanvasContext.stroke();
  52102. VirtualJoystick.vjCanvasContext.closePath();
  52103. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  52104. }
  52105. else {
  52106. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  52107. VirtualJoystick.vjCanvasContext.beginPath();
  52108. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  52109. VirtualJoystick.vjCanvasContext.beginPath();
  52110. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  52111. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  52112. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  52113. VirtualJoystick.vjCanvasContext.stroke();
  52114. VirtualJoystick.vjCanvasContext.closePath();
  52115. touch.prevX = touch.x;
  52116. touch.prevY = touch.y;
  52117. }
  52118. ;
  52119. });
  52120. }
  52121. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  52122. };
  52123. VirtualJoystick.prototype.releaseCanvas = function () {
  52124. if (VirtualJoystick.vjCanvas) {
  52125. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  52126. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  52127. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  52128. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  52129. window.removeEventListener("resize", this._onResize);
  52130. document.body.removeChild(VirtualJoystick.vjCanvas);
  52131. VirtualJoystick.vjCanvas = null;
  52132. }
  52133. };
  52134. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  52135. VirtualJoystick._globalJoystickIndex = 0;
  52136. return VirtualJoystick;
  52137. })();
  52138. BABYLON.VirtualJoystick = VirtualJoystick;
  52139. })(BABYLON || (BABYLON = {}));
  52140. var BABYLON;
  52141. (function (BABYLON) {
  52142. // We're mainly based on the logic defined into the FreeCamera code
  52143. var VirtualJoysticksCamera = (function (_super) {
  52144. __extends(VirtualJoysticksCamera, _super);
  52145. function VirtualJoysticksCamera(name, position, scene) {
  52146. _super.call(this, name, position, scene);
  52147. this.inputs.addVirtualJoystick();
  52148. }
  52149. return VirtualJoysticksCamera;
  52150. })(BABYLON.FreeCamera);
  52151. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  52152. })(BABYLON || (BABYLON = {}));
  52153. var BABYLON;
  52154. (function (BABYLON) {
  52155. var FreeCameraVirtualJoystickInput = (function () {
  52156. function FreeCameraVirtualJoystickInput() {
  52157. }
  52158. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  52159. return this._leftjoystick;
  52160. };
  52161. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  52162. return this._rightjoystick;
  52163. };
  52164. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  52165. if (this._leftjoystick) {
  52166. var camera = this.camera;
  52167. var speed = camera._computeLocalCameraSpeed() * 50;
  52168. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  52169. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  52170. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  52171. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  52172. if (!this._leftjoystick.pressed) {
  52173. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  52174. }
  52175. if (!this._rightjoystick.pressed) {
  52176. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  52177. }
  52178. }
  52179. };
  52180. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  52181. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  52182. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  52183. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  52184. this._leftjoystick.setJoystickSensibility(0.15);
  52185. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  52186. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  52187. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  52188. this._rightjoystick.reverseUpDown = true;
  52189. this._rightjoystick.setJoystickSensibility(0.05);
  52190. this._rightjoystick.setJoystickColor("yellow");
  52191. };
  52192. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  52193. this._leftjoystick.releaseCanvas();
  52194. this._rightjoystick.releaseCanvas();
  52195. };
  52196. FreeCameraVirtualJoystickInput.prototype.getTypeName = function () {
  52197. return "FreeCameraVirtualJoystickInput";
  52198. };
  52199. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  52200. return "virtualJoystick";
  52201. };
  52202. return FreeCameraVirtualJoystickInput;
  52203. })();
  52204. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  52205. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  52206. })(BABYLON || (BABYLON = {}));
  52207. var BABYLON;
  52208. (function (BABYLON) {
  52209. var AnaglyphPostProcess = (function (_super) {
  52210. __extends(AnaglyphPostProcess, _super);
  52211. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  52212. var _this = this;
  52213. _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable);
  52214. this._passedProcess = rigCameras[0]._rigPostProcess;
  52215. this.onApplyObservable.add(function (effect) {
  52216. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  52217. });
  52218. }
  52219. return AnaglyphPostProcess;
  52220. })(BABYLON.PostProcess);
  52221. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  52222. })(BABYLON || (BABYLON = {}));
  52223. var BABYLON;
  52224. (function (BABYLON) {
  52225. var OutlineRenderer = (function () {
  52226. function OutlineRenderer(scene) {
  52227. this._scene = scene;
  52228. }
  52229. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  52230. var _this = this;
  52231. if (useOverlay === void 0) { useOverlay = false; }
  52232. var scene = this._scene;
  52233. var engine = this._scene.getEngine();
  52234. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  52235. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  52236. return;
  52237. }
  52238. var mesh = subMesh.getRenderingMesh();
  52239. var material = subMesh.getMaterial();
  52240. engine.enableEffect(this._effect);
  52241. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  52242. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  52243. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  52244. // Bones
  52245. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  52246. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  52247. }
  52248. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  52249. // Alpha test
  52250. if (material && material.needAlphaTesting()) {
  52251. var alphaTexture = material.getAlphaTestTexture();
  52252. this._effect.setTexture("diffuseSampler", alphaTexture);
  52253. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  52254. }
  52255. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  52256. };
  52257. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  52258. var defines = [];
  52259. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  52260. var mesh = subMesh.getMesh();
  52261. var material = subMesh.getMaterial();
  52262. // Alpha test
  52263. if (material && material.needAlphaTesting()) {
  52264. defines.push("#define ALPHATEST");
  52265. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  52266. attribs.push(BABYLON.VertexBuffer.UVKind);
  52267. defines.push("#define UV1");
  52268. }
  52269. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  52270. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  52271. defines.push("#define UV2");
  52272. }
  52273. }
  52274. // Bones
  52275. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  52276. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  52277. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  52278. if (mesh.numBoneInfluencers > 4) {
  52279. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  52280. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  52281. }
  52282. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  52283. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  52284. }
  52285. else {
  52286. defines.push("#define NUM_BONE_INFLUENCERS 0");
  52287. }
  52288. // Instances
  52289. if (useInstances) {
  52290. defines.push("#define INSTANCES");
  52291. attribs.push("world0");
  52292. attribs.push("world1");
  52293. attribs.push("world2");
  52294. attribs.push("world3");
  52295. }
  52296. // Get correct effect
  52297. var join = defines.join("\n");
  52298. if (this._cachedDefines !== join) {
  52299. this._cachedDefines = join;
  52300. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  52301. }
  52302. return this._effect.isReady();
  52303. };
  52304. return OutlineRenderer;
  52305. })();
  52306. BABYLON.OutlineRenderer = OutlineRenderer;
  52307. })(BABYLON || (BABYLON = {}));
  52308. var BABYLON;
  52309. (function (BABYLON) {
  52310. var MeshAssetTask = (function () {
  52311. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  52312. this.name = name;
  52313. this.meshesNames = meshesNames;
  52314. this.rootUrl = rootUrl;
  52315. this.sceneFilename = sceneFilename;
  52316. this.isCompleted = false;
  52317. }
  52318. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  52319. var _this = this;
  52320. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  52321. _this.loadedMeshes = meshes;
  52322. _this.loadedParticleSystems = particleSystems;
  52323. _this.loadedSkeletons = skeletons;
  52324. _this.isCompleted = true;
  52325. if (_this.onSuccess) {
  52326. _this.onSuccess(_this);
  52327. }
  52328. onSuccess();
  52329. }, null, function () {
  52330. if (_this.onError) {
  52331. _this.onError(_this);
  52332. }
  52333. onError();
  52334. });
  52335. };
  52336. return MeshAssetTask;
  52337. })();
  52338. BABYLON.MeshAssetTask = MeshAssetTask;
  52339. var TextFileAssetTask = (function () {
  52340. function TextFileAssetTask(name, url) {
  52341. this.name = name;
  52342. this.url = url;
  52343. this.isCompleted = false;
  52344. }
  52345. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  52346. var _this = this;
  52347. BABYLON.Tools.LoadFile(this.url, function (data) {
  52348. _this.text = data;
  52349. _this.isCompleted = true;
  52350. if (_this.onSuccess) {
  52351. _this.onSuccess(_this);
  52352. }
  52353. onSuccess();
  52354. }, null, scene.database, false, function () {
  52355. if (_this.onError) {
  52356. _this.onError(_this);
  52357. }
  52358. onError();
  52359. });
  52360. };
  52361. return TextFileAssetTask;
  52362. })();
  52363. BABYLON.TextFileAssetTask = TextFileAssetTask;
  52364. var BinaryFileAssetTask = (function () {
  52365. function BinaryFileAssetTask(name, url) {
  52366. this.name = name;
  52367. this.url = url;
  52368. this.isCompleted = false;
  52369. }
  52370. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  52371. var _this = this;
  52372. BABYLON.Tools.LoadFile(this.url, function (data) {
  52373. _this.data = data;
  52374. _this.isCompleted = true;
  52375. if (_this.onSuccess) {
  52376. _this.onSuccess(_this);
  52377. }
  52378. onSuccess();
  52379. }, null, scene.database, true, function () {
  52380. if (_this.onError) {
  52381. _this.onError(_this);
  52382. }
  52383. onError();
  52384. });
  52385. };
  52386. return BinaryFileAssetTask;
  52387. })();
  52388. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  52389. var ImageAssetTask = (function () {
  52390. function ImageAssetTask(name, url) {
  52391. this.name = name;
  52392. this.url = url;
  52393. this.isCompleted = false;
  52394. }
  52395. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  52396. var _this = this;
  52397. var img = new Image();
  52398. BABYLON.Tools.SetCorsBehavior(this.url, img);
  52399. img.onload = function () {
  52400. _this.image = img;
  52401. _this.isCompleted = true;
  52402. if (_this.onSuccess) {
  52403. _this.onSuccess(_this);
  52404. }
  52405. onSuccess();
  52406. };
  52407. img.onerror = function () {
  52408. if (_this.onError) {
  52409. _this.onError(_this);
  52410. }
  52411. onError();
  52412. };
  52413. img.src = this.url;
  52414. };
  52415. return ImageAssetTask;
  52416. })();
  52417. BABYLON.ImageAssetTask = ImageAssetTask;
  52418. var TextureAssetTask = (function () {
  52419. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  52420. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  52421. this.name = name;
  52422. this.url = url;
  52423. this.noMipmap = noMipmap;
  52424. this.invertY = invertY;
  52425. this.samplingMode = samplingMode;
  52426. this.isCompleted = false;
  52427. }
  52428. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  52429. var _this = this;
  52430. var onload = function () {
  52431. _this.isCompleted = true;
  52432. if (_this.onSuccess) {
  52433. _this.onSuccess(_this);
  52434. }
  52435. onSuccess();
  52436. };
  52437. var onerror = function () {
  52438. if (_this.onError) {
  52439. _this.onError(_this);
  52440. }
  52441. onError();
  52442. };
  52443. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  52444. };
  52445. return TextureAssetTask;
  52446. })();
  52447. BABYLON.TextureAssetTask = TextureAssetTask;
  52448. var AssetsManager = (function () {
  52449. function AssetsManager(scene) {
  52450. this._tasks = new Array();
  52451. this._waitingTasksCount = 0;
  52452. this.useDefaultLoadingScreen = true;
  52453. this._scene = scene;
  52454. }
  52455. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  52456. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  52457. this._tasks.push(task);
  52458. return task;
  52459. };
  52460. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  52461. var task = new TextFileAssetTask(taskName, url);
  52462. this._tasks.push(task);
  52463. return task;
  52464. };
  52465. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  52466. var task = new BinaryFileAssetTask(taskName, url);
  52467. this._tasks.push(task);
  52468. return task;
  52469. };
  52470. AssetsManager.prototype.addImageTask = function (taskName, url) {
  52471. var task = new ImageAssetTask(taskName, url);
  52472. this._tasks.push(task);
  52473. return task;
  52474. };
  52475. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  52476. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  52477. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  52478. this._tasks.push(task);
  52479. return task;
  52480. };
  52481. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  52482. this._waitingTasksCount--;
  52483. if (this._waitingTasksCount === 0) {
  52484. if (this.onFinish) {
  52485. this.onFinish(this._tasks);
  52486. }
  52487. this._scene.getEngine().hideLoadingUI();
  52488. }
  52489. };
  52490. AssetsManager.prototype._runTask = function (task) {
  52491. var _this = this;
  52492. task.run(this._scene, function () {
  52493. if (_this.onTaskSuccess) {
  52494. _this.onTaskSuccess(task);
  52495. }
  52496. _this._decreaseWaitingTasksCount();
  52497. }, function () {
  52498. if (_this.onTaskError) {
  52499. _this.onTaskError(task);
  52500. }
  52501. _this._decreaseWaitingTasksCount();
  52502. });
  52503. };
  52504. AssetsManager.prototype.reset = function () {
  52505. this._tasks = new Array();
  52506. return this;
  52507. };
  52508. AssetsManager.prototype.load = function () {
  52509. this._waitingTasksCount = this._tasks.length;
  52510. if (this._waitingTasksCount === 0) {
  52511. if (this.onFinish) {
  52512. this.onFinish(this._tasks);
  52513. }
  52514. return this;
  52515. }
  52516. if (this.useDefaultLoadingScreen) {
  52517. this._scene.getEngine().displayLoadingUI();
  52518. }
  52519. for (var index = 0; index < this._tasks.length; index++) {
  52520. var task = this._tasks[index];
  52521. this._runTask(task);
  52522. }
  52523. return this;
  52524. };
  52525. return AssetsManager;
  52526. })();
  52527. BABYLON.AssetsManager = AssetsManager;
  52528. })(BABYLON || (BABYLON = {}));
  52529. var BABYLON;
  52530. (function (BABYLON) {
  52531. var VRCameraMetrics = (function () {
  52532. function VRCameraMetrics() {
  52533. this.compensateDistortion = true;
  52534. }
  52535. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  52536. get: function () {
  52537. return this.hResolution / (2 * this.vResolution);
  52538. },
  52539. enumerable: true,
  52540. configurable: true
  52541. });
  52542. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  52543. get: function () {
  52544. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  52545. },
  52546. enumerable: true,
  52547. configurable: true
  52548. });
  52549. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  52550. get: function () {
  52551. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  52552. var h = (4 * meters) / this.hScreenSize;
  52553. return BABYLON.Matrix.Translation(h, 0, 0);
  52554. },
  52555. enumerable: true,
  52556. configurable: true
  52557. });
  52558. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  52559. get: function () {
  52560. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  52561. var h = (4 * meters) / this.hScreenSize;
  52562. return BABYLON.Matrix.Translation(-h, 0, 0);
  52563. },
  52564. enumerable: true,
  52565. configurable: true
  52566. });
  52567. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  52568. get: function () {
  52569. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  52570. },
  52571. enumerable: true,
  52572. configurable: true
  52573. });
  52574. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  52575. get: function () {
  52576. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  52577. },
  52578. enumerable: true,
  52579. configurable: true
  52580. });
  52581. VRCameraMetrics.GetDefault = function () {
  52582. var result = new VRCameraMetrics();
  52583. result.hResolution = 1280;
  52584. result.vResolution = 800;
  52585. result.hScreenSize = 0.149759993;
  52586. result.vScreenSize = 0.0935999975;
  52587. result.vScreenCenter = 0.0467999987,
  52588. result.eyeToScreenDistance = 0.0410000011;
  52589. result.lensSeparationDistance = 0.0635000020;
  52590. result.interpupillaryDistance = 0.0640000030;
  52591. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  52592. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  52593. result.postProcessScaleFactor = 1.714605507808412;
  52594. result.lensCenterOffset = 0.151976421;
  52595. return result;
  52596. };
  52597. return VRCameraMetrics;
  52598. })();
  52599. BABYLON.VRCameraMetrics = VRCameraMetrics;
  52600. })(BABYLON || (BABYLON = {}));
  52601. var BABYLON;
  52602. (function (BABYLON) {
  52603. var WebVRFreeCamera = (function (_super) {
  52604. __extends(WebVRFreeCamera, _super);
  52605. function WebVRFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  52606. if (compensateDistortion === void 0) { compensateDistortion = true; }
  52607. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  52608. _super.call(this, name, position, scene);
  52609. this._hmdDevice = null;
  52610. this._sensorDevice = null;
  52611. this._cacheState = null;
  52612. this._vrEnabled = false;
  52613. vrCameraMetrics.compensateDistortion = compensateDistortion;
  52614. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  52615. this._getWebVRDevices = this._getWebVRDevices.bind(this);
  52616. this.rotationQuaternion = new BABYLON.Quaternion();
  52617. this._quaternionCache = new BABYLON.Quaternion();
  52618. }
  52619. WebVRFreeCamera.prototype._getWebVRDevices = function (devices) {
  52620. var size = devices.length;
  52621. var i = 0;
  52622. // Reset devices.
  52623. this._sensorDevice = null;
  52624. this._hmdDevice = null;
  52625. // Search for a HmdDevice.
  52626. while (i < size && this._hmdDevice === null) {
  52627. if (devices[i] instanceof HMDVRDevice) {
  52628. this._hmdDevice = devices[i];
  52629. }
  52630. i++;
  52631. }
  52632. i = 0;
  52633. while (i < size && this._sensorDevice === null) {
  52634. if (devices[i] instanceof PositionSensorVRDevice && (!this._hmdDevice || devices[i].hardwareUnitId === this._hmdDevice.hardwareUnitId)) {
  52635. this._sensorDevice = devices[i];
  52636. }
  52637. i++;
  52638. }
  52639. this._vrEnabled = this._sensorDevice && this._hmdDevice ? true : false;
  52640. };
  52641. WebVRFreeCamera.prototype._checkInputs = function () {
  52642. if (this._vrEnabled) {
  52643. this._cacheState = this._sensorDevice.getState();
  52644. this.rotationQuaternion.copyFrom(this._cacheState.orientation);
  52645. //Flip in XY plane
  52646. this.rotationQuaternion.z *= -1;
  52647. this.rotationQuaternion.w *= -1;
  52648. if (this._initialQuaternion) {
  52649. this._quaternionCache.copyFrom(this.rotationQuaternion);
  52650. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  52651. }
  52652. }
  52653. _super.prototype._checkInputs.call(this);
  52654. };
  52655. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  52656. _super.prototype.attachControl.call(this, element, noPreventDefault);
  52657. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  52658. if (navigator.getVRDevices) {
  52659. navigator.getVRDevices().then(this._getWebVRDevices);
  52660. }
  52661. else if (navigator.mozGetVRDevices) {
  52662. navigator.mozGetVRDevices(this._getWebVRDevices);
  52663. }
  52664. };
  52665. WebVRFreeCamera.prototype.detachControl = function (element) {
  52666. _super.prototype.detachControl.call(this, element);
  52667. this._vrEnabled = false;
  52668. };
  52669. WebVRFreeCamera.prototype.requestVRFullscreen = function (requestPointerlock) {
  52670. if (!this._hmdDevice)
  52671. return;
  52672. this.getEngine().switchFullscreen(requestPointerlock, { vrDisplay: this._hmdDevice });
  52673. };
  52674. WebVRFreeCamera.prototype.getTypeName = function () {
  52675. return "WebVRFreeCamera";
  52676. };
  52677. WebVRFreeCamera.prototype.resetToCurrentRotation = function (axis) {
  52678. var _this = this;
  52679. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  52680. //can only work if this camera has a rotation quaternion already.
  52681. if (!this.rotationQuaternion)
  52682. return;
  52683. if (!this._initialQuaternion) {
  52684. this._initialQuaternion = new BABYLON.Quaternion();
  52685. }
  52686. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  52687. ['x', 'y', 'z'].forEach(function (axisName) {
  52688. if (!axis[axisName]) {
  52689. _this._initialQuaternion[axisName] = 0;
  52690. }
  52691. else {
  52692. _this._initialQuaternion[axisName] *= -1;
  52693. }
  52694. });
  52695. this._initialQuaternion.normalize();
  52696. };
  52697. return WebVRFreeCamera;
  52698. })(BABYLON.FreeCamera);
  52699. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  52700. })(BABYLON || (BABYLON = {}));
  52701. var BABYLON;
  52702. (function (BABYLON) {
  52703. // Standard optimizations
  52704. var SceneOptimization = (function () {
  52705. function SceneOptimization(priority) {
  52706. if (priority === void 0) { priority = 0; }
  52707. this.priority = priority;
  52708. this.apply = function (scene) {
  52709. return true; // Return true if everything that can be done was applied
  52710. };
  52711. }
  52712. return SceneOptimization;
  52713. })();
  52714. BABYLON.SceneOptimization = SceneOptimization;
  52715. var TextureOptimization = (function (_super) {
  52716. __extends(TextureOptimization, _super);
  52717. function TextureOptimization(priority, maximumSize) {
  52718. var _this = this;
  52719. if (priority === void 0) { priority = 0; }
  52720. if (maximumSize === void 0) { maximumSize = 1024; }
  52721. _super.call(this, priority);
  52722. this.priority = priority;
  52723. this.maximumSize = maximumSize;
  52724. this.apply = function (scene) {
  52725. var allDone = true;
  52726. for (var index = 0; index < scene.textures.length; index++) {
  52727. var texture = scene.textures[index];
  52728. if (!texture.canRescale) {
  52729. continue;
  52730. }
  52731. var currentSize = texture.getSize();
  52732. var maxDimension = Math.max(currentSize.width, currentSize.height);
  52733. if (maxDimension > _this.maximumSize) {
  52734. texture.scale(0.5);
  52735. allDone = false;
  52736. }
  52737. }
  52738. return allDone;
  52739. };
  52740. }
  52741. return TextureOptimization;
  52742. })(SceneOptimization);
  52743. BABYLON.TextureOptimization = TextureOptimization;
  52744. var HardwareScalingOptimization = (function (_super) {
  52745. __extends(HardwareScalingOptimization, _super);
  52746. function HardwareScalingOptimization(priority, maximumScale) {
  52747. var _this = this;
  52748. if (priority === void 0) { priority = 0; }
  52749. if (maximumScale === void 0) { maximumScale = 2; }
  52750. _super.call(this, priority);
  52751. this.priority = priority;
  52752. this.maximumScale = maximumScale;
  52753. this._currentScale = 1;
  52754. this.apply = function (scene) {
  52755. _this._currentScale++;
  52756. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  52757. return _this._currentScale >= _this.maximumScale;
  52758. };
  52759. }
  52760. return HardwareScalingOptimization;
  52761. })(SceneOptimization);
  52762. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  52763. var ShadowsOptimization = (function (_super) {
  52764. __extends(ShadowsOptimization, _super);
  52765. function ShadowsOptimization() {
  52766. _super.apply(this, arguments);
  52767. this.apply = function (scene) {
  52768. scene.shadowsEnabled = false;
  52769. return true;
  52770. };
  52771. }
  52772. return ShadowsOptimization;
  52773. })(SceneOptimization);
  52774. BABYLON.ShadowsOptimization = ShadowsOptimization;
  52775. var PostProcessesOptimization = (function (_super) {
  52776. __extends(PostProcessesOptimization, _super);
  52777. function PostProcessesOptimization() {
  52778. _super.apply(this, arguments);
  52779. this.apply = function (scene) {
  52780. scene.postProcessesEnabled = false;
  52781. return true;
  52782. };
  52783. }
  52784. return PostProcessesOptimization;
  52785. })(SceneOptimization);
  52786. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  52787. var LensFlaresOptimization = (function (_super) {
  52788. __extends(LensFlaresOptimization, _super);
  52789. function LensFlaresOptimization() {
  52790. _super.apply(this, arguments);
  52791. this.apply = function (scene) {
  52792. scene.lensFlaresEnabled = false;
  52793. return true;
  52794. };
  52795. }
  52796. return LensFlaresOptimization;
  52797. })(SceneOptimization);
  52798. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  52799. var ParticlesOptimization = (function (_super) {
  52800. __extends(ParticlesOptimization, _super);
  52801. function ParticlesOptimization() {
  52802. _super.apply(this, arguments);
  52803. this.apply = function (scene) {
  52804. scene.particlesEnabled = false;
  52805. return true;
  52806. };
  52807. }
  52808. return ParticlesOptimization;
  52809. })(SceneOptimization);
  52810. BABYLON.ParticlesOptimization = ParticlesOptimization;
  52811. var RenderTargetsOptimization = (function (_super) {
  52812. __extends(RenderTargetsOptimization, _super);
  52813. function RenderTargetsOptimization() {
  52814. _super.apply(this, arguments);
  52815. this.apply = function (scene) {
  52816. scene.renderTargetsEnabled = false;
  52817. return true;
  52818. };
  52819. }
  52820. return RenderTargetsOptimization;
  52821. })(SceneOptimization);
  52822. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  52823. var MergeMeshesOptimization = (function (_super) {
  52824. __extends(MergeMeshesOptimization, _super);
  52825. function MergeMeshesOptimization() {
  52826. var _this = this;
  52827. _super.apply(this, arguments);
  52828. this._canBeMerged = function (abstractMesh) {
  52829. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  52830. return false;
  52831. }
  52832. var mesh = abstractMesh;
  52833. if (!mesh.isVisible || !mesh.isEnabled()) {
  52834. return false;
  52835. }
  52836. if (mesh.instances.length > 0) {
  52837. return false;
  52838. }
  52839. if (mesh.skeleton || mesh.hasLODLevels) {
  52840. return false;
  52841. }
  52842. if (mesh.parent) {
  52843. return false;
  52844. }
  52845. return true;
  52846. };
  52847. this.apply = function (scene, updateSelectionTree) {
  52848. var globalPool = scene.meshes.slice(0);
  52849. var globalLength = globalPool.length;
  52850. for (var index = 0; index < globalLength; index++) {
  52851. var currentPool = new Array();
  52852. var current = globalPool[index];
  52853. // Checks
  52854. if (!_this._canBeMerged(current)) {
  52855. continue;
  52856. }
  52857. currentPool.push(current);
  52858. // Find compatible meshes
  52859. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  52860. var otherMesh = globalPool[subIndex];
  52861. if (!_this._canBeMerged(otherMesh)) {
  52862. continue;
  52863. }
  52864. if (otherMesh.material !== current.material) {
  52865. continue;
  52866. }
  52867. if (otherMesh.checkCollisions !== current.checkCollisions) {
  52868. continue;
  52869. }
  52870. currentPool.push(otherMesh);
  52871. globalLength--;
  52872. globalPool.splice(subIndex, 1);
  52873. subIndex--;
  52874. }
  52875. if (currentPool.length < 2) {
  52876. continue;
  52877. }
  52878. // Merge meshes
  52879. BABYLON.Mesh.MergeMeshes(currentPool);
  52880. }
  52881. if (updateSelectionTree != undefined) {
  52882. if (updateSelectionTree) {
  52883. scene.createOrUpdateSelectionOctree();
  52884. }
  52885. }
  52886. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  52887. scene.createOrUpdateSelectionOctree();
  52888. }
  52889. return true;
  52890. };
  52891. }
  52892. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  52893. get: function () {
  52894. return MergeMeshesOptimization._UpdateSelectionTree;
  52895. },
  52896. set: function (value) {
  52897. MergeMeshesOptimization._UpdateSelectionTree = value;
  52898. },
  52899. enumerable: true,
  52900. configurable: true
  52901. });
  52902. MergeMeshesOptimization._UpdateSelectionTree = false;
  52903. return MergeMeshesOptimization;
  52904. })(SceneOptimization);
  52905. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  52906. // Options
  52907. var SceneOptimizerOptions = (function () {
  52908. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  52909. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  52910. if (trackerDuration === void 0) { trackerDuration = 2000; }
  52911. this.targetFrameRate = targetFrameRate;
  52912. this.trackerDuration = trackerDuration;
  52913. this.optimizations = new Array();
  52914. }
  52915. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  52916. var result = new SceneOptimizerOptions(targetFrameRate);
  52917. var priority = 0;
  52918. result.optimizations.push(new MergeMeshesOptimization(priority));
  52919. result.optimizations.push(new ShadowsOptimization(priority));
  52920. result.optimizations.push(new LensFlaresOptimization(priority));
  52921. // Next priority
  52922. priority++;
  52923. result.optimizations.push(new PostProcessesOptimization(priority));
  52924. result.optimizations.push(new ParticlesOptimization(priority));
  52925. // Next priority
  52926. priority++;
  52927. result.optimizations.push(new TextureOptimization(priority, 1024));
  52928. return result;
  52929. };
  52930. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  52931. var result = new SceneOptimizerOptions(targetFrameRate);
  52932. var priority = 0;
  52933. result.optimizations.push(new MergeMeshesOptimization(priority));
  52934. result.optimizations.push(new ShadowsOptimization(priority));
  52935. result.optimizations.push(new LensFlaresOptimization(priority));
  52936. // Next priority
  52937. priority++;
  52938. result.optimizations.push(new PostProcessesOptimization(priority));
  52939. result.optimizations.push(new ParticlesOptimization(priority));
  52940. // Next priority
  52941. priority++;
  52942. result.optimizations.push(new TextureOptimization(priority, 512));
  52943. // Next priority
  52944. priority++;
  52945. result.optimizations.push(new RenderTargetsOptimization(priority));
  52946. // Next priority
  52947. priority++;
  52948. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  52949. return result;
  52950. };
  52951. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  52952. var result = new SceneOptimizerOptions(targetFrameRate);
  52953. var priority = 0;
  52954. result.optimizations.push(new MergeMeshesOptimization(priority));
  52955. result.optimizations.push(new ShadowsOptimization(priority));
  52956. result.optimizations.push(new LensFlaresOptimization(priority));
  52957. // Next priority
  52958. priority++;
  52959. result.optimizations.push(new PostProcessesOptimization(priority));
  52960. result.optimizations.push(new ParticlesOptimization(priority));
  52961. // Next priority
  52962. priority++;
  52963. result.optimizations.push(new TextureOptimization(priority, 256));
  52964. // Next priority
  52965. priority++;
  52966. result.optimizations.push(new RenderTargetsOptimization(priority));
  52967. // Next priority
  52968. priority++;
  52969. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  52970. return result;
  52971. };
  52972. return SceneOptimizerOptions;
  52973. })();
  52974. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  52975. // Scene optimizer tool
  52976. var SceneOptimizer = (function () {
  52977. function SceneOptimizer() {
  52978. }
  52979. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  52980. // TODO: add an epsilon
  52981. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  52982. if (onSuccess) {
  52983. onSuccess();
  52984. }
  52985. return;
  52986. }
  52987. // Apply current level of optimizations
  52988. var allDone = true;
  52989. var noOptimizationApplied = true;
  52990. for (var index = 0; index < options.optimizations.length; index++) {
  52991. var optimization = options.optimizations[index];
  52992. if (optimization.priority === currentPriorityLevel) {
  52993. noOptimizationApplied = false;
  52994. allDone = allDone && optimization.apply(scene);
  52995. }
  52996. }
  52997. // If no optimization was applied, this is a failure :(
  52998. if (noOptimizationApplied) {
  52999. if (onFailure) {
  53000. onFailure();
  53001. }
  53002. return;
  53003. }
  53004. // If all optimizations were done, move to next level
  53005. if (allDone) {
  53006. currentPriorityLevel++;
  53007. }
  53008. // Let's the system running for a specific amount of time before checking FPS
  53009. scene.executeWhenReady(function () {
  53010. setTimeout(function () {
  53011. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  53012. }, options.trackerDuration);
  53013. });
  53014. };
  53015. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  53016. if (!options) {
  53017. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  53018. }
  53019. // Let's the system running for a specific amount of time before checking FPS
  53020. scene.executeWhenReady(function () {
  53021. setTimeout(function () {
  53022. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  53023. }, options.trackerDuration);
  53024. });
  53025. };
  53026. return SceneOptimizer;
  53027. })();
  53028. BABYLON.SceneOptimizer = SceneOptimizer;
  53029. })(BABYLON || (BABYLON = {}));
  53030. var BABYLON;
  53031. (function (BABYLON) {
  53032. var Internals;
  53033. (function (Internals) {
  53034. var MeshLODLevel = (function () {
  53035. function MeshLODLevel(distance, mesh) {
  53036. this.distance = distance;
  53037. this.mesh = mesh;
  53038. }
  53039. return MeshLODLevel;
  53040. })();
  53041. Internals.MeshLODLevel = MeshLODLevel;
  53042. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  53043. })(BABYLON || (BABYLON = {}));
  53044. var BABYLON;
  53045. (function (BABYLON) {
  53046. var RawTexture = (function (_super) {
  53047. __extends(RawTexture, _super);
  53048. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  53049. if (generateMipMaps === void 0) { generateMipMaps = true; }
  53050. if (invertY === void 0) { invertY = false; }
  53051. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  53052. _super.call(this, null, scene, !generateMipMaps, invertY);
  53053. this.format = format;
  53054. this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  53055. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53056. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53057. }
  53058. RawTexture.prototype.update = function (data) {
  53059. this.getScene().getEngine().updateRawTexture(this._texture, data, this.format, this._invertY);
  53060. };
  53061. // Statics
  53062. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  53063. if (generateMipMaps === void 0) { generateMipMaps = true; }
  53064. if (invertY === void 0) { invertY = false; }
  53065. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  53066. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  53067. };
  53068. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  53069. if (generateMipMaps === void 0) { generateMipMaps = true; }
  53070. if (invertY === void 0) { invertY = false; }
  53071. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  53072. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  53073. };
  53074. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  53075. if (generateMipMaps === void 0) { generateMipMaps = true; }
  53076. if (invertY === void 0) { invertY = false; }
  53077. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  53078. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  53079. };
  53080. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  53081. if (generateMipMaps === void 0) { generateMipMaps = true; }
  53082. if (invertY === void 0) { invertY = false; }
  53083. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  53084. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  53085. };
  53086. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  53087. if (generateMipMaps === void 0) { generateMipMaps = true; }
  53088. if (invertY === void 0) { invertY = false; }
  53089. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  53090. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  53091. };
  53092. return RawTexture;
  53093. })(BABYLON.Texture);
  53094. BABYLON.RawTexture = RawTexture;
  53095. })(BABYLON || (BABYLON = {}));
  53096. var BABYLON;
  53097. (function (BABYLON) {
  53098. var IndexedVector2 = (function (_super) {
  53099. __extends(IndexedVector2, _super);
  53100. function IndexedVector2(original, index) {
  53101. _super.call(this, original.x, original.y);
  53102. this.index = index;
  53103. }
  53104. return IndexedVector2;
  53105. })(BABYLON.Vector2);
  53106. var PolygonPoints = (function () {
  53107. function PolygonPoints() {
  53108. this.elements = new Array();
  53109. }
  53110. PolygonPoints.prototype.add = function (originalPoints) {
  53111. var _this = this;
  53112. var result = new Array();
  53113. originalPoints.forEach(function (point) {
  53114. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  53115. var newPoint = new IndexedVector2(point, _this.elements.length);
  53116. result.push(newPoint);
  53117. _this.elements.push(newPoint);
  53118. }
  53119. });
  53120. return result;
  53121. };
  53122. PolygonPoints.prototype.computeBounds = function () {
  53123. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  53124. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  53125. this.elements.forEach(function (point) {
  53126. // x
  53127. if (point.x < lmin.x) {
  53128. lmin.x = point.x;
  53129. }
  53130. else if (point.x > lmax.x) {
  53131. lmax.x = point.x;
  53132. }
  53133. // y
  53134. if (point.y < lmin.y) {
  53135. lmin.y = point.y;
  53136. }
  53137. else if (point.y > lmax.y) {
  53138. lmax.y = point.y;
  53139. }
  53140. });
  53141. return {
  53142. min: lmin,
  53143. max: lmax,
  53144. width: lmax.x - lmin.x,
  53145. height: lmax.y - lmin.y
  53146. };
  53147. };
  53148. return PolygonPoints;
  53149. })();
  53150. var Polygon = (function () {
  53151. function Polygon() {
  53152. }
  53153. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  53154. return [
  53155. new BABYLON.Vector2(xmin, ymin),
  53156. new BABYLON.Vector2(xmax, ymin),
  53157. new BABYLON.Vector2(xmax, ymax),
  53158. new BABYLON.Vector2(xmin, ymax)
  53159. ];
  53160. };
  53161. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  53162. if (cx === void 0) { cx = 0; }
  53163. if (cy === void 0) { cy = 0; }
  53164. if (numberOfSides === void 0) { numberOfSides = 32; }
  53165. var result = new Array();
  53166. var angle = 0;
  53167. var increment = (Math.PI * 2) / numberOfSides;
  53168. for (var i = 0; i < numberOfSides; i++) {
  53169. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  53170. angle -= increment;
  53171. }
  53172. return result;
  53173. };
  53174. Polygon.Parse = function (input) {
  53175. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  53176. var i, result = [];
  53177. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  53178. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  53179. }
  53180. return result;
  53181. };
  53182. Polygon.StartingAt = function (x, y) {
  53183. return BABYLON.Path2.StartingAt(x, y);
  53184. };
  53185. return Polygon;
  53186. })();
  53187. BABYLON.Polygon = Polygon;
  53188. var PolygonMeshBuilder = (function () {
  53189. function PolygonMeshBuilder(name, contours, scene) {
  53190. this._points = new PolygonPoints();
  53191. this._outlinepoints = new PolygonPoints();
  53192. this._holes = [];
  53193. this._epoints = new Array();
  53194. this._eholes = new Array();
  53195. this._name = name;
  53196. this._scene = scene;
  53197. var points;
  53198. if (contours instanceof BABYLON.Path2) {
  53199. points = contours.getPoints();
  53200. }
  53201. else {
  53202. points = contours;
  53203. }
  53204. this._addToepoint(points);
  53205. this._points.add(points);
  53206. this._outlinepoints.add(points);
  53207. }
  53208. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  53209. for (var _i = 0; _i < points.length; _i++) {
  53210. var p = points[_i];
  53211. this._epoints.push(p.x, p.y);
  53212. }
  53213. };
  53214. PolygonMeshBuilder.prototype.addHole = function (hole) {
  53215. this._points.add(hole);
  53216. var holepoints = new PolygonPoints();
  53217. holepoints.add(hole);
  53218. this._holes.push(holepoints);
  53219. this._eholes.push(this._epoints.length / 2);
  53220. this._addToepoint(hole);
  53221. return this;
  53222. };
  53223. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  53224. var _this = this;
  53225. if (updatable === void 0) { updatable = false; }
  53226. var result = new BABYLON.Mesh(this._name, this._scene);
  53227. var normals = [];
  53228. var positions = [];
  53229. var uvs = [];
  53230. var bounds = this._points.computeBounds();
  53231. this._points.elements.forEach(function (p) {
  53232. normals.push(0, 1.0, 0);
  53233. positions.push(p.x, 0, p.y);
  53234. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  53235. });
  53236. var indices = [];
  53237. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  53238. for (var i = 0; i < res.length; i++) {
  53239. indices.push(res[i]);
  53240. }
  53241. if (depth > 0) {
  53242. var positionscount = (positions.length / 3); //get the current pointcount
  53243. this._points.elements.forEach(function (p) {
  53244. normals.push(0, -1.0, 0);
  53245. positions.push(p.x, -depth, p.y);
  53246. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  53247. });
  53248. var totalCount = indices.length;
  53249. for (var i = 0; i < totalCount; i += 3) {
  53250. var i0 = indices[i + 0];
  53251. var i1 = indices[i + 1];
  53252. var i2 = indices[i + 2];
  53253. indices.push(i2 + positionscount);
  53254. indices.push(i1 + positionscount);
  53255. indices.push(i0 + positionscount);
  53256. }
  53257. //Add the sides
  53258. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  53259. this._holes.forEach(function (hole) {
  53260. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  53261. });
  53262. }
  53263. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  53264. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  53265. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  53266. result.setIndices(indices);
  53267. return result;
  53268. };
  53269. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  53270. var StartIndex = positions.length / 3;
  53271. var ulength = 0;
  53272. for (var i = 0; i < points.elements.length; i++) {
  53273. var p = points.elements[i];
  53274. var p1;
  53275. if ((i + 1) > points.elements.length - 1) {
  53276. p1 = points.elements[0];
  53277. }
  53278. else {
  53279. p1 = points.elements[i + 1];
  53280. }
  53281. positions.push(p.x, 0, p.y);
  53282. positions.push(p.x, -depth, p.y);
  53283. positions.push(p1.x, 0, p1.y);
  53284. positions.push(p1.x, -depth, p1.y);
  53285. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  53286. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  53287. var v3 = v2.subtract(v1);
  53288. var v4 = new BABYLON.Vector3(0, 1, 0);
  53289. var vn = BABYLON.Vector3.Cross(v3, v4);
  53290. vn = vn.normalize();
  53291. uvs.push(ulength / bounds.width, 0);
  53292. uvs.push(ulength / bounds.width, 1);
  53293. ulength += v3.length();
  53294. uvs.push((ulength / bounds.width), 0);
  53295. uvs.push((ulength / bounds.width), 1);
  53296. if (!flip) {
  53297. normals.push(-vn.x, -vn.y, -vn.z);
  53298. normals.push(-vn.x, -vn.y, -vn.z);
  53299. normals.push(-vn.x, -vn.y, -vn.z);
  53300. normals.push(-vn.x, -vn.y, -vn.z);
  53301. indices.push(StartIndex);
  53302. indices.push(StartIndex + 1);
  53303. indices.push(StartIndex + 2);
  53304. indices.push(StartIndex + 1);
  53305. indices.push(StartIndex + 3);
  53306. indices.push(StartIndex + 2);
  53307. }
  53308. else {
  53309. normals.push(vn.x, vn.y, vn.z);
  53310. normals.push(vn.x, vn.y, vn.z);
  53311. normals.push(vn.x, vn.y, vn.z);
  53312. normals.push(vn.x, vn.y, vn.z);
  53313. indices.push(StartIndex);
  53314. indices.push(StartIndex + 2);
  53315. indices.push(StartIndex + 1);
  53316. indices.push(StartIndex + 1);
  53317. indices.push(StartIndex + 2);
  53318. indices.push(StartIndex + 3);
  53319. }
  53320. StartIndex += 4;
  53321. }
  53322. ;
  53323. };
  53324. return PolygonMeshBuilder;
  53325. })();
  53326. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  53327. })(BABYLON || (BABYLON = {}));
  53328. var BABYLON;
  53329. (function (BABYLON) {
  53330. var Octree = (function () {
  53331. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  53332. if (maxDepth === void 0) { maxDepth = 2; }
  53333. this.maxDepth = maxDepth;
  53334. this.dynamicContent = new Array();
  53335. this._maxBlockCapacity = maxBlockCapacity || 64;
  53336. this._selectionContent = new BABYLON.SmartArray(1024);
  53337. this._creationFunc = creationFunc;
  53338. }
  53339. // Methods
  53340. Octree.prototype.update = function (worldMin, worldMax, entries) {
  53341. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  53342. };
  53343. Octree.prototype.addMesh = function (entry) {
  53344. for (var index = 0; index < this.blocks.length; index++) {
  53345. var block = this.blocks[index];
  53346. block.addEntry(entry);
  53347. }
  53348. };
  53349. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  53350. this._selectionContent.reset();
  53351. for (var index = 0; index < this.blocks.length; index++) {
  53352. var block = this.blocks[index];
  53353. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  53354. }
  53355. if (allowDuplicate) {
  53356. this._selectionContent.concat(this.dynamicContent);
  53357. }
  53358. else {
  53359. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  53360. }
  53361. return this._selectionContent;
  53362. };
  53363. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  53364. this._selectionContent.reset();
  53365. for (var index = 0; index < this.blocks.length; index++) {
  53366. var block = this.blocks[index];
  53367. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  53368. }
  53369. if (allowDuplicate) {
  53370. this._selectionContent.concat(this.dynamicContent);
  53371. }
  53372. else {
  53373. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  53374. }
  53375. return this._selectionContent;
  53376. };
  53377. Octree.prototype.intersectsRay = function (ray) {
  53378. this._selectionContent.reset();
  53379. for (var index = 0; index < this.blocks.length; index++) {
  53380. var block = this.blocks[index];
  53381. block.intersectsRay(ray, this._selectionContent);
  53382. }
  53383. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  53384. return this._selectionContent;
  53385. };
  53386. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  53387. target.blocks = new Array();
  53388. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  53389. // Segmenting space
  53390. for (var x = 0; x < 2; x++) {
  53391. for (var y = 0; y < 2; y++) {
  53392. for (var z = 0; z < 2; z++) {
  53393. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  53394. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  53395. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  53396. block.addEntries(entries);
  53397. target.blocks.push(block);
  53398. }
  53399. }
  53400. }
  53401. };
  53402. Octree.CreationFuncForMeshes = function (entry, block) {
  53403. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  53404. block.entries.push(entry);
  53405. }
  53406. };
  53407. Octree.CreationFuncForSubMeshes = function (entry, block) {
  53408. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  53409. block.entries.push(entry);
  53410. }
  53411. };
  53412. return Octree;
  53413. })();
  53414. BABYLON.Octree = Octree;
  53415. })(BABYLON || (BABYLON = {}));
  53416. var BABYLON;
  53417. (function (BABYLON) {
  53418. var OctreeBlock = (function () {
  53419. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  53420. this.entries = new Array();
  53421. this._boundingVectors = new Array();
  53422. this._capacity = capacity;
  53423. this._depth = depth;
  53424. this._maxDepth = maxDepth;
  53425. this._creationFunc = creationFunc;
  53426. this._minPoint = minPoint;
  53427. this._maxPoint = maxPoint;
  53428. this._boundingVectors.push(minPoint.clone());
  53429. this._boundingVectors.push(maxPoint.clone());
  53430. this._boundingVectors.push(minPoint.clone());
  53431. this._boundingVectors[2].x = maxPoint.x;
  53432. this._boundingVectors.push(minPoint.clone());
  53433. this._boundingVectors[3].y = maxPoint.y;
  53434. this._boundingVectors.push(minPoint.clone());
  53435. this._boundingVectors[4].z = maxPoint.z;
  53436. this._boundingVectors.push(maxPoint.clone());
  53437. this._boundingVectors[5].z = minPoint.z;
  53438. this._boundingVectors.push(maxPoint.clone());
  53439. this._boundingVectors[6].x = minPoint.x;
  53440. this._boundingVectors.push(maxPoint.clone());
  53441. this._boundingVectors[7].y = minPoint.y;
  53442. }
  53443. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  53444. // Property
  53445. get: function () {
  53446. return this._capacity;
  53447. },
  53448. enumerable: true,
  53449. configurable: true
  53450. });
  53451. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  53452. get: function () {
  53453. return this._minPoint;
  53454. },
  53455. enumerable: true,
  53456. configurable: true
  53457. });
  53458. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  53459. get: function () {
  53460. return this._maxPoint;
  53461. },
  53462. enumerable: true,
  53463. configurable: true
  53464. });
  53465. // Methods
  53466. OctreeBlock.prototype.addEntry = function (entry) {
  53467. if (this.blocks) {
  53468. for (var index = 0; index < this.blocks.length; index++) {
  53469. var block = this.blocks[index];
  53470. block.addEntry(entry);
  53471. }
  53472. return;
  53473. }
  53474. this._creationFunc(entry, this);
  53475. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  53476. this.createInnerBlocks();
  53477. }
  53478. };
  53479. OctreeBlock.prototype.addEntries = function (entries) {
  53480. for (var index = 0; index < entries.length; index++) {
  53481. var mesh = entries[index];
  53482. this.addEntry(mesh);
  53483. }
  53484. };
  53485. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  53486. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  53487. if (this.blocks) {
  53488. for (var index = 0; index < this.blocks.length; index++) {
  53489. var block = this.blocks[index];
  53490. block.select(frustumPlanes, selection, allowDuplicate);
  53491. }
  53492. return;
  53493. }
  53494. if (allowDuplicate) {
  53495. selection.concat(this.entries);
  53496. }
  53497. else {
  53498. selection.concatWithNoDuplicate(this.entries);
  53499. }
  53500. }
  53501. };
  53502. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  53503. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  53504. if (this.blocks) {
  53505. for (var index = 0; index < this.blocks.length; index++) {
  53506. var block = this.blocks[index];
  53507. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  53508. }
  53509. return;
  53510. }
  53511. if (allowDuplicate) {
  53512. selection.concat(this.entries);
  53513. }
  53514. else {
  53515. selection.concatWithNoDuplicate(this.entries);
  53516. }
  53517. }
  53518. };
  53519. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  53520. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  53521. if (this.blocks) {
  53522. for (var index = 0; index < this.blocks.length; index++) {
  53523. var block = this.blocks[index];
  53524. block.intersectsRay(ray, selection);
  53525. }
  53526. return;
  53527. }
  53528. selection.concatWithNoDuplicate(this.entries);
  53529. }
  53530. };
  53531. OctreeBlock.prototype.createInnerBlocks = function () {
  53532. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  53533. };
  53534. return OctreeBlock;
  53535. })();
  53536. BABYLON.OctreeBlock = OctreeBlock;
  53537. })(BABYLON || (BABYLON = {}));
  53538. var BABYLON;
  53539. (function (BABYLON) {
  53540. var BlurPostProcess = (function (_super) {
  53541. __extends(BlurPostProcess, _super);
  53542. function BlurPostProcess(name, direction, blurWidth, options, camera, samplingMode, engine, reusable) {
  53543. var _this = this;
  53544. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  53545. _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable);
  53546. this.direction = direction;
  53547. this.blurWidth = blurWidth;
  53548. this.onApplyObservable.add(function (effect) {
  53549. effect.setFloat2("screenSize", _this.width, _this.height);
  53550. effect.setVector2("direction", _this.direction);
  53551. effect.setFloat("blurWidth", _this.blurWidth);
  53552. });
  53553. }
  53554. return BlurPostProcess;
  53555. })(BABYLON.PostProcess);
  53556. BABYLON.BlurPostProcess = BlurPostProcess;
  53557. })(BABYLON || (BABYLON = {}));
  53558. var BABYLON;
  53559. (function (BABYLON) {
  53560. var RefractionPostProcess = (function (_super) {
  53561. __extends(RefractionPostProcess, _super);
  53562. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  53563. var _this = this;
  53564. _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable);
  53565. this.color = color;
  53566. this.depth = depth;
  53567. this.colorLevel = colorLevel;
  53568. this.onActivateObservable.add(function (cam) {
  53569. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  53570. });
  53571. this.onApplyObservable.add(function (effect) {
  53572. effect.setColor3("baseColor", _this.color);
  53573. effect.setFloat("depth", _this.depth);
  53574. effect.setFloat("colorLevel", _this.colorLevel);
  53575. effect.setTexture("refractionSampler", _this._refRexture);
  53576. });
  53577. }
  53578. // Methods
  53579. RefractionPostProcess.prototype.dispose = function (camera) {
  53580. if (this._refRexture) {
  53581. this._refRexture.dispose();
  53582. }
  53583. _super.prototype.dispose.call(this, camera);
  53584. };
  53585. return RefractionPostProcess;
  53586. })(BABYLON.PostProcess);
  53587. BABYLON.RefractionPostProcess = RefractionPostProcess;
  53588. })(BABYLON || (BABYLON = {}));
  53589. var BABYLON;
  53590. (function (BABYLON) {
  53591. var BlackAndWhitePostProcess = (function (_super) {
  53592. __extends(BlackAndWhitePostProcess, _super);
  53593. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  53594. _super.call(this, name, "blackAndWhite", null, null, options, camera, samplingMode, engine, reusable);
  53595. }
  53596. return BlackAndWhitePostProcess;
  53597. })(BABYLON.PostProcess);
  53598. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  53599. })(BABYLON || (BABYLON = {}));
  53600. var BABYLON;
  53601. (function (BABYLON) {
  53602. var ConvolutionPostProcess = (function (_super) {
  53603. __extends(ConvolutionPostProcess, _super);
  53604. function ConvolutionPostProcess(name, kernel, options, camera, samplingMode, engine, reusable) {
  53605. var _this = this;
  53606. _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable);
  53607. this.kernel = kernel;
  53608. this.onApply = function (effect) {
  53609. effect.setFloat2("screenSize", _this.width, _this.height);
  53610. effect.setArray("kernel", _this.kernel);
  53611. };
  53612. }
  53613. // Statics
  53614. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  53615. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  53616. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  53617. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  53618. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  53619. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  53620. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  53621. return ConvolutionPostProcess;
  53622. })(BABYLON.PostProcess);
  53623. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  53624. })(BABYLON || (BABYLON = {}));
  53625. var BABYLON;
  53626. (function (BABYLON) {
  53627. var FilterPostProcess = (function (_super) {
  53628. __extends(FilterPostProcess, _super);
  53629. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  53630. var _this = this;
  53631. _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable);
  53632. this.kernelMatrix = kernelMatrix;
  53633. this.onApply = function (effect) {
  53634. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  53635. };
  53636. }
  53637. return FilterPostProcess;
  53638. })(BABYLON.PostProcess);
  53639. BABYLON.FilterPostProcess = FilterPostProcess;
  53640. })(BABYLON || (BABYLON = {}));
  53641. var BABYLON;
  53642. (function (BABYLON) {
  53643. var FxaaPostProcess = (function (_super) {
  53644. __extends(FxaaPostProcess, _super);
  53645. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable) {
  53646. var _this = this;
  53647. _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode, engine, reusable);
  53648. this.onSizeChangedObservable.add(function () {
  53649. _this.texelWidth = 1.0 / _this.width;
  53650. _this.texelHeight = 1.0 / _this.height;
  53651. });
  53652. this.onApplyObservable.add(function (effect) {
  53653. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  53654. });
  53655. }
  53656. return FxaaPostProcess;
  53657. })(BABYLON.PostProcess);
  53658. BABYLON.FxaaPostProcess = FxaaPostProcess;
  53659. })(BABYLON || (BABYLON = {}));
  53660. var BABYLON;
  53661. (function (BABYLON) {
  53662. var StereoscopicInterlacePostProcess = (function (_super) {
  53663. __extends(StereoscopicInterlacePostProcess, _super);
  53664. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  53665. var _this = this;
  53666. _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined);
  53667. this._passedProcess = rigCameras[0]._rigPostProcess;
  53668. this._stepSize = new BABYLON.Vector2(1 / this.width, 1 / this.height);
  53669. this.onSizeChangedObservable.add(function () {
  53670. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  53671. });
  53672. this.onApplyObservable.add(function (effect) {
  53673. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  53674. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  53675. });
  53676. }
  53677. return StereoscopicInterlacePostProcess;
  53678. })(BABYLON.PostProcess);
  53679. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  53680. })(BABYLON || (BABYLON = {}));
  53681. var BABYLON;
  53682. (function (BABYLON) {
  53683. var LensFlare = (function () {
  53684. function LensFlare(size, position, color, imgUrl, system) {
  53685. this.size = size;
  53686. this.position = position;
  53687. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  53688. this.dispose = function () {
  53689. if (this.texture) {
  53690. this.texture.dispose();
  53691. }
  53692. // Remove from scene
  53693. var index = this._system.lensFlares.indexOf(this);
  53694. this._system.lensFlares.splice(index, 1);
  53695. };
  53696. this.color = color || new BABYLON.Color3(1, 1, 1);
  53697. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  53698. this._system = system;
  53699. system.lensFlares.push(this);
  53700. }
  53701. return LensFlare;
  53702. })();
  53703. BABYLON.LensFlare = LensFlare;
  53704. })(BABYLON || (BABYLON = {}));
  53705. var BABYLON;
  53706. (function (BABYLON) {
  53707. var LensFlareSystem = (function () {
  53708. function LensFlareSystem(name, emitter, scene) {
  53709. this.name = name;
  53710. this.lensFlares = new Array();
  53711. this.borderLimit = 300;
  53712. this.layerMask = 0x0FFFFFFF;
  53713. this._vertexBuffers = {};
  53714. this._isEnabled = true;
  53715. this._scene = scene;
  53716. this._emitter = emitter;
  53717. this.id = name;
  53718. scene.lensFlareSystems.push(this);
  53719. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  53720. var engine = scene.getEngine();
  53721. // VBO
  53722. var vertices = [];
  53723. vertices.push(1, 1);
  53724. vertices.push(-1, 1);
  53725. vertices.push(-1, -1);
  53726. vertices.push(1, -1);
  53727. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  53728. // Indices
  53729. var indices = [];
  53730. indices.push(0);
  53731. indices.push(1);
  53732. indices.push(2);
  53733. indices.push(0);
  53734. indices.push(2);
  53735. indices.push(3);
  53736. this._indexBuffer = engine.createIndexBuffer(indices);
  53737. // Effects
  53738. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  53739. }
  53740. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  53741. get: function () {
  53742. return this._isEnabled;
  53743. },
  53744. set: function (value) {
  53745. this._isEnabled = value;
  53746. },
  53747. enumerable: true,
  53748. configurable: true
  53749. });
  53750. LensFlareSystem.prototype.getScene = function () {
  53751. return this._scene;
  53752. };
  53753. LensFlareSystem.prototype.getEmitter = function () {
  53754. return this._emitter;
  53755. };
  53756. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  53757. this._emitter = newEmitter;
  53758. };
  53759. LensFlareSystem.prototype.getEmitterPosition = function () {
  53760. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  53761. };
  53762. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  53763. var position = this.getEmitterPosition();
  53764. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  53765. this._positionX = position.x;
  53766. this._positionY = position.y;
  53767. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  53768. if (position.z > 0) {
  53769. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  53770. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  53771. return true;
  53772. }
  53773. }
  53774. return false;
  53775. };
  53776. LensFlareSystem.prototype._isVisible = function () {
  53777. if (!this._isEnabled) {
  53778. return false;
  53779. }
  53780. var emitterPosition = this.getEmitterPosition();
  53781. var direction = emitterPosition.subtract(this._scene.activeCamera.position);
  53782. var distance = direction.length();
  53783. direction.normalize();
  53784. var ray = new BABYLON.Ray(this._scene.activeCamera.position, direction);
  53785. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  53786. return !pickInfo.hit || pickInfo.distance > distance;
  53787. };
  53788. LensFlareSystem.prototype.render = function () {
  53789. if (!this._effect.isReady())
  53790. return false;
  53791. var engine = this._scene.getEngine();
  53792. var viewport = this._scene.activeCamera.viewport;
  53793. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  53794. // Position
  53795. if (!this.computeEffectivePosition(globalViewport)) {
  53796. return false;
  53797. }
  53798. // Visibility
  53799. if (!this._isVisible()) {
  53800. return false;
  53801. }
  53802. // Intensity
  53803. var awayX;
  53804. var awayY;
  53805. if (this._positionX < this.borderLimit + globalViewport.x) {
  53806. awayX = this.borderLimit + globalViewport.x - this._positionX;
  53807. }
  53808. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  53809. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  53810. }
  53811. else {
  53812. awayX = 0;
  53813. }
  53814. if (this._positionY < this.borderLimit + globalViewport.y) {
  53815. awayY = this.borderLimit + globalViewport.y - this._positionY;
  53816. }
  53817. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  53818. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  53819. }
  53820. else {
  53821. awayY = 0;
  53822. }
  53823. var away = (awayX > awayY) ? awayX : awayY;
  53824. if (away > this.borderLimit) {
  53825. away = this.borderLimit;
  53826. }
  53827. var intensity = 1.0 - (away / this.borderLimit);
  53828. if (intensity < 0) {
  53829. return false;
  53830. }
  53831. if (intensity > 1.0) {
  53832. intensity = 1.0;
  53833. }
  53834. // Position
  53835. var centerX = globalViewport.x + globalViewport.width / 2;
  53836. var centerY = globalViewport.y + globalViewport.height / 2;
  53837. var distX = centerX - this._positionX;
  53838. var distY = centerY - this._positionY;
  53839. // Effects
  53840. engine.enableEffect(this._effect);
  53841. engine.setState(false);
  53842. engine.setDepthBuffer(false);
  53843. // VBOs
  53844. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  53845. // Flares
  53846. for (var index = 0; index < this.lensFlares.length; index++) {
  53847. var flare = this.lensFlares[index];
  53848. engine.setAlphaMode(flare.alphaMode);
  53849. var x = centerX - (distX * flare.position);
  53850. var y = centerY - (distY * flare.position);
  53851. var cw = flare.size;
  53852. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  53853. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  53854. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  53855. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  53856. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  53857. // Texture
  53858. this._effect.setTexture("textureSampler", flare.texture);
  53859. // Color
  53860. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  53861. // Draw order
  53862. engine.draw(true, 0, 6);
  53863. }
  53864. engine.setDepthBuffer(true);
  53865. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  53866. return true;
  53867. };
  53868. LensFlareSystem.prototype.dispose = function () {
  53869. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  53870. if (vertexBuffer) {
  53871. vertexBuffer.dispose();
  53872. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  53873. }
  53874. if (this._indexBuffer) {
  53875. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  53876. this._indexBuffer = null;
  53877. }
  53878. while (this.lensFlares.length) {
  53879. this.lensFlares[0].dispose();
  53880. }
  53881. // Remove from scene
  53882. var index = this._scene.lensFlareSystems.indexOf(this);
  53883. this._scene.lensFlareSystems.splice(index, 1);
  53884. };
  53885. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  53886. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  53887. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  53888. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  53889. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  53890. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  53891. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  53892. var parsedFlare = parsedLensFlareSystem.flares[index];
  53893. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  53894. }
  53895. return lensFlareSystem;
  53896. };
  53897. LensFlareSystem.prototype.serialize = function () {
  53898. var serializationObject = {};
  53899. serializationObject.id = this.id;
  53900. serializationObject.name = this.name;
  53901. serializationObject.emitterId = this.getEmitter().id;
  53902. serializationObject.borderLimit = this.borderLimit;
  53903. serializationObject.flares = [];
  53904. for (var index = 0; index < this.lensFlares.length; index++) {
  53905. var flare = this.lensFlares[index];
  53906. serializationObject.flares.push({
  53907. size: flare.size,
  53908. position: flare.position,
  53909. color: flare.color.asArray(),
  53910. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  53911. });
  53912. }
  53913. return serializationObject;
  53914. };
  53915. return LensFlareSystem;
  53916. })();
  53917. BABYLON.LensFlareSystem = LensFlareSystem;
  53918. })(BABYLON || (BABYLON = {}));
  53919. var BABYLON;
  53920. (function (BABYLON) {
  53921. // We're mainly based on the logic defined into the FreeCamera code
  53922. var DeviceOrientationCamera = (function (_super) {
  53923. __extends(DeviceOrientationCamera, _super);
  53924. function DeviceOrientationCamera(name, position, scene) {
  53925. _super.call(this, name, position, scene);
  53926. this.inputs.addDeviceOrientation();
  53927. }
  53928. DeviceOrientationCamera.prototype.getTypeName = function () {
  53929. return "DeviceOrientationCamera";
  53930. };
  53931. DeviceOrientationCamera.prototype._checkInputs = function () {
  53932. _super.prototype._checkInputs.call(this);
  53933. if (this._initialQuaternion) {
  53934. this._quaternionCache.copyFrom(this.rotationQuaternion);
  53935. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  53936. }
  53937. };
  53938. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  53939. var _this = this;
  53940. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  53941. //can only work if this camera has a rotation quaternion already.
  53942. if (!this.rotationQuaternion)
  53943. return;
  53944. if (!this._initialQuaternion) {
  53945. this._initialQuaternion = new BABYLON.Quaternion();
  53946. }
  53947. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  53948. ['x', 'y', 'z'].forEach(function (axisName) {
  53949. if (!axis[axisName]) {
  53950. _this._initialQuaternion[axisName] = 0;
  53951. }
  53952. else {
  53953. _this._initialQuaternion[axisName] *= -1;
  53954. }
  53955. });
  53956. this._initialQuaternion.normalize();
  53957. };
  53958. return DeviceOrientationCamera;
  53959. })(BABYLON.FreeCamera);
  53960. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  53961. })(BABYLON || (BABYLON = {}));
  53962. var BABYLON;
  53963. (function (BABYLON) {
  53964. var VRDeviceOrientationFreeCamera = (function (_super) {
  53965. __extends(VRDeviceOrientationFreeCamera, _super);
  53966. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  53967. if (compensateDistortion === void 0) { compensateDistortion = true; }
  53968. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  53969. _super.call(this, name, position, scene);
  53970. vrCameraMetrics.compensateDistortion = compensateDistortion;
  53971. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  53972. }
  53973. VRDeviceOrientationFreeCamera.prototype.getTypeName = function () {
  53974. return "VRDeviceOrientationFreeCamera";
  53975. };
  53976. return VRDeviceOrientationFreeCamera;
  53977. })(BABYLON.DeviceOrientationCamera);
  53978. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  53979. var VRDeviceOrientationArcRotateCamera = (function (_super) {
  53980. __extends(VRDeviceOrientationArcRotateCamera, _super);
  53981. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion) {
  53982. if (compensateDistortion === void 0) { compensateDistortion = true; }
  53983. _super.call(this, name, alpha, beta, radius, target, scene);
  53984. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  53985. metrics.compensateDistortion = compensateDistortion;
  53986. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
  53987. this.inputs.addVRDeviceOrientation();
  53988. }
  53989. VRDeviceOrientationArcRotateCamera.prototype.getTypeName = function () {
  53990. return "VRDeviceOrientationArcRotateCamera";
  53991. };
  53992. return VRDeviceOrientationArcRotateCamera;
  53993. })(BABYLON.ArcRotateCamera);
  53994. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  53995. })(BABYLON || (BABYLON = {}));
  53996. var BABYLON;
  53997. (function (BABYLON) {
  53998. // We're mainly based on the logic defined into the FreeCamera code
  53999. var UniversalCamera = (function (_super) {
  54000. __extends(UniversalCamera, _super);
  54001. //-- end properties for backward compatibility for inputs
  54002. function UniversalCamera(name, position, scene) {
  54003. _super.call(this, name, position, scene);
  54004. this.inputs.addGamepad();
  54005. }
  54006. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  54007. //-- Begin properties for backward compatibility for inputs
  54008. get: function () {
  54009. var gamepad = this.inputs.attached["gamepad"];
  54010. if (gamepad)
  54011. return gamepad.gamepadAngularSensibility;
  54012. },
  54013. set: function (value) {
  54014. var gamepad = this.inputs.attached["gamepad"];
  54015. if (gamepad)
  54016. gamepad.gamepadAngularSensibility = value;
  54017. },
  54018. enumerable: true,
  54019. configurable: true
  54020. });
  54021. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  54022. get: function () {
  54023. var gamepad = this.inputs.attached["gamepad"];
  54024. if (gamepad)
  54025. return gamepad.gamepadMoveSensibility;
  54026. },
  54027. set: function (value) {
  54028. var gamepad = this.inputs.attached["gamepad"];
  54029. if (gamepad)
  54030. gamepad.gamepadMoveSensibility = value;
  54031. },
  54032. enumerable: true,
  54033. configurable: true
  54034. });
  54035. UniversalCamera.prototype.getTypeName = function () {
  54036. return "UniversalCamera";
  54037. };
  54038. return UniversalCamera;
  54039. })(BABYLON.TouchCamera);
  54040. BABYLON.UniversalCamera = UniversalCamera;
  54041. })(BABYLON || (BABYLON = {}));
  54042. var BABYLON;
  54043. (function (BABYLON) {
  54044. var Gamepads = (function () {
  54045. function Gamepads(ongamedpadconnected) {
  54046. var _this = this;
  54047. this.babylonGamepads = [];
  54048. this.oneGamepadConnected = false;
  54049. this.isMonitoring = false;
  54050. this.gamepadEventSupported = 'GamepadEvent' in window;
  54051. this.gamepadSupportAvailable = (navigator.getGamepads ||
  54052. !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  54053. this._callbackGamepadConnected = ongamedpadconnected;
  54054. if (this.gamepadSupportAvailable) {
  54055. // Checking if the gamepad connected event is supported (like in Firefox)
  54056. if (this.gamepadEventSupported) {
  54057. this._onGamepadConnectedEvent = function (evt) {
  54058. _this._onGamepadConnected(evt);
  54059. };
  54060. this._onGamepadDisonnectedEvent = function (evt) {
  54061. _this._onGamepadDisconnected(evt);
  54062. };
  54063. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  54064. window.addEventListener('gamepaddisconnected', this._onGamepadDisonnectedEvent, false);
  54065. }
  54066. else {
  54067. this._startMonitoringGamepads();
  54068. }
  54069. }
  54070. }
  54071. Gamepads.prototype.dispose = function () {
  54072. if (Gamepads.gamepadDOMInfo) {
  54073. document.body.removeChild(Gamepads.gamepadDOMInfo);
  54074. }
  54075. if (this._onGamepadConnectedEvent) {
  54076. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  54077. window.removeEventListener('gamepaddisconnected', this._onGamepadDisonnectedEvent, false);
  54078. this._onGamepadConnectedEvent = null;
  54079. this._onGamepadDisonnectedEvent = null;
  54080. }
  54081. };
  54082. Gamepads.prototype._onGamepadConnected = function (evt) {
  54083. var newGamepad = this._addNewGamepad(evt.gamepad);
  54084. if (this._callbackGamepadConnected)
  54085. this._callbackGamepadConnected(newGamepad);
  54086. this._startMonitoringGamepads();
  54087. };
  54088. Gamepads.prototype._addNewGamepad = function (gamepad) {
  54089. if (!this.oneGamepadConnected) {
  54090. this.oneGamepadConnected = true;
  54091. if (Gamepads.gamepadDOMInfo) {
  54092. document.body.removeChild(Gamepads.gamepadDOMInfo);
  54093. Gamepads.gamepadDOMInfo = null;
  54094. }
  54095. }
  54096. var newGamepad;
  54097. if (gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  54098. newGamepad = new Xbox360Pad(gamepad.id, gamepad.index, gamepad);
  54099. }
  54100. else {
  54101. newGamepad = new GenericPad(gamepad.id, gamepad.index, gamepad);
  54102. }
  54103. this.babylonGamepads.push(newGamepad);
  54104. return newGamepad;
  54105. };
  54106. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  54107. // Remove the gamepad from the list of gamepads to monitor.
  54108. for (var i in this.babylonGamepads) {
  54109. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  54110. this.babylonGamepads.splice(+i, 1);
  54111. break;
  54112. }
  54113. }
  54114. // If no gamepads are left, stop the polling loop.
  54115. if (this.babylonGamepads.length == 0) {
  54116. this._stopMonitoringGamepads();
  54117. }
  54118. };
  54119. Gamepads.prototype._startMonitoringGamepads = function () {
  54120. if (!this.isMonitoring) {
  54121. this.isMonitoring = true;
  54122. this._checkGamepadsStatus();
  54123. }
  54124. };
  54125. Gamepads.prototype._stopMonitoringGamepads = function () {
  54126. this.isMonitoring = false;
  54127. };
  54128. Gamepads.prototype._checkGamepadsStatus = function () {
  54129. var _this = this;
  54130. // updating gamepad objects
  54131. this._updateGamepadObjects();
  54132. for (var i in this.babylonGamepads) {
  54133. this.babylonGamepads[i].update();
  54134. }
  54135. if (this.isMonitoring) {
  54136. if (window.requestAnimationFrame) {
  54137. window.requestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  54138. }
  54139. else if (window.mozRequestAnimationFrame) {
  54140. window.mozRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  54141. }
  54142. else if (window.webkitRequestAnimationFrame) {
  54143. window.webkitRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  54144. }
  54145. }
  54146. };
  54147. // This function is called only on Chrome, which does not yet support
  54148. // connection/disconnection events, but requires you to monitor
  54149. // an array for changes.
  54150. Gamepads.prototype._updateGamepadObjects = function () {
  54151. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  54152. for (var i = 0; i < gamepads.length; i++) {
  54153. if (gamepads[i]) {
  54154. if (!(gamepads[i].index in this.babylonGamepads)) {
  54155. var newGamepad = this._addNewGamepad(gamepads[i]);
  54156. if (this._callbackGamepadConnected) {
  54157. this._callbackGamepadConnected(newGamepad);
  54158. }
  54159. }
  54160. else {
  54161. this.babylonGamepads[i].browserGamepad = gamepads[i];
  54162. }
  54163. }
  54164. }
  54165. };
  54166. return Gamepads;
  54167. })();
  54168. BABYLON.Gamepads = Gamepads;
  54169. var StickValues = (function () {
  54170. function StickValues(x, y) {
  54171. this.x = x;
  54172. this.y = y;
  54173. }
  54174. return StickValues;
  54175. })();
  54176. BABYLON.StickValues = StickValues;
  54177. var Gamepad = (function () {
  54178. function Gamepad(id, index, browserGamepad) {
  54179. this.id = id;
  54180. this.index = index;
  54181. this.browserGamepad = browserGamepad;
  54182. if (this.browserGamepad.axes.length >= 2) {
  54183. this._leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  54184. }
  54185. if (this.browserGamepad.axes.length >= 4) {
  54186. this._rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  54187. }
  54188. }
  54189. Gamepad.prototype.onleftstickchanged = function (callback) {
  54190. this._onleftstickchanged = callback;
  54191. };
  54192. Gamepad.prototype.onrightstickchanged = function (callback) {
  54193. this._onrightstickchanged = callback;
  54194. };
  54195. Object.defineProperty(Gamepad.prototype, "leftStick", {
  54196. get: function () {
  54197. return this._leftStick;
  54198. },
  54199. set: function (newValues) {
  54200. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  54201. this._onleftstickchanged(newValues);
  54202. }
  54203. this._leftStick = newValues;
  54204. },
  54205. enumerable: true,
  54206. configurable: true
  54207. });
  54208. Object.defineProperty(Gamepad.prototype, "rightStick", {
  54209. get: function () {
  54210. return this._rightStick;
  54211. },
  54212. set: function (newValues) {
  54213. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  54214. this._onrightstickchanged(newValues);
  54215. }
  54216. this._rightStick = newValues;
  54217. },
  54218. enumerable: true,
  54219. configurable: true
  54220. });
  54221. Gamepad.prototype.update = function () {
  54222. if (this._leftStick) {
  54223. this.leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  54224. }
  54225. if (this._rightStick) {
  54226. this.rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  54227. }
  54228. };
  54229. return Gamepad;
  54230. })();
  54231. BABYLON.Gamepad = Gamepad;
  54232. var GenericPad = (function (_super) {
  54233. __extends(GenericPad, _super);
  54234. function GenericPad(id, index, gamepad) {
  54235. _super.call(this, id, index, gamepad);
  54236. this.id = id;
  54237. this.index = index;
  54238. this.gamepad = gamepad;
  54239. this._buttons = new Array(gamepad.buttons.length);
  54240. }
  54241. GenericPad.prototype.onbuttondown = function (callback) {
  54242. this._onbuttondown = callback;
  54243. };
  54244. GenericPad.prototype.onbuttonup = function (callback) {
  54245. this._onbuttonup = callback;
  54246. };
  54247. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  54248. if (newValue !== currentValue) {
  54249. if (this._onbuttondown && newValue === 1) {
  54250. this._onbuttondown(buttonIndex);
  54251. }
  54252. if (this._onbuttonup && newValue === 0) {
  54253. this._onbuttonup(buttonIndex);
  54254. }
  54255. }
  54256. return newValue;
  54257. };
  54258. GenericPad.prototype.update = function () {
  54259. _super.prototype.update.call(this);
  54260. for (var index = 0; index < this._buttons.length; index++) {
  54261. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  54262. }
  54263. };
  54264. return GenericPad;
  54265. })(Gamepad);
  54266. BABYLON.GenericPad = GenericPad;
  54267. (function (Xbox360Button) {
  54268. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  54269. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  54270. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  54271. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  54272. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  54273. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  54274. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  54275. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  54276. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  54277. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  54278. })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  54279. var Xbox360Button = BABYLON.Xbox360Button;
  54280. (function (Xbox360Dpad) {
  54281. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  54282. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  54283. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  54284. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  54285. })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  54286. var Xbox360Dpad = BABYLON.Xbox360Dpad;
  54287. var Xbox360Pad = (function (_super) {
  54288. __extends(Xbox360Pad, _super);
  54289. function Xbox360Pad() {
  54290. _super.apply(this, arguments);
  54291. this._leftTrigger = 0;
  54292. this._rightTrigger = 0;
  54293. this._buttonA = 0;
  54294. this._buttonB = 0;
  54295. this._buttonX = 0;
  54296. this._buttonY = 0;
  54297. this._buttonBack = 0;
  54298. this._buttonStart = 0;
  54299. this._buttonLB = 0;
  54300. this._buttonRB = 0;
  54301. this._buttonLeftStick = 0;
  54302. this._buttonRightStick = 0;
  54303. this._dPadUp = 0;
  54304. this._dPadDown = 0;
  54305. this._dPadLeft = 0;
  54306. this._dPadRight = 0;
  54307. }
  54308. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  54309. this._onlefttriggerchanged = callback;
  54310. };
  54311. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  54312. this._onrighttriggerchanged = callback;
  54313. };
  54314. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  54315. get: function () {
  54316. return this._leftTrigger;
  54317. },
  54318. set: function (newValue) {
  54319. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  54320. this._onlefttriggerchanged(newValue);
  54321. }
  54322. this._leftTrigger = newValue;
  54323. },
  54324. enumerable: true,
  54325. configurable: true
  54326. });
  54327. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  54328. get: function () {
  54329. return this._rightTrigger;
  54330. },
  54331. set: function (newValue) {
  54332. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  54333. this._onrighttriggerchanged(newValue);
  54334. }
  54335. this._rightTrigger = newValue;
  54336. },
  54337. enumerable: true,
  54338. configurable: true
  54339. });
  54340. Xbox360Pad.prototype.onbuttondown = function (callback) {
  54341. this._onbuttondown = callback;
  54342. };
  54343. Xbox360Pad.prototype.onbuttonup = function (callback) {
  54344. this._onbuttonup = callback;
  54345. };
  54346. Xbox360Pad.prototype.ondpaddown = function (callback) {
  54347. this._ondpaddown = callback;
  54348. };
  54349. Xbox360Pad.prototype.ondpadup = function (callback) {
  54350. this._ondpadup = callback;
  54351. };
  54352. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  54353. if (newValue !== currentValue) {
  54354. if (this._onbuttondown && newValue === 1) {
  54355. this._onbuttondown(buttonType);
  54356. }
  54357. if (this._onbuttonup && newValue === 0) {
  54358. this._onbuttonup(buttonType);
  54359. }
  54360. }
  54361. return newValue;
  54362. };
  54363. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  54364. if (newValue !== currentValue) {
  54365. if (this._ondpaddown && newValue === 1) {
  54366. this._ondpaddown(buttonType);
  54367. }
  54368. if (this._ondpadup && newValue === 0) {
  54369. this._ondpadup(buttonType);
  54370. }
  54371. }
  54372. return newValue;
  54373. };
  54374. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  54375. get: function () {
  54376. return this._buttonA;
  54377. },
  54378. set: function (value) {
  54379. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  54380. },
  54381. enumerable: true,
  54382. configurable: true
  54383. });
  54384. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  54385. get: function () {
  54386. return this._buttonB;
  54387. },
  54388. set: function (value) {
  54389. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  54390. },
  54391. enumerable: true,
  54392. configurable: true
  54393. });
  54394. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  54395. get: function () {
  54396. return this._buttonX;
  54397. },
  54398. set: function (value) {
  54399. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  54400. },
  54401. enumerable: true,
  54402. configurable: true
  54403. });
  54404. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  54405. get: function () {
  54406. return this._buttonY;
  54407. },
  54408. set: function (value) {
  54409. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  54410. },
  54411. enumerable: true,
  54412. configurable: true
  54413. });
  54414. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  54415. get: function () {
  54416. return this._buttonStart;
  54417. },
  54418. set: function (value) {
  54419. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  54420. },
  54421. enumerable: true,
  54422. configurable: true
  54423. });
  54424. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  54425. get: function () {
  54426. return this._buttonBack;
  54427. },
  54428. set: function (value) {
  54429. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  54430. },
  54431. enumerable: true,
  54432. configurable: true
  54433. });
  54434. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  54435. get: function () {
  54436. return this._buttonLB;
  54437. },
  54438. set: function (value) {
  54439. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  54440. },
  54441. enumerable: true,
  54442. configurable: true
  54443. });
  54444. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  54445. get: function () {
  54446. return this._buttonRB;
  54447. },
  54448. set: function (value) {
  54449. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  54450. },
  54451. enumerable: true,
  54452. configurable: true
  54453. });
  54454. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  54455. get: function () {
  54456. return this._buttonLeftStick;
  54457. },
  54458. set: function (value) {
  54459. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  54460. },
  54461. enumerable: true,
  54462. configurable: true
  54463. });
  54464. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  54465. get: function () {
  54466. return this._buttonRightStick;
  54467. },
  54468. set: function (value) {
  54469. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  54470. },
  54471. enumerable: true,
  54472. configurable: true
  54473. });
  54474. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  54475. get: function () {
  54476. return this._dPadUp;
  54477. },
  54478. set: function (value) {
  54479. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  54480. },
  54481. enumerable: true,
  54482. configurable: true
  54483. });
  54484. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  54485. get: function () {
  54486. return this._dPadDown;
  54487. },
  54488. set: function (value) {
  54489. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  54490. },
  54491. enumerable: true,
  54492. configurable: true
  54493. });
  54494. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  54495. get: function () {
  54496. return this._dPadLeft;
  54497. },
  54498. set: function (value) {
  54499. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  54500. },
  54501. enumerable: true,
  54502. configurable: true
  54503. });
  54504. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  54505. get: function () {
  54506. return this._dPadRight;
  54507. },
  54508. set: function (value) {
  54509. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  54510. },
  54511. enumerable: true,
  54512. configurable: true
  54513. });
  54514. Xbox360Pad.prototype.update = function () {
  54515. _super.prototype.update.call(this);
  54516. this.buttonA = this.browserGamepad.buttons[0].value;
  54517. this.buttonB = this.browserGamepad.buttons[1].value;
  54518. this.buttonX = this.browserGamepad.buttons[2].value;
  54519. this.buttonY = this.browserGamepad.buttons[3].value;
  54520. this.buttonLB = this.browserGamepad.buttons[4].value;
  54521. this.buttonRB = this.browserGamepad.buttons[5].value;
  54522. this.leftTrigger = this.browserGamepad.buttons[6].value;
  54523. this.rightTrigger = this.browserGamepad.buttons[7].value;
  54524. this.buttonBack = this.browserGamepad.buttons[8].value;
  54525. this.buttonStart = this.browserGamepad.buttons[9].value;
  54526. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  54527. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  54528. this.dPadUp = this.browserGamepad.buttons[12].value;
  54529. this.dPadDown = this.browserGamepad.buttons[13].value;
  54530. this.dPadLeft = this.browserGamepad.buttons[14].value;
  54531. this.dPadRight = this.browserGamepad.buttons[15].value;
  54532. };
  54533. return Xbox360Pad;
  54534. })(Gamepad);
  54535. BABYLON.Xbox360Pad = Xbox360Pad;
  54536. })(BABYLON || (BABYLON = {}));
  54537. var BABYLON;
  54538. (function (BABYLON) {
  54539. // We're mainly based on the logic defined into the FreeCamera code
  54540. var GamepadCamera = (function (_super) {
  54541. __extends(GamepadCamera, _super);
  54542. //-- end properties for backward compatibility for inputs
  54543. function GamepadCamera(name, position, scene) {
  54544. BABYLON.Tools.Warn("Deprecated. Please use Universal Camera instead.");
  54545. _super.call(this, name, position, scene);
  54546. }
  54547. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  54548. //-- Begin properties for backward compatibility for inputs
  54549. get: function () {
  54550. var gamepad = this.inputs.attached["gamepad"];
  54551. if (gamepad)
  54552. return gamepad.gamepadAngularSensibility;
  54553. },
  54554. set: function (value) {
  54555. var gamepad = this.inputs.attached["gamepad"];
  54556. if (gamepad)
  54557. gamepad.gamepadAngularSensibility = value;
  54558. },
  54559. enumerable: true,
  54560. configurable: true
  54561. });
  54562. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  54563. get: function () {
  54564. var gamepad = this.inputs.attached["gamepad"];
  54565. if (gamepad)
  54566. return gamepad.gamepadMoveSensibility;
  54567. },
  54568. set: function (value) {
  54569. var gamepad = this.inputs.attached["gamepad"];
  54570. if (gamepad)
  54571. gamepad.gamepadMoveSensibility = value;
  54572. },
  54573. enumerable: true,
  54574. configurable: true
  54575. });
  54576. GamepadCamera.prototype.getTypeName = function () {
  54577. return "GamepadCamera";
  54578. };
  54579. return GamepadCamera;
  54580. })(BABYLON.UniversalCamera);
  54581. BABYLON.GamepadCamera = GamepadCamera;
  54582. })(BABYLON || (BABYLON = {}));
  54583. var BABYLON;
  54584. (function (BABYLON) {
  54585. var Analyser = (function () {
  54586. function Analyser(scene) {
  54587. this.SMOOTHING = 0.75;
  54588. this.FFT_SIZE = 512;
  54589. this.BARGRAPHAMPLITUDE = 256;
  54590. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  54591. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  54592. this._scene = scene;
  54593. this._audioEngine = BABYLON.Engine.audioEngine;
  54594. if (this._audioEngine.canUseWebAudio) {
  54595. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  54596. this._webAudioAnalyser.minDecibels = -140;
  54597. this._webAudioAnalyser.maxDecibels = 0;
  54598. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  54599. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  54600. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  54601. }
  54602. }
  54603. Analyser.prototype.getFrequencyBinCount = function () {
  54604. if (this._audioEngine.canUseWebAudio) {
  54605. return this._webAudioAnalyser.frequencyBinCount;
  54606. }
  54607. else {
  54608. return 0;
  54609. }
  54610. };
  54611. Analyser.prototype.getByteFrequencyData = function () {
  54612. if (this._audioEngine.canUseWebAudio) {
  54613. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  54614. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  54615. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  54616. }
  54617. return this._byteFreqs;
  54618. };
  54619. Analyser.prototype.getByteTimeDomainData = function () {
  54620. if (this._audioEngine.canUseWebAudio) {
  54621. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  54622. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  54623. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  54624. }
  54625. return this._byteTime;
  54626. };
  54627. Analyser.prototype.getFloatFrequencyData = function () {
  54628. if (this._audioEngine.canUseWebAudio) {
  54629. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  54630. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  54631. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  54632. }
  54633. return this._floatFreqs;
  54634. };
  54635. Analyser.prototype.drawDebugCanvas = function () {
  54636. var _this = this;
  54637. if (this._audioEngine.canUseWebAudio) {
  54638. if (!this._debugCanvas) {
  54639. this._debugCanvas = document.createElement("canvas");
  54640. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  54641. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  54642. this._debugCanvas.style.position = "absolute";
  54643. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  54644. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  54645. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  54646. document.body.appendChild(this._debugCanvas);
  54647. this._registerFunc = function () {
  54648. _this.drawDebugCanvas();
  54649. };
  54650. this._scene.registerBeforeRender(this._registerFunc);
  54651. }
  54652. if (this._registerFunc) {
  54653. var workingArray = this.getByteFrequencyData();
  54654. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  54655. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  54656. // Draw the frequency domain chart.
  54657. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  54658. var value = workingArray[i];
  54659. var percent = value / this.BARGRAPHAMPLITUDE;
  54660. var height = this.DEBUGCANVASSIZE.height * percent;
  54661. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  54662. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  54663. var hue = i / this.getFrequencyBinCount() * 360;
  54664. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  54665. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  54666. }
  54667. }
  54668. }
  54669. };
  54670. Analyser.prototype.stopDebugCanvas = function () {
  54671. if (this._debugCanvas) {
  54672. this._scene.unregisterBeforeRender(this._registerFunc);
  54673. this._registerFunc = null;
  54674. document.body.removeChild(this._debugCanvas);
  54675. this._debugCanvas = null;
  54676. this._debugCanvasContext = null;
  54677. }
  54678. };
  54679. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  54680. if (this._audioEngine.canUseWebAudio) {
  54681. inputAudioNode.connect(this._webAudioAnalyser);
  54682. this._webAudioAnalyser.connect(outputAudioNode);
  54683. }
  54684. };
  54685. Analyser.prototype.dispose = function () {
  54686. if (this._audioEngine.canUseWebAudio) {
  54687. this._webAudioAnalyser.disconnect();
  54688. }
  54689. };
  54690. return Analyser;
  54691. })();
  54692. BABYLON.Analyser = Analyser;
  54693. })(BABYLON || (BABYLON = {}));
  54694. var BABYLON;
  54695. (function (BABYLON) {
  54696. var DepthRenderer = (function () {
  54697. function DepthRenderer(scene, type) {
  54698. var _this = this;
  54699. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  54700. this._viewMatrix = BABYLON.Matrix.Zero();
  54701. this._projectionMatrix = BABYLON.Matrix.Zero();
  54702. this._transformMatrix = BABYLON.Matrix.Zero();
  54703. this._worldViewProjection = BABYLON.Matrix.Zero();
  54704. this._scene = scene;
  54705. var engine = scene.getEngine();
  54706. // Render target
  54707. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  54708. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54709. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54710. this._depthMap.refreshRate = 1;
  54711. this._depthMap.renderParticles = false;
  54712. this._depthMap.renderList = null;
  54713. // set default depth value to 1.0 (far away)
  54714. this._depthMap.onClearObservable.add(function (engine) {
  54715. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  54716. });
  54717. // Custom render function
  54718. var renderSubMesh = function (subMesh) {
  54719. var mesh = subMesh.getRenderingMesh();
  54720. var scene = _this._scene;
  54721. var engine = scene.getEngine();
  54722. // Culling
  54723. engine.setState(subMesh.getMaterial().backFaceCulling);
  54724. // Managing instances
  54725. var batch = mesh._getInstancesRenderList(subMesh._id);
  54726. if (batch.mustReturn) {
  54727. return;
  54728. }
  54729. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  54730. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  54731. engine.enableEffect(_this._effect);
  54732. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  54733. var material = subMesh.getMaterial();
  54734. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  54735. _this._effect.setFloat("far", scene.activeCamera.maxZ);
  54736. // Alpha test
  54737. if (material && material.needAlphaTesting()) {
  54738. var alphaTexture = material.getAlphaTestTexture();
  54739. _this._effect.setTexture("diffuseSampler", alphaTexture);
  54740. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  54741. }
  54742. // Bones
  54743. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  54744. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  54745. }
  54746. // Draw
  54747. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  54748. }
  54749. };
  54750. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  54751. var index;
  54752. for (index = 0; index < opaqueSubMeshes.length; index++) {
  54753. renderSubMesh(opaqueSubMeshes.data[index]);
  54754. }
  54755. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  54756. renderSubMesh(alphaTestSubMeshes.data[index]);
  54757. }
  54758. };
  54759. }
  54760. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  54761. var material = subMesh.getMaterial();
  54762. if (material.disableDepthWrite) {
  54763. return false;
  54764. }
  54765. var defines = [];
  54766. var attribs = [BABYLON.VertexBuffer.PositionKind];
  54767. var mesh = subMesh.getMesh();
  54768. var scene = mesh.getScene();
  54769. // Alpha test
  54770. if (material && material.needAlphaTesting()) {
  54771. defines.push("#define ALPHATEST");
  54772. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  54773. attribs.push(BABYLON.VertexBuffer.UVKind);
  54774. defines.push("#define UV1");
  54775. }
  54776. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  54777. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  54778. defines.push("#define UV2");
  54779. }
  54780. }
  54781. // Bones
  54782. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  54783. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  54784. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  54785. if (mesh.numBoneInfluencers > 4) {
  54786. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  54787. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  54788. }
  54789. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  54790. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  54791. }
  54792. else {
  54793. defines.push("#define NUM_BONE_INFLUENCERS 0");
  54794. }
  54795. // Instances
  54796. if (useInstances) {
  54797. defines.push("#define INSTANCES");
  54798. attribs.push("world0");
  54799. attribs.push("world1");
  54800. attribs.push("world2");
  54801. attribs.push("world3");
  54802. }
  54803. // Get correct effect
  54804. var join = defines.join("\n");
  54805. if (this._cachedDefines !== join) {
  54806. this._cachedDefines = join;
  54807. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler"], join);
  54808. }
  54809. return this._effect.isReady();
  54810. };
  54811. DepthRenderer.prototype.getDepthMap = function () {
  54812. return this._depthMap;
  54813. };
  54814. // Methods
  54815. DepthRenderer.prototype.dispose = function () {
  54816. this._depthMap.dispose();
  54817. };
  54818. return DepthRenderer;
  54819. })();
  54820. BABYLON.DepthRenderer = DepthRenderer;
  54821. })(BABYLON || (BABYLON = {}));
  54822. var BABYLON;
  54823. (function (BABYLON) {
  54824. var SSAORenderingPipeline = (function (_super) {
  54825. __extends(SSAORenderingPipeline, _super);
  54826. /**
  54827. * @constructor
  54828. * @param {string} name - The rendering pipeline name
  54829. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  54830. * @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 }
  54831. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  54832. */
  54833. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  54834. var _this = this;
  54835. _super.call(this, scene.getEngine(), name);
  54836. // Members
  54837. /**
  54838. * The PassPostProcess id in the pipeline that contains the original scene color
  54839. * @type {string}
  54840. */
  54841. this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  54842. /**
  54843. * The SSAO PostProcess id in the pipeline
  54844. * @type {string}
  54845. */
  54846. this.SSAORenderEffect = "SSAORenderEffect";
  54847. /**
  54848. * The horizontal blur PostProcess id in the pipeline
  54849. * @type {string}
  54850. */
  54851. this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  54852. /**
  54853. * The vertical blur PostProcess id in the pipeline
  54854. * @type {string}
  54855. */
  54856. this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  54857. /**
  54858. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  54859. * @type {string}
  54860. */
  54861. this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  54862. /**
  54863. * The output strength of the SSAO post-process. Default value is 1.0.
  54864. * @type {number}
  54865. */
  54866. this.totalStrength = 1.0;
  54867. /**
  54868. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  54869. * @type {number}
  54870. */
  54871. this.radius = 0.0001;
  54872. /**
  54873. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  54874. * Must not be equal to fallOff and superior to fallOff.
  54875. * Default value is 0.975
  54876. * @type {number}
  54877. */
  54878. this.area = 0.0075;
  54879. /**
  54880. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  54881. * Must not be equal to area and inferior to area.
  54882. * Default value is 0.0
  54883. * @type {number}
  54884. */
  54885. this.fallOff = 0.000001;
  54886. /**
  54887. * The base color of the SSAO post-process
  54888. * The final result is "base + ssao" between [0, 1]
  54889. * @type {number}
  54890. */
  54891. this.base = 0.5;
  54892. this._firstUpdate = true;
  54893. this._scene = scene;
  54894. // Set up assets
  54895. this._createRandomTexture();
  54896. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  54897. var ssaoRatio = ratio.ssaoRatio || ratio;
  54898. var combineRatio = ratio.combineRatio || ratio;
  54899. this._ratio = {
  54900. ssaoRatio: ssaoRatio,
  54901. combineRatio: combineRatio
  54902. };
  54903. this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  54904. this._createSSAOPostProcess(ssaoRatio);
  54905. this._createBlurPostProcess(ssaoRatio);
  54906. this._createSSAOCombinePostProcess(combineRatio);
  54907. // Set up pipeline
  54908. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  54909. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  54910. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  54911. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  54912. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  54913. // Finish
  54914. scene.postProcessRenderPipelineManager.addPipeline(this);
  54915. if (cameras)
  54916. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  54917. }
  54918. // Public Methods
  54919. /**
  54920. * Returns the horizontal blur PostProcess
  54921. * @return {BABYLON.BlurPostProcess} The horizontal blur post-process
  54922. */
  54923. SSAORenderingPipeline.prototype.getBlurHPostProcess = function () {
  54924. BABYLON.Tools.Error("SSAORenderinPipeline.getBlurHPostProcess() is deprecated, no more blur post-process exists");
  54925. return null;
  54926. };
  54927. /**
  54928. * Returns the vertical blur PostProcess
  54929. * @return {BABYLON.BlurPostProcess} The vertical blur post-process
  54930. */
  54931. SSAORenderingPipeline.prototype.getBlurVPostProcess = function () {
  54932. BABYLON.Tools.Error("SSAORenderinPipeline.getBlurVPostProcess() is deprecated, no more blur post-process exists");
  54933. return null;
  54934. };
  54935. /**
  54936. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  54937. */
  54938. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  54939. if (disableDepthRender === void 0) { disableDepthRender = false; }
  54940. for (var i = 0; i < this._scene.cameras.length; i++) {
  54941. var camera = this._scene.cameras[i];
  54942. this._originalColorPostProcess.dispose(camera);
  54943. this._ssaoPostProcess.dispose(camera);
  54944. this._blurHPostProcess.dispose(camera);
  54945. this._blurVPostProcess.dispose(camera);
  54946. this._ssaoCombinePostProcess.dispose(camera);
  54947. }
  54948. this._randomTexture.dispose();
  54949. if (disableDepthRender)
  54950. this._scene.disableDepthRenderer();
  54951. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  54952. };
  54953. // Private Methods
  54954. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  54955. var _this = this;
  54956. /*
  54957. var samplerOffsets = [
  54958. -8.0, -6.0, -4.0, -2.0,
  54959. 0.0,
  54960. 2.0, 4.0, 6.0, 8.0
  54961. ];
  54962. */
  54963. var samples = 16;
  54964. var samplerOffsets = [];
  54965. for (var i = -8; i < 8; i++) {
  54966. samplerOffsets.push(i * 2);
  54967. }
  54968. 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");
  54969. this._blurHPostProcess.onApply = function (effect) {
  54970. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width);
  54971. effect.setTexture("depthSampler", _this._depthTexture);
  54972. if (_this._firstUpdate) {
  54973. effect.setArray("samplerOffsets", samplerOffsets);
  54974. }
  54975. };
  54976. 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");
  54977. this._blurVPostProcess.onApply = function (effect) {
  54978. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height);
  54979. effect.setTexture("depthSampler", _this._depthTexture);
  54980. if (_this._firstUpdate) {
  54981. effect.setArray("samplerOffsets", samplerOffsets);
  54982. _this._firstUpdate = false;
  54983. }
  54984. };
  54985. };
  54986. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  54987. var _this = this;
  54988. var numSamples = 16;
  54989. var sampleSphere = [
  54990. 0.5381, 0.1856, -0.4319,
  54991. 0.1379, 0.2486, 0.4430,
  54992. 0.3371, 0.5679, -0.0057,
  54993. -0.6999, -0.0451, -0.0019,
  54994. 0.0689, -0.1598, -0.8547,
  54995. 0.0560, 0.0069, -0.1843,
  54996. -0.0146, 0.1402, 0.0762,
  54997. 0.0100, -0.1924, -0.0344,
  54998. -0.3577, -0.5301, -0.4358,
  54999. -0.3169, 0.1063, 0.0158,
  55000. 0.0103, -0.5869, 0.0046,
  55001. -0.0897, -0.4940, 0.3287,
  55002. 0.7119, -0.0154, -0.0918,
  55003. -0.0533, 0.0596, -0.5411,
  55004. 0.0352, -0.0631, 0.5460,
  55005. -0.4776, 0.2847, -0.0271
  55006. ];
  55007. var samplesFactor = 1.0 / numSamples;
  55008. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  55009. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  55010. "area", "fallOff", "base", "range", "viewport"
  55011. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  55012. var viewport = new BABYLON.Vector2(0, 0);
  55013. this._ssaoPostProcess.onApply = function (effect) {
  55014. if (_this._firstUpdate) {
  55015. effect.setArray3("sampleSphere", sampleSphere);
  55016. effect.setFloat("samplesFactor", samplesFactor);
  55017. effect.setFloat("randTextureTiles", 4.0);
  55018. }
  55019. effect.setFloat("totalStrength", _this.totalStrength);
  55020. effect.setFloat("radius", _this.radius);
  55021. effect.setFloat("area", _this.area);
  55022. effect.setFloat("fallOff", _this.fallOff);
  55023. effect.setFloat("base", _this.base);
  55024. effect.setTexture("textureSampler", _this._depthTexture);
  55025. effect.setTexture("randomSampler", _this._randomTexture);
  55026. };
  55027. };
  55028. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  55029. var _this = this;
  55030. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  55031. this._ssaoCombinePostProcess.onApply = function (effect) {
  55032. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  55033. };
  55034. };
  55035. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  55036. var size = 512;
  55037. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  55038. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  55039. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  55040. var context = this._randomTexture.getContext();
  55041. var rand = function (min, max) {
  55042. return Math.random() * (max - min) + min;
  55043. };
  55044. var randVector = BABYLON.Vector3.Zero();
  55045. for (var x = 0; x < size; x++) {
  55046. for (var y = 0; y < size; y++) {
  55047. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  55048. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  55049. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  55050. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  55051. context.fillRect(x, y, 1, 1);
  55052. }
  55053. }
  55054. this._randomTexture.update(false);
  55055. };
  55056. __decorate([
  55057. BABYLON.serialize()
  55058. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  55059. __decorate([
  55060. BABYLON.serialize()
  55061. ], SSAORenderingPipeline.prototype, "radius", void 0);
  55062. __decorate([
  55063. BABYLON.serialize()
  55064. ], SSAORenderingPipeline.prototype, "area", void 0);
  55065. __decorate([
  55066. BABYLON.serialize()
  55067. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  55068. __decorate([
  55069. BABYLON.serialize()
  55070. ], SSAORenderingPipeline.prototype, "base", void 0);
  55071. __decorate([
  55072. BABYLON.serialize()
  55073. ], SSAORenderingPipeline.prototype, "_ratio", void 0);
  55074. return SSAORenderingPipeline;
  55075. })(BABYLON.PostProcessRenderPipeline);
  55076. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  55077. })(BABYLON || (BABYLON = {}));
  55078. var BABYLON;
  55079. (function (BABYLON) {
  55080. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  55081. var VolumetricLightScatteringPostProcess = (function (_super) {
  55082. __extends(VolumetricLightScatteringPostProcess, _super);
  55083. /**
  55084. * @constructor
  55085. * @param {string} name - The post-process name
  55086. * @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)
  55087. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  55088. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  55089. * @param {number} samples - The post-process quality, default 100
  55090. * @param {number} samplingMode - The post-process filtering mode
  55091. * @param {BABYLON.Engine} engine - The babylon engine
  55092. * @param {boolean} reusable - If the post-process is reusable
  55093. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  55094. */
  55095. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  55096. var _this = this;
  55097. if (samples === void 0) { samples = 100; }
  55098. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  55099. _super.call(this, name, "volumetricLightScattering", ["decay", "exposure", "weight", "meshPositionOnScreen", "density"], ["lightScatteringSampler"], ratio.postProcessRatio || ratio, camera, samplingMode, engine, reusable, "#define NUM_SAMPLES " + samples);
  55100. this._screenCoordinates = BABYLON.Vector2.Zero();
  55101. /**
  55102. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  55103. * @type {Vector3}
  55104. */
  55105. this.customMeshPosition = BABYLON.Vector3.Zero();
  55106. /**
  55107. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  55108. * @type {boolean}
  55109. */
  55110. this.useCustomMeshPosition = false;
  55111. /**
  55112. * If the post-process should inverse the light scattering direction
  55113. * @type {boolean}
  55114. */
  55115. this.invert = true;
  55116. /**
  55117. * Array containing the excluded meshes not rendered in the internal pass
  55118. */
  55119. this.excludedMeshes = new Array();
  55120. /**
  55121. * Controls the overall intensity of the post-process
  55122. * @type {number}
  55123. */
  55124. this.exposure = 0.3;
  55125. /**
  55126. * Dissipates each sample's contribution in range [0, 1]
  55127. * @type {number}
  55128. */
  55129. this.decay = 0.96815;
  55130. /**
  55131. * Controls the overall intensity of each sample
  55132. * @type {number}
  55133. */
  55134. this.weight = 0.58767;
  55135. /**
  55136. * Controls the density of each sample
  55137. * @type {number}
  55138. */
  55139. this.density = 0.926;
  55140. scene = (camera === null) ? scene : camera.getScene(); // parameter "scene" can be null.
  55141. var engine = scene.getEngine();
  55142. this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  55143. // Configure mesh
  55144. this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  55145. // Configure
  55146. this._createPass(scene, ratio.passRatio || ratio);
  55147. this.onActivate = function (camera) {
  55148. if (!_this.isSupported) {
  55149. _this.dispose(camera);
  55150. }
  55151. _this.onActivate = null;
  55152. };
  55153. this.onApplyObservable.add(function (effect) {
  55154. _this._updateMeshScreenCoordinates(scene);
  55155. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  55156. effect.setFloat("exposure", _this.exposure);
  55157. effect.setFloat("decay", _this.decay);
  55158. effect.setFloat("weight", _this.weight);
  55159. effect.setFloat("density", _this.density);
  55160. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  55161. });
  55162. }
  55163. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  55164. get: function () {
  55165. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  55166. return false;
  55167. },
  55168. set: function (useDiffuseColor) {
  55169. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  55170. },
  55171. enumerable: true,
  55172. configurable: true
  55173. });
  55174. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  55175. var mesh = subMesh.getMesh();
  55176. // Render this.mesh as default
  55177. if (mesh === this.mesh) {
  55178. return mesh.material.isReady(mesh);
  55179. }
  55180. var defines = [];
  55181. var attribs = [BABYLON.VertexBuffer.PositionKind];
  55182. var material = subMesh.getMaterial();
  55183. var needUV = false;
  55184. // Alpha test
  55185. if (material) {
  55186. if (material.needAlphaTesting()) {
  55187. defines.push("#define ALPHATEST");
  55188. }
  55189. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  55190. attribs.push(BABYLON.VertexBuffer.UVKind);
  55191. defines.push("#define UV1");
  55192. }
  55193. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  55194. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  55195. defines.push("#define UV2");
  55196. }
  55197. }
  55198. // Bones
  55199. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  55200. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  55201. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  55202. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  55203. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  55204. }
  55205. else {
  55206. defines.push("#define NUM_BONE_INFLUENCERS 0");
  55207. }
  55208. // Instances
  55209. if (useInstances) {
  55210. defines.push("#define INSTANCES");
  55211. attribs.push("world0");
  55212. attribs.push("world1");
  55213. attribs.push("world2");
  55214. attribs.push("world3");
  55215. }
  55216. // Get correct effect
  55217. var join = defines.join("\n");
  55218. if (this._cachedDefines !== join) {
  55219. this._cachedDefines = join;
  55220. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  55221. }
  55222. return this._volumetricLightScatteringPass.isReady();
  55223. };
  55224. /**
  55225. * Sets the new light position for light scattering effect
  55226. * @param {BABYLON.Vector3} The new custom light position
  55227. */
  55228. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  55229. this.customMeshPosition = position;
  55230. };
  55231. /**
  55232. * Returns the light position for light scattering effect
  55233. * @return {BABYLON.Vector3} The custom light position
  55234. */
  55235. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  55236. return this.customMeshPosition;
  55237. };
  55238. /**
  55239. * Disposes the internal assets and detaches the post-process from the camera
  55240. */
  55241. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  55242. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  55243. if (rttIndex !== -1) {
  55244. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  55245. }
  55246. this._volumetricLightScatteringRTT.dispose();
  55247. _super.prototype.dispose.call(this, camera);
  55248. };
  55249. /**
  55250. * Returns the render target texture used by the post-process
  55251. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  55252. */
  55253. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  55254. return this._volumetricLightScatteringRTT;
  55255. };
  55256. // Private methods
  55257. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  55258. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  55259. return true;
  55260. }
  55261. return false;
  55262. };
  55263. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  55264. var _this = this;
  55265. var engine = scene.getEngine();
  55266. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  55267. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  55268. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  55269. this._volumetricLightScatteringRTT.renderList = null;
  55270. this._volumetricLightScatteringRTT.renderParticles = false;
  55271. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  55272. // Custom render function for submeshes
  55273. var renderSubMesh = function (subMesh) {
  55274. var mesh = subMesh.getRenderingMesh();
  55275. if (_this._meshExcluded(mesh)) {
  55276. return;
  55277. }
  55278. var scene = mesh.getScene();
  55279. var engine = scene.getEngine();
  55280. // Culling
  55281. engine.setState(subMesh.getMaterial().backFaceCulling);
  55282. // Managing instances
  55283. var batch = mesh._getInstancesRenderList(subMesh._id);
  55284. if (batch.mustReturn) {
  55285. return;
  55286. }
  55287. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  55288. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  55289. var effect = _this._volumetricLightScatteringPass;
  55290. if (mesh === _this.mesh) {
  55291. effect = subMesh.getMaterial().getEffect();
  55292. }
  55293. engine.enableEffect(effect);
  55294. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  55295. if (mesh === _this.mesh) {
  55296. subMesh.getMaterial().bind(mesh.getWorldMatrix(), mesh);
  55297. }
  55298. else {
  55299. var material = subMesh.getMaterial();
  55300. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  55301. // Alpha test
  55302. if (material && material.needAlphaTesting()) {
  55303. var alphaTexture = material.getAlphaTestTexture();
  55304. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  55305. if (alphaTexture) {
  55306. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  55307. }
  55308. }
  55309. // Bones
  55310. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  55311. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  55312. }
  55313. }
  55314. // Draw
  55315. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  55316. }
  55317. };
  55318. // Render target texture callbacks
  55319. var savedSceneClearColor;
  55320. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  55321. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  55322. savedSceneClearColor = scene.clearColor;
  55323. scene.clearColor = sceneClearColor;
  55324. });
  55325. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  55326. scene.clearColor = savedSceneClearColor;
  55327. });
  55328. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  55329. var engine = scene.getEngine();
  55330. var index;
  55331. for (index = 0; index < opaqueSubMeshes.length; index++) {
  55332. renderSubMesh(opaqueSubMeshes.data[index]);
  55333. }
  55334. engine.setAlphaTesting(true);
  55335. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  55336. renderSubMesh(alphaTestSubMeshes.data[index]);
  55337. }
  55338. engine.setAlphaTesting(false);
  55339. if (transparentSubMeshes.length) {
  55340. // Sort sub meshes
  55341. for (index = 0; index < transparentSubMeshes.length; index++) {
  55342. var submesh = transparentSubMeshes.data[index];
  55343. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  55344. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  55345. }
  55346. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  55347. sortedArray.sort(function (a, b) {
  55348. // Alpha index first
  55349. if (a._alphaIndex > b._alphaIndex) {
  55350. return 1;
  55351. }
  55352. if (a._alphaIndex < b._alphaIndex) {
  55353. return -1;
  55354. }
  55355. // Then distance to camera
  55356. if (a._distanceToCamera < b._distanceToCamera) {
  55357. return 1;
  55358. }
  55359. if (a._distanceToCamera > b._distanceToCamera) {
  55360. return -1;
  55361. }
  55362. return 0;
  55363. });
  55364. // Render sub meshes
  55365. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  55366. for (index = 0; index < sortedArray.length; index++) {
  55367. renderSubMesh(sortedArray[index]);
  55368. }
  55369. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  55370. }
  55371. };
  55372. };
  55373. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  55374. var transform = scene.getTransformMatrix();
  55375. var meshPosition;
  55376. if (this.useCustomMeshPosition) {
  55377. meshPosition = this.customMeshPosition;
  55378. }
  55379. else if (this.attachedNode) {
  55380. meshPosition = this.attachedNode.position;
  55381. }
  55382. else {
  55383. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  55384. }
  55385. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  55386. this._screenCoordinates.x = pos.x / this._viewPort.width;
  55387. this._screenCoordinates.y = pos.y / this._viewPort.height;
  55388. if (this.invert)
  55389. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  55390. };
  55391. // Static methods
  55392. /**
  55393. * Creates a default mesh for the Volumeric Light Scattering post-process
  55394. * @param {string} The mesh name
  55395. * @param {BABYLON.Scene} The scene where to create the mesh
  55396. * @return {BABYLON.Mesh} the default mesh
  55397. */
  55398. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  55399. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  55400. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  55401. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  55402. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  55403. mesh.material = material;
  55404. return mesh;
  55405. };
  55406. __decorate([
  55407. BABYLON.serializeAsVector3()
  55408. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  55409. __decorate([
  55410. BABYLON.serialize()
  55411. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  55412. __decorate([
  55413. BABYLON.serialize()
  55414. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  55415. __decorate([
  55416. BABYLON.serializeAsMeshReference()
  55417. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  55418. __decorate([
  55419. BABYLON.serialize()
  55420. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  55421. __decorate([
  55422. BABYLON.serialize()
  55423. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  55424. __decorate([
  55425. BABYLON.serialize()
  55426. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  55427. __decorate([
  55428. BABYLON.serialize()
  55429. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  55430. __decorate([
  55431. BABYLON.serialize()
  55432. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  55433. return VolumetricLightScatteringPostProcess;
  55434. })(BABYLON.PostProcess);
  55435. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  55436. })(BABYLON || (BABYLON = {}));
  55437. // BABYLON.JS Chromatic Aberration GLSL Shader
  55438. // Author: Olivier Guyot
  55439. // Separates very slightly R, G and B colors on the edges of the screen
  55440. // Inspired by Francois Tarlier & Martins Upitis
  55441. var BABYLON;
  55442. (function (BABYLON) {
  55443. var LensRenderingPipeline = (function (_super) {
  55444. __extends(LensRenderingPipeline, _super);
  55445. /**
  55446. * @constructor
  55447. *
  55448. * Effect parameters are as follow:
  55449. * {
  55450. * chromatic_aberration: number; // from 0 to x (1 for realism)
  55451. * edge_blur: number; // from 0 to x (1 for realism)
  55452. * distortion: number; // from 0 to x (1 for realism)
  55453. * grain_amount: number; // from 0 to 1
  55454. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  55455. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  55456. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  55457. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  55458. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  55459. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  55460. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  55461. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  55462. * }
  55463. * Note: if an effect parameter is unset, effect is disabled
  55464. *
  55465. * @param {string} name - The rendering pipeline name
  55466. * @param {object} parameters - An object containing all parameters (see above)
  55467. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  55468. * @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)
  55469. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  55470. */
  55471. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  55472. var _this = this;
  55473. if (ratio === void 0) { ratio = 1.0; }
  55474. _super.call(this, scene.getEngine(), name);
  55475. // Lens effects can be of the following:
  55476. // - chromatic aberration (slight shift of RGB colors)
  55477. // - blur on the edge of the lens
  55478. // - lens distortion
  55479. // - depth-of-field blur & highlights enhancing
  55480. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  55481. // - grain effect (noise or custom texture)
  55482. // Two additional texture samplers are needed:
  55483. // - depth map (for depth-of-field)
  55484. // - grain texture
  55485. /**
  55486. * The chromatic aberration PostProcess id in the pipeline
  55487. * @type {string}
  55488. */
  55489. this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  55490. /**
  55491. * The highlights enhancing PostProcess id in the pipeline
  55492. * @type {string}
  55493. */
  55494. this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  55495. /**
  55496. * The depth-of-field PostProcess id in the pipeline
  55497. * @type {string}
  55498. */
  55499. this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  55500. this._scene = scene;
  55501. // Fetch texture samplers
  55502. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  55503. if (parameters.grain_texture) {
  55504. this._grainTexture = parameters.grain_texture;
  55505. }
  55506. else {
  55507. this._createGrainTexture();
  55508. }
  55509. // save parameters
  55510. this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  55511. this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  55512. this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  55513. this._distortion = parameters.distortion ? parameters.distortion : 0;
  55514. this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  55515. this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  55516. this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  55517. this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  55518. this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  55519. this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  55520. this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  55521. // Create effects
  55522. this._createChromaticAberrationPostProcess(ratio);
  55523. this._createHighlightsPostProcess(ratio);
  55524. this._createDepthOfFieldPostProcess(ratio / 4);
  55525. // Set up pipeline
  55526. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  55527. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  55528. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  55529. if (this._highlightsGain === -1) {
  55530. this._disableEffect(this.HighlightsEnhancingEffect, null);
  55531. }
  55532. // Finish
  55533. scene.postProcessRenderPipelineManager.addPipeline(this);
  55534. if (cameras) {
  55535. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  55536. }
  55537. }
  55538. // public methods (self explanatory)
  55539. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  55540. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  55541. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  55542. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  55543. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  55544. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  55545. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  55546. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  55547. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  55548. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  55549. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  55550. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  55551. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  55552. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  55553. };
  55554. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  55555. this._highlightsPostProcess.updateEffect();
  55556. };
  55557. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  55558. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  55559. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  55560. this._highlightsGain = amount;
  55561. };
  55562. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  55563. if (this._highlightsGain === -1) {
  55564. this._highlightsGain = 1.0;
  55565. }
  55566. this._highlightsThreshold = amount;
  55567. };
  55568. LensRenderingPipeline.prototype.disableHighlights = function () {
  55569. this._highlightsGain = -1;
  55570. };
  55571. /**
  55572. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  55573. */
  55574. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  55575. if (disableDepthRender === void 0) { disableDepthRender = false; }
  55576. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  55577. this._chromaticAberrationPostProcess = undefined;
  55578. this._highlightsPostProcess = undefined;
  55579. this._depthOfFieldPostProcess = undefined;
  55580. this._grainTexture.dispose();
  55581. if (disableDepthRender)
  55582. this._scene.disableDepthRenderer();
  55583. };
  55584. // colors shifting and distortion
  55585. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  55586. var _this = this;
  55587. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  55588. [], // samplers
  55589. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  55590. this._chromaticAberrationPostProcess.onApply = function (effect) {
  55591. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  55592. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  55593. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  55594. };
  55595. };
  55596. // highlights enhancing
  55597. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  55598. var _this = this;
  55599. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  55600. [], // samplers
  55601. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  55602. this._highlightsPostProcess.onApply = function (effect) {
  55603. effect.setFloat('gain', _this._highlightsGain);
  55604. effect.setFloat('threshold', _this._highlightsThreshold);
  55605. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  55606. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  55607. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  55608. };
  55609. };
  55610. // colors shifting and distortion
  55611. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  55612. var _this = this;
  55613. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  55614. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  55615. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  55616. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  55617. this._depthOfFieldPostProcess.onApply = function (effect) {
  55618. effect.setTexture("depthSampler", _this._depthTexture);
  55619. effect.setTexture("grainSampler", _this._grainTexture);
  55620. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  55621. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  55622. effect.setFloat('grain_amount', _this._grainAmount);
  55623. effect.setBool('blur_noise', _this._blurNoise);
  55624. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  55625. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  55626. effect.setFloat('distortion', _this._distortion);
  55627. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  55628. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  55629. effect.setFloat('aperture', _this._dofAperture);
  55630. effect.setFloat('darken', _this._dofDarken);
  55631. effect.setFloat('edge_blur', _this._edgeBlur);
  55632. effect.setBool('highlights', (_this._highlightsGain !== -1));
  55633. effect.setFloat('near', _this._scene.activeCamera.minZ);
  55634. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  55635. };
  55636. };
  55637. // creates a black and white random noise texture, 512x512
  55638. LensRenderingPipeline.prototype._createGrainTexture = function () {
  55639. var size = 512;
  55640. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  55641. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  55642. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  55643. var context = this._grainTexture.getContext();
  55644. var rand = function (min, max) {
  55645. return Math.random() * (max - min) + min;
  55646. };
  55647. var value;
  55648. for (var x = 0; x < size; x++) {
  55649. for (var y = 0; y < size; y++) {
  55650. value = Math.floor(rand(0.42, 0.58) * 255);
  55651. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  55652. context.fillRect(x, y, 1, 1);
  55653. }
  55654. }
  55655. this._grainTexture.update(false);
  55656. };
  55657. return LensRenderingPipeline;
  55658. })(BABYLON.PostProcessRenderPipeline);
  55659. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  55660. })(BABYLON || (BABYLON = {}));
  55661. //
  55662. // This post-process allows the modification of rendered colors by using
  55663. // a 'look-up table' (LUT). This effect is also called Color Grading.
  55664. //
  55665. // The object needs to be provided an url to a texture containing the color
  55666. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  55667. // Use an image editing software to tweak the LUT to match your needs.
  55668. //
  55669. // For an example of a color LUT, see here:
  55670. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  55671. // For explanations on color grading, see here:
  55672. // http://udn.epicgames.com/Three/ColorGrading.html
  55673. //
  55674. var BABYLON;
  55675. (function (BABYLON) {
  55676. var ColorCorrectionPostProcess = (function (_super) {
  55677. __extends(ColorCorrectionPostProcess, _super);
  55678. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  55679. var _this = this;
  55680. _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable);
  55681. this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  55682. this._colorTableTexture.anisotropicFilteringLevel = 1;
  55683. this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  55684. this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  55685. this.onApply = function (effect) {
  55686. effect.setTexture("colorTable", _this._colorTableTexture);
  55687. };
  55688. }
  55689. return ColorCorrectionPostProcess;
  55690. })(BABYLON.PostProcess);
  55691. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  55692. })(BABYLON || (BABYLON = {}));
  55693. var BABYLON;
  55694. (function (BABYLON) {
  55695. var AnaglyphFreeCamera = (function (_super) {
  55696. __extends(AnaglyphFreeCamera, _super);
  55697. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  55698. _super.call(this, name, position, scene);
  55699. this.interaxialDistance = interaxialDistance;
  55700. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  55701. }
  55702. AnaglyphFreeCamera.prototype.getTypeName = function () {
  55703. return "AnaglyphFreeCamera";
  55704. };
  55705. return AnaglyphFreeCamera;
  55706. })(BABYLON.FreeCamera);
  55707. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  55708. var AnaglyphArcRotateCamera = (function (_super) {
  55709. __extends(AnaglyphArcRotateCamera, _super);
  55710. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  55711. _super.call(this, name, alpha, beta, radius, target, scene);
  55712. this.interaxialDistance = interaxialDistance;
  55713. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  55714. }
  55715. AnaglyphArcRotateCamera.prototype.getTypeName = function () {
  55716. return "AnaglyphArcRotateCamera";
  55717. };
  55718. return AnaglyphArcRotateCamera;
  55719. })(BABYLON.ArcRotateCamera);
  55720. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  55721. var AnaglyphGamepadCamera = (function (_super) {
  55722. __extends(AnaglyphGamepadCamera, _super);
  55723. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  55724. _super.call(this, name, position, scene);
  55725. this.interaxialDistance = interaxialDistance;
  55726. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  55727. }
  55728. AnaglyphGamepadCamera.prototype.getTypeName = function () {
  55729. return "AnaglyphGamepadCamera";
  55730. };
  55731. return AnaglyphGamepadCamera;
  55732. })(BABYLON.GamepadCamera);
  55733. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  55734. var AnaglyphUniversalCamera = (function (_super) {
  55735. __extends(AnaglyphUniversalCamera, _super);
  55736. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  55737. _super.call(this, name, position, scene);
  55738. this.interaxialDistance = interaxialDistance;
  55739. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  55740. }
  55741. AnaglyphUniversalCamera.prototype.getTypeName = function () {
  55742. return "AnaglyphUniversalCamera";
  55743. };
  55744. return AnaglyphUniversalCamera;
  55745. })(BABYLON.UniversalCamera);
  55746. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  55747. var StereoscopicFreeCamera = (function (_super) {
  55748. __extends(StereoscopicFreeCamera, _super);
  55749. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  55750. _super.call(this, name, position, scene);
  55751. this.interaxialDistance = interaxialDistance;
  55752. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  55753. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  55754. }
  55755. StereoscopicFreeCamera.prototype.getTypeName = function () {
  55756. return "StereoscopicFreeCamera";
  55757. };
  55758. return StereoscopicFreeCamera;
  55759. })(BABYLON.FreeCamera);
  55760. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  55761. var StereoscopicArcRotateCamera = (function (_super) {
  55762. __extends(StereoscopicArcRotateCamera, _super);
  55763. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  55764. _super.call(this, name, alpha, beta, radius, target, scene);
  55765. this.interaxialDistance = interaxialDistance;
  55766. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  55767. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  55768. }
  55769. StereoscopicArcRotateCamera.prototype.getTypeName = function () {
  55770. return "StereoscopicArcRotateCamera";
  55771. };
  55772. return StereoscopicArcRotateCamera;
  55773. })(BABYLON.ArcRotateCamera);
  55774. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  55775. var StereoscopicGamepadCamera = (function (_super) {
  55776. __extends(StereoscopicGamepadCamera, _super);
  55777. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  55778. _super.call(this, name, position, scene);
  55779. this.interaxialDistance = interaxialDistance;
  55780. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  55781. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  55782. }
  55783. StereoscopicGamepadCamera.prototype.getTypeName = function () {
  55784. return "StereoscopicGamepadCamera";
  55785. };
  55786. return StereoscopicGamepadCamera;
  55787. })(BABYLON.GamepadCamera);
  55788. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  55789. var StereoscopicUniversalCamera = (function (_super) {
  55790. __extends(StereoscopicUniversalCamera, _super);
  55791. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  55792. _super.call(this, name, position, scene);
  55793. this.interaxialDistance = interaxialDistance;
  55794. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  55795. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  55796. }
  55797. StereoscopicUniversalCamera.prototype.getTypeName = function () {
  55798. return "StereoscopicUniversalCamera";
  55799. };
  55800. return StereoscopicUniversalCamera;
  55801. })(BABYLON.UniversalCamera);
  55802. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  55803. })(BABYLON || (BABYLON = {}));
  55804. var BABYLON;
  55805. (function (BABYLON) {
  55806. var HDRRenderingPipeline = (function (_super) {
  55807. __extends(HDRRenderingPipeline, _super);
  55808. /**
  55809. * @constructor
  55810. * @param {string} name - The rendering pipeline name
  55811. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  55812. * @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)
  55813. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  55814. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  55815. */
  55816. function HDRRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  55817. var _this = this;
  55818. if (originalPostProcess === void 0) { originalPostProcess = null; }
  55819. _super.call(this, scene.getEngine(), name);
  55820. /**
  55821. * Public members
  55822. */
  55823. // Gaussian Blur
  55824. /**
  55825. * Gaussian blur coefficient
  55826. * @type {number}
  55827. */
  55828. this.gaussCoeff = 0.3;
  55829. /**
  55830. * Gaussian blur mean
  55831. * @type {number}
  55832. */
  55833. this.gaussMean = 1.0;
  55834. /**
  55835. * Gaussian blur standard deviation
  55836. * @type {number}
  55837. */
  55838. this.gaussStandDev = 0.8;
  55839. /**
  55840. * Gaussian blur multiplier. Multiplies the blur effect
  55841. * @type {number}
  55842. */
  55843. this.gaussMultiplier = 4.0;
  55844. // HDR
  55845. /**
  55846. * Exposure, controls the overall intensity of the pipeline
  55847. * @type {number}
  55848. */
  55849. this.exposure = 1.0;
  55850. /**
  55851. * Minimum luminance that the post-process can output. Luminance is >= 0
  55852. * @type {number}
  55853. */
  55854. this.minimumLuminance = 1.0;
  55855. /**
  55856. * Maximum luminance that the post-process can output. Must be suprerior to minimumLuminance
  55857. * @type {number}
  55858. */
  55859. this.maximumLuminance = 1e20;
  55860. /**
  55861. * Increase rate for luminance: eye adaptation speed to dark
  55862. * @type {number}
  55863. */
  55864. this.luminanceIncreaserate = 0.5;
  55865. /**
  55866. * Decrease rate for luminance: eye adaptation speed to bright
  55867. * @type {number}
  55868. */
  55869. this.luminanceDecreaseRate = 0.5;
  55870. // Bright pass
  55871. /**
  55872. * Minimum luminance needed to compute HDR
  55873. * @type {number}
  55874. */
  55875. this.brightThreshold = 0.8;
  55876. this._needUpdate = true;
  55877. this._scene = scene;
  55878. // Bright pass
  55879. this._createBrightPassPostProcess(scene, ratio);
  55880. // Down sample X4
  55881. this._createDownSampleX4PostProcess(scene, ratio);
  55882. // Create gaussian blur post-processes
  55883. this._createGaussianBlurPostProcess(scene, ratio);
  55884. // Texture adder
  55885. this._createTextureAdderPostProcess(scene, ratio);
  55886. // Luminance generator
  55887. this._createLuminanceGeneratorPostProcess(scene);
  55888. // HDR
  55889. this._createHDRPostProcess(scene, ratio);
  55890. // Pass postprocess
  55891. if (originalPostProcess === null) {
  55892. this._originalPostProcess = new BABYLON.PassPostProcess("hdr", ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  55893. }
  55894. else {
  55895. this._originalPostProcess = originalPostProcess;
  55896. }
  55897. // Configure pipeline
  55898. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this._originalPostProcess; }, true));
  55899. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this._brightPassPostProcess; }, true));
  55900. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this._downSampleX4PostProcess; }, true));
  55901. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurH", function () { return _this._guassianBlurHPostProcess; }, true));
  55902. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurV", function () { return _this._guassianBlurVPostProcess; }, true));
  55903. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this._textureAdderPostProcess; }, true));
  55904. var addDownSamplerPostProcess = function (id) {
  55905. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampler" + id, function () { return _this._downSamplePostProcesses[id]; }, true));
  55906. };
  55907. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  55908. addDownSamplerPostProcess(i);
  55909. }
  55910. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this._hdrPostProcess; }, true));
  55911. // Finish
  55912. scene.postProcessRenderPipelineManager.addPipeline(this);
  55913. if (cameras !== null) {
  55914. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  55915. }
  55916. this.update();
  55917. }
  55918. /**
  55919. * Tells the pipeline to update its post-processes
  55920. */
  55921. HDRRenderingPipeline.prototype.update = function () {
  55922. this._needUpdate = true;
  55923. };
  55924. /**
  55925. * Returns the current calculated luminance
  55926. */
  55927. HDRRenderingPipeline.prototype.getCurrentLuminance = function () {
  55928. return this._hdrCurrentLuminance;
  55929. };
  55930. /**
  55931. * Returns the currently drawn luminance
  55932. */
  55933. HDRRenderingPipeline.prototype.getOutputLuminance = function () {
  55934. return this._hdrOutputLuminance;
  55935. };
  55936. /**
  55937. * Releases the rendering pipeline and its internal effects. Detaches pipeline from cameras
  55938. */
  55939. HDRRenderingPipeline.prototype.dispose = function () {
  55940. this._originalPostProcess = undefined;
  55941. this._brightPassPostProcess = undefined;
  55942. this._downSampleX4PostProcess = undefined;
  55943. this._guassianBlurHPostProcess = undefined;
  55944. this._guassianBlurVPostProcess = undefined;
  55945. this._textureAdderPostProcess = undefined;
  55946. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  55947. this._downSamplePostProcesses[i] = undefined;
  55948. }
  55949. this._hdrPostProcess = undefined;
  55950. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  55951. };
  55952. /**
  55953. * Creates the HDR post-process and computes the luminance adaptation
  55954. */
  55955. HDRRenderingPipeline.prototype._createHDRPostProcess = function (scene, ratio) {
  55956. var _this = this;
  55957. var hdrLastLuminance = 0.0;
  55958. this._hdrOutputLuminance = -1.0;
  55959. this._hdrCurrentLuminance = 1.0;
  55960. this._hdrPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["exposure", "avgLuminance"], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define HDR");
  55961. this._hdrPostProcess.onApply = function (effect) {
  55962. if (_this._hdrOutputLuminance < 0.0) {
  55963. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  55964. }
  55965. else {
  55966. var dt = (hdrLastLuminance - (hdrLastLuminance + scene.getEngine().getDeltaTime())) / 1000.0;
  55967. if (_this._hdrCurrentLuminance < _this._hdrOutputLuminance + _this.luminanceDecreaseRate * dt) {
  55968. _this._hdrOutputLuminance += _this.luminanceDecreaseRate * dt;
  55969. }
  55970. else if (_this._hdrCurrentLuminance > _this._hdrOutputLuminance - _this.luminanceIncreaserate * dt) {
  55971. _this._hdrOutputLuminance -= _this.luminanceIncreaserate * dt;
  55972. }
  55973. else {
  55974. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  55975. }
  55976. }
  55977. _this._hdrOutputLuminance = BABYLON.MathTools.Clamp(_this._hdrOutputLuminance, _this.minimumLuminance, _this.maximumLuminance);
  55978. hdrLastLuminance += scene.getEngine().getDeltaTime();
  55979. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  55980. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  55981. effect.setFloat("exposure", _this.exposure);
  55982. effect.setFloat("avgLuminance", _this._hdrOutputLuminance);
  55983. _this._needUpdate = false;
  55984. };
  55985. };
  55986. /**
  55987. * Texture Adder post-process
  55988. */
  55989. HDRRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  55990. var _this = this;
  55991. this._textureAdderPostProcess = new BABYLON.PostProcess("hdr", "hdr", [], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define TEXTURE_ADDER");
  55992. this._textureAdderPostProcess.onApply = function (effect) {
  55993. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  55994. };
  55995. };
  55996. /**
  55997. * Down sample X4 post-process
  55998. */
  55999. HDRRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  56000. var _this = this;
  56001. var downSampleX4Offsets = new Array(32);
  56002. this._downSampleX4PostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets"], [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define DOWN_SAMPLE_X4");
  56003. this._downSampleX4PostProcess.onApply = function (effect) {
  56004. if (_this._needUpdate) {
  56005. var id = 0;
  56006. for (var i = -2; i < 2; i++) {
  56007. for (var j = -2; j < 2; j++) {
  56008. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this._downSampleX4PostProcess.width);
  56009. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this._downSampleX4PostProcess.height);
  56010. id += 2;
  56011. }
  56012. }
  56013. }
  56014. effect.setArray2("dsOffsets", downSampleX4Offsets);
  56015. };
  56016. };
  56017. /**
  56018. * Bright pass post-process
  56019. */
  56020. HDRRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  56021. var _this = this;
  56022. var brightOffsets = new Array(8);
  56023. var brightPassCallback = function (effect) {
  56024. if (_this._needUpdate) {
  56025. var sU = (1.0 / _this._brightPassPostProcess.width);
  56026. var sV = (1.0 / _this._brightPassPostProcess.height);
  56027. brightOffsets[0] = -0.5 * sU;
  56028. brightOffsets[1] = 0.5 * sV;
  56029. brightOffsets[2] = 0.5 * sU;
  56030. brightOffsets[3] = 0.5 * sV;
  56031. brightOffsets[4] = -0.5 * sU;
  56032. brightOffsets[5] = -0.5 * sV;
  56033. brightOffsets[6] = 0.5 * sU;
  56034. brightOffsets[7] = -0.5 * sV;
  56035. }
  56036. effect.setArray2("dsOffsets", brightOffsets);
  56037. effect.setFloat("brightThreshold", _this.brightThreshold);
  56038. };
  56039. this._brightPassPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "brightThreshold"], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define BRIGHT_PASS");
  56040. this._brightPassPostProcess.onApply = brightPassCallback;
  56041. };
  56042. /**
  56043. * Luminance generator. Creates the luminance post-process and down sample post-processes
  56044. */
  56045. HDRRenderingPipeline.prototype._createLuminanceGeneratorPostProcess = function (scene) {
  56046. var _this = this;
  56047. var lumSteps = HDRRenderingPipeline.LUM_STEPS;
  56048. var luminanceOffsets = new Array(8);
  56049. var downSampleOffsets = new Array(18);
  56050. var halfDestPixelSize;
  56051. this._downSamplePostProcesses = new Array(lumSteps);
  56052. // Utils for luminance
  56053. var luminanceUpdateSourceOffsets = function (width, height) {
  56054. var sU = (1.0 / width);
  56055. var sV = (1.0 / height);
  56056. luminanceOffsets[0] = -0.5 * sU;
  56057. luminanceOffsets[1] = 0.5 * sV;
  56058. luminanceOffsets[2] = 0.5 * sU;
  56059. luminanceOffsets[3] = 0.5 * sV;
  56060. luminanceOffsets[4] = -0.5 * sU;
  56061. luminanceOffsets[5] = -0.5 * sV;
  56062. luminanceOffsets[6] = 0.5 * sU;
  56063. luminanceOffsets[7] = -0.5 * sV;
  56064. };
  56065. var luminanceUpdateDestOffsets = function (width, height) {
  56066. var id = 0;
  56067. for (var x = -1; x < 2; x++) {
  56068. for (var y = -1; y < 2; y++) {
  56069. downSampleOffsets[id] = (x) / width;
  56070. downSampleOffsets[id + 1] = (y) / height;
  56071. id += 2;
  56072. }
  56073. }
  56074. };
  56075. // Luminance callback
  56076. var luminanceCallback = function (effect) {
  56077. if (_this._needUpdate) {
  56078. luminanceUpdateSourceOffsets(_this._textureAdderPostProcess.width, _this._textureAdderPostProcess.height);
  56079. }
  56080. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  56081. effect.setArray2("lumOffsets", luminanceOffsets);
  56082. };
  56083. // Down sample callbacks
  56084. var downSampleCallback = function (indice) {
  56085. var i = indice;
  56086. return function (effect) {
  56087. luminanceUpdateSourceOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  56088. luminanceUpdateDestOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  56089. halfDestPixelSize = 0.5 / _this._downSamplePostProcesses[i].width;
  56090. effect.setTextureFromPostProcess("textureSampler", _this._downSamplePostProcesses[i + 1]);
  56091. effect.setFloat("halfDestPixelSize", halfDestPixelSize);
  56092. effect.setArray2("dsOffsets", downSampleOffsets);
  56093. };
  56094. };
  56095. var downSampleAfterRenderCallback = function (effect) {
  56096. // Unpack result
  56097. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  56098. 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);
  56099. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  56100. };
  56101. // Create luminance post-process
  56102. var ratio = { width: Math.pow(3, lumSteps - 1), height: Math.pow(3, lumSteps - 1) };
  56103. 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);
  56104. this._downSamplePostProcesses[lumSteps - 1].onApply = luminanceCallback;
  56105. // Create down sample post-processes
  56106. for (var i = lumSteps - 2; i >= 0; i--) {
  56107. var length = Math.pow(3, i);
  56108. ratio = { width: length, height: length };
  56109. var defines = "#define DOWN_SAMPLE\n";
  56110. if (i === 0) {
  56111. defines += "#define FINAL_DOWN_SAMPLE\n"; // To pack the result
  56112. }
  56113. this._downSamplePostProcesses[i] = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "halfDestPixelSize"], [], ratio, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, scene.getEngine(), false, defines, BABYLON.Engine.TEXTURETYPE_FLOAT);
  56114. this._downSamplePostProcesses[i].onApply = downSampleCallback(i);
  56115. if (i === 0) {
  56116. this._downSamplePostProcesses[i].onAfterRender = downSampleAfterRenderCallback;
  56117. }
  56118. }
  56119. };
  56120. /**
  56121. * Gaussian blur post-processes. Horizontal and Vertical
  56122. */
  56123. HDRRenderingPipeline.prototype._createGaussianBlurPostProcess = function (scene, ratio) {
  56124. var _this = this;
  56125. var blurOffsetsW = new Array(9);
  56126. var blurOffsetsH = new Array(9);
  56127. var blurWeights = new Array(9);
  56128. var uniforms = ["blurOffsets", "blurWeights", "multiplier"];
  56129. // Utils for gaussian blur
  56130. var calculateBlurOffsets = function (height) {
  56131. var lastOutputDimensions = {
  56132. width: scene.getEngine().getRenderWidth(),
  56133. height: scene.getEngine().getRenderHeight()
  56134. };
  56135. for (var i = 0; i < 9; i++) {
  56136. var value = (i - 4.0) * (1.0 / (height === true ? lastOutputDimensions.height : lastOutputDimensions.width));
  56137. if (height) {
  56138. blurOffsetsH[i] = value;
  56139. }
  56140. else {
  56141. blurOffsetsW[i] = value;
  56142. }
  56143. }
  56144. };
  56145. var calculateWeights = function () {
  56146. var x = 0.0;
  56147. for (var i = 0; i < 9; i++) {
  56148. x = (i - 4.0) / 4.0;
  56149. 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));
  56150. }
  56151. };
  56152. // Callback
  56153. var gaussianBlurCallback = function (height) {
  56154. return function (effect) {
  56155. if (_this._needUpdate) {
  56156. calculateWeights();
  56157. calculateBlurOffsets(height);
  56158. }
  56159. effect.setArray("blurOffsets", height ? blurOffsetsH : blurOffsetsW);
  56160. effect.setArray("blurWeights", blurWeights);
  56161. effect.setFloat("multiplier", _this.gaussMultiplier);
  56162. };
  56163. };
  56164. // Create horizontal gaussian blur post-processes
  56165. this._guassianBlurHPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_H");
  56166. this._guassianBlurHPostProcess.onApply = gaussianBlurCallback(false);
  56167. // Create vertical gaussian blur post-process
  56168. this._guassianBlurVPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_V");
  56169. this._guassianBlurVPostProcess.onApply = gaussianBlurCallback(true);
  56170. };
  56171. // Luminance generator
  56172. HDRRenderingPipeline.LUM_STEPS = 6;
  56173. return HDRRenderingPipeline;
  56174. })(BABYLON.PostProcessRenderPipeline);
  56175. BABYLON.HDRRenderingPipeline = HDRRenderingPipeline;
  56176. })(BABYLON || (BABYLON = {}));
  56177. var BABYLON;
  56178. (function (BABYLON) {
  56179. var FaceAdjacencies = (function () {
  56180. function FaceAdjacencies() {
  56181. this.edges = new Array();
  56182. this.edgesConnectedCount = 0;
  56183. }
  56184. return FaceAdjacencies;
  56185. })();
  56186. var EdgesRenderer = (function () {
  56187. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  56188. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  56189. if (epsilon === void 0) { epsilon = 0.95; }
  56190. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  56191. this.edgesWidthScalerForOrthographic = 1000.0;
  56192. this.edgesWidthScalerForPerspective = 50.0;
  56193. this._linesPositions = new Array();
  56194. this._linesNormals = new Array();
  56195. this._linesIndices = new Array();
  56196. this._buffers = {};
  56197. this._checkVerticesInsteadOfIndices = false;
  56198. this._source = source;
  56199. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  56200. this._epsilon = epsilon;
  56201. this._prepareRessources();
  56202. this._generateEdgesLines();
  56203. }
  56204. EdgesRenderer.prototype._prepareRessources = function () {
  56205. if (this._lineShader) {
  56206. return;
  56207. }
  56208. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  56209. attributes: ["position", "normal"],
  56210. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  56211. });
  56212. this._lineShader.disableDepthWrite = true;
  56213. this._lineShader.backFaceCulling = false;
  56214. };
  56215. EdgesRenderer.prototype.dispose = function () {
  56216. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  56217. if (buffer) {
  56218. buffer.dispose();
  56219. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  56220. }
  56221. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  56222. if (buffer) {
  56223. buffer.dispose();
  56224. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  56225. }
  56226. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  56227. this._lineShader.dispose();
  56228. };
  56229. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  56230. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  56231. return 0;
  56232. }
  56233. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  56234. return 1;
  56235. }
  56236. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  56237. return 2;
  56238. }
  56239. return -1;
  56240. };
  56241. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  56242. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  56243. return 0;
  56244. }
  56245. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  56246. return 1;
  56247. }
  56248. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  56249. return 2;
  56250. }
  56251. return -1;
  56252. };
  56253. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  56254. var needToCreateLine;
  56255. if (edge === undefined) {
  56256. needToCreateLine = true;
  56257. }
  56258. else {
  56259. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  56260. needToCreateLine = dotProduct < this._epsilon;
  56261. }
  56262. if (needToCreateLine) {
  56263. var offset = this._linesPositions.length / 3;
  56264. var normal = p0.subtract(p1);
  56265. normal.normalize();
  56266. // Positions
  56267. this._linesPositions.push(p0.x);
  56268. this._linesPositions.push(p0.y);
  56269. this._linesPositions.push(p0.z);
  56270. this._linesPositions.push(p0.x);
  56271. this._linesPositions.push(p0.y);
  56272. this._linesPositions.push(p0.z);
  56273. this._linesPositions.push(p1.x);
  56274. this._linesPositions.push(p1.y);
  56275. this._linesPositions.push(p1.z);
  56276. this._linesPositions.push(p1.x);
  56277. this._linesPositions.push(p1.y);
  56278. this._linesPositions.push(p1.z);
  56279. // Normals
  56280. this._linesNormals.push(p1.x);
  56281. this._linesNormals.push(p1.y);
  56282. this._linesNormals.push(p1.z);
  56283. this._linesNormals.push(-1);
  56284. this._linesNormals.push(p1.x);
  56285. this._linesNormals.push(p1.y);
  56286. this._linesNormals.push(p1.z);
  56287. this._linesNormals.push(1);
  56288. this._linesNormals.push(p0.x);
  56289. this._linesNormals.push(p0.y);
  56290. this._linesNormals.push(p0.z);
  56291. this._linesNormals.push(-1);
  56292. this._linesNormals.push(p0.x);
  56293. this._linesNormals.push(p0.y);
  56294. this._linesNormals.push(p0.z);
  56295. this._linesNormals.push(1);
  56296. // Indices
  56297. this._linesIndices.push(offset);
  56298. this._linesIndices.push(offset + 1);
  56299. this._linesIndices.push(offset + 2);
  56300. this._linesIndices.push(offset);
  56301. this._linesIndices.push(offset + 2);
  56302. this._linesIndices.push(offset + 3);
  56303. }
  56304. };
  56305. EdgesRenderer.prototype._generateEdgesLines = function () {
  56306. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  56307. var indices = this._source.getIndices();
  56308. // First let's find adjacencies
  56309. var adjacencies = new Array();
  56310. var faceNormals = new Array();
  56311. var index;
  56312. var faceAdjacencies;
  56313. // Prepare faces
  56314. for (index = 0; index < indices.length; index += 3) {
  56315. faceAdjacencies = new FaceAdjacencies();
  56316. var p0Index = indices[index];
  56317. var p1Index = indices[index + 1];
  56318. var p2Index = indices[index + 2];
  56319. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  56320. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  56321. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  56322. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  56323. faceNormal.normalize();
  56324. faceNormals.push(faceNormal);
  56325. adjacencies.push(faceAdjacencies);
  56326. }
  56327. // Scan
  56328. for (index = 0; index < adjacencies.length; index++) {
  56329. faceAdjacencies = adjacencies[index];
  56330. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  56331. var otherFaceAdjacencies = adjacencies[otherIndex];
  56332. if (faceAdjacencies.edgesConnectedCount === 3) {
  56333. break;
  56334. }
  56335. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  56336. continue;
  56337. }
  56338. var otherP0 = indices[otherIndex * 3];
  56339. var otherP1 = indices[otherIndex * 3 + 1];
  56340. var otherP2 = indices[otherIndex * 3 + 2];
  56341. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  56342. var otherEdgeIndex;
  56343. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  56344. continue;
  56345. }
  56346. switch (edgeIndex) {
  56347. case 0:
  56348. if (this._checkVerticesInsteadOfIndices) {
  56349. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  56350. }
  56351. else {
  56352. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  56353. }
  56354. break;
  56355. case 1:
  56356. if (this._checkVerticesInsteadOfIndices) {
  56357. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  56358. }
  56359. else {
  56360. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  56361. }
  56362. break;
  56363. case 2:
  56364. if (this._checkVerticesInsteadOfIndices) {
  56365. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  56366. }
  56367. else {
  56368. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  56369. }
  56370. break;
  56371. }
  56372. if (otherEdgeIndex === -1) {
  56373. continue;
  56374. }
  56375. faceAdjacencies.edges[edgeIndex] = otherIndex;
  56376. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  56377. faceAdjacencies.edgesConnectedCount++;
  56378. otherFaceAdjacencies.edgesConnectedCount++;
  56379. if (faceAdjacencies.edgesConnectedCount === 3) {
  56380. break;
  56381. }
  56382. }
  56383. }
  56384. }
  56385. // Create lines
  56386. for (index = 0; index < adjacencies.length; index++) {
  56387. // 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
  56388. var current = adjacencies[index];
  56389. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  56390. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  56391. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  56392. }
  56393. // Merge into a single mesh
  56394. var engine = this._source.getScene().getEngine();
  56395. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  56396. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  56397. this._ib = engine.createIndexBuffer(this._linesIndices);
  56398. this._indicesCount = this._linesIndices.length;
  56399. };
  56400. EdgesRenderer.prototype.render = function () {
  56401. if (!this._lineShader.isReady()) {
  56402. return;
  56403. }
  56404. var scene = this._source.getScene();
  56405. var engine = scene.getEngine();
  56406. this._lineShader._preBind();
  56407. // VBOs
  56408. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  56409. scene.resetCachedMaterial();
  56410. this._lineShader.setColor4("color", this._source.edgesColor);
  56411. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  56412. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  56413. }
  56414. else {
  56415. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  56416. }
  56417. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  56418. this._lineShader.bind(this._source.getWorldMatrix());
  56419. // Draw order
  56420. engine.draw(true, 0, this._indicesCount);
  56421. this._lineShader.unbind();
  56422. engine.setDepthWrite(true);
  56423. };
  56424. return EdgesRenderer;
  56425. })();
  56426. BABYLON.EdgesRenderer = EdgesRenderer;
  56427. })(BABYLON || (BABYLON = {}));
  56428. var BABYLON;
  56429. (function (BABYLON) {
  56430. (function (TonemappingOperator) {
  56431. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  56432. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  56433. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  56434. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  56435. })(BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  56436. var TonemappingOperator = BABYLON.TonemappingOperator;
  56437. ;
  56438. var TonemapPostProcess = (function (_super) {
  56439. __extends(TonemapPostProcess, _super);
  56440. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  56441. var _this = this;
  56442. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  56443. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  56444. _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, defines, textureFormat);
  56445. this._operator = _operator;
  56446. this.exposureAdjustment = exposureAdjustment;
  56447. var defines = "#define ";
  56448. if (this._operator === TonemappingOperator.Hable)
  56449. defines += "HABLE_TONEMAPPING";
  56450. else if (this._operator === TonemappingOperator.Reinhard)
  56451. defines += "REINHARD_TONEMAPPING";
  56452. else if (this._operator === TonemappingOperator.HejiDawson)
  56453. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  56454. else if (this._operator === TonemappingOperator.Photographic)
  56455. defines += "PHOTOGRAPHIC_TONEMAPPING";
  56456. //sadly a second call to create the effect.
  56457. this.updateEffect(defines);
  56458. this.onApply = function (effect) {
  56459. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  56460. };
  56461. }
  56462. return TonemapPostProcess;
  56463. })(BABYLON.PostProcess);
  56464. BABYLON.TonemapPostProcess = TonemapPostProcess;
  56465. })(BABYLON || (BABYLON = {}));
  56466. var BABYLON;
  56467. (function (BABYLON) {
  56468. var ReflectionProbe = (function () {
  56469. function ReflectionProbe(name, size, scene, generateMipMaps) {
  56470. var _this = this;
  56471. if (generateMipMaps === void 0) { generateMipMaps = true; }
  56472. this.name = name;
  56473. this._viewMatrix = BABYLON.Matrix.Identity();
  56474. this._target = BABYLON.Vector3.Zero();
  56475. this._add = BABYLON.Vector3.Zero();
  56476. this.invertYAxis = false;
  56477. this.position = BABYLON.Vector3.Zero();
  56478. this._scene = scene;
  56479. this._scene.reflectionProbes.push(this);
  56480. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  56481. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  56482. switch (faceIndex) {
  56483. case 0:
  56484. _this._add.copyFromFloats(1, 0, 0);
  56485. break;
  56486. case 1:
  56487. _this._add.copyFromFloats(-1, 0, 0);
  56488. break;
  56489. case 2:
  56490. _this._add.copyFromFloats(0, _this.invertYAxis ? 1 : -1, 0);
  56491. break;
  56492. case 3:
  56493. _this._add.copyFromFloats(0, _this.invertYAxis ? -1 : 1, 0);
  56494. break;
  56495. case 4:
  56496. _this._add.copyFromFloats(0, 0, 1);
  56497. break;
  56498. case 5:
  56499. _this._add.copyFromFloats(0, 0, -1);
  56500. break;
  56501. }
  56502. if (_this._attachedMesh) {
  56503. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  56504. }
  56505. _this.position.addToRef(_this._add, _this._target);
  56506. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  56507. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  56508. });
  56509. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  56510. scene.updateTransformMatrix(true);
  56511. });
  56512. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  56513. }
  56514. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  56515. get: function () {
  56516. return this._renderTargetTexture.refreshRate;
  56517. },
  56518. set: function (value) {
  56519. this._renderTargetTexture.refreshRate = value;
  56520. },
  56521. enumerable: true,
  56522. configurable: true
  56523. });
  56524. ReflectionProbe.prototype.getScene = function () {
  56525. return this._scene;
  56526. };
  56527. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  56528. get: function () {
  56529. return this._renderTargetTexture;
  56530. },
  56531. enumerable: true,
  56532. configurable: true
  56533. });
  56534. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  56535. get: function () {
  56536. return this._renderTargetTexture.renderList;
  56537. },
  56538. enumerable: true,
  56539. configurable: true
  56540. });
  56541. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  56542. this._attachedMesh = mesh;
  56543. };
  56544. ReflectionProbe.prototype.dispose = function () {
  56545. var index = this._scene.reflectionProbes.indexOf(this);
  56546. if (index !== -1) {
  56547. // Remove from the scene if found
  56548. this._scene.reflectionProbes.splice(index, 1);
  56549. }
  56550. if (this._renderTargetTexture) {
  56551. this._renderTargetTexture.dispose();
  56552. this._renderTargetTexture = null;
  56553. }
  56554. };
  56555. return ReflectionProbe;
  56556. })();
  56557. BABYLON.ReflectionProbe = ReflectionProbe;
  56558. })(BABYLON || (BABYLON = {}));
  56559. var BABYLON;
  56560. (function (BABYLON) {
  56561. var SolidParticle = (function () {
  56562. function SolidParticle(particleIndex, positionIndex, model, shapeId, idxInShape) {
  56563. this.color = new BABYLON.Color4(1, 1, 1, 1); // color
  56564. this.position = BABYLON.Vector3.Zero(); // position
  56565. this.rotation = BABYLON.Vector3.Zero(); // rotation
  56566. this.scaling = new BABYLON.Vector3(1, 1, 1); // scaling
  56567. this.uvs = new BABYLON.Vector4(0, 0, 1, 1); // uvs
  56568. this.velocity = BABYLON.Vector3.Zero(); // velocity
  56569. this.alive = true; // alive
  56570. this.isVisible = true; // visibility
  56571. this.idx = particleIndex;
  56572. this._pos = positionIndex;
  56573. this._model = model;
  56574. this.shapeId = shapeId;
  56575. this.idxInShape = idxInShape;
  56576. }
  56577. Object.defineProperty(SolidParticle.prototype, "scale", {
  56578. //legacy support, changed scale to scaling
  56579. get: function () {
  56580. return this.scaling;
  56581. },
  56582. set: function (scale) {
  56583. this.scaling = scale;
  56584. },
  56585. enumerable: true,
  56586. configurable: true
  56587. });
  56588. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  56589. //legacy support, changed quaternion to rotationQuaternion
  56590. get: function () {
  56591. return this.rotationQuaternion;
  56592. },
  56593. set: function (q) {
  56594. this.rotationQuaternion = q;
  56595. },
  56596. enumerable: true,
  56597. configurable: true
  56598. });
  56599. return SolidParticle;
  56600. })();
  56601. BABYLON.SolidParticle = SolidParticle;
  56602. var ModelShape = (function () {
  56603. function ModelShape(id, shape, shapeUV, posFunction, vtxFunction) {
  56604. this.shapeID = id;
  56605. this._shape = shape;
  56606. this._shapeUV = shapeUV;
  56607. this._positionFunction = posFunction;
  56608. this._vertexFunction = vtxFunction;
  56609. }
  56610. return ModelShape;
  56611. })();
  56612. BABYLON.ModelShape = ModelShape;
  56613. })(BABYLON || (BABYLON = {}));
  56614. var BABYLON;
  56615. (function (BABYLON) {
  56616. /**
  56617. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  56618. */
  56619. var SolidParticleSystem = (function () {
  56620. /**
  56621. * Creates a SPS (Solid Particle System) object.
  56622. * `name` (String) is the SPS name, this will be the underlying mesh name.
  56623. * `scene` (Scene) is the scene in which the SPS is added.
  56624. * `updatable` (default true) : if the SPS must be updatable or immutable.
  56625. * `isPickable` (default false) : if the solid particles must be pickable.
  56626. */
  56627. function SolidParticleSystem(name, scene, options) {
  56628. // public members
  56629. /**
  56630. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  56631. * Example : var p = SPS.particles[i];
  56632. */
  56633. this.particles = new Array();
  56634. /**
  56635. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  56636. */
  56637. this.nbParticles = 0;
  56638. /**
  56639. * If the particles must ever face the camera (default false). Useful for planar particles.
  56640. */
  56641. this.billboard = false;
  56642. /**
  56643. * This a counter ofr your own usage. It's not set by any SPS functions.
  56644. */
  56645. this.counter = 0;
  56646. /**
  56647. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  56648. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  56649. */
  56650. this.vars = {};
  56651. this._positions = new Array();
  56652. this._indices = new Array();
  56653. this._normals = new Array();
  56654. this._colors = new Array();
  56655. this._uvs = new Array();
  56656. this._index = 0; // indices index
  56657. this._updatable = true;
  56658. this._pickable = false;
  56659. this._isVisibilityBoxLocked = false;
  56660. this._alwaysVisible = false;
  56661. this._shapeCounter = 0;
  56662. this._copy = new BABYLON.SolidParticle(null, null, null, null, null);
  56663. this._color = new BABYLON.Color4(0, 0, 0, 0);
  56664. this._computeParticleColor = true;
  56665. this._computeParticleTexture = true;
  56666. this._computeParticleRotation = true;
  56667. this._computeParticleVertex = false;
  56668. this._computeBoundingBox = false;
  56669. this._cam_axisZ = BABYLON.Vector3.Zero();
  56670. this._cam_axisY = BABYLON.Vector3.Zero();
  56671. this._cam_axisX = BABYLON.Vector3.Zero();
  56672. this._axisX = BABYLON.Axis.X;
  56673. this._axisY = BABYLON.Axis.Y;
  56674. this._axisZ = BABYLON.Axis.Z;
  56675. this._camDir = BABYLON.Vector3.Zero();
  56676. this._rotMatrix = new BABYLON.Matrix();
  56677. this._invertMatrix = new BABYLON.Matrix();
  56678. this._rotated = BABYLON.Vector3.Zero();
  56679. this._quaternion = new BABYLON.Quaternion();
  56680. this._vertex = BABYLON.Vector3.Zero();
  56681. this._normal = BABYLON.Vector3.Zero();
  56682. this._yaw = 0.0;
  56683. this._pitch = 0.0;
  56684. this._roll = 0.0;
  56685. this._halfroll = 0.0;
  56686. this._halfpitch = 0.0;
  56687. this._halfyaw = 0.0;
  56688. this._sinRoll = 0.0;
  56689. this._cosRoll = 0.0;
  56690. this._sinPitch = 0.0;
  56691. this._cosPitch = 0.0;
  56692. this._sinYaw = 0.0;
  56693. this._cosYaw = 0.0;
  56694. this._w = 0.0;
  56695. this._minimum = BABYLON.Tmp.Vector3[0];
  56696. this._maximum = BABYLON.Tmp.Vector3[1];
  56697. this.name = name;
  56698. this._scene = scene;
  56699. this._camera = scene.activeCamera;
  56700. this._pickable = options ? options.isPickable : false;
  56701. if (options && options.updatable) {
  56702. this._updatable = options.updatable;
  56703. }
  56704. else {
  56705. this._updatable = true;
  56706. }
  56707. if (this._pickable) {
  56708. this.pickedParticles = [];
  56709. }
  56710. }
  56711. /**
  56712. * Builds the SPS underlying mesh. Returns a standard Mesh.
  56713. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  56714. */
  56715. SolidParticleSystem.prototype.buildMesh = function () {
  56716. if (this.nbParticles === 0) {
  56717. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  56718. this.addShape(triangle, 1);
  56719. triangle.dispose();
  56720. }
  56721. this._positions32 = new Float32Array(this._positions);
  56722. this._uvs32 = new Float32Array(this._uvs);
  56723. this._colors32 = new Float32Array(this._colors);
  56724. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals);
  56725. this._normals32 = new Float32Array(this._normals);
  56726. this._fixedNormal32 = new Float32Array(this._normals);
  56727. var vertexData = new BABYLON.VertexData();
  56728. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  56729. vertexData.indices = this._indices;
  56730. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  56731. if (this._uvs32) {
  56732. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  56733. ;
  56734. }
  56735. if (this._colors32) {
  56736. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  56737. }
  56738. var mesh = new BABYLON.Mesh(this.name, this._scene);
  56739. vertexData.applyToMesh(mesh, this._updatable);
  56740. this.mesh = mesh;
  56741. this.mesh.isPickable = this._pickable;
  56742. // free memory
  56743. this._positions = null;
  56744. this._normals = null;
  56745. this._uvs = null;
  56746. this._colors = null;
  56747. if (!this._updatable) {
  56748. this.particles.length = 0;
  56749. }
  56750. return mesh;
  56751. };
  56752. /**
  56753. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  56754. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  56755. * Thus the particles generated from `digest()` have their property `position` set yet.
  56756. * `mesh` ( Mesh ) is the mesh to be digested
  56757. * `facetNb` (optional integer, default 1) is the number of mesh facets per particle, this parameter is overriden by the parameter `number` if any
  56758. * `delta` (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  56759. * `number` (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  56760. */
  56761. SolidParticleSystem.prototype.digest = function (mesh, options) {
  56762. var size = (options && options.facetNb) || 1;
  56763. var number = (options && options.number);
  56764. var delta = (options && options.delta) || 0;
  56765. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  56766. var meshInd = mesh.getIndices();
  56767. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  56768. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  56769. var f = 0; // facet counter
  56770. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  56771. // compute size from number
  56772. if (number) {
  56773. number = (number > totalFacets) ? totalFacets : number;
  56774. size = Math.round(totalFacets / number);
  56775. delta = 0;
  56776. }
  56777. else {
  56778. size = (size > totalFacets) ? totalFacets : size;
  56779. }
  56780. var facetPos = []; // submesh positions
  56781. var facetInd = []; // submesh indices
  56782. var facetUV = []; // submesh UV
  56783. var facetCol = []; // submesh colors
  56784. var barycenter = BABYLON.Tmp.Vector3[0];
  56785. var rand;
  56786. var sizeO = size;
  56787. while (f < totalFacets) {
  56788. size = sizeO + Math.floor((1 + delta) * Math.random());
  56789. if (f > totalFacets - size) {
  56790. size = totalFacets - f;
  56791. }
  56792. // reset temp arrays
  56793. facetPos.length = 0;
  56794. facetInd.length = 0;
  56795. facetUV.length = 0;
  56796. facetCol.length = 0;
  56797. // iterate over "size" facets
  56798. var fi = 0;
  56799. for (var j = f * 3; j < (f + size) * 3; j++) {
  56800. facetInd.push(fi);
  56801. var i = meshInd[j];
  56802. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  56803. if (meshUV) {
  56804. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  56805. }
  56806. if (meshCol) {
  56807. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  56808. }
  56809. fi++;
  56810. }
  56811. // create a model shape for each single particle
  56812. var idx = this.nbParticles;
  56813. var shape = this._posToShape(facetPos);
  56814. var shapeUV = this._uvsToShapeUV(facetUV);
  56815. // compute the barycenter of the shape
  56816. var v;
  56817. for (v = 0; v < shape.length; v++) {
  56818. barycenter.addInPlace(shape[v]);
  56819. }
  56820. barycenter.scaleInPlace(1 / shape.length);
  56821. // shift the shape from its barycenter to the origin
  56822. for (v = 0; v < shape.length; v++) {
  56823. shape[v].subtractInPlace(barycenter);
  56824. }
  56825. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, null, null);
  56826. // add the particle in the SPS
  56827. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, idx, 0, null);
  56828. this._addParticle(idx, this._positions.length, modelShape, this._shapeCounter, 0);
  56829. // initialize the particle position
  56830. this.particles[this.nbParticles].position.addInPlace(barycenter);
  56831. this._index += shape.length;
  56832. idx++;
  56833. this.nbParticles++;
  56834. this._shapeCounter++;
  56835. f += size;
  56836. }
  56837. return this;
  56838. };
  56839. //reset copy
  56840. SolidParticleSystem.prototype._resetCopy = function () {
  56841. this._copy.position.x = 0;
  56842. this._copy.position.y = 0;
  56843. this._copy.position.z = 0;
  56844. this._copy.rotation.x = 0;
  56845. this._copy.rotation.y = 0;
  56846. this._copy.rotation.z = 0;
  56847. this._copy.rotationQuaternion = null;
  56848. this._copy.scaling.x = 1;
  56849. this._copy.scaling.y = 1;
  56850. this._copy.scaling.z = 1;
  56851. this._copy.uvs.x = 0;
  56852. this._copy.uvs.y = 0;
  56853. this._copy.uvs.z = 1;
  56854. this._copy.uvs.w = 1;
  56855. this._copy.color = null;
  56856. };
  56857. // _meshBuilder : inserts the shape model in the global SPS mesh
  56858. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, idx, idxInShape, options) {
  56859. var i;
  56860. var u = 0;
  56861. var c = 0;
  56862. this._resetCopy();
  56863. if (options && options.positionFunction) {
  56864. options.positionFunction(this._copy, idx, idxInShape);
  56865. }
  56866. if (this._copy.rotationQuaternion) {
  56867. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  56868. }
  56869. else {
  56870. this._yaw = this._copy.rotation.y;
  56871. this._pitch = this._copy.rotation.x;
  56872. this._roll = this._copy.rotation.z;
  56873. this._quaternionRotationYPR();
  56874. }
  56875. this._quaternionToRotationMatrix();
  56876. for (i = 0; i < shape.length; i++) {
  56877. this._vertex.x = shape[i].x;
  56878. this._vertex.y = shape[i].y;
  56879. this._vertex.z = shape[i].z;
  56880. if (options && options.vertexFunction) {
  56881. options.vertexFunction(this._copy, this._vertex, i);
  56882. }
  56883. this._vertex.x *= this._copy.scaling.x;
  56884. this._vertex.y *= this._copy.scaling.y;
  56885. this._vertex.z *= this._copy.scaling.z;
  56886. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  56887. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  56888. if (meshUV) {
  56889. 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);
  56890. u += 2;
  56891. }
  56892. if (this._copy.color) {
  56893. this._color = this._copy.color;
  56894. }
  56895. else if (meshCol && meshCol[c] !== undefined) {
  56896. this._color.r = meshCol[c];
  56897. this._color.g = meshCol[c + 1];
  56898. this._color.b = meshCol[c + 2];
  56899. this._color.a = meshCol[c + 3];
  56900. }
  56901. else {
  56902. this._color.r = 1;
  56903. this._color.g = 1;
  56904. this._color.b = 1;
  56905. this._color.a = 1;
  56906. }
  56907. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  56908. c += 4;
  56909. }
  56910. for (i = 0; i < meshInd.length; i++) {
  56911. indices.push(p + meshInd[i]);
  56912. }
  56913. if (this._pickable) {
  56914. var nbfaces = meshInd.length / 3;
  56915. for (i = 0; i < nbfaces; i++) {
  56916. this.pickedParticles.push({ idx: idx, faceId: i });
  56917. }
  56918. }
  56919. };
  56920. // returns a shape array from positions array
  56921. SolidParticleSystem.prototype._posToShape = function (positions) {
  56922. var shape = [];
  56923. for (var i = 0; i < positions.length; i += 3) {
  56924. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  56925. }
  56926. return shape;
  56927. };
  56928. // returns a shapeUV array from a Vector4 uvs
  56929. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  56930. var shapeUV = [];
  56931. if (uvs) {
  56932. for (var i = 0; i < uvs.length; i++)
  56933. shapeUV.push(uvs[i]);
  56934. }
  56935. return shapeUV;
  56936. };
  56937. // adds a new particle object in the particles array
  56938. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, model, shapeId, idxInShape) {
  56939. this.particles.push(new BABYLON.SolidParticle(idx, idxpos, model, shapeId, idxInShape));
  56940. };
  56941. /**
  56942. * Adds some particles to the SPS from the model shape. Returns the shape id.
  56943. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  56944. * `mesh` is any Mesh object that will be used as a model for the solid particles.
  56945. * `nb` (positive integer) the number of particles to be created from this model
  56946. * `positionFunction` is an optional javascript function to called for each particle on SPS creation.
  56947. * `vertexFunction` is an optional javascript function to called for each vertex of each particle on SPS creation
  56948. */
  56949. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  56950. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  56951. var meshInd = mesh.getIndices();
  56952. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  56953. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  56954. var shape = this._posToShape(meshPos);
  56955. var shapeUV = this._uvsToShapeUV(meshUV);
  56956. var posfunc = options ? options.positionFunction : null;
  56957. var vtxfunc = options ? options.vertexFunction : null;
  56958. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, posfunc, vtxfunc);
  56959. // particles
  56960. var idx = this.nbParticles;
  56961. for (var i = 0; i < nb; i++) {
  56962. this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, idx, i, options);
  56963. if (this._updatable) {
  56964. this._addParticle(idx, this._positions.length, modelShape, this._shapeCounter, i);
  56965. }
  56966. this._index += shape.length;
  56967. idx++;
  56968. }
  56969. this.nbParticles += nb;
  56970. this._shapeCounter++;
  56971. return this._shapeCounter - 1;
  56972. };
  56973. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  56974. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  56975. this._resetCopy();
  56976. if (particle._model._positionFunction) {
  56977. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  56978. }
  56979. if (this._copy.rotationQuaternion) {
  56980. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  56981. }
  56982. else {
  56983. this._yaw = this._copy.rotation.y;
  56984. this._pitch = this._copy.rotation.x;
  56985. this._roll = this._copy.rotation.z;
  56986. this._quaternionRotationYPR();
  56987. }
  56988. this._quaternionToRotationMatrix();
  56989. this._shape = particle._model._shape;
  56990. for (var pt = 0; pt < this._shape.length; pt++) {
  56991. this._vertex.x = this._shape[pt].x;
  56992. this._vertex.y = this._shape[pt].y;
  56993. this._vertex.z = this._shape[pt].z;
  56994. if (particle._model._vertexFunction) {
  56995. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  56996. }
  56997. this._vertex.x *= this._copy.scaling.x;
  56998. this._vertex.y *= this._copy.scaling.y;
  56999. this._vertex.z *= this._copy.scaling.z;
  57000. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  57001. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  57002. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  57003. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  57004. }
  57005. particle.position.x = 0;
  57006. particle.position.y = 0;
  57007. particle.position.z = 0;
  57008. particle.rotation.x = 0;
  57009. particle.rotation.y = 0;
  57010. particle.rotation.z = 0;
  57011. particle.rotationQuaternion = null;
  57012. particle.scaling.x = 1;
  57013. particle.scaling.y = 1;
  57014. particle.scaling.z = 1;
  57015. };
  57016. /**
  57017. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  57018. */
  57019. SolidParticleSystem.prototype.rebuildMesh = function () {
  57020. for (var p = 0; p < this.particles.length; p++) {
  57021. this._rebuildParticle(this.particles[p]);
  57022. }
  57023. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  57024. };
  57025. /**
  57026. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  57027. * This method calls `updateParticle()` for each particle of the SPS.
  57028. * For an animated SPS, it is usually called within the render loop.
  57029. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  57030. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  57031. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  57032. */
  57033. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  57034. if (start === void 0) { start = 0; }
  57035. if (end === void 0) { end = this.nbParticles - 1; }
  57036. if (update === void 0) { update = true; }
  57037. if (!this._updatable) {
  57038. return;
  57039. }
  57040. // custom beforeUpdate
  57041. this.beforeUpdateParticles(start, end, update);
  57042. this._cam_axisX.x = 1.0;
  57043. this._cam_axisX.y = 0.0;
  57044. this._cam_axisX.z = 0.0;
  57045. this._cam_axisY.x = 0.0;
  57046. this._cam_axisY.y = 1.0;
  57047. this._cam_axisY.z = 0.0;
  57048. this._cam_axisZ.x = 0.0;
  57049. this._cam_axisZ.y = 0.0;
  57050. this._cam_axisZ.z = 1.0;
  57051. // if the particles will always face the camera
  57052. if (this.billboard) {
  57053. // compute the camera position and un-rotate it by the current mesh rotation
  57054. this._yaw = this.mesh.rotation.y;
  57055. this._pitch = this.mesh.rotation.x;
  57056. this._roll = this.mesh.rotation.z;
  57057. this._quaternionRotationYPR();
  57058. this._quaternionToRotationMatrix();
  57059. this._rotMatrix.invertToRef(this._invertMatrix);
  57060. this._camera._currentTarget.subtractToRef(this._camera.globalPosition, this._camDir);
  57061. BABYLON.Vector3.TransformCoordinatesToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  57062. this._cam_axisZ.normalize();
  57063. // set two orthogonal vectors (_cam_axisX and and _cam_axisY) to the rotated camDir axis (_cam_axisZ)
  57064. BABYLON.Vector3.CrossToRef(this._cam_axisZ, this._axisX, this._cam_axisY);
  57065. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  57066. this._cam_axisY.normalize();
  57067. this._cam_axisX.normalize();
  57068. }
  57069. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  57070. var idx = 0;
  57071. var index = 0;
  57072. var colidx = 0;
  57073. var colorIndex = 0;
  57074. var uvidx = 0;
  57075. var uvIndex = 0;
  57076. var pt = 0;
  57077. if (this._computeBoundingBox) {
  57078. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  57079. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  57080. }
  57081. // particle loop
  57082. end = (end > this.nbParticles - 1) ? this.nbParticles - 1 : end;
  57083. for (var p = start; p <= end; p++) {
  57084. this._particle = this.particles[p];
  57085. this._shape = this._particle._model._shape;
  57086. this._shapeUV = this._particle._model._shapeUV;
  57087. // call to custom user function to update the particle properties
  57088. this.updateParticle(this._particle);
  57089. if (this._particle.isVisible) {
  57090. // particle rotation matrix
  57091. if (this.billboard) {
  57092. this._particle.rotation.x = 0.0;
  57093. this._particle.rotation.y = 0.0;
  57094. }
  57095. if (this._computeParticleRotation || this.billboard) {
  57096. if (this._particle.rotationQuaternion) {
  57097. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  57098. }
  57099. else {
  57100. this._yaw = this._particle.rotation.y;
  57101. this._pitch = this._particle.rotation.x;
  57102. this._roll = this._particle.rotation.z;
  57103. this._quaternionRotationYPR();
  57104. }
  57105. this._quaternionToRotationMatrix();
  57106. }
  57107. // particle vertex loop
  57108. for (pt = 0; pt < this._shape.length; pt++) {
  57109. idx = index + pt * 3;
  57110. colidx = colorIndex + pt * 4;
  57111. uvidx = uvIndex + pt * 2;
  57112. this._vertex.x = this._shape[pt].x;
  57113. this._vertex.y = this._shape[pt].y;
  57114. this._vertex.z = this._shape[pt].z;
  57115. if (this._computeParticleVertex) {
  57116. this.updateParticleVertex(this._particle, this._vertex, pt);
  57117. }
  57118. // positions
  57119. this._vertex.x *= this._particle.scaling.x;
  57120. this._vertex.y *= this._particle.scaling.y;
  57121. this._vertex.z *= this._particle.scaling.z;
  57122. 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];
  57123. 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;
  57124. 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;
  57125. 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;
  57126. 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;
  57127. 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;
  57128. 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;
  57129. if (this._computeBoundingBox) {
  57130. if (this._positions32[idx] < this._minimum.x) {
  57131. this._minimum.x = this._positions32[idx];
  57132. }
  57133. if (this._positions32[idx] > this._maximum.x) {
  57134. this._maximum.x = this._positions32[idx];
  57135. }
  57136. if (this._positions32[idx + 1] < this._minimum.y) {
  57137. this._minimum.y = this._positions32[idx + 1];
  57138. }
  57139. if (this._positions32[idx + 1] > this._maximum.y) {
  57140. this._maximum.y = this._positions32[idx + 1];
  57141. }
  57142. if (this._positions32[idx + 2] < this._minimum.z) {
  57143. this._minimum.z = this._positions32[idx + 2];
  57144. }
  57145. if (this._positions32[idx + 2] > this._maximum.z) {
  57146. this._maximum.z = this._positions32[idx + 2];
  57147. }
  57148. }
  57149. // normals : if the particles can't be morphed then just rotate the normals, what if much more faster than ComputeNormals()
  57150. if (!this._computeParticleVertex) {
  57151. this._normal.x = this._fixedNormal32[idx];
  57152. this._normal.y = this._fixedNormal32[idx + 1];
  57153. this._normal.z = this._fixedNormal32[idx + 2];
  57154. 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];
  57155. 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;
  57156. 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;
  57157. 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;
  57158. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  57159. 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;
  57160. 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;
  57161. }
  57162. if (this._computeParticleColor) {
  57163. this._colors32[colidx] = this._particle.color.r;
  57164. this._colors32[colidx + 1] = this._particle.color.g;
  57165. this._colors32[colidx + 2] = this._particle.color.b;
  57166. this._colors32[colidx + 3] = this._particle.color.a;
  57167. }
  57168. if (this._computeParticleTexture) {
  57169. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  57170. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  57171. }
  57172. }
  57173. }
  57174. else {
  57175. for (pt = 0; pt < this._shape.length; pt++) {
  57176. idx = index + pt * 3;
  57177. colidx = colorIndex + pt * 4;
  57178. uvidx = uvIndex + pt * 2;
  57179. this._positions32[idx] = this._camera.position.x;
  57180. this._positions32[idx + 1] = this._camera.position.y;
  57181. this._positions32[idx + 2] = this._camera.position.z;
  57182. this._normals32[idx] = 0.0;
  57183. this._normals32[idx + 1] = 0.0;
  57184. this._normals32[idx + 2] = 0.0;
  57185. if (this._computeParticleColor) {
  57186. this._colors32[colidx] = this._particle.color.r;
  57187. this._colors32[colidx + 1] = this._particle.color.g;
  57188. this._colors32[colidx + 2] = this._particle.color.b;
  57189. this._colors32[colidx + 3] = this._particle.color.a;
  57190. }
  57191. if (this._computeParticleTexture) {
  57192. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  57193. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  57194. }
  57195. }
  57196. }
  57197. // increment indexes for the next particle
  57198. index = idx + 3;
  57199. colorIndex = colidx + 4;
  57200. uvIndex = uvidx + 2;
  57201. }
  57202. // if the VBO must be updated
  57203. if (update) {
  57204. if (this._computeParticleColor) {
  57205. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  57206. }
  57207. if (this._computeParticleTexture) {
  57208. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  57209. }
  57210. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  57211. if (!this.mesh.areNormalsFrozen) {
  57212. if (this._computeParticleVertex) {
  57213. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  57214. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals32);
  57215. for (var i = 0; i < this._normals32.length; i++) {
  57216. this._fixedNormal32[i] = this._normals32[i];
  57217. }
  57218. }
  57219. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  57220. }
  57221. }
  57222. if (this._computeBoundingBox) {
  57223. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  57224. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  57225. }
  57226. this.afterUpdateParticles(start, end, update);
  57227. };
  57228. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  57229. this._halfroll = this._roll * 0.5;
  57230. this._halfpitch = this._pitch * 0.5;
  57231. this._halfyaw = this._yaw * 0.5;
  57232. this._sinRoll = Math.sin(this._halfroll);
  57233. this._cosRoll = Math.cos(this._halfroll);
  57234. this._sinPitch = Math.sin(this._halfpitch);
  57235. this._cosPitch = Math.cos(this._halfpitch);
  57236. this._sinYaw = Math.sin(this._halfyaw);
  57237. this._cosYaw = Math.cos(this._halfyaw);
  57238. this._quaternion.x = (this._cosYaw * this._sinPitch * this._cosRoll) + (this._sinYaw * this._cosPitch * this._sinRoll);
  57239. this._quaternion.y = (this._sinYaw * this._cosPitch * this._cosRoll) - (this._cosYaw * this._sinPitch * this._sinRoll);
  57240. this._quaternion.z = (this._cosYaw * this._cosPitch * this._sinRoll) - (this._sinYaw * this._sinPitch * this._cosRoll);
  57241. this._quaternion.w = (this._cosYaw * this._cosPitch * this._cosRoll) + (this._sinYaw * this._sinPitch * this._sinRoll);
  57242. };
  57243. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  57244. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  57245. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  57246. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  57247. this._rotMatrix.m[3] = 0;
  57248. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  57249. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  57250. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  57251. this._rotMatrix.m[7] = 0;
  57252. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  57253. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  57254. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  57255. this._rotMatrix.m[11] = 0;
  57256. this._rotMatrix.m[12] = 0;
  57257. this._rotMatrix.m[13] = 0;
  57258. this._rotMatrix.m[14] = 0;
  57259. this._rotMatrix.m[15] = 1.0;
  57260. };
  57261. /**
  57262. * Disposes the SPS
  57263. */
  57264. SolidParticleSystem.prototype.dispose = function () {
  57265. this.mesh.dispose();
  57266. this.vars = null;
  57267. // drop references to internal big arrays for the GC
  57268. this._positions = null;
  57269. this._indices = null;
  57270. this._normals = null;
  57271. this._uvs = null;
  57272. this._colors = null;
  57273. this._positions32 = null;
  57274. this._normals32 = null;
  57275. this._fixedNormal32 = null;
  57276. this._uvs32 = null;
  57277. this._colors32 = null;
  57278. this.pickedParticles = null;
  57279. };
  57280. /**
  57281. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  57282. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  57283. */
  57284. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  57285. if (!this._isVisibilityBoxLocked) {
  57286. this.mesh.refreshBoundingInfo();
  57287. }
  57288. };
  57289. /**
  57290. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  57291. * @param size the size (float) of the visibility box
  57292. * note : this doesn't lock the SPS mesh bounding box.
  57293. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  57294. */
  57295. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  57296. var vis = size / 2;
  57297. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  57298. };
  57299. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  57300. // getter and setter
  57301. get: function () {
  57302. return this._alwaysVisible;
  57303. },
  57304. /**
  57305. * Sets the SPS as always visible or not
  57306. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  57307. */
  57308. set: function (val) {
  57309. this._alwaysVisible = val;
  57310. this.mesh.alwaysSelectAsActiveMesh = val;
  57311. },
  57312. enumerable: true,
  57313. configurable: true
  57314. });
  57315. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  57316. get: function () {
  57317. return this._isVisibilityBoxLocked;
  57318. },
  57319. /**
  57320. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  57321. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  57322. */
  57323. set: function (val) {
  57324. this._isVisibilityBoxLocked = val;
  57325. this.mesh.getBoundingInfo().isLocked = val;
  57326. },
  57327. enumerable: true,
  57328. configurable: true
  57329. });
  57330. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  57331. // getters
  57332. get: function () {
  57333. return this._computeParticleRotation;
  57334. },
  57335. // Optimizer setters
  57336. /**
  57337. * Tells to `setParticles()` to compute the particle rotations or not.
  57338. * Default value : true. The SPS is faster when it's set to false.
  57339. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  57340. */
  57341. set: function (val) {
  57342. this._computeParticleRotation = val;
  57343. },
  57344. enumerable: true,
  57345. configurable: true
  57346. });
  57347. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  57348. get: function () {
  57349. return this._computeParticleColor;
  57350. },
  57351. /**
  57352. * Tells to `setParticles()` to compute the particle colors or not.
  57353. * Default value : true. The SPS is faster when it's set to false.
  57354. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  57355. */
  57356. set: function (val) {
  57357. this._computeParticleColor = val;
  57358. },
  57359. enumerable: true,
  57360. configurable: true
  57361. });
  57362. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  57363. get: function () {
  57364. return this._computeParticleTexture;
  57365. },
  57366. /**
  57367. * Tells to `setParticles()` to compute the particle textures or not.
  57368. * Default value : true. The SPS is faster when it's set to false.
  57369. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  57370. */
  57371. set: function (val) {
  57372. this._computeParticleTexture = val;
  57373. },
  57374. enumerable: true,
  57375. configurable: true
  57376. });
  57377. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  57378. get: function () {
  57379. return this._computeParticleVertex;
  57380. },
  57381. /**
  57382. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  57383. * Default value : false. The SPS is faster when it's set to false.
  57384. * Note : the particle custom vertex positions aren't stored values.
  57385. */
  57386. set: function (val) {
  57387. this._computeParticleVertex = val;
  57388. },
  57389. enumerable: true,
  57390. configurable: true
  57391. });
  57392. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  57393. get: function () {
  57394. return this._computeBoundingBox;
  57395. },
  57396. /**
  57397. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  57398. */
  57399. set: function (val) {
  57400. this._computeBoundingBox = val;
  57401. },
  57402. enumerable: true,
  57403. configurable: true
  57404. });
  57405. // =======================================================================
  57406. // Particle behavior logic
  57407. // these following methods may be overwritten by the user to fit his needs
  57408. /**
  57409. * This function does nothing. It may be overwritten to set all the particle first values.
  57410. * The SPS doesn't call this function, you may have to call it by your own.
  57411. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  57412. */
  57413. SolidParticleSystem.prototype.initParticles = function () {
  57414. };
  57415. /**
  57416. * This function does nothing. It may be overwritten to recycle a particle.
  57417. * The SPS doesn't call this function, you may have to call it by your own.
  57418. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  57419. */
  57420. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  57421. return particle;
  57422. };
  57423. /**
  57424. * Updates a particle : this function should be overwritten by the user.
  57425. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  57426. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  57427. * ex : just set a particle position or velocity and recycle conditions
  57428. */
  57429. SolidParticleSystem.prototype.updateParticle = function (particle) {
  57430. return particle;
  57431. };
  57432. /**
  57433. * Updates a vertex of a particle : it can be overwritten by the user.
  57434. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  57435. * @param particle the current particle
  57436. * @param vertex the current index of the current particle
  57437. * @param pt the index of the current vertex in the particle shape
  57438. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  57439. * ex : just set a vertex particle position
  57440. */
  57441. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  57442. return vertex;
  57443. };
  57444. /**
  57445. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  57446. * This does nothing and may be overwritten by the user.
  57447. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  57448. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  57449. * @param update the boolean update value actually passed to setParticles()
  57450. */
  57451. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  57452. };
  57453. /**
  57454. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  57455. * This will be passed three parameters.
  57456. * This does nothing and may be overwritten by the user.
  57457. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  57458. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  57459. * @param update the boolean update value actually passed to setParticles()
  57460. */
  57461. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  57462. };
  57463. return SolidParticleSystem;
  57464. })();
  57465. BABYLON.SolidParticleSystem = SolidParticleSystem;
  57466. })(BABYLON || (BABYLON = {}));
  57467. var BABYLON;
  57468. (function (BABYLON) {
  57469. var Internals;
  57470. (function (Internals) {
  57471. var FileFaceOrientation = (function () {
  57472. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  57473. this.name = name;
  57474. this.worldAxisForNormal = worldAxisForNormal;
  57475. this.worldAxisForFileX = worldAxisForFileX;
  57476. this.worldAxisForFileY = worldAxisForFileY;
  57477. }
  57478. return FileFaceOrientation;
  57479. })();
  57480. ;
  57481. /**
  57482. * Helper class dealing with the extraction of spherical polynomial dataArray
  57483. * from a cube map.
  57484. */
  57485. var CubeMapToSphericalPolynomialTools = (function () {
  57486. function CubeMapToSphericalPolynomialTools() {
  57487. }
  57488. /**
  57489. * Converts a cubemap to the according Spherical Polynomial data.
  57490. * This extracts the first 3 orders only as they are the only one used in the lighting.
  57491. *
  57492. * @param cubeInfo The Cube map to extract the information from.
  57493. * @return The Spherical Polynomial data.
  57494. */
  57495. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  57496. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  57497. var totalSolidAngle = 0.0;
  57498. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  57499. var du = 2.0 / cubeInfo.size;
  57500. var dv = du;
  57501. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  57502. var minUV = du * 0.5 - 1.0;
  57503. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  57504. var fileFace = this.FileFaces[faceIndex];
  57505. var dataArray = cubeInfo[fileFace.name];
  57506. var v = minUV;
  57507. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  57508. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  57509. // Because SP is still linear, so summation is fine in that basis.
  57510. for (var y = 0; y < cubeInfo.size; y++) {
  57511. var u = minUV;
  57512. for (var x = 0; x < cubeInfo.size; x++) {
  57513. // World direction (not normalised)
  57514. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  57515. worldDirection.normalize();
  57516. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  57517. if (1) {
  57518. var r = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0];
  57519. var g = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1];
  57520. var b = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2];
  57521. var color = new BABYLON.Color3(r, g, b);
  57522. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  57523. }
  57524. else {
  57525. if (faceIndex == 0) {
  57526. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  57527. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  57528. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  57529. }
  57530. else if (faceIndex == 1) {
  57531. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  57532. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  57533. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  57534. }
  57535. else if (faceIndex == 2) {
  57536. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  57537. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  57538. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  57539. }
  57540. else if (faceIndex == 3) {
  57541. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  57542. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  57543. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  57544. }
  57545. else if (faceIndex == 4) {
  57546. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  57547. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  57548. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  57549. }
  57550. else if (faceIndex == 5) {
  57551. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  57552. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  57553. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  57554. }
  57555. 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]);
  57556. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  57557. }
  57558. totalSolidAngle += deltaSolidAngle;
  57559. u += du;
  57560. }
  57561. v += dv;
  57562. }
  57563. }
  57564. var correctSolidAngle = 4.0 * Math.PI; // Solid angle for entire sphere is 4*pi
  57565. var correction = correctSolidAngle / totalSolidAngle;
  57566. sphericalHarmonics.scale(correction);
  57567. // Additionally scale by pi -- audit needed
  57568. sphericalHarmonics.scale(1.0 / Math.PI);
  57569. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  57570. };
  57571. CubeMapToSphericalPolynomialTools.FileFaces = [
  57572. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  57573. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  57574. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  57575. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  57576. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  57577. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  57578. ];
  57579. return CubeMapToSphericalPolynomialTools;
  57580. })();
  57581. Internals.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  57582. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  57583. })(BABYLON || (BABYLON = {}));
  57584. var BABYLON;
  57585. (function (BABYLON) {
  57586. var Internals;
  57587. (function (Internals) {
  57588. /**
  57589. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  57590. */
  57591. var PanoramaToCubeMapTools = (function () {
  57592. function PanoramaToCubeMapTools() {
  57593. }
  57594. /**
  57595. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  57596. *
  57597. * @param float32Array The source data.
  57598. * @param inputWidth The width of the input panorama.
  57599. * @param inputhHeight The height of the input panorama.
  57600. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  57601. * @return The cubemap data
  57602. */
  57603. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  57604. if (!float32Array) {
  57605. throw "ConvertPanoramaToCubemap: input cannot be null";
  57606. }
  57607. if (float32Array.length != inputWidth * inputHeight * 3) {
  57608. throw "ConvertPanoramaToCubemap: input size is wrong";
  57609. }
  57610. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  57611. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  57612. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  57613. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  57614. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  57615. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  57616. return {
  57617. front: textureFront,
  57618. back: textureBack,
  57619. left: textureLeft,
  57620. right: textureRight,
  57621. up: textureUp,
  57622. down: textureDown,
  57623. size: size
  57624. };
  57625. };
  57626. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  57627. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  57628. var textureArray = new Float32Array(buffer);
  57629. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  57630. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  57631. var dy = 1 / texSize;
  57632. var fy = 0;
  57633. for (var y = 0; y < texSize; y++) {
  57634. var xv1 = faceData[0];
  57635. var xv2 = faceData[2];
  57636. for (var x = 0; x < texSize; x++) {
  57637. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  57638. v.normalize();
  57639. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  57640. // 3 channels per pixels
  57641. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  57642. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  57643. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  57644. xv1 = xv1.add(rotDX1);
  57645. xv2 = xv2.add(rotDX2);
  57646. }
  57647. fy += dy;
  57648. }
  57649. return textureArray;
  57650. };
  57651. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  57652. var theta = Math.atan2(vDir.z, vDir.x);
  57653. var phi = Math.acos(vDir.y);
  57654. while (theta < -Math.PI)
  57655. theta += 2 * Math.PI;
  57656. while (theta > Math.PI)
  57657. theta -= 2 * Math.PI;
  57658. var dx = theta / Math.PI;
  57659. var dy = phi / Math.PI;
  57660. // recenter.
  57661. dx = dx * 0.5 + 0.5;
  57662. var px = Math.round(dx * inputWidth);
  57663. if (px < 0)
  57664. px = 0;
  57665. else if (px >= inputWidth)
  57666. px = inputWidth - 1;
  57667. var py = Math.round(dy * inputHeight);
  57668. if (py < 0)
  57669. py = 0;
  57670. else if (py >= inputHeight)
  57671. py = inputHeight - 1;
  57672. var inputY = (inputHeight - py - 1);
  57673. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  57674. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  57675. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  57676. return {
  57677. r: r,
  57678. g: g,
  57679. b: b
  57680. };
  57681. };
  57682. PanoramaToCubeMapTools.FACE_FRONT = [
  57683. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  57684. new BABYLON.Vector3(1.0, -1.0, -1.0),
  57685. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  57686. new BABYLON.Vector3(1.0, 1.0, -1.0)
  57687. ];
  57688. PanoramaToCubeMapTools.FACE_BACK = [
  57689. new BABYLON.Vector3(1.0, -1.0, 1.0),
  57690. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  57691. new BABYLON.Vector3(1.0, 1.0, 1.0),
  57692. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  57693. ];
  57694. PanoramaToCubeMapTools.FACE_RIGHT = [
  57695. new BABYLON.Vector3(1.0, -1.0, -1.0),
  57696. new BABYLON.Vector3(1.0, -1.0, 1.0),
  57697. new BABYLON.Vector3(1.0, 1.0, -1.0),
  57698. new BABYLON.Vector3(1.0, 1.0, 1.0)
  57699. ];
  57700. PanoramaToCubeMapTools.FACE_LEFT = [
  57701. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  57702. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  57703. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  57704. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  57705. ];
  57706. PanoramaToCubeMapTools.FACE_DOWN = [
  57707. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  57708. new BABYLON.Vector3(1.0, 1.0, -1.0),
  57709. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  57710. new BABYLON.Vector3(1.0, 1.0, 1.0)
  57711. ];
  57712. PanoramaToCubeMapTools.FACE_UP = [
  57713. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  57714. new BABYLON.Vector3(1.0, -1.0, 1.0),
  57715. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  57716. new BABYLON.Vector3(1.0, -1.0, -1.0)
  57717. ];
  57718. return PanoramaToCubeMapTools;
  57719. })();
  57720. Internals.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  57721. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  57722. })(BABYLON || (BABYLON = {}));
  57723. var BABYLON;
  57724. (function (BABYLON) {
  57725. var Internals;
  57726. (function (Internals) {
  57727. ;
  57728. /**
  57729. * This groups tools to convert HDR texture to native colors array.
  57730. */
  57731. var HDRTools = (function () {
  57732. function HDRTools() {
  57733. }
  57734. HDRTools.Ldexp = function (mantissa, exponent) {
  57735. if (exponent > 1023) {
  57736. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  57737. }
  57738. if (exponent < -1074) {
  57739. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  57740. }
  57741. return mantissa * Math.pow(2, exponent);
  57742. };
  57743. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  57744. if (exponent > 0) {
  57745. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  57746. float32array[index + 0] = red * exponent;
  57747. float32array[index + 1] = green * exponent;
  57748. float32array[index + 2] = blue * exponent;
  57749. }
  57750. else {
  57751. float32array[index + 0] = 0;
  57752. float32array[index + 1] = 0;
  57753. float32array[index + 2] = 0;
  57754. }
  57755. };
  57756. HDRTools.readStringLine = function (uint8array, startIndex) {
  57757. var line = "";
  57758. var character = "";
  57759. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  57760. character = String.fromCharCode(uint8array[i]);
  57761. if (character == "\n") {
  57762. break;
  57763. }
  57764. line += character;
  57765. }
  57766. return line;
  57767. };
  57768. /**
  57769. * Reads header information from an RGBE texture stored in a native array.
  57770. * More information on this format are available here:
  57771. * https://en.wikipedia.org/wiki/RGBE_image_format
  57772. *
  57773. * @param uint8array The binary file stored in native array.
  57774. * @return The header information.
  57775. */
  57776. HDRTools.RGBE_ReadHeader = function (uint8array) {
  57777. var height = 0;
  57778. var width = 0;
  57779. var line = this.readStringLine(uint8array, 0);
  57780. if (line[0] != '#' || line[1] != '?') {
  57781. throw "Bad HDR Format.";
  57782. }
  57783. var endOfHeader = false;
  57784. var findFormat = false;
  57785. var lineIndex = 0;
  57786. do {
  57787. lineIndex += (line.length + 1);
  57788. line = this.readStringLine(uint8array, lineIndex);
  57789. if (line == "FORMAT=32-bit_rle_rgbe") {
  57790. findFormat = true;
  57791. }
  57792. else if (line.length == 0) {
  57793. endOfHeader = true;
  57794. }
  57795. } while (!endOfHeader);
  57796. if (!findFormat) {
  57797. throw "HDR Bad header format, unsupported FORMAT";
  57798. }
  57799. lineIndex += (line.length + 1);
  57800. line = this.readStringLine(uint8array, lineIndex);
  57801. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  57802. var match = sizeRegexp.exec(line);
  57803. // TODO. Support +Y and -X if needed.
  57804. if (match.length < 3) {
  57805. throw "HDR Bad header format, no size";
  57806. }
  57807. width = parseInt(match[2]);
  57808. height = parseInt(match[1]);
  57809. if (width < 8 || width > 0x7fff) {
  57810. throw "HDR Bad header format, unsupported size";
  57811. }
  57812. lineIndex += (line.length + 1);
  57813. return {
  57814. height: height,
  57815. width: width,
  57816. dataPosition: lineIndex
  57817. };
  57818. };
  57819. /**
  57820. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  57821. * This RGBE texture needs to store the information as a panorama.
  57822. *
  57823. * More information on this format are available here:
  57824. * https://en.wikipedia.org/wiki/RGBE_image_format
  57825. *
  57826. * @param buffer The binary file stored in an array buffer.
  57827. * @param size The expected size of the extracted cubemap.
  57828. * @return The Cube Map information.
  57829. */
  57830. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  57831. var uint8array = new Uint8Array(buffer);
  57832. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  57833. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  57834. var cubeMapData = Internals.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  57835. return cubeMapData;
  57836. };
  57837. /**
  57838. * Returns the pixels data extracted from an RGBE texture.
  57839. * This pixels will be stored left to right up to down in the R G B order in one array.
  57840. *
  57841. * More information on this format are available here:
  57842. * https://en.wikipedia.org/wiki/RGBE_image_format
  57843. *
  57844. * @param uint8array The binary file stored in an array buffer.
  57845. * @param hdrInfo The header information of the file.
  57846. * @return The pixels data in RGB right to left up to down order.
  57847. */
  57848. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  57849. // Keep for multi format supports.
  57850. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  57851. };
  57852. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  57853. var num_scanlines = hdrInfo.height;
  57854. var scanline_width = hdrInfo.width;
  57855. var a, b, c, d, count;
  57856. var dataIndex = hdrInfo.dataPosition;
  57857. var index = 0, endIndex = 0, i = 0;
  57858. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  57859. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  57860. // 3 channels of 4 bytes per pixel in float.
  57861. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  57862. var resultArray = new Float32Array(resultBuffer);
  57863. // read in each successive scanline
  57864. while (num_scanlines > 0) {
  57865. a = uint8array[dataIndex++];
  57866. b = uint8array[dataIndex++];
  57867. c = uint8array[dataIndex++];
  57868. d = uint8array[dataIndex++];
  57869. if (a != 2 || b != 2 || (c & 0x80)) {
  57870. // this file is not run length encoded
  57871. throw "HDR Bad header format, not RLE";
  57872. }
  57873. if (((c << 8) | d) != scanline_width) {
  57874. throw "HDR Bad header format, wrong scan line width";
  57875. }
  57876. index = 0;
  57877. // read each of the four channels for the scanline into the buffer
  57878. for (i = 0; i < 4; i++) {
  57879. endIndex = (i + 1) * scanline_width;
  57880. while (index < endIndex) {
  57881. a = uint8array[dataIndex++];
  57882. b = uint8array[dataIndex++];
  57883. if (a > 128) {
  57884. // a run of the same value
  57885. count = a - 128;
  57886. if ((count == 0) || (count > endIndex - index)) {
  57887. throw "HDR Bad Format, bad scanline data (run)";
  57888. }
  57889. while (count-- > 0) {
  57890. scanLineArray[index++] = b;
  57891. }
  57892. }
  57893. else {
  57894. // a non-run
  57895. count = a;
  57896. if ((count == 0) || (count > endIndex - index)) {
  57897. throw "HDR Bad Format, bad scanline data (non-run)";
  57898. }
  57899. scanLineArray[index++] = b;
  57900. if (--count > 0) {
  57901. for (var j = 0; j < count; j++) {
  57902. scanLineArray[index++] = uint8array[dataIndex++];
  57903. }
  57904. }
  57905. }
  57906. }
  57907. }
  57908. // now convert data from buffer into floats
  57909. for (i = 0; i < scanline_width; i++) {
  57910. a = scanLineArray[i];
  57911. b = scanLineArray[i + scanline_width];
  57912. c = scanLineArray[i + 2 * scanline_width];
  57913. d = scanLineArray[i + 3 * scanline_width];
  57914. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  57915. }
  57916. num_scanlines--;
  57917. }
  57918. return resultArray;
  57919. };
  57920. return HDRTools;
  57921. })();
  57922. Internals.HDRTools = HDRTools;
  57923. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  57924. })(BABYLON || (BABYLON = {}));
  57925. //_______________________________________________________________
  57926. // Extracted from CubeMapGen:
  57927. // https://code.google.com/archive/p/cubemapgen/
  57928. //
  57929. // Following https://seblagarde.wordpress.com/2012/06/10/amd-cubemapgen-for-physically-based-rendering/
  57930. //_______________________________________________________________
  57931. var BABYLON;
  57932. (function (BABYLON) {
  57933. var Internals;
  57934. (function (Internals) {
  57935. /**
  57936. * The bounding box information used during the conversion process.
  57937. */
  57938. var CMGBoundinBox = (function () {
  57939. function CMGBoundinBox() {
  57940. this.min = new BABYLON.Vector3(0, 0, 0);
  57941. this.max = new BABYLON.Vector3(0, 0, 0);
  57942. this.clear();
  57943. }
  57944. CMGBoundinBox.prototype.clear = function () {
  57945. this.min.x = CMGBoundinBox.MAX;
  57946. this.min.y = CMGBoundinBox.MAX;
  57947. this.min.z = CMGBoundinBox.MAX;
  57948. this.max.x = CMGBoundinBox.MIN;
  57949. this.max.y = CMGBoundinBox.MIN;
  57950. this.max.z = CMGBoundinBox.MIN;
  57951. };
  57952. CMGBoundinBox.prototype.augment = function (x, y, z) {
  57953. this.min.x = Math.min(this.min.x, x);
  57954. this.min.y = Math.min(this.min.y, y);
  57955. this.min.z = Math.min(this.min.z, z);
  57956. this.max.x = Math.max(this.max.x, x);
  57957. this.max.y = Math.max(this.max.y, y);
  57958. this.max.z = Math.max(this.max.z, z);
  57959. };
  57960. CMGBoundinBox.prototype.clampMin = function (x, y, z) {
  57961. this.min.x = Math.max(this.min.x, x);
  57962. this.min.y = Math.max(this.min.y, y);
  57963. this.min.z = Math.max(this.min.z, z);
  57964. };
  57965. CMGBoundinBox.prototype.clampMax = function (x, y, z) {
  57966. this.max.x = Math.min(this.max.x, x);
  57967. this.max.y = Math.min(this.max.y, y);
  57968. this.max.z = Math.min(this.max.z, z);
  57969. };
  57970. CMGBoundinBox.prototype.empty = function () {
  57971. if ((this.min.x > this.max.y) ||
  57972. (this.min.y > this.max.y) ||
  57973. (this.min.z > this.max.y)) {
  57974. return true;
  57975. }
  57976. else {
  57977. return false;
  57978. }
  57979. };
  57980. CMGBoundinBox.MAX = Number.MAX_VALUE;
  57981. CMGBoundinBox.MIN = Number.MIN_VALUE;
  57982. return CMGBoundinBox;
  57983. })();
  57984. /**
  57985. * Helper class to PreProcess a cubemap in order to generate mipmap according to the level of blur
  57986. * required by the glossinees of a material.
  57987. *
  57988. * This only supports the cosine drop power as well as Warp fixup generation method.
  57989. *
  57990. * This is using the process from CubeMapGen described here:
  57991. * https://seblagarde.wordpress.com/2012/06/10/amd-cubemapgen-for-physically-based-rendering/
  57992. */
  57993. var PMREMGenerator = (function () {
  57994. /**
  57995. * Constructor of the generator.
  57996. *
  57997. * @param input The different faces data from the original cubemap in the order X+ X- Y+ Y- Z+ Z-
  57998. * @param inputSize The size of the cubemap faces
  57999. * @param outputSize The size of the output cubemap faces
  58000. * @param maxNumMipLevels The max number of mip map to generate (0 means all)
  58001. * @param numChannels The number of channels stored in the cubemap (3 for RBGE for instance)
  58002. * @param isFloat Specifies if the input texture is in float or int (hdr is usually in float)
  58003. * @param specularPower The max specular level of the desired cubemap
  58004. * @param cosinePowerDropPerMip The amount of drop the specular power will follow on each mip
  58005. * @param excludeBase Specifies wether to process the level 0 (original level) or not
  58006. * @param fixup Specifies wether to apply the edge fixup algorythm or not
  58007. */
  58008. function PMREMGenerator(input, inputSize, outputSize, maxNumMipLevels, numChannels, isFloat, specularPower, cosinePowerDropPerMip, excludeBase, fixup) {
  58009. this.input = input;
  58010. this.inputSize = inputSize;
  58011. this.outputSize = outputSize;
  58012. this.maxNumMipLevels = maxNumMipLevels;
  58013. this.numChannels = numChannels;
  58014. this.isFloat = isFloat;
  58015. this.specularPower = specularPower;
  58016. this.cosinePowerDropPerMip = cosinePowerDropPerMip;
  58017. this.excludeBase = excludeBase;
  58018. this.fixup = fixup;
  58019. this._outputSurface = [];
  58020. this._numMipLevels = 0;
  58021. }
  58022. /**
  58023. * Launches the filter process and return the result.
  58024. *
  58025. * @return the filter cubemap in the form mip0 [faces1..6] .. mipN [faces1..6]
  58026. */
  58027. PMREMGenerator.prototype.filterCubeMap = function () {
  58028. // Init cubemap processor
  58029. this.init();
  58030. // Filters the cubemap
  58031. this.filterCubeMapMipChain();
  58032. // Returns the filtered mips.
  58033. return this._outputSurface;
  58034. };
  58035. PMREMGenerator.prototype.init = function () {
  58036. var i;
  58037. var j;
  58038. var mipLevelSize;
  58039. //if nax num mip levels is set to 0, set it to generate the entire mip chain
  58040. if (this.maxNumMipLevels == 0) {
  58041. this.maxNumMipLevels = PMREMGenerator.CP_MAX_MIPLEVELS;
  58042. }
  58043. //first miplevel size
  58044. mipLevelSize = this.outputSize;
  58045. //Iterate over mip chain, and init ArrayBufferView for mip-chain
  58046. for (j = 0; j < this.maxNumMipLevels; j++) {
  58047. this._outputSurface.length++;
  58048. this._outputSurface[j] = [];
  58049. //Iterate over faces for output images
  58050. for (i = 0; i < 6; i++) {
  58051. this._outputSurface[j].length++;
  58052. // Initializes a new array for the output.
  58053. if (this.isFloat) {
  58054. this._outputSurface[j][i] = new Float32Array(mipLevelSize * mipLevelSize * this.numChannels);
  58055. }
  58056. else {
  58057. this._outputSurface[j][i] = new Uint32Array(mipLevelSize * mipLevelSize * this.numChannels);
  58058. }
  58059. }
  58060. //next mip level is half size
  58061. mipLevelSize >>= 1;
  58062. this._numMipLevels++;
  58063. //terminate if mip chain becomes too small
  58064. if (mipLevelSize == 0) {
  58065. this.maxNumMipLevels = j;
  58066. return;
  58067. }
  58068. }
  58069. };
  58070. //--------------------------------------------------------------------------------------
  58071. //Cube map filtering and mip chain generation.
  58072. // the cube map filtereing is specified using a number of parameters:
  58073. // Filtering per miplevel is specified using 2D cone angle (in degrees) that
  58074. // indicates the region of the hemisphere to filter over for each tap.
  58075. //
  58076. // Note that the top mip level is also a filtered version of the original input images
  58077. // as well in order to create mip chains for diffuse environment illumination.
  58078. // The cone angle for the top level is specified by a_BaseAngle. This can be used to
  58079. // generate mipchains used to store the resutls of preintegration across the hemisphere.
  58080. //
  58081. // Then the mip angle used to genreate the next level of the mip chain from the first level
  58082. // is a_InitialMipAngle
  58083. //
  58084. // The angle for the subsequent levels of the mip chain are specified by their parents
  58085. // filtering angle and a per-level scale and bias
  58086. // newAngle = oldAngle * a_MipAnglePerLevelScale;
  58087. //
  58088. //--------------------------------------------------------------------------------------
  58089. PMREMGenerator.prototype.filterCubeMapMipChain = function () {
  58090. // First, take count of the lighting model to modify SpecularPower
  58091. // 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;
  58092. // var refSpecularPower = this.specularPower; // Only Phong BRDF yet. This explains the line below using this.specularpower.
  58093. //Cone angle start (for generating subsequent mip levels)
  58094. var currentSpecularPower = this.specularPower;
  58095. //Build filter lookup tables based on the source miplevel size
  58096. this.precomputeFilterLookupTables(this.inputSize);
  58097. // Note that we need to filter the first level before generating mipmap
  58098. // So LevelIndex == 0 is base filtering hen LevelIndex > 0 is mipmap generation
  58099. for (var levelIndex = 0; levelIndex < this._numMipLevels; levelIndex++) {
  58100. // TODO : Write a function to copy and scale the base mipmap in output
  58101. // I am just lazy here and just put a high specular power value, and do some if.
  58102. if (this.excludeBase && (levelIndex == 0)) {
  58103. // 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).
  58104. currentSpecularPower = 100000.0;
  58105. }
  58106. // Special case for cosine power mipmap chain. For quality requirement, we always process the current mipmap from the top mipmap
  58107. var srcCubeImage = this.input;
  58108. var dstCubeImage = this._outputSurface[levelIndex];
  58109. var dstSize = this.outputSize >> levelIndex;
  58110. // Compute required angle.
  58111. var angle = this.getBaseFilterAngle(currentSpecularPower);
  58112. // filter cube surfaces
  58113. this.filterCubeSurfaces(srcCubeImage, this.inputSize, dstCubeImage, dstSize, angle, currentSpecularPower);
  58114. // fix seams
  58115. if (this.fixup) {
  58116. this.fixupCubeEdges(dstCubeImage, dstSize);
  58117. }
  58118. // Decrease the specular power to generate the mipmap chain
  58119. // TODO : Use another method for Exclude (see first comment at start of the function
  58120. if (this.excludeBase && (levelIndex == 0)) {
  58121. currentSpecularPower = this.specularPower;
  58122. }
  58123. currentSpecularPower *= this.cosinePowerDropPerMip;
  58124. }
  58125. };
  58126. //--------------------------------------------------------------------------------------
  58127. // This function return the BaseFilterAngle require by PMREMGenerator to its FilterExtends
  58128. // It allow to optimize the texel to access base on the specular power.
  58129. //--------------------------------------------------------------------------------------
  58130. PMREMGenerator.prototype.getBaseFilterAngle = function (cosinePower) {
  58131. // We want to find the alpha such that:
  58132. // cos(alpha)^cosinePower = epsilon
  58133. // That's: acos(epsilon^(1/cosinePower))
  58134. var threshold = 0.000001; // Empirical threshold (Work perfectly, didn't check for a more big number, may get some performance and still god approximation)
  58135. var angle = 180.0;
  58136. angle = Math.acos(Math.pow(threshold, 1.0 / cosinePower));
  58137. angle *= 180.0 / Math.PI; // Convert to degree
  58138. angle *= 2.0; // * 2.0f because PMREMGenerator divide by 2 later
  58139. return angle;
  58140. };
  58141. //--------------------------------------------------------------------------------------
  58142. //Builds the following lookup tables prior to filtering:
  58143. // -normalizer cube map
  58144. // -tap weight lookup table
  58145. //
  58146. //--------------------------------------------------------------------------------------
  58147. PMREMGenerator.prototype.precomputeFilterLookupTables = function (srcCubeMapWidth) {
  58148. var srcTexelAngle;
  58149. var iCubeFace;
  58150. //clear pre-existing normalizer cube map
  58151. this._normCubeMap = [];
  58152. //Normalized vectors per cubeface and per-texel solid angle
  58153. this.buildNormalizerSolidAngleCubemap(srcCubeMapWidth);
  58154. };
  58155. //--------------------------------------------------------------------------------------
  58156. //Builds a normalizer cubemap, with the texels solid angle stored in the fourth component
  58157. //
  58158. //Takes in a cube face size, and an array of 6 surfaces to write the cube faces into
  58159. //
  58160. //Note that this normalizer cube map stores the vectors in unbiased -1 to 1 range.
  58161. // if _bx2 style scaled and biased vectors are needed, uncomment the SCALE and BIAS
  58162. // below
  58163. //--------------------------------------------------------------------------------------
  58164. PMREMGenerator.prototype.buildNormalizerSolidAngleCubemap = function (size) {
  58165. var iCubeFace;
  58166. var u;
  58167. var v;
  58168. //iterate over cube faces
  58169. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  58170. //First three channels for norm cube, and last channel for solid angle
  58171. this._normCubeMap.push(new Float32Array(size * size * 4));
  58172. //fast texture walk, build normalizer cube map
  58173. var facesData = this.input[iCubeFace];
  58174. for (v = 0; v < size; v++) {
  58175. for (u = 0; u < size; u++) {
  58176. var vect = this.texelCoordToVect(iCubeFace, u, v, size, this.fixup);
  58177. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 0] = vect.x;
  58178. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 1] = vect.y;
  58179. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 2] = vect.z;
  58180. var solidAngle = this.texelCoordSolidAngle(iCubeFace, u, v, size);
  58181. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 4] = solidAngle;
  58182. }
  58183. }
  58184. }
  58185. };
  58186. //--------------------------------------------------------------------------------------
  58187. // Convert cubemap face texel coordinates and face idx to 3D vector
  58188. // note the U and V coords are integer coords and range from 0 to size-1
  58189. // this routine can be used to generate a normalizer cube map
  58190. //--------------------------------------------------------------------------------------
  58191. // SL BEGIN
  58192. PMREMGenerator.prototype.texelCoordToVect = function (faceIdx, u, v, size, fixup) {
  58193. var nvcU;
  58194. var nvcV;
  58195. var tempVec;
  58196. // Change from original AMD code
  58197. // transform from [0..res - 1] to [- (1 - 1 / res) .. (1 - 1 / res)]
  58198. // + 0.5f is for texel center addressing
  58199. nvcU = (2.0 * (u + 0.5) / size) - 1.0;
  58200. nvcV = (2.0 * (v + 0.5) / size) - 1.0;
  58201. // warp fixup
  58202. if (fixup && size > 1) {
  58203. // Code from Nvtt : http://code.google.com/p/nvidia-texture-tools/source/browse/trunk/src/nvtt/CubeSurface.cpp
  58204. var a = Math.pow(size, 2.0) / Math.pow(size - 1, 3.0);
  58205. nvcU = a * Math.pow(nvcU, 3) + nvcU;
  58206. nvcV = a * Math.pow(nvcV, 3) + nvcV;
  58207. }
  58208. // Get current vector
  58209. // generate x,y,z vector (xform 2d NVC coord to 3D vector)
  58210. // U contribution
  58211. var UVec = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_UDIR];
  58212. PMREMGenerator._vectorTemp.x = UVec[0] * nvcU;
  58213. PMREMGenerator._vectorTemp.y = UVec[1] * nvcU;
  58214. PMREMGenerator._vectorTemp.z = UVec[2] * nvcU;
  58215. // V contribution and Sum
  58216. var VVec = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_VDIR];
  58217. PMREMGenerator._vectorTemp.x += VVec[0] * nvcV;
  58218. PMREMGenerator._vectorTemp.y += VVec[1] * nvcV;
  58219. PMREMGenerator._vectorTemp.z += VVec[2] * nvcV;
  58220. //add face axis
  58221. var faceAxis = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_FACEAXIS];
  58222. PMREMGenerator._vectorTemp.x += faceAxis[0];
  58223. PMREMGenerator._vectorTemp.y += faceAxis[1];
  58224. PMREMGenerator._vectorTemp.z += faceAxis[2];
  58225. //normalize vector
  58226. PMREMGenerator._vectorTemp.normalize();
  58227. return PMREMGenerator._vectorTemp;
  58228. };
  58229. //--------------------------------------------------------------------------------------
  58230. // Convert 3D vector to cubemap face texel coordinates and face idx
  58231. // note the U and V coords are integer coords and range from 0 to size-1
  58232. // this routine can be used to generate a normalizer cube map
  58233. //
  58234. // returns face IDX and texel coords
  58235. //--------------------------------------------------------------------------------------
  58236. // SL BEGIN
  58237. /*
  58238. Mapping Texture Coordinates to Cube Map Faces
  58239. Because there are multiple faces, the mapping of texture coordinates to positions on cube map faces
  58240. is more complicated than the other texturing targets. The EXT_texture_cube_map extension is purposefully
  58241. designed to be consistent with DirectX 7's cube map arrangement. This is also consistent with the cube
  58242. map arrangement in Pixar's RenderMan package.
  58243. For cube map texturing, the (s,t,r) texture coordinates are treated as a direction vector (rx,ry,rz)
  58244. emanating from the center of a cube. (The q coordinate can be ignored since it merely scales the vector
  58245. without affecting the direction.) At texture application time, the interpolated per-fragment (s,t,r)
  58246. selects one of the cube map face's 2D mipmap sets based on the largest magnitude coordinate direction
  58247. the major axis direction). The target column in the table below explains how the major axis direction
  58248. maps to the 2D image of a particular cube map target.
  58249. major axis
  58250. direction target sc tc ma
  58251. ---------- --------------------------------- --- --- ---
  58252. +rx GL_TEXTURE_CUBE_MAP_POSITIVE_X_EXT -rz -ry rx
  58253. -rx GL_TEXTURE_CUBE_MAP_NEGATIVE_X_EXT +rz -ry rx
  58254. +ry GL_TEXTURE_CUBE_MAP_POSITIVE_Y_EXT +rx +rz ry
  58255. -ry GL_TEXTURE_CUBE_MAP_NEGATIVE_Y_EXT +rx -rz ry
  58256. +rz GL_TEXTURE_CUBE_MAP_POSITIVE_Z_EXT +rx -ry rz
  58257. -rz GL_TEXTURE_CUBE_MAP_NEGATIVE_Z_EXT -rx -ry rz
  58258. Using the sc, tc, and ma determined by the major axis direction as specified in the table above,
  58259. an updated (s,t) is calculated as follows
  58260. s = ( sc/|ma| + 1 ) / 2
  58261. t = ( tc/|ma| + 1 ) / 2
  58262. If |ma| is zero or very nearly zero, the results of the above two equations need not be defined
  58263. (though the result may not lead to GL interruption or termination). Once the cube map face's 2D mipmap
  58264. set and (s,t) is determined, texture fetching and filtering proceeds like standard OpenGL 2D texturing.
  58265. */
  58266. // Note this method return U and V in range from 0 to size-1
  58267. // SL END
  58268. // Store the information in vector3 for convenience (faceindex, u, v)
  58269. PMREMGenerator.prototype.vectToTexelCoord = function (x, y, z, size) {
  58270. var maxCoord;
  58271. var faceIdx;
  58272. //absolute value 3
  58273. var absX = Math.abs(x);
  58274. var absY = Math.abs(y);
  58275. var absZ = Math.abs(z);
  58276. if (absX >= absY && absX >= absZ) {
  58277. maxCoord = absX;
  58278. if (x >= 0) {
  58279. faceIdx = PMREMGenerator.CP_FACE_X_POS;
  58280. }
  58281. else {
  58282. faceIdx = PMREMGenerator.CP_FACE_X_NEG;
  58283. }
  58284. }
  58285. else if (absY >= absX && absY >= absZ) {
  58286. maxCoord = absY;
  58287. if (y >= 0) {
  58288. faceIdx = PMREMGenerator.CP_FACE_Y_POS;
  58289. }
  58290. else {
  58291. faceIdx = PMREMGenerator.CP_FACE_Y_NEG;
  58292. }
  58293. }
  58294. else {
  58295. maxCoord = absZ;
  58296. if (z >= 0) {
  58297. faceIdx = PMREMGenerator.CP_FACE_Z_POS;
  58298. }
  58299. else {
  58300. faceIdx = PMREMGenerator.CP_FACE_Z_NEG;
  58301. }
  58302. }
  58303. //divide through by max coord so face vector lies on cube face
  58304. var scale = 1 / maxCoord;
  58305. x *= scale;
  58306. y *= scale;
  58307. z *= scale;
  58308. var temp = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_UDIR];
  58309. var nvcU = temp[0] * x + temp[1] * y + temp[2] * z;
  58310. temp = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_VDIR];
  58311. var nvcV = temp[0] * x + temp[1] * y + temp[2] * z;
  58312. // Modify original AMD code to return value from 0 to Size - 1
  58313. var u = Math.floor((size - 1) * 0.5 * (nvcU + 1.0));
  58314. var v = Math.floor((size - 1) * 0.5 * (nvcV + 1.0));
  58315. PMREMGenerator._vectorTemp.x = faceIdx;
  58316. PMREMGenerator._vectorTemp.y = u;
  58317. PMREMGenerator._vectorTemp.z = v;
  58318. return PMREMGenerator._vectorTemp;
  58319. };
  58320. //--------------------------------------------------------------------------------------
  58321. //Original code from Ignacio CastaÒo
  58322. // This formula is from Manne ÷hrstrˆm's thesis.
  58323. // Take two coordiantes in the range [-1, 1] that define a portion of a
  58324. // cube face and return the area of the projection of that portion on the
  58325. // surface of the sphere.
  58326. //--------------------------------------------------------------------------------------
  58327. PMREMGenerator.prototype.areaElement = function (x, y) {
  58328. return Math.atan2(x * y, Math.sqrt(x * x + y * y + 1));
  58329. };
  58330. PMREMGenerator.prototype.texelCoordSolidAngle = function (faceIdx, u, v, size) {
  58331. // transform from [0..res - 1] to [- (1 - 1 / res) .. (1 - 1 / res)]
  58332. // (+ 0.5f is for texel center addressing)
  58333. u = (2.0 * (u + 0.5) / size) - 1.0;
  58334. v = (2.0 * (v + 0.5) / size) - 1.0;
  58335. // Shift from a demi texel, mean 1.0f / a_Size with U and V in [-1..1]
  58336. var invResolution = 1.0 / size;
  58337. // U and V are the -1..1 texture coordinate on the current face.
  58338. // Get projected area for this texel
  58339. var x0 = u - invResolution;
  58340. var y0 = v - invResolution;
  58341. var x1 = u + invResolution;
  58342. var y1 = v + invResolution;
  58343. var solidAngle = this.areaElement(x0, y0) - this.areaElement(x0, y1) - this.areaElement(x1, y0) + this.areaElement(x1, y1);
  58344. return solidAngle;
  58345. };
  58346. //--------------------------------------------------------------------------------------
  58347. //The key to the speed of these filtering routines is to quickly define a per-face
  58348. // bounding box of pixels which enclose all the taps in the filter kernel efficiently.
  58349. // Later these pixels are selectively processed based on their dot products to see if
  58350. // they reside within the filtering cone.
  58351. //
  58352. //This is done by computing the smallest per-texel angle to get a conservative estimate
  58353. // of the number of texels needed to be covered in width and height order to filter the
  58354. // region. the bounding box for the center taps face is defined first, and if the
  58355. // filtereing region bleeds onto the other faces, bounding boxes for the other faces are
  58356. // defined next
  58357. //--------------------------------------------------------------------------------------
  58358. PMREMGenerator.prototype.filterCubeSurfaces = function (srcCubeMap, srcSize, dstCubeMap, dstSize, filterConeAngle, specularPower) {
  58359. // note that pixels within these regions may be rejected
  58360. // based on the anlge
  58361. var iCubeFace;
  58362. var u;
  58363. var v;
  58364. // bounding box per face to specify region to process
  58365. var filterExtents = [];
  58366. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  58367. filterExtents.push(new CMGBoundinBox());
  58368. }
  58369. // min angle a src texel can cover (in degrees)
  58370. var srcTexelAngle = (180.0 / (Math.PI) * Math.atan2(1.0, srcSize));
  58371. // angle about center tap to define filter cone
  58372. // filter angle is 1/2 the cone angle
  58373. var filterAngle = filterConeAngle / 2.0;
  58374. //ensure filter angle is larger than a texel
  58375. if (filterAngle < srcTexelAngle) {
  58376. filterAngle = srcTexelAngle;
  58377. }
  58378. //ensure filter cone is always smaller than the hemisphere
  58379. if (filterAngle > 90.0) {
  58380. filterAngle = 90.0;
  58381. }
  58382. // the maximum number of texels in 1D the filter cone angle will cover
  58383. // used to determine bounding box size for filter extents
  58384. var filterSize = Math.ceil(filterAngle / srcTexelAngle);
  58385. // ensure conservative region always covers at least one texel
  58386. if (filterSize < 1) {
  58387. filterSize = 1;
  58388. }
  58389. // dotProdThresh threshold based on cone angle to determine whether or not taps
  58390. // reside within the cone angle
  58391. var dotProdThresh = Math.cos((Math.PI / 180.0) * filterAngle);
  58392. // process required faces
  58393. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  58394. //iterate over dst cube map face texel
  58395. for (v = 0; v < dstSize; v++) {
  58396. for (u = 0; u < dstSize; u++) {
  58397. //get center tap direction
  58398. var centerTapDir = this.texelCoordToVect(iCubeFace, u, v, dstSize, this.fixup).clone();
  58399. //clear old per-face filter extents
  58400. this.clearFilterExtents(filterExtents);
  58401. //define per-face filter extents
  58402. this.determineFilterExtents(centerTapDir, srcSize, filterSize, filterExtents);
  58403. //perform filtering of src faces using filter extents
  58404. var vect = this.processFilterExtents(centerTapDir, dotProdThresh, filterExtents, srcCubeMap, srcSize, specularPower);
  58405. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 0] = vect.x;
  58406. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 1] = vect.y;
  58407. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 2] = vect.z;
  58408. }
  58409. }
  58410. }
  58411. };
  58412. //--------------------------------------------------------------------------------------
  58413. //Clear filter extents for the 6 cube map faces
  58414. //--------------------------------------------------------------------------------------
  58415. PMREMGenerator.prototype.clearFilterExtents = function (filterExtents) {
  58416. for (var iCubeFaces = 0; iCubeFaces < 6; iCubeFaces++) {
  58417. filterExtents[iCubeFaces].clear();
  58418. }
  58419. };
  58420. //--------------------------------------------------------------------------------------
  58421. //Define per-face bounding box filter extents
  58422. //
  58423. // These define conservative texel regions in each of the faces the filter can possibly
  58424. // process. When the pixels in the regions are actually processed, the dot product
  58425. // between the tap vector and the center tap vector is used to determine the weight of
  58426. // the tap and whether or not the tap is within the cone.
  58427. //
  58428. //--------------------------------------------------------------------------------------
  58429. PMREMGenerator.prototype.determineFilterExtents = function (centerTapDir, srcSize, bboxSize, filterExtents) {
  58430. //neighboring face and bleed over amount, and width of BBOX for
  58431. // left, right, top, and bottom edges of this face
  58432. var bleedOverAmount = [0, 0, 0, 0];
  58433. var bleedOverBBoxMin = [0, 0, 0, 0];
  58434. var bleedOverBBoxMax = [0, 0, 0, 0];
  58435. var neighborFace;
  58436. var neighborEdge;
  58437. var oppositeFaceIdx;
  58438. //get face idx, and u, v info from center tap dir
  58439. var result = this.vectToTexelCoord(centerTapDir.x, centerTapDir.y, centerTapDir.z, srcSize);
  58440. var faceIdx = result.x;
  58441. var u = result.y;
  58442. var v = result.z;
  58443. //define bbox size within face
  58444. filterExtents[faceIdx].augment(u - bboxSize, v - bboxSize, 0);
  58445. filterExtents[faceIdx].augment(u + bboxSize, v + bboxSize, 0);
  58446. filterExtents[faceIdx].clampMin(0, 0, 0);
  58447. filterExtents[faceIdx].clampMax(srcSize - 1, srcSize - 1, 0);
  58448. //u and v extent in face corresponding to center tap
  58449. var minU = filterExtents[faceIdx].min.x;
  58450. var minV = filterExtents[faceIdx].min.y;
  58451. var maxU = filterExtents[faceIdx].max.x;
  58452. var maxV = filterExtents[faceIdx].max.y;
  58453. //bleed over amounts for face across u=0 edge (left)
  58454. bleedOverAmount[0] = (bboxSize - u);
  58455. bleedOverBBoxMin[0] = minV;
  58456. bleedOverBBoxMax[0] = maxV;
  58457. //bleed over amounts for face across u=1 edge (right)
  58458. bleedOverAmount[1] = (u + bboxSize) - (srcSize - 1);
  58459. bleedOverBBoxMin[1] = minV;
  58460. bleedOverBBoxMax[1] = maxV;
  58461. //bleed over to face across v=0 edge (up)
  58462. bleedOverAmount[2] = (bboxSize - v);
  58463. bleedOverBBoxMin[2] = minU;
  58464. bleedOverBBoxMax[2] = maxU;
  58465. //bleed over to face across v=1 edge (down)
  58466. bleedOverAmount[3] = (v + bboxSize) - (srcSize - 1);
  58467. bleedOverBBoxMin[3] = minU;
  58468. bleedOverBBoxMax[3] = maxU;
  58469. //compute bleed over regions in neighboring faces
  58470. for (var i = 0; i < 4; i++) {
  58471. if (bleedOverAmount[i] > 0) {
  58472. neighborFace = PMREMGenerator._sgCubeNgh[faceIdx][i][0];
  58473. neighborEdge = PMREMGenerator._sgCubeNgh[faceIdx][i][1];
  58474. //For certain types of edge abutments, the bleedOverBBoxMin, and bleedOverBBoxMax need to
  58475. // be flipped: the cases are
  58476. // if a left edge mates with a left or bottom edge on the neighbor
  58477. // if a top edge mates with a top or right edge on the neighbor
  58478. // if a right edge mates with a right or top edge on the neighbor
  58479. // if a bottom edge mates with a bottom or left edge on the neighbor
  58480. //Seeing as the edges are enumerated as follows
  58481. // left =0
  58482. // right =1
  58483. // top =2
  58484. // bottom =3
  58485. //
  58486. // so if the edge enums are the same, or the sum of the enums == 3,
  58487. // the bbox needs to be flipped
  58488. if ((i == neighborEdge) || ((i + neighborEdge) == 3)) {
  58489. bleedOverBBoxMin[i] = (srcSize - 1) - bleedOverBBoxMin[i];
  58490. bleedOverBBoxMax[i] = (srcSize - 1) - bleedOverBBoxMax[i];
  58491. }
  58492. //The way the bounding box is extended onto the neighboring face
  58493. // depends on which edge of neighboring face abuts with this one
  58494. switch (PMREMGenerator._sgCubeNgh[faceIdx][i][1]) {
  58495. case PMREMGenerator.CP_EDGE_LEFT:
  58496. filterExtents[neighborFace].augment(0, bleedOverBBoxMin[i], 0);
  58497. filterExtents[neighborFace].augment(bleedOverAmount[i], bleedOverBBoxMax[i], 0);
  58498. break;
  58499. case PMREMGenerator.CP_EDGE_RIGHT:
  58500. filterExtents[neighborFace].augment((srcSize - 1), bleedOverBBoxMin[i], 0);
  58501. filterExtents[neighborFace].augment((srcSize - 1) - bleedOverAmount[i], bleedOverBBoxMax[i], 0);
  58502. break;
  58503. case PMREMGenerator.CP_EDGE_TOP:
  58504. filterExtents[neighborFace].augment(bleedOverBBoxMin[i], 0, 0);
  58505. filterExtents[neighborFace].augment(bleedOverBBoxMax[i], bleedOverAmount[i], 0);
  58506. break;
  58507. case PMREMGenerator.CP_EDGE_BOTTOM:
  58508. filterExtents[neighborFace].augment(bleedOverBBoxMin[i], (srcSize - 1), 0);
  58509. filterExtents[neighborFace].augment(bleedOverBBoxMax[i], (srcSize - 1) - bleedOverAmount[i], 0);
  58510. break;
  58511. }
  58512. //clamp filter extents in non-center tap faces to remain within surface
  58513. filterExtents[neighborFace].clampMin(0, 0, 0);
  58514. filterExtents[neighborFace].clampMax(srcSize - 1, srcSize - 1, 0);
  58515. }
  58516. //If the bleed over amount bleeds past the adjacent face onto the opposite face
  58517. // from the center tap face, then process the opposite face entirely for now.
  58518. //Note that the cases in which this happens, what usually happens is that
  58519. // more than one edge bleeds onto the opposite face, and the bounding box
  58520. // encompasses the entire cube map face.
  58521. if (bleedOverAmount[i] > srcSize) {
  58522. //determine opposite face
  58523. switch (faceIdx) {
  58524. case PMREMGenerator.CP_FACE_X_POS:
  58525. oppositeFaceIdx = PMREMGenerator.CP_FACE_X_NEG;
  58526. break;
  58527. case PMREMGenerator.CP_FACE_X_NEG:
  58528. oppositeFaceIdx = PMREMGenerator.CP_FACE_X_POS;
  58529. break;
  58530. case PMREMGenerator.CP_FACE_Y_POS:
  58531. oppositeFaceIdx = PMREMGenerator.CP_FACE_Y_NEG;
  58532. break;
  58533. case PMREMGenerator.CP_FACE_Y_NEG:
  58534. oppositeFaceIdx = PMREMGenerator.CP_FACE_Y_POS;
  58535. break;
  58536. case PMREMGenerator.CP_FACE_Z_POS:
  58537. oppositeFaceIdx = PMREMGenerator.CP_FACE_Z_NEG;
  58538. break;
  58539. case PMREMGenerator.CP_FACE_Z_NEG:
  58540. oppositeFaceIdx = PMREMGenerator.CP_FACE_Z_POS;
  58541. break;
  58542. default:
  58543. break;
  58544. }
  58545. //just encompass entire face for now
  58546. filterExtents[oppositeFaceIdx].augment(0, 0, 0);
  58547. filterExtents[oppositeFaceIdx].augment((srcSize - 1), (srcSize - 1), 0);
  58548. }
  58549. }
  58550. };
  58551. //--------------------------------------------------------------------------------------
  58552. //ProcessFilterExtents
  58553. // Process bounding box in each cube face
  58554. //
  58555. //--------------------------------------------------------------------------------------
  58556. PMREMGenerator.prototype.processFilterExtents = function (centerTapDir, dotProdThresh, filterExtents, srcCubeMap, srcSize, specularPower) {
  58557. //accumulators are 64-bit floats in order to have the precision needed
  58558. // over a summation of a large number of pixels
  58559. var dstAccum = [0, 0, 0, 0];
  58560. var weightAccum = 0;
  58561. var k = 0;
  58562. var nSrcChannels = this.numChannels;
  58563. // norm cube map and srcCubeMap have same face width
  58564. var faceWidth = srcSize;
  58565. //amount to add to pointer to move to next scanline in images
  58566. var normCubePitch = faceWidth * 4; // 4 channels in normCubeMap.
  58567. var srcCubePitch = faceWidth * this.numChannels; // numChannels correponds to the cubemap number of channel
  58568. var IsPhongBRDF = 1; // Only works in Phong BRDF yet.
  58569. //(a_LightingModel == CP_LIGHTINGMODEL_PHONG_BRDF || a_LightingModel == CP_LIGHTINGMODEL_BLINN_BRDF) ? 1 : 0; // This value will be added to the specular power
  58570. // iterate over cubefaces
  58571. for (var iFaceIdx = 0; iFaceIdx < 6; iFaceIdx++) {
  58572. //if bbox is non empty
  58573. if (!filterExtents[iFaceIdx].empty()) {
  58574. var uStart = filterExtents[iFaceIdx].min.x;
  58575. var vStart = filterExtents[iFaceIdx].min.y;
  58576. var uEnd = filterExtents[iFaceIdx].max.x;
  58577. var vEnd = filterExtents[iFaceIdx].max.y;
  58578. var startIndexNormCubeMap = (4 * ((vStart * faceWidth) + uStart));
  58579. var startIndexSrcCubeMap = (this.numChannels * ((vStart * faceWidth) + uStart));
  58580. //note that <= is used to ensure filter extents always encompass at least one pixel if bbox is non empty
  58581. for (var v = vStart; v <= vEnd; v++) {
  58582. var normCubeRowWalk = 0;
  58583. var srcCubeRowWalk = 0;
  58584. for (var u = uStart; u <= uEnd; u++) {
  58585. //pointer to direction in cube map associated with texel
  58586. var texelVectX = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 0];
  58587. var texelVectY = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 1];
  58588. var texelVectZ = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 2];
  58589. //check dot product to see if texel is within cone
  58590. var tapDotProd = texelVectX * centerTapDir.x +
  58591. texelVectY * centerTapDir.y +
  58592. texelVectZ * centerTapDir.z;
  58593. if (tapDotProd >= dotProdThresh && tapDotProd > 0.0) {
  58594. //solid angle stored in 4th channel of normalizer/solid angle cube map
  58595. var weight = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 3];
  58596. // Here we decide if we use a Phong/Blinn or a Phong/Blinn BRDF.
  58597. // Phong/Blinn BRDF is just the Phong/Blinn model multiply by the cosine of the lambert law
  58598. // so just adding one to specularpower do the trick.
  58599. weight *= Math.pow(tapDotProd, (specularPower + IsPhongBRDF));
  58600. //iterate over channels
  58601. for (k = 0; k < nSrcChannels; k++) {
  58602. dstAccum[k] += weight * srcCubeMap[iFaceIdx][startIndexSrcCubeMap + srcCubeRowWalk];
  58603. srcCubeRowWalk++;
  58604. }
  58605. weightAccum += weight; //accumulate weight
  58606. }
  58607. else {
  58608. //step across source pixel
  58609. srcCubeRowWalk += nSrcChannels;
  58610. }
  58611. normCubeRowWalk += 4; // 4 channels per norm cube map.
  58612. }
  58613. startIndexNormCubeMap += normCubePitch;
  58614. startIndexSrcCubeMap += srcCubePitch;
  58615. }
  58616. }
  58617. }
  58618. //divide through by weights if weight is non zero
  58619. if (weightAccum != 0.0) {
  58620. PMREMGenerator._vectorTemp.x = (dstAccum[0] / weightAccum);
  58621. PMREMGenerator._vectorTemp.y = (dstAccum[1] / weightAccum);
  58622. PMREMGenerator._vectorTemp.z = (dstAccum[2] / weightAccum);
  58623. if (this.numChannels > 3) {
  58624. PMREMGenerator._vectorTemp.w = (dstAccum[3] / weightAccum);
  58625. }
  58626. }
  58627. else {
  58628. // otherwise sample nearest
  58629. // get face idx and u, v texel coordinate in face
  58630. var coord = this.vectToTexelCoord(centerTapDir.x, centerTapDir.y, centerTapDir.z, srcSize).clone();
  58631. PMREMGenerator._vectorTemp.x = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 0];
  58632. PMREMGenerator._vectorTemp.y = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 1];
  58633. PMREMGenerator._vectorTemp.z = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 2];
  58634. if (this.numChannels > 3) {
  58635. PMREMGenerator._vectorTemp.z = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 3];
  58636. }
  58637. }
  58638. return PMREMGenerator._vectorTemp;
  58639. };
  58640. //--------------------------------------------------------------------------------------
  58641. // Fixup cube edges
  58642. //
  58643. // average texels on cube map faces across the edges
  58644. // WARP/BENT Method Only.
  58645. //--------------------------------------------------------------------------------------
  58646. PMREMGenerator.prototype.fixupCubeEdges = function (cubeMap, cubeMapSize) {
  58647. var k;
  58648. var j;
  58649. var i;
  58650. var iFace;
  58651. var iCorner = 0;
  58652. var cornerNumPtrs = [0, 0, 0, 0, 0, 0, 0, 0]; //indexed by corner and face idx
  58653. var faceCornerStartIndicies = [[], [], [], []]; //corner pointers for face keeping track of the face they belong to.
  58654. // note that if functionality to filter across the three texels for each corner, then
  58655. //indexed by corner and face idx. the array contains the face the start points belongs to.
  58656. var cornerPtr = [
  58657. [[], [], []],
  58658. [[], [], []],
  58659. [[], [], []],
  58660. [[], [], []],
  58661. [[], [], []],
  58662. [[], [], []],
  58663. [[], [], []],
  58664. [[], [], []]
  58665. ];
  58666. //if there is no fixup, or fixup width = 0, do nothing
  58667. if (cubeMapSize < 1) {
  58668. return;
  58669. }
  58670. //special case 1x1 cubemap, average face colors
  58671. if (cubeMapSize == 1) {
  58672. //iterate over channels
  58673. for (k = 0; k < this.numChannels; k++) {
  58674. var accum = 0.0;
  58675. //iterate over faces to accumulate face colors
  58676. for (iFace = 0; iFace < 6; iFace++) {
  58677. accum += cubeMap[iFace][k];
  58678. }
  58679. //compute average over 6 face colors
  58680. accum /= 6.0;
  58681. //iterate over faces to distribute face colors
  58682. for (iFace = 0; iFace < 6; iFace++) {
  58683. cubeMap[iFace][k] = accum;
  58684. }
  58685. }
  58686. return;
  58687. }
  58688. //iterate over faces to collect list of corner texel pointers
  58689. for (iFace = 0; iFace < 6; iFace++) {
  58690. //the 4 corner pointers for this face
  58691. faceCornerStartIndicies[0] = [iFace, 0];
  58692. faceCornerStartIndicies[1] = [iFace, ((cubeMapSize - 1) * this.numChannels)];
  58693. faceCornerStartIndicies[2] = [iFace, ((cubeMapSize) * (cubeMapSize - 1) * this.numChannels)];
  58694. faceCornerStartIndicies[3] = [iFace, ((((cubeMapSize) * (cubeMapSize - 1)) + (cubeMapSize - 1)) * this.numChannels)];
  58695. //iterate over face corners to collect cube corner pointers
  58696. for (iCorner = 0; iCorner < 4; iCorner++) {
  58697. var corner = PMREMGenerator._sgCubeCornerList[iFace][iCorner];
  58698. cornerPtr[corner][cornerNumPtrs[corner]] = faceCornerStartIndicies[iCorner];
  58699. cornerNumPtrs[corner]++;
  58700. }
  58701. }
  58702. //iterate over corners to average across corner tap values
  58703. for (iCorner = 0; iCorner < 8; iCorner++) {
  58704. for (k = 0; k < this.numChannels; k++) {
  58705. var cornerTapAccum = 0.0;
  58706. //iterate over corner texels and average results
  58707. for (i = 0; i < 3; i++) {
  58708. cornerTapAccum += cubeMap[cornerPtr[iCorner][i][0]][cornerPtr[iCorner][i][1] + k]; // Get in the cube map face the start point + channel.
  58709. }
  58710. //divide by 3 to compute average of corner tap values
  58711. cornerTapAccum *= (1.0 / 3.0);
  58712. //iterate over corner texels and average results
  58713. for (i = 0; i < 3; i++) {
  58714. cubeMap[cornerPtr[iCorner][i][0]][cornerPtr[iCorner][i][1] + k] = cornerTapAccum;
  58715. }
  58716. }
  58717. }
  58718. //iterate over the twelve edges of the cube to average across edges
  58719. for (i = 0; i < 12; i++) {
  58720. var face = PMREMGenerator._sgCubeEdgeList[i][0];
  58721. var edge = PMREMGenerator._sgCubeEdgeList[i][1];
  58722. var neighborFace = PMREMGenerator._sgCubeNgh[face][edge][0];
  58723. var neighborEdge = PMREMGenerator._sgCubeNgh[face][edge][1];
  58724. var edgeStartIndex = 0; // a_CubeMap[face].m_ImgData;
  58725. var neighborEdgeStartIndex = 0; // a_CubeMap[neighborFace].m_ImgData;
  58726. var edgeWalk = 0;
  58727. var neighborEdgeWalk = 0;
  58728. //Determine walking pointers based on edge type
  58729. // e.g. CP_EDGE_LEFT, CP_EDGE_RIGHT, CP_EDGE_TOP, CP_EDGE_BOTTOM
  58730. switch (edge) {
  58731. case PMREMGenerator.CP_EDGE_LEFT:
  58732. // no change to faceEdgeStartPtr
  58733. edgeWalk = this.numChannels * cubeMapSize;
  58734. break;
  58735. case PMREMGenerator.CP_EDGE_RIGHT:
  58736. edgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  58737. edgeWalk = this.numChannels * cubeMapSize;
  58738. break;
  58739. case PMREMGenerator.CP_EDGE_TOP:
  58740. // no change to faceEdgeStartPtr
  58741. edgeWalk = this.numChannels;
  58742. break;
  58743. case PMREMGenerator.CP_EDGE_BOTTOM:
  58744. edgeStartIndex += (cubeMapSize) * (cubeMapSize - 1) * this.numChannels;
  58745. edgeWalk = this.numChannels;
  58746. break;
  58747. }
  58748. //For certain types of edge abutments, the neighbor edge walk needs to
  58749. // be flipped: the cases are
  58750. // if a left edge mates with a left or bottom edge on the neighbor
  58751. // if a top edge mates with a top or right edge on the neighbor
  58752. // if a right edge mates with a right or top edge on the neighbor
  58753. // if a bottom edge mates with a bottom or left edge on the neighbor
  58754. //Seeing as the edges are enumerated as follows
  58755. // left =0
  58756. // right =1
  58757. // top =2
  58758. // bottom =3
  58759. //
  58760. //If the edge enums are the same, or the sum of the enums == 3,
  58761. // the neighbor edge walk needs to be flipped
  58762. if ((edge == neighborEdge) || ((edge + neighborEdge) == 3)) {
  58763. switch (neighborEdge) {
  58764. case PMREMGenerator.CP_EDGE_LEFT:
  58765. neighborEdgeStartIndex += (cubeMapSize - 1) * (cubeMapSize) * this.numChannels;
  58766. neighborEdgeWalk = -(this.numChannels * cubeMapSize);
  58767. break;
  58768. case PMREMGenerator.CP_EDGE_RIGHT:
  58769. neighborEdgeStartIndex += ((cubeMapSize - 1) * (cubeMapSize) + (cubeMapSize - 1)) * this.numChannels;
  58770. neighborEdgeWalk = -(this.numChannels * cubeMapSize);
  58771. break;
  58772. case PMREMGenerator.CP_EDGE_TOP:
  58773. neighborEdgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  58774. neighborEdgeWalk = -this.numChannels;
  58775. break;
  58776. case PMREMGenerator.CP_EDGE_BOTTOM:
  58777. neighborEdgeStartIndex += ((cubeMapSize - 1) * (cubeMapSize) + (cubeMapSize - 1)) * this.numChannels;
  58778. neighborEdgeWalk = -this.numChannels;
  58779. break;
  58780. }
  58781. }
  58782. else {
  58783. //swapped direction neighbor edge walk
  58784. switch (neighborEdge) {
  58785. case PMREMGenerator.CP_EDGE_LEFT:
  58786. //no change to neighborEdgeStartPtr for this case since it points
  58787. // to the upper left corner already
  58788. neighborEdgeWalk = this.numChannels * cubeMapSize;
  58789. break;
  58790. case PMREMGenerator.CP_EDGE_RIGHT:
  58791. neighborEdgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  58792. neighborEdgeWalk = this.numChannels * cubeMapSize;
  58793. break;
  58794. case PMREMGenerator.CP_EDGE_TOP:
  58795. //no change to neighborEdgeStartPtr for this case since it points
  58796. // to the upper left corner already
  58797. neighborEdgeWalk = this.numChannels;
  58798. break;
  58799. case PMREMGenerator.CP_EDGE_BOTTOM:
  58800. neighborEdgeStartIndex += (cubeMapSize) * (cubeMapSize - 1) * this.numChannels;
  58801. neighborEdgeWalk = this.numChannels;
  58802. break;
  58803. }
  58804. }
  58805. //Perform edge walk, to average across the 12 edges and smoothly propagate change to
  58806. //nearby neighborhood
  58807. //step ahead one texel on edge
  58808. edgeStartIndex += edgeWalk;
  58809. neighborEdgeStartIndex += neighborEdgeWalk;
  58810. // note that this loop does not process the corner texels, since they have already been
  58811. // averaged across faces across earlier
  58812. for (j = 1; j < (cubeMapSize - 1); j++) {
  58813. //for each set of taps along edge, average them
  58814. // and rewrite the results into the edges
  58815. for (k = 0; k < this.numChannels; k++) {
  58816. var edgeTap = cubeMap[face][edgeStartIndex + k];
  58817. var neighborEdgeTap = cubeMap[neighborFace][neighborEdgeStartIndex + k];
  58818. //compute average of tap intensity values
  58819. var avgTap = 0.5 * (edgeTap + neighborEdgeTap);
  58820. //propagate average of taps to edge taps
  58821. cubeMap[face][edgeStartIndex + k] = avgTap;
  58822. cubeMap[neighborFace][neighborEdgeStartIndex + k] = avgTap;
  58823. }
  58824. edgeStartIndex += edgeWalk;
  58825. neighborEdgeStartIndex += neighborEdgeWalk;
  58826. }
  58827. }
  58828. };
  58829. PMREMGenerator.CP_MAX_MIPLEVELS = 16;
  58830. PMREMGenerator.CP_UDIR = 0;
  58831. PMREMGenerator.CP_VDIR = 1;
  58832. PMREMGenerator.CP_FACEAXIS = 2;
  58833. //used to index cube faces
  58834. PMREMGenerator.CP_FACE_X_POS = 0;
  58835. PMREMGenerator.CP_FACE_X_NEG = 1;
  58836. PMREMGenerator.CP_FACE_Y_POS = 2;
  58837. PMREMGenerator.CP_FACE_Y_NEG = 3;
  58838. PMREMGenerator.CP_FACE_Z_POS = 4;
  58839. PMREMGenerator.CP_FACE_Z_NEG = 5;
  58840. //used to index image edges
  58841. // NOTE.. the actual number corresponding to the edge is important
  58842. // do not change these, or the code will break
  58843. //
  58844. // CP_EDGE_LEFT is u = 0
  58845. // CP_EDGE_RIGHT is u = width-1
  58846. // CP_EDGE_TOP is v = 0
  58847. // CP_EDGE_BOTTOM is v = height-1
  58848. PMREMGenerator.CP_EDGE_LEFT = 0;
  58849. PMREMGenerator.CP_EDGE_RIGHT = 1;
  58850. PMREMGenerator.CP_EDGE_TOP = 2;
  58851. PMREMGenerator.CP_EDGE_BOTTOM = 3;
  58852. //corners of CUBE map (P or N specifys if it corresponds to the
  58853. // positive or negative direction each of X, Y, and Z
  58854. PMREMGenerator.CP_CORNER_NNN = 0;
  58855. PMREMGenerator.CP_CORNER_NNP = 1;
  58856. PMREMGenerator.CP_CORNER_NPN = 2;
  58857. PMREMGenerator.CP_CORNER_NPP = 3;
  58858. PMREMGenerator.CP_CORNER_PNN = 4;
  58859. PMREMGenerator.CP_CORNER_PNP = 5;
  58860. PMREMGenerator.CP_CORNER_PPN = 6;
  58861. PMREMGenerator.CP_CORNER_PPP = 7;
  58862. PMREMGenerator._vectorTemp = new BABYLON.Vector4(0, 0, 0, 0);
  58863. //3x2 matrices that map cube map indexing vectors in 3d
  58864. // (after face selection and divide through by the
  58865. // _ABSOLUTE VALUE_ of the max coord)
  58866. // into NVC space
  58867. //Note this currently assumes the D3D cube face ordering and orientation
  58868. PMREMGenerator._sgFace2DMapping = [
  58869. //XPOS face
  58870. [[0, 0, -1],
  58871. [0, -1, 0],
  58872. [1, 0, 0]],
  58873. //XNEG face
  58874. [[0, 0, 1],
  58875. [0, -1, 0],
  58876. [-1, 0, 0]],
  58877. //YPOS face
  58878. [[1, 0, 0],
  58879. [0, 0, 1],
  58880. [0, 1, 0]],
  58881. //YNEG face
  58882. [[1, 0, 0],
  58883. [0, 0, -1],
  58884. [0, -1, 0]],
  58885. //ZPOS face
  58886. [[1, 0, 0],
  58887. [0, -1, 0],
  58888. [0, 0, 1]],
  58889. //ZNEG face
  58890. [[-1, 0, 0],
  58891. [0, -1, 0],
  58892. [0, 0, -1]],
  58893. ];
  58894. //------------------------------------------------------------------------------
  58895. // D3D cube map face specification
  58896. // mapping from 3D x,y,z cube map lookup coordinates
  58897. // to 2D within face u,v coordinates
  58898. //
  58899. // --------------------> U direction
  58900. // | (within-face texture space)
  58901. // | _____
  58902. // | | |
  58903. // | | +Y |
  58904. // | _____|_____|_____ _____
  58905. // | | | | | |
  58906. // | | -X | +Z | +X | -Z |
  58907. // | |_____|_____|_____|_____|
  58908. // | | |
  58909. // | | -Y |
  58910. // | |_____|
  58911. // |
  58912. // v V direction
  58913. // (within-face texture space)
  58914. //------------------------------------------------------------------------------
  58915. //Information about neighbors and how texture coorrdinates change across faces
  58916. // in ORDER of left, right, top, bottom (e.g. edges corresponding to u=0,
  58917. // u=1, v=0, v=1 in the 2D coordinate system of the particular face.
  58918. //Note this currently assumes the D3D cube face ordering and orientation
  58919. PMREMGenerator._sgCubeNgh = [
  58920. //XPOS face
  58921. [[PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_RIGHT],
  58922. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_LEFT],
  58923. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_RIGHT],
  58924. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_RIGHT]],
  58925. //XNEG face
  58926. [[PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  58927. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_LEFT],
  58928. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_LEFT],
  58929. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_LEFT]],
  58930. //YPOS face
  58931. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_TOP],
  58932. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_TOP],
  58933. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_TOP],
  58934. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_TOP]],
  58935. //YNEG face
  58936. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_BOTTOM],
  58937. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  58938. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  58939. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_BOTTOM]],
  58940. //ZPOS face
  58941. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  58942. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_LEFT],
  58943. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  58944. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_TOP]],
  58945. //ZNEG face
  58946. [[PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_RIGHT],
  58947. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_LEFT],
  58948. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_TOP],
  58949. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_BOTTOM]]
  58950. ];
  58951. //The 12 edges of the cubemap, (entries are used to index into the neighbor table)
  58952. // this table is used to average over the edges.
  58953. PMREMGenerator._sgCubeEdgeList = [
  58954. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_LEFT],
  58955. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_RIGHT],
  58956. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_TOP],
  58957. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  58958. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_LEFT],
  58959. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  58960. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_TOP],
  58961. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_BOTTOM],
  58962. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_TOP],
  58963. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  58964. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_TOP],
  58965. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_BOTTOM]
  58966. ];
  58967. //Information about which of the 8 cube corners are correspond to the
  58968. // the 4 corners in each cube face
  58969. // the order is upper left, upper right, lower left, lower right
  58970. PMREMGenerator._sgCubeCornerList = [
  58971. [PMREMGenerator.CP_CORNER_PPP, PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_PNP, PMREMGenerator.CP_CORNER_PNN],
  58972. [PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_NNN, PMREMGenerator.CP_CORNER_NNP],
  58973. [PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_PPP],
  58974. [PMREMGenerator.CP_CORNER_NNP, PMREMGenerator.CP_CORNER_PNP, PMREMGenerator.CP_CORNER_NNN, PMREMGenerator.CP_CORNER_PNN],
  58975. [PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_PPP, PMREMGenerator.CP_CORNER_NNP, PMREMGenerator.CP_CORNER_PNP],
  58976. [PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_PNN, PMREMGenerator.CP_CORNER_NNN] // ZNEG face
  58977. ];
  58978. return PMREMGenerator;
  58979. })();
  58980. Internals.PMREMGenerator = PMREMGenerator;
  58981. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  58982. })(BABYLON || (BABYLON = {}));
  58983. var BABYLON;
  58984. (function (BABYLON) {
  58985. /**
  58986. * This represents a texture coming from an HDR input.
  58987. *
  58988. * The only supported format is currently panorama picture stored in RGBE format.
  58989. * Example of such files can be found on HDRLib: http://hdrlib.com/
  58990. */
  58991. var HDRCubeTexture = (function (_super) {
  58992. __extends(HDRCubeTexture, _super);
  58993. /**
  58994. * Instantiates an HDRTexture from the following parameters.
  58995. *
  58996. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  58997. * @param scene The scene the texture will be used in
  58998. * @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.
  58999. * @param noMipmap Forces to not generate the mipmap if true
  59000. * @param generateHarmonics Specifies wether you want to extract the polynomial harmonics during the generation process
  59001. * @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)
  59002. * @param usePMREMGenerator Specifies wether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  59003. */
  59004. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  59005. if (noMipmap === void 0) { noMipmap = false; }
  59006. if (generateHarmonics === void 0) { generateHarmonics = true; }
  59007. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  59008. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  59009. _super.call(this, scene);
  59010. this._useInGammaSpace = false;
  59011. this._generateHarmonics = true;
  59012. this._isBABYLONPreprocessed = false;
  59013. /**
  59014. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  59015. */
  59016. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  59017. /**
  59018. * The spherical polynomial data extracted from the texture.
  59019. */
  59020. this.sphericalPolynomial = null;
  59021. /**
  59022. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  59023. * This is usefull at run time to apply the good shader.
  59024. */
  59025. this.isPMREM = false;
  59026. if (!url) {
  59027. return;
  59028. }
  59029. this.name = url;
  59030. this.url = url;
  59031. this.hasAlpha = false;
  59032. this.isCube = true;
  59033. this._textureMatrix = BABYLON.Matrix.Identity();
  59034. if (size) {
  59035. this._isBABYLONPreprocessed = false;
  59036. this._noMipmap = noMipmap;
  59037. this._size = size;
  59038. this._useInGammaSpace = useInGammaSpace;
  59039. this._usePMREMGenerator = usePMREMGenerator &&
  59040. scene.getEngine().getCaps().textureLOD &&
  59041. this.getScene().getEngine().getCaps().textureFloat &&
  59042. !this._useInGammaSpace;
  59043. }
  59044. else {
  59045. this._isBABYLONPreprocessed = true;
  59046. this._noMipmap = false;
  59047. this._useInGammaSpace = false;
  59048. this._usePMREMGenerator = scene.getEngine().getCaps().textureLOD &&
  59049. this.getScene().getEngine().getCaps().textureFloat &&
  59050. !this._useInGammaSpace;
  59051. }
  59052. this.isPMREM = this._usePMREMGenerator;
  59053. this._texture = this._getFromCache(url, this._noMipmap);
  59054. if (!this._texture) {
  59055. if (!scene.useDelayedTextureLoading) {
  59056. this.loadTexture();
  59057. }
  59058. else {
  59059. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  59060. }
  59061. }
  59062. }
  59063. /**
  59064. * Occurs when the file is a preprocessed .babylon.hdr file.
  59065. */
  59066. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  59067. var _this = this;
  59068. var mipLevels = 0;
  59069. var floatArrayView = null;
  59070. var mipmapGenerator = (!this._useInGammaSpace && this.getScene().getEngine().getCaps().textureFloat) ? function (data) {
  59071. var mips = [];
  59072. var startIndex = 30;
  59073. for (var level = 0; level < mipLevels; level++) {
  59074. mips.push([]);
  59075. // Fill each pixel of the mip level.
  59076. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  59077. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  59078. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  59079. mips[level].push(faceData);
  59080. startIndex += faceSize;
  59081. }
  59082. }
  59083. return mips;
  59084. } : null;
  59085. var callback = function (buffer) {
  59086. // Create Native Array Views
  59087. var intArrayView = new Int32Array(buffer);
  59088. floatArrayView = new Float32Array(buffer);
  59089. // Fill header.
  59090. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  59091. _this._size = intArrayView[1]; // CubeMap max mip face size.
  59092. // Update Texture Information.
  59093. _this.getScene().getEngine().updateTextureSize(_this._texture, _this._size, _this._size);
  59094. // Fill polynomial information.
  59095. _this.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  59096. _this.sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  59097. _this.sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  59098. _this.sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  59099. _this.sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  59100. _this.sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  59101. _this.sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  59102. _this.sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  59103. _this.sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  59104. _this.sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  59105. // Fill pixel data.
  59106. mipLevels = intArrayView[29]; // Number of mip levels.
  59107. var startIndex = 30;
  59108. var data = [];
  59109. var faceSize = Math.pow(_this._size, 2) * 3;
  59110. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  59111. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  59112. startIndex += faceSize;
  59113. }
  59114. var results = [];
  59115. var byteArray = null;
  59116. // Push each faces.
  59117. for (var k = 0; k < 6; k++) {
  59118. var dataFace = null;
  59119. // If special cases.
  59120. if (!mipmapGenerator) {
  59121. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y... if no mipmapgenerator...
  59122. dataFace = data[j];
  59123. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  59124. // 3 channels of 1 bytes per pixel in bytes.
  59125. var byteBuffer = new ArrayBuffer(faceSize);
  59126. byteArray = new Uint8Array(byteBuffer);
  59127. }
  59128. for (var i = 0; i < _this._size * _this._size; i++) {
  59129. // Put in gamma space if requested.
  59130. if (_this._useInGammaSpace) {
  59131. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  59132. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  59133. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  59134. }
  59135. // Convert to int texture for fallback.
  59136. if (byteArray) {
  59137. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  59138. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  59139. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  59140. // May use luminance instead if the result is not accurate.
  59141. var max = Math.max(Math.max(r, g), b);
  59142. if (max > 255) {
  59143. var scale = 255 / max;
  59144. r *= scale;
  59145. g *= scale;
  59146. b *= scale;
  59147. }
  59148. byteArray[(i * 3) + 0] = r;
  59149. byteArray[(i * 3) + 1] = g;
  59150. byteArray[(i * 3) + 2] = b;
  59151. }
  59152. }
  59153. }
  59154. else {
  59155. dataFace = data[k];
  59156. }
  59157. // Fill the array accordingly.
  59158. if (byteArray) {
  59159. results.push(byteArray);
  59160. }
  59161. else {
  59162. results.push(dataFace);
  59163. }
  59164. }
  59165. return results;
  59166. };
  59167. 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);
  59168. };
  59169. /**
  59170. * Occurs when the file is raw .hdr file.
  59171. */
  59172. HDRCubeTexture.prototype.loadHDRTexture = function () {
  59173. var _this = this;
  59174. var callback = function (buffer) {
  59175. // Extract the raw linear data.
  59176. var data = BABYLON.Internals.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  59177. // Generate harmonics if needed.
  59178. if (_this._generateHarmonics) {
  59179. _this.sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  59180. }
  59181. var results = [];
  59182. var byteArray = null;
  59183. // Push each faces.
  59184. for (var j = 0; j < 6; j++) {
  59185. // Create uintarray fallback.
  59186. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  59187. // 3 channels of 1 bytes per pixel in bytes.
  59188. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  59189. byteArray = new Uint8Array(byteBuffer);
  59190. }
  59191. var dataFace = data[HDRCubeTexture._facesMapping[j]];
  59192. // If special cases.
  59193. if (_this._useInGammaSpace || byteArray) {
  59194. for (var i = 0; i < _this._size * _this._size; i++) {
  59195. // Put in gamma space if requested.
  59196. if (_this._useInGammaSpace) {
  59197. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  59198. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  59199. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  59200. }
  59201. // Convert to int texture for fallback.
  59202. if (byteArray) {
  59203. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  59204. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  59205. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  59206. // May use luminance instead if the result is not accurate.
  59207. var max = Math.max(Math.max(r, g), b);
  59208. if (max > 255) {
  59209. var scale = 255 / max;
  59210. r *= scale;
  59211. g *= scale;
  59212. b *= scale;
  59213. }
  59214. byteArray[(i * 3) + 0] = r;
  59215. byteArray[(i * 3) + 1] = g;
  59216. byteArray[(i * 3) + 2] = b;
  59217. }
  59218. }
  59219. }
  59220. if (byteArray) {
  59221. results.push(byteArray);
  59222. }
  59223. else {
  59224. results.push(dataFace);
  59225. }
  59226. }
  59227. return results;
  59228. };
  59229. var mipmapGenerator = null;
  59230. if (!this._noMipmap &&
  59231. this._usePMREMGenerator) {
  59232. mipmapGenerator = function (data) {
  59233. // Custom setup of the generator matching with the PBR shader values.
  59234. var generator = new BABYLON.Internals.PMREMGenerator(data, _this._size, _this._size, 0, 3, _this.getScene().getEngine().getCaps().textureFloat, 2048, 0.25, false, true);
  59235. return generator.filterCubeMap();
  59236. };
  59237. }
  59238. 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);
  59239. };
  59240. /**
  59241. * Starts the loading process of the texture.
  59242. */
  59243. HDRCubeTexture.prototype.loadTexture = function () {
  59244. if (this._isBABYLONPreprocessed) {
  59245. this.loadBabylonTexture();
  59246. }
  59247. else {
  59248. this.loadHDRTexture();
  59249. }
  59250. };
  59251. HDRCubeTexture.prototype.clone = function () {
  59252. var size = this._isBABYLONPreprocessed ? null : this._size;
  59253. var newTexture = new HDRCubeTexture(this.url, this.getScene(), size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  59254. // Base texture
  59255. newTexture.level = this.level;
  59256. newTexture.wrapU = this.wrapU;
  59257. newTexture.wrapV = this.wrapV;
  59258. newTexture.coordinatesIndex = this.coordinatesIndex;
  59259. newTexture.coordinatesMode = this.coordinatesMode;
  59260. return newTexture;
  59261. };
  59262. // Methods
  59263. HDRCubeTexture.prototype.delayLoad = function () {
  59264. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  59265. return;
  59266. }
  59267. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  59268. this._texture = this._getFromCache(this.url, this._noMipmap);
  59269. if (!this._texture) {
  59270. this.loadTexture();
  59271. }
  59272. };
  59273. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  59274. return this._textureMatrix;
  59275. };
  59276. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  59277. var texture = null;
  59278. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  59279. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  59280. texture = new BABYLON.HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, texture.generateHarmonics, texture.useInGammaSpace, texture.usePMREMGenerator);
  59281. texture.name = parsedTexture.name;
  59282. texture.hasAlpha = parsedTexture.hasAlpha;
  59283. texture.level = parsedTexture.level;
  59284. texture.coordinatesMode = parsedTexture.coordinatesMode;
  59285. }
  59286. return texture;
  59287. };
  59288. HDRCubeTexture.prototype.serialize = function () {
  59289. if (!this.name) {
  59290. return null;
  59291. }
  59292. var serializationObject = {};
  59293. serializationObject.name = this.name;
  59294. serializationObject.hasAlpha = this.hasAlpha;
  59295. serializationObject.isCube = true;
  59296. serializationObject.level = this.level;
  59297. serializationObject.size = this._size;
  59298. serializationObject.coordinatesMode = this.coordinatesMode;
  59299. serializationObject.useInGammaSpace = this._useInGammaSpace;
  59300. serializationObject.generateHarmonics = this._generateHarmonics;
  59301. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  59302. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  59303. serializationObject.customType = "BABYLON.HDRCubeTexture";
  59304. return serializationObject;
  59305. };
  59306. /**
  59307. * Saves as a file the data contained in the texture in a binary format.
  59308. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  59309. * as the spherical used in the lighting.
  59310. * @param url The HDR file url.
  59311. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  59312. * @param onError Method called if any error happens during download.
  59313. * @return The packed binary data.
  59314. */
  59315. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  59316. if (onError === void 0) { onError = null; }
  59317. var callback = function (buffer) {
  59318. var data = new Blob([buffer], { type: 'application/octet-stream' });
  59319. // Returns a URL you can use as a href.
  59320. var objUrl = window.URL.createObjectURL(data);
  59321. // Simulates a link to it and click to dowload.
  59322. var a = document.createElement("a");
  59323. document.body.appendChild(a);
  59324. a.style.display = "none";
  59325. a.href = objUrl;
  59326. a.download = "envmap.babylon.hdr";
  59327. a.click();
  59328. };
  59329. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  59330. };
  59331. /**
  59332. * Serializes the data contained in the texture in a binary format.
  59333. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  59334. * as the spherical used in the lighting.
  59335. * @param url The HDR file url.
  59336. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  59337. * @param onError Method called if any error happens during download.
  59338. * @return The packed binary data.
  59339. */
  59340. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  59341. if (onError === void 0) { onError = null; }
  59342. // Needs the url tho create the texture.
  59343. if (!url) {
  59344. return null;
  59345. }
  59346. // Check Power of two size.
  59347. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  59348. return null;
  59349. }
  59350. var getDataCallback = function (dataBuffer) {
  59351. // Extract the raw linear data.
  59352. var cubeData = BABYLON.Internals.HDRTools.GetCubeMapTextureData(dataBuffer, size);
  59353. // Generate harmonics if needed.
  59354. var sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(cubeData);
  59355. // Generate seamless faces
  59356. var mipGeneratorArray = [];
  59357. // Data are known to be in +X +Y +Z -X -Y -Z
  59358. // mipmmapGenerator data is expected to be order in +X -X +Y -Y +Z -Z
  59359. mipGeneratorArray.push(cubeData.right); // +X
  59360. mipGeneratorArray.push(cubeData.left); // -X
  59361. mipGeneratorArray.push(cubeData.up); // +Y
  59362. mipGeneratorArray.push(cubeData.down); // -Y
  59363. mipGeneratorArray.push(cubeData.front); // +Z
  59364. mipGeneratorArray.push(cubeData.back); // -Z
  59365. // Custom setup of the generator matching with the PBR shader values.
  59366. var generator = new BABYLON.Internals.PMREMGenerator(mipGeneratorArray, size, size, 0, 3, true, 2048, 0.25, false, true);
  59367. var mippedData = generator.filterCubeMap();
  59368. // Compute required byte length.
  59369. var byteLength = 1 * 4; // Raw Data Version int32.
  59370. byteLength += 4; // CubeMap max mip face size int32.
  59371. byteLength += (9 * 3 * 4); // Spherical polynomial byte length 9 Vector 3 of floats.
  59372. // Add data size.
  59373. byteLength += 4; // Number of mip levels int32.
  59374. for (var level = 0; level < mippedData.length; level++) {
  59375. var mipSize = size >> level;
  59376. byteLength += (6 * mipSize * mipSize * 3 * 4); // 6 faces of size squared rgb float pixels.
  59377. }
  59378. // Prepare binary structure.
  59379. var buffer = new ArrayBuffer(byteLength);
  59380. var intArrayView = new Int32Array(buffer);
  59381. var floatArrayView = new Float32Array(buffer);
  59382. // Fill header.
  59383. intArrayView[0] = 1; // Version 1.
  59384. intArrayView[1] = size; // CubeMap max mip face size.
  59385. // Fill polynomial information.
  59386. sphericalPolynomial.x.toArray(floatArrayView, 2);
  59387. sphericalPolynomial.y.toArray(floatArrayView, 5);
  59388. sphericalPolynomial.z.toArray(floatArrayView, 8);
  59389. sphericalPolynomial.xx.toArray(floatArrayView, 11);
  59390. sphericalPolynomial.yy.toArray(floatArrayView, 14);
  59391. sphericalPolynomial.zz.toArray(floatArrayView, 17);
  59392. sphericalPolynomial.xy.toArray(floatArrayView, 20);
  59393. sphericalPolynomial.yz.toArray(floatArrayView, 23);
  59394. sphericalPolynomial.zx.toArray(floatArrayView, 26);
  59395. // Fill pixel data.
  59396. intArrayView[29] = mippedData.length; // Number of mip levels.
  59397. var startIndex = 30;
  59398. for (var level = 0; level < mippedData.length; level++) {
  59399. // Fill each pixel of the mip level.
  59400. var faceSize = Math.pow(size >> level, 2) * 3;
  59401. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  59402. floatArrayView.set(mippedData[level][faceIndex], startIndex);
  59403. startIndex += faceSize;
  59404. }
  59405. }
  59406. // Callback.
  59407. callback(buffer);
  59408. };
  59409. // Download and process.
  59410. BABYLON.Tools.LoadFile(url, function (data) {
  59411. getDataCallback(data);
  59412. }, null, null, true, onError);
  59413. };
  59414. HDRCubeTexture._facesMapping = [
  59415. "right",
  59416. "up",
  59417. "front",
  59418. "left",
  59419. "down",
  59420. "back"
  59421. ];
  59422. return HDRCubeTexture;
  59423. })(BABYLON.BaseTexture);
  59424. BABYLON.HDRCubeTexture = HDRCubeTexture;
  59425. })(BABYLON || (BABYLON = {}));
  59426. var BABYLON;
  59427. (function (BABYLON) {
  59428. var Debug;
  59429. (function (Debug) {
  59430. /**
  59431. * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
  59432. */
  59433. var SkeletonViewer = (function () {
  59434. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  59435. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  59436. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  59437. this.skeleton = skeleton;
  59438. this.mesh = mesh;
  59439. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  59440. this.renderingGroupId = renderingGroupId;
  59441. this.color = BABYLON.Color3.White();
  59442. this._debugLines = [];
  59443. this._isEnabled = false;
  59444. this._scene = scene;
  59445. this.update();
  59446. this._renderFunction = this.update.bind(this);
  59447. }
  59448. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  59449. get: function () {
  59450. return this._isEnabled;
  59451. },
  59452. set: function (value) {
  59453. if (this._isEnabled === value) {
  59454. return;
  59455. }
  59456. this._isEnabled = value;
  59457. if (value) {
  59458. this._scene.registerBeforeRender(this._renderFunction);
  59459. }
  59460. else {
  59461. this._scene.unregisterBeforeRender(this._renderFunction);
  59462. }
  59463. },
  59464. enumerable: true,
  59465. configurable: true
  59466. });
  59467. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  59468. if (x === void 0) { x = 0; }
  59469. if (y === void 0) { y = 0; }
  59470. if (z === void 0) { z = 0; }
  59471. var tmat = BABYLON.Tmp.Matrix[0];
  59472. var parentBone = bone.getParent();
  59473. tmat.copyFrom(bone.getLocalMatrix());
  59474. if (x !== 0 || y !== 0 || z !== 0) {
  59475. var tmat2 = BABYLON.Tmp.Matrix[1];
  59476. BABYLON.Matrix.IdentityToRef(tmat2);
  59477. tmat2.m[12] = x;
  59478. tmat2.m[13] = y;
  59479. tmat2.m[14] = z;
  59480. tmat2.multiplyToRef(tmat, tmat);
  59481. }
  59482. if (parentBone) {
  59483. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  59484. }
  59485. tmat.multiplyToRef(meshMat, tmat);
  59486. position.x = tmat.m[12];
  59487. position.y = tmat.m[13];
  59488. position.z = tmat.m[14];
  59489. };
  59490. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  59491. var len = bones.length;
  59492. for (var i = 0; i < len; i++) {
  59493. var bone = bones[i];
  59494. var points = this._debugLines[i];
  59495. if (!points) {
  59496. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  59497. this._debugLines[i] = points;
  59498. }
  59499. this._getBonePosition(points[0], bone, meshMat);
  59500. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  59501. }
  59502. };
  59503. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  59504. var len = bones.length;
  59505. var boneNum = 0;
  59506. for (var i = len - 1; i >= 0; i--) {
  59507. var childBone = bones[i];
  59508. var parentBone = childBone.getParent();
  59509. if (!parentBone) {
  59510. continue;
  59511. }
  59512. var points = this._debugLines[boneNum];
  59513. if (!points) {
  59514. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  59515. this._debugLines[boneNum] = points;
  59516. }
  59517. this._getBonePosition(points[0], childBone, meshMat);
  59518. this._getBonePosition(points[1], parentBone, meshMat);
  59519. boneNum++;
  59520. }
  59521. };
  59522. SkeletonViewer.prototype.update = function () {
  59523. if (this.autoUpdateBonesMatrices) {
  59524. this._updateBoneMatrix(this.skeleton.bones[0]);
  59525. }
  59526. if (this.skeleton.bones[0].length === undefined) {
  59527. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  59528. }
  59529. else {
  59530. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  59531. }
  59532. if (!this._debugMesh) {
  59533. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true }, this._scene);
  59534. this._debugMesh.renderingGroupId = this.renderingGroupId;
  59535. }
  59536. else {
  59537. BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  59538. }
  59539. this._debugMesh.color = this.color;
  59540. };
  59541. SkeletonViewer.prototype._updateBoneMatrix = function (bone) {
  59542. if (bone.getParent()) {
  59543. bone.getLocalMatrix().multiplyToRef(bone.getParent().getAbsoluteTransform(), bone.getAbsoluteTransform());
  59544. }
  59545. var children = bone.children;
  59546. var len = children.length;
  59547. for (var i = 0; i < len; i++) {
  59548. this._updateBoneMatrix(children[i]);
  59549. }
  59550. };
  59551. SkeletonViewer.prototype.dispose = function () {
  59552. if (this._debugMesh) {
  59553. this.isEnabled = false;
  59554. this._debugMesh.dispose();
  59555. this._debugMesh = null;
  59556. }
  59557. };
  59558. return SkeletonViewer;
  59559. })();
  59560. Debug.SkeletonViewer = SkeletonViewer;
  59561. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  59562. })(BABYLON || (BABYLON = {}));
  59563. var BABYLON;
  59564. (function (BABYLON) {
  59565. /**
  59566. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  59567. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  59568. * 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;
  59569. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  59570. */
  59571. var ColorCurves = (function () {
  59572. function ColorCurves() {
  59573. this._dirty = true;
  59574. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  59575. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  59576. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  59577. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  59578. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  59579. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  59580. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  59581. this._globalHue = 30;
  59582. this._globalDensity = 0;
  59583. this._globalSaturation = 0;
  59584. this._globalExposure = 0;
  59585. this._highlightsHue = 30;
  59586. this._highlightsDensity = 0;
  59587. this._highlightsSaturation = 0;
  59588. this._highlightsExposure = 0;
  59589. this._midtonesHue = 30;
  59590. this._midtonesDensity = 0;
  59591. this._midtonesSaturation = 0;
  59592. this._midtonesExposure = 0;
  59593. this._shadowsHue = 30;
  59594. this._shadowsDensity = 0;
  59595. this._shadowsSaturation = 0;
  59596. this._shadowsExposure = 0;
  59597. }
  59598. Object.defineProperty(ColorCurves.prototype, "GlobalHue", {
  59599. /**
  59600. * Gets the global Hue value.
  59601. * 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).
  59602. */
  59603. get: function () {
  59604. return this._globalHue;
  59605. },
  59606. /**
  59607. * Sets the global Hue value.
  59608. * 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).
  59609. */
  59610. set: function (value) {
  59611. this._globalHue = value;
  59612. this._dirty = true;
  59613. },
  59614. enumerable: true,
  59615. configurable: true
  59616. });
  59617. Object.defineProperty(ColorCurves.prototype, "GlobalDensity", {
  59618. /**
  59619. * Gets the global Density value.
  59620. * 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.
  59621. * Values less than zero provide a filter of opposite hue.
  59622. */
  59623. get: function () {
  59624. return this._globalDensity;
  59625. },
  59626. /**
  59627. * Sets the global Density value.
  59628. * 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.
  59629. * Values less than zero provide a filter of opposite hue.
  59630. */
  59631. set: function (value) {
  59632. this._globalDensity = value;
  59633. this._dirty = true;
  59634. },
  59635. enumerable: true,
  59636. configurable: true
  59637. });
  59638. Object.defineProperty(ColorCurves.prototype, "GlobalSaturation", {
  59639. /**
  59640. * Gets the global Saturation value.
  59641. * 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.
  59642. */
  59643. get: function () {
  59644. return this._globalSaturation;
  59645. },
  59646. /**
  59647. * Sets the global Saturation value.
  59648. * 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.
  59649. */
  59650. set: function (value) {
  59651. this._globalSaturation = value;
  59652. this._dirty = true;
  59653. },
  59654. enumerable: true,
  59655. configurable: true
  59656. });
  59657. Object.defineProperty(ColorCurves.prototype, "HighlightsHue", {
  59658. /**
  59659. * Gets the highlights Hue value.
  59660. * 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).
  59661. */
  59662. get: function () {
  59663. return this._highlightsHue;
  59664. },
  59665. /**
  59666. * Sets the highlights Hue value.
  59667. * 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).
  59668. */
  59669. set: function (value) {
  59670. this._highlightsHue = value;
  59671. this._dirty = true;
  59672. },
  59673. enumerable: true,
  59674. configurable: true
  59675. });
  59676. Object.defineProperty(ColorCurves.prototype, "HighlightsDensity", {
  59677. /**
  59678. * Gets the highlights Density value.
  59679. * 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.
  59680. * Values less than zero provide a filter of opposite hue.
  59681. */
  59682. get: function () {
  59683. return this._highlightsDensity;
  59684. },
  59685. /**
  59686. * Sets the highlights Density value.
  59687. * 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.
  59688. * Values less than zero provide a filter of opposite hue.
  59689. */
  59690. set: function (value) {
  59691. this._highlightsDensity = value;
  59692. this._dirty = true;
  59693. },
  59694. enumerable: true,
  59695. configurable: true
  59696. });
  59697. Object.defineProperty(ColorCurves.prototype, "HighlightsSaturation", {
  59698. /**
  59699. * Gets the highlights Saturation value.
  59700. * 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.
  59701. */
  59702. get: function () {
  59703. return this._highlightsSaturation;
  59704. },
  59705. /**
  59706. * Sets the highlights Saturation value.
  59707. * 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.
  59708. */
  59709. set: function (value) {
  59710. this._highlightsSaturation = value;
  59711. this._dirty = true;
  59712. },
  59713. enumerable: true,
  59714. configurable: true
  59715. });
  59716. Object.defineProperty(ColorCurves.prototype, "HighlightsExposure", {
  59717. /**
  59718. * Gets the highlights Exposure value.
  59719. * 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.
  59720. */
  59721. get: function () {
  59722. return this._highlightsExposure;
  59723. },
  59724. /**
  59725. * Sets the highlights Exposure value.
  59726. * 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.
  59727. */
  59728. set: function (value) {
  59729. this._highlightsExposure = value;
  59730. this._dirty = true;
  59731. },
  59732. enumerable: true,
  59733. configurable: true
  59734. });
  59735. Object.defineProperty(ColorCurves.prototype, "MidtonesHue", {
  59736. /**
  59737. * Gets the midtones Hue value.
  59738. * 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).
  59739. */
  59740. get: function () {
  59741. return this._midtonesHue;
  59742. },
  59743. /**
  59744. * Sets the midtones Hue value.
  59745. * 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).
  59746. */
  59747. set: function (value) {
  59748. this._midtonesHue = value;
  59749. this._dirty = true;
  59750. },
  59751. enumerable: true,
  59752. configurable: true
  59753. });
  59754. Object.defineProperty(ColorCurves.prototype, "MidtonesDensity", {
  59755. /**
  59756. * Gets the midtones Density value.
  59757. * 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.
  59758. * Values less than zero provide a filter of opposite hue.
  59759. */
  59760. get: function () {
  59761. return this._midtonesDensity;
  59762. },
  59763. /**
  59764. * Sets the midtones Density value.
  59765. * 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.
  59766. * Values less than zero provide a filter of opposite hue.
  59767. */
  59768. set: function (value) {
  59769. this._midtonesDensity = value;
  59770. this._dirty = true;
  59771. },
  59772. enumerable: true,
  59773. configurable: true
  59774. });
  59775. Object.defineProperty(ColorCurves.prototype, "MidtonesSaturation", {
  59776. /**
  59777. * Gets the midtones Saturation value.
  59778. * 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.
  59779. */
  59780. get: function () {
  59781. return this._midtonesSaturation;
  59782. },
  59783. /**
  59784. * Sets the midtones Saturation value.
  59785. * 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.
  59786. */
  59787. set: function (value) {
  59788. this._midtonesSaturation = value;
  59789. this._dirty = true;
  59790. },
  59791. enumerable: true,
  59792. configurable: true
  59793. });
  59794. Object.defineProperty(ColorCurves.prototype, "MidtonesExposure", {
  59795. /**
  59796. * Gets the midtones Exposure value.
  59797. * 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.
  59798. */
  59799. get: function () {
  59800. return this._midtonesExposure;
  59801. },
  59802. /**
  59803. * Sets the midtones Exposure value.
  59804. * 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.
  59805. */
  59806. set: function (value) {
  59807. this._midtonesExposure = value;
  59808. this._dirty = true;
  59809. },
  59810. enumerable: true,
  59811. configurable: true
  59812. });
  59813. Object.defineProperty(ColorCurves.prototype, "ShadowsHue", {
  59814. /**
  59815. * Gets the shadows Hue value.
  59816. * 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).
  59817. */
  59818. get: function () {
  59819. return this._shadowsHue;
  59820. },
  59821. /**
  59822. * Sets the shadows Hue value.
  59823. * 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).
  59824. */
  59825. set: function (value) {
  59826. this._shadowsHue = value;
  59827. this._dirty = true;
  59828. },
  59829. enumerable: true,
  59830. configurable: true
  59831. });
  59832. Object.defineProperty(ColorCurves.prototype, "ShadowsDensity", {
  59833. /**
  59834. * Gets the shadows Density value.
  59835. * 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.
  59836. * Values less than zero provide a filter of opposite hue.
  59837. */
  59838. get: function () {
  59839. return this._shadowsDensity;
  59840. },
  59841. /**
  59842. * Sets the shadows Density value.
  59843. * 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.
  59844. * Values less than zero provide a filter of opposite hue.
  59845. */
  59846. set: function (value) {
  59847. this._shadowsDensity = value;
  59848. this._dirty = true;
  59849. },
  59850. enumerable: true,
  59851. configurable: true
  59852. });
  59853. Object.defineProperty(ColorCurves.prototype, "ShadowsSaturation", {
  59854. /**
  59855. * Gets the shadows Saturation value.
  59856. * 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.
  59857. */
  59858. get: function () {
  59859. return this._shadowsSaturation;
  59860. },
  59861. /**
  59862. * Sets the shadows Saturation value.
  59863. * 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.
  59864. */
  59865. set: function (value) {
  59866. this._shadowsSaturation = value;
  59867. this._dirty = true;
  59868. },
  59869. enumerable: true,
  59870. configurable: true
  59871. });
  59872. Object.defineProperty(ColorCurves.prototype, "ShadowsExposure", {
  59873. /**
  59874. * Gets the shadows Exposure value.
  59875. * 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.
  59876. */
  59877. get: function () {
  59878. return this._shadowsExposure;
  59879. },
  59880. /**
  59881. * Sets the shadows Exposure value.
  59882. * 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.
  59883. */
  59884. set: function (value) {
  59885. this._shadowsExposure = value;
  59886. this._dirty = true;
  59887. },
  59888. enumerable: true,
  59889. configurable: true
  59890. });
  59891. /**
  59892. * Binds the color curves to the shader.
  59893. * @param colorCurves The color curve to bind
  59894. * @param effect The effect to bind to
  59895. */
  59896. ColorCurves.Bind = function (colorCurves, effect) {
  59897. if (colorCurves._dirty) {
  59898. colorCurves._dirty = false;
  59899. // Fill in global info.
  59900. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  59901. // Compute highlights info.
  59902. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  59903. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  59904. // Compute midtones info.
  59905. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  59906. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  59907. // Compute shadows info.
  59908. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  59909. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  59910. // Compute deltas (neutral is midtones).
  59911. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  59912. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  59913. }
  59914. effect.setFloat4("vCameraColorCurvePositive", colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  59915. effect.setFloat4("vCameraColorCurveNeutral", colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  59916. effect.setFloat4("vCameraColorCurveNegative", colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  59917. };
  59918. /**
  59919. * Prepare the list of uniforms associated with the ColorCurves effects.
  59920. * @param uniformsList The list of uniforms used in the effect
  59921. */
  59922. ColorCurves.PrepareUniforms = function (uniformsList) {
  59923. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  59924. };
  59925. /**
  59926. * Returns color grading data based on a hue, density, saturation and exposure value.
  59927. * @param filterHue The hue of the color filter.
  59928. * @param filterDensity The density of the color filter.
  59929. * @param saturation The saturation.
  59930. * @param exposure The exposure.
  59931. * @param result The result data container.
  59932. */
  59933. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  59934. if (hue == null) {
  59935. return;
  59936. }
  59937. hue = ColorCurves.clamp(hue, 0, 360);
  59938. density = ColorCurves.clamp(density, -100, 100);
  59939. saturation = ColorCurves.clamp(saturation, -100, 100);
  59940. exposure = ColorCurves.clamp(exposure, -100, 100);
  59941. // Remap the slider/config filter density with non-linear mapping and also scale by half
  59942. // so that the maximum filter density is only 50% control. This provides fine control
  59943. // for small values and reasonable range.
  59944. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  59945. density *= 0.5;
  59946. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  59947. if (density < 0) {
  59948. density *= -1;
  59949. hue = (hue + 180) % 360;
  59950. }
  59951. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  59952. result.scaleToRef(2, result);
  59953. result.a = 1 + 0.01 * saturation;
  59954. };
  59955. /**
  59956. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  59957. * @param value The input slider value in range [-100,100].
  59958. * @returns Adjusted value.
  59959. */
  59960. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  59961. value /= 100;
  59962. var x = Math.abs(value);
  59963. x = Math.pow(x, 2);
  59964. if (value < 0) {
  59965. x *= -1;
  59966. }
  59967. x *= 100;
  59968. return x;
  59969. };
  59970. /**
  59971. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  59972. * @param hue The hue (H) input.
  59973. * @param saturation The saturation (S) input.
  59974. * @param brightness The brightness (B) input.
  59975. * @result An RGBA color represented as Vector4.
  59976. */
  59977. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  59978. var h = ColorCurves.clamp(hue, 0, 360);
  59979. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  59980. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  59981. if (s === 0) {
  59982. result.r = v;
  59983. result.g = v;
  59984. result.b = v;
  59985. }
  59986. else {
  59987. // sector 0 to 5
  59988. h /= 60;
  59989. var i = Math.floor(h);
  59990. // fractional part of h
  59991. var f = h - i;
  59992. var p = v * (1 - s);
  59993. var q = v * (1 - s * f);
  59994. var t = v * (1 - s * (1 - f));
  59995. switch (i) {
  59996. case 0:
  59997. result.r = v;
  59998. result.g = t;
  59999. result.b = p;
  60000. break;
  60001. case 1:
  60002. result.r = q;
  60003. result.g = v;
  60004. result.b = p;
  60005. break;
  60006. case 2:
  60007. result.r = p;
  60008. result.g = v;
  60009. result.b = t;
  60010. break;
  60011. case 3:
  60012. result.r = p;
  60013. result.g = q;
  60014. result.b = v;
  60015. break;
  60016. case 4:
  60017. result.r = t;
  60018. result.g = p;
  60019. result.b = v;
  60020. break;
  60021. default:
  60022. result.r = v;
  60023. result.g = p;
  60024. result.b = q;
  60025. break;
  60026. }
  60027. }
  60028. result.a = 1;
  60029. };
  60030. /**
  60031. * Returns a value clamped between min and max
  60032. * @param value The value to clamp
  60033. * @param min The minimum of value
  60034. * @param max The maximum of value
  60035. * @returns The clamped value.
  60036. */
  60037. ColorCurves.clamp = function (value, min, max) {
  60038. return Math.min(Math.max(value, min), max);
  60039. };
  60040. /**
  60041. * Clones the current color curve instance.
  60042. * @return The cloned curves
  60043. */
  60044. ColorCurves.prototype.clone = function () {
  60045. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  60046. };
  60047. /**
  60048. * Serializes the current color curve instance to a json representation.
  60049. * @return a JSON representation
  60050. */
  60051. ColorCurves.prototype.serialize = function () {
  60052. return BABYLON.SerializationHelper.Serialize(this);
  60053. };
  60054. /**
  60055. * Parses the color curve from a json representation.
  60056. * @param source the JSON source to parse
  60057. * @return The parsed curves
  60058. */
  60059. ColorCurves.Parse = function (source) {
  60060. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  60061. };
  60062. __decorate([
  60063. BABYLON.serialize()
  60064. ], ColorCurves.prototype, "_globalHue", void 0);
  60065. __decorate([
  60066. BABYLON.serialize()
  60067. ], ColorCurves.prototype, "_globalDensity", void 0);
  60068. __decorate([
  60069. BABYLON.serialize()
  60070. ], ColorCurves.prototype, "_globalSaturation", void 0);
  60071. __decorate([
  60072. BABYLON.serialize()
  60073. ], ColorCurves.prototype, "_globalExposure", void 0);
  60074. __decorate([
  60075. BABYLON.serialize()
  60076. ], ColorCurves.prototype, "_highlightsHue", void 0);
  60077. __decorate([
  60078. BABYLON.serialize()
  60079. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  60080. __decorate([
  60081. BABYLON.serialize()
  60082. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  60083. __decorate([
  60084. BABYLON.serialize()
  60085. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  60086. __decorate([
  60087. BABYLON.serialize()
  60088. ], ColorCurves.prototype, "_midtonesHue", void 0);
  60089. __decorate([
  60090. BABYLON.serialize()
  60091. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  60092. __decorate([
  60093. BABYLON.serialize()
  60094. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  60095. __decorate([
  60096. BABYLON.serialize()
  60097. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  60098. return ColorCurves;
  60099. })();
  60100. BABYLON.ColorCurves = ColorCurves;
  60101. })(BABYLON || (BABYLON = {}));
  60102. var BABYLON;
  60103. (function (BABYLON) {
  60104. /**
  60105. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  60106. * It can help converting any input color in a desired output one. This can then be used to create effects
  60107. * from sepia, black and white to sixties or futuristic rendering...
  60108. *
  60109. * The only supported format is currently 3dl.
  60110. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  60111. */
  60112. var ColorGradingTexture = (function (_super) {
  60113. __extends(ColorGradingTexture, _super);
  60114. /**
  60115. * Instantiates a ColorGradingTexture from the following parameters.
  60116. *
  60117. * @param url The location of the color gradind data (currently only supporting 3dl)
  60118. * @param scene The scene the texture will be used in
  60119. */
  60120. function ColorGradingTexture(url, scene) {
  60121. _super.call(this, scene);
  60122. if (!url) {
  60123. return;
  60124. }
  60125. this._textureMatrix = BABYLON.Matrix.Identity();
  60126. this.name = url;
  60127. this.url = url;
  60128. this.hasAlpha = false;
  60129. this.isCube = false;
  60130. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60131. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60132. this.anisotropicFilteringLevel = 1;
  60133. this._texture = this._getFromCache(url, true);
  60134. if (!this._texture) {
  60135. if (!scene.useDelayedTextureLoading) {
  60136. this.loadTexture();
  60137. }
  60138. else {
  60139. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  60140. }
  60141. }
  60142. }
  60143. /**
  60144. * Returns the texture matrix used in most of the material.
  60145. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  60146. */
  60147. ColorGradingTexture.prototype.getTextureMatrix = function () {
  60148. return this._textureMatrix;
  60149. };
  60150. /**
  60151. * Occurs when the file being loaded is a .3dl LUT file.
  60152. */
  60153. ColorGradingTexture.prototype.load3dlTexture = function () {
  60154. var _this = this;
  60155. var mipLevels = 0;
  60156. var floatArrayView = null;
  60157. var texture = this.getScene().getEngine().createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  60158. this._texture = texture;
  60159. var callback = function (text) {
  60160. var data;
  60161. var tempData;
  60162. var line;
  60163. var lines = text.split('\n');
  60164. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  60165. var maxColor = 0;
  60166. for (var i = 0; i < lines.length; i++) {
  60167. line = lines[i];
  60168. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  60169. continue;
  60170. if (line.indexOf('#') === 0)
  60171. continue;
  60172. var words = line.split(" ");
  60173. if (size === 0) {
  60174. // Number of space + one
  60175. size = words.length;
  60176. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  60177. tempData = new Float32Array(size * size * size * 4);
  60178. continue;
  60179. }
  60180. if (size != 0) {
  60181. var r = Math.max(parseInt(words[0]), 0);
  60182. var g = Math.max(parseInt(words[1]), 0);
  60183. var b = Math.max(parseInt(words[2]), 0);
  60184. maxColor = Math.max(r, maxColor);
  60185. maxColor = Math.max(g, maxColor);
  60186. maxColor = Math.max(b, maxColor);
  60187. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  60188. tempData[pixelStorageIndex + 0] = r;
  60189. tempData[pixelStorageIndex + 1] = g;
  60190. tempData[pixelStorageIndex + 2] = b;
  60191. tempData[pixelStorageIndex + 3] = 0;
  60192. pixelIndexSlice++;
  60193. if (pixelIndexSlice % size == 0) {
  60194. pixelIndexH++;
  60195. pixelIndexSlice = 0;
  60196. if (pixelIndexH % size == 0) {
  60197. pixelIndexW++;
  60198. pixelIndexH = 0;
  60199. }
  60200. }
  60201. }
  60202. }
  60203. for (var i = 0; i < tempData.length; i++) {
  60204. var value = tempData[i];
  60205. data[i] = (value / maxColor * 255);
  60206. }
  60207. _this.getScene().getEngine().updateTextureSize(texture, size * size, size);
  60208. _this.getScene().getEngine().updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  60209. };
  60210. BABYLON.Tools.LoadFile(this.url, callback);
  60211. return this._texture;
  60212. };
  60213. /**
  60214. * Starts the loading process of the texture.
  60215. */
  60216. ColorGradingTexture.prototype.loadTexture = function () {
  60217. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  60218. this.load3dlTexture();
  60219. }
  60220. };
  60221. /**
  60222. * Clones the color gradind texture.
  60223. */
  60224. ColorGradingTexture.prototype.clone = function () {
  60225. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  60226. // Base texture
  60227. newTexture.level = this.level;
  60228. return newTexture;
  60229. };
  60230. /**
  60231. * Called during delayed load for textures.
  60232. */
  60233. ColorGradingTexture.prototype.delayLoad = function () {
  60234. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  60235. return;
  60236. }
  60237. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  60238. this._texture = this._getFromCache(this.url, true);
  60239. if (!this._texture) {
  60240. this.loadTexture();
  60241. }
  60242. };
  60243. /**
  60244. * Binds the color grading to the shader.
  60245. * @param colorGrading The texture to bind
  60246. * @param effect The effect to bind to
  60247. */
  60248. ColorGradingTexture.Bind = function (colorGrading, effect) {
  60249. effect.setTexture("cameraColorGrading2DSampler", colorGrading);
  60250. var x = colorGrading.level; // Texture Level
  60251. var y = colorGrading.getSize().height; // Texture Size example with 8
  60252. var z = y - 1.0; // SizeMinusOne 8 - 1
  60253. var w = 1 / y; // Space of 1 slice 1 / 8
  60254. effect.setFloat4("vCameraColorGradingInfos", x, y, z, w);
  60255. var slicePixelSizeU = w / y; // Space of 1 pixel in U direction, e.g. 1/64
  60256. 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
  60257. 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
  60258. 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
  60259. var z2 = 0.5 * slicePixelSizeU; // Offset of lookup range in U to align sample position with texel centre, for example 0.5/64
  60260. var w2 = 0.5 * slicePixelSizeV; // Offset of lookup range in V to align sample position with texel centre, for example 0.5/8
  60261. effect.setFloat4("vCameraColorGradingScaleOffset", x2, y2, z2, w2);
  60262. };
  60263. /**
  60264. * Prepare the list of uniforms associated with the ColorGrading effects.
  60265. * @param uniformsList The list of uniforms used in the effect
  60266. * @param samplersList The list of samplers used in the effect
  60267. */
  60268. ColorGradingTexture.PrepareUniformsAndSamplers = function (uniformsList, samplersList) {
  60269. uniformsList.push("vCameraColorGradingInfos", "vCameraColorGradingScaleOffset");
  60270. samplersList.push("cameraColorGrading2DSampler");
  60271. };
  60272. /**
  60273. * Parses a color grading texture serialized by Babylon.
  60274. * @param parsedTexture The texture information being parsedTexture
  60275. * @param scene The scene to load the texture in
  60276. * @param rootUrl The root url of the data assets to load
  60277. * @return A color gradind texture
  60278. */
  60279. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  60280. var texture = null;
  60281. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  60282. texture = new BABYLON.ColorGradingTexture(parsedTexture.name, scene);
  60283. texture.name = parsedTexture.name;
  60284. texture.level = parsedTexture.level;
  60285. }
  60286. return texture;
  60287. };
  60288. /**
  60289. * Serializes the LUT texture to json format.
  60290. */
  60291. ColorGradingTexture.prototype.serialize = function () {
  60292. if (!this.name) {
  60293. return null;
  60294. }
  60295. var serializationObject = {};
  60296. serializationObject.name = this.name;
  60297. serializationObject.level = this.level;
  60298. serializationObject.customType = "BABYLON.ColorGradingTexture";
  60299. return serializationObject;
  60300. };
  60301. /**
  60302. * Empty line regex stored for GC.
  60303. */
  60304. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  60305. return ColorGradingTexture;
  60306. })(BABYLON.BaseTexture);
  60307. BABYLON.ColorGradingTexture = ColorGradingTexture;
  60308. })(BABYLON || (BABYLON = {}));
  60309. var BABYLON;
  60310. (function (BABYLON) {
  60311. var PBRMaterialDefines = (function (_super) {
  60312. __extends(PBRMaterialDefines, _super);
  60313. function PBRMaterialDefines() {
  60314. _super.call(this);
  60315. this.ALBEDO = false;
  60316. this.AMBIENT = false;
  60317. this.OPACITY = false;
  60318. this.OPACITYRGB = false;
  60319. this.REFLECTION = false;
  60320. this.EMISSIVE = false;
  60321. this.REFLECTIVITY = false;
  60322. this.BUMP = false;
  60323. this.PARALLAX = false;
  60324. this.PARALLAXOCCLUSION = false;
  60325. this.SPECULAROVERALPHA = false;
  60326. this.CLIPPLANE = false;
  60327. this.ALPHATEST = false;
  60328. this.ALPHAFROMALBEDO = false;
  60329. this.POINTSIZE = false;
  60330. this.FOG = false;
  60331. this.SPECULARTERM = false;
  60332. this.OPACITYFRESNEL = false;
  60333. this.EMISSIVEFRESNEL = false;
  60334. this.FRESNEL = false;
  60335. this.NORMAL = false;
  60336. this.UV1 = false;
  60337. this.UV2 = false;
  60338. this.VERTEXCOLOR = false;
  60339. this.VERTEXALPHA = false;
  60340. this.NUM_BONE_INFLUENCERS = 0;
  60341. this.BonesPerMesh = 0;
  60342. this.INSTANCES = false;
  60343. this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  60344. this.MICROSURFACEAUTOMATIC = false;
  60345. this.EMISSIVEASILLUMINATION = false;
  60346. this.LINKEMISSIVEWITHALBEDO = false;
  60347. this.LIGHTMAP = false;
  60348. this.USELIGHTMAPASSHADOWMAP = false;
  60349. this.REFLECTIONMAP_3D = false;
  60350. this.REFLECTIONMAP_SPHERICAL = false;
  60351. this.REFLECTIONMAP_PLANAR = false;
  60352. this.REFLECTIONMAP_CUBIC = false;
  60353. this.REFLECTIONMAP_PROJECTION = false;
  60354. this.REFLECTIONMAP_SKYBOX = false;
  60355. this.REFLECTIONMAP_EXPLICIT = false;
  60356. this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  60357. this.INVERTCUBICMAP = false;
  60358. this.LOGARITHMICDEPTH = false;
  60359. this.CAMERATONEMAP = false;
  60360. this.CAMERACONTRAST = false;
  60361. this.CAMERACOLORGRADING = false;
  60362. this.CAMERACOLORCURVES = false;
  60363. this.OVERLOADEDVALUES = false;
  60364. this.OVERLOADEDSHADOWVALUES = false;
  60365. this.USESPHERICALFROMREFLECTIONMAP = false;
  60366. this.REFRACTION = false;
  60367. this.REFRACTIONMAP_3D = false;
  60368. this.LINKREFRACTIONTOTRANSPARENCY = false;
  60369. this.REFRACTIONMAPINLINEARSPACE = false;
  60370. this.LODBASEDMICROSFURACE = false;
  60371. this.USEPHYSICALLIGHTFALLOFF = false;
  60372. this.RADIANCEOVERALPHA = false;
  60373. this.USEPMREMREFLECTION = false;
  60374. this.USEPMREMREFRACTION = false;
  60375. this.OPENGLNORMALMAP = false;
  60376. this.INVERTNORMALMAPX = false;
  60377. this.INVERTNORMALMAPY = false;
  60378. this.SHADOWFULLFLOAT = false;
  60379. this.rebuild();
  60380. }
  60381. return PBRMaterialDefines;
  60382. })(BABYLON.MaterialDefines);
  60383. /**
  60384. * The Physically based material of BJS.
  60385. *
  60386. * This offers the main features of a standard PBR material.
  60387. * For more information, please refer to the documentation :
  60388. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  60389. */
  60390. var PBRMaterial = (function (_super) {
  60391. __extends(PBRMaterial, _super);
  60392. /**
  60393. * Instantiates a new PBRMaterial instance.
  60394. *
  60395. * @param name The material name
  60396. * @param scene The scene the material will be use in.
  60397. */
  60398. function PBRMaterial(name, scene) {
  60399. var _this = this;
  60400. _super.call(this, name, scene);
  60401. /**
  60402. * Intensity of the direct lights e.g. the four lights available in your scene.
  60403. * This impacts both the direct diffuse and specular highlights.
  60404. */
  60405. this.directIntensity = 1.0;
  60406. /**
  60407. * Intensity of the emissive part of the material.
  60408. * This helps controlling the emissive effect without modifying the emissive color.
  60409. */
  60410. this.emissiveIntensity = 1.0;
  60411. /**
  60412. * Intensity of the environment e.g. how much the environment will light the object
  60413. * either through harmonics for rough material or through the refelction for shiny ones.
  60414. */
  60415. this.environmentIntensity = 1.0;
  60416. /**
  60417. * This is a special control allowing the reduction of the specular highlights coming from the
  60418. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  60419. */
  60420. this.specularIntensity = 1.0;
  60421. this._lightingInfos = new BABYLON.Vector4(this.directIntensity, this.emissiveIntensity, this.environmentIntensity, this.specularIntensity);
  60422. /**
  60423. * Debug Control allowing disabling the bump map on this material.
  60424. */
  60425. this.disableBumpMap = false;
  60426. /**
  60427. * Debug Control helping enforcing or dropping the darkness of shadows.
  60428. * 1.0 means the shadows have their normal darkness, 0.0 means the shadows are not visible.
  60429. */
  60430. this.overloadedShadowIntensity = 1.0;
  60431. /**
  60432. * Debug Control helping dropping the shading effect coming from the diffuse lighting.
  60433. * 1.0 means the shade have their normal impact, 0.0 means no shading at all.
  60434. */
  60435. this.overloadedShadeIntensity = 1.0;
  60436. this._overloadedShadowInfos = new BABYLON.Vector4(this.overloadedShadowIntensity, this.overloadedShadeIntensity, 0.0, 0.0);
  60437. /**
  60438. * The camera exposure used on this material.
  60439. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  60440. * This corresponds to a photographic exposure.
  60441. */
  60442. this.cameraExposure = 1.0;
  60443. /**
  60444. * The camera contrast used on this material.
  60445. * This property is here and not in the camera to allow controlling contrast without full screen post process.
  60446. */
  60447. this.cameraContrast = 1.0;
  60448. /**
  60449. * Color Grading 2D Lookup Texture.
  60450. * This allows special effects like sepia, black and white to sixties rendering style.
  60451. */
  60452. this.cameraColorGradingTexture = null;
  60453. /**
  60454. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  60455. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  60456. * 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;
  60457. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  60458. */
  60459. this.cameraColorCurves = null;
  60460. this._cameraInfos = new BABYLON.Vector4(1.0, 1.0, 0.0, 0.0);
  60461. this._microsurfaceTextureLods = new BABYLON.Vector2(0.0, 0.0);
  60462. /**
  60463. * Debug Control allowing to overload the ambient color.
  60464. * This as to be use with the overloadedAmbientIntensity parameter.
  60465. */
  60466. this.overloadedAmbient = BABYLON.Color3.White();
  60467. /**
  60468. * Debug Control indicating how much the overloaded ambient color is used against the default one.
  60469. */
  60470. this.overloadedAmbientIntensity = 0.0;
  60471. /**
  60472. * Debug Control allowing to overload the albedo color.
  60473. * This as to be use with the overloadedAlbedoIntensity parameter.
  60474. */
  60475. this.overloadedAlbedo = BABYLON.Color3.White();
  60476. /**
  60477. * Debug Control indicating how much the overloaded albedo color is used against the default one.
  60478. */
  60479. this.overloadedAlbedoIntensity = 0.0;
  60480. /**
  60481. * Debug Control allowing to overload the reflectivity color.
  60482. * This as to be use with the overloadedReflectivityIntensity parameter.
  60483. */
  60484. this.overloadedReflectivity = new BABYLON.Color3(0.3, 0.3, 0.3);
  60485. /**
  60486. * Debug Control indicating how much the overloaded reflectivity color is used against the default one.
  60487. */
  60488. this.overloadedReflectivityIntensity = 0.0;
  60489. /**
  60490. * Debug Control allowing to overload the emissive color.
  60491. * This as to be use with the overloadedEmissiveIntensity parameter.
  60492. */
  60493. this.overloadedEmissive = BABYLON.Color3.White();
  60494. /**
  60495. * Debug Control indicating how much the overloaded emissive color is used against the default one.
  60496. */
  60497. this.overloadedEmissiveIntensity = 0.0;
  60498. this._overloadedIntensity = new BABYLON.Vector4(this.overloadedAmbientIntensity, this.overloadedAlbedoIntensity, this.overloadedReflectivityIntensity, this.overloadedEmissiveIntensity);
  60499. /**
  60500. * Debug Control allowing to overload the reflection color.
  60501. * This as to be use with the overloadedReflectionIntensity parameter.
  60502. */
  60503. this.overloadedReflection = BABYLON.Color3.White();
  60504. /**
  60505. * Debug Control indicating how much the overloaded reflection color is used against the default one.
  60506. */
  60507. this.overloadedReflectionIntensity = 0.0;
  60508. /**
  60509. * Debug Control allowing to overload the microsurface.
  60510. * This as to be use with the overloadedMicroSurfaceIntensity parameter.
  60511. */
  60512. this.overloadedMicroSurface = 0.0;
  60513. /**
  60514. * Debug Control indicating how much the overloaded microsurface is used against the default one.
  60515. */
  60516. this.overloadedMicroSurfaceIntensity = 0.0;
  60517. this._overloadedMicroSurface = new BABYLON.Vector3(this.overloadedMicroSurface, this.overloadedMicroSurfaceIntensity, this.overloadedReflectionIntensity);
  60518. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  60519. /**
  60520. * AKA Diffuse Color in other nomenclature.
  60521. */
  60522. this.albedoColor = new BABYLON.Color3(1, 1, 1);
  60523. /**
  60524. * AKA Specular Color in other nomenclature.
  60525. */
  60526. this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  60527. this.reflectionColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  60528. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  60529. /**
  60530. * AKA Glossiness in other nomenclature.
  60531. */
  60532. this.microSurface = 0.9;
  60533. /**
  60534. * source material index of refraction (IOR)' / 'destination material IOR.
  60535. */
  60536. this.indexOfRefraction = 0.66;
  60537. /**
  60538. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  60539. */
  60540. this.invertRefractionY = false;
  60541. /**
  60542. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  60543. * Materials half opaque for instance using refraction could benefit from this control.
  60544. */
  60545. this.linkRefractionWithTransparency = false;
  60546. /**
  60547. * The emissive and albedo are linked to never be more than one (Energy conservation).
  60548. */
  60549. this.linkEmissiveWithAlbedo = false;
  60550. this.useLightmapAsShadowmap = false;
  60551. /**
  60552. * In this mode, the emissive informtaion will always be added to the lighting once.
  60553. * A light for instance can be thought as emissive.
  60554. */
  60555. this.useEmissiveAsIllumination = false;
  60556. /**
  60557. * Secifies that the alpha is coming form the albedo channel alpha channel.
  60558. */
  60559. this.useAlphaFromAlbedoTexture = false;
  60560. /**
  60561. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  60562. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  60563. */
  60564. this.useSpecularOverAlpha = true;
  60565. /**
  60566. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  60567. */
  60568. this.useMicroSurfaceFromReflectivityMapAlpha = false;
  60569. /**
  60570. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  60571. * The material will try to infer what glossiness each pixel should be.
  60572. */
  60573. this.useAutoMicroSurfaceFromReflectivityMap = false;
  60574. /**
  60575. * Allows to work with scalar in linear mode. This is definitely a matter of preferences and tools used during
  60576. * the creation of the material.
  60577. */
  60578. this.useScalarInLinearSpace = false;
  60579. /**
  60580. * BJS is using an harcoded light falloff based on a manually sets up range.
  60581. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  60582. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  60583. */
  60584. this.usePhysicalLightFalloff = true;
  60585. /**
  60586. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  60587. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  60588. */
  60589. this.useRadianceOverAlpha = true;
  60590. /**
  60591. * Allows using the bump map in parallax mode.
  60592. */
  60593. this.useParallax = false;
  60594. /**
  60595. * Allows using the bump map in parallax occlusion mode.
  60596. */
  60597. this.useParallaxOcclusion = false;
  60598. /**
  60599. * Controls the scale bias of the parallax mode.
  60600. */
  60601. this.parallaxScaleBias = 0.05;
  60602. /**
  60603. * If sets to true, disables all the lights affecting the material.
  60604. */
  60605. this.disableLighting = false;
  60606. /**
  60607. * Number of Simultaneous lights allowed on the material.
  60608. */
  60609. this.maxSimultaneousLights = 4;
  60610. /**
  60611. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  60612. */
  60613. this.invertNormalMapX = false;
  60614. /**
  60615. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  60616. */
  60617. this.invertNormalMapY = false;
  60618. this._renderTargets = new BABYLON.SmartArray(16);
  60619. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  60620. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  60621. this._tempColor = new BABYLON.Color3();
  60622. this._defines = new PBRMaterialDefines();
  60623. this._cachedDefines = new PBRMaterialDefines();
  60624. this._myScene = null;
  60625. this._myShadowGenerator = null;
  60626. this._cachedDefines.BonesPerMesh = -1;
  60627. this.getRenderTargetTextures = function () {
  60628. _this._renderTargets.reset();
  60629. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  60630. _this._renderTargets.push(_this.reflectionTexture);
  60631. }
  60632. if (_this.refractionTexture && _this.refractionTexture.isRenderTarget) {
  60633. _this._renderTargets.push(_this.refractionTexture);
  60634. }
  60635. return _this._renderTargets;
  60636. };
  60637. }
  60638. Object.defineProperty(PBRMaterial.prototype, "useLogarithmicDepth", {
  60639. get: function () {
  60640. return this._useLogarithmicDepth;
  60641. },
  60642. set: function (value) {
  60643. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  60644. },
  60645. enumerable: true,
  60646. configurable: true
  60647. });
  60648. PBRMaterial.prototype.needAlphaBlending = function () {
  60649. if (this.linkRefractionWithTransparency) {
  60650. return false;
  60651. }
  60652. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  60653. };
  60654. PBRMaterial.prototype.needAlphaTesting = function () {
  60655. if (this.linkRefractionWithTransparency) {
  60656. return false;
  60657. }
  60658. return this.albedoTexture != null && this.albedoTexture.hasAlpha;
  60659. };
  60660. PBRMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  60661. return this.albedoTexture != null && this.albedoTexture.hasAlpha && this.useAlphaFromAlbedoTexture;
  60662. };
  60663. PBRMaterial.prototype.getAlphaTestTexture = function () {
  60664. return this.albedoTexture;
  60665. };
  60666. PBRMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  60667. if (!mesh) {
  60668. return true;
  60669. }
  60670. if (this._defines.INSTANCES !== useInstances) {
  60671. return false;
  60672. }
  60673. if (mesh._materialDefines && mesh._materialDefines.isEqual(this._defines)) {
  60674. return true;
  60675. }
  60676. return false;
  60677. };
  60678. PBRMaterial.prototype.convertColorToLinearSpaceToRef = function (color, ref) {
  60679. PBRMaterial.convertColorToLinearSpaceToRef(color, ref, this.useScalarInLinearSpace);
  60680. };
  60681. PBRMaterial.convertColorToLinearSpaceToRef = function (color, ref, useScalarInLinear) {
  60682. if (!useScalarInLinear) {
  60683. color.toLinearSpaceToRef(ref);
  60684. }
  60685. else {
  60686. ref.r = color.r;
  60687. ref.g = color.g;
  60688. ref.b = color.b;
  60689. }
  60690. };
  60691. PBRMaterial.BindLights = function (scene, mesh, effect, defines, useScalarInLinearSpace, maxSimultaneousLights, usePhysicalLightFalloff) {
  60692. var lightIndex = 0;
  60693. var depthValuesAlreadySet = false;
  60694. for (var index = 0; index < scene.lights.length; index++) {
  60695. var light = scene.lights[index];
  60696. if (!light.isEnabled()) {
  60697. continue;
  60698. }
  60699. if (!light.canAffectMesh(mesh)) {
  60700. continue;
  60701. }
  60702. BABYLON.MaterialHelper.BindLightProperties(light, effect, lightIndex);
  60703. // GAMMA CORRECTION.
  60704. this.convertColorToLinearSpaceToRef(light.diffuse, PBRMaterial._scaledAlbedo, useScalarInLinearSpace);
  60705. PBRMaterial._scaledAlbedo.scaleToRef(light.intensity, PBRMaterial._scaledAlbedo);
  60706. effect.setColor4("vLightDiffuse" + lightIndex, PBRMaterial._scaledAlbedo, usePhysicalLightFalloff ? light.radius : light.range);
  60707. if (defines["SPECULARTERM"]) {
  60708. this.convertColorToLinearSpaceToRef(light.specular, PBRMaterial._scaledReflectivity, useScalarInLinearSpace);
  60709. PBRMaterial._scaledReflectivity.scaleToRef(light.intensity, PBRMaterial._scaledReflectivity);
  60710. effect.setColor3("vLightSpecular" + lightIndex, PBRMaterial._scaledReflectivity);
  60711. }
  60712. // Shadows
  60713. if (scene.shadowsEnabled) {
  60714. depthValuesAlreadySet = BABYLON.MaterialHelper.BindLightShadow(light, scene, mesh, lightIndex, effect, depthValuesAlreadySet);
  60715. }
  60716. lightIndex++;
  60717. if (lightIndex === maxSimultaneousLights)
  60718. break;
  60719. }
  60720. };
  60721. PBRMaterial.prototype.isReady = function (mesh, useInstances) {
  60722. if (this.checkReadyOnlyOnce) {
  60723. if (this._wasPreviouslyReady) {
  60724. return true;
  60725. }
  60726. }
  60727. var scene = this.getScene();
  60728. if (!this.checkReadyOnEveryCall) {
  60729. if (this._renderId === scene.getRenderId()) {
  60730. if (this._checkCache(scene, mesh, useInstances)) {
  60731. return true;
  60732. }
  60733. }
  60734. }
  60735. var engine = scene.getEngine();
  60736. var needNormals = false;
  60737. var needUVs = false;
  60738. this._defines.reset();
  60739. if (scene.texturesEnabled) {
  60740. // Textures
  60741. if (scene.texturesEnabled) {
  60742. if (scene.getEngine().getCaps().textureLOD) {
  60743. this._defines.LODBASEDMICROSFURACE = true;
  60744. }
  60745. if (this.albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  60746. if (!this.albedoTexture.isReady()) {
  60747. return false;
  60748. }
  60749. else {
  60750. needUVs = true;
  60751. this._defines.ALBEDO = true;
  60752. }
  60753. }
  60754. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  60755. if (!this.ambientTexture.isReady()) {
  60756. return false;
  60757. }
  60758. else {
  60759. needUVs = true;
  60760. this._defines.AMBIENT = true;
  60761. }
  60762. }
  60763. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  60764. if (!this.opacityTexture.isReady()) {
  60765. return false;
  60766. }
  60767. else {
  60768. needUVs = true;
  60769. this._defines.OPACITY = true;
  60770. if (this.opacityTexture.getAlphaFromRGB) {
  60771. this._defines.OPACITYRGB = true;
  60772. }
  60773. }
  60774. }
  60775. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  60776. if (!this.reflectionTexture.isReady()) {
  60777. return false;
  60778. }
  60779. else {
  60780. needNormals = true;
  60781. this._defines.REFLECTION = true;
  60782. if (this.reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  60783. this._defines.INVERTCUBICMAP = true;
  60784. }
  60785. this._defines.REFLECTIONMAP_3D = this.reflectionTexture.isCube;
  60786. switch (this.reflectionTexture.coordinatesMode) {
  60787. case BABYLON.Texture.CUBIC_MODE:
  60788. case BABYLON.Texture.INVCUBIC_MODE:
  60789. this._defines.REFLECTIONMAP_CUBIC = true;
  60790. break;
  60791. case BABYLON.Texture.EXPLICIT_MODE:
  60792. this._defines.REFLECTIONMAP_EXPLICIT = true;
  60793. break;
  60794. case BABYLON.Texture.PLANAR_MODE:
  60795. this._defines.REFLECTIONMAP_PLANAR = true;
  60796. break;
  60797. case BABYLON.Texture.PROJECTION_MODE:
  60798. this._defines.REFLECTIONMAP_PROJECTION = true;
  60799. break;
  60800. case BABYLON.Texture.SKYBOX_MODE:
  60801. this._defines.REFLECTIONMAP_SKYBOX = true;
  60802. break;
  60803. case BABYLON.Texture.SPHERICAL_MODE:
  60804. this._defines.REFLECTIONMAP_SPHERICAL = true;
  60805. break;
  60806. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  60807. this._defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  60808. break;
  60809. }
  60810. if (this.reflectionTexture instanceof BABYLON.HDRCubeTexture && this.reflectionTexture) {
  60811. this._defines.USESPHERICALFROMREFLECTIONMAP = true;
  60812. needNormals = true;
  60813. if (this.reflectionTexture.isPMREM) {
  60814. this._defines.USEPMREMREFLECTION = true;
  60815. }
  60816. }
  60817. }
  60818. }
  60819. if (this.lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  60820. if (!this.lightmapTexture.isReady()) {
  60821. return false;
  60822. }
  60823. else {
  60824. needUVs = true;
  60825. this._defines.LIGHTMAP = true;
  60826. this._defines.USELIGHTMAPASSHADOWMAP = this.useLightmapAsShadowmap;
  60827. }
  60828. }
  60829. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  60830. if (!this.emissiveTexture.isReady()) {
  60831. return false;
  60832. }
  60833. else {
  60834. needUVs = true;
  60835. this._defines.EMISSIVE = true;
  60836. }
  60837. }
  60838. if (this.reflectivityTexture && BABYLON.StandardMaterial.SpecularTextureEnabled) {
  60839. if (!this.reflectivityTexture.isReady()) {
  60840. return false;
  60841. }
  60842. else {
  60843. needUVs = true;
  60844. this._defines.REFLECTIVITY = true;
  60845. this._defines.MICROSURFACEFROMREFLECTIVITYMAP = this.useMicroSurfaceFromReflectivityMapAlpha;
  60846. this._defines.MICROSURFACEAUTOMATIC = this.useAutoMicroSurfaceFromReflectivityMap;
  60847. }
  60848. }
  60849. }
  60850. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this.disableBumpMap) {
  60851. if (!this.bumpTexture.isReady()) {
  60852. return false;
  60853. }
  60854. else {
  60855. needUVs = true;
  60856. this._defines.BUMP = true;
  60857. if (this.useParallax) {
  60858. this._defines.PARALLAX = true;
  60859. if (this.useParallaxOcclusion) {
  60860. this._defines.PARALLAXOCCLUSION = true;
  60861. }
  60862. }
  60863. if (this.invertNormalMapX) {
  60864. this._defines.INVERTNORMALMAPX = true;
  60865. }
  60866. if (this.invertNormalMapY) {
  60867. this._defines.INVERTNORMALMAPY = true;
  60868. }
  60869. }
  60870. }
  60871. if (this.refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  60872. if (!this.refractionTexture.isReady()) {
  60873. return false;
  60874. }
  60875. else {
  60876. needUVs = true;
  60877. this._defines.REFRACTION = true;
  60878. this._defines.REFRACTIONMAP_3D = this.refractionTexture.isCube;
  60879. if (this.linkRefractionWithTransparency) {
  60880. this._defines.LINKREFRACTIONTOTRANSPARENCY = true;
  60881. }
  60882. if (this.refractionTexture instanceof BABYLON.HDRCubeTexture) {
  60883. this._defines.REFRACTIONMAPINLINEARSPACE = true;
  60884. if (this.refractionTexture.isPMREM) {
  60885. this._defines.USEPMREMREFRACTION = true;
  60886. }
  60887. }
  60888. }
  60889. }
  60890. if (this.cameraColorGradingTexture && BABYLON.StandardMaterial.ColorGradingTextureEnabled) {
  60891. if (!this.cameraColorGradingTexture.isReady()) {
  60892. return false;
  60893. }
  60894. else {
  60895. this._defines.CAMERACOLORGRADING = true;
  60896. }
  60897. }
  60898. }
  60899. // Effect
  60900. if (scene.clipPlane) {
  60901. this._defines.CLIPPLANE = true;
  60902. }
  60903. if (engine.getAlphaTesting()) {
  60904. this._defines.ALPHATEST = true;
  60905. }
  60906. if (this._shouldUseAlphaFromAlbedoTexture()) {
  60907. this._defines.ALPHAFROMALBEDO = true;
  60908. }
  60909. if (this.useEmissiveAsIllumination) {
  60910. this._defines.EMISSIVEASILLUMINATION = true;
  60911. }
  60912. if (this.linkEmissiveWithAlbedo) {
  60913. this._defines.LINKEMISSIVEWITHALBEDO = true;
  60914. }
  60915. if (this.useLogarithmicDepth) {
  60916. this._defines.LOGARITHMICDEPTH = true;
  60917. }
  60918. if (this.cameraContrast != 1) {
  60919. this._defines.CAMERACONTRAST = true;
  60920. }
  60921. if (this.cameraExposure != 1) {
  60922. this._defines.CAMERATONEMAP = true;
  60923. }
  60924. if (this.cameraColorCurves) {
  60925. this._defines.CAMERACOLORCURVES = true;
  60926. }
  60927. if (this.overloadedShadeIntensity != 1 ||
  60928. this.overloadedShadowIntensity != 1) {
  60929. this._defines.OVERLOADEDSHADOWVALUES = true;
  60930. }
  60931. if (this.overloadedMicroSurfaceIntensity > 0 ||
  60932. this.overloadedEmissiveIntensity > 0 ||
  60933. this.overloadedReflectivityIntensity > 0 ||
  60934. this.overloadedAlbedoIntensity > 0 ||
  60935. this.overloadedAmbientIntensity > 0 ||
  60936. this.overloadedReflectionIntensity > 0) {
  60937. this._defines.OVERLOADEDVALUES = true;
  60938. }
  60939. // Point size
  60940. if (this.pointsCloud || scene.forcePointsCloud) {
  60941. this._defines.POINTSIZE = true;
  60942. }
  60943. // Fog
  60944. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  60945. this._defines.FOG = true;
  60946. }
  60947. if (scene.lightsEnabled && !this.disableLighting) {
  60948. needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, this._defines, this.maxSimultaneousLights) || needNormals;
  60949. }
  60950. if (BABYLON.StandardMaterial.FresnelEnabled) {
  60951. // Fresnel
  60952. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  60953. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  60954. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  60955. this._defines.OPACITYFRESNEL = true;
  60956. }
  60957. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  60958. this._defines.EMISSIVEFRESNEL = true;
  60959. }
  60960. needNormals = true;
  60961. this._defines.FRESNEL = true;
  60962. }
  60963. }
  60964. if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
  60965. this._defines.SPECULAROVERALPHA = true;
  60966. }
  60967. if (this.usePhysicalLightFalloff) {
  60968. this._defines.USEPHYSICALLIGHTFALLOFF = true;
  60969. }
  60970. if (this.useRadianceOverAlpha) {
  60971. this._defines.RADIANCEOVERALPHA = true;
  60972. }
  60973. // Attribs
  60974. if (mesh) {
  60975. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  60976. this._defines.NORMAL = true;
  60977. }
  60978. if (needUVs) {
  60979. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  60980. this._defines.UV1 = true;
  60981. }
  60982. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  60983. this._defines.UV2 = true;
  60984. }
  60985. }
  60986. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  60987. this._defines.VERTEXCOLOR = true;
  60988. if (mesh.hasVertexAlpha) {
  60989. this._defines.VERTEXALPHA = true;
  60990. }
  60991. }
  60992. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  60993. this._defines.NUM_BONE_INFLUENCERS = mesh.numBoneInfluencers;
  60994. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  60995. }
  60996. // Instances
  60997. if (useInstances) {
  60998. this._defines.INSTANCES = true;
  60999. }
  61000. }
  61001. // Get correct effect
  61002. if (!this._defines.isEqual(this._cachedDefines)) {
  61003. this._defines.cloneTo(this._cachedDefines);
  61004. scene.resetCachedMaterial();
  61005. // Fallbacks
  61006. var fallbacks = new BABYLON.EffectFallbacks();
  61007. if (this._defines.REFLECTION) {
  61008. fallbacks.addFallback(0, "REFLECTION");
  61009. }
  61010. if (this._defines.REFRACTION) {
  61011. fallbacks.addFallback(0, "REFRACTION");
  61012. }
  61013. if (this._defines.REFLECTIVITY) {
  61014. fallbacks.addFallback(0, "REFLECTIVITY");
  61015. }
  61016. if (this._defines.BUMP) {
  61017. fallbacks.addFallback(0, "BUMP");
  61018. }
  61019. if (this._defines.PARALLAX) {
  61020. fallbacks.addFallback(1, "PARALLAX");
  61021. }
  61022. if (this._defines.PARALLAXOCCLUSION) {
  61023. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  61024. }
  61025. if (this._defines.SPECULAROVERALPHA) {
  61026. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  61027. }
  61028. if (this._defines.FOG) {
  61029. fallbacks.addFallback(1, "FOG");
  61030. }
  61031. if (this._defines.POINTSIZE) {
  61032. fallbacks.addFallback(0, "POINTSIZE");
  61033. }
  61034. if (this._defines.LOGARITHMICDEPTH) {
  61035. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  61036. }
  61037. BABYLON.MaterialHelper.HandleFallbacksForShadows(this._defines, fallbacks, this.maxSimultaneousLights);
  61038. if (this._defines.SPECULARTERM) {
  61039. fallbacks.addFallback(0, "SPECULARTERM");
  61040. }
  61041. if (this._defines.OPACITYFRESNEL) {
  61042. fallbacks.addFallback(1, "OPACITYFRESNEL");
  61043. }
  61044. if (this._defines.EMISSIVEFRESNEL) {
  61045. fallbacks.addFallback(2, "EMISSIVEFRESNEL");
  61046. }
  61047. if (this._defines.FRESNEL) {
  61048. fallbacks.addFallback(3, "FRESNEL");
  61049. }
  61050. if (this._defines.NUM_BONE_INFLUENCERS > 0) {
  61051. fallbacks.addCPUSkinningFallback(0, mesh);
  61052. }
  61053. //Attributes
  61054. var attribs = [BABYLON.VertexBuffer.PositionKind];
  61055. if (this._defines.NORMAL) {
  61056. attribs.push(BABYLON.VertexBuffer.NormalKind);
  61057. }
  61058. if (this._defines.UV1) {
  61059. attribs.push(BABYLON.VertexBuffer.UVKind);
  61060. }
  61061. if (this._defines.UV2) {
  61062. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  61063. }
  61064. if (this._defines.VERTEXCOLOR) {
  61065. attribs.push(BABYLON.VertexBuffer.ColorKind);
  61066. }
  61067. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, this._defines, fallbacks);
  61068. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, this._defines);
  61069. // Legacy browser patch
  61070. var shaderName = "pbr";
  61071. if (!scene.getEngine().getCaps().standardDerivatives) {
  61072. shaderName = "legacypbr";
  61073. }
  61074. var join = this._defines.toString();
  61075. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  61076. "vFogInfos", "vFogColor", "pointSize",
  61077. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vReflectivityInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  61078. "mBones",
  61079. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  61080. "depthValues",
  61081. "opacityParts", "emissiveLeftColor", "emissiveRightColor",
  61082. "vLightingIntensity", "vOverloadedShadowIntensity", "vOverloadedIntensity", "vOverloadedAlbedo", "vOverloadedReflection", "vOverloadedReflectivity", "vOverloadedEmissive", "vOverloadedMicroSurface",
  61083. "logarithmicDepthConstant",
  61084. "vSphericalX", "vSphericalY", "vSphericalZ",
  61085. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  61086. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  61087. "vMicrosurfaceTextureLods",
  61088. "vCameraInfos"
  61089. ];
  61090. var samplers = ["albedoSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "reflectivitySampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  61091. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  61092. BABYLON.ColorGradingTexture.PrepareUniformsAndSamplers(uniforms, samplers);
  61093. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList(uniforms, samplers, this._defines, this.maxSimultaneousLights);
  61094. this._effect = scene.getEngine().createEffect(shaderName, attribs, uniforms, samplers, join, fallbacks, this.onCompiled, this.onError, { maxSimultaneousLights: this.maxSimultaneousLights });
  61095. }
  61096. if (!this._effect.isReady()) {
  61097. return false;
  61098. }
  61099. this._renderId = scene.getRenderId();
  61100. this._wasPreviouslyReady = true;
  61101. if (mesh) {
  61102. if (!mesh._materialDefines) {
  61103. mesh._materialDefines = new PBRMaterialDefines();
  61104. }
  61105. this._defines.cloneTo(mesh._materialDefines);
  61106. }
  61107. return true;
  61108. };
  61109. PBRMaterial.prototype.unbind = function () {
  61110. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  61111. this._effect.setTexture("reflection2DSampler", null);
  61112. }
  61113. if (this.refractionTexture && this.refractionTexture.isRenderTarget) {
  61114. this._effect.setTexture("refraction2DSampler", null);
  61115. }
  61116. _super.prototype.unbind.call(this);
  61117. };
  61118. PBRMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  61119. this._effect.setMatrix("world", world);
  61120. };
  61121. PBRMaterial.prototype.bind = function (world, mesh) {
  61122. this._myScene = this.getScene();
  61123. // Matrices
  61124. this.bindOnlyWorldMatrix(world);
  61125. // Bones
  61126. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  61127. if (this._myScene.getCachedMaterial() !== this) {
  61128. this._effect.setMatrix("viewProjection", this._myScene.getTransformMatrix());
  61129. if (BABYLON.StandardMaterial.FresnelEnabled) {
  61130. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  61131. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  61132. }
  61133. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  61134. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  61135. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  61136. }
  61137. }
  61138. // Textures
  61139. if (this._myScene.texturesEnabled) {
  61140. if (this.albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  61141. this._effect.setTexture("albedoSampler", this.albedoTexture);
  61142. this._effect.setFloat2("vAlbedoInfos", this.albedoTexture.coordinatesIndex, this.albedoTexture.level);
  61143. this._effect.setMatrix("albedoMatrix", this.albedoTexture.getTextureMatrix());
  61144. }
  61145. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  61146. this._effect.setTexture("ambientSampler", this.ambientTexture);
  61147. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  61148. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  61149. }
  61150. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  61151. this._effect.setTexture("opacitySampler", this.opacityTexture);
  61152. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  61153. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  61154. }
  61155. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  61156. this._microsurfaceTextureLods.x = Math.round(Math.log(this.reflectionTexture.getSize().width) * Math.LOG2E);
  61157. if (this.reflectionTexture.isCube) {
  61158. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  61159. }
  61160. else {
  61161. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  61162. }
  61163. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  61164. this._effect.setFloat2("vReflectionInfos", this.reflectionTexture.level, 0);
  61165. if (this._defines.USESPHERICALFROMREFLECTIONMAP) {
  61166. this._effect.setFloat3("vSphericalX", this.reflectionTexture.sphericalPolynomial.x.x, this.reflectionTexture.sphericalPolynomial.x.y, this.reflectionTexture.sphericalPolynomial.x.z);
  61167. this._effect.setFloat3("vSphericalY", this.reflectionTexture.sphericalPolynomial.y.x, this.reflectionTexture.sphericalPolynomial.y.y, this.reflectionTexture.sphericalPolynomial.y.z);
  61168. this._effect.setFloat3("vSphericalZ", this.reflectionTexture.sphericalPolynomial.z.x, this.reflectionTexture.sphericalPolynomial.z.y, this.reflectionTexture.sphericalPolynomial.z.z);
  61169. this._effect.setFloat3("vSphericalXX", this.reflectionTexture.sphericalPolynomial.xx.x, this.reflectionTexture.sphericalPolynomial.xx.y, this.reflectionTexture.sphericalPolynomial.xx.z);
  61170. this._effect.setFloat3("vSphericalYY", this.reflectionTexture.sphericalPolynomial.yy.x, this.reflectionTexture.sphericalPolynomial.yy.y, this.reflectionTexture.sphericalPolynomial.yy.z);
  61171. this._effect.setFloat3("vSphericalZZ", this.reflectionTexture.sphericalPolynomial.zz.x, this.reflectionTexture.sphericalPolynomial.zz.y, this.reflectionTexture.sphericalPolynomial.zz.z);
  61172. this._effect.setFloat3("vSphericalXY", this.reflectionTexture.sphericalPolynomial.xy.x, this.reflectionTexture.sphericalPolynomial.xy.y, this.reflectionTexture.sphericalPolynomial.xy.z);
  61173. this._effect.setFloat3("vSphericalYZ", this.reflectionTexture.sphericalPolynomial.yz.x, this.reflectionTexture.sphericalPolynomial.yz.y, this.reflectionTexture.sphericalPolynomial.yz.z);
  61174. this._effect.setFloat3("vSphericalZX", this.reflectionTexture.sphericalPolynomial.zx.x, this.reflectionTexture.sphericalPolynomial.zx.y, this.reflectionTexture.sphericalPolynomial.zx.z);
  61175. }
  61176. }
  61177. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  61178. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  61179. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  61180. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  61181. }
  61182. if (this.lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  61183. this._effect.setTexture("lightmapSampler", this.lightmapTexture);
  61184. this._effect.setFloat2("vLightmapInfos", this.lightmapTexture.coordinatesIndex, this.lightmapTexture.level);
  61185. this._effect.setMatrix("lightmapMatrix", this.lightmapTexture.getTextureMatrix());
  61186. }
  61187. if (this.reflectivityTexture && BABYLON.StandardMaterial.SpecularTextureEnabled) {
  61188. this._effect.setTexture("reflectivitySampler", this.reflectivityTexture);
  61189. this._effect.setFloat2("vReflectivityInfos", this.reflectivityTexture.coordinatesIndex, this.reflectivityTexture.level);
  61190. this._effect.setMatrix("reflectivityMatrix", this.reflectivityTexture.getTextureMatrix());
  61191. }
  61192. if (this.bumpTexture && this._myScene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this.disableBumpMap) {
  61193. this._effect.setTexture("bumpSampler", this.bumpTexture);
  61194. this._effect.setFloat3("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level, this.parallaxScaleBias);
  61195. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  61196. }
  61197. if (this.refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  61198. this._microsurfaceTextureLods.y = Math.round(Math.log(this.refractionTexture.getSize().width) * Math.LOG2E);
  61199. var depth = 1.0;
  61200. if (this.refractionTexture.isCube) {
  61201. this._effect.setTexture("refractionCubeSampler", this.refractionTexture);
  61202. }
  61203. else {
  61204. this._effect.setTexture("refraction2DSampler", this.refractionTexture);
  61205. this._effect.setMatrix("refractionMatrix", this.refractionTexture.getReflectionTextureMatrix());
  61206. if (this.refractionTexture.depth) {
  61207. depth = this.refractionTexture.depth;
  61208. }
  61209. }
  61210. this._effect.setFloat4("vRefractionInfos", this.refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  61211. }
  61212. if ((this.reflectionTexture || this.refractionTexture)) {
  61213. this._effect.setFloat2("vMicrosurfaceTextureLods", this._microsurfaceTextureLods.x, this._microsurfaceTextureLods.y);
  61214. }
  61215. if (this.cameraColorGradingTexture && BABYLON.StandardMaterial.ColorGradingTextureEnabled) {
  61216. BABYLON.ColorGradingTexture.Bind(this.cameraColorGradingTexture, this._effect);
  61217. }
  61218. }
  61219. // Clip plane
  61220. BABYLON.MaterialHelper.BindClipPlane(this._effect, this._myScene);
  61221. // Point size
  61222. if (this.pointsCloud) {
  61223. this._effect.setFloat("pointSize", this.pointSize);
  61224. }
  61225. // Colors
  61226. this._myScene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  61227. // GAMMA CORRECTION.
  61228. this.convertColorToLinearSpaceToRef(this.reflectivityColor, PBRMaterial._scaledReflectivity);
  61229. this._effect.setVector3("vEyePosition", this._myScene._mirroredCameraPosition ? this._myScene._mirroredCameraPosition : this._myScene.activeCamera.position);
  61230. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  61231. this._effect.setColor4("vReflectivityColor", PBRMaterial._scaledReflectivity, this.microSurface);
  61232. // GAMMA CORRECTION.
  61233. this.convertColorToLinearSpaceToRef(this.emissiveColor, PBRMaterial._scaledEmissive);
  61234. this._effect.setColor3("vEmissiveColor", PBRMaterial._scaledEmissive);
  61235. // GAMMA CORRECTION.
  61236. this.convertColorToLinearSpaceToRef(this.reflectionColor, PBRMaterial._scaledReflection);
  61237. this._effect.setColor3("vReflectionColor", PBRMaterial._scaledReflection);
  61238. }
  61239. if (this._myScene.getCachedMaterial() !== this || !this.isFrozen) {
  61240. // GAMMA CORRECTION.
  61241. this.convertColorToLinearSpaceToRef(this.albedoColor, PBRMaterial._scaledAlbedo);
  61242. this._effect.setColor4("vAlbedoColor", PBRMaterial._scaledAlbedo, this.alpha * mesh.visibility);
  61243. // Lights
  61244. if (this._myScene.lightsEnabled && !this.disableLighting) {
  61245. PBRMaterial.BindLights(this._myScene, mesh, this._effect, this._defines, this.useScalarInLinearSpace, this.maxSimultaneousLights, this.usePhysicalLightFalloff);
  61246. }
  61247. // View
  61248. if (this._myScene.fogEnabled && mesh.applyFog && this._myScene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  61249. this._effect.setMatrix("view", this._myScene.getViewMatrix());
  61250. }
  61251. // Fog
  61252. BABYLON.MaterialHelper.BindFogParameters(this._myScene, mesh, this._effect);
  61253. this._lightingInfos.x = this.directIntensity;
  61254. this._lightingInfos.y = this.emissiveIntensity;
  61255. this._lightingInfos.z = this.environmentIntensity;
  61256. this._lightingInfos.w = this.specularIntensity;
  61257. this._effect.setVector4("vLightingIntensity", this._lightingInfos);
  61258. this._overloadedShadowInfos.x = this.overloadedShadowIntensity;
  61259. this._overloadedShadowInfos.y = this.overloadedShadeIntensity;
  61260. this._effect.setVector4("vOverloadedShadowIntensity", this._overloadedShadowInfos);
  61261. this._cameraInfos.x = this.cameraExposure;
  61262. this._cameraInfos.y = this.cameraContrast;
  61263. this._effect.setVector4("vCameraInfos", this._cameraInfos);
  61264. if (this.cameraColorCurves) {
  61265. BABYLON.ColorCurves.Bind(this.cameraColorCurves, this._effect);
  61266. }
  61267. this._overloadedIntensity.x = this.overloadedAmbientIntensity;
  61268. this._overloadedIntensity.y = this.overloadedAlbedoIntensity;
  61269. this._overloadedIntensity.z = this.overloadedReflectivityIntensity;
  61270. this._overloadedIntensity.w = this.overloadedEmissiveIntensity;
  61271. this._effect.setVector4("vOverloadedIntensity", this._overloadedIntensity);
  61272. this.convertColorToLinearSpaceToRef(this.overloadedAmbient, this._tempColor);
  61273. this._effect.setColor3("vOverloadedAmbient", this._tempColor);
  61274. this.convertColorToLinearSpaceToRef(this.overloadedAlbedo, this._tempColor);
  61275. this._effect.setColor3("vOverloadedAlbedo", this._tempColor);
  61276. this.convertColorToLinearSpaceToRef(this.overloadedReflectivity, this._tempColor);
  61277. this._effect.setColor3("vOverloadedReflectivity", this._tempColor);
  61278. this.convertColorToLinearSpaceToRef(this.overloadedEmissive, this._tempColor);
  61279. this._effect.setColor3("vOverloadedEmissive", this._tempColor);
  61280. this.convertColorToLinearSpaceToRef(this.overloadedReflection, this._tempColor);
  61281. this._effect.setColor3("vOverloadedReflection", this._tempColor);
  61282. this._overloadedMicroSurface.x = this.overloadedMicroSurface;
  61283. this._overloadedMicroSurface.y = this.overloadedMicroSurfaceIntensity;
  61284. this._overloadedMicroSurface.z = this.overloadedReflectionIntensity;
  61285. this._effect.setVector3("vOverloadedMicroSurface", this._overloadedMicroSurface);
  61286. // Log. depth
  61287. BABYLON.MaterialHelper.BindLogDepth(this._defines, this._effect, this._myScene);
  61288. }
  61289. _super.prototype.bind.call(this, world, mesh);
  61290. this._myScene = null;
  61291. };
  61292. PBRMaterial.prototype.getAnimatables = function () {
  61293. var results = [];
  61294. if (this.albedoTexture && this.albedoTexture.animations && this.albedoTexture.animations.length > 0) {
  61295. results.push(this.albedoTexture);
  61296. }
  61297. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  61298. results.push(this.ambientTexture);
  61299. }
  61300. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  61301. results.push(this.opacityTexture);
  61302. }
  61303. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  61304. results.push(this.reflectionTexture);
  61305. }
  61306. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  61307. results.push(this.emissiveTexture);
  61308. }
  61309. if (this.reflectivityTexture && this.reflectivityTexture.animations && this.reflectivityTexture.animations.length > 0) {
  61310. results.push(this.reflectivityTexture);
  61311. }
  61312. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  61313. results.push(this.bumpTexture);
  61314. }
  61315. if (this.lightmapTexture && this.lightmapTexture.animations && this.lightmapTexture.animations.length > 0) {
  61316. results.push(this.lightmapTexture);
  61317. }
  61318. if (this.refractionTexture && this.refractionTexture.animations && this.refractionTexture.animations.length > 0) {
  61319. results.push(this.refractionTexture);
  61320. }
  61321. if (this.cameraColorGradingTexture && this.cameraColorGradingTexture.animations && this.cameraColorGradingTexture.animations.length > 0) {
  61322. results.push(this.cameraColorGradingTexture);
  61323. }
  61324. return results;
  61325. };
  61326. PBRMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  61327. if (forceDisposeTextures) {
  61328. if (this.albedoTexture) {
  61329. this.albedoTexture.dispose();
  61330. }
  61331. if (this.ambientTexture) {
  61332. this.ambientTexture.dispose();
  61333. }
  61334. if (this.opacityTexture) {
  61335. this.opacityTexture.dispose();
  61336. }
  61337. if (this.reflectionTexture) {
  61338. this.reflectionTexture.dispose();
  61339. }
  61340. if (this.emissiveTexture) {
  61341. this.emissiveTexture.dispose();
  61342. }
  61343. if (this.reflectivityTexture) {
  61344. this.reflectivityTexture.dispose();
  61345. }
  61346. if (this.bumpTexture) {
  61347. this.bumpTexture.dispose();
  61348. }
  61349. if (this.lightmapTexture) {
  61350. this.lightmapTexture.dispose();
  61351. }
  61352. if (this.refractionTexture) {
  61353. this.refractionTexture.dispose();
  61354. }
  61355. if (this.cameraColorGradingTexture) {
  61356. this.cameraColorGradingTexture.dispose();
  61357. }
  61358. }
  61359. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  61360. };
  61361. PBRMaterial.prototype.clone = function (name) {
  61362. var _this = this;
  61363. return BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  61364. };
  61365. PBRMaterial.prototype.serialize = function () {
  61366. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  61367. serializationObject.customType = "BABYLON.PBRMaterial";
  61368. return serializationObject;
  61369. };
  61370. // Statics
  61371. PBRMaterial.Parse = function (source, scene, rootUrl) {
  61372. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  61373. };
  61374. PBRMaterial._scaledAlbedo = new BABYLON.Color3();
  61375. PBRMaterial._scaledReflectivity = new BABYLON.Color3();
  61376. PBRMaterial._scaledEmissive = new BABYLON.Color3();
  61377. PBRMaterial._scaledReflection = new BABYLON.Color3();
  61378. __decorate([
  61379. BABYLON.serialize()
  61380. ], PBRMaterial.prototype, "directIntensity", void 0);
  61381. __decorate([
  61382. BABYLON.serialize()
  61383. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  61384. __decorate([
  61385. BABYLON.serialize()
  61386. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  61387. __decorate([
  61388. BABYLON.serialize()
  61389. ], PBRMaterial.prototype, "specularIntensity", void 0);
  61390. __decorate([
  61391. BABYLON.serialize()
  61392. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  61393. __decorate([
  61394. BABYLON.serialize()
  61395. ], PBRMaterial.prototype, "overloadedShadowIntensity", void 0);
  61396. __decorate([
  61397. BABYLON.serialize()
  61398. ], PBRMaterial.prototype, "overloadedShadeIntensity", void 0);
  61399. __decorate([
  61400. BABYLON.serialize()
  61401. ], PBRMaterial.prototype, "cameraExposure", void 0);
  61402. __decorate([
  61403. BABYLON.serialize()
  61404. ], PBRMaterial.prototype, "cameraContrast", void 0);
  61405. __decorate([
  61406. BABYLON.serializeAsTexture()
  61407. ], PBRMaterial.prototype, "cameraColorGradingTexture", void 0);
  61408. __decorate([
  61409. BABYLON.serializeAsColorCurves()
  61410. ], PBRMaterial.prototype, "cameraColorCurves", void 0);
  61411. __decorate([
  61412. BABYLON.serializeAsColor3()
  61413. ], PBRMaterial.prototype, "overloadedAmbient", void 0);
  61414. __decorate([
  61415. BABYLON.serialize()
  61416. ], PBRMaterial.prototype, "overloadedAmbientIntensity", void 0);
  61417. __decorate([
  61418. BABYLON.serializeAsColor3()
  61419. ], PBRMaterial.prototype, "overloadedAlbedo", void 0);
  61420. __decorate([
  61421. BABYLON.serialize()
  61422. ], PBRMaterial.prototype, "overloadedAlbedoIntensity", void 0);
  61423. __decorate([
  61424. BABYLON.serializeAsColor3()
  61425. ], PBRMaterial.prototype, "overloadedReflectivity", void 0);
  61426. __decorate([
  61427. BABYLON.serialize()
  61428. ], PBRMaterial.prototype, "overloadedReflectivityIntensity", void 0);
  61429. __decorate([
  61430. BABYLON.serializeAsColor3()
  61431. ], PBRMaterial.prototype, "overloadedEmissive", void 0);
  61432. __decorate([
  61433. BABYLON.serialize()
  61434. ], PBRMaterial.prototype, "overloadedEmissiveIntensity", void 0);
  61435. __decorate([
  61436. BABYLON.serializeAsColor3()
  61437. ], PBRMaterial.prototype, "overloadedReflection", void 0);
  61438. __decorate([
  61439. BABYLON.serialize()
  61440. ], PBRMaterial.prototype, "overloadedReflectionIntensity", void 0);
  61441. __decorate([
  61442. BABYLON.serialize()
  61443. ], PBRMaterial.prototype, "overloadedMicroSurface", void 0);
  61444. __decorate([
  61445. BABYLON.serialize()
  61446. ], PBRMaterial.prototype, "overloadedMicroSurfaceIntensity", void 0);
  61447. __decorate([
  61448. BABYLON.serializeAsTexture()
  61449. ], PBRMaterial.prototype, "albedoTexture", void 0);
  61450. __decorate([
  61451. BABYLON.serializeAsTexture()
  61452. ], PBRMaterial.prototype, "ambientTexture", void 0);
  61453. __decorate([
  61454. BABYLON.serializeAsTexture()
  61455. ], PBRMaterial.prototype, "opacityTexture", void 0);
  61456. __decorate([
  61457. BABYLON.serializeAsTexture()
  61458. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  61459. __decorate([
  61460. BABYLON.serializeAsTexture()
  61461. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  61462. __decorate([
  61463. BABYLON.serializeAsTexture()
  61464. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  61465. __decorate([
  61466. BABYLON.serializeAsTexture()
  61467. ], PBRMaterial.prototype, "bumpTexture", void 0);
  61468. __decorate([
  61469. BABYLON.serializeAsTexture()
  61470. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  61471. __decorate([
  61472. BABYLON.serializeAsTexture()
  61473. ], PBRMaterial.prototype, "refractionTexture", void 0);
  61474. __decorate([
  61475. BABYLON.serializeAsColor3("ambient")
  61476. ], PBRMaterial.prototype, "ambientColor", void 0);
  61477. __decorate([
  61478. BABYLON.serializeAsColor3("albedo")
  61479. ], PBRMaterial.prototype, "albedoColor", void 0);
  61480. __decorate([
  61481. BABYLON.serializeAsColor3("reflectivity")
  61482. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  61483. __decorate([
  61484. BABYLON.serializeAsColor3("reflection")
  61485. ], PBRMaterial.prototype, "reflectionColor", void 0);
  61486. __decorate([
  61487. BABYLON.serializeAsColor3("emissive")
  61488. ], PBRMaterial.prototype, "emissiveColor", void 0);
  61489. __decorate([
  61490. BABYLON.serialize()
  61491. ], PBRMaterial.prototype, "microSurface", void 0);
  61492. __decorate([
  61493. BABYLON.serialize()
  61494. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  61495. __decorate([
  61496. BABYLON.serialize()
  61497. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  61498. __decorate([
  61499. BABYLON.serializeAsFresnelParameters()
  61500. ], PBRMaterial.prototype, "opacityFresnelParameters", void 0);
  61501. __decorate([
  61502. BABYLON.serializeAsFresnelParameters()
  61503. ], PBRMaterial.prototype, "emissiveFresnelParameters", void 0);
  61504. __decorate([
  61505. BABYLON.serialize()
  61506. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  61507. __decorate([
  61508. BABYLON.serialize()
  61509. ], PBRMaterial.prototype, "linkEmissiveWithAlbedo", void 0);
  61510. __decorate([
  61511. BABYLON.serialize()
  61512. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  61513. __decorate([
  61514. BABYLON.serialize()
  61515. ], PBRMaterial.prototype, "useEmissiveAsIllumination", void 0);
  61516. __decorate([
  61517. BABYLON.serialize()
  61518. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  61519. __decorate([
  61520. BABYLON.serialize()
  61521. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  61522. __decorate([
  61523. BABYLON.serialize()
  61524. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  61525. __decorate([
  61526. BABYLON.serialize()
  61527. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  61528. __decorate([
  61529. BABYLON.serialize()
  61530. ], PBRMaterial.prototype, "useScalarInLinearSpace", void 0);
  61531. __decorate([
  61532. BABYLON.serialize()
  61533. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  61534. __decorate([
  61535. BABYLON.serialize()
  61536. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  61537. __decorate([
  61538. BABYLON.serialize()
  61539. ], PBRMaterial.prototype, "useParallax", void 0);
  61540. __decorate([
  61541. BABYLON.serialize()
  61542. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  61543. __decorate([
  61544. BABYLON.serialize()
  61545. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  61546. __decorate([
  61547. BABYLON.serialize()
  61548. ], PBRMaterial.prototype, "disableLighting", void 0);
  61549. __decorate([
  61550. BABYLON.serialize()
  61551. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  61552. __decorate([
  61553. BABYLON.serialize()
  61554. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  61555. __decorate([
  61556. BABYLON.serialize()
  61557. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  61558. __decorate([
  61559. BABYLON.serialize()
  61560. ], PBRMaterial.prototype, "useLogarithmicDepth", null);
  61561. return PBRMaterial;
  61562. })(BABYLON.Material);
  61563. BABYLON.PBRMaterial = PBRMaterial;
  61564. })(BABYLON || (BABYLON = {}));
  61565. BABYLON.Effect.ShadersStore={"anaglyphPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D leftSampler;\nvoid main(void)\n{\nvec4 leftFrag=texture2D(leftSampler,vUV);\nleftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);\nvec4 rightFrag=texture2D(textureSampler,vUV);\nrightFrag=vec4(rightFrag.r,1.0,1.0,1.0);\ngl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);\n}","blackAndWhitePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\nfloat luminance=dot(texture2D(textureSampler,vUV).rgb,vec3(0.3,0.59,0.11));\ngl_FragColor=vec4(luminance,luminance,luminance,1.0);\n}","blurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\nvoid main(void)\n{\nfloat weights[7];\nweights[0]=0.05;\nweights[1]=0.1;\nweights[2]=0.2;\nweights[3]=0.3;\nweights[4]=0.2;\nweights[5]=0.1;\nweights[6]=0.05;\nvec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);\nvec2 texelStep=texelSize*direction*blurWidth;\nvec2 start=vUV-3.0*texelStep;\nvec4 baseColor=vec4(0.,0.,0.,0.);\nvec2 texelOffset=vec2(0.,0.);\nfor (int i=0; i<7; i++)\n{\nbaseColor+=texture2D(textureSampler,start+texelOffset)*weights[i];\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\n}","chromaticAberrationPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float chromatic_aberration;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec2 centered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nfloat radius2=centered_screen_pos.x*centered_screen_pos.x\n+centered_screen_pos.y*centered_screen_pos.y;\nfloat radius=sqrt(radius2);\nvec4 original=texture2D(textureSampler,vUV);\nif (chromatic_aberration>0.0) {\n\nvec3 ref_indices=vec3(-0.3,0.0,0.3);\nfloat ref_shiftX=chromatic_aberration*radius*17.0/screen_width;\nfloat ref_shiftY=chromatic_aberration*radius*17.0/screen_height;\n\nvec2 ref_coords_r=vec2(vUV.x+ref_indices.r*ref_shiftX,vUV.y+ref_indices.r*ref_shiftY*0.5);\nvec2 ref_coords_g=vec2(vUV.x+ref_indices.g*ref_shiftX,vUV.y+ref_indices.g*ref_shiftY*0.5);\nvec2 ref_coords_b=vec2(vUV.x+ref_indices.b*ref_shiftX,vUV.y+ref_indices.b*ref_shiftY*0.5);\noriginal.r=texture2D(textureSampler,ref_coords_r).r;\noriginal.g=texture2D(textureSampler,ref_coords_g).g;\noriginal.b=texture2D(textureSampler,ref_coords_b).b;\n}\ngl_FragColor=original;\n}","colorPixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","colorVertexShader":"\nattribute vec3 position;\n\nuniform mat4 worldViewProjection;\nvoid main(void) {\ngl_Position=worldViewProjection*vec4(position,1.0);\n}","colorCorrectionPixelShader":"\nuniform sampler2D textureSampler; \nuniform sampler2D colorTable; \n\nvarying vec2 vUV;\n\nconst float SLICE_COUNT=16.0; \n\nvec4 sampleAs3DTexture(sampler2D texture,vec3 uv,float width) {\nfloat sliceSize=1.0/width; \nfloat slicePixelSize=sliceSize/width; \nfloat sliceInnerSize=slicePixelSize*(width-1.0); \nfloat zSlice0=min(floor(uv.z*width),width-1.0);\nfloat zSlice1=min(zSlice0+1.0,width-1.0);\nfloat xOffset=slicePixelSize*0.5+uv.x*sliceInnerSize;\nfloat s0=xOffset+(zSlice0*sliceSize);\nfloat s1=xOffset+(zSlice1*sliceSize);\nvec4 slice0Color=texture2D(texture,vec2(s0,uv.y));\nvec4 slice1Color=texture2D(texture,vec2(s1,uv.y));\nfloat zOffset=mod(uv.z*width,1.0);\nvec4 result=mix(slice0Color,slice1Color,zOffset);\nreturn result;\n}\nvoid main(void)\n{\nvec4 screen_color=texture2D(textureSampler,vUV);\ngl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);\n}","convolutionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform float kernel[9];\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 colorSum =\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];\nfloat kernelWeight =\nkernel[0] +\nkernel[1] +\nkernel[2] +\nkernel[3] +\nkernel[4] +\nkernel[5] +\nkernel[6] +\nkernel[7] +\nkernel[8];\nif (kernelWeight<=0.0) {\nkernelWeight=1.0;\n}\ngl_FragColor=vec4((colorSum/kernelWeight).rgb,1);\n}","defaultPixelShader":"#ifdef BUMP\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n\n#define RECIPROCAL_PI2 0.15915494\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<helperFunctions>\n\n#include<lightFragmentDeclaration>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform sampler2D diffuseSampler;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform sampler2D ambientSampler;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform vec2 vLightmapInfos;\nuniform sampler2D lightmapSampler;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\nuniform mat4 refractionMatrix;\n#endif\n#ifdef REFRACTIONFRESNEL\nuniform vec4 refractionLeftColor;\nuniform vec4 refractionRightColor;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform sampler2D specularSampler;\n#endif\n\n#include<fresnelFunction>\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvarying vec3 vDirectionW;\n#endif\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#endif\n#include<reflectionFunction>\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n#endif\n#ifdef CAMERACOLORGRADING\n#include<colorGradingDefinition> \n#include<colorGrading>\n#endif\n#ifdef CAMERACOLORCURVES\n#include<colorCurvesDefinition>\n#include<colorCurves>\n#endif\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\n#ifdef DIFFUSE\nvec2 diffuseUV=vDiffuseUV;\n#endif\n#include<bumpFragment>\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,diffuseUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#ifdef ALPHAFROMDIFFUSE\nalpha*=baseColor.a;\n#endif\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV).rgb*vAmbientInfos.y;\n#endif\n\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nvec4 specularMapColor=texture2D(specularSampler,vSpecularUV);\nspecularColor=specularMapColor.rgb;\n#ifdef GLOSSINESS\nglossiness=glossiness*specularMapColor.a;\n#endif\n#endif\n#else\nfloat glossiness=0.;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\nfloat shadow=1.;\n#include<lightFragment>[0..maxSimultaneousLights]\n\nvec3 refractionColor=vec3(0.,0.,0.);\n#ifdef REFRACTION\nvec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y));\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0)\n{\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb*vRefractionInfos.x;\n}\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\nrefractionColor=texture2D(refraction2DSampler,refractionCoords).rgb*vRefractionInfos.x;\n#endif\n#endif\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_3D\n#ifdef ROUGHNESS\nfloat bias=vReflectionInfos.y;\n#ifdef SPECULARTERM\n#ifdef SPECULAR\n#ifdef GLOSSINESS\nbias*=(1.0-specularMapColor.a);\n#endif\n#endif\n#endif\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias).rgb*vReflectionInfos.x;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb*vReflectionInfos.x;\n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb*vReflectionInfos.x;\n#endif\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\n#ifdef REFLECTIONFRESNELFROMSPECULAR\n#ifdef SPECULARTERM\nreflectionColor*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n#endif\n#ifdef REFRACTIONFRESNEL\nfloat refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);\nrefractionColor*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\n#ifdef LINKEMISSIVEWITHDIFFUSE\nvec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#endif\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n#ifdef REFLECTIONOVERALPHA\nalpha=clamp(alpha+dot(reflectionColor,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 color=vec4(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+emissiveColor+refractionColor,0.0,1.0),alpha);\n#else\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+refractionColor,alpha);\n#endif\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV).rgb*vLightmapInfos.y;\n#ifdef USELIGHTMAPASSHADOWMAP\ncolor.rgb*=lightmapColor;\n#else\ncolor.rgb+=lightmapColor;\n#endif\n#endif\n#include<logDepthFragment>\n#include<fogFragment>\n#ifdef CAMERACOLORGRADING\ncolor=colorGrades(color);\n#endif\n#ifdef CAMERACOLORCURVES\ncolor.rgb=applyColorCurves(color.rgb);\n#endif\ngl_FragColor=color;\n}","defaultVertexShader":"\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#include<pointCloudVertexDeclaration>\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<shadowsVertexDeclaration>[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=position;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef DIFFUSE\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef AMBIENT\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef OPACITY\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef EMISSIVE\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef LIGHTMAP\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef BUMP\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n#include<pointCloudVertex>\n#include<logDepthVertex>\n}","depthPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nuniform float far;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\nfloat depth=(gl_FragCoord.z/gl_FragCoord.w)/far;\ngl_FragColor=vec4(depth,depth*depth,0.0,1.0);\n}","depthVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","depthBoxBlurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nvoid main(void)\n{\nvec4 colorDepth=vec4(0.0);\nfor (int x=-OFFSET; x<=OFFSET; x++)\nfor (int y=-OFFSET; y<=OFFSET; y++)\ncolorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);\ngl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));\n}","depthOfFieldPixelShader":"\n\n\n\n\nuniform sampler2D textureSampler;\nuniform sampler2D highlightsSampler;\nuniform sampler2D depthSampler;\nuniform sampler2D grainSampler;\n\nuniform float grain_amount;\nuniform bool blur_noise;\nuniform float screen_width;\nuniform float screen_height;\nuniform float distortion;\nuniform bool dof_enabled;\n\nuniform float screen_distance; \nuniform float aperture;\nuniform float darken;\nuniform float edge_blur;\nuniform bool highlights;\n\nuniform float near;\nuniform float far;\n\nvarying vec2 vUV;\n\n#define PI 3.14159265\n#define TWOPI 6.28318530\n#define inverse_focal_length 0.1 \n\nvec2 centered_screen_pos;\nvec2 distorted_coords;\nfloat radius2;\nfloat radius;\n\nvec2 rand(vec2 co)\n{\nfloat noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));\nfloat noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));\nreturn clamp(vec2(noise1,noise2),0.0,1.0);\n}\n\nvec2 getDistortedCoords(vec2 coords) {\nif (distortion == 0.0) { return coords; }\nvec2 direction=1.0*normalize(centered_screen_pos);\nvec2 dist_coords=vec2(0.5,0.5);\ndist_coords.x=0.5+direction.x*radius2*1.0;\ndist_coords.y=0.5+direction.y*radius2*1.0;\nfloat dist_amount=clamp(distortion*0.23,0.0,1.0);\ndist_coords=mix(coords,dist_coords,dist_amount);\nreturn dist_coords;\n}\n\nfloat sampleScreen(inout vec4 color,const in vec2 offset,const in float weight) {\n\nvec2 coords=distorted_coords;\nfloat angle=rand(coords*100.0).x*TWOPI;\ncoords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));\ncolor+=texture2D(textureSampler,coords)*weight;\nreturn weight;\n}\n\nfloat getBlurLevel(float size) {\nreturn min(3.0,ceil(size/1.0));\n}\n\nvec4 getBlurColor(float size) {\nvec4 col=texture2D(textureSampler,distorted_coords);\nif (size == 0.0) { return col; }\n\n\nfloat blur_level=getBlurLevel(size);\nfloat w=(size/screen_width);\nfloat h=(size/screen_height);\nfloat total_weight=1.0;\nvec2 sample_coords;\ntotal_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);\ntotal_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);\ntotal_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);\ntotal_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);\ntotal_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);\ntotal_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);\ntotal_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);\ntotal_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);\ntotal_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);\nif (blur_level>1.0) {\ntotal_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);\ntotal_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);\ntotal_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);\ntotal_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);\ntotal_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);\ntotal_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);\ntotal_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);\ntotal_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);\ntotal_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);\n}\nif (blur_level>2.0) {\ntotal_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);\ntotal_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);\ntotal_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);\ntotal_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);\ntotal_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);\ntotal_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);\ntotal_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);\ntotal_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);\ntotal_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);\n}\ncol/=total_weight; \n\nif (darken>0.0) {\ncol.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);\n}\n\n\n\n\nreturn col;\n}\nvoid main(void)\n{\n\ncentered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nradius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;\nradius=sqrt(radius2);\ndistorted_coords=getDistortedCoords(vUV); \nvec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); \nfloat depth=texture2D(depthSampler,distorted_coords).r; \nfloat distance=near+(far-near)*depth; \nvec4 color=texture2D(textureSampler,vUV); \n\n\nfloat coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));\n\nif (dof_enabled == false || coc<0.07) { coc=0.0; }\n\nfloat edge_blur_amount=0.0;\nif (edge_blur>0.0) {\nedge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;\n}\n\nfloat blur_amount=max(edge_blur_amount,coc);\n\nif (blur_amount == 0.0) {\ngl_FragColor=texture2D(textureSampler,distorted_coords);\n}\nelse {\n\ngl_FragColor=getBlurColor(blur_amount*1.7);\n\nif (highlights) {\ngl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;\n}\nif (blur_noise) {\n\nvec2 noise=rand(distorted_coords)*0.01*blur_amount;\nvec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);\ngl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;\n}\n}\n\nif (grain_amount>0.0) {\nvec4 grain_color=texture2D(grainSampler,texels_coords*0.003);\ngl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;\n}\n}\n","displayPassPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D passSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(passSampler,vUV);\n}","ellipse2dPixelShader":"varying vec4 vColor;\nvoid main(void) {\ngl_FragColor=vColor;\n}","ellipse2dVertexShader":"\n#ifdef Instanced\n#define att attribute\n#else\n#define att uniform\n#endif\nattribute float index;\natt vec2 zBias;\natt vec4 transformX;\natt vec4 transformY;\natt float opacity;\n#ifdef Border\natt float borderThickness;\n#endif\n#ifdef FillSolid\natt vec4 fillSolidColor;\n#endif\n#ifdef BorderSolid\natt vec4 borderSolidColor;\n#endif\n#ifdef FillGradient\natt vec4 fillGradientColor1;\natt vec4 fillGradientColor2;\natt vec4 fillGradientTY;\n#endif\n#ifdef BorderGradient\natt vec4 borderGradientColor1;\natt vec4 borderGradientColor2;\natt vec4 borderGradientTY;\n#endif\n\natt vec3 properties;\n#define TWOPI 6.28318530\n\nvarying vec2 vUV;\nvarying vec4 vColor;\nvoid main(void) {\nvec2 pos2;\n#ifdef Border\nfloat w=properties.x;\nfloat h=properties.y;\nfloat ms=properties.z;\nvec2 borderOffset=vec2(1.0,1.0);\nfloat segi=index;\nif (index<ms) {\nborderOffset=vec2(1.0-(borderThickness*2.0/w),1.0-(borderThickness*2.0/h));\n}\nelse {\nsegi-=ms;\n}\nfloat angle=TWOPI*segi/ms;\npos2.x=(cos(angle)/2.0)+0.5;\npos2.y=(sin(angle)/2.0)+0.5;\npos2.x=((pos2.x-0.5)*borderOffset.x)+0.5;\npos2.y=((pos2.y-0.5)*borderOffset.y)+0.5;\n#else\nif (index == 0.0) {\npos2=vec2(0.5,0.5);\n}\nelse {\nfloat ms=properties.z;\nfloat angle=TWOPI*(index-1.0)/ms;\npos2.x=(cos(angle)/2.0)+0.5;\npos2.y=(sin(angle)/2.0)+0.5;\n}\n#endif\n#ifdef FillSolid\nvColor=fillSolidColor;\n#endif\n#ifdef BorderSolid\nvColor=borderSolidColor;\n#endif\n#ifdef FillGradient\nfloat v=dot(vec4(pos2.xy,1,1),fillGradientTY);\nvColor=mix(fillGradientColor2,fillGradientColor1,v); \n#endif\n#ifdef BorderGradient\nfloat v=dot(vec4(pos2.xy,1,1),borderGradientTY);\nvColor=mix(borderGradientColor2,borderGradientColor1,v); \n#endif\nvColor.a*=opacity;\nvec4 pos;\npos.xy=pos2.xy*properties.xy;\npos.z=1.0;\npos.w=1.0;\ngl_Position=vec4(dot(pos,transformX),dot(pos,transformY),zBias.x,1);\n}","filterPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform mat4 kernelMatrix;\nvoid main(void)\n{\nvec3 baseColor=texture2D(textureSampler,vUV).rgb;\nvec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;\ngl_FragColor=vec4(updatedColor,1.0);\n}","fxaaPixelShader":"#define FXAA_REDUCE_MIN (1.0/128.0)\n#define FXAA_REDUCE_MUL (1.0/8.0)\n#define FXAA_SPAN_MAX 8.0\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 texelSize;\nvoid main(){\nvec2 localTexelSize=texelSize;\nvec4 rgbNW=texture2D(textureSampler,(vUV+vec2(-1.0,-1.0)*localTexelSize));\nvec4 rgbNE=texture2D(textureSampler,(vUV+vec2(1.0,-1.0)*localTexelSize));\nvec4 rgbSW=texture2D(textureSampler,(vUV+vec2(-1.0,1.0)*localTexelSize));\nvec4 rgbSE=texture2D(textureSampler,(vUV+vec2(1.0,1.0)*localTexelSize));\nvec4 rgbM=texture2D(textureSampler,vUV);\nvec4 luma=vec4(0.299,0.587,0.114,1.0);\nfloat lumaNW=dot(rgbNW,luma);\nfloat lumaNE=dot(rgbNE,luma);\nfloat lumaSW=dot(rgbSW,luma);\nfloat lumaSE=dot(rgbSE,luma);\nfloat lumaM=dot(rgbM,luma);\nfloat lumaMin=min(lumaM,min(min(lumaNW,lumaNE),min(lumaSW,lumaSE)));\nfloat lumaMax=max(lumaM,max(max(lumaNW,lumaNE),max(lumaSW,lumaSE)));\nvec2 dir=vec2(-((lumaNW+lumaNE)-(lumaSW+lumaSE)),((lumaNW+lumaSW)-(lumaNE+lumaSE)));\nfloat dirReduce=max(\n(lumaNW+lumaNE+lumaSW+lumaSE)*(0.25*FXAA_REDUCE_MUL),\nFXAA_REDUCE_MIN);\nfloat rcpDirMin=1.0/(min(abs(dir.x),abs(dir.y))+dirReduce);\ndir=min(vec2(FXAA_SPAN_MAX,FXAA_SPAN_MAX),\nmax(vec2(-FXAA_SPAN_MAX,-FXAA_SPAN_MAX),\ndir*rcpDirMin))*localTexelSize;\nvec4 rgbA=0.5*(\ntexture2D(textureSampler,vUV+dir*(1.0/3.0-0.5)) +\ntexture2D(textureSampler,vUV+dir*(2.0/3.0-0.5)));\nvec4 rgbB=rgbA*0.5+0.25*(\ntexture2D(textureSampler,vUV+dir*-0.5) +\ntexture2D(textureSampler,vUV+dir*0.5));\nfloat lumaB=dot(rgbB,luma);\nif ((lumaB<lumaMin) || (lumaB>lumaMax)) {\ngl_FragColor=rgbA;\n}\nelse {\ngl_FragColor=rgbB;\n}\n}","hdrPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(GAUSSIAN_BLUR_H) || defined(GAUSSIAN_BLUR_V)\nuniform float blurOffsets[9];\nuniform float blurWeights[9];\nuniform float multiplier;\nvoid main(void) {\nvec4 color=vec4(0.0,0.0,0.0,0.0);\nfor (int i=0; i<9; i++) {\n#ifdef GAUSSIAN_BLUR_H\ncolor+=(texture2D(textureSampler,vUV+vec2(blurOffsets[i]*multiplier,0.0))*blurWeights[i]);\n#else\ncolor+=(texture2D(textureSampler,vUV+vec2(0.0,blurOffsets[i]*multiplier))*blurWeights[i]);\n#endif\n}\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nvoid main() {\nvec4 sum=texture2D(textureSampler,vUV)+texture2D(otherSampler,vUV);\nsum.a=clamp(sum.a,0.0,1.0);\ngl_FragColor=sum;\n}\n#endif\n#if defined(LUMINANCE_GENERATOR)\nuniform vec2 lumOffsets[4];\nvoid main() {\nfloat average=0.0;\nvec4 color=vec4(0.0,0.0,0.0,0.0);\nfloat maximum=-1e20;\nfor (int i=0; i<4; i++) {\ncolor=texture2D(textureSampler,vUV+lumOffsets[i]);\nfloat GreyValue=length(color.rgb);\nmaximum=max(maximum,GreyValue);\naverage+=(0.25*log(1e-5+GreyValue));\n}\naverage=exp(average);\ngl_FragColor=vec4(average,maximum,0.0,1.0);\n}\n#endif\n#if defined(DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];\nuniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLE\nvec4 pack(float value) {\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(value*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvoid main() {\nvec4 color=vec4(0.0,0.0,0.0,0.0);\nfloat average=0.0;\nfor (int i=0; i<9; i++) {\ncolor=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);\naverage+=color.r;\n}\naverage/=9.0;\n#ifndef FINAL_DOWN_SAMPLE\ngl_FragColor=vec4(average,average,0.0,1.0);\n#else\ngl_FragColor=pack(average);\n#endif\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main() {\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main() {\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(HDR)\nuniform sampler2D otherSampler;\nuniform float exposure;\nuniform float avgLuminance;\nvoid main() {\nvec4 color=texture2D(textureSampler,vUV)+texture2D(otherSampler,vUV);\nvec4 adjustedColor=color/avgLuminance*exposure;\ncolor=adjustedColor;\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n","layerPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=baseColor*color;\n}","layerVertexShader":"\nattribute vec2 position;\n\nuniform vec2 scale;\nuniform vec2 offset;\nuniform mat4 textureMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvec2 shiftedPosition=position*scale+offset;\nvUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));\ngl_Position=vec4(shiftedPosition,0.0,1.0);\n}","legacydefaultPixelShader":"#define MAP_PROJECTION 4.\n\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\n\nvarying vec3 vPositionW;\nvarying vec3 vNormalW;\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<lightFragmentDeclaration>[0..3]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform sampler2D diffuseSampler;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform sampler2D ambientSampler;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef REFLECTION\nvarying vec3 vReflectionUVW;\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\nuniform vec2 vReflectionInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform sampler2D emissiveSampler;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform sampler2D specularSampler;\n#endif\n\n#include<fresnelFunction>\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n#include<clipPlaneFragmentDeclaration>\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n\nvec3 normalW=normalize(vNormalW);\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV).rgb*vAmbientInfos.y;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\nfloat glossiness=0.;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\nglossiness=vSpecularColor.a;\n#endif\nfloat shadow=1.;\n#include<lightFragment>[0..3]\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb*vReflectionInfos.x;\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb*vReflectionInfos.x;\n#endif\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n\nfloat alpha=vDiffuseColor.a;\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef SPECULARTERM\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nspecularColor=texture2D(specularSampler,vSpecularUV).rgb*vSpecularInfos.y;\n#endif\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor,alpha);\n#include<fogFragment>\ngl_FragColor=color;\n}","legacydefaultVertexShader":"\nattribute vec3 position;\nattribute vec3 normal;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\nuniform mat4 world;\nuniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform vec2 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n\nvarying vec3 vPositionW;\nvarying vec3 vNormalW;\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<shadowsVertexDeclaration>[0..maxSimultaneousLights]\n#ifdef REFLECTION\nuniform vec3 vEyePosition;\nvarying vec3 vReflectionUVW;\nuniform mat4 reflectionMatrix;\nvec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#ifdef REFLECTIONMAP_SPHERICAL\nvec3 coords=vec3(view*vec4(worldNormal,0.0));\nreturn vec3(reflectionMatrix*vec4(coords,1.0));\n#endif\n#ifdef REFLECTIONMAP_PLANAR\nvec3 viewDir=worldPos.xyz-vEyePosition;\nvec3 coords=normalize(reflect(viewDir,worldNormal));\nreturn vec3(reflectionMatrix*vec4(coords,1));\n#endif\n#ifdef REFLECTIONMAP_CUBIC\nvec3 viewDir=worldPos.xyz-vEyePosition;\nvec3 coords=reflect(viewDir,worldNormal);\n#ifdef INVERTCUBICMAP\ncoords.y=1.0-coords.y;\n#endif\nreturn vec3(reflectionMatrix*vec4(coords,0));\n#endif\n#ifdef REFLECTIONMAP_PROJECTION\nreturn vec3(reflectionMatrix*(view*worldPos));\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nreturn position;\n#endif\n#ifdef REFLECTIONMAP_EXPLICIT\nreturn vec3(0,0,0);\n#endif\n}\n#endif\nvoid main(void) {\nmat4 finalWorld=world;\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef DIFFUSE\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef AMBIENT\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef OPACITY\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef REFLECTION\nvReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),vNormalW);\n#endif\n#ifdef EMISSIVE\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef BUMP\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n}","legacypbrPixelShader":"precision mediump float;\n\n#define RECIPROCAL_PI2 0.15915494\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vAlbedoColor;\nuniform vec3 vReflectionColor;\n\nuniform vec4 vLightingIntensity;\nuniform vec4 vCameraInfos;\n#ifdef OVERLOADEDVALUES\nuniform vec4 vOverloadedIntensity;\nuniform vec3 vOverloadedAmbient;\nuniform vec3 vOverloadedAlbedo;\nuniform vec3 vOverloadedReflectivity;\nuniform vec3 vOverloadedEmissive;\nuniform vec3 vOverloadedReflection;\nuniform vec3 vOverloadedMicroSurface;\n#endif\n#ifdef OVERLOADEDSHADOWVALUES\nuniform vec4 vOverloadedShadowIntensity;\n#endif\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<lightFragmentDeclaration>[0..maxSimultaneousLights]\n\n#ifdef ALBEDO\nvarying vec2 vAlbedoUV;\nuniform sampler2D albedoSampler;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform sampler2D ambientSampler;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform vec2 vLightmapInfos;\nuniform sampler2D lightmapSampler;\n#endif\n#if defined(REFLECTIVITY)\nvarying vec2 vReflectivityUV;\nuniform vec2 vReflectivityInfos;\nuniform sampler2D reflectivitySampler;\n#endif\n#include<clipPlaneFragmentDeclaration>\n#ifdef CAMERACOLORGRADING\nuniform sampler2D cameraColorGrading2DSampler;\nuniform vec4 vCameraColorGradingInfos;\nuniform vec4 vCameraColorGradingScaleOffset;\n#endif\n\n#include<pbrFunctions>\n#include<harmonicsFunctions>\n#include<pbrLightFunctions>\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 surfaceAlbedo=vec4(1.,1.,1.,1.);\nvec3 surfaceAlbedoContribution=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nsurfaceAlbedo=texture2D(albedoSampler,vAlbedoUV);\nsurfaceAlbedo=vec4(toLinearSpace(surfaceAlbedo.rgb),surfaceAlbedo.a);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#ifdef ALPHAFROMALBEDO\nalpha*=surfaceAlbedo.a;\n#endif\nsurfaceAlbedo.rgb*=vAlbedoInfos.y;\n#else\n\nsurfaceAlbedo.rgb=surfaceAlbedoContribution;\nsurfaceAlbedoContribution=vec3(1.,1.,1.);\n#endif\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n#ifdef OVERLOADEDVALUES\nsurfaceAlbedo.rgb=mix(surfaceAlbedo.rgb,vOverloadedAlbedo,vOverloadedIntensity.y);\n#endif\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\n\nvec3 ambientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nambientColor=texture2D(ambientSampler,vAmbientUV).rgb*vAmbientInfos.y;\n#ifdef OVERLOADEDVALUES\nambientColor.rgb=mix(ambientColor.rgb,vOverloadedAmbient,vOverloadedIntensity.x);\n#endif\n#endif\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef OVERLOADEDVALUES\nsurfaceReflectivityColor.rgb=mix(surfaceReflectivityColor.rgb,vOverloadedReflectivity,vOverloadedIntensity.z);\n#endif\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV);\nsurfaceReflectivityColor=surfaceReflectivityColorMap.rgb;\nsurfaceReflectivityColor=toLinearSpace(surfaceReflectivityColor);\n#ifdef OVERLOADEDVALUES\nsurfaceReflectivityColor=mix(surfaceReflectivityColor,vOverloadedReflectivity,vOverloadedIntensity.z);\n#endif\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface=surfaceReflectivityColorMap.a;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#endif\n#endif\n#ifdef OVERLOADEDVALUES\nmicroSurface=mix(microSurface,vOverloadedMicroSurface.x,vOverloadedMicroSurface.y);\n#endif\n\nfloat NdotV=max(0.00000000001,dot(normalW,viewDirectionW));\n\nmicroSurface=clamp(microSurface,0.,1.)*0.98;\n\nfloat roughness=clamp(1.-microSurface,0.000001,1.0);\n\nvec3 lightDiffuseContribution=vec3(0.,0.,0.);\n#ifdef OVERLOADEDSHADOWVALUES\nvec3 shadowedOnlyLightDiffuseContribution=vec3(1.,1.,1.);\n#endif\n#ifdef SPECULARTERM\nvec3 lightSpecularContribution= vec3(0.,0.,0.);\n#endif\nfloat notShadowLevel=1.; \nfloat NdotL=-1.;\nlightingInfo info;\n#include<pbrLightFunctionsCall>[0..maxSimultaneousLights]\n#ifdef SPECULARTERM\nlightSpecularContribution*=vLightingIntensity.w;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n\nvec3 environmentRadiance=vReflectionColor.rgb;\nvec3 environmentIrradiance=vReflectionColor.rgb;\n#ifdef OVERLOADEDVALUES\nenvironmentIrradiance=mix(environmentIrradiance,vOverloadedReflection,vOverloadedMicroSurface.z);\nenvironmentRadiance=mix(environmentRadiance,vOverloadedReflection,vOverloadedMicroSurface.z);\n#endif\nenvironmentRadiance*=vLightingIntensity.z;\nenvironmentIrradiance*=vLightingIntensity.z;\n\nvec3 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0);\nvec3 specularEnvironmentReflectance=FresnelSchlickEnvironmentGGX(clamp(NdotV,0.,1.),specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\nenvironmentRadiance*=specularEnvironmentReflectance;\n\nvec3 surfaceEmissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV).rgb;\nsurfaceEmissiveColor=toLinearSpace(emissiveColorTex.rgb)*surfaceEmissiveColor*vEmissiveInfos.y;\n#endif\n#ifdef OVERLOADEDVALUES\nsurfaceEmissiveColor=mix(surfaceEmissiveColor,vOverloadedEmissive,vOverloadedIntensity.w);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=max(lightDiffuseContribution*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#ifdef OVERLOADEDSHADOWVALUES\nshadowedOnlyLightDiffuseContribution=max(shadowedOnlyLightDiffuseContribution*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#endif\n#else\n#ifdef LINKEMISSIVEWITHALBEDO\nvec3 finalDiffuse=max((lightDiffuseContribution+surfaceEmissiveColor)*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#ifdef OVERLOADEDSHADOWVALUES\nshadowedOnlyLightDiffuseContribution=max((shadowedOnlyLightDiffuseContribution+surfaceEmissiveColor)*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#endif\n#else\nvec3 finalDiffuse=max(lightDiffuseContribution*surfaceAlbedoContribution+surfaceEmissiveColor+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#ifdef OVERLOADEDSHADOWVALUES\nshadowedOnlyLightDiffuseContribution=max(shadowedOnlyLightDiffuseContribution*surfaceAlbedoContribution+surfaceEmissiveColor+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#endif\n#endif\n#endif\n#ifdef OVERLOADEDSHADOWVALUES\nfinalDiffuse=mix(finalDiffuse,shadowedOnlyLightDiffuseContribution,(1.0-vOverloadedShadowIntensity.y));\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=lightSpecularContribution*surfaceReflectivityColor;\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+getLuminance(finalSpecular),0.,1.);\n#endif\n#ifdef RADIANCEOVERALPHA\nalpha=clamp(alpha+getLuminance(environmentRadiance),0.,1.);\n#endif\n\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 finalColor=vec4(finalDiffuse*ambientColor*vLightingIntensity.x+surfaceAlbedo.rgb*environmentIrradiance+finalSpecular*vLightingIntensity.x+environmentRadiance+surfaceEmissiveColor*vLightingIntensity.y,alpha);\n#else\nvec4 finalColor=vec4(finalDiffuse*ambientColor*vLightingIntensity.x+surfaceAlbedo.rgb*environmentIrradiance+finalSpecular*vLightingIntensity.x+environmentRadiance,alpha);\n#endif\nfinalColor=max(finalColor,0.0);\n#ifdef CAMERATONEMAP\nfinalColor.rgb=toneMaps(finalColor.rgb);\n#endif\nfinalColor.rgb=toGammaSpace(finalColor.rgb);\n#ifdef CAMERACONTRAST\nfinalColor=contrasts(finalColor);\n#endif\nfinalColor.rgb=clamp(finalColor.rgb,0.,1.);\n#ifdef CAMERACOLORGRADING\nfinalColor=colorGrades(finalColor,cameraColorGrading2DSampler,vCameraColorGradingInfos,vCameraColorGradingScaleOffset);\n#endif\ngl_FragColor=finalColor;\n}","legacypbrVertexShader":"precision mediump float;\n\nattribute vec3 position;\nattribute vec3 normal;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\nuniform mat4 world;\nuniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef ALBEDO\nvarying vec2 vAlbedoUV;\nuniform mat4 albedoMatrix;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#if defined(REFLECTIVITY)\nvarying vec2 vReflectivityUV;\nuniform vec2 vReflectivityInfos;\nuniform mat4 reflectivityMatrix;\n#endif\n\nvarying vec3 vPositionW;\nvarying vec3 vNormalW;\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<clipPlaneVertexDeclaration>\nvoid main(void) {\nmat4 finalWorld=world;\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef ALBEDO\nif (vAlbedoInfos.x == 0.)\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef AMBIENT\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef OPACITY\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef EMISSIVE\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(REFLECTIVITY)\nif (vReflectivityInfos.x == 0.)\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<clipPlaneVertex>\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n}","lensFlarePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\ngl_FragColor=baseColor*color;\n}","lensFlareVertexShader":"\nattribute vec2 position;\n\nuniform mat4 viewportMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=position*madd+madd;\ngl_Position=viewportMatrix*vec4(position,0.0,1.0);\n}","lensHighlightsPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float gain;\nuniform float threshold;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\n\nvec4 highlightColor(vec4 color) {\nvec4 highlight=color;\nfloat luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));\nfloat lum_threshold;\nif (threshold>1.0) { lum_threshold=0.94+0.01*threshold; }\nelse { lum_threshold=0.5+0.44*threshold; }\nluminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);\nhighlight*=luminance*gain;\nhighlight.a=1.0;\nreturn highlight;\n}\nvoid main(void)\n{\nvec4 original=texture2D(textureSampler,vUV);\n\nif (gain == -1.0) {\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nreturn;\n}\nfloat w=2.0/screen_width;\nfloat h=2.0/screen_height;\nfloat weight=1.0;\n\nvec4 blurred=vec4(0.0,0.0,0.0,0.0);\n#ifdef PENTAGON\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h)));\n#else\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h)));\n#endif\nblurred/=39.0;\ngl_FragColor=blurred;\n\n}","linePixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","lineVertexShader":"\nattribute vec3 position;\nattribute vec4 normal;\n\nuniform mat4 worldViewProjection;\nuniform float width;\nuniform float aspectRatio;\nvoid main(void) {\nvec4 viewPosition=worldViewProjection*vec4(position,1.0);\nvec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);\nvec2 currentScreen=viewPosition.xy/viewPosition.w;\nvec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;\ncurrentScreen.x*=aspectRatio;\nnextScreen.x*=aspectRatio;\nvec2 dir=normalize(nextScreen-currentScreen);\nvec2 normalDir=vec2(-dir.y,dir.x);\nnormalDir*=width/2.0;\nnormalDir.x/=aspectRatio;\nvec4 offset=vec4(normalDir*normal.w,0.0,0.0);\ngl_Position=viewPosition+offset;\n}","lines2dPixelShader":"varying vec4 vColor;\nvoid main(void) {\ngl_FragColor=vColor;\n}","lines2dVertexShader":"\n#ifdef Instanced\n#define att attribute\n#else\n#define att uniform\n#endif\nattribute vec2 position;\natt vec2 zBias;\natt vec4 transformX;\natt vec4 transformY;\natt float opacity;\n#ifdef FillSolid\natt vec4 fillSolidColor;\n#endif\n#ifdef BorderSolid\natt vec4 borderSolidColor;\n#endif\n#ifdef FillGradient\natt vec2 boundingMin;\natt vec2 boundingMax;\natt vec4 fillGradientColor1;\natt vec4 fillGradientColor2;\natt vec4 fillGradientTY;\n#endif\n#ifdef BorderGradient\natt vec4 borderGradientColor1;\natt vec4 borderGradientColor2;\natt vec4 borderGradientTY;\n#endif\n#define TWOPI 6.28318530\n\nvarying vec2 vUV;\nvarying vec4 vColor;\nvoid main(void) {\n#ifdef FillSolid\nvColor=fillSolidColor;\n#endif\n#ifdef BorderSolid\nvColor=borderSolidColor;\n#endif\n#ifdef FillGradient\nfloat v=dot(vec4((position.xy-boundingMin)/(boundingMax-boundingMin),1,1),fillGradientTY);\nvColor=mix(fillGradientColor2,fillGradientColor1,v); \n#endif\n#ifdef BorderGradient\nfloat v=dot(vec4((position.xy-boundingMin)/(boundingMax-boundingMin),1,1),borderGradientTY);\nvColor=mix(borderGradientColor2,borderGradientColor1,v); \n#endif\nvColor.a*=opacity;\nvec4 pos;\npos.xy=position.xy;\npos.z=1.0;\npos.w=1.0;\ngl_Position=vec4(dot(pos,transformX),dot(pos,transformY),zBias.x,1);\n}","outlinePixelShader":"uniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void) {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragColor=color;\n}","outlineVertexShader":"\nattribute vec3 position;\nattribute vec3 normal;\n#include<bonesDeclaration>\n\nuniform float offset;\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\nvec3 offsetPosition=position+normal*offset;\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(offsetPosition,1.0);\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}\n","particlesPixelShader":"\nvarying vec2 vUV;\nvarying vec4 vColor;\nuniform vec4 textureMask;\nuniform sampler2D diffuseSampler;\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\nvoid main(void) {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif\nvec4 baseColor=texture2D(diffuseSampler,vUV);\ngl_FragColor=(baseColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;\n}","particlesVertexShader":"\nattribute vec3 position;\nattribute vec4 color;\nattribute vec4 options;\n\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nvarying float fClipDistance;\n#endif\nvoid main(void) { \nvec3 viewPos=(view*vec4(position,1.0)).xyz; \nvec3 cornerPos;\nfloat size=options.y;\nfloat angle=options.x;\nvec2 offset=options.zw;\ncornerPos=vec3(offset.x-0.5,offset.y-0.5,0.)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \nvColor=color;\nvUV=offset;\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*vec4(viewPos,1.0);\nfClipDistance=dot(worldPos,vClipPlane);\n#endif\n}","passPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\n}","pbrPixelShader":"#ifdef BUMP\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LODBASEDMICROSFURACE\n#extension GL_EXT_shader_texture_lod : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nprecision highp float;\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\n\nuniform vec4 vLightingIntensity;\nuniform vec4 vCameraInfos;\n#ifdef OVERLOADEDVALUES\nuniform vec4 vOverloadedIntensity;\nuniform vec3 vOverloadedAmbient;\nuniform vec3 vOverloadedAlbedo;\nuniform vec3 vOverloadedReflectivity;\nuniform vec3 vOverloadedEmissive;\nuniform vec3 vOverloadedReflection;\nuniform vec3 vOverloadedMicroSurface;\n#endif\n#ifdef OVERLOADEDSHADOWVALUES\nuniform vec4 vOverloadedShadowIntensity;\n#endif\n#if defined(REFLECTION) || defined(REFRACTION)\nuniform vec2 vMicrosurfaceTextureLods;\n#endif\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<lightFragmentDeclaration>[0..maxSimultaneousLights]\n\n#ifdef ALBEDO\nvarying vec2 vAlbedoUV;\nuniform sampler2D albedoSampler;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform sampler2D ambientSampler;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform vec2 vLightmapInfos;\nuniform sampler2D lightmapSampler;\n#endif\n#if defined(REFLECTIVITY)\nvarying vec2 vReflectivityUV;\nuniform vec2 vReflectivityInfos;\nuniform sampler2D reflectivitySampler;\n#endif\n\n#include<fresnelFunction>\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\nuniform mat4 refractionMatrix;\n#endif\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvarying vec3 vDirectionW;\n#endif\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#ifdef CAMERACOLORGRADING\n#include<colorGradingDefinition>\n#endif\n#ifdef CAMERACOLORCURVES\n#include<colorCurvesDefinition>\n#endif\n\n#include<pbrShadowFunctions>\n#include<pbrFunctions>\n#ifdef CAMERACOLORGRADING\n#include<colorGrading>\n#endif\n#ifdef CAMERACOLORCURVES\n#include<colorCurves>\n#endif\n#include<harmonicsFunctions>\n#include<pbrLightFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 surfaceAlbedo=vec4(1.,1.,1.,1.);\nvec3 surfaceAlbedoContribution=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nsurfaceAlbedo=texture2D(albedoSampler,vAlbedoUV);\nsurfaceAlbedo=vec4(toLinearSpace(surfaceAlbedo.rgb),surfaceAlbedo.a);\n#ifndef LINKREFRACTIONTOTRANSPARENCY\n#ifdef ALPHATEST\nif (surfaceAlbedo.a<0.4)\ndiscard;\n#endif\n#endif\n#ifdef ALPHAFROMALBEDO\nalpha*=surfaceAlbedo.a;\n#endif\nsurfaceAlbedo.rgb*=vAlbedoInfos.y;\n#else\n\nsurfaceAlbedo.rgb=surfaceAlbedoContribution;\nsurfaceAlbedoContribution=vec3(1.,1.,1.);\n#endif\n#ifdef VERTEXCOLOR\nsurfaceAlbedo.rgb*=vColor.rgb;\n#endif\n#ifdef OVERLOADEDVALUES\nsurfaceAlbedo.rgb=mix(surfaceAlbedo.rgb,vOverloadedAlbedo,vOverloadedIntensity.y);\n#endif\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\n#include<bumpFragment>\n\nvec3 ambientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nambientColor=texture2D(ambientSampler,vAmbientUV).rgb*vAmbientInfos.y;\n#ifdef OVERLOADEDVALUES\nambientColor.rgb=mix(ambientColor.rgb,vOverloadedAmbient,vOverloadedIntensity.x);\n#endif\n#endif\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef OVERLOADEDVALUES\nsurfaceReflectivityColor.rgb=mix(surfaceReflectivityColor.rgb,vOverloadedReflectivity,vOverloadedIntensity.z);\n#endif\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV);\nsurfaceReflectivityColor=surfaceReflectivityColorMap.rgb;\nsurfaceReflectivityColor=toLinearSpace(surfaceReflectivityColor);\n#ifdef OVERLOADEDVALUES\nsurfaceReflectivityColor=mix(surfaceReflectivityColor,vOverloadedReflectivity,vOverloadedIntensity.z);\n#endif\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface=surfaceReflectivityColorMap.a;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#endif\n#endif\n#ifdef OVERLOADEDVALUES\nmicroSurface=mix(microSurface,vOverloadedMicroSurface.x,vOverloadedMicroSurface.y);\n#endif\n\nfloat NdotV=max(0.00000000001,dot(normalW,viewDirectionW));\n\nmicroSurface=clamp(microSurface,0.,1.)*0.98;\n\nfloat roughness=clamp(1.-microSurface,0.000001,1.0);\n\nvec3 lightDiffuseContribution=vec3(0.,0.,0.);\n#ifdef OVERLOADEDSHADOWVALUES\nvec3 shadowedOnlyLightDiffuseContribution=vec3(1.,1.,1.);\n#endif\n#ifdef SPECULARTERM\nvec3 lightSpecularContribution=vec3(0.,0.,0.);\n#endif\nfloat notShadowLevel=1.; \nfloat NdotL=-1.;\nlightingInfo info;\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\n\n\nfloat reflectance90=clamp(reflectance*25.0,0.0,1.0);\nvec3 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0)*reflectance90;\n#include<pbrLightFunctionsCall>[0..maxSimultaneousLights]\n#ifdef SPECULARTERM\nlightSpecularContribution*=vLightingIntensity.w;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 surfaceRefractionColor=vec3(0.,0.,0.);\n\n#ifdef LODBASEDMICROSFURACE\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\n#endif\n#ifdef REFRACTION\nvec3 refractionVector=refract(-viewDirectionW,normalW,vRefractionInfos.y);\n#ifdef LODBASEDMICROSFURACE\n#ifdef USEPMREMREFRACTION\nfloat lodRefraction=getMipMapIndexFromAverageSlopeWithPMREM(vMicrosurfaceTextureLods.y,alphaG);\n#else\nfloat lodRefraction=getMipMapIndexFromAverageSlope(vMicrosurfaceTextureLods.y,alphaG);\n#endif\n#else\nfloat biasRefraction=(vMicrosurfaceTextureLods.y+2.)*(1.0-microSurface);\n#endif\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0)\n{\n#ifdef LODBASEDMICROSFURACE\n#ifdef USEPMREMREFRACTION\n\nif ((vMicrosurfaceTextureLods.y-lodRefraction)>4.0)\n{\n\nfloat scaleRefraction=1.-exp2(lodRefraction)/exp2(vMicrosurfaceTextureLods.y); \nfloat maxRefraction=max(max(abs(refractionVector.x),abs(refractionVector.y)),abs(refractionVector.z));\nif (abs(refractionVector.x) != maxRefraction) refractionVector.x*=scaleRefraction;\nif (abs(refractionVector.y) != maxRefraction) refractionVector.y*=scaleRefraction;\nif (abs(refractionVector.z) != maxRefraction) refractionVector.z*=scaleRefraction;\n}\n#endif\nsurfaceRefractionColor=textureCubeLodEXT(refractionCubeSampler,refractionVector,lodRefraction).rgb*vRefractionInfos.x;\n#else\nsurfaceRefractionColor=textureCube(refractionCubeSampler,refractionVector,biasRefraction).rgb*vRefractionInfos.x;\n#endif\n}\n#ifndef REFRACTIONMAPINLINEARSPACE\nsurfaceRefractionColor=toLinearSpace(surfaceRefractionColor.rgb);\n#endif\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\n#ifdef LODBASEDMICROSFURACE\nsurfaceRefractionColor=texture2DLodEXT(refraction2DSampler,refractionCoords,lodRefraction).rgb*vRefractionInfos.x;\n#else\nsurfaceRefractionColor=texture2D(refraction2DSampler,refractionCoords,biasRefraction).rgb*vRefractionInfos.x;\n#endif \nsurfaceRefractionColor=toLinearSpace(surfaceRefractionColor.rgb);\n#endif\n#endif\n\nvec3 environmentRadiance=vReflectionColor.rgb;\nvec3 environmentIrradiance=vReflectionColor.rgb;\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef LODBASEDMICROSFURACE\n#ifdef USEPMREMREFLECTION\nfloat lodReflection=getMipMapIndexFromAverageSlopeWithPMREM(vMicrosurfaceTextureLods.x,alphaG);\n#else\nfloat lodReflection=getMipMapIndexFromAverageSlope(vMicrosurfaceTextureLods.x,alphaG);\n#endif\n#else\nfloat biasReflection=(vMicrosurfaceTextureLods.x+2.)*(1.0-microSurface);\n#endif\n#ifdef REFLECTIONMAP_3D\n#ifdef LODBASEDMICROSFURACE\n#ifdef USEPMREMREFLECTION\n\nif ((vMicrosurfaceTextureLods.y-lodReflection)>4.0)\n{\n\nfloat scaleReflection=1.-exp2(lodReflection)/exp2(vMicrosurfaceTextureLods.x); \nfloat maxReflection=max(max(abs(vReflectionUVW.x),abs(vReflectionUVW.y)),abs(vReflectionUVW.z));\nif (abs(vReflectionUVW.x) != maxReflection) vReflectionUVW.x*=scaleReflection;\nif (abs(vReflectionUVW.y) != maxReflection) vReflectionUVW.y*=scaleReflection;\nif (abs(vReflectionUVW.z) != maxReflection) vReflectionUVW.z*=scaleReflection;\n}\n#endif\nenvironmentRadiance=textureCubeLodEXT(reflectionCubeSampler,vReflectionUVW,lodReflection).rgb*vReflectionInfos.x;\n#else\nenvironmentRadiance=textureCube(reflectionCubeSampler,vReflectionUVW,biasReflection).rgb*vReflectionInfos.x;\n#endif\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#ifndef REFLECTIONMAP_SKYBOX\nvec3 normalEnvironmentSpace=(reflectionMatrix*vec4(normalW,1)).xyz;\nenvironmentIrradiance=EnvironmentIrradiance(normalEnvironmentSpace);\n#endif\n#else\nenvironmentRadiance=toLinearSpace(environmentRadiance.rgb);\nenvironmentIrradiance=textureCube(reflectionCubeSampler,normalW,20.).rgb*vReflectionInfos.x;\nenvironmentIrradiance=toLinearSpace(environmentIrradiance.rgb);\nenvironmentIrradiance*=0.2; \n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\n#ifdef LODBASEDMICROSFURACE\nenvironmentRadiance=texture2DLodEXT(reflection2DSampler,coords,lodReflection).rgb*vReflectionInfos.x;\n#else\nenvironmentRadiance=texture2D(reflection2DSampler,coords,biasReflection).rgb*vReflectionInfos.x;\n#endif\nenvironmentRadiance=toLinearSpace(environmentRadiance.rgb);\nenvironmentIrradiance=texture2D(reflection2DSampler,coords,20.).rgb*vReflectionInfos.x;\nenvironmentIrradiance=toLinearSpace(environmentIrradiance.rgb);\n#endif\n#endif\n#ifdef OVERLOADEDVALUES\nenvironmentIrradiance=mix(environmentIrradiance,vOverloadedReflection,vOverloadedMicroSurface.z);\nenvironmentRadiance=mix(environmentRadiance,vOverloadedReflection,vOverloadedMicroSurface.z);\n#endif\nenvironmentRadiance*=vLightingIntensity.z;\nenvironmentIrradiance*=vLightingIntensity.z;\n\nvec3 specularEnvironmentReflectance=FresnelSchlickEnvironmentGGX(clamp(NdotV,0.,1.),specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n\nvec3 refractance=vec3(0.0,0.0,0.0);\n#ifdef REFRACTION\nvec3 transmission=vec3(1.0,1.0,1.0);\n#ifdef LINKREFRACTIONTOTRANSPARENCY\n\ntransmission*=(1.0-alpha);\n\n\nvec3 mixedAlbedo=surfaceAlbedoContribution.rgb*surfaceAlbedo.rgb;\nfloat maxChannel=max(max(mixedAlbedo.r,mixedAlbedo.g),mixedAlbedo.b);\nvec3 tint=clamp(maxChannel*mixedAlbedo,0.0,1.0);\n\nsurfaceAlbedoContribution*=alpha;\n\nenvironmentIrradiance*=alpha;\n\nsurfaceRefractionColor*=tint;\n\nalpha=1.0;\n#endif\n\nvec3 bounceSpecularEnvironmentReflectance=(2.0*specularEnvironmentReflectance)/(1.0+specularEnvironmentReflectance);\nspecularEnvironmentReflectance=mix(bounceSpecularEnvironmentReflectance,specularEnvironmentReflectance,alpha);\n\ntransmission*=1.0-specularEnvironmentReflectance;\n\nrefractance=surfaceRefractionColor*transmission;\n#endif\n\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\nrefractance*=vLightingIntensity.z;\nenvironmentRadiance*=specularEnvironmentReflectance;\n\nvec3 surfaceEmissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV).rgb;\nsurfaceEmissiveColor=toLinearSpace(emissiveColorTex.rgb)*surfaceEmissiveColor*vEmissiveInfos.y;\n#endif\n#ifdef OVERLOADEDVALUES\nsurfaceEmissiveColor=mix(surfaceEmissiveColor,vOverloadedEmissive,vOverloadedIntensity.w);\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nsurfaceEmissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=max(lightDiffuseContribution*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#ifdef OVERLOADEDSHADOWVALUES\nshadowedOnlyLightDiffuseContribution=max(shadowedOnlyLightDiffuseContribution*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#endif\n#else\n#ifdef LINKEMISSIVEWITHALBEDO\nvec3 finalDiffuse=max((lightDiffuseContribution+surfaceEmissiveColor)*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#ifdef OVERLOADEDSHADOWVALUES\nshadowedOnlyLightDiffuseContribution=max((shadowedOnlyLightDiffuseContribution+surfaceEmissiveColor)*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#endif\n#else\nvec3 finalDiffuse=max(lightDiffuseContribution*surfaceAlbedoContribution+surfaceEmissiveColor+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#ifdef OVERLOADEDSHADOWVALUES\nshadowedOnlyLightDiffuseContribution=max(shadowedOnlyLightDiffuseContribution*surfaceAlbedoContribution+surfaceEmissiveColor+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#endif\n#endif\n#endif\n#ifdef OVERLOADEDSHADOWVALUES\nfinalDiffuse=mix(finalDiffuse,shadowedOnlyLightDiffuseContribution,(1.0-vOverloadedShadowIntensity.y));\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=lightSpecularContribution*surfaceReflectivityColor;\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+getLuminance(finalSpecular),0.,1.);\n#endif\n#ifdef RADIANCEOVERALPHA\nalpha=clamp(alpha+getLuminance(environmentRadiance),0.,1.);\n#endif\n\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 finalColor=vec4(finalDiffuse*ambientColor*vLightingIntensity.x+surfaceAlbedo.rgb*environmentIrradiance+finalSpecular*vLightingIntensity.x+environmentRadiance+surfaceEmissiveColor*vLightingIntensity.y+refractance,alpha);\n#else\nvec4 finalColor=vec4(finalDiffuse*ambientColor*vLightingIntensity.x+surfaceAlbedo.rgb*environmentIrradiance+finalSpecular*vLightingIntensity.x+environmentRadiance+refractance,alpha);\n#endif\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV).rgb*vLightmapInfos.y;\n#ifdef USELIGHTMAPASSHADOWMAP\nfinalColor.rgb*=lightmapColor;\n#else\nfinalColor.rgb+=lightmapColor;\n#endif\n#endif\nfinalColor=max(finalColor,0.0);\n#ifdef CAMERATONEMAP\nfinalColor.rgb=toneMaps(finalColor.rgb);\n#endif\nfinalColor.rgb=toGammaSpace(finalColor.rgb);\n#include<logDepthFragment>\n#include<fogFragment>(color,finalColor)\n#ifdef CAMERACONTRAST\nfinalColor=contrasts(finalColor);\n#endif\nfinalColor.rgb=clamp(finalColor.rgb,0.,1.);\n#ifdef CAMERACOLORGRADING\nfinalColor=colorGrades(finalColor);\n#endif\n#ifdef CAMERACOLORCURVES\nfinalColor.rgb=applyColorCurves(finalColor.rgb);\n#endif\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\ngl_FragColor=finalColor;\n}","pbrVertexShader":"precision highp float;\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef ALBEDO\nvarying vec2 vAlbedoUV;\nuniform mat4 albedoMatrix;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(REFLECTIVITY)\nvarying vec2 vReflectivityUV;\nuniform vec2 vReflectivityInfos;\nuniform mat4 reflectivityMatrix;\n#endif\n#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<shadowsVertexDeclaration>[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=position;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef ALBEDO\nif (vAlbedoInfos.x == 0.)\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef AMBIENT\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef OPACITY\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef EMISSIVE\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef LIGHTMAP\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(REFLECTIVITY)\nif (vReflectivityInfos.x == 0.)\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef BUMP\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n\n#include<logDepthVertex>\n}","postprocessVertexShader":"\nattribute vec2 position;\nuniform vec2 scale;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd)*scale;\ngl_Position=vec4(position,0.0,1.0);\n}","proceduralVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvPosition=position;\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","rect2dPixelShader":"varying vec4 vColor;\nvoid main(void) {\ngl_FragColor=vColor;\n}","rect2dVertexShader":"\n#ifdef Instanced\n#define att attribute\n#else\n#define att uniform\n#endif\nattribute float index;\natt vec2 zBias;\natt vec4 transformX;\natt vec4 transformY;\natt float opacity;\n#ifdef Border\natt float borderThickness;\n#endif\n#ifdef FillSolid\natt vec4 fillSolidColor;\n#endif\n#ifdef BorderSolid\natt vec4 borderSolidColor;\n#endif\n#ifdef FillGradient\natt vec4 fillGradientColor1;\natt vec4 fillGradientColor2;\natt vec4 fillGradientTY;\n#endif\n#ifdef BorderGradient\natt vec4 borderGradientColor1;\natt vec4 borderGradientColor2;\natt vec4 borderGradientTY;\n#endif\n\natt vec3 properties;\n\n#define rsub0 17.0\n#define rsub1 33.0\n#define rsub2 49.0\n#define rsub3 65.0\n#define rsub 64.0\n#define TWOPI 6.28318530\n\nvarying vec2 vUV;\nvarying vec4 vColor;\nvoid main(void) {\nvec2 pos2;\n\nif (properties.z == 0.0) {\n#ifdef Border\nfloat w=properties.x;\nfloat h=properties.y;\nvec2 borderOffset=vec2(1.0,1.0);\nfloat segi=index;\nif (index<4.0) {\nborderOffset=vec2(1.0-(borderThickness*2.0/w),1.0-(borderThickness*2.0/h));\n}\nelse {\nsegi-=4.0;\n}\nif (segi == 0.0) {\npos2=vec2(1.0,1.0);\n} \nelse if (segi == 1.0) {\npos2=vec2(1.0,0.0);\n}\nelse if (segi == 2.0) {\npos2=vec2(0.0,0.0);\n} \nelse {\npos2=vec2(0.0,1.0);\n}\npos2.x=((pos2.x-0.5)*borderOffset.x)+0.5;\npos2.y=((pos2.y-0.5)*borderOffset.y)+0.5;\n#else\nif (index == 0.0) {\npos2=vec2(0.5,0.5);\n}\nelse if (index == 1.0) {\npos2=vec2(1.0,1.0);\n}\nelse if (index == 2.0) {\npos2=vec2(1.0,0.0);\n}\nelse if (index == 3.0) {\npos2=vec2(0.0,0.0);\n}\nelse {\npos2=vec2(0.0,1.0);\n}\n#endif\n}\nelse\n{\n#ifdef Border\nfloat w=properties.x;\nfloat h=properties.y;\nfloat r=properties.z;\nfloat nru=r/w;\nfloat nrv=r/h;\nvec2 borderOffset=vec2(1.0,1.0);\nfloat segi=index;\nif (index<rsub) {\nborderOffset=vec2(1.0-(borderThickness*2.0/w),1.0-(borderThickness*2.0/h));\n}\nelse {\nsegi-=rsub;\n}\n\nif (segi<rsub0) {\npos2=vec2(1.0-nru,nrv);\n}\n\nelse if (segi<rsub1) {\npos2=vec2(nru,nrv);\n}\n\nelse if (segi<rsub2) {\npos2=vec2(nru,1.0-nrv);\n}\n\nelse {\npos2=vec2(1.0-nru,1.0-nrv);\n}\nfloat angle=TWOPI-((index-1.0)*TWOPI/(rsub-0.5));\npos2.x+=cos(angle)*nru;\npos2.y+=sin(angle)*nrv;\npos2.x=((pos2.x-0.5)*borderOffset.x)+0.5;\npos2.y=((pos2.y-0.5)*borderOffset.y)+0.5;\n#else\nif (index == 0.0) {\npos2=vec2(0.5,0.5);\n}\nelse {\nfloat w=properties.x;\nfloat h=properties.y;\nfloat r=properties.z;\nfloat nru=r/w;\nfloat nrv=r/h;\n\nif (index<rsub0) {\npos2=vec2(1.0-nru,nrv);\n}\n\nelse if (index<rsub1) {\npos2=vec2(nru,nrv);\n}\n\nelse if (index<rsub2) {\npos2=vec2(nru,1.0-nrv);\n}\n\nelse {\npos2=vec2(1.0-nru,1.0-nrv);\n}\nfloat angle=TWOPI-((index-1.0)*TWOPI/(rsub-0.5));\npos2.x+=cos(angle)*nru;\npos2.y+=sin(angle)*nrv;\n}\n#endif\n}\n#ifdef FillSolid\nvColor=fillSolidColor;\n#endif\n#ifdef BorderSolid\nvColor=borderSolidColor;\n#endif\n#ifdef FillGradient\nfloat v=dot(vec4(pos2.xy,1,1),fillGradientTY);\nvColor=mix(fillGradientColor2,fillGradientColor1,v); \n#endif\n#ifdef BorderGradient\nfloat v=dot(vec4(pos2.xy,1,1),borderGradientTY);\nvColor=mix(borderGradientColor2,borderGradientColor1,v); \n#endif\nvColor.a*=opacity;\nvec4 pos;\npos.xy=pos2.xy*properties.xy;\npos.z=1.0;\npos.w=1.0;\ngl_Position=vec4(dot(pos,transformX),dot(pos,transformY),zBias.x,1);\n}","refractionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\nvoid main() {\nfloat ref=1.0-texture2D(refractionSampler,vUV).r;\nvec2 uv=vUV-vec2(0.5);\nvec2 offset=uv*depth*ref;\nvec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;\ngl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);\n}","shadowMapPixelShader":"#ifndef FULLFLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n\nvec2 packHalf(float depth) \n{ \nconst vec2 bitOffset=vec2(1.0/255.,0.);\nvec2 color=vec2(depth,fract(depth*255.));\nreturn color-(color.yy*bitOffset);\n}\n#endif\nvarying vec4 vPosition;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef CUBEMAP\nuniform vec3 lightPosition;\nuniform vec2 depthValues;\n#endif\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#ifdef CUBEMAP\nvec3 directionToLight=vPosition.xyz-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth-depthValues.x)/(depthValues.y-depthValues.x);\ndepth=clamp(depth,0.,1.0);\n#else\nfloat depth=vPosition.z/vPosition.w;\ndepth=depth*0.5+0.5;\n#endif\n#ifdef VSM\nfloat moment1=depth;\nfloat moment2=moment1*moment1;\n#ifndef FULLFLOAT\ngl_FragColor=vec4(packHalf(moment1),packHalf(moment2));\n#else\ngl_FragColor=vec4(moment1,moment2,1.0,1.0);\n#endif\n#else\n#ifndef FULLFLOAT\ngl_FragColor=pack(depth);\n#else\ngl_FragColor=vec4(depth,1.0,1.0,1.0);\n#endif\n#endif\n}","shadowMapVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nvarying vec4 vPosition;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(position,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(position,1.0);\ngl_Position=vPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","sprite2dPixelShader":"varying vec2 vUV;\nvarying float vOpacity;\nuniform bool alphaTest;\nuniform sampler2D diffuseSampler;\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\nif (alphaTest)\n{\nif (color.a<0.95) {\ndiscard;\n}\n}\ncolor.a*=vOpacity;\ngl_FragColor=color;\n}","sprite2dVertexShader":"\n#ifdef Instanced\n#define att attribute\n#else\n#define att uniform\n#endif\n\nattribute float index;\natt vec2 topLeftUV;\natt vec2 sizeUV;\natt vec2 scaleFactor;\natt vec2 textureSize;\n\natt vec3 properties;\natt vec2 zBias;\natt vec4 transformX;\natt vec4 transformY;\natt float opacity;\n\n\nvarying vec2 vUV;\nvarying float vOpacity;\nvoid main(void) {\nvec2 pos2;\n\nvec2 off=vec2(0.0,0.0);\nvec2 sfSizeUV=sizeUV*scaleFactor;\nfloat frame=properties.x;\nfloat invertY=properties.y;\nfloat alignToPixel=properties.z;\n\nif (index == 0.0) {\npos2=vec2(0.0,0.0);\nvUV=vec2(topLeftUV.x+(frame*sfSizeUV.x)+off.x,topLeftUV.y-off.y);\n}\n\nelse if (index == 1.0) {\npos2=vec2(0.0,1.0);\nvUV=vec2(topLeftUV.x+(frame*sfSizeUV.x)+off.x,(topLeftUV.y+sfSizeUV.y));\n}\n\nelse if (index == 2.0) {\npos2=vec2( 1.0,1.0);\nvUV=vec2(topLeftUV.x+sfSizeUV.x+(frame*sfSizeUV.x),(topLeftUV.y+sfSizeUV.y));\n}\n\nelse if (index == 3.0) {\npos2=vec2( 1.0,0.0);\nvUV=vec2(topLeftUV.x+sfSizeUV.x+(frame*sfSizeUV.x),topLeftUV.y-off.y);\n}\nif (invertY == 1.0) {\nvUV.y=1.0-vUV.y;\n}\nvec4 pos;\nif (alignToPixel == 1.0)\n{\npos.xy=floor(pos2.xy*sizeUV*textureSize);\n} else {\npos.xy=pos2.xy*sizeUV*textureSize;\n}\nvOpacity=opacity;\npos.z=1.0;\npos.w=1.0;\ngl_Position=vec4(dot(pos,transformX),dot(pos,transformY),zBias.x,1);\n} ","spritesPixelShader":"uniform bool alphaTest;\nvarying vec4 vColor;\n\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\nif (alphaTest) \n{\nif (color.a<0.95)\ndiscard;\n}\ncolor*=vColor;\n#include<fogFragment>\ngl_FragColor=color;\n}","spritesVertexShader":"\nattribute vec4 position;\nattribute vec4 options;\nattribute vec4 cellInfo;\nattribute vec4 color;\n\nuniform vec2 textureInfos;\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#include<fogVertexDeclaration>\nvoid main(void) { \nvec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; \nvec2 cornerPos;\nfloat angle=position.w;\nvec2 size=vec2(options.x,options.y);\nvec2 offset=options.zw;\nvec2 uvScale=textureInfos.xy;\ncornerPos=vec2(offset.x-0.5,offset.y-0.5)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \n\nvColor=color;\n\nvec2 uvOffset=vec2(abs(offset.x-cellInfo.x),1.0-abs(offset.y-cellInfo.y));\nvUV=(uvOffset+cellInfo.zw)*uvScale;\n\n#ifdef FOG\nfFogDistance=viewPos.z;\n#endif\n}","ssaoPixelShader":"\nuniform sampler2D textureSampler;\nvarying vec2 vUV;\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float radius;\nuniform float area;\nuniform float fallOff;\nuniform float base;\nvec3 normalFromDepth(float depth,vec2 coords)\n{\nvec2 offset1=vec2(0.0,radius);\nvec2 offset2=vec2(radius,0.0);\nfloat depth1=texture2D(textureSampler,coords+offset1).r;\nfloat depth2=texture2D(textureSampler,coords+offset2).r;\nvec3 p1=vec3(offset1,depth1-depth);\nvec3 p2=vec3(offset2,depth2-depth);\nvec3 normal=cross(p1,p2);\nnormal.z=-normal.z;\nreturn normalize(normal);\n}\nvoid main()\n{\nvec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);\nfloat depth=texture2D(textureSampler,vUV).r;\nvec3 position=vec3(vUV,depth);\nvec3 normal=normalFromDepth(depth,vUV);\nfloat radiusDepth=radius/depth;\nfloat occlusion=0.0;\nvec3 ray;\nvec3 hemiRay;\nfloat occlusionDepth;\nfloat difference;\nfor (int i=0; i<SAMPLES; i++)\n{\nray=radiusDepth*reflect(sampleSphere[i],random);\nhemiRay=position+sign(dot(ray,normal))*ray;\nocclusionDepth=texture2D(textureSampler,clamp(hemiRay.xy,vec2(0.001,0.001),vec2(0.999,0.999))).r;\ndifference=depth-occlusionDepth;\nocclusion+=step(fallOff,difference)*(1.0-smoothstep(fallOff,area,difference));\n}\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor.r=result;\ngl_FragColor.g=result;\ngl_FragColor.b=result;\ngl_FragColor.a=1.0;\n}\n#endif\n#ifdef BILATERAL_BLUR\nuniform sampler2D depthSampler;\nuniform float outSize;\nuniform float samplerOffsets[SAMPLES];\nvoid main()\n{\nfloat texelsize=1.0/outSize;\nfloat compareDepth=texture2D(depthSampler,vUV).r;\nfloat result=0.0;\nfloat weightSum=0.0;\nfor (int i=0; i<SAMPLES; ++i)\n{\n#ifdef BILATERAL_BLUR_H\nvec2 sampleOffset=vec2(texelsize*samplerOffsets[i],0.0);\n#else\nvec2 sampleOffset=vec2(0.0,texelsize*samplerOffsets[i]);\n#endif\nvec2 samplePos=vUV+sampleOffset;\nfloat sampleDepth=texture2D(depthSampler,samplePos).r;\nfloat weight=(1.0/(0.0001+abs(compareDepth-sampleDepth)));\nresult+=texture2D(textureSampler,samplePos).r*weight;\nweightSum+=weight;\n}\nresult/=weightSum;\ngl_FragColor.rgb=vec3(result);\ngl_FragColor.a=1.0;\n}\n#endif\n","ssaoCombinePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D originalColor;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,vUV);\nvec4 sceneColor=texture2D(originalColor,vUV);\ngl_FragColor=sceneColor*ssaoColor;\n}\n","stereoscopicInterlacePixelShader":"const vec3 TWO=vec3(2.0,2.0,2.0);\nvarying vec2 vUV;\nuniform sampler2D camASampler;\nuniform sampler2D textureSampler;\nuniform vec2 stepSize;\nvoid main(void)\n{\nbool useCamB;\nvec2 texCoord1;\nvec2 texCoord2;\nvec3 frag1;\nvec3 frag2;\n#ifdef IS_STEREOSCOPIC_HORIZ\nuseCamB=vUV.x>0.5;\ntexCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);\ntexCoord2=vec2(texCoord1.x+stepSize.x,vUV.y);\n#else\nuseCamB=vUV.y>0.5;\ntexCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);\ntexCoord2=vec2(vUV.x,texCoord1.y+stepSize.y);\n#endif\n\nif (useCamB){\nfrag1=texture2D(textureSampler,texCoord1).rgb;\nfrag2=texture2D(textureSampler,texCoord2).rgb;\n}else{\nfrag1=texture2D(camASampler ,texCoord1).rgb;\nfrag2=texture2D(camASampler ,texCoord2).rgb;\n}\ngl_FragColor=vec4((frag1+frag2)/TWO,1.0);\n}","text2dPixelShader":"varying vec4 vColor;\nvarying vec2 vUV;\n\nuniform sampler2D diffuseSampler;\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\ngl_FragColor=color*vColor;\n}","text2dVertexShader":"\n#ifdef Instanced\n#define att attribute\n#else\n#define att uniform\n#endif\n\nattribute float index;\natt vec2 zBias;\natt vec4 transformX;\natt vec4 transformY;\natt float opacity;\natt vec2 topLeftUV;\natt vec2 sizeUV;\natt vec2 textureSize;\natt vec4 color;\natt float superSampleFactor;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\nvoid main(void) {\nvec2 pos2;\n\nif (index == 0.0) {\npos2=vec2(0.0,0.0);\nvUV=vec2(topLeftUV.x,topLeftUV.y+sizeUV.y);\n}\n\nelse if (index == 1.0) {\npos2=vec2(0.0,1.0);\nvUV=vec2(topLeftUV.x,topLeftUV.y);\n}\n\nelse if (index == 2.0) {\npos2=vec2(1.0,1.0);\nvUV=vec2(topLeftUV.x+sizeUV.x,topLeftUV.y);\n}\n\nelse if (index == 3.0) {\npos2=vec2(1.0,0.0);\nvUV=vec2(topLeftUV.x+sizeUV.x,topLeftUV.y+sizeUV.y);\n}\n\nvUV=(floor(vUV*textureSize)+vec2(0.0,0.0))/textureSize;\nvColor=color;\nvColor.a*=opacity;\nvec4 pos;\npos.xy=floor(pos2.xy*superSampleFactor*sizeUV*textureSize); \npos.z=1.0;\npos.w=1.0;\ngl_Position=vec4(dot(pos,transformX),dot(pos,transformY),zBias.x,1);\n}","tonemapPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float _ExposureAdjustment;\n#if defined(HABLE_TONEMAPPING)\nconst float A=0.15;\nconst float B=0.50;\nconst float C=0.10;\nconst float D=0.20;\nconst float E=0.02;\nconst float F=0.30;\nconst float W=11.2;\n#endif\nfloat Luminance(vec3 c)\n{\nreturn dot(c,vec3(0.22,0.707,0.071));\n}\nvoid main(void) \n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\n#if defined(REINHARD_TONEMAPPING)\nfloat lum=Luminance(colour.rgb); \nfloat lumTm=lum*_ExposureAdjustment;\nfloat scale=lumTm/(1.0+lumTm); \ncolour*=scale/lum;\n#elif defined(HABLE_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nconst float ExposureBias=2.0;\nvec3 x=ExposureBias*colour;\nvec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;\nx=vec3(W,W,W);\nvec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);\ncolour=curr*whiteScale;\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\ncolour=vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour);\n#endif\ngl_FragColor=vec4(colour.rgb,1.0);\n}","volumetricLightScatteringPixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D lightScatteringSampler;\nuniform float decay;\nuniform float exposure;\nuniform float weight;\nuniform float density;\nuniform vec2 meshPositionOnScreen;\nvarying vec2 vUV;\nvoid main(void) {\nvec2 tc=vUV;\nvec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);\ndeltaTexCoord*=1.0/float(NUM_SAMPLES)*density;\nfloat illuminationDecay=1.0;\nvec4 color=texture2D(lightScatteringSampler,tc)*0.4;\nfor(int i=0; i<NUM_SAMPLES; i++) {\ntc-=deltaTexCoord;\nvec4 sample=texture2D(lightScatteringSampler,tc)*0.4;\nsample*=illuminationDecay*weight;\ncolor+=sample;\nilluminationDecay*=decay;\n}\nvec4 realColor=texture2D(textureSampler,vUV);\ngl_FragColor=((vec4((vec3(color.r,color.g,color.b)*exposure),1))+(realColor*(1.5-0.4)));\n}\n","volumetricLightScatteringPassPixelShader":"#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\n#endif\n#if defined(ALPHATEST)\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void)\n{\n#if defined(ALPHATEST)\nvec4 diffuseColor=texture2D(diffuseSampler,vUV);\nif (diffuseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\n","vrDistortionCorrectionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\nvec2 HmdWarp(vec2 in01) {\nvec2 theta=(in01-LensCenter)*ScaleIn; \nfloat rSq=theta.x*theta.x+theta.y*theta.y;\nvec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);\nreturn LensCenter+Scale*rvector;\n}\nvoid main(void)\n{\nvec2 tc=HmdWarp(vUV);\nif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nelse{\ngl_FragColor=vec4(texture2D(textureSampler,tc).rgb,1.0);\n}\n}"};
  61566. 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"};
  61567. BABYLON.CollisionWorker="var BABYLON;!function(t){var e=function(t,e,o,i){return t.x>o.x+i?!1:o.x-i>e.x?!1:t.y>o.y+i?!1:o.y-i>e.y?!1:t.z>o.z+i?!1:!(o.z-i>e.z)},o=function(){var t={root:0,found:!1};return function(e,o,i,s){t.root=0,t.found=!1;var r=o*o-4*e*i;if(0>r)return t;var n=Math.sqrt(r),c=(-o-n)/(2*e),h=(-o+n)/(2*e);if(c>h){var a=h;h=c,c=a}return c>0&&s>c?(t.root=c,t.found=!0,t):h>0&&s>h?(t.root=h,t.found=!0,t):t}}(),i=function(){function i(){this.radius=new t.Vector3(1,1,1),this.retry=0,this.basePointWorld=t.Vector3.Zero(),this.velocityWorld=t.Vector3.Zero(),this.normalizedVelocity=t.Vector3.Zero(),this._collisionPoint=t.Vector3.Zero(),this._planeIntersectionPoint=t.Vector3.Zero(),this._tempVector=t.Vector3.Zero(),this._tempVector2=t.Vector3.Zero(),this._tempVector3=t.Vector3.Zero(),this._tempVector4=t.Vector3.Zero(),this._edge=t.Vector3.Zero(),this._baseToVertex=t.Vector3.Zero(),this._destinationPoint=t.Vector3.Zero(),this._slidePlaneNormal=t.Vector3.Zero(),this._displacementVector=t.Vector3.Zero()}return i.prototype._initialize=function(e,o,i){this.velocity=o,t.Vector3.NormalizeToRef(o,this.normalizedVelocity),this.basePoint=e,e.multiplyToRef(this.radius,this.basePointWorld),o.multiplyToRef(this.radius,this.velocityWorld),this.velocityWorldLength=this.velocityWorld.length(),this.epsilon=i,this.collisionFound=!1},i.prototype._checkPointInTriangle=function(e,o,i,s,r){o.subtractToRef(e,this._tempVector),i.subtractToRef(e,this._tempVector2),t.Vector3.CrossToRef(this._tempVector,this._tempVector2,this._tempVector4);var n=t.Vector3.Dot(this._tempVector4,r);return 0>n?!1:(s.subtractToRef(e,this._tempVector3),t.Vector3.CrossToRef(this._tempVector2,this._tempVector3,this._tempVector4),n=t.Vector3.Dot(this._tempVector4,r),0>n?!1:(t.Vector3.CrossToRef(this._tempVector3,this._tempVector,this._tempVector4),n=t.Vector3.Dot(this._tempVector4,r),n>=0))},i.prototype._canDoCollision=function(o,i,s,r){var n=t.Vector3.Distance(this.basePointWorld,o),c=Math.max(this.radius.x,this.radius.y,this.radius.z);return n>this.velocityWorldLength+c+i?!1:!!e(s,r,this.basePointWorld,this.velocityWorldLength+c)},i.prototype._testTriangle=function(e,i,s,r,n,c){var h,a=!1;i||(i=[]),i[e]||(i[e]=new t.Plane(0,0,0,0),i[e].copyFromPoints(s,r,n));var l=i[e];if(c||l.isFrontFacingTo(this.normalizedVelocity,0)){var _=l.signedDistanceTo(this.basePoint),d=t.Vector3.Dot(l.normal,this.velocity);if(0==d){if(Math.abs(_)>=1)return;a=!0,h=0}else{h=(-1-_)/d;var V=(1-_)/d;if(h>V){var u=V;V=h,h=u}if(h>1||0>V)return;0>h&&(h=0),h>1&&(h=1)}this._collisionPoint.copyFromFloats(0,0,0);var P=!1,p=1;if(a||(this.basePoint.subtractToRef(l.normal,this._planeIntersectionPoint),this.velocity.scaleToRef(h,this._tempVector),this._planeIntersectionPoint.addInPlace(this._tempVector),this._checkPointInTriangle(this._planeIntersectionPoint,s,r,n,l.normal)&&(P=!0,p=h,this._collisionPoint.copyFrom(this._planeIntersectionPoint))),!P){var f=this.velocity.lengthSquared(),m=f;this.basePoint.subtractToRef(s,this._tempVector);var T=2*t.Vector3.Dot(this.velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,y=o(m,T,b,p);y.found&&(p=y.root,P=!0,this._collisionPoint.copyFrom(s)),this.basePoint.subtractToRef(r,this._tempVector),T=2*t.Vector3.Dot(this.velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,y=o(m,T,b,p),y.found&&(p=y.root,P=!0,this._collisionPoint.copyFrom(r)),this.basePoint.subtractToRef(n,this._tempVector),T=2*t.Vector3.Dot(this.velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,y=o(m,T,b,p),y.found&&(p=y.root,P=!0,this._collisionPoint.copyFrom(n)),r.subtractToRef(s,this._edge),s.subtractToRef(this.basePoint,this._baseToVertex);var g=this._edge.lengthSquared(),v=t.Vector3.Dot(this._edge,this.velocity),R=t.Vector3.Dot(this._edge,this._baseToVertex);if(m=g*-f+v*v,T=g*(2*t.Vector3.Dot(this.velocity,this._baseToVertex))-2*v*R,b=g*(1-this._baseToVertex.lengthSquared())+R*R,y=o(m,T,b,p),y.found){var D=(v*y.root-R)/g;D>=0&&1>=D&&(p=y.root,P=!0,this._edge.scaleInPlace(D),s.addToRef(this._edge,this._collisionPoint))}n.subtractToRef(r,this._edge),r.subtractToRef(this.basePoint,this._baseToVertex),g=this._edge.lengthSquared(),v=t.Vector3.Dot(this._edge,this.velocity),R=t.Vector3.Dot(this._edge,this._baseToVertex),m=g*-f+v*v,T=g*(2*t.Vector3.Dot(this.velocity,this._baseToVertex))-2*v*R,b=g*(1-this._baseToVertex.lengthSquared())+R*R,y=o(m,T,b,p),y.found&&(D=(v*y.root-R)/g,D>=0&&1>=D&&(p=y.root,P=!0,this._edge.scaleInPlace(D),r.addToRef(this._edge,this._collisionPoint))),s.subtractToRef(n,this._edge),n.subtractToRef(this.basePoint,this._baseToVertex),g=this._edge.lengthSquared(),v=t.Vector3.Dot(this._edge,this.velocity),R=t.Vector3.Dot(this._edge,this._baseToVertex),m=g*-f+v*v,T=g*(2*t.Vector3.Dot(this.velocity,this._baseToVertex))-2*v*R,b=g*(1-this._baseToVertex.lengthSquared())+R*R,y=o(m,T,b,p),y.found&&(D=(v*y.root-R)/g,D>=0&&1>=D&&(p=y.root,P=!0,this._edge.scaleInPlace(D),n.addToRef(this._edge,this._collisionPoint)))}if(P){var x=p*this.velocity.length();(!this.collisionFound||x<this.nearestDistance)&&(this.intersectionPoint?this.intersectionPoint.copyFrom(this._collisionPoint):this.intersectionPoint=this._collisionPoint.clone(),this.nearestDistance=x,this.collisionFound=!0)}}},i.prototype._collide=function(t,e,o,i,s,r,n){for(var c=i;s>c;c+=3){var h=e[o[c]-r],a=e[o[c+1]-r],l=e[o[c+2]-r];this._testTriangle(c,t,l,a,h,n)}},i.prototype._getResponse=function(e,o){e.addToRef(o,this._destinationPoint),o.scaleInPlace(this.nearestDistance/o.length()),this.basePoint.addToRef(o,e),e.subtractToRef(this.intersectionPoint,this._slidePlaneNormal),this._slidePlaneNormal.normalize(),this._slidePlaneNormal.scaleToRef(this.epsilon,this._displacementVector),e.addInPlace(this._displacementVector),this.intersectionPoint.addInPlace(this._displacementVector),this._slidePlaneNormal.scaleInPlace(t.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint,this._slidePlaneNormal,this._destinationPoint)),this._destinationPoint.subtractInPlace(this._slidePlaneNormal),this._destinationPoint.subtractToRef(this.intersectionPoint,o)},i}();t.Collider=i}(BABYLON||(BABYLON={}));var BABYLON;!function(o){o.WorkerIncluded=!0;var e=function(){function o(){this._meshes={},this._geometries={}}return o.prototype.getMeshes=function(){return this._meshes},o.prototype.getGeometries=function(){return this._geometries},o.prototype.getMesh=function(o){return this._meshes[o]},o.prototype.addMesh=function(o){this._meshes[o.uniqueId]=o},o.prototype.removeMesh=function(o){delete this._meshes[o]},o.prototype.getGeometry=function(o){return this._geometries[o]},o.prototype.addGeometry=function(o){this._geometries[o.id]=o},o.prototype.removeGeometry=function(o){delete this._geometries[o]},o}();o.CollisionCache=e;var i=function(){function e(e,i,r){this.collider=e,this._collisionCache=i,this.finalPosition=r,this.collisionsScalingMatrix=o.Matrix.Zero(),this.collisionTranformationMatrix=o.Matrix.Zero()}return e.prototype.collideWithWorld=function(o,e,i,r){var t=.01;if(this.collider.retry>=i)return void this.finalPosition.copyFrom(o);this.collider._initialize(o,e,t);for(var s,l=this._collisionCache.getMeshes(),n=Object.keys(l),a=n.length,c=0;a>c;++c)if(s=n[c],parseInt(s)!=r){var d=l[s];d.checkCollisions&&this.checkCollision(d)}return this.collider.collisionFound?(0===e.x&&0===e.y&&0===e.z||this.collider._getResponse(o,e),e.length()<=t?void this.finalPosition.copyFrom(o):(this.collider.retry++,void this.collideWithWorld(o,e,i,r))):void o.addToRef(e,this.finalPosition)},e.prototype.checkCollision=function(e){if(this.collider._canDoCollision(o.Vector3.FromArray(e.sphereCenter),e.sphereRadius,o.Vector3.FromArray(e.boxMinimum),o.Vector3.FromArray(e.boxMaximum))){o.Matrix.ScalingToRef(1/this.collider.radius.x,1/this.collider.radius.y,1/this.collider.radius.z,this.collisionsScalingMatrix);var i=o.Matrix.FromArray(e.worldMatrixFromCache);i.multiplyToRef(this.collisionsScalingMatrix,this.collisionTranformationMatrix),this.processCollisionsForSubMeshes(this.collisionTranformationMatrix,e)}},e.prototype.processCollisionsForSubMeshes=function(o,e){var i=e.subMeshes,r=i.length;if(!e.geometryId)return void console.log(\"no mesh geometry id\");var t=this._collisionCache.getGeometry(e.geometryId);if(!t)return void console.log(\"couldn't find geometry\",e.geometryId);for(var s=0;r>s;s++){var l=i[s];r>1&&!this.checkSubmeshCollision(l)||(this.collideForSubMesh(l,o,t),this.collider.collisionFound&&(this.collider.collidedMesh=e.uniqueId))}},e.prototype.collideForSubMesh=function(e,i,r){if(!r.positionsArray){r.positionsArray=[];for(var t=0,s=r.positions.length;s>t;t+=3){var l=o.Vector3.FromArray([r.positions[t],r.positions[t+1],r.positions[t+2]]);r.positionsArray.push(l)}}if(!e._lastColliderWorldVertices||!e._lastColliderTransformMatrix.equals(i)){e._lastColliderTransformMatrix=i.clone(),e._lastColliderWorldVertices=[],e._trianglePlanes=[];for(var n=e.verticesStart,a=e.verticesStart+e.verticesCount,t=n;a>t;t++)e._lastColliderWorldVertices.push(o.Vector3.TransformCoordinates(r.positionsArray[t],i))}this.collider._collide(e._trianglePlanes,e._lastColliderWorldVertices,r.indices,e.indexStart,e.indexStart+e.indexCount,e.verticesStart,e.hasMaterial)},e.prototype.checkSubmeshCollision=function(e){return this.collider._canDoCollision(o.Vector3.FromArray(e.sphereCenter),e.sphereRadius,o.Vector3.FromArray(e.boxMinimum),o.Vector3.FromArray(e.boxMaximum))},e}();o.CollideWorker=i;var r=function(){function r(){}return r.prototype.onInit=function(i){this._collisionCache=new e;var r={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.INIT};postMessage(r,void 0)},r.prototype.onUpdate=function(e){var i=this,r={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.UPDATE};try{for(var t in e.updatedGeometries)e.updatedGeometries.hasOwnProperty(t)&&this._collisionCache.addGeometry(e.updatedGeometries[t]);for(var s in e.updatedMeshes)e.updatedMeshes.hasOwnProperty(s)&&this._collisionCache.addMesh(e.updatedMeshes[s]);e.removedGeometries.forEach(function(o){i._collisionCache.removeGeometry(o)}),e.removedMeshes.forEach(function(o){i._collisionCache.removeMesh(o)})}catch(l){r.error=o.WorkerReplyType.UNKNOWN_ERROR}postMessage(r,void 0)},r.prototype.onCollision=function(e){var r=o.Vector3.Zero(),t=new o.Collider;t.radius=o.Vector3.FromArray(e.collider.radius);var s=new i(t,this._collisionCache,r);s.collideWithWorld(o.Vector3.FromArray(e.collider.position),o.Vector3.FromArray(e.collider.velocity),e.maximumRetry,e.excludedMeshUniqueId);var l={collidedMeshUniqueId:t.collidedMesh,collisionId:e.collisionId,newPosition:r.asArray()},n={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.COLLIDE,payload:l};postMessage(n,void 0)},r}();o.CollisionDetectorTransferable=r;try{if(self&&self instanceof WorkerGlobalScope){window={},o.Collider||(importScripts(\"./babylon.collisionCoordinator.js\"),importScripts(\"./babylon.collider.js\"),importScripts(\"../Math/babylon.math.js\"));var t=new r,s=function(e){var i=e.data;switch(i.taskType){case o.WorkerTaskType.INIT:t.onInit(i.payload);break;case o.WorkerTaskType.COLLIDE:t.onCollision(i.payload);break;case o.WorkerTaskType.UPDATE:t.onUpdate(i.payload)}};self.onmessage=s}}catch(l){console.log(\"single worker init\")}}(BABYLON||(BABYLON={}));var BABYLON;!function(e){e.CollisionWorker=\"\",function(e){e[e.INIT=0]=\"INIT\",e[e.UPDATE=1]=\"UPDATE\",e[e.COLLIDE=2]=\"COLLIDE\"}(e.WorkerTaskType||(e.WorkerTaskType={}));var o=e.WorkerTaskType;!function(e){e[e.SUCCESS=0]=\"SUCCESS\",e[e.UNKNOWN_ERROR=1]=\"UNKNOWN_ERROR\"}(e.WorkerReplyType||(e.WorkerReplyType={}));var i=e.WorkerReplyType,t=function(){function t(){var r=this;this._scaledPosition=e.Vector3.Zero(),this._scaledVelocity=e.Vector3.Zero(),this.onMeshUpdated=function(e){r._addUpdateMeshesList[e.uniqueId]=t.SerializeMesh(e)},this.onGeometryUpdated=function(e){r._addUpdateGeometriesList[e.id]=t.SerializeGeometry(e)},this._afterRender=function(){if(r._init&&!(0==r._toRemoveGeometryArray.length&&0==r._toRemoveMeshesArray.length&&0==Object.keys(r._addUpdateGeometriesList).length&&0==Object.keys(r._addUpdateMeshesList).length||r._runningUpdated>4)){++r._runningUpdated;var e={updatedMeshes:r._addUpdateMeshesList,updatedGeometries:r._addUpdateGeometriesList,removedGeometries:r._toRemoveGeometryArray,removedMeshes:r._toRemoveMeshesArray},i={payload:e,taskType:o.UPDATE},t=[];for(var s in e.updatedGeometries)e.updatedGeometries.hasOwnProperty(s)&&(t.push(i.payload.updatedGeometries[s].indices.buffer),t.push(i.payload.updatedGeometries[s].normals.buffer),t.push(i.payload.updatedGeometries[s].positions.buffer));r._worker.postMessage(i,t),r._addUpdateMeshesList={},r._addUpdateGeometriesList={},r._toRemoveGeometryArray=[],r._toRemoveMeshesArray=[]}},this._onMessageFromWorker=function(t){var s=t.data;if(s.error!=i.SUCCESS)return void e.Tools.Warn(\"error returned from worker!\");switch(s.taskType){case o.INIT:r._init=!0,r._scene.meshes.forEach(function(e){r.onMeshAdded(e)}),r._scene.getGeometries().forEach(function(e){r.onGeometryAdded(e)});break;case o.UPDATE:r._runningUpdated--;break;case o.COLLIDE:r._runningCollisionTask=!1;var n=s.payload;if(!r._collisionsCallbackArray[n.collisionId])return;r._collisionsCallbackArray[n.collisionId](n.collisionId,e.Vector3.FromArray(n.newPosition),r._scene.getMeshByUniqueID(n.collidedMeshUniqueId)),r._collisionsCallbackArray[n.collisionId]=void 0}},this._collisionsCallbackArray=[],this._init=!1,this._runningUpdated=0,this._runningCollisionTask=!1,this._addUpdateMeshesList={},this._addUpdateGeometriesList={},this._toRemoveGeometryArray=[],this._toRemoveMeshesArray=[]}return t.prototype.getNewPosition=function(e,i,t,r,s,n,a){if(this._init&&!this._collisionsCallbackArray[a]&&!this._collisionsCallbackArray[a+1e5]){e.divideToRef(t.radius,this._scaledPosition),i.divideToRef(t.radius,this._scaledVelocity),this._collisionsCallbackArray[a]=n;var d={collider:{position:this._scaledPosition.asArray(),velocity:this._scaledVelocity.asArray(),radius:t.radius.asArray()},collisionId:a,excludedMeshUniqueId:s?s.uniqueId:null,maximumRetry:r},l={payload:d,taskType:o.COLLIDE};this._worker.postMessage(l)}},t.prototype.init=function(i){this._scene=i,this._scene.registerAfterRender(this._afterRender);var t=e.WorkerIncluded?e.Engine.CodeRepository+\"Collisions/babylon.collisionWorker.js\":URL.createObjectURL(new Blob([e.CollisionWorker],{type:\"application/javascript\"}));this._worker=new Worker(t),this._worker.onmessage=this._onMessageFromWorker;var r={payload:{},taskType:o.INIT};this._worker.postMessage(r)},t.prototype.destroy=function(){this._scene.unregisterAfterRender(this._afterRender),this._worker.terminate()},t.prototype.onMeshAdded=function(e){e.registerAfterWorldMatrixUpdate(this.onMeshUpdated),this.onMeshUpdated(e)},t.prototype.onMeshRemoved=function(e){this._toRemoveMeshesArray.push(e.uniqueId)},t.prototype.onGeometryAdded=function(e){e.onGeometryUpdated=this.onGeometryUpdated,this.onGeometryUpdated(e)},t.prototype.onGeometryDeleted=function(e){this._toRemoveGeometryArray.push(e.id)},t.SerializeMesh=function(o){var i=[];o.subMeshes&&(i=o.subMeshes.map(function(e,o){return{position:o,verticesStart:e.verticesStart,verticesCount:e.verticesCount,indexStart:e.indexStart,indexCount:e.indexCount,hasMaterial:!!e.getMaterial(),sphereCenter:e.getBoundingInfo().boundingSphere.centerWorld.asArray(),sphereRadius:e.getBoundingInfo().boundingSphere.radiusWorld,boxMinimum:e.getBoundingInfo().boundingBox.minimumWorld.asArray(),boxMaximum:e.getBoundingInfo().boundingBox.maximumWorld.asArray()}}));var t=null;return o instanceof e.Mesh?t=o.geometry?o.geometry.id:null:o instanceof e.InstancedMesh&&(t=o.sourceMesh&&o.sourceMesh.geometry?o.sourceMesh.geometry.id:null),{uniqueId:o.uniqueId,id:o.id,name:o.name,geometryId:t,sphereCenter:o.getBoundingInfo().boundingSphere.centerWorld.asArray(),sphereRadius:o.getBoundingInfo().boundingSphere.radiusWorld,boxMinimum:o.getBoundingInfo().boundingBox.minimumWorld.asArray(),boxMaximum:o.getBoundingInfo().boundingBox.maximumWorld.asArray(),worldMatrixFromCache:o.worldMatrixFromCache.asArray(),subMeshes:i,checkCollisions:o.checkCollisions}},t.SerializeGeometry=function(o){return{id:o.id,positions:new Float32Array(o.getVerticesData(e.VertexBuffer.PositionKind)||[]),normals:new Float32Array(o.getVerticesData(e.VertexBuffer.NormalKind)||[]),indices:new Int32Array(o.getIndices()||[])}},t}();e.CollisionCoordinatorWorker=t;var r=function(){function o(){this._scaledPosition=e.Vector3.Zero(),this._scaledVelocity=e.Vector3.Zero(),this._finalPosition=e.Vector3.Zero()}return o.prototype.getNewPosition=function(e,o,i,t,r,s,n){e.divideToRef(i.radius,this._scaledPosition),o.divideToRef(i.radius,this._scaledVelocity),i.collidedMesh=null,i.retry=0,i.initialVelocity=this._scaledVelocity,i.initialPosition=this._scaledPosition,this._collideWithWorld(this._scaledPosition,this._scaledVelocity,i,t,this._finalPosition,r),this._finalPosition.multiplyInPlace(i.radius),s(n,this._finalPosition,i.collidedMesh)},o.prototype.init=function(e){this._scene=e},o.prototype.destroy=function(){},o.prototype.onMeshAdded=function(e){},o.prototype.onMeshUpdated=function(e){},o.prototype.onMeshRemoved=function(e){},o.prototype.onGeometryAdded=function(e){},o.prototype.onGeometryUpdated=function(e){},o.prototype.onGeometryDeleted=function(e){},o.prototype._collideWithWorld=function(o,i,t,r,s,n){void 0===n&&(n=null);var a=10*e.Engine.CollisionsEpsilon;if(t.retry>=r)return void s.copyFrom(o);t._initialize(o,i,a);for(var d=0;d<this._scene.meshes.length;d++){var l=this._scene.meshes[d];l.isEnabled()&&l.checkCollisions&&l.subMeshes&&l!==n&&l._checkCollision(t)}return t.collisionFound?(0===i.x&&0===i.y&&0===i.z||t._getResponse(o,i),i.length()<=a?void s.copyFrom(o):(t.retry++,void this._collideWithWorld(o,i,t,r,s,n))):void o.addToRef(i,s)},o}();e.CollisionCoordinatorLegacy=r}(BABYLON||(BABYLON={}));var BABYLON;!function(t){t.ToGammaSpace=1/2.2,t.ToLinearSpace=2.2,t.Epsilon=.001;var i=function(){function t(){}return t.WithinEpsilon=function(t,i,n){void 0===n&&(n=1.401298e-45);var r=t-i;return r>=-n&&n>=r},t.ToHex=function(t){var i=t.toString(16);return 15>=t?(\"0\"+i).toUpperCase():i.toUpperCase()},t.Sign=function(t){return t=+t,0===t||isNaN(t)?t:t>0?1:-1},t.Clamp=function(t,i,n){return void 0===i&&(i=0),void 0===n&&(n=1),Math.min(n,Math.max(i,t))},t}();t.MathTools=i;var n=function(){function n(t,i,n){void 0===t&&(t=0),void 0===i&&(i=0),void 0===n&&(n=0),this.r=t,this.g=i,this.b=n}return n.prototype.toString=function(){return\"{R: \"+this.r+\" G:\"+this.g+\" B:\"+this.b+\"}\"},n.prototype.getClassName=function(){return\"Color3\"},n.prototype.getHashCode=function(){var t=this.r||0;return t=397*t^(this.g||0),t=397*t^(this.b||0)},n.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.r,t[i+1]=this.g,t[i+2]=this.b,this},n.prototype.toColor4=function(t){return void 0===t&&(t=1),new r(this.r,this.g,this.b,t)},n.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},n.prototype.toLuminance=function(){return.3*this.r+.59*this.g+.11*this.b},n.prototype.multiply=function(t){return new n(this.r*t.r,this.g*t.g,this.b*t.b)},n.prototype.multiplyToRef=function(t,i){return i.r=this.r*t.r,i.g=this.g*t.g,i.b=this.b*t.b,this},n.prototype.equals=function(t){return t&&this.r===t.r&&this.g===t.g&&this.b===t.b},n.prototype.equalsFloats=function(t,i,n){return this.r===t&&this.g===i&&this.b===n},n.prototype.scale=function(t){return new n(this.r*t,this.g*t,this.b*t)},n.prototype.scaleToRef=function(t,i){return i.r=this.r*t,i.g=this.g*t,i.b=this.b*t,this},n.prototype.add=function(t){return new n(this.r+t.r,this.g+t.g,this.b+t.b)},n.prototype.addToRef=function(t,i){return i.r=this.r+t.r,i.g=this.g+t.g,i.b=this.b+t.b,this},n.prototype.subtract=function(t){return new n(this.r-t.r,this.g-t.g,this.b-t.b)},n.prototype.subtractToRef=function(t,i){return i.r=this.r-t.r,i.g=this.g-t.g,i.b=this.b-t.b,this},n.prototype.clone=function(){return new n(this.r,this.g,this.b)},n.prototype.copyFrom=function(t){return this.r=t.r,this.g=t.g,this.b=t.b,this},n.prototype.copyFromFloats=function(t,i,n){return this.r=t,this.g=i,this.b=n,this},n.prototype.toHexString=function(){var t=255*this.r|0,n=255*this.g|0,r=255*this.b|0;return\"#\"+i.ToHex(t)+i.ToHex(n)+i.ToHex(r)},n.prototype.toLinearSpace=function(){var t=new n;return this.toLinearSpaceToRef(t),t},n.prototype.toLinearSpaceToRef=function(i){return i.r=Math.pow(this.r,t.ToLinearSpace),i.g=Math.pow(this.g,t.ToLinearSpace),i.b=Math.pow(this.b,t.ToLinearSpace),this},n.prototype.toGammaSpace=function(){var t=new n;return this.toGammaSpaceToRef(t),t},n.prototype.toGammaSpaceToRef=function(i){return i.r=Math.pow(this.r,t.ToGammaSpace),i.g=Math.pow(this.g,t.ToGammaSpace),i.b=Math.pow(this.b,t.ToGammaSpace),this},n.FromHexString=function(t){if(\"#\"!==t.substring(0,1)||7!==t.length)return new n(0,0,0);var i=parseInt(t.substring(1,3),16),r=parseInt(t.substring(3,5),16),o=parseInt(t.substring(5,7),16);return n.FromInts(i,r,o)},n.FromArray=function(t,i){return void 0===i&&(i=0),new n(t[i],t[i+1],t[i+2])},n.FromInts=function(t,i,r){return new n(t/255,i/255,r/255)},n.Lerp=function(t,i,r){var o=t.r+(i.r-t.r)*r,e=t.g+(i.g-t.g)*r,s=t.b+(i.b-t.b)*r;return new n(o,e,s)},n.Red=function(){return new n(1,0,0)},n.Green=function(){return new n(0,1,0)},n.Blue=function(){return new n(0,0,1)},n.Black=function(){return new n(0,0,0)},n.White=function(){return new n(1,1,1)},n.Purple=function(){return new n(.5,0,.5)},n.Magenta=function(){return new n(1,0,1)},n.Yellow=function(){return new n(1,1,0)},n.Gray=function(){return new n(.5,.5,.5)},n}();t.Color3=n;var r=function(){function t(t,i,n,r){this.r=t,this.g=i,this.b=n,this.a=r}return t.prototype.addInPlace=function(t){return this.r+=t.r,this.g+=t.g,this.b+=t.b,this.a+=t.a,this},t.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},t.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.r,t[i+1]=this.g,t[i+2]=this.b,t[i+3]=this.a,this},t.prototype.add=function(i){return new t(this.r+i.r,this.g+i.g,this.b+i.b,this.a+i.a)},t.prototype.subtract=function(i){return new t(this.r-i.r,this.g-i.g,this.b-i.b,this.a-i.a)},t.prototype.subtractToRef=function(t,i){return i.r=this.r-t.r,i.g=this.g-t.g,i.b=this.b-t.b,i.a=this.a-t.a,this},t.prototype.scale=function(i){return new t(this.r*i,this.g*i,this.b*i,this.a*i)},t.prototype.scaleToRef=function(t,i){return i.r=this.r*t,i.g=this.g*t,i.b=this.b*t,i.a=this.a*t,this},t.prototype.multiply=function(i){return new t(this.r*i.r,this.g*i.g,this.b*i.b,this.a*i.a)},t.prototype.multiplyToRef=function(t,i){return i.r=this.r*t.r,i.g=this.g*t.g,i.b=this.b*t.b,i.a=this.a*t.a,i},t.prototype.toString=function(){return\"{R: \"+this.r+\" G:\"+this.g+\" B:\"+this.b+\" A:\"+this.a+\"}\"},t.prototype.getClassName=function(){return\"Color4\"},t.prototype.getHashCode=function(){var t=this.r||0;return t=397*t^(this.g||0),t=397*t^(this.b||0),t=397*t^(this.a||0)},t.prototype.clone=function(){return new t(this.r,this.g,this.b,this.a)},t.prototype.copyFrom=function(t){return this.r=t.r,this.g=t.g,this.b=t.b,this.a=t.a,this},t.prototype.toHexString=function(){var t=255*this.r|0,n=255*this.g|0,r=255*this.b|0,o=255*this.a|0;return\"#\"+i.ToHex(t)+i.ToHex(n)+i.ToHex(r)+i.ToHex(o)},t.FromHexString=function(i){if(\"#\"!==i.substring(0,1)||9!==i.length)return new t(0,0,0,0);var n=parseInt(i.substring(1,3),16),r=parseInt(i.substring(3,5),16),o=parseInt(i.substring(5,7),16),e=parseInt(i.substring(7,9),16);return t.FromInts(n,r,o,e)},t.Lerp=function(i,n,r){var o=new t(0,0,0,0);return t.LerpToRef(i,n,r,o),o},t.LerpToRef=function(t,i,n,r){r.r=t.r+(i.r-t.r)*n,r.g=t.g+(i.g-t.g)*n,r.b=t.b+(i.b-t.b)*n,r.a=t.a+(i.a-t.a)*n},t.FromArray=function(i,n){return void 0===n&&(n=0),new t(i[n],i[n+1],i[n+2],i[n+3])},t.FromInts=function(i,n,r,o){return new t(i/255,n/255,r/255,o/255)},t.CheckColors4=function(t,i){if(t.length===3*i){for(var n=[],r=0;r<t.length;r+=3){var o=r/3*4;n[o]=t[r],n[o+1]=t[r+1],n[o+2]=t[r+2],n[o+3]=1}return n}return t},t}();t.Color4=r;var o=function(){function n(t,i){this.x=t,this.y=i}return n.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\"}\"},n.prototype.getClassName=function(){return\"Vector2\"},n.prototype.getHashCode=function(){var t=this.x||0;return t=397*t^(this.y||0)},n.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,this},n.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},n.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this},n.prototype.copyFromFloats=function(t,i){return this.x=t,this.y=i,this},n.prototype.add=function(t){return new n(this.x+t.x,this.y+t.y)},n.prototype.addToRef=function(t,i){return i.x=this.x+t.x,i.y=this.y+t.y,this},n.prototype.addInPlace=function(t){return this.x+=t.x,this.y+=t.y,this},n.prototype.addVector3=function(t){return new n(this.x+t.x,this.y+t.y)},n.prototype.subtract=function(t){return new n(this.x-t.x,this.y-t.y)},n.prototype.subtractToRef=function(t,i){return i.x=this.x-t.x,i.y=this.y-t.y,this},n.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this},n.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this},n.prototype.multiply=function(t){return new n(this.x*t.x,this.y*t.y)},n.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,this},n.prototype.multiplyByFloats=function(t,i){return new n(this.x*t,this.y*i)},n.prototype.divide=function(t){return new n(this.x/t.x,this.y/t.y)},n.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,this},n.prototype.negate=function(){return new n(-this.x,-this.y)},n.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this},n.prototype.scale=function(t){return new n(this.x*t,this.y*t)},n.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y},n.prototype.equalsWithEpsilon=function(n,r){return void 0===r&&(r=t.Epsilon),n&&i.WithinEpsilon(this.x,n.x,r)&&i.WithinEpsilon(this.y,n.y,r)},n.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y)},n.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y},n.prototype.normalize=function(){var t=this.length();if(0===t)return this;var i=1/t;return this.x*=i,this.y*=i,this},n.prototype.clone=function(){return new n(this.x,this.y)},n.Zero=function(){return new n(0,0)},n.FromArray=function(t,i){return void 0===i&&(i=0),new n(t[i],t[i+1])},n.FromArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1]},n.CatmullRom=function(t,i,r,o,e){var s=e*e,h=e*s,a=.5*(2*i.x+(-t.x+r.x)*e+(2*t.x-5*i.x+4*r.x-o.x)*s+(-t.x+3*i.x-3*r.x+o.x)*h),u=.5*(2*i.y+(-t.y+r.y)*e+(2*t.y-5*i.y+4*r.y-o.y)*s+(-t.y+3*i.y-3*r.y+o.y)*h);return new n(a,u)},n.Clamp=function(t,i,r){var o=t.x;o=o>r.x?r.x:o,o=o<i.x?i.x:o;var e=t.y;return e=e>r.y?r.y:e,e=e<i.y?i.y:e,new n(o,e)},n.Hermite=function(t,i,r,o,e){var s=e*e,h=e*s,a=2*h-3*s+1,u=-2*h+3*s,m=h-2*s+e,y=h-s,c=t.x*a+r.x*u+i.x*m+o.x*y,p=t.y*a+r.y*u+i.y*m+o.y*y;return new n(c,p)},n.Lerp=function(t,i,r){var o=t.x+(i.x-t.x)*r,e=t.y+(i.y-t.y)*r;return new n(o,e)},n.Dot=function(t,i){return t.x*i.x+t.y*i.y},n.Normalize=function(t){var i=t.clone();return i.normalize(),i},n.Minimize=function(t,i){var r=t.x<i.x?t.x:i.x,o=t.y<i.y?t.y:i.y;return new n(r,o)},n.Maximize=function(t,i){var r=t.x>i.x?t.x:i.x,o=t.y>i.y?t.y:i.y;return new n(r,o)},n.Transform=function(t,i){var r=n.Zero();return n.TransformToRef(t,i,r),r},n.TransformToRef=function(t,i,n){var r=t.x*i.m[0]+t.y*i.m[4]+i.m[12],o=t.x*i.m[1]+t.y*i.m[5]+i.m[13];n.x=r,n.y=o},n.PointInTriangle=function(t,i,n,r){var o=.5*(-n.y*r.x+i.y*(-n.x+r.x)+i.x*(n.y-r.y)+n.x*r.y),e=0>o?-1:1,s=(i.y*r.x-i.x*r.y+(r.y-i.y)*t.x+(i.x-r.x)*t.y)*e,h=(i.x*n.y-i.y*n.x+(i.y-n.y)*t.x+(n.x-i.x)*t.y)*e;return s>0&&h>0&&2*o*e>s+h},n.Distance=function(t,i){return Math.sqrt(n.DistanceSquared(t,i))},n.DistanceSquared=function(t,i){var n=t.x-i.x,r=t.y-i.y;return n*n+r*r},n.Center=function(t,i){var n=t.add(i);return n.scaleInPlace(.5),n},n.DistanceOfPointFromSegment=function(t,i,r){var o=n.DistanceSquared(i,r);if(0===o)return n.Distance(t,i);var e=r.subtract(i),s=Math.max(0,Math.min(1,n.Dot(t.subtract(i),e)/o)),h=i.add(e.multiplyByFloats(s,s));return n.Distance(t,h)},n}();t.Vector2=o;var e=function(){function n(t,i,n){this.x=t,this.y=i,this.z=n}return n.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\"}\"},n.prototype.getClassName=function(){return\"Vector3\"},n.prototype.getHashCode=function(){var t=this.x||0;return t=397*t^(this.y||0),t=397*t^(this.z||0)},n.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},n.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,t[i+2]=this.z,this},n.prototype.toQuaternion=function(){var t=new a(0,0,0,1),i=Math.cos(.5*(this.x+this.z)),n=Math.sin(.5*(this.x+this.z)),r=Math.cos(.5*(this.z-this.x)),o=Math.sin(.5*(this.z-this.x)),e=Math.cos(.5*this.y),s=Math.sin(.5*this.y);return t.x=r*s,t.y=-o*s,t.z=n*e,t.w=i*e,t},n.prototype.addInPlace=function(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this},n.prototype.add=function(t){return new n(this.x+t.x,this.y+t.y,this.z+t.z)},n.prototype.addToRef=function(t,i){return i.x=this.x+t.x,i.y=this.y+t.y,i.z=this.z+t.z,this},n.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this},n.prototype.subtract=function(t){return new n(this.x-t.x,this.y-t.y,this.z-t.z)},n.prototype.subtractToRef=function(t,i){return i.x=this.x-t.x,i.y=this.y-t.y,i.z=this.z-t.z,this},n.prototype.subtractFromFloats=function(t,i,r){return new n(this.x-t,this.y-i,this.z-r)},n.prototype.subtractFromFloatsToRef=function(t,i,n,r){return r.x=this.x-t,r.y=this.y-i,r.z=this.z-n,this},n.prototype.negate=function(){return new n(-this.x,-this.y,-this.z)},n.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this.z*=t,this},n.prototype.scale=function(t){return new n(this.x*t,this.y*t,this.z*t)},n.prototype.scaleToRef=function(t,i){i.x=this.x*t,i.y=this.y*t,i.z=this.z*t},n.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z},n.prototype.equalsWithEpsilon=function(n,r){return void 0===r&&(r=t.Epsilon),n&&i.WithinEpsilon(this.x,n.x,r)&&i.WithinEpsilon(this.y,n.y,r)&&i.WithinEpsilon(this.z,n.z,r)},n.prototype.equalsToFloats=function(t,i,n){return this.x===t&&this.y===i&&this.z===n},n.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this},n.prototype.multiply=function(t){return new n(this.x*t.x,this.y*t.y,this.z*t.z)},n.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,i.z=this.z*t.z,this},n.prototype.multiplyByFloats=function(t,i,r){return new n(this.x*t,this.y*i,this.z*r)},n.prototype.divide=function(t){return new n(this.x/t.x,this.y/t.y,this.z/t.z)},n.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,i.z=this.z/t.z,this},n.prototype.MinimizeInPlace=function(t){return t.x<this.x&&(this.x=t.x),t.y<this.y&&(this.y=t.y),t.z<this.z&&(this.z=t.z),this},n.prototype.MaximizeInPlace=function(t){return t.x>this.x&&(this.x=t.x),t.y>this.y&&(this.y=t.y),t.z>this.z&&(this.z=t.z),this},n.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)},n.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y+this.z*this.z},n.prototype.normalize=function(){var t=this.length();if(0===t||1===t)return this;var i=1/t;return this.x*=i,this.y*=i,this.z*=i,this},n.prototype.clone=function(){return new n(this.x,this.y,this.z)},n.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this},n.prototype.copyFromFloats=function(t,i,n){return this.x=t,this.y=i,this.z=n,this},n.GetClipFactor=function(t,i,r,o){var e=n.Dot(t,r)-o,s=n.Dot(i,r)-o,h=e/(e-s);return h},n.FromArray=function(t,i){return i||(i=0),new n(t[i],t[i+1],t[i+2])},n.FromFloatArray=function(t,i){return i||(i=0),new n(t[i],t[i+1],t[i+2])},n.FromArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1],n.z=t[i+2]},n.FromFloatArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1],n.z=t[i+2]},n.FromFloatsToRef=function(t,i,n,r){r.x=t,r.y=i,r.z=n},n.Zero=function(){return new n(0,0,0)},n.Up=function(){return new n(0,1,0)},n.TransformCoordinates=function(t,i){var r=n.Zero();return n.TransformCoordinatesToRef(t,i,r),r},n.TransformCoordinatesToRef=function(t,i,n){var r=t.x*i.m[0]+t.y*i.m[4]+t.z*i.m[8]+i.m[12],o=t.x*i.m[1]+t.y*i.m[5]+t.z*i.m[9]+i.m[13],e=t.x*i.m[2]+t.y*i.m[6]+t.z*i.m[10]+i.m[14],s=t.x*i.m[3]+t.y*i.m[7]+t.z*i.m[11]+i.m[15];n.x=r/s,n.y=o/s,n.z=e/s},n.TransformCoordinatesFromFloatsToRef=function(t,i,n,r,o){var e=t*r.m[0]+i*r.m[4]+n*r.m[8]+r.m[12],s=t*r.m[1]+i*r.m[5]+n*r.m[9]+r.m[13],h=t*r.m[2]+i*r.m[6]+n*r.m[10]+r.m[14],a=t*r.m[3]+i*r.m[7]+n*r.m[11]+r.m[15];o.x=e/a,o.y=s/a,o.z=h/a},n.TransformNormal=function(t,i){var r=n.Zero();return n.TransformNormalToRef(t,i,r),r},n.TransformNormalToRef=function(t,i,n){n.x=t.x*i.m[0]+t.y*i.m[4]+t.z*i.m[8],n.y=t.x*i.m[1]+t.y*i.m[5]+t.z*i.m[9],n.z=t.x*i.m[2]+t.y*i.m[6]+t.z*i.m[10]},n.TransformNormalFromFloatsToRef=function(t,i,n,r,o){o.x=t*r.m[0]+i*r.m[4]+n*r.m[8],o.y=t*r.m[1]+i*r.m[5]+n*r.m[9],o.z=t*r.m[2]+i*r.m[6]+n*r.m[10]},n.CatmullRom=function(t,i,r,o,e){var s=e*e,h=e*s,a=.5*(2*i.x+(-t.x+r.x)*e+(2*t.x-5*i.x+4*r.x-o.x)*s+(-t.x+3*i.x-3*r.x+o.x)*h),u=.5*(2*i.y+(-t.y+r.y)*e+(2*t.y-5*i.y+4*r.y-o.y)*s+(-t.y+3*i.y-3*r.y+o.y)*h),m=.5*(2*i.z+(-t.z+r.z)*e+(2*t.z-5*i.z+4*r.z-o.z)*s+(-t.z+3*i.z-3*r.z+o.z)*h);return new n(a,u,m)},n.Clamp=function(t,i,r){var o=t.x;o=o>r.x?r.x:o,o=o<i.x?i.x:o;var e=t.y;e=e>r.y?r.y:e,e=e<i.y?i.y:e;var s=t.z;return s=s>r.z?r.z:s,s=s<i.z?i.z:s,new n(o,e,s)},n.Hermite=function(t,i,r,o,e){var s=e*e,h=e*s,a=2*h-3*s+1,u=-2*h+3*s,m=h-2*s+e,y=h-s,c=t.x*a+r.x*u+i.x*m+o.x*y,p=t.y*a+r.y*u+i.y*m+o.y*y,f=t.z*a+r.z*u+i.z*m+o.z*y;return new n(c,p,f)},n.Lerp=function(t,i,r){var o=t.x+(i.x-t.x)*r,e=t.y+(i.y-t.y)*r,s=t.z+(i.z-t.z)*r;return new n(o,e,s)},n.Dot=function(t,i){return t.x*i.x+t.y*i.y+t.z*i.z},n.Cross=function(t,i){var r=n.Zero();return n.CrossToRef(t,i,r),r},n.CrossToRef=function(t,i,n){M.Vector3[0].x=t.y*i.z-t.z*i.y,M.Vector3[0].y=t.z*i.x-t.x*i.z,M.Vector3[0].z=t.x*i.y-t.y*i.x,n.copyFrom(M.Vector3[0])},n.Normalize=function(t){var i=n.Zero();return n.NormalizeToRef(t,i),i},n.NormalizeToRef=function(t,i){i.copyFrom(t),i.normalize()},n.Project=function(t,i,r,o){var e=o.width,s=o.height,h=o.x,a=o.y,m=n._viewportMatrixCache?n._viewportMatrixCache:n._viewportMatrixCache=new u;u.FromValuesToRef(e/2,0,0,0,0,-s/2,0,0,0,0,1,0,h+e/2,s/2+a,0,1,m);var y=n._matrixCache?n._matrixCache:n._matrixCache=new u;return i.multiplyToRef(r,y),y.multiplyToRef(m,y),n.TransformCoordinates(t,y)},n.UnprojectFromTransform=function(t,r,o,e,s){var h=n._matrixCache?n._matrixCache:n._matrixCache=new u;e.multiplyToRef(s,h),h.invert(),t.x=t.x/r*2-1,t.y=-(t.y/o*2-1);var a=n.TransformCoordinates(t,h),m=t.x*h.m[3]+t.y*h.m[7]+t.z*h.m[11]+h.m[15];return i.WithinEpsilon(m,1)&&(a=a.scale(1/m)),a},n.Unproject=function(t,r,o,e,s,h){var a=n._matrixCache?n._matrixCache:n._matrixCache=new u;e.multiplyToRef(s,a),a.multiplyToRef(h,a),a.invert();var m=new n(t.x/r*2-1,-(t.y/o*2-1),t.z),y=n.TransformCoordinates(m,a),c=m.x*a.m[3]+m.y*a.m[7]+m.z*a.m[11]+a.m[15];return i.WithinEpsilon(c,1)&&(y=y.scale(1/c)),y},n.Minimize=function(t,i){var n=t.clone();return n.MinimizeInPlace(i),n},n.Maximize=function(t,i){var n=t.clone();return n.MaximizeInPlace(i),n},n.Distance=function(t,i){return Math.sqrt(n.DistanceSquared(t,i))},n.DistanceSquared=function(t,i){var n=t.x-i.x,r=t.y-i.y,o=t.z-i.z;return n*n+r*r+o*o},n.Center=function(t,i){var n=t.add(i);return n.scaleInPlace(.5),n},n.RotationFromAxis=function(t,i,r){var o=n.Zero();return n.RotationFromAxisToRef(t,i,r,o),o},n.RotationFromAxisToRef=function(r,o,e,s){var h=r.normalize(),a=e.normalize(),u=p.X,m=p.Y,y=0,c=0,f=0,l=0,x=0,z=0,w=0,v=-1,d=0,g=M.Vector3[0],T=0,R=M.Vector3[1];i.WithinEpsilon(a.z,0,t.Epsilon)?z=1:i.WithinEpsilon(a.x,0,t.Epsilon)?l=1:(w=a.z/a.x,l=-w*Math.sqrt(1/(1+w*w)),z=Math.sqrt(1/(1+w*w))),R.x=l,R.y=x,R.z=z,R.normalize(),n.CrossToRef(h,R,g),g.normalize(),n.Dot(a,g)<0&&(v=1),T=n.Dot(h,R),T=Math.min(1,Math.max(-1,T)),f=Math.acos(T)*v,n.Dot(R,u)<0&&(f=Math.PI+f,R=R.scaleInPlace(-1),d++);var _=M.Vector3[2],b=M.Vector3[3];l=0,x=0,z=0,v=-1,i.WithinEpsilon(a.z,0,t.Epsilon)?l=1:(w=R.z/R.x,l=-w*Math.sqrt(1/(1+w*w)),z=Math.sqrt(1/(1+w*w))),_.x=l,_.y=x,_.z=z,_.normalize(),n.CrossToRef(_,R,b),b.normalize(),n.CrossToRef(a,_,g),g.normalize(),n.Dot(R,g)<0&&(v=1),T=n.Dot(a,_),T=Math.min(1,Math.max(-1,T)),c=Math.acos(T)*v,n.Dot(b,m)<0&&(c=Math.PI+c,d++),v=-1,n.CrossToRef(u,R,g),g.normalize(),n.Dot(g,m)<0&&(v=1),T=n.Dot(R,u),T=Math.min(1,Math.max(-1,T)),y=-Math.acos(T)*v,0>T&&2>d&&(y=Math.PI+y),s.x=c,s.y=y,s.z=f},n}();t.Vector3=e;var s=function(){function n(t,i,n,r){this.x=t,this.y=i,this.z=n,this.w=r}return n.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\"W:\"+this.w+\"}\"},n.prototype.getClassName=function(){return\"Vector4\"},n.prototype.getHashCode=function(){var t=this.x||0;return t=397*t^(this.y||0),t=397*t^(this.z||0),t=397*t^(this.w||0)},n.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},n.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,t[i+2]=this.z,t[i+3]=this.w,this},n.prototype.addInPlace=function(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this.w+=t.w,this},n.prototype.add=function(t){return new n(this.x+t.x,this.y+t.y,this.z+t.z,this.w+t.w)},n.prototype.addToRef=function(t,i){return i.x=this.x+t.x,i.y=this.y+t.y,i.z=this.z+t.z,i.w=this.w+t.w,this},n.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this.w-=t.w,this},n.prototype.subtract=function(t){return new n(this.x-t.x,this.y-t.y,this.z-t.z,this.w-t.w)},n.prototype.subtractToRef=function(t,i){return i.x=this.x-t.x,i.y=this.y-t.y,i.z=this.z-t.z,i.w=this.w-t.w,this},n.prototype.subtractFromFloats=function(t,i,r,o){return new n(this.x-t,this.y-i,this.z-r,this.w-o)},n.prototype.subtractFromFloatsToRef=function(t,i,n,r,o){return o.x=this.x-t,o.y=this.y-i,o.z=this.z-n,o.w=this.w-r,this},n.prototype.negate=function(){return new n(-this.x,-this.y,-this.z,-this.w)},n.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this},n.prototype.scale=function(t){return new n(this.x*t,this.y*t,this.z*t,this.w*t)},n.prototype.scaleToRef=function(t,i){i.x=this.x*t,i.y=this.y*t,i.z=this.z*t,i.w=this.w*t},n.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z&&this.w===t.w},n.prototype.equalsWithEpsilon=function(n,r){return void 0===r&&(r=t.Epsilon),n&&i.WithinEpsilon(this.x,n.x,r)&&i.WithinEpsilon(this.y,n.y,r)&&i.WithinEpsilon(this.z,n.z,r)&&i.WithinEpsilon(this.w,n.w,r)},n.prototype.equalsToFloats=function(t,i,n,r){return this.x===t&&this.y===i&&this.z===n&&this.w===r},n.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this.w*=t.w,this},n.prototype.multiply=function(t){return new n(this.x*t.x,this.y*t.y,this.z*t.z,this.w*t.w)},n.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,i.z=this.z*t.z,i.w=this.w*t.w,this},n.prototype.multiplyByFloats=function(t,i,r,o){return new n(this.x*t,this.y*i,this.z*r,this.w*o)},n.prototype.divide=function(t){return new n(this.x/t.x,this.y/t.y,this.z/t.z,this.w/t.w)},n.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,i.z=this.z/t.z,i.w=this.w/t.w,this},n.prototype.MinimizeInPlace=function(t){return t.x<this.x&&(this.x=t.x),t.y<this.y&&(this.y=t.y),t.z<this.z&&(this.z=t.z),t.w<this.w&&(this.w=t.w),this},n.prototype.MaximizeInPlace=function(t){return t.x>this.x&&(this.x=t.x),t.y>this.y&&(this.y=t.y),t.z>this.z&&(this.z=t.z),t.w>this.w&&(this.w=t.w),this},n.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},n.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w},n.prototype.normalize=function(){var t=this.length();if(0===t)return this;var i=1/t;return this.x*=i,this.y*=i,this.z*=i,this.w*=i,this},n.prototype.toVector3=function(){return new e(this.x,this.y,this.z)},n.prototype.clone=function(){return new n(this.x,this.y,this.z,this.w)},n.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=t.w,this},n.prototype.copyFromFloats=function(t,i,n,r){return this.x=t,this.y=i,this.z=n,this.w=r,this},n.FromArray=function(t,i){return i||(i=0),new n(t[i],t[i+1],t[i+2],t[i+3])},n.FromArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1],n.z=t[i+2],n.w=t[i+3]},n.FromFloatArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1],n.z=t[i+2],n.w=t[i+3]},n.FromFloatsToRef=function(t,i,n,r,o){o.x=t,o.y=i,o.z=n,o.w=r},n.Zero=function(){return new n(0,0,0,0)},n.Normalize=function(t){var i=n.Zero();return n.NormalizeToRef(t,i),i},n.NormalizeToRef=function(t,i){i.copyFrom(t),i.normalize()},n.Minimize=function(t,i){var n=t.clone();return n.MinimizeInPlace(i),n},n.Maximize=function(t,i){var n=t.clone();return n.MaximizeInPlace(i),n},n.Distance=function(t,i){return Math.sqrt(n.DistanceSquared(t,i))},n.DistanceSquared=function(t,i){var n=t.x-i.x,r=t.y-i.y,o=t.z-i.z,e=t.w-i.w;return n*n+r*r+o*o+e*e},n.Center=function(t,i){var n=t.add(i);return n.scaleInPlace(.5),n},n}();t.Vector4=s;var h=function(){function t(t,i){this.width=t,this.height=i}return t.prototype.toString=function(){return\"{W: \"+this.width+\", H: \"+this.height+\"}\"},t.prototype.getClassName=function(){return\"Size\"},t.prototype.getHashCode=function(){var t=this.width||0;return t=397*t^(this.height||0)},t.prototype.copyFrom=function(t){this.width=t.width,this.height=t.height},t.prototype.copyFromFloats=function(t,i){this.width=t,this.height=i},t.prototype.multiplyByFloats=function(i,n){return new t(this.width*i,this.height*n)},t.prototype.clone=function(){return new t(this.width,this.height)},t.prototype.equals=function(t){return t?this.width===t.width&&this.height===t.height:!1},Object.defineProperty(t.prototype,\"surface\",{get:function(){return this.width*this.height},enumerable:!0,configurable:!0}),t.Zero=function(){return new t(0,0)},t.prototype.add=function(i){var n=new t(this.width+i.width,this.height+i.height);return n},t.prototype.substract=function(i){var n=new t(this.width-i.width,this.height-i.height);return n},t.Lerp=function(i,n,r){var o=i.width+(n.width-i.width)*r,e=i.height+(n.height-i.height)*r;return new t(o,e)},t}();t.Size=h;var a=function(){function t(t,i,n,r){void 0===t&&(t=0),void 0===i&&(i=0),void 0===n&&(n=0),void 0===r&&(r=1),this.x=t,this.y=i,this.z=n,this.w=r}return t.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\" W:\"+this.w+\"}\"},t.prototype.getClassName=function(){return\"Quaternion\"},t.prototype.getHashCode=function(){var t=this.x||0;return t=397*t^(this.y||0),t=397*t^(this.z||0),t=397*t^(this.w||0)},t.prototype.asArray=function(){return[this.x,this.y,this.z,this.w]},t.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z&&this.w===t.w},t.prototype.clone=function(){return new t(this.x,this.y,this.z,this.w)},t.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=t.w,this},t.prototype.copyFromFloats=function(t,i,n,r){return this.x=t,this.y=i,this.z=n,this.w=r,this},t.prototype.add=function(i){return new t(this.x+i.x,this.y+i.y,this.z+i.z,this.w+i.w)},t.prototype.subtract=function(i){return new t(this.x-i.x,this.y-i.y,this.z-i.z,this.w-i.w)},t.prototype.scale=function(i){return new t(this.x*i,this.y*i,this.z*i,this.w*i)},t.prototype.multiply=function(i){var n=new t(0,0,0,1);return this.multiplyToRef(i,n),n},t.prototype.multiplyToRef=function(t,i){var n=this.x*t.w+this.y*t.z-this.z*t.y+this.w*t.x,r=-this.x*t.z+this.y*t.w+this.z*t.x+this.w*t.y,o=this.x*t.y-this.y*t.x+this.z*t.w+this.w*t.z,e=-this.x*t.x-this.y*t.y-this.z*t.z+this.w*t.w;return i.copyFromFloats(n,r,o,e),this},t.prototype.multiplyInPlace=function(t){return this.multiplyToRef(t,this),this},t.prototype.conjugateToRef=function(t){return t.copyFromFloats(-this.x,-this.y,-this.z,this.w),this},t.prototype.conjugateInPlace=function(){return this.x*=-1,this.y*=-1,this.z*=-1,this},t.prototype.conjugate=function(){var i=new t(-this.x,-this.y,-this.z,this.w);return i},t.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},t.prototype.normalize=function(){var t=1/this.length();return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this},t.prototype.toEulerAngles=function(t){void 0===t&&(t=\"YZX\");var i=e.Zero();return this.toEulerAnglesToRef(i,t),i},t.prototype.toEulerAnglesToRef=function(t,i){void 0===i&&(i=\"YZX\");var n,r,o,e=this.x,s=this.y,h=this.z,a=this.w;switch(i){case\"YZX\":var u=e*s+h*a;if(u>.499&&(n=2*Math.atan2(e,a),r=Math.PI/2,o=0),-.499>u&&(n=-2*Math.atan2(e,a),r=-Math.PI/2,o=0),isNaN(n)){var m=e*e,y=s*s,c=h*h;n=Math.atan2(2*s*a-2*e*h,1-2*y-2*c),r=Math.asin(2*u),o=Math.atan2(2*e*a-2*s*h,1-2*m-2*c)}break;default:throw new Error(\"Euler order \"+i+\" not supported yet.\")}return t.y=n,t.z=r,t.x=o,this},t.prototype.toRotationMatrix=function(t){var i=this.x*this.x,n=this.y*this.y,r=this.z*this.z,o=this.x*this.y,e=this.z*this.w,s=this.z*this.x,h=this.y*this.w,a=this.y*this.z,u=this.x*this.w;return t.m[0]=1-2*(n+r),t.m[1]=2*(o+e),t.m[2]=2*(s-h),t.m[3]=0,t.m[4]=2*(o-e),t.m[5]=1-2*(r+i),t.m[6]=2*(a+u),t.m[7]=0,t.m[8]=2*(s+h),t.m[9]=2*(a-u),t.m[10]=1-2*(n+i),t.m[11]=0,t.m[12]=0,t.m[13]=0,t.m[14]=0,t.m[15]=1,this},t.prototype.fromRotationMatrix=function(i){return t.FromRotationMatrixToRef(i,this),this},t.FromRotationMatrix=function(i){var n=new t;return t.FromRotationMatrixToRef(i,n),n},t.FromRotationMatrixToRef=function(t,i){var n,r=t.m,o=r[0],e=r[4],s=r[8],h=r[1],a=r[5],u=r[9],m=r[2],y=r[6],c=r[10],p=o+a+c;p>0?(n=.5/Math.sqrt(p+1),i.w=.25/n,i.x=(y-u)*n,i.y=(s-m)*n,i.z=(h-e)*n):o>a&&o>c?(n=2*Math.sqrt(1+o-a-c),i.w=(y-u)/n,i.x=.25*n,i.y=(e+h)/n,i.z=(s+m)/n):a>c?(n=2*Math.sqrt(1+a-o-c),i.w=(s-m)/n,i.x=(e+h)/n,i.y=.25*n,i.z=(u+y)/n):(n=2*Math.sqrt(1+c-o-a),i.w=(h-e)/n,i.x=(s+m)/n,i.y=(u+y)/n,i.z=.25*n)},t.Inverse=function(i){return new t(-i.x,-i.y,-i.z,i.w)},t.Identity=function(){return new t(0,0,0,1)},t.RotationAxis=function(i,n){return t.RotationAxisToRef(i,n,new t)},t.RotationAxisToRef=function(t,i,n){var r=Math.sin(i/2);return t.normalize(),n.w=Math.cos(i/2),n.x=t.x*r,n.y=t.y*r,n.z=t.z*r,n},t.FromArray=function(i,n){return n||(n=0),new t(i[n],i[n+1],i[n+2],i[n+3])},t.RotationYawPitchRoll=function(i,n,r){var o=new t;return t.RotationYawPitchRollToRef(i,n,r,o),o},t.RotationYawPitchRollToRef=function(t,i,n,r){var o=.5*n,e=.5*i,s=.5*t,h=Math.sin(o),a=Math.cos(o),u=Math.sin(e),m=Math.cos(e),y=Math.sin(s),c=Math.cos(s);r.x=c*u*a+y*m*h,r.y=y*m*a-c*u*h,r.z=c*m*h-y*u*a,r.w=c*m*a+y*u*h},t.RotationAlphaBetaGamma=function(i,n,r){var o=new t;return t.RotationAlphaBetaGammaToRef(i,n,r,o),o},t.RotationAlphaBetaGammaToRef=function(t,i,n,r){var o=.5*(n+t),e=.5*(n-t),s=.5*i;r.x=Math.cos(e)*Math.sin(s),r.y=Math.sin(e)*Math.sin(s),r.z=Math.sin(o)*Math.cos(s),r.w=Math.cos(o)*Math.cos(s)},t.Slerp=function(i,n,r){var o,e,s=r,h=i.x*n.x+i.y*n.y+i.z*n.z+i.w*n.w,a=!1;if(0>h&&(a=!0,h=-h),h>.999999)e=1-s,o=a?-s:s;else{var u=Math.acos(h),m=1/Math.sin(u);e=Math.sin((1-s)*u)*m,o=a?-Math.sin(s*u)*m:Math.sin(s*u)*m}return new t(e*i.x+o*n.x,e*i.y+o*n.y,e*i.z+o*n.z,e*i.w+o*n.w)},t}();t.Quaternion=a;var u=function(){function t(){this.m=new Float32Array(16)}return t.prototype.isIdentity=function(){return 1!==this.m[0]||1!==this.m[5]||1!==this.m[10]||1!==this.m[15]?!1:0===this.m[1]&&0===this.m[2]&&0===this.m[3]&&0===this.m[4]&&0===this.m[6]&&0===this.m[7]&&0===this.m[8]&&0===this.m[9]&&0===this.m[11]&&0===this.m[12]&&0===this.m[13]&&0===this.m[14]},t.prototype.determinant=function(){var t=this.m[10]*this.m[15]-this.m[11]*this.m[14],i=this.m[9]*this.m[15]-this.m[11]*this.m[13],n=this.m[9]*this.m[14]-this.m[10]*this.m[13],r=this.m[8]*this.m[15]-this.m[11]*this.m[12],o=this.m[8]*this.m[14]-this.m[10]*this.m[12],e=this.m[8]*this.m[13]-this.m[9]*this.m[12];return this.m[0]*(this.m[5]*t-this.m[6]*i+this.m[7]*n)-this.m[1]*(this.m[4]*t-this.m[6]*r+this.m[7]*o)+this.m[2]*(this.m[4]*i-this.m[5]*r+this.m[7]*e)-this.m[3]*(this.m[4]*n-this.m[5]*o+this.m[6]*e)},t.prototype.toArray=function(){return this.m},t.prototype.asArray=function(){return this.toArray()},t.prototype.invert=function(){return this.invertToRef(this),this},t.prototype.reset=function(){for(var t=0;16>t;t++)this.m[t]=0;return this},t.prototype.add=function(i){var n=new t;return this.addToRef(i,n),n},t.prototype.addToRef=function(t,i){for(var n=0;16>n;n++)i.m[n]=this.m[n]+t.m[n];return this},t.prototype.addToSelf=function(t){for(var i=0;16>i;i++)this.m[i]+=t.m[i];return this},t.prototype.invertToRef=function(t){var i=this.m[0],n=this.m[1],r=this.m[2],o=this.m[3],e=this.m[4],s=this.m[5],h=this.m[6],a=this.m[7],u=this.m[8],m=this.m[9],y=this.m[10],c=this.m[11],p=this.m[12],f=this.m[13],l=this.m[14],x=this.m[15],z=y*x-c*l,w=m*x-c*f,v=m*l-y*f,d=u*x-c*p,g=u*l-y*p,T=u*f-m*p,R=s*z-h*w+a*v,_=-(e*z-h*d+a*g),M=e*w-s*d+a*T,b=-(e*v-s*g+h*T),F=1/(i*R+n*_+r*M+o*b),A=h*x-a*l,L=s*x-a*f,C=s*l-h*f,P=e*x-a*p,Z=e*l-h*p,S=e*f-s*p,I=h*c-a*y,q=s*c-a*m,H=s*y-h*m,N=e*c-a*u,V=e*y-h*u,D=e*m-s*u;return t.m[0]=R*F,t.m[4]=_*F,t.m[8]=M*F,t.m[12]=b*F,t.m[1]=-(n*z-r*w+o*v)*F,t.m[5]=(i*z-r*d+o*g)*F,t.m[9]=-(i*w-n*d+o*T)*F,t.m[13]=(i*v-n*g+r*T)*F,t.m[2]=(n*A-r*L+o*C)*F,t.m[6]=-(i*A-r*P+o*Z)*F,t.m[10]=(i*L-n*P+o*S)*F,t.m[14]=-(i*C-n*Z+r*S)*F,t.m[3]=-(n*I-r*q+o*H)*F,t.m[7]=(i*I-r*N+o*V)*F,t.m[11]=-(i*q-n*N+o*D)*F,t.m[15]=(i*H-n*V+r*D)*F,this},t.prototype.setTranslation=function(t){return this.m[12]=t.x,this.m[13]=t.y,this.m[14]=t.z,this},t.prototype.getTranslation=function(){return new e(this.m[12],this.m[13],this.m[14])},t.prototype.multiply=function(i){var n=new t;return this.multiplyToRef(i,n),n},t.prototype.copyFrom=function(t){for(var i=0;16>i;i++)this.m[i]=t.m[i];return this},t.prototype.copyToArray=function(t,i){void 0===i&&(i=0);for(var n=0;16>n;n++)t[i+n]=this.m[n];return this},t.prototype.multiplyToRef=function(t,i){return this.multiplyToArray(t,i.m,0),\nthis},t.prototype.multiplyToArray=function(t,i,n){var r=this.m[0],o=this.m[1],e=this.m[2],s=this.m[3],h=this.m[4],a=this.m[5],u=this.m[6],m=this.m[7],y=this.m[8],c=this.m[9],p=this.m[10],f=this.m[11],l=this.m[12],x=this.m[13],z=this.m[14],w=this.m[15],v=t.m[0],d=t.m[1],g=t.m[2],T=t.m[3],R=t.m[4],_=t.m[5],M=t.m[6],b=t.m[7],F=t.m[8],A=t.m[9],L=t.m[10],C=t.m[11],P=t.m[12],Z=t.m[13],S=t.m[14],I=t.m[15];return i[n]=r*v+o*R+e*F+s*P,i[n+1]=r*d+o*_+e*A+s*Z,i[n+2]=r*g+o*M+e*L+s*S,i[n+3]=r*T+o*b+e*C+s*I,i[n+4]=h*v+a*R+u*F+m*P,i[n+5]=h*d+a*_+u*A+m*Z,i[n+6]=h*g+a*M+u*L+m*S,i[n+7]=h*T+a*b+u*C+m*I,i[n+8]=y*v+c*R+p*F+f*P,i[n+9]=y*d+c*_+p*A+f*Z,i[n+10]=y*g+c*M+p*L+f*S,i[n+11]=y*T+c*b+p*C+f*I,i[n+12]=l*v+x*R+z*F+w*P,i[n+13]=l*d+x*_+z*A+w*Z,i[n+14]=l*g+x*M+z*L+w*S,i[n+15]=l*T+x*b+z*C+w*I,this},t.prototype.equals=function(t){return t&&this.m[0]===t.m[0]&&this.m[1]===t.m[1]&&this.m[2]===t.m[2]&&this.m[3]===t.m[3]&&this.m[4]===t.m[4]&&this.m[5]===t.m[5]&&this.m[6]===t.m[6]&&this.m[7]===t.m[7]&&this.m[8]===t.m[8]&&this.m[9]===t.m[9]&&this.m[10]===t.m[10]&&this.m[11]===t.m[11]&&this.m[12]===t.m[12]&&this.m[13]===t.m[13]&&this.m[14]===t.m[14]&&this.m[15]===t.m[15]},t.prototype.clone=function(){return t.FromValues(this.m[0],this.m[1],this.m[2],this.m[3],this.m[4],this.m[5],this.m[6],this.m[7],this.m[8],this.m[9],this.m[10],this.m[11],this.m[12],this.m[13],this.m[14],this.m[15])},t.prototype.getClassName=function(){return\"Matrix\"},t.prototype.getHashCode=function(){for(var t=this.m[0]||0,i=1;16>i;i++)t=397*t^(this.m[i]||0);return t},t.prototype.decompose=function(n,r,o){o.x=this.m[12],o.y=this.m[13],o.z=this.m[14];var e=i.Sign(this.m[0]*this.m[1]*this.m[2]*this.m[3])<0?-1:1,s=i.Sign(this.m[4]*this.m[5]*this.m[6]*this.m[7])<0?-1:1,h=i.Sign(this.m[8]*this.m[9]*this.m[10]*this.m[11])<0?-1:1;if(n.x=e*Math.sqrt(this.m[0]*this.m[0]+this.m[1]*this.m[1]+this.m[2]*this.m[2]),n.y=s*Math.sqrt(this.m[4]*this.m[4]+this.m[5]*this.m[5]+this.m[6]*this.m[6]),n.z=h*Math.sqrt(this.m[8]*this.m[8]+this.m[9]*this.m[9]+this.m[10]*this.m[10]),0===n.x||0===n.y||0===n.z)return r.x=0,r.y=0,r.z=0,r.w=1,!1;var u=t.FromValues(this.m[0]/n.x,this.m[1]/n.x,this.m[2]/n.x,0,this.m[4]/n.y,this.m[5]/n.y,this.m[6]/n.y,0,this.m[8]/n.z,this.m[9]/n.z,this.m[10]/n.z,0,0,0,0,1);return a.FromRotationMatrixToRef(u,r),!0},t.FromArray=function(i,n){var r=new t;return n||(n=0),t.FromArrayToRef(i,n,r),r},t.FromArrayToRef=function(t,i,n){for(var r=0;16>r;r++)n.m[r]=t[r+i]},t.FromFloat32ArrayToRefScaled=function(t,i,n,r){for(var o=0;16>o;o++)r.m[o]=t[o+i]*n},t.FromValuesToRef=function(t,i,n,r,o,e,s,h,a,u,m,y,c,p,f,l,x){x.m[0]=t,x.m[1]=i,x.m[2]=n,x.m[3]=r,x.m[4]=o,x.m[5]=e,x.m[6]=s,x.m[7]=h,x.m[8]=a,x.m[9]=u,x.m[10]=m,x.m[11]=y,x.m[12]=c,x.m[13]=p,x.m[14]=f,x.m[15]=l},t.prototype.getRow=function(t){if(0>t||t>3)return null;var i=4*t;return new s(this.m[i+0],this.m[i+1],this.m[i+2],this.m[i+3])},t.prototype.setRow=function(t,i){if(0>t||t>3)return this;var n=4*t;return this.m[n+0]=i.x,this.m[n+1]=i.y,this.m[n+2]=i.z,this.m[n+3]=i.w,this},t.FromValues=function(i,n,r,o,e,s,h,a,u,m,y,c,p,f,l,x){var z=new t;return z.m[0]=i,z.m[1]=n,z.m[2]=r,z.m[3]=o,z.m[4]=e,z.m[5]=s,z.m[6]=h,z.m[7]=a,z.m[8]=u,z.m[9]=m,z.m[10]=y,z.m[11]=c,z.m[12]=p,z.m[13]=f,z.m[14]=l,z.m[15]=x,z},t.Compose=function(i,n,r){var o=t.FromValues(i.x,0,0,0,0,i.y,0,0,0,0,i.z,0,0,0,0,1),e=t.Identity();return n.toRotationMatrix(e),o=o.multiply(e),o.setTranslation(r),o},t.Identity=function(){return t.FromValues(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1)},t.IdentityToRef=function(i){t.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1,i)},t.Zero=function(){return t.FromValues(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)},t.RotationX=function(i){var n=new t;return t.RotationXToRef(i,n),n},t.Invert=function(i){var n=new t;return i.invertToRef(n),n},t.RotationXToRef=function(t,i){var n=Math.sin(t),r=Math.cos(t);i.m[0]=1,i.m[15]=1,i.m[5]=r,i.m[10]=r,i.m[9]=-n,i.m[6]=n,i.m[1]=0,i.m[2]=0,i.m[3]=0,i.m[4]=0,i.m[7]=0,i.m[8]=0,i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0},t.RotationY=function(i){var n=new t;return t.RotationYToRef(i,n),n},t.RotationYToRef=function(t,i){var n=Math.sin(t),r=Math.cos(t);i.m[5]=1,i.m[15]=1,i.m[0]=r,i.m[2]=-n,i.m[8]=n,i.m[10]=r,i.m[1]=0,i.m[3]=0,i.m[4]=0,i.m[6]=0,i.m[7]=0,i.m[9]=0,i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0},t.RotationZ=function(i){var n=new t;return t.RotationZToRef(i,n),n},t.RotationZToRef=function(t,i){var n=Math.sin(t),r=Math.cos(t);i.m[10]=1,i.m[15]=1,i.m[0]=r,i.m[1]=n,i.m[4]=-n,i.m[5]=r,i.m[2]=0,i.m[3]=0,i.m[6]=0,i.m[7]=0,i.m[8]=0,i.m[9]=0,i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0},t.RotationAxis=function(i,n){var r=t.Zero();return t.RotationAxisToRef(i,n,r),r},t.RotationAxisToRef=function(t,i,n){var r=Math.sin(-i),o=Math.cos(-i),e=1-o;t.normalize(),n.m[0]=t.x*t.x*e+o,n.m[1]=t.x*t.y*e-t.z*r,n.m[2]=t.x*t.z*e+t.y*r,n.m[3]=0,n.m[4]=t.y*t.x*e+t.z*r,n.m[5]=t.y*t.y*e+o,n.m[6]=t.y*t.z*e-t.x*r,n.m[7]=0,n.m[8]=t.z*t.x*e-t.y*r,n.m[9]=t.z*t.y*e+t.x*r,n.m[10]=t.z*t.z*e+o,n.m[11]=0,n.m[15]=1},t.RotationYawPitchRoll=function(i,n,r){var o=new t;return t.RotationYawPitchRollToRef(i,n,r,o),o},t.RotationYawPitchRollToRef=function(t,i,n,r){a.RotationYawPitchRollToRef(t,i,n,this._tempQuaternion),this._tempQuaternion.toRotationMatrix(r)},t.Scaling=function(i,n,r){var o=t.Zero();return t.ScalingToRef(i,n,r,o),o},t.ScalingToRef=function(t,i,n,r){r.m[0]=t,r.m[1]=0,r.m[2]=0,r.m[3]=0,r.m[4]=0,r.m[5]=i,r.m[6]=0,r.m[7]=0,r.m[8]=0,r.m[9]=0,r.m[10]=n,r.m[11]=0,r.m[12]=0,r.m[13]=0,r.m[14]=0,r.m[15]=1},t.Translation=function(i,n,r){var o=t.Identity();return t.TranslationToRef(i,n,r,o),o},t.TranslationToRef=function(i,n,r,o){t.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,i,n,r,1,o)},t.Lerp=function(i,n,r){for(var o=t.Zero(),e=0;16>e;e++)o.m[e]=i.m[e]*(1-r)+n.m[e]*r;return o},t.DecomposeLerp=function(i,n,r){var o=new e(0,0,0),s=new a,h=new e(0,0,0);i.decompose(o,s,h);var u=new e(0,0,0),m=new a,y=new e(0,0,0);n.decompose(u,m,y);var c=e.Lerp(o,u,r),p=a.Slerp(s,m,r),f=e.Lerp(h,y,r);return t.Compose(c,p,f)},t.LookAtLH=function(i,n,r){var o=t.Zero();return t.LookAtLHToRef(i,n,r,o),o},t.LookAtLHToRef=function(i,n,r,o){n.subtractToRef(i,this._zAxis),this._zAxis.normalize(),e.CrossToRef(r,this._zAxis,this._xAxis),0===this._xAxis.lengthSquared()?this._xAxis.x=1:this._xAxis.normalize(),e.CrossToRef(this._zAxis,this._xAxis,this._yAxis),this._yAxis.normalize();var s=-e.Dot(this._xAxis,i),h=-e.Dot(this._yAxis,i),a=-e.Dot(this._zAxis,i);return t.FromValuesToRef(this._xAxis.x,this._yAxis.x,this._zAxis.x,0,this._xAxis.y,this._yAxis.y,this._zAxis.y,0,this._xAxis.z,this._yAxis.z,this._zAxis.z,0,s,h,a,1,o)},t.OrthoLH=function(i,n,r,o){var e=t.Zero();return t.OrthoLHToRef(i,n,r,o,e),e},t.OrthoLHToRef=function(i,n,r,o,e){var s=2/i,h=2/n,a=1/(o-r),u=r/(r-o);t.FromValuesToRef(s,0,0,0,0,h,0,0,0,0,a,0,0,0,u,1,e)},t.OrthoOffCenterLH=function(i,n,r,o,e,s){var h=t.Zero();return t.OrthoOffCenterLHToRef(i,n,r,o,e,s,h),h},t.OrthoOffCenterLHToRef=function(t,i,n,r,o,e,s){s.m[0]=2/(i-t),s.m[1]=s.m[2]=s.m[3]=0,s.m[5]=2/(r-n),s.m[4]=s.m[6]=s.m[7]=0,s.m[10]=-1/(o-e),s.m[8]=s.m[9]=s.m[11]=0,s.m[12]=(t+i)/(t-i),s.m[13]=(r+n)/(n-r),s.m[14]=o/(o-e),s.m[15]=1},t.PerspectiveLH=function(i,n,r,o){var e=t.Zero();return e.m[0]=2*r/i,e.m[1]=e.m[2]=e.m[3]=0,e.m[5]=2*r/n,e.m[4]=e.m[6]=e.m[7]=0,e.m[10]=-o/(r-o),e.m[8]=e.m[9]=0,e.m[11]=1,e.m[12]=e.m[13]=e.m[15]=0,e.m[14]=r*o/(r-o),e},t.PerspectiveFovLH=function(i,n,r,o){var e=t.Zero();return t.PerspectiveFovLHToRef(i,n,r,o,e),e},t.PerspectiveFovLHToRef=function(t,i,n,r,o,e){void 0===e&&(e=!0);var s=1/Math.tan(.5*t);e?o.m[0]=s/i:o.m[0]=s,o.m[1]=o.m[2]=o.m[3]=0,e?o.m[5]=s:o.m[5]=s*i,o.m[4]=o.m[6]=o.m[7]=0,o.m[8]=o.m[9]=0,o.m[10]=-r/(n-r),o.m[11]=1,o.m[12]=o.m[13]=o.m[15]=0,o.m[14]=n*r/(n-r)},t.GetFinalMatrix=function(i,n,r,o,e,s){var h=i.width,a=i.height,u=i.x,m=i.y,y=t.FromValues(h/2,0,0,0,0,-a/2,0,0,0,0,s-e,0,u+h/2,a/2+m,e,1);return n.multiply(r).multiply(o).multiply(y)},t.GetAsMatrix2x2=function(t){return new Float32Array([t.m[0],t.m[1],t.m[4],t.m[5]])},t.GetAsMatrix3x3=function(t){return new Float32Array([t.m[0],t.m[1],t.m[2],t.m[4],t.m[5],t.m[6],t.m[8],t.m[9],t.m[10]])},t.Transpose=function(i){var n=new t;return n.m[0]=i.m[0],n.m[1]=i.m[4],n.m[2]=i.m[8],n.m[3]=i.m[12],n.m[4]=i.m[1],n.m[5]=i.m[5],n.m[6]=i.m[9],n.m[7]=i.m[13],n.m[8]=i.m[2],n.m[9]=i.m[6],n.m[10]=i.m[10],n.m[11]=i.m[14],n.m[12]=i.m[3],n.m[13]=i.m[7],n.m[14]=i.m[11],n.m[15]=i.m[15],n},t.Reflection=function(i){var n=new t;return t.ReflectionToRef(i,n),n},t.ReflectionToRef=function(t,i){t.normalize();var n=t.normal.x,r=t.normal.y,o=t.normal.z,e=-2*n,s=-2*r,h=-2*o;i.m[0]=e*n+1,i.m[1]=s*n,i.m[2]=h*n,i.m[3]=0,i.m[4]=e*r,i.m[5]=s*r+1,i.m[6]=h*r,i.m[7]=0,i.m[8]=e*o,i.m[9]=s*o,i.m[10]=h*o+1,i.m[11]=0,i.m[12]=e*t.d,i.m[13]=s*t.d,i.m[14]=h*t.d,i.m[15]=1},t._tempQuaternion=new a,t._xAxis=e.Zero(),t._yAxis=e.Zero(),t._zAxis=e.Zero(),t}();t.Matrix=u;var m=function(){function t(t,i,n,r){this.normal=new e(t,i,n),this.d=r}return t.prototype.asArray=function(){return[this.normal.x,this.normal.y,this.normal.z,this.d]},t.prototype.clone=function(){return new t(this.normal.x,this.normal.y,this.normal.z,this.d)},t.prototype.getClassName=function(){return\"Plane\"},t.prototype.getHashCode=function(){var t=this.normal.getHashCode();return t=397*t^(this.d||0)},t.prototype.normalize=function(){var t=Math.sqrt(this.normal.x*this.normal.x+this.normal.y*this.normal.y+this.normal.z*this.normal.z),i=0;return 0!==t&&(i=1/t),this.normal.x*=i,this.normal.y*=i,this.normal.z*=i,this.d*=i,this},t.prototype.transform=function(i){var n=u.Transpose(i),r=this.normal.x,o=this.normal.y,e=this.normal.z,s=this.d,h=r*n.m[0]+o*n.m[1]+e*n.m[2]+s*n.m[3],a=r*n.m[4]+o*n.m[5]+e*n.m[6]+s*n.m[7],m=r*n.m[8]+o*n.m[9]+e*n.m[10]+s*n.m[11],y=r*n.m[12]+o*n.m[13]+e*n.m[14]+s*n.m[15];return new t(h,a,m,y)},t.prototype.dotCoordinate=function(t){return this.normal.x*t.x+this.normal.y*t.y+this.normal.z*t.z+this.d},t.prototype.copyFromPoints=function(t,i,n){var r,o=i.x-t.x,e=i.y-t.y,s=i.z-t.z,h=n.x-t.x,a=n.y-t.y,u=n.z-t.z,m=e*u-s*a,y=s*h-o*u,c=o*a-e*h,p=Math.sqrt(m*m+y*y+c*c);return r=0!==p?1/p:0,this.normal.x=m*r,this.normal.y=y*r,this.normal.z=c*r,this.d=-(this.normal.x*t.x+this.normal.y*t.y+this.normal.z*t.z),this},t.prototype.isFrontFacingTo=function(t,i){var n=e.Dot(this.normal,t);return i>=n},t.prototype.signedDistanceTo=function(t){return e.Dot(t,this.normal)+this.d},t.FromArray=function(i){return new t(i[0],i[1],i[2],i[3])},t.FromPoints=function(i,n,r){var o=new t(0,0,0,0);return o.copyFromPoints(i,n,r),o},t.FromPositionAndNormal=function(i,n){var r=new t(0,0,0,0);return n.normalize(),r.normal=n,r.d=-(n.x*i.x+n.y*i.y+n.z*i.z),r},t.SignedDistanceToPlaneFromPositionAndNormal=function(t,i,n){var r=-(i.x*t.x+i.y*t.y+i.z*t.z);return e.Dot(n,i)+r},t}();t.Plane=m;var y=function(){function t(t,i,n,r){this.x=t,this.y=i,this.width=n,this.height=r}return t.prototype.toGlobal=function(i,n){return new t(this.x*i,this.y*n,this.width*i,this.height*n)},t}();t.Viewport=y;var c=function(){function t(){}return t.GetPlanes=function(i){for(var n=[],r=0;6>r;r++)n.push(new m(0,0,0,0));return t.GetPlanesToRef(i,n),n},t.GetPlanesToRef=function(t,i){i[0].normal.x=t.m[3]+t.m[2],i[0].normal.y=t.m[7]+t.m[6],i[0].normal.z=t.m[11]+t.m[10],i[0].d=t.m[15]+t.m[14],i[0].normalize(),i[1].normal.x=t.m[3]-t.m[2],i[1].normal.y=t.m[7]-t.m[6],i[1].normal.z=t.m[11]-t.m[10],i[1].d=t.m[15]-t.m[14],i[1].normalize(),i[2].normal.x=t.m[3]+t.m[0],i[2].normal.y=t.m[7]+t.m[4],i[2].normal.z=t.m[11]+t.m[8],i[2].d=t.m[15]+t.m[12],i[2].normalize(),i[3].normal.x=t.m[3]-t.m[0],i[3].normal.y=t.m[7]-t.m[4],i[3].normal.z=t.m[11]-t.m[8],i[3].d=t.m[15]-t.m[12],i[3].normalize(),i[4].normal.x=t.m[3]-t.m[1],i[4].normal.y=t.m[7]-t.m[5],i[4].normal.z=t.m[11]-t.m[9],i[4].d=t.m[15]-t.m[13],i[4].normalize(),i[5].normal.x=t.m[3]+t.m[1],i[5].normal.y=t.m[7]+t.m[5],i[5].normal.z=t.m[11]+t.m[9],i[5].d=t.m[15]+t.m[13],i[5].normalize()},t}();t.Frustum=c,function(t){t[t.LOCAL=0]=\"LOCAL\",t[t.WORLD=1]=\"WORLD\"}(t.Space||(t.Space={}));var p=(t.Space,function(){function t(){}return t.X=new e(1,0,0),t.Y=new e(0,1,0),t.Z=new e(0,0,1),t}());t.Axis=p;var f=function(){function t(){}return t.interpolate=function(t,i,n,r,o){for(var e=1-3*r+3*i,s=3*r-6*i,h=3*i,a=t,u=0;5>u;u++){var m=a*a,y=m*a,c=e*y+s*m+h*a,p=1/(3*e*m+2*s*a+h);a-=(c-t)*p,a=Math.min(1,Math.max(0,a))}return 3*Math.pow(1-a,2)*a*n+3*(1-a)*Math.pow(a,2)*o+Math.pow(a,3)},t}();t.BezierCurve=f,function(t){t[t.CW=0]=\"CW\",t[t.CCW=1]=\"CCW\"}(t.Orientation||(t.Orientation={}));var l=t.Orientation,x=function(){function t(t){var i=this;this.degrees=function(){return 180*i._radians/Math.PI},this.radians=function(){return i._radians},this._radians=t,this._radians<0&&(this._radians+=2*Math.PI)}return t.BetweenTwoPoints=function(i,n){var r=n.subtract(i),o=Math.atan2(r.y,r.x);return new t(o)},t.FromRadians=function(i){return new t(i)},t.FromDegrees=function(i){return new t(i*Math.PI/180)},t}();t.Angle=x;var z=function(){function t(t,i,n){this.startPoint=t,this.midPoint=i,this.endPoint=n;var r=Math.pow(i.x,2)+Math.pow(i.y,2),e=(Math.pow(t.x,2)+Math.pow(t.y,2)-r)/2,s=(r-Math.pow(n.x,2)-Math.pow(n.y,2))/2,h=(t.x-i.x)*(i.y-n.y)-(i.x-n.x)*(t.y-i.y);this.centerPoint=new o((e*(i.y-n.y)-s*(t.y-i.y))/h,((t.x-i.x)*s-(i.x-n.x)*e)/h),this.radius=this.centerPoint.subtract(this.startPoint).length(),this.startAngle=x.BetweenTwoPoints(this.centerPoint,this.startPoint);var a=this.startAngle.degrees(),u=x.BetweenTwoPoints(this.centerPoint,this.midPoint).degrees(),m=x.BetweenTwoPoints(this.centerPoint,this.endPoint).degrees();u-a>180&&(u-=360),-180>u-a&&(u+=360),m-u>180&&(m-=360),-180>m-u&&(m+=360),this.orientation=0>u-a?l.CW:l.CCW,this.angle=x.FromDegrees(this.orientation===l.CW?a-m:m-a)}return t}();t.Arc2=z;var w=function(){function t(t,i){this._points=new Array,this._length=0,this.closed=!1,this._points.push(new o(t,i))}return t.prototype.addLineTo=function(t,i){if(closed)return this;var n=new o(t,i),r=this._points[this._points.length-1];return this._points.push(n),this._length+=n.subtract(r).length(),this},t.prototype.addArcTo=function(t,i,n,r,e){if(void 0===e&&(e=36),closed)return this;var s=this._points[this._points.length-1],h=new o(t,i),a=new o(n,r),u=new z(s,h,a),m=u.angle.radians()/e;u.orientation===l.CW&&(m*=-1);for(var y=u.startAngle.radians()+m,c=0;e>c;c++){var p=Math.cos(y)*u.radius+u.centerPoint.x,f=Math.sin(y)*u.radius+u.centerPoint.y;this.addLineTo(p,f),y+=m}return this},t.prototype.close=function(){return this.closed=!0,this},t.prototype.length=function(){var t=this._length;if(!this.closed){var i=this._points[this._points.length-1],n=this._points[0];t+=n.subtract(i).length()}return t},t.prototype.getPoints=function(){return this._points},t.prototype.getPointAtLengthPosition=function(t){if(0>t||t>1)return o.Zero();for(var i=t*this.length(),n=0,r=0;r<this._points.length;r++){var e=(r+1)%this._points.length,s=this._points[r],h=this._points[e],a=h.subtract(s),u=a.length()+n;if(i>=n&&u>=i){var m=a.normalize(),y=i-n;return new o(s.x+m.x*y,s.y+m.y*y)}n=u}return o.Zero()},t.StartingAt=function(i,n){return new t(i,n)},t}();t.Path2=w;var v=function(){function n(t,i,n){this.path=t,this._curve=new Array,this._distances=new Array,this._tangents=new Array,this._normals=new Array,this._binormals=new Array;for(var r=0;r<t.length;r++)this._curve[r]=t[r].clone();this._raw=n||!1,this._compute(i)}return n.prototype.getCurve=function(){return this._curve},n.prototype.getTangents=function(){return this._tangents},n.prototype.getNormals=function(){return this._normals},n.prototype.getBinormals=function(){return this._binormals},n.prototype.getDistances=function(){return this._distances},n.prototype.update=function(t,i){for(var n=0;n<t.length;n++)this._curve[n].x=t[n].x,this._curve[n].y=t[n].y,this._curve[n].z=t[n].z;return this._compute(i),this},n.prototype._compute=function(t){var i=this._curve.length;this._tangents[0]=this._getFirstNonNullVector(0),this._raw||this._tangents[0].normalize(),this._tangents[i-1]=this._curve[i-1].subtract(this._curve[i-2]),this._raw||this._tangents[i-1].normalize();var n=this._tangents[0],r=this._normalVector(this._curve[0],n,t);this._normals[0]=r,this._raw||this._normals[0].normalize(),this._binormals[0]=e.Cross(n,this._normals[0]),this._raw||this._binormals[0].normalize(),this._distances[0]=0;for(var o,s,h,a,u=1;i>u;u++)o=this._getLastNonNullVector(u),i-1>u&&(s=this._getFirstNonNullVector(u),this._tangents[u]=o.add(s),this._tangents[u].normalize()),this._distances[u]=this._distances[u-1]+o.length(),h=this._tangents[u],a=this._binormals[u-1],this._normals[u]=e.Cross(a,h),this._raw||this._normals[u].normalize(),this._binormals[u]=e.Cross(h,this._normals[u]),this._raw||this._binormals[u].normalize()},n.prototype._getFirstNonNullVector=function(t){for(var i=1,n=this._curve[t+i].subtract(this._curve[t]);0===n.length()&&t+i+1<this._curve.length;)i++,n=this._curve[t+i].subtract(this._curve[t]);return n},n.prototype._getLastNonNullVector=function(t){for(var i=1,n=this._curve[t].subtract(this._curve[t-i]);0===n.length()&&t>i+1;)i++,n=this._curve[t].subtract(this._curve[t-i]);return n},n.prototype._normalVector=function(n,r,o){var s,h=r.length();if(0===h&&(h=1),void 0===o||null===o){var a;i.WithinEpsilon(Math.abs(r.y)/h,1,t.Epsilon)?i.WithinEpsilon(Math.abs(r.x)/h,1,t.Epsilon)?i.WithinEpsilon(Math.abs(r.z)/h,1,t.Epsilon)||(a=new e(0,0,1)):a=new e(1,0,0):a=new e(0,-1,0),s=e.Cross(r,a)}else s=e.Cross(r,o),e.CrossToRef(s,r,s);return s.normalize(),s},n}();t.Path3D=v;var d=function(){function t(t){this._length=0,this._points=t,this._length=this._computeLength(t)}return t.CreateQuadraticBezier=function(i,n,r,o){o=o>2?o:3;for(var s=new Array,h=function(t,i,n,r){var o=(1-t)*(1-t)*i+2*t*(1-t)*n+t*t*r;return o},a=0;o>=a;a++)s.push(new e(h(a/o,i.x,n.x,r.x),h(a/o,i.y,n.y,r.y),h(a/o,i.z,n.z,r.z)));return new t(s)},t.CreateCubicBezier=function(i,n,r,o,s){s=s>3?s:4;for(var h=new Array,a=function(t,i,n,r,o){var e=(1-t)*(1-t)*(1-t)*i+3*t*(1-t)*(1-t)*n+3*t*t*(1-t)*r+t*t*t*o;return e},u=0;s>=u;u++)h.push(new e(a(u/s,i.x,n.x,r.x,o.x),a(u/s,i.y,n.y,r.y,o.y),a(u/s,i.z,n.z,r.z,o.z)));return new t(h)},t.CreateHermiteSpline=function(i,n,r,o,s){for(var h=new Array,a=1/s,u=0;s>=u;u++)h.push(e.Hermite(i,n,r,o,u*a));return new t(h)},t.prototype.getPoints=function(){return this._points},t.prototype.length=function(){return this._length},t.prototype[\"continue\"]=function(i){for(var n=this._points[this._points.length-1],r=this._points.slice(),o=i.getPoints(),e=1;e<o.length;e++)r.push(o[e].subtract(o[0]).add(n));var s=new t(r);return s},t.prototype._computeLength=function(t){for(var i=0,n=1;n<t.length;n++)i+=t[n].subtract(t[n-1]).length();return i},t}();t.Curve3=d;var g=function(){function t(){this.L00=e.Zero(),this.L1_1=e.Zero(),this.L10=e.Zero(),this.L11=e.Zero(),this.L2_2=e.Zero(),this.L2_1=e.Zero(),this.L20=e.Zero(),this.L21=e.Zero(),this.L22=e.Zero()}return t.prototype.addLight=function(t,i,n){var r=new e(i.r,i.g,i.b),o=r.scale(n);this.L00=this.L00.add(o.scale(.282095)),this.L1_1=this.L1_1.add(o.scale(.488603*t.y)),this.L10=this.L10.add(o.scale(.488603*t.z)),this.L11=this.L11.add(o.scale(.488603*t.x)),this.L2_2=this.L2_2.add(o.scale(1.092548*t.x*t.y)),this.L2_1=this.L2_1.add(o.scale(1.092548*t.y*t.z)),this.L21=this.L21.add(o.scale(1.092548*t.x*t.z)),this.L20=this.L20.add(o.scale(.315392*(3*t.z*t.z-1))),this.L22=this.L22.add(o.scale(.546274*(t.x*t.x-t.y*t.y)))},t.prototype.scale=function(t){this.L00=this.L00.scale(t),this.L1_1=this.L1_1.scale(t),this.L10=this.L10.scale(t),this.L11=this.L11.scale(t),this.L2_2=this.L2_2.scale(t),this.L2_1=this.L2_1.scale(t),this.L20=this.L20.scale(t),this.L21=this.L21.scale(t),this.L22=this.L22.scale(t)},t}();t.SphericalHarmonics=g;var T=function(){function t(){this.x=e.Zero(),this.y=e.Zero(),this.z=e.Zero(),this.xx=e.Zero(),this.yy=e.Zero(),this.zz=e.Zero(),this.xy=e.Zero(),this.yz=e.Zero(),this.zx=e.Zero()}return t.prototype.addAmbient=function(t){var i=new e(t.r,t.g,t.b);this.xx=this.xx.add(i),this.yy=this.yy.add(i),this.zz=this.zz.add(i)},t.getSphericalPolynomialFromHarmonics=function(i){var n=new t;return n.x=i.L11.scale(1.02333),n.y=i.L1_1.scale(1.02333),n.z=i.L10.scale(1.02333),n.xx=i.L00.scale(.886277).subtract(i.L20.scale(.247708)).add(i.L22.scale(.429043)),n.yy=i.L00.scale(.886277).subtract(i.L20.scale(.247708)).subtract(i.L22.scale(.429043)),n.zz=i.L00.scale(.886277).add(i.L20.scale(.495417)),n.yz=i.L2_1.scale(.858086),n.zx=i.L21.scale(.858086),n.xy=i.L2_2.scale(.858086),n},t}();t.SphericalPolynomial=T;var R=function(){function t(t,i){void 0===t&&(t=e.Zero()),void 0===i&&(i=e.Up()),this.position=t,this.normal=i}return t.prototype.clone=function(){return new t(this.position.clone(),this.normal.clone())},t}();t.PositionNormalVertex=R;var _=function(){function t(t,i,n){void 0===t&&(t=e.Zero()),void 0===i&&(i=e.Up()),void 0===n&&(n=o.Zero()),this.position=t,this.normal=i,this.uv=n}return t.prototype.clone=function(){return new t(this.position.clone(),this.normal.clone(),this.uv.clone())},t}();t.PositionNormalTextureVertex=_;var M=function(){function t(){}return t.Color3=[n.Black(),n.Black(),n.Black()],t.Vector2=[o.Zero(),o.Zero(),o.Zero()],t.Vector3=[e.Zero(),e.Zero(),e.Zero(),e.Zero(),e.Zero(),e.Zero(),e.Zero(),e.Zero(),e.Zero()],t.Vector4=[s.Zero(),s.Zero(),s.Zero()],t.Quaternion=[new a(0,0,0,0)],t.Matrix=[u.Zero(),u.Zero(),u.Zero(),u.Zero(),u.Zero(),u.Zero(),u.Zero(),u.Zero()],t}();t.Tmp=M}(BABYLON||(BABYLON={}));";
  61568. if (((typeof window != "undefined" && window.module) || (typeof module != "undefined")) && typeof module.exports != "undefined") {
  61569. module.exports = BABYLON;
  61570. };