babylon.max.js 3.2 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054370553705637057370583705937060370613706237063370643706537066370673706837069370703707137072370733707437075370763707737078370793708037081370823708337084370853708637087370883708937090370913709237093370943709537096370973709837099371003710137102371033710437105371063710737108371093711037111371123711337114371153711637117371183711937120371213712237123371243712537126371273712837129371303713137132371333713437135371363713737138371393714037141371423714337144371453714637147371483714937150371513715237153371543715537156371573715837159371603716137162371633716437165371663716737168371693717037171371723717337174371753717637177371783717937180371813718237183371843718537186371873718837189371903719137192371933719437195371963719737198371993720037201372023720337204372053720637207372083720937210372113721237213372143721537216372173721837219372203722137222372233722437225372263722737228372293723037231372323723337234372353723637237372383723937240372413724237243372443724537246372473724837249372503725137252372533725437255372563725737258372593726037261372623726337264372653726637267372683726937270372713727237273372743727537276372773727837279372803728137282372833728437285372863728737288372893729037291372923729337294372953729637297372983729937300373013730237303373043730537306373073730837309373103731137312373133731437315373163731737318373193732037321373223732337324373253732637327373283732937330373313733237333373343733537336373373733837339373403734137342373433734437345373463734737348373493735037351373523735337354373553735637357373583735937360373613736237363373643736537366373673736837369373703737137372373733737437375373763737737378373793738037381373823738337384373853738637387373883738937390373913739237393373943739537396373973739837399374003740137402374033740437405374063740737408374093741037411374123741337414374153741637417374183741937420374213742237423374243742537426374273742837429374303743137432374333743437435374363743737438374393744037441374423744337444374453744637447374483744937450374513745237453374543745537456374573745837459374603746137462374633746437465374663746737468374693747037471374723747337474374753747637477374783747937480374813748237483374843748537486374873748837489374903749137492374933749437495374963749737498374993750037501375023750337504375053750637507375083750937510375113751237513375143751537516375173751837519375203752137522375233752437525375263752737528375293753037531375323753337534375353753637537375383753937540375413754237543375443754537546375473754837549375503755137552375533755437555375563755737558375593756037561375623756337564375653756637567375683756937570375713757237573375743757537576375773757837579375803758137582375833758437585375863758737588375893759037591375923759337594375953759637597375983759937600376013760237603376043760537606376073760837609376103761137612376133761437615376163761737618376193762037621376223762337624376253762637627376283762937630376313763237633376343763537636376373763837639376403764137642376433764437645376463764737648376493765037651376523765337654376553765637657376583765937660376613766237663376643766537666376673766837669376703767137672376733767437675376763767737678376793768037681376823768337684376853768637687376883768937690376913769237693376943769537696376973769837699377003770137702377033770437705377063770737708377093771037711377123771337714377153771637717377183771937720377213772237723377243772537726377273772837729377303773137732377333773437735377363773737738377393774037741377423774337744377453774637747377483774937750377513775237753377543775537756377573775837759377603776137762377633776437765377663776737768377693777037771377723777337774377753777637777377783777937780377813778237783377843778537786377873778837789377903779137792377933779437795377963779737798377993780037801378023780337804378053780637807378083780937810378113781237813378143781537816378173781837819378203782137822378233782437825378263782737828378293783037831378323783337834378353783637837378383783937840378413784237843378443784537846378473784837849378503785137852378533785437855378563785737858378593786037861378623786337864378653786637867378683786937870378713787237873378743787537876378773787837879378803788137882378833788437885378863788737888378893789037891378923789337894378953789637897378983789937900379013790237903379043790537906379073790837909379103791137912379133791437915379163791737918379193792037921379223792337924379253792637927379283792937930379313793237933379343793537936379373793837939379403794137942379433794437945379463794737948379493795037951379523795337954379553795637957379583795937960379613796237963379643796537966379673796837969379703797137972379733797437975379763797737978379793798037981379823798337984379853798637987379883798937990379913799237993379943799537996379973799837999380003800138002380033800438005380063800738008380093801038011380123801338014380153801638017380183801938020380213802238023380243802538026380273802838029380303803138032380333803438035380363803738038380393804038041380423804338044380453804638047380483804938050380513805238053380543805538056380573805838059380603806138062380633806438065380663806738068380693807038071380723807338074380753807638077380783807938080380813808238083380843808538086380873808838089380903809138092380933809438095380963809738098380993810038101381023810338104381053810638107381083810938110381113811238113381143811538116381173811838119381203812138122381233812438125381263812738128381293813038131381323813338134381353813638137381383813938140381413814238143381443814538146381473814838149381503815138152381533815438155381563815738158381593816038161381623816338164381653816638167381683816938170381713817238173381743817538176381773817838179381803818138182381833818438185381863818738188381893819038191381923819338194381953819638197381983819938200382013820238203382043820538206382073820838209382103821138212382133821438215382163821738218382193822038221382223822338224382253822638227382283822938230382313823238233382343823538236382373823838239382403824138242382433824438245382463824738248382493825038251382523825338254382553825638257382583825938260382613826238263382643826538266382673826838269382703827138272382733827438275382763827738278382793828038281382823828338284382853828638287382883828938290382913829238293382943829538296382973829838299383003830138302383033830438305383063830738308383093831038311383123831338314383153831638317383183831938320383213832238323383243832538326383273832838329383303833138332383333833438335383363833738338383393834038341383423834338344383453834638347383483834938350383513835238353383543835538356383573835838359383603836138362383633836438365383663836738368383693837038371383723837338374383753837638377383783837938380383813838238383383843838538386383873838838389383903839138392383933839438395383963839738398383993840038401384023840338404384053840638407384083840938410384113841238413384143841538416384173841838419384203842138422384233842438425384263842738428384293843038431384323843338434384353843638437384383843938440384413844238443384443844538446384473844838449384503845138452384533845438455384563845738458384593846038461384623846338464384653846638467384683846938470384713847238473384743847538476384773847838479384803848138482384833848438485384863848738488384893849038491384923849338494384953849638497384983849938500385013850238503385043850538506385073850838509385103851138512385133851438515385163851738518385193852038521385223852338524385253852638527385283852938530385313853238533385343853538536385373853838539385403854138542385433854438545385463854738548385493855038551385523855338554385553855638557385583855938560385613856238563385643856538566385673856838569385703857138572385733857438575385763857738578385793858038581385823858338584385853858638587385883858938590385913859238593385943859538596385973859838599386003860138602386033860438605386063860738608386093861038611386123861338614386153861638617386183861938620386213862238623386243862538626386273862838629386303863138632386333863438635386363863738638386393864038641386423864338644386453864638647386483864938650386513865238653386543865538656386573865838659386603866138662386633866438665386663866738668386693867038671386723867338674386753867638677386783867938680386813868238683386843868538686386873868838689386903869138692386933869438695386963869738698386993870038701387023870338704387053870638707387083870938710387113871238713387143871538716387173871838719387203872138722387233872438725387263872738728387293873038731387323873338734387353873638737387383873938740387413874238743387443874538746387473874838749387503875138752387533875438755387563875738758387593876038761387623876338764387653876638767387683876938770387713877238773387743877538776387773877838779387803878138782387833878438785387863878738788387893879038791387923879338794387953879638797387983879938800388013880238803388043880538806388073880838809388103881138812388133881438815388163881738818388193882038821388223882338824388253882638827388283882938830388313883238833388343883538836388373883838839388403884138842388433884438845388463884738848388493885038851388523885338854388553885638857388583885938860388613886238863388643886538866388673886838869388703887138872388733887438875388763887738878388793888038881388823888338884388853888638887388883888938890388913889238893388943889538896388973889838899389003890138902389033890438905389063890738908389093891038911389123891338914389153891638917389183891938920389213892238923389243892538926389273892838929389303893138932389333893438935389363893738938389393894038941389423894338944389453894638947389483894938950389513895238953389543895538956389573895838959389603896138962389633896438965389663896738968389693897038971389723897338974389753897638977389783897938980389813898238983389843898538986389873898838989389903899138992389933899438995389963899738998389993900039001390023900339004390053900639007390083900939010390113901239013390143901539016390173901839019390203902139022390233902439025390263902739028390293903039031390323903339034390353903639037390383903939040390413904239043390443904539046390473904839049390503905139052390533905439055390563905739058390593906039061390623906339064390653906639067390683906939070390713907239073390743907539076390773907839079390803908139082390833908439085390863908739088390893909039091390923909339094390953909639097390983909939100391013910239103391043910539106391073910839109391103911139112391133911439115391163911739118391193912039121391223912339124391253912639127391283912939130391313913239133391343913539136391373913839139391403914139142391433914439145391463914739148391493915039151391523915339154391553915639157391583915939160391613916239163391643916539166391673916839169391703917139172391733917439175391763917739178391793918039181391823918339184391853918639187391883918939190391913919239193391943919539196391973919839199392003920139202392033920439205392063920739208392093921039211392123921339214392153921639217392183921939220392213922239223392243922539226392273922839229392303923139232392333923439235392363923739238392393924039241392423924339244392453924639247392483924939250392513925239253392543925539256392573925839259392603926139262392633926439265392663926739268392693927039271392723927339274392753927639277392783927939280392813928239283392843928539286392873928839289392903929139292392933929439295392963929739298392993930039301393023930339304393053930639307393083930939310393113931239313393143931539316393173931839319393203932139322393233932439325393263932739328393293933039331393323933339334393353933639337393383933939340393413934239343393443934539346393473934839349393503935139352393533935439355393563935739358393593936039361393623936339364393653936639367393683936939370393713937239373393743937539376393773937839379393803938139382393833938439385393863938739388393893939039391393923939339394393953939639397393983939939400394013940239403394043940539406394073940839409394103941139412394133941439415394163941739418394193942039421394223942339424394253942639427394283942939430394313943239433394343943539436394373943839439394403944139442394433944439445394463944739448394493945039451394523945339454394553945639457394583945939460394613946239463394643946539466394673946839469394703947139472394733947439475394763947739478394793948039481394823948339484394853948639487394883948939490394913949239493394943949539496394973949839499395003950139502395033950439505395063950739508395093951039511395123951339514395153951639517395183951939520395213952239523395243952539526395273952839529395303953139532395333953439535395363953739538395393954039541395423954339544395453954639547395483954939550395513955239553395543955539556395573955839559395603956139562395633956439565395663956739568395693957039571395723957339574395753957639577395783957939580395813958239583395843958539586395873958839589395903959139592395933959439595395963959739598395993960039601396023960339604396053960639607396083960939610396113961239613396143961539616396173961839619396203962139622396233962439625396263962739628396293963039631396323963339634396353963639637396383963939640396413964239643396443964539646396473964839649396503965139652396533965439655396563965739658396593966039661396623966339664396653966639667396683966939670396713967239673396743967539676396773967839679396803968139682396833968439685396863968739688396893969039691396923969339694396953969639697396983969939700397013970239703397043970539706397073970839709397103971139712397133971439715397163971739718397193972039721397223972339724397253972639727397283972939730397313973239733397343973539736397373973839739397403974139742397433974439745397463974739748397493975039751397523975339754397553975639757397583975939760397613976239763397643976539766397673976839769397703977139772397733977439775397763977739778397793978039781397823978339784397853978639787397883978939790397913979239793397943979539796397973979839799398003980139802398033980439805398063980739808398093981039811398123981339814398153981639817398183981939820398213982239823398243982539826398273982839829398303983139832398333983439835398363983739838398393984039841398423984339844398453984639847398483984939850398513985239853398543985539856398573985839859398603986139862398633986439865398663986739868398693987039871398723987339874398753987639877398783987939880398813988239883398843988539886398873988839889398903989139892398933989439895398963989739898398993990039901399023990339904399053990639907399083990939910399113991239913399143991539916399173991839919399203992139922399233992439925399263992739928399293993039931399323993339934399353993639937399383993939940399413994239943399443994539946399473994839949399503995139952399533995439955399563995739958399593996039961399623996339964399653996639967399683996939970399713997239973399743997539976399773997839979399803998139982399833998439985399863998739988399893999039991399923999339994399953999639997399983999940000400014000240003400044000540006400074000840009400104001140012400134001440015400164001740018400194002040021400224002340024400254002640027400284002940030400314003240033400344003540036400374003840039400404004140042400434004440045400464004740048400494005040051400524005340054400554005640057400584005940060400614006240063400644006540066400674006840069400704007140072400734007440075400764007740078400794008040081400824008340084400854008640087400884008940090400914009240093400944009540096400974009840099401004010140102401034010440105401064010740108401094011040111401124011340114401154011640117401184011940120401214012240123401244012540126401274012840129401304013140132401334013440135401364013740138401394014040141401424014340144401454014640147401484014940150401514015240153401544015540156401574015840159401604016140162401634016440165401664016740168401694017040171401724017340174401754017640177401784017940180401814018240183401844018540186401874018840189401904019140192401934019440195401964019740198401994020040201402024020340204402054020640207402084020940210402114021240213402144021540216402174021840219402204022140222402234022440225402264022740228402294023040231402324023340234402354023640237402384023940240402414024240243402444024540246402474024840249402504025140252402534025440255402564025740258402594026040261402624026340264402654026640267402684026940270402714027240273402744027540276402774027840279402804028140282402834028440285402864028740288402894029040291402924029340294402954029640297402984029940300403014030240303403044030540306403074030840309403104031140312403134031440315403164031740318403194032040321403224032340324403254032640327403284032940330403314033240333403344033540336403374033840339403404034140342403434034440345403464034740348403494035040351403524035340354403554035640357403584035940360403614036240363403644036540366403674036840369403704037140372403734037440375403764037740378403794038040381403824038340384403854038640387403884038940390403914039240393403944039540396403974039840399404004040140402404034040440405404064040740408404094041040411404124041340414404154041640417404184041940420404214042240423404244042540426404274042840429404304043140432404334043440435404364043740438404394044040441404424044340444404454044640447404484044940450404514045240453404544045540456404574045840459404604046140462404634046440465404664046740468404694047040471404724047340474404754047640477404784047940480404814048240483404844048540486404874048840489404904049140492404934049440495404964049740498404994050040501405024050340504405054050640507405084050940510405114051240513405144051540516405174051840519405204052140522405234052440525405264052740528405294053040531405324053340534405354053640537405384053940540405414054240543405444054540546405474054840549405504055140552405534055440555405564055740558405594056040561405624056340564405654056640567405684056940570405714057240573405744057540576405774057840579405804058140582405834058440585405864058740588405894059040591405924059340594405954059640597405984059940600406014060240603406044060540606406074060840609406104061140612406134061440615406164061740618406194062040621406224062340624406254062640627406284062940630406314063240633406344063540636406374063840639406404064140642406434064440645406464064740648406494065040651406524065340654406554065640657406584065940660406614066240663406644066540666406674066840669406704067140672406734067440675406764067740678406794068040681406824068340684406854068640687406884068940690406914069240693406944069540696406974069840699407004070140702407034070440705407064070740708407094071040711407124071340714407154071640717407184071940720407214072240723407244072540726407274072840729407304073140732407334073440735407364073740738407394074040741407424074340744407454074640747407484074940750407514075240753407544075540756407574075840759407604076140762407634076440765407664076740768407694077040771407724077340774407754077640777407784077940780407814078240783407844078540786407874078840789407904079140792407934079440795407964079740798407994080040801408024080340804408054080640807408084080940810408114081240813408144081540816408174081840819408204082140822408234082440825408264082740828408294083040831408324083340834408354083640837408384083940840408414084240843408444084540846408474084840849408504085140852408534085440855408564085740858408594086040861408624086340864408654086640867408684086940870408714087240873408744087540876408774087840879408804088140882408834088440885408864088740888408894089040891408924089340894408954089640897408984089940900409014090240903409044090540906409074090840909409104091140912409134091440915409164091740918409194092040921409224092340924409254092640927409284092940930409314093240933409344093540936409374093840939409404094140942409434094440945409464094740948409494095040951409524095340954409554095640957409584095940960409614096240963409644096540966409674096840969409704097140972409734097440975409764097740978409794098040981409824098340984409854098640987409884098940990409914099240993409944099540996409974099840999410004100141002410034100441005410064100741008410094101041011410124101341014410154101641017410184101941020410214102241023410244102541026410274102841029410304103141032410334103441035410364103741038410394104041041410424104341044410454104641047410484104941050410514105241053410544105541056410574105841059410604106141062410634106441065410664106741068410694107041071410724107341074410754107641077410784107941080410814108241083410844108541086410874108841089410904109141092410934109441095410964109741098410994110041101411024110341104411054110641107411084110941110411114111241113411144111541116411174111841119411204112141122411234112441125411264112741128411294113041131411324113341134411354113641137411384113941140411414114241143411444114541146411474114841149411504115141152411534115441155411564115741158411594116041161411624116341164411654116641167411684116941170411714117241173411744117541176411774117841179411804118141182411834118441185411864118741188411894119041191411924119341194411954119641197411984119941200412014120241203412044120541206412074120841209412104121141212412134121441215412164121741218412194122041221412224122341224412254122641227412284122941230412314123241233412344123541236412374123841239412404124141242412434124441245412464124741248412494125041251412524125341254412554125641257412584125941260412614126241263412644126541266412674126841269412704127141272412734127441275412764127741278412794128041281412824128341284412854128641287412884128941290412914129241293412944129541296412974129841299413004130141302413034130441305413064130741308413094131041311413124131341314413154131641317413184131941320413214132241323413244132541326413274132841329413304133141332413334133441335413364133741338413394134041341413424134341344413454134641347413484134941350413514135241353413544135541356413574135841359413604136141362413634136441365413664136741368413694137041371413724137341374413754137641377413784137941380413814138241383413844138541386413874138841389413904139141392413934139441395413964139741398413994140041401414024140341404414054140641407414084140941410414114141241413414144141541416414174141841419414204142141422414234142441425414264142741428414294143041431414324143341434414354143641437414384143941440414414144241443414444144541446414474144841449414504145141452414534145441455414564145741458414594146041461414624146341464414654146641467414684146941470414714147241473414744147541476414774147841479414804148141482414834148441485414864148741488414894149041491414924149341494414954149641497414984149941500415014150241503415044150541506415074150841509415104151141512415134151441515415164151741518415194152041521415224152341524415254152641527415284152941530415314153241533415344153541536415374153841539415404154141542415434154441545415464154741548415494155041551415524155341554415554155641557415584155941560415614156241563415644156541566415674156841569415704157141572415734157441575415764157741578415794158041581415824158341584415854158641587415884158941590415914159241593415944159541596415974159841599416004160141602416034160441605416064160741608416094161041611416124161341614416154161641617416184161941620416214162241623416244162541626416274162841629416304163141632416334163441635416364163741638416394164041641416424164341644416454164641647416484164941650416514165241653416544165541656416574165841659416604166141662416634166441665416664166741668416694167041671416724167341674416754167641677416784167941680416814168241683416844168541686416874168841689416904169141692416934169441695416964169741698416994170041701417024170341704417054170641707417084170941710417114171241713417144171541716417174171841719417204172141722417234172441725417264172741728417294173041731417324173341734417354173641737417384173941740417414174241743417444174541746417474174841749417504175141752417534175441755417564175741758417594176041761417624176341764417654176641767417684176941770417714177241773417744177541776417774177841779417804178141782417834178441785417864178741788417894179041791417924179341794417954179641797417984179941800418014180241803418044180541806418074180841809418104181141812418134181441815418164181741818418194182041821418224182341824418254182641827418284182941830418314183241833418344183541836418374183841839418404184141842418434184441845418464184741848418494185041851418524185341854418554185641857418584185941860418614186241863418644186541866418674186841869418704187141872418734187441875418764187741878418794188041881418824188341884418854188641887418884188941890418914189241893418944189541896418974189841899419004190141902419034190441905419064190741908419094191041911419124191341914419154191641917419184191941920419214192241923419244192541926419274192841929419304193141932419334193441935419364193741938419394194041941419424194341944419454194641947419484194941950419514195241953419544195541956419574195841959419604196141962419634196441965419664196741968419694197041971419724197341974419754197641977419784197941980419814198241983419844198541986419874198841989419904199141992419934199441995419964199741998419994200042001420024200342004420054200642007420084200942010420114201242013420144201542016420174201842019420204202142022420234202442025420264202742028420294203042031420324203342034420354203642037420384203942040420414204242043420444204542046420474204842049420504205142052420534205442055420564205742058420594206042061420624206342064420654206642067420684206942070420714207242073420744207542076420774207842079420804208142082420834208442085420864208742088420894209042091420924209342094420954209642097420984209942100421014210242103421044210542106421074210842109421104211142112421134211442115421164211742118421194212042121421224212342124421254212642127421284212942130421314213242133421344213542136421374213842139421404214142142421434214442145421464214742148421494215042151421524215342154421554215642157421584215942160421614216242163421644216542166421674216842169421704217142172421734217442175421764217742178421794218042181421824218342184421854218642187421884218942190421914219242193421944219542196421974219842199422004220142202422034220442205422064220742208422094221042211422124221342214422154221642217422184221942220422214222242223422244222542226422274222842229422304223142232422334223442235422364223742238422394224042241422424224342244422454224642247422484224942250422514225242253422544225542256422574225842259422604226142262422634226442265422664226742268422694227042271422724227342274422754227642277422784227942280422814228242283422844228542286422874228842289422904229142292422934229442295422964229742298422994230042301423024230342304423054230642307423084230942310423114231242313423144231542316423174231842319423204232142322423234232442325423264232742328423294233042331423324233342334423354233642337423384233942340423414234242343423444234542346423474234842349423504235142352423534235442355423564235742358423594236042361423624236342364423654236642367423684236942370423714237242373423744237542376423774237842379423804238142382423834238442385423864238742388423894239042391423924239342394423954239642397423984239942400424014240242403424044240542406424074240842409424104241142412424134241442415424164241742418424194242042421424224242342424424254242642427424284242942430424314243242433424344243542436424374243842439424404244142442424434244442445424464244742448424494245042451424524245342454424554245642457424584245942460424614246242463424644246542466424674246842469424704247142472424734247442475424764247742478424794248042481424824248342484424854248642487424884248942490424914249242493424944249542496424974249842499425004250142502425034250442505425064250742508425094251042511425124251342514425154251642517425184251942520425214252242523425244252542526425274252842529425304253142532425334253442535425364253742538425394254042541425424254342544425454254642547425484254942550425514255242553425544255542556425574255842559425604256142562425634256442565425664256742568425694257042571425724257342574425754257642577425784257942580425814258242583425844258542586425874258842589425904259142592425934259442595425964259742598425994260042601426024260342604426054260642607426084260942610426114261242613426144261542616426174261842619426204262142622426234262442625426264262742628426294263042631426324263342634426354263642637426384263942640426414264242643426444264542646426474264842649426504265142652426534265442655426564265742658426594266042661426624266342664426654266642667426684266942670426714267242673426744267542676426774267842679426804268142682426834268442685426864268742688426894269042691426924269342694426954269642697426984269942700427014270242703427044270542706427074270842709427104271142712427134271442715427164271742718427194272042721427224272342724427254272642727427284272942730427314273242733427344273542736427374273842739427404274142742427434274442745427464274742748427494275042751427524275342754427554275642757427584275942760427614276242763427644276542766427674276842769427704277142772427734277442775427764277742778427794278042781427824278342784427854278642787427884278942790427914279242793427944279542796427974279842799428004280142802428034280442805428064280742808428094281042811428124281342814428154281642817428184281942820428214282242823428244282542826428274282842829428304283142832428334283442835428364283742838428394284042841428424284342844428454284642847428484284942850428514285242853428544285542856428574285842859428604286142862428634286442865428664286742868428694287042871428724287342874428754287642877428784287942880428814288242883428844288542886428874288842889428904289142892428934289442895428964289742898428994290042901429024290342904429054290642907429084290942910429114291242913429144291542916429174291842919429204292142922429234292442925429264292742928429294293042931429324293342934429354293642937429384293942940429414294242943429444294542946429474294842949429504295142952429534295442955429564295742958429594296042961429624296342964429654296642967429684296942970429714297242973429744297542976429774297842979429804298142982429834298442985429864298742988429894299042991429924299342994429954299642997429984299943000430014300243003430044300543006430074300843009430104301143012430134301443015430164301743018430194302043021430224302343024430254302643027430284302943030430314303243033430344303543036430374303843039430404304143042430434304443045430464304743048430494305043051430524305343054430554305643057430584305943060430614306243063430644306543066430674306843069430704307143072430734307443075430764307743078430794308043081430824308343084430854308643087430884308943090430914309243093430944309543096430974309843099431004310143102431034310443105431064310743108431094311043111431124311343114431154311643117431184311943120431214312243123431244312543126431274312843129431304313143132431334313443135431364313743138431394314043141431424314343144431454314643147431484314943150431514315243153431544315543156431574315843159431604316143162431634316443165431664316743168431694317043171431724317343174431754317643177431784317943180431814318243183431844318543186431874318843189431904319143192431934319443195431964319743198431994320043201432024320343204432054320643207432084320943210432114321243213432144321543216432174321843219432204322143222432234322443225432264322743228432294323043231432324323343234432354323643237432384323943240432414324243243432444324543246432474324843249432504325143252432534325443255432564325743258432594326043261432624326343264432654326643267432684326943270432714327243273432744327543276432774327843279432804328143282432834328443285432864328743288432894329043291432924329343294432954329643297432984329943300433014330243303433044330543306433074330843309433104331143312433134331443315433164331743318433194332043321433224332343324433254332643327433284332943330433314333243333433344333543336433374333843339433404334143342433434334443345433464334743348433494335043351433524335343354433554335643357433584335943360433614336243363433644336543366433674336843369433704337143372433734337443375433764337743378433794338043381433824338343384433854338643387433884338943390433914339243393433944339543396433974339843399434004340143402434034340443405434064340743408434094341043411434124341343414434154341643417434184341943420434214342243423434244342543426434274342843429434304343143432434334343443435434364343743438434394344043441434424344343444434454344643447434484344943450434514345243453434544345543456434574345843459434604346143462434634346443465434664346743468434694347043471434724347343474434754347643477434784347943480434814348243483434844348543486434874348843489434904349143492434934349443495434964349743498434994350043501435024350343504435054350643507435084350943510435114351243513435144351543516435174351843519435204352143522435234352443525435264352743528435294353043531435324353343534435354353643537435384353943540435414354243543435444354543546435474354843549435504355143552435534355443555435564355743558435594356043561435624356343564435654356643567435684356943570435714357243573435744357543576435774357843579435804358143582435834358443585435864358743588435894359043591435924359343594435954359643597435984359943600436014360243603436044360543606436074360843609436104361143612436134361443615436164361743618436194362043621436224362343624436254362643627436284362943630436314363243633436344363543636436374363843639436404364143642436434364443645436464364743648436494365043651436524365343654436554365643657436584365943660436614366243663436644366543666436674366843669436704367143672436734367443675436764367743678436794368043681436824368343684436854368643687436884368943690436914369243693436944369543696436974369843699437004370143702437034370443705437064370743708437094371043711437124371343714437154371643717437184371943720437214372243723437244372543726437274372843729437304373143732437334373443735437364373743738437394374043741437424374343744437454374643747437484374943750437514375243753437544375543756437574375843759437604376143762437634376443765437664376743768437694377043771437724377343774437754377643777437784377943780437814378243783437844378543786437874378843789437904379143792437934379443795437964379743798437994380043801438024380343804438054380643807438084380943810438114381243813438144381543816438174381843819438204382143822438234382443825438264382743828438294383043831438324383343834438354383643837438384383943840438414384243843438444384543846438474384843849438504385143852438534385443855438564385743858438594386043861438624386343864438654386643867438684386943870438714387243873438744387543876438774387843879438804388143882438834388443885438864388743888438894389043891438924389343894438954389643897438984389943900439014390243903439044390543906439074390843909439104391143912439134391443915439164391743918439194392043921439224392343924439254392643927439284392943930439314393243933439344393543936439374393843939439404394143942439434394443945439464394743948439494395043951439524395343954439554395643957439584395943960439614396243963439644396543966439674396843969439704397143972439734397443975439764397743978439794398043981439824398343984439854398643987439884398943990439914399243993439944399543996439974399843999440004400144002440034400444005440064400744008440094401044011440124401344014440154401644017440184401944020440214402244023440244402544026440274402844029440304403144032440334403444035440364403744038440394404044041440424404344044440454404644047440484404944050440514405244053440544405544056440574405844059440604406144062440634406444065440664406744068440694407044071440724407344074440754407644077440784407944080440814408244083440844408544086440874408844089440904409144092440934409444095440964409744098440994410044101441024410344104441054410644107441084410944110441114411244113441144411544116441174411844119441204412144122441234412444125441264412744128441294413044131441324413344134441354413644137441384413944140441414414244143441444414544146441474414844149441504415144152441534415444155441564415744158441594416044161441624416344164441654416644167441684416944170441714417244173441744417544176441774417844179441804418144182441834418444185441864418744188441894419044191441924419344194441954419644197441984419944200442014420244203442044420544206442074420844209442104421144212442134421444215442164421744218442194422044221442224422344224442254422644227442284422944230442314423244233442344423544236442374423844239442404424144242442434424444245442464424744248442494425044251442524425344254442554425644257442584425944260442614426244263442644426544266442674426844269442704427144272442734427444275442764427744278442794428044281442824428344284442854428644287442884428944290442914429244293442944429544296442974429844299443004430144302443034430444305443064430744308443094431044311443124431344314443154431644317443184431944320443214432244323443244432544326443274432844329443304433144332443334433444335443364433744338443394434044341443424434344344443454434644347443484434944350443514435244353443544435544356443574435844359443604436144362443634436444365443664436744368443694437044371443724437344374443754437644377443784437944380443814438244383443844438544386443874438844389443904439144392443934439444395443964439744398443994440044401444024440344404444054440644407444084440944410444114441244413444144441544416444174441844419444204442144422444234442444425444264442744428444294443044431444324443344434444354443644437444384443944440444414444244443444444444544446444474444844449444504445144452444534445444455444564445744458444594446044461444624446344464444654446644467444684446944470444714447244473444744447544476444774447844479444804448144482444834448444485444864448744488444894449044491444924449344494444954449644497444984449944500445014450244503445044450544506445074450844509445104451144512445134451444515445164451744518445194452044521445224452344524445254452644527445284452944530445314453244533445344453544536445374453844539445404454144542445434454444545445464454744548445494455044551445524455344554445554455644557445584455944560445614456244563445644456544566445674456844569445704457144572445734457444575445764457744578445794458044581445824458344584445854458644587445884458944590445914459244593445944459544596445974459844599446004460144602446034460444605446064460744608446094461044611446124461344614446154461644617446184461944620446214462244623446244462544626446274462844629446304463144632446334463444635446364463744638446394464044641446424464344644446454464644647446484464944650446514465244653446544465544656446574465844659446604466144662446634466444665446664466744668446694467044671446724467344674446754467644677446784467944680446814468244683446844468544686446874468844689446904469144692446934469444695446964469744698446994470044701447024470344704447054470644707447084470944710447114471244713447144471544716447174471844719447204472144722447234472444725447264472744728447294473044731447324473344734447354473644737447384473944740447414474244743447444474544746447474474844749447504475144752447534475444755447564475744758447594476044761447624476344764447654476644767447684476944770447714477244773447744477544776447774477844779447804478144782447834478444785447864478744788447894479044791447924479344794447954479644797447984479944800448014480244803448044480544806448074480844809448104481144812448134481444815448164481744818448194482044821448224482344824448254482644827448284482944830448314483244833448344483544836448374483844839448404484144842448434484444845448464484744848448494485044851448524485344854448554485644857448584485944860448614486244863448644486544866448674486844869448704487144872448734487444875448764487744878448794488044881448824488344884448854488644887448884488944890448914489244893448944489544896448974489844899449004490144902449034490444905449064490744908449094491044911449124491344914449154491644917449184491944920449214492244923449244492544926449274492844929449304493144932449334493444935449364493744938449394494044941449424494344944449454494644947449484494944950449514495244953449544495544956449574495844959449604496144962449634496444965449664496744968449694497044971449724497344974449754497644977449784497944980449814498244983449844498544986449874498844989449904499144992449934499444995449964499744998449994500045001450024500345004450054500645007450084500945010450114501245013450144501545016450174501845019450204502145022450234502445025450264502745028450294503045031450324503345034450354503645037450384503945040450414504245043450444504545046450474504845049450504505145052450534505445055450564505745058450594506045061450624506345064450654506645067450684506945070450714507245073450744507545076450774507845079450804508145082450834508445085450864508745088450894509045091450924509345094450954509645097450984509945100451014510245103451044510545106451074510845109451104511145112451134511445115451164511745118451194512045121451224512345124451254512645127451284512945130451314513245133451344513545136451374513845139451404514145142451434514445145451464514745148451494515045151451524515345154451554515645157451584515945160451614516245163451644516545166451674516845169451704517145172451734517445175451764517745178451794518045181451824518345184451854518645187451884518945190451914519245193451944519545196451974519845199452004520145202452034520445205452064520745208452094521045211452124521345214452154521645217452184521945220452214522245223452244522545226452274522845229452304523145232452334523445235452364523745238452394524045241452424524345244452454524645247452484524945250452514525245253452544525545256452574525845259452604526145262452634526445265452664526745268452694527045271452724527345274452754527645277452784527945280452814528245283452844528545286452874528845289452904529145292452934529445295452964529745298452994530045301453024530345304453054530645307453084530945310453114531245313453144531545316453174531845319453204532145322453234532445325453264532745328453294533045331453324533345334453354533645337453384533945340453414534245343453444534545346453474534845349453504535145352453534535445355453564535745358453594536045361453624536345364453654536645367453684536945370453714537245373453744537545376453774537845379453804538145382453834538445385453864538745388453894539045391453924539345394453954539645397453984539945400454014540245403454044540545406454074540845409454104541145412454134541445415454164541745418454194542045421454224542345424454254542645427454284542945430454314543245433454344543545436454374543845439454404544145442454434544445445454464544745448454494545045451454524545345454454554545645457454584545945460454614546245463454644546545466454674546845469454704547145472454734547445475454764547745478454794548045481454824548345484454854548645487454884548945490454914549245493454944549545496454974549845499455004550145502455034550445505455064550745508455094551045511455124551345514455154551645517455184551945520455214552245523455244552545526455274552845529455304553145532455334553445535455364553745538455394554045541455424554345544455454554645547455484554945550455514555245553455544555545556455574555845559455604556145562455634556445565455664556745568455694557045571455724557345574455754557645577455784557945580455814558245583455844558545586455874558845589455904559145592455934559445595455964559745598455994560045601456024560345604456054560645607456084560945610456114561245613456144561545616456174561845619456204562145622456234562445625456264562745628456294563045631456324563345634456354563645637456384563945640456414564245643456444564545646456474564845649456504565145652456534565445655456564565745658456594566045661456624566345664456654566645667456684566945670456714567245673456744567545676456774567845679456804568145682456834568445685456864568745688456894569045691456924569345694456954569645697456984569945700457014570245703457044570545706457074570845709457104571145712457134571445715457164571745718457194572045721457224572345724457254572645727457284572945730457314573245733457344573545736457374573845739457404574145742457434574445745457464574745748457494575045751457524575345754457554575645757457584575945760457614576245763457644576545766457674576845769457704577145772457734577445775457764577745778457794578045781457824578345784457854578645787457884578945790457914579245793457944579545796457974579845799458004580145802458034580445805458064580745808458094581045811458124581345814458154581645817458184581945820458214582245823458244582545826458274582845829458304583145832458334583445835458364583745838458394584045841458424584345844458454584645847458484584945850458514585245853458544585545856458574585845859458604586145862458634586445865458664586745868458694587045871458724587345874458754587645877458784587945880458814588245883458844588545886458874588845889458904589145892458934589445895458964589745898458994590045901459024590345904459054590645907459084590945910459114591245913459144591545916459174591845919459204592145922459234592445925459264592745928459294593045931459324593345934459354593645937459384593945940459414594245943459444594545946459474594845949459504595145952459534595445955459564595745958459594596045961459624596345964459654596645967459684596945970459714597245973459744597545976459774597845979459804598145982459834598445985459864598745988459894599045991459924599345994459954599645997459984599946000460014600246003460044600546006460074600846009460104601146012460134601446015460164601746018460194602046021460224602346024460254602646027460284602946030460314603246033460344603546036460374603846039460404604146042460434604446045460464604746048460494605046051460524605346054460554605646057460584605946060460614606246063460644606546066460674606846069460704607146072460734607446075460764607746078460794608046081460824608346084460854608646087460884608946090460914609246093460944609546096460974609846099461004610146102461034610446105461064610746108461094611046111461124611346114461154611646117461184611946120461214612246123461244612546126461274612846129461304613146132461334613446135461364613746138461394614046141461424614346144461454614646147461484614946150461514615246153461544615546156461574615846159461604616146162461634616446165461664616746168461694617046171461724617346174461754617646177461784617946180461814618246183461844618546186461874618846189461904619146192461934619446195461964619746198461994620046201462024620346204462054620646207462084620946210462114621246213462144621546216462174621846219462204622146222462234622446225462264622746228462294623046231462324623346234462354623646237462384623946240462414624246243462444624546246462474624846249462504625146252462534625446255462564625746258462594626046261462624626346264462654626646267462684626946270462714627246273462744627546276462774627846279462804628146282462834628446285462864628746288462894629046291462924629346294462954629646297462984629946300463014630246303463044630546306463074630846309463104631146312463134631446315463164631746318463194632046321463224632346324463254632646327463284632946330463314633246333463344633546336463374633846339463404634146342463434634446345463464634746348463494635046351463524635346354463554635646357463584635946360463614636246363463644636546366463674636846369463704637146372463734637446375463764637746378463794638046381463824638346384463854638646387463884638946390463914639246393463944639546396463974639846399464004640146402464034640446405464064640746408464094641046411464124641346414464154641646417464184641946420464214642246423464244642546426464274642846429464304643146432464334643446435464364643746438464394644046441464424644346444464454644646447464484644946450464514645246453464544645546456464574645846459464604646146462464634646446465464664646746468464694647046471464724647346474464754647646477464784647946480464814648246483464844648546486464874648846489464904649146492464934649446495464964649746498464994650046501465024650346504465054650646507465084650946510465114651246513465144651546516465174651846519465204652146522465234652446525465264652746528465294653046531465324653346534465354653646537465384653946540465414654246543465444654546546465474654846549465504655146552465534655446555465564655746558465594656046561465624656346564465654656646567465684656946570465714657246573465744657546576465774657846579465804658146582465834658446585465864658746588465894659046591465924659346594465954659646597465984659946600466014660246603466044660546606466074660846609466104661146612466134661446615466164661746618466194662046621466224662346624466254662646627466284662946630466314663246633466344663546636466374663846639466404664146642466434664446645466464664746648466494665046651466524665346654466554665646657466584665946660466614666246663466644666546666466674666846669466704667146672466734667446675466764667746678466794668046681466824668346684466854668646687466884668946690466914669246693466944669546696466974669846699467004670146702467034670446705467064670746708467094671046711467124671346714467154671646717467184671946720467214672246723467244672546726467274672846729467304673146732467334673446735467364673746738467394674046741467424674346744467454674646747467484674946750467514675246753467544675546756467574675846759467604676146762467634676446765467664676746768467694677046771467724677346774467754677646777467784677946780467814678246783467844678546786467874678846789467904679146792467934679446795467964679746798467994680046801468024680346804468054680646807468084680946810468114681246813468144681546816468174681846819468204682146822468234682446825468264682746828468294683046831468324683346834468354683646837468384683946840468414684246843468444684546846468474684846849468504685146852468534685446855468564685746858468594686046861468624686346864468654686646867468684686946870468714687246873468744687546876468774687846879468804688146882468834688446885468864688746888468894689046891468924689346894468954689646897468984689946900469014690246903469044690546906469074690846909469104691146912469134691446915469164691746918469194692046921469224692346924469254692646927469284692946930469314693246933469344693546936469374693846939469404694146942469434694446945469464694746948469494695046951469524695346954469554695646957469584695946960469614696246963469644696546966469674696846969469704697146972469734697446975469764697746978469794698046981469824698346984469854698646987469884698946990469914699246993469944699546996469974699846999470004700147002470034700447005470064700747008470094701047011470124701347014470154701647017470184701947020470214702247023470244702547026470274702847029470304703147032470334703447035470364703747038470394704047041470424704347044470454704647047470484704947050470514705247053470544705547056470574705847059470604706147062470634706447065470664706747068470694707047071470724707347074470754707647077470784707947080470814708247083470844708547086470874708847089470904709147092470934709447095470964709747098470994710047101471024710347104471054710647107471084710947110471114711247113471144711547116471174711847119471204712147122471234712447125471264712747128471294713047131471324713347134471354713647137471384713947140471414714247143471444714547146471474714847149471504715147152471534715447155471564715747158471594716047161471624716347164471654716647167471684716947170471714717247173471744717547176471774717847179471804718147182471834718447185471864718747188471894719047191471924719347194471954719647197471984719947200472014720247203472044720547206472074720847209472104721147212472134721447215472164721747218472194722047221472224722347224472254722647227472284722947230472314723247233472344723547236472374723847239472404724147242472434724447245472464724747248472494725047251472524725347254472554725647257472584725947260472614726247263472644726547266472674726847269472704727147272472734727447275472764727747278472794728047281472824728347284472854728647287472884728947290472914729247293472944729547296472974729847299473004730147302473034730447305473064730747308473094731047311473124731347314473154731647317473184731947320473214732247323473244732547326473274732847329473304733147332473334733447335473364733747338473394734047341473424734347344473454734647347473484734947350473514735247353473544735547356473574735847359473604736147362473634736447365473664736747368473694737047371473724737347374473754737647377473784737947380473814738247383473844738547386473874738847389473904739147392473934739447395473964739747398473994740047401474024740347404474054740647407474084740947410474114741247413474144741547416474174741847419474204742147422474234742447425474264742747428474294743047431474324743347434474354743647437474384743947440474414744247443474444744547446474474744847449474504745147452474534745447455474564745747458474594746047461474624746347464474654746647467474684746947470474714747247473474744747547476474774747847479474804748147482474834748447485474864748747488474894749047491474924749347494474954749647497474984749947500475014750247503475044750547506475074750847509475104751147512475134751447515475164751747518475194752047521475224752347524475254752647527475284752947530475314753247533475344753547536475374753847539475404754147542475434754447545475464754747548475494755047551475524755347554475554755647557475584755947560475614756247563475644756547566475674756847569475704757147572475734757447575475764757747578475794758047581475824758347584475854758647587475884758947590475914759247593475944759547596475974759847599476004760147602476034760447605476064760747608476094761047611476124761347614476154761647617476184761947620476214762247623476244762547626476274762847629476304763147632476334763447635476364763747638476394764047641476424764347644476454764647647476484764947650476514765247653476544765547656476574765847659476604766147662476634766447665476664766747668476694767047671476724767347674476754767647677476784767947680476814768247683476844768547686476874768847689476904769147692476934769447695476964769747698476994770047701477024770347704477054770647707477084770947710477114771247713477144771547716477174771847719477204772147722477234772447725477264772747728477294773047731477324773347734477354773647737477384773947740477414774247743477444774547746477474774847749477504775147752477534775447755477564775747758477594776047761477624776347764477654776647767477684776947770477714777247773477744777547776477774777847779477804778147782477834778447785477864778747788477894779047791477924779347794477954779647797477984779947800478014780247803478044780547806478074780847809478104781147812478134781447815478164781747818478194782047821478224782347824478254782647827478284782947830478314783247833478344783547836478374783847839478404784147842478434784447845478464784747848478494785047851478524785347854478554785647857478584785947860478614786247863478644786547866478674786847869478704787147872478734787447875478764787747878478794788047881478824788347884478854788647887478884788947890478914789247893478944789547896478974789847899479004790147902479034790447905479064790747908479094791047911479124791347914479154791647917479184791947920479214792247923479244792547926479274792847929479304793147932479334793447935479364793747938479394794047941479424794347944479454794647947479484794947950479514795247953479544795547956479574795847959479604796147962479634796447965479664796747968479694797047971479724797347974479754797647977479784797947980479814798247983479844798547986479874798847989479904799147992479934799447995479964799747998479994800048001480024800348004480054800648007480084800948010480114801248013480144801548016480174801848019480204802148022480234802448025480264802748028480294803048031480324803348034480354803648037480384803948040480414804248043480444804548046480474804848049480504805148052480534805448055480564805748058480594806048061480624806348064480654806648067480684806948070480714807248073480744807548076480774807848079480804808148082480834808448085480864808748088480894809048091480924809348094480954809648097480984809948100481014810248103481044810548106481074810848109481104811148112481134811448115481164811748118481194812048121481224812348124481254812648127481284812948130481314813248133481344813548136481374813848139481404814148142481434814448145481464814748148481494815048151481524815348154481554815648157481584815948160481614816248163481644816548166481674816848169481704817148172481734817448175481764817748178481794818048181481824818348184481854818648187481884818948190481914819248193481944819548196481974819848199482004820148202482034820448205482064820748208482094821048211482124821348214482154821648217482184821948220482214822248223482244822548226482274822848229482304823148232482334823448235482364823748238482394824048241482424824348244482454824648247482484824948250482514825248253482544825548256482574825848259482604826148262482634826448265482664826748268482694827048271482724827348274482754827648277482784827948280482814828248283482844828548286482874828848289482904829148292482934829448295482964829748298482994830048301483024830348304483054830648307483084830948310483114831248313483144831548316483174831848319483204832148322483234832448325483264832748328483294833048331483324833348334483354833648337483384833948340483414834248343483444834548346483474834848349483504835148352483534835448355483564835748358483594836048361483624836348364483654836648367483684836948370483714837248373483744837548376483774837848379483804838148382483834838448385483864838748388483894839048391483924839348394483954839648397483984839948400484014840248403484044840548406484074840848409484104841148412484134841448415484164841748418484194842048421484224842348424484254842648427484284842948430484314843248433484344843548436484374843848439484404844148442484434844448445484464844748448484494845048451484524845348454484554845648457484584845948460484614846248463484644846548466484674846848469484704847148472484734847448475484764847748478484794848048481484824848348484484854848648487484884848948490484914849248493484944849548496484974849848499485004850148502485034850448505485064850748508485094851048511485124851348514485154851648517485184851948520485214852248523485244852548526485274852848529485304853148532485334853448535485364853748538485394854048541485424854348544485454854648547485484854948550485514855248553485544855548556485574855848559485604856148562485634856448565485664856748568485694857048571485724857348574485754857648577485784857948580485814858248583485844858548586485874858848589485904859148592485934859448595485964859748598485994860048601486024860348604486054860648607486084860948610486114861248613486144861548616486174861848619486204862148622486234862448625486264862748628486294863048631486324863348634486354863648637486384863948640486414864248643486444864548646486474864848649486504865148652486534865448655486564865748658486594866048661486624866348664486654866648667486684866948670486714867248673486744867548676486774867848679486804868148682486834868448685486864868748688486894869048691486924869348694486954869648697486984869948700487014870248703487044870548706487074870848709487104871148712487134871448715487164871748718487194872048721487224872348724487254872648727487284872948730487314873248733487344873548736487374873848739487404874148742487434874448745487464874748748487494875048751487524875348754487554875648757487584875948760487614876248763487644876548766487674876848769487704877148772487734877448775487764877748778487794878048781487824878348784487854878648787487884878948790487914879248793487944879548796487974879848799488004880148802488034880448805488064880748808488094881048811488124881348814488154881648817488184881948820488214882248823488244882548826488274882848829488304883148832488334883448835488364883748838488394884048841488424884348844488454884648847488484884948850488514885248853488544885548856488574885848859488604886148862488634886448865488664886748868488694887048871488724887348874488754887648877488784887948880488814888248883488844888548886488874888848889488904889148892488934889448895488964889748898488994890048901489024890348904489054890648907489084890948910489114891248913489144891548916489174891848919489204892148922489234892448925489264892748928489294893048931489324893348934489354893648937489384893948940489414894248943489444894548946489474894848949489504895148952489534895448955489564895748958489594896048961489624896348964489654896648967489684896948970489714897248973489744897548976489774897848979489804898148982489834898448985489864898748988489894899048991489924899348994489954899648997489984899949000490014900249003490044900549006490074900849009490104901149012490134901449015490164901749018490194902049021490224902349024490254902649027490284902949030490314903249033490344903549036490374903849039490404904149042490434904449045490464904749048490494905049051490524905349054490554905649057490584905949060490614906249063490644906549066490674906849069490704907149072490734907449075490764907749078490794908049081490824908349084490854908649087490884908949090490914909249093490944909549096490974909849099491004910149102491034910449105491064910749108491094911049111491124911349114491154911649117491184911949120491214912249123491244912549126491274912849129491304913149132491334913449135491364913749138491394914049141491424914349144491454914649147491484914949150491514915249153491544915549156491574915849159491604916149162491634916449165491664916749168491694917049171491724917349174491754917649177491784917949180491814918249183491844918549186491874918849189491904919149192491934919449195491964919749198491994920049201492024920349204492054920649207492084920949210492114921249213492144921549216492174921849219492204922149222492234922449225492264922749228492294923049231492324923349234492354923649237492384923949240492414924249243492444924549246492474924849249492504925149252492534925449255492564925749258492594926049261492624926349264492654926649267492684926949270492714927249273492744927549276492774927849279492804928149282492834928449285492864928749288492894929049291492924929349294492954929649297492984929949300493014930249303493044930549306493074930849309493104931149312493134931449315493164931749318493194932049321493224932349324493254932649327493284932949330493314933249333493344933549336493374933849339493404934149342493434934449345493464934749348493494935049351493524935349354493554935649357493584935949360493614936249363493644936549366493674936849369493704937149372493734937449375493764937749378493794938049381493824938349384493854938649387493884938949390493914939249393493944939549396493974939849399494004940149402494034940449405494064940749408494094941049411494124941349414494154941649417494184941949420494214942249423494244942549426494274942849429494304943149432494334943449435494364943749438494394944049441494424944349444494454944649447494484944949450494514945249453494544945549456494574945849459494604946149462494634946449465494664946749468494694947049471494724947349474494754947649477494784947949480494814948249483494844948549486494874948849489494904949149492494934949449495494964949749498494994950049501495024950349504495054950649507495084950949510495114951249513495144951549516495174951849519495204952149522495234952449525495264952749528495294953049531495324953349534495354953649537495384953949540495414954249543495444954549546495474954849549495504955149552495534955449555495564955749558495594956049561495624956349564495654956649567495684956949570495714957249573495744957549576495774957849579495804958149582495834958449585495864958749588495894959049591495924959349594495954959649597495984959949600496014960249603496044960549606496074960849609496104961149612496134961449615496164961749618496194962049621496224962349624496254962649627496284962949630496314963249633496344963549636496374963849639496404964149642496434964449645496464964749648496494965049651496524965349654496554965649657496584965949660496614966249663496644966549666496674966849669496704967149672496734967449675496764967749678496794968049681496824968349684496854968649687496884968949690496914969249693496944969549696496974969849699497004970149702497034970449705497064970749708497094971049711497124971349714497154971649717497184971949720497214972249723497244972549726497274972849729497304973149732497334973449735497364973749738497394974049741497424974349744497454974649747497484974949750497514975249753497544975549756497574975849759497604976149762497634976449765497664976749768497694977049771497724977349774497754977649777497784977949780497814978249783497844978549786497874978849789497904979149792497934979449795497964979749798497994980049801498024980349804498054980649807498084980949810498114981249813498144981549816498174981849819498204982149822498234982449825498264982749828498294983049831498324983349834498354983649837498384983949840498414984249843498444984549846498474984849849498504985149852498534985449855498564985749858498594986049861498624986349864498654986649867498684986949870498714987249873498744987549876498774987849879498804988149882498834988449885498864988749888498894989049891498924989349894498954989649897498984989949900499014990249903499044990549906499074990849909499104991149912499134991449915499164991749918499194992049921499224992349924499254992649927499284992949930499314993249933499344993549936499374993849939499404994149942499434994449945499464994749948499494995049951499524995349954499554995649957499584995949960499614996249963499644996549966499674996849969499704997149972499734997449975499764997749978499794998049981499824998349984499854998649987499884998949990499914999249993499944999549996499974999849999500005000150002500035000450005500065000750008500095001050011500125001350014500155001650017500185001950020500215002250023500245002550026500275002850029500305003150032500335003450035500365003750038500395004050041500425004350044500455004650047500485004950050500515005250053500545005550056500575005850059500605006150062500635006450065500665006750068500695007050071500725007350074500755007650077500785007950080500815008250083500845008550086500875008850089500905009150092500935009450095500965009750098500995010050101501025010350104501055010650107501085010950110501115011250113501145011550116501175011850119501205012150122501235012450125501265012750128501295013050131501325013350134501355013650137501385013950140501415014250143501445014550146501475014850149501505015150152501535015450155501565015750158501595016050161501625016350164501655016650167501685016950170501715017250173501745017550176501775017850179501805018150182501835018450185501865018750188501895019050191501925019350194501955019650197501985019950200502015020250203502045020550206502075020850209502105021150212502135021450215502165021750218502195022050221502225022350224502255022650227502285022950230502315023250233502345023550236502375023850239502405024150242502435024450245502465024750248502495025050251502525025350254502555025650257502585025950260502615026250263502645026550266502675026850269502705027150272502735027450275502765027750278502795028050281502825028350284502855028650287502885028950290502915029250293502945029550296502975029850299503005030150302503035030450305503065030750308503095031050311503125031350314503155031650317503185031950320503215032250323503245032550326503275032850329503305033150332503335033450335503365033750338503395034050341503425034350344503455034650347503485034950350503515035250353503545035550356503575035850359503605036150362503635036450365503665036750368503695037050371503725037350374503755037650377503785037950380503815038250383503845038550386503875038850389503905039150392503935039450395503965039750398503995040050401504025040350404504055040650407504085040950410504115041250413504145041550416504175041850419504205042150422504235042450425504265042750428504295043050431504325043350434504355043650437504385043950440504415044250443504445044550446504475044850449504505045150452504535045450455504565045750458504595046050461504625046350464504655046650467504685046950470504715047250473504745047550476504775047850479504805048150482504835048450485504865048750488504895049050491504925049350494504955049650497504985049950500505015050250503505045050550506505075050850509505105051150512505135051450515505165051750518505195052050521505225052350524505255052650527505285052950530505315053250533505345053550536505375053850539505405054150542505435054450545505465054750548505495055050551505525055350554505555055650557505585055950560505615056250563505645056550566505675056850569505705057150572505735057450575505765057750578505795058050581505825058350584505855058650587505885058950590505915059250593505945059550596505975059850599506005060150602506035060450605506065060750608506095061050611506125061350614506155061650617506185061950620506215062250623506245062550626506275062850629506305063150632506335063450635506365063750638506395064050641506425064350644506455064650647506485064950650506515065250653506545065550656506575065850659506605066150662506635066450665506665066750668506695067050671506725067350674506755067650677506785067950680506815068250683506845068550686506875068850689506905069150692506935069450695506965069750698506995070050701507025070350704507055070650707507085070950710507115071250713507145071550716507175071850719507205072150722507235072450725507265072750728507295073050731507325073350734507355073650737507385073950740507415074250743507445074550746507475074850749507505075150752507535075450755507565075750758507595076050761507625076350764507655076650767507685076950770507715077250773507745077550776507775077850779507805078150782507835078450785507865078750788507895079050791507925079350794507955079650797507985079950800508015080250803508045080550806508075080850809508105081150812508135081450815508165081750818508195082050821508225082350824508255082650827508285082950830508315083250833508345083550836508375083850839508405084150842508435084450845508465084750848508495085050851508525085350854508555085650857508585085950860508615086250863508645086550866508675086850869508705087150872508735087450875508765087750878508795088050881508825088350884508855088650887508885088950890508915089250893508945089550896508975089850899509005090150902509035090450905509065090750908509095091050911509125091350914509155091650917509185091950920509215092250923509245092550926509275092850929509305093150932509335093450935509365093750938509395094050941509425094350944509455094650947509485094950950509515095250953509545095550956509575095850959509605096150962509635096450965509665096750968509695097050971509725097350974509755097650977509785097950980509815098250983509845098550986509875098850989509905099150992509935099450995509965099750998509995100051001510025100351004510055100651007510085100951010510115101251013510145101551016510175101851019510205102151022510235102451025510265102751028510295103051031510325103351034510355103651037510385103951040510415104251043510445104551046510475104851049510505105151052510535105451055510565105751058510595106051061510625106351064510655106651067510685106951070510715107251073510745107551076510775107851079510805108151082510835108451085510865108751088510895109051091510925109351094510955109651097510985109951100511015110251103511045110551106511075110851109511105111151112511135111451115511165111751118511195112051121511225112351124511255112651127511285112951130511315113251133511345113551136511375113851139511405114151142511435114451145511465114751148511495115051151511525115351154511555115651157511585115951160511615116251163511645116551166511675116851169511705117151172511735117451175511765117751178511795118051181511825118351184511855118651187511885118951190511915119251193511945119551196511975119851199512005120151202512035120451205512065120751208512095121051211512125121351214512155121651217512185121951220512215122251223512245122551226512275122851229512305123151232512335123451235512365123751238512395124051241512425124351244512455124651247512485124951250512515125251253512545125551256512575125851259512605126151262512635126451265512665126751268512695127051271512725127351274512755127651277512785127951280512815128251283512845128551286512875128851289512905129151292512935129451295512965129751298512995130051301513025130351304513055130651307513085130951310513115131251313513145131551316513175131851319513205132151322513235132451325513265132751328513295133051331513325133351334513355133651337513385133951340513415134251343513445134551346513475134851349513505135151352513535135451355513565135751358513595136051361513625136351364513655136651367513685136951370513715137251373513745137551376513775137851379513805138151382513835138451385513865138751388513895139051391513925139351394513955139651397513985139951400514015140251403514045140551406514075140851409514105141151412514135141451415514165141751418514195142051421514225142351424514255142651427514285142951430514315143251433514345143551436514375143851439514405144151442514435144451445514465144751448514495145051451514525145351454514555145651457514585145951460514615146251463514645146551466514675146851469514705147151472514735147451475514765147751478514795148051481514825148351484514855148651487514885148951490514915149251493514945149551496514975149851499515005150151502515035150451505515065150751508515095151051511515125151351514515155151651517515185151951520515215152251523515245152551526515275152851529515305153151532515335153451535515365153751538515395154051541515425154351544515455154651547515485154951550515515155251553515545155551556515575155851559515605156151562515635156451565515665156751568515695157051571515725157351574515755157651577515785157951580515815158251583515845158551586515875158851589515905159151592515935159451595515965159751598515995160051601516025160351604516055160651607516085160951610516115161251613516145161551616516175161851619516205162151622516235162451625516265162751628516295163051631516325163351634516355163651637516385163951640516415164251643516445164551646516475164851649516505165151652516535165451655516565165751658516595166051661516625166351664516655166651667516685166951670516715167251673516745167551676516775167851679516805168151682516835168451685516865168751688516895169051691516925169351694516955169651697516985169951700517015170251703517045170551706517075170851709517105171151712517135171451715517165171751718517195172051721517225172351724517255172651727517285172951730517315173251733517345173551736517375173851739517405174151742517435174451745517465174751748517495175051751517525175351754517555175651757517585175951760517615176251763517645176551766517675176851769517705177151772517735177451775517765177751778517795178051781517825178351784517855178651787517885178951790517915179251793517945179551796517975179851799518005180151802518035180451805518065180751808518095181051811518125181351814518155181651817518185181951820518215182251823518245182551826518275182851829518305183151832518335183451835518365183751838518395184051841518425184351844518455184651847518485184951850518515185251853518545185551856518575185851859518605186151862518635186451865518665186751868518695187051871518725187351874518755187651877518785187951880518815188251883518845188551886518875188851889518905189151892518935189451895518965189751898518995190051901519025190351904519055190651907519085190951910519115191251913519145191551916519175191851919519205192151922519235192451925519265192751928519295193051931519325193351934519355193651937519385193951940519415194251943519445194551946519475194851949519505195151952519535195451955519565195751958519595196051961519625196351964519655196651967519685196951970519715197251973519745197551976519775197851979519805198151982519835198451985519865198751988519895199051991519925199351994519955199651997519985199952000520015200252003520045200552006520075200852009520105201152012520135201452015520165201752018520195202052021520225202352024520255202652027520285202952030520315203252033520345203552036520375203852039520405204152042520435204452045520465204752048520495205052051520525205352054520555205652057520585205952060520615206252063520645206552066520675206852069520705207152072520735207452075520765207752078520795208052081520825208352084520855208652087520885208952090520915209252093520945209552096520975209852099521005210152102521035210452105521065210752108521095211052111521125211352114521155211652117521185211952120521215212252123521245212552126521275212852129521305213152132521335213452135521365213752138521395214052141521425214352144521455214652147521485214952150521515215252153521545215552156521575215852159521605216152162521635216452165521665216752168521695217052171521725217352174521755217652177521785217952180521815218252183521845218552186521875218852189521905219152192521935219452195521965219752198521995220052201522025220352204522055220652207522085220952210522115221252213522145221552216522175221852219522205222152222522235222452225522265222752228522295223052231522325223352234522355223652237522385223952240522415224252243522445224552246522475224852249522505225152252522535225452255522565225752258522595226052261522625226352264522655226652267522685226952270522715227252273522745227552276522775227852279522805228152282522835228452285522865228752288522895229052291522925229352294522955229652297522985229952300523015230252303523045230552306523075230852309523105231152312523135231452315523165231752318523195232052321523225232352324523255232652327523285232952330523315233252333523345233552336523375233852339523405234152342523435234452345523465234752348523495235052351523525235352354523555235652357523585235952360523615236252363523645236552366523675236852369523705237152372523735237452375523765237752378523795238052381523825238352384523855238652387523885238952390523915239252393523945239552396523975239852399524005240152402524035240452405524065240752408524095241052411524125241352414524155241652417524185241952420524215242252423524245242552426524275242852429524305243152432524335243452435524365243752438524395244052441524425244352444524455244652447524485244952450524515245252453524545245552456524575245852459524605246152462524635246452465524665246752468524695247052471524725247352474524755247652477524785247952480524815248252483524845248552486524875248852489524905249152492524935249452495524965249752498524995250052501525025250352504525055250652507525085250952510525115251252513525145251552516525175251852519525205252152522525235252452525525265252752528525295253052531525325253352534525355253652537525385253952540525415254252543525445254552546525475254852549525505255152552525535255452555525565255752558525595256052561525625256352564525655256652567525685256952570525715257252573525745257552576525775257852579525805258152582525835258452585525865258752588525895259052591525925259352594525955259652597525985259952600526015260252603526045260552606526075260852609526105261152612526135261452615526165261752618526195262052621526225262352624526255262652627526285262952630526315263252633526345263552636526375263852639526405264152642526435264452645526465264752648526495265052651526525265352654526555265652657526585265952660526615266252663526645266552666526675266852669526705267152672526735267452675526765267752678526795268052681526825268352684526855268652687526885268952690526915269252693526945269552696526975269852699527005270152702527035270452705527065270752708527095271052711527125271352714527155271652717527185271952720527215272252723527245272552726527275272852729527305273152732527335273452735527365273752738527395274052741527425274352744527455274652747527485274952750527515275252753527545275552756527575275852759527605276152762527635276452765527665276752768527695277052771527725277352774527755277652777527785277952780527815278252783527845278552786527875278852789527905279152792527935279452795527965279752798527995280052801528025280352804528055280652807528085280952810528115281252813528145281552816528175281852819528205282152822528235282452825528265282752828528295283052831528325283352834528355283652837528385283952840528415284252843528445284552846528475284852849528505285152852528535285452855528565285752858528595286052861528625286352864528655286652867528685286952870528715287252873528745287552876528775287852879528805288152882528835288452885528865288752888528895289052891528925289352894528955289652897528985289952900529015290252903529045290552906529075290852909529105291152912529135291452915529165291752918529195292052921529225292352924529255292652927529285292952930529315293252933529345293552936529375293852939529405294152942529435294452945529465294752948529495295052951529525295352954529555295652957529585295952960529615296252963529645296552966529675296852969529705297152972529735297452975529765297752978529795298052981529825298352984529855298652987529885298952990529915299252993529945299552996529975299852999530005300153002530035300453005530065300753008530095301053011530125301353014530155301653017530185301953020530215302253023530245302553026530275302853029530305303153032530335303453035530365303753038530395304053041530425304353044530455304653047530485304953050530515305253053530545305553056530575305853059530605306153062530635306453065530665306753068530695307053071530725307353074530755307653077530785307953080530815308253083530845308553086530875308853089530905309153092530935309453095530965309753098530995310053101531025310353104531055310653107531085310953110531115311253113531145311553116531175311853119531205312153122531235312453125531265312753128531295313053131531325313353134531355313653137531385313953140531415314253143531445314553146531475314853149531505315153152531535315453155531565315753158531595316053161531625316353164531655316653167531685316953170531715317253173531745317553176531775317853179531805318153182531835318453185531865318753188531895319053191531925319353194531955319653197531985319953200532015320253203532045320553206532075320853209532105321153212532135321453215532165321753218532195322053221532225322353224532255322653227532285322953230532315323253233532345323553236532375323853239532405324153242532435324453245532465324753248532495325053251532525325353254532555325653257532585325953260532615326253263532645326553266532675326853269532705327153272532735327453275532765327753278532795328053281532825328353284532855328653287532885328953290532915329253293532945329553296532975329853299533005330153302533035330453305533065330753308533095331053311533125331353314533155331653317533185331953320533215332253323533245332553326533275332853329533305333153332533335333453335533365333753338533395334053341533425334353344533455334653347533485334953350533515335253353533545335553356533575335853359533605336153362533635336453365533665336753368533695337053371533725337353374533755337653377533785337953380533815338253383533845338553386533875338853389533905339153392533935339453395533965339753398533995340053401534025340353404534055340653407534085340953410534115341253413534145341553416534175341853419534205342153422534235342453425534265342753428534295343053431534325343353434534355343653437534385343953440534415344253443534445344553446534475344853449534505345153452534535345453455534565345753458534595346053461534625346353464534655346653467534685346953470534715347253473534745347553476534775347853479534805348153482534835348453485534865348753488534895349053491534925349353494534955349653497534985349953500535015350253503535045350553506535075350853509535105351153512535135351453515535165351753518535195352053521535225352353524535255352653527535285352953530535315353253533535345353553536535375353853539535405354153542535435354453545535465354753548535495355053551535525355353554535555355653557535585355953560535615356253563535645356553566535675356853569535705357153572535735357453575535765357753578535795358053581535825358353584535855358653587535885358953590535915359253593535945359553596535975359853599536005360153602536035360453605536065360753608536095361053611536125361353614536155361653617536185361953620536215362253623536245362553626536275362853629536305363153632536335363453635536365363753638536395364053641536425364353644536455364653647536485364953650536515365253653536545365553656536575365853659536605366153662536635366453665536665366753668536695367053671536725367353674536755367653677536785367953680536815368253683536845368553686536875368853689536905369153692536935369453695536965369753698536995370053701537025370353704537055370653707537085370953710537115371253713537145371553716537175371853719537205372153722537235372453725537265372753728537295373053731537325373353734537355373653737537385373953740537415374253743537445374553746537475374853749537505375153752537535375453755537565375753758537595376053761537625376353764537655376653767537685376953770537715377253773537745377553776537775377853779537805378153782537835378453785537865378753788537895379053791537925379353794537955379653797537985379953800538015380253803538045380553806538075380853809538105381153812538135381453815538165381753818538195382053821538225382353824538255382653827538285382953830538315383253833538345383553836538375383853839538405384153842538435384453845538465384753848538495385053851538525385353854538555385653857538585385953860538615386253863538645386553866538675386853869538705387153872538735387453875538765387753878538795388053881538825388353884538855388653887538885388953890538915389253893538945389553896538975389853899539005390153902539035390453905539065390753908539095391053911539125391353914539155391653917539185391953920539215392253923539245392553926539275392853929539305393153932539335393453935539365393753938539395394053941539425394353944539455394653947539485394953950539515395253953539545395553956539575395853959539605396153962539635396453965539665396753968539695397053971539725397353974539755397653977539785397953980539815398253983539845398553986539875398853989539905399153992539935399453995539965399753998539995400054001540025400354004540055400654007540085400954010540115401254013540145401554016540175401854019540205402154022540235402454025540265402754028540295403054031540325403354034540355403654037540385403954040540415404254043540445404554046540475404854049540505405154052540535405454055540565405754058540595406054061540625406354064540655406654067540685406954070540715407254073540745407554076540775407854079540805408154082540835408454085540865408754088540895409054091540925409354094540955409654097540985409954100541015410254103541045410554106541075410854109541105411154112541135411454115541165411754118541195412054121541225412354124541255412654127541285412954130541315413254133541345413554136541375413854139541405414154142541435414454145541465414754148541495415054151541525415354154541555415654157541585415954160541615416254163541645416554166541675416854169541705417154172541735417454175541765417754178541795418054181541825418354184541855418654187541885418954190541915419254193541945419554196541975419854199542005420154202542035420454205542065420754208542095421054211542125421354214542155421654217542185421954220542215422254223542245422554226542275422854229542305423154232542335423454235542365423754238542395424054241542425424354244542455424654247542485424954250542515425254253542545425554256542575425854259542605426154262542635426454265542665426754268542695427054271542725427354274542755427654277542785427954280542815428254283542845428554286542875428854289542905429154292542935429454295542965429754298542995430054301543025430354304543055430654307543085430954310543115431254313543145431554316543175431854319543205432154322543235432454325543265432754328543295433054331543325433354334543355433654337543385433954340543415434254343543445434554346543475434854349543505435154352543535435454355543565435754358543595436054361543625436354364543655436654367543685436954370543715437254373543745437554376543775437854379543805438154382543835438454385543865438754388543895439054391543925439354394543955439654397543985439954400544015440254403544045440554406544075440854409544105441154412544135441454415544165441754418544195442054421544225442354424544255442654427544285442954430544315443254433544345443554436544375443854439544405444154442544435444454445544465444754448544495445054451544525445354454544555445654457544585445954460544615446254463544645446554466544675446854469544705447154472544735447454475544765447754478544795448054481544825448354484544855448654487544885448954490544915449254493544945449554496544975449854499545005450154502545035450454505545065450754508545095451054511545125451354514545155451654517545185451954520545215452254523545245452554526545275452854529545305453154532545335453454535545365453754538545395454054541545425454354544545455454654547545485454954550545515455254553545545455554556545575455854559545605456154562545635456454565545665456754568545695457054571545725457354574545755457654577545785457954580545815458254583545845458554586545875458854589545905459154592545935459454595545965459754598545995460054601546025460354604546055460654607546085460954610546115461254613546145461554616546175461854619546205462154622546235462454625546265462754628546295463054631546325463354634546355463654637546385463954640546415464254643546445464554646546475464854649546505465154652546535465454655546565465754658546595466054661546625466354664546655466654667546685466954670546715467254673546745467554676546775467854679546805468154682546835468454685546865468754688546895469054691546925469354694546955469654697546985469954700547015470254703547045470554706547075470854709547105471154712547135471454715547165471754718547195472054721547225472354724547255472654727547285472954730547315473254733547345473554736547375473854739547405474154742547435474454745547465474754748547495475054751547525475354754547555475654757547585475954760547615476254763547645476554766547675476854769547705477154772547735477454775547765477754778547795478054781547825478354784547855478654787547885478954790547915479254793547945479554796547975479854799548005480154802548035480454805548065480754808548095481054811548125481354814548155481654817548185481954820548215482254823548245482554826548275482854829548305483154832548335483454835548365483754838548395484054841548425484354844548455484654847548485484954850548515485254853548545485554856548575485854859548605486154862548635486454865548665486754868548695487054871548725487354874548755487654877548785487954880548815488254883548845488554886548875488854889548905489154892548935489454895548965489754898548995490054901549025490354904549055490654907549085490954910549115491254913549145491554916549175491854919549205492154922549235492454925549265492754928549295493054931549325493354934549355493654937549385493954940549415494254943549445494554946549475494854949549505495154952549535495454955549565495754958549595496054961549625496354964549655496654967549685496954970549715497254973549745497554976549775497854979549805498154982549835498454985549865498754988549895499054991549925499354994549955499654997549985499955000550015500255003550045500555006550075500855009550105501155012550135501455015550165501755018550195502055021550225502355024550255502655027550285502955030550315503255033550345503555036550375503855039550405504155042550435504455045550465504755048550495505055051550525505355054550555505655057550585505955060550615506255063550645506555066550675506855069550705507155072550735507455075550765507755078550795508055081550825508355084550855508655087550885508955090550915509255093550945509555096550975509855099551005510155102551035510455105551065510755108551095511055111551125511355114551155511655117551185511955120551215512255123551245512555126551275512855129551305513155132551335513455135551365513755138551395514055141551425514355144551455514655147551485514955150551515515255153551545515555156551575515855159551605516155162551635516455165551665516755168551695517055171551725517355174551755517655177551785517955180551815518255183551845518555186551875518855189551905519155192551935519455195551965519755198551995520055201552025520355204552055520655207552085520955210552115521255213552145521555216552175521855219552205522155222552235522455225552265522755228552295523055231552325523355234552355523655237552385523955240552415524255243552445524555246552475524855249552505525155252552535525455255552565525755258552595526055261552625526355264552655526655267552685526955270552715527255273552745527555276552775527855279552805528155282552835528455285552865528755288552895529055291552925529355294552955529655297552985529955300553015530255303553045530555306553075530855309553105531155312553135531455315553165531755318553195532055321553225532355324553255532655327553285532955330553315533255333553345533555336553375533855339553405534155342553435534455345553465534755348553495535055351553525535355354553555535655357553585535955360553615536255363553645536555366553675536855369553705537155372553735537455375553765537755378553795538055381553825538355384553855538655387553885538955390553915539255393553945539555396553975539855399554005540155402554035540455405554065540755408554095541055411554125541355414554155541655417554185541955420554215542255423554245542555426554275542855429554305543155432554335543455435554365543755438554395544055441554425544355444554455544655447554485544955450554515545255453554545545555456554575545855459554605546155462554635546455465554665546755468554695547055471554725547355474554755547655477554785547955480554815548255483554845548555486554875548855489554905549155492554935549455495554965549755498554995550055501555025550355504555055550655507555085550955510555115551255513555145551555516555175551855519555205552155522555235552455525555265552755528555295553055531555325553355534555355553655537555385553955540555415554255543555445554555546555475554855549555505555155552555535555455555555565555755558555595556055561555625556355564555655556655567555685556955570555715557255573555745557555576555775557855579555805558155582555835558455585555865558755588555895559055591555925559355594555955559655597555985559955600556015560255603556045560555606556075560855609556105561155612556135561455615556165561755618556195562055621556225562355624556255562655627556285562955630556315563255633556345563555636556375563855639556405564155642556435564455645556465564755648556495565055651556525565355654556555565655657556585565955660556615566255663556645566555666556675566855669556705567155672556735567455675556765567755678556795568055681556825568355684556855568655687556885568955690556915569255693556945569555696556975569855699557005570155702557035570455705557065570755708557095571055711557125571355714557155571655717557185571955720557215572255723557245572555726557275572855729557305573155732557335573455735557365573755738557395574055741557425574355744557455574655747557485574955750557515575255753557545575555756557575575855759557605576155762557635576455765557665576755768557695577055771557725577355774557755577655777557785577955780557815578255783557845578555786557875578855789557905579155792557935579455795557965579755798557995580055801558025580355804558055580655807558085580955810558115581255813558145581555816558175581855819558205582155822558235582455825558265582755828558295583055831558325583355834558355583655837558385583955840558415584255843558445584555846558475584855849558505585155852558535585455855558565585755858558595586055861558625586355864558655586655867558685586955870558715587255873558745587555876558775587855879558805588155882558835588455885558865588755888558895589055891558925589355894558955589655897558985589955900559015590255903559045590555906559075590855909559105591155912559135591455915559165591755918559195592055921559225592355924559255592655927559285592955930559315593255933559345593555936559375593855939559405594155942559435594455945559465594755948559495595055951559525595355954559555595655957559585595955960559615596255963559645596555966559675596855969559705597155972559735597455975559765597755978559795598055981559825598355984559855598655987559885598955990559915599255993559945599555996559975599855999560005600156002560035600456005560065600756008560095601056011560125601356014560155601656017560185601956020560215602256023560245602556026560275602856029560305603156032560335603456035560365603756038560395604056041560425604356044560455604656047560485604956050560515605256053560545605556056560575605856059560605606156062560635606456065560665606756068560695607056071560725607356074560755607656077560785607956080560815608256083560845608556086560875608856089560905609156092560935609456095560965609756098560995610056101561025610356104561055610656107561085610956110561115611256113561145611556116561175611856119561205612156122561235612456125561265612756128561295613056131561325613356134561355613656137561385613956140561415614256143561445614556146561475614856149561505615156152561535615456155561565615756158561595616056161561625616356164561655616656167561685616956170561715617256173561745617556176561775617856179561805618156182561835618456185561865618756188561895619056191561925619356194561955619656197561985619956200562015620256203562045620556206562075620856209562105621156212562135621456215562165621756218562195622056221562225622356224562255622656227562285622956230562315623256233562345623556236562375623856239562405624156242562435624456245562465624756248562495625056251562525625356254562555625656257562585625956260562615626256263562645626556266562675626856269562705627156272562735627456275562765627756278562795628056281562825628356284562855628656287562885628956290562915629256293562945629556296562975629856299563005630156302563035630456305563065630756308563095631056311563125631356314563155631656317563185631956320563215632256323563245632556326563275632856329563305633156332563335633456335563365633756338563395634056341563425634356344563455634656347563485634956350563515635256353563545635556356563575635856359563605636156362563635636456365563665636756368563695637056371563725637356374563755637656377563785637956380563815638256383563845638556386563875638856389563905639156392563935639456395563965639756398563995640056401564025640356404564055640656407564085640956410564115641256413564145641556416564175641856419564205642156422564235642456425564265642756428564295643056431564325643356434564355643656437564385643956440564415644256443564445644556446564475644856449564505645156452564535645456455564565645756458564595646056461564625646356464564655646656467564685646956470564715647256473564745647556476564775647856479564805648156482564835648456485564865648756488564895649056491564925649356494564955649656497564985649956500565015650256503565045650556506565075650856509565105651156512565135651456515565165651756518565195652056521565225652356524565255652656527565285652956530565315653256533565345653556536565375653856539565405654156542565435654456545565465654756548565495655056551565525655356554565555655656557565585655956560565615656256563565645656556566565675656856569565705657156572565735657456575565765657756578565795658056581565825658356584565855658656587565885658956590565915659256593565945659556596565975659856599566005660156602566035660456605566065660756608566095661056611566125661356614566155661656617566185661956620566215662256623566245662556626566275662856629566305663156632566335663456635566365663756638566395664056641566425664356644566455664656647566485664956650566515665256653566545665556656566575665856659566605666156662566635666456665566665666756668566695667056671566725667356674566755667656677566785667956680566815668256683566845668556686566875668856689566905669156692566935669456695566965669756698566995670056701567025670356704567055670656707567085670956710567115671256713567145671556716567175671856719567205672156722567235672456725567265672756728567295673056731567325673356734567355673656737567385673956740567415674256743567445674556746567475674856749567505675156752567535675456755567565675756758567595676056761567625676356764567655676656767567685676956770567715677256773567745677556776567775677856779567805678156782567835678456785567865678756788567895679056791567925679356794567955679656797567985679956800568015680256803568045680556806568075680856809568105681156812568135681456815568165681756818568195682056821568225682356824568255682656827568285682956830568315683256833568345683556836568375683856839568405684156842568435684456845568465684756848568495685056851568525685356854568555685656857568585685956860568615686256863568645686556866568675686856869568705687156872568735687456875568765687756878568795688056881568825688356884568855688656887568885688956890568915689256893568945689556896568975689856899569005690156902569035690456905569065690756908569095691056911569125691356914569155691656917569185691956920569215692256923569245692556926569275692856929569305693156932569335693456935569365693756938569395694056941569425694356944569455694656947569485694956950569515695256953569545695556956569575695856959569605696156962569635696456965569665696756968569695697056971569725697356974569755697656977569785697956980569815698256983569845698556986569875698856989569905699156992569935699456995569965699756998569995700057001570025700357004570055700657007570085700957010570115701257013570145701557016570175701857019570205702157022570235702457025570265702757028570295703057031570325703357034570355703657037570385703957040570415704257043570445704557046570475704857049570505705157052570535705457055570565705757058570595706057061570625706357064570655706657067570685706957070570715707257073570745707557076570775707857079570805708157082570835708457085570865708757088570895709057091570925709357094570955709657097570985709957100571015710257103571045710557106571075710857109571105711157112571135711457115571165711757118571195712057121571225712357124571255712657127571285712957130571315713257133571345713557136571375713857139571405714157142571435714457145571465714757148571495715057151571525715357154571555715657157571585715957160571615716257163571645716557166571675716857169571705717157172571735717457175571765717757178571795718057181571825718357184571855718657187571885718957190571915719257193571945719557196571975719857199572005720157202572035720457205572065720757208572095721057211572125721357214572155721657217572185721957220572215722257223572245722557226572275722857229572305723157232572335723457235572365723757238572395724057241572425724357244572455724657247572485724957250572515725257253572545725557256572575725857259572605726157262572635726457265572665726757268572695727057271572725727357274572755727657277572785727957280572815728257283572845728557286572875728857289572905729157292572935729457295572965729757298572995730057301573025730357304573055730657307573085730957310573115731257313573145731557316573175731857319573205732157322573235732457325573265732757328573295733057331573325733357334573355733657337573385733957340573415734257343573445734557346573475734857349573505735157352573535735457355573565735757358573595736057361573625736357364573655736657367573685736957370573715737257373573745737557376573775737857379573805738157382573835738457385573865738757388573895739057391573925739357394573955739657397573985739957400574015740257403574045740557406574075740857409574105741157412574135741457415574165741757418574195742057421574225742357424574255742657427574285742957430574315743257433574345743557436574375743857439574405744157442574435744457445574465744757448574495745057451574525745357454574555745657457574585745957460574615746257463574645746557466574675746857469574705747157472574735747457475574765747757478574795748057481574825748357484574855748657487574885748957490574915749257493574945749557496574975749857499575005750157502575035750457505575065750757508575095751057511575125751357514575155751657517575185751957520575215752257523575245752557526575275752857529575305753157532575335753457535575365753757538575395754057541575425754357544575455754657547575485754957550575515755257553575545755557556575575755857559575605756157562575635756457565575665756757568575695757057571575725757357574575755757657577575785757957580575815758257583575845758557586575875758857589575905759157592575935759457595575965759757598575995760057601576025760357604576055760657607576085760957610576115761257613576145761557616576175761857619576205762157622576235762457625576265762757628576295763057631576325763357634576355763657637576385763957640576415764257643576445764557646576475764857649576505765157652576535765457655576565765757658576595766057661576625766357664576655766657667576685766957670576715767257673576745767557676576775767857679576805768157682576835768457685576865768757688576895769057691576925769357694576955769657697576985769957700577015770257703577045770557706577075770857709577105771157712577135771457715577165771757718577195772057721577225772357724577255772657727577285772957730577315773257733577345773557736577375773857739577405774157742577435774457745577465774757748577495775057751577525775357754577555775657757577585775957760577615776257763577645776557766577675776857769577705777157772577735777457775577765777757778577795778057781577825778357784577855778657787577885778957790577915779257793577945779557796577975779857799578005780157802578035780457805578065780757808578095781057811578125781357814578155781657817578185781957820578215782257823578245782557826578275782857829578305783157832578335783457835578365783757838578395784057841578425784357844578455784657847578485784957850578515785257853578545785557856578575785857859578605786157862578635786457865578665786757868578695787057871578725787357874578755787657877578785787957880578815788257883578845788557886578875788857889578905789157892578935789457895578965789757898578995790057901579025790357904579055790657907579085790957910579115791257913579145791557916579175791857919579205792157922579235792457925579265792757928579295793057931579325793357934579355793657937579385793957940579415794257943579445794557946579475794857949579505795157952579535795457955579565795757958579595796057961579625796357964579655796657967579685796957970579715797257973579745797557976579775797857979579805798157982579835798457985579865798757988579895799057991579925799357994579955799657997579985799958000580015800258003580045800558006580075800858009580105801158012580135801458015580165801758018580195802058021580225802358024580255802658027580285802958030580315803258033580345803558036580375803858039580405804158042580435804458045580465804758048580495805058051580525805358054580555805658057580585805958060580615806258063580645806558066580675806858069580705807158072580735807458075580765807758078580795808058081580825808358084580855808658087580885808958090580915809258093580945809558096580975809858099581005810158102581035810458105581065810758108581095811058111581125811358114581155811658117581185811958120581215812258123581245812558126581275812858129581305813158132581335813458135581365813758138581395814058141581425814358144581455814658147581485814958150581515815258153581545815558156581575815858159581605816158162581635816458165581665816758168581695817058171581725817358174581755817658177581785817958180581815818258183581845818558186581875818858189581905819158192581935819458195581965819758198581995820058201582025820358204582055820658207582085820958210582115821258213582145821558216582175821858219582205822158222582235822458225582265822758228582295823058231582325823358234582355823658237582385823958240582415824258243582445824558246582475824858249582505825158252582535825458255582565825758258582595826058261582625826358264582655826658267582685826958270582715827258273582745827558276582775827858279582805828158282582835828458285582865828758288582895829058291582925829358294582955829658297582985829958300583015830258303583045830558306583075830858309583105831158312583135831458315583165831758318583195832058321583225832358324583255832658327583285832958330583315833258333583345833558336583375833858339583405834158342583435834458345583465834758348583495835058351583525835358354583555835658357583585835958360583615836258363583645836558366583675836858369583705837158372583735837458375583765837758378583795838058381583825838358384583855838658387583885838958390583915839258393583945839558396583975839858399584005840158402584035840458405584065840758408584095841058411584125841358414584155841658417584185841958420584215842258423584245842558426584275842858429584305843158432584335843458435584365843758438584395844058441584425844358444584455844658447584485844958450584515845258453584545845558456584575845858459584605846158462584635846458465584665846758468584695847058471584725847358474584755847658477584785847958480584815848258483584845848558486584875848858489584905849158492584935849458495584965849758498584995850058501585025850358504585055850658507585085850958510585115851258513585145851558516585175851858519585205852158522585235852458525585265852758528585295853058531585325853358534585355853658537585385853958540585415854258543585445854558546585475854858549585505855158552585535855458555585565855758558585595856058561585625856358564585655856658567585685856958570585715857258573585745857558576585775857858579585805858158582585835858458585585865858758588585895859058591585925859358594585955859658597585985859958600586015860258603586045860558606586075860858609586105861158612586135861458615586165861758618586195862058621586225862358624586255862658627586285862958630586315863258633586345863558636586375863858639586405864158642586435864458645586465864758648586495865058651586525865358654586555865658657586585865958660586615866258663586645866558666586675866858669586705867158672586735867458675586765867758678586795868058681586825868358684586855868658687586885868958690586915869258693586945869558696586975869858699587005870158702587035870458705587065870758708587095871058711587125871358714587155871658717587185871958720587215872258723587245872558726587275872858729587305873158732587335873458735587365873758738587395874058741587425874358744587455874658747587485874958750587515875258753587545875558756587575875858759587605876158762587635876458765587665876758768587695877058771587725877358774587755877658777587785877958780587815878258783587845878558786587875878858789587905879158792587935879458795587965879758798587995880058801588025880358804588055880658807588085880958810588115881258813588145881558816588175881858819588205882158822588235882458825588265882758828588295883058831588325883358834588355883658837588385883958840588415884258843588445884558846588475884858849588505885158852588535885458855588565885758858588595886058861588625886358864588655886658867588685886958870588715887258873588745887558876588775887858879588805888158882588835888458885588865888758888588895889058891588925889358894588955889658897588985889958900589015890258903589045890558906589075890858909589105891158912589135891458915589165891758918589195892058921589225892358924589255892658927589285892958930589315893258933589345893558936589375893858939589405894158942589435894458945589465894758948589495895058951589525895358954589555895658957589585895958960589615896258963589645896558966589675896858969589705897158972589735897458975589765897758978589795898058981589825898358984589855898658987589885898958990589915899258993589945899558996589975899858999590005900159002590035900459005590065900759008590095901059011590125901359014590155901659017590185901959020590215902259023590245902559026590275902859029590305903159032590335903459035590365903759038590395904059041590425904359044590455904659047590485904959050590515905259053590545905559056590575905859059590605906159062590635906459065590665906759068590695907059071590725907359074590755907659077590785907959080590815908259083590845908559086590875908859089590905909159092590935909459095590965909759098590995910059101591025910359104591055910659107591085910959110591115911259113591145911559116591175911859119591205912159122591235912459125591265912759128591295913059131591325913359134591355913659137591385913959140591415914259143591445914559146591475914859149591505915159152591535915459155591565915759158591595916059161591625916359164591655916659167591685916959170591715917259173591745917559176591775917859179591805918159182591835918459185591865918759188591895919059191591925919359194591955919659197591985919959200592015920259203592045920559206592075920859209592105921159212592135921459215592165921759218592195922059221592225922359224592255922659227592285922959230592315923259233592345923559236592375923859239592405924159242592435924459245592465924759248592495925059251592525925359254592555925659257592585925959260592615926259263592645926559266592675926859269592705927159272592735927459275592765927759278592795928059281592825928359284592855928659287592885928959290592915929259293592945929559296592975929859299593005930159302593035930459305593065930759308593095931059311593125931359314593155931659317593185931959320593215932259323593245932559326593275932859329593305933159332593335933459335593365933759338593395934059341593425934359344593455934659347593485934959350593515935259353593545935559356593575935859359593605936159362593635936459365593665936759368593695937059371593725937359374593755937659377593785937959380593815938259383593845938559386593875938859389593905939159392593935939459395593965939759398593995940059401594025940359404594055940659407594085940959410594115941259413594145941559416594175941859419594205942159422594235942459425594265942759428594295943059431594325943359434594355943659437594385943959440594415944259443594445944559446594475944859449594505945159452594535945459455594565945759458594595946059461594625946359464594655946659467594685946959470594715947259473594745947559476594775947859479594805948159482594835948459485594865948759488594895949059491594925949359494594955949659497594985949959500595015950259503595045950559506595075950859509595105951159512595135951459515595165951759518595195952059521595225952359524595255952659527595285952959530595315953259533595345953559536595375953859539595405954159542595435954459545595465954759548595495955059551595525955359554595555955659557595585955959560595615956259563595645956559566595675956859569595705957159572595735957459575595765957759578595795958059581595825958359584595855958659587595885958959590595915959259593595945959559596595975959859599596005960159602596035960459605596065960759608596095961059611596125961359614596155961659617596185961959620596215962259623596245962559626596275962859629596305963159632596335963459635596365963759638596395964059641596425964359644596455964659647596485964959650596515965259653596545965559656596575965859659596605966159662596635966459665596665966759668596695967059671596725967359674596755967659677596785967959680596815968259683596845968559686596875968859689596905969159692596935969459695596965969759698596995970059701597025970359704597055970659707597085970959710597115971259713597145971559716597175971859719597205972159722597235972459725597265972759728597295973059731597325973359734597355973659737597385973959740597415974259743597445974559746597475974859749597505975159752597535975459755597565975759758597595976059761597625976359764597655976659767597685976959770597715977259773597745977559776597775977859779597805978159782597835978459785597865978759788597895979059791597925979359794597955979659797597985979959800598015980259803598045980559806598075980859809598105981159812598135981459815598165981759818598195982059821598225982359824598255982659827598285982959830598315983259833598345983559836598375983859839598405984159842598435984459845598465984759848598495985059851598525985359854598555985659857598585985959860598615986259863598645986559866598675986859869598705987159872598735987459875598765987759878598795988059881598825988359884598855988659887598885988959890598915989259893598945989559896598975989859899599005990159902599035990459905599065990759908599095991059911599125991359914599155991659917599185991959920599215992259923599245992559926599275992859929599305993159932599335993459935599365993759938599395994059941599425994359944599455994659947599485994959950599515995259953599545995559956599575995859959599605996159962599635996459965599665996759968599695997059971599725997359974599755997659977599785997959980599815998259983599845998559986599875998859989599905999159992599935999459995599965999759998599996000060001600026000360004600056000660007600086000960010600116001260013600146001560016600176001860019600206002160022600236002460025600266002760028600296003060031600326003360034600356003660037600386003960040600416004260043600446004560046600476004860049600506005160052600536005460055600566005760058600596006060061600626006360064600656006660067600686006960070600716007260073600746007560076600776007860079600806008160082600836008460085600866008760088600896009060091600926009360094600956009660097600986009960100601016010260103601046010560106601076010860109601106011160112601136011460115601166011760118601196012060121601226012360124601256012660127601286012960130601316013260133601346013560136601376013860139601406014160142601436014460145601466014760148601496015060151601526015360154601556015660157601586015960160601616016260163601646016560166601676016860169601706017160172601736017460175601766017760178601796018060181601826018360184601856018660187601886018960190601916019260193601946019560196601976019860199602006020160202602036020460205602066020760208602096021060211602126021360214602156021660217602186021960220602216022260223602246022560226602276022860229602306023160232602336023460235602366023760238602396024060241602426024360244602456024660247602486024960250602516025260253602546025560256602576025860259602606026160262602636026460265602666026760268602696027060271602726027360274602756027660277602786027960280602816028260283602846028560286602876028860289602906029160292602936029460295602966029760298602996030060301603026030360304603056030660307603086030960310603116031260313603146031560316603176031860319603206032160322603236032460325603266032760328603296033060331603326033360334603356033660337603386033960340603416034260343603446034560346603476034860349603506035160352603536035460355603566035760358603596036060361603626036360364603656036660367603686036960370603716037260373603746037560376603776037860379603806038160382603836038460385603866038760388603896039060391603926039360394603956039660397603986039960400604016040260403604046040560406604076040860409604106041160412604136041460415604166041760418604196042060421604226042360424604256042660427604286042960430604316043260433604346043560436604376043860439604406044160442604436044460445604466044760448604496045060451604526045360454604556045660457604586045960460604616046260463604646046560466604676046860469604706047160472604736047460475604766047760478604796048060481604826048360484604856048660487604886048960490604916049260493604946049560496604976049860499605006050160502605036050460505605066050760508605096051060511605126051360514605156051660517605186051960520605216052260523605246052560526605276052860529605306053160532605336053460535605366053760538605396054060541605426054360544605456054660547605486054960550605516055260553605546055560556605576055860559605606056160562605636056460565605666056760568605696057060571605726057360574605756057660577605786057960580605816058260583605846058560586605876058860589605906059160592605936059460595605966059760598605996060060601606026060360604606056060660607606086060960610606116061260613606146061560616606176061860619606206062160622606236062460625606266062760628606296063060631606326063360634606356063660637606386063960640606416064260643606446064560646606476064860649606506065160652606536065460655606566065760658606596066060661606626066360664606656066660667606686066960670606716067260673606746067560676606776067860679606806068160682606836068460685606866068760688606896069060691606926069360694606956069660697606986069960700607016070260703607046070560706607076070860709607106071160712607136071460715607166071760718607196072060721607226072360724607256072660727607286072960730607316073260733607346073560736607376073860739607406074160742607436074460745607466074760748607496075060751607526075360754607556075660757607586075960760607616076260763607646076560766607676076860769607706077160772607736077460775607766077760778607796078060781607826078360784607856078660787607886078960790607916079260793607946079560796607976079860799608006080160802608036080460805608066080760808608096081060811608126081360814608156081660817608186081960820608216082260823608246082560826608276082860829608306083160832608336083460835608366083760838608396084060841608426084360844608456084660847608486084960850608516085260853608546085560856608576085860859608606086160862608636086460865608666086760868608696087060871608726087360874608756087660877608786087960880608816088260883608846088560886608876088860889608906089160892608936089460895608966089760898608996090060901609026090360904609056090660907609086090960910609116091260913609146091560916609176091860919609206092160922609236092460925609266092760928609296093060931609326093360934609356093660937609386093960940609416094260943609446094560946609476094860949609506095160952609536095460955609566095760958609596096060961609626096360964609656096660967609686096960970609716097260973609746097560976609776097860979609806098160982609836098460985609866098760988609896099060991609926099360994609956099660997609986099961000610016100261003610046100561006610076100861009610106101161012610136101461015610166101761018610196102061021610226102361024610256102661027610286102961030610316103261033610346103561036610376103861039610406104161042610436104461045610466104761048610496105061051610526105361054610556105661057610586105961060610616106261063610646106561066610676106861069610706107161072610736107461075610766107761078610796108061081610826108361084610856108661087610886108961090610916109261093610946109561096610976109861099611006110161102611036110461105611066110761108611096111061111611126111361114611156111661117611186111961120611216112261123611246112561126611276112861129611306113161132611336113461135611366113761138611396114061141611426114361144611456114661147611486114961150611516115261153611546115561156611576115861159611606116161162611636116461165611666116761168611696117061171611726117361174611756117661177611786117961180611816118261183611846118561186611876118861189611906119161192611936119461195611966119761198611996120061201612026120361204612056120661207612086120961210612116121261213612146121561216612176121861219612206122161222612236122461225612266122761228612296123061231612326123361234612356123661237612386123961240612416124261243612446124561246612476124861249612506125161252612536125461255612566125761258612596126061261612626126361264612656126661267612686126961270612716127261273612746127561276612776127861279612806128161282612836128461285612866128761288612896129061291612926129361294612956129661297612986129961300613016130261303613046130561306613076130861309613106131161312613136131461315613166131761318613196132061321613226132361324613256132661327613286132961330613316133261333613346133561336613376133861339613406134161342613436134461345613466134761348613496135061351613526135361354613556135661357613586135961360613616136261363613646136561366613676136861369613706137161372613736137461375613766137761378613796138061381613826138361384613856138661387613886138961390613916139261393613946139561396613976139861399614006140161402614036140461405614066140761408614096141061411614126141361414614156141661417614186141961420614216142261423614246142561426614276142861429614306143161432614336143461435614366143761438614396144061441614426144361444614456144661447614486144961450614516145261453614546145561456614576145861459614606146161462614636146461465614666146761468614696147061471614726147361474614756147661477614786147961480614816148261483614846148561486614876148861489614906149161492614936149461495614966149761498614996150061501615026150361504615056150661507615086150961510615116151261513615146151561516615176151861519615206152161522615236152461525615266152761528615296153061531615326153361534615356153661537615386153961540615416154261543615446154561546615476154861549615506155161552615536155461555615566155761558615596156061561615626156361564615656156661567615686156961570615716157261573615746157561576615776157861579615806158161582615836158461585615866158761588615896159061591615926159361594615956159661597615986159961600616016160261603616046160561606616076160861609616106161161612616136161461615616166161761618616196162061621616226162361624616256162661627616286162961630616316163261633616346163561636616376163861639616406164161642616436164461645616466164761648616496165061651616526165361654616556165661657616586165961660616616166261663616646166561666616676166861669616706167161672616736167461675616766167761678616796168061681616826168361684616856168661687616886168961690616916169261693616946169561696616976169861699617006170161702617036170461705617066170761708617096171061711617126171361714617156171661717617186171961720617216172261723617246172561726617276172861729617306173161732617336173461735617366173761738617396174061741617426174361744617456174661747617486174961750617516175261753617546175561756617576175861759617606176161762617636176461765617666176761768617696177061771617726177361774617756177661777617786177961780617816178261783617846178561786617876178861789617906179161792617936179461795617966179761798617996180061801618026180361804618056180661807618086180961810618116181261813618146181561816618176181861819618206182161822618236182461825618266182761828618296183061831618326183361834618356183661837618386183961840618416184261843618446184561846618476184861849618506185161852618536185461855618566185761858618596186061861618626186361864618656186661867618686186961870618716187261873618746187561876618776187861879618806188161882618836188461885618866188761888618896189061891618926189361894618956189661897618986189961900619016190261903619046190561906619076190861909619106191161912619136191461915619166191761918619196192061921619226192361924619256192661927619286192961930619316193261933619346193561936619376193861939619406194161942619436194461945619466194761948619496195061951619526195361954619556195661957619586195961960619616196261963619646196561966619676196861969619706197161972619736197461975619766197761978619796198061981619826198361984619856198661987619886198961990619916199261993619946199561996619976199861999620006200162002620036200462005620066200762008620096201062011620126201362014620156201662017620186201962020620216202262023620246202562026620276202862029620306203162032620336203462035620366203762038620396204062041620426204362044620456204662047620486204962050620516205262053620546205562056620576205862059620606206162062620636206462065620666206762068620696207062071620726207362074620756207662077620786207962080620816208262083620846208562086620876208862089620906209162092620936209462095620966209762098620996210062101621026210362104621056210662107621086210962110621116211262113621146211562116621176211862119621206212162122621236212462125621266212762128621296213062131621326213362134621356213662137621386213962140621416214262143621446214562146621476214862149621506215162152621536215462155621566215762158621596216062161621626216362164621656216662167621686216962170621716217262173621746217562176621776217862179621806218162182621836218462185621866218762188621896219062191621926219362194621956219662197621986219962200622016220262203622046220562206622076220862209622106221162212622136221462215622166221762218622196222062221622226222362224622256222662227622286222962230622316223262233622346223562236622376223862239622406224162242622436224462245622466224762248622496225062251622526225362254622556225662257622586225962260622616226262263622646226562266622676226862269622706227162272622736227462275622766227762278622796228062281622826228362284622856228662287622886228962290622916229262293622946229562296622976229862299623006230162302623036230462305623066230762308623096231062311623126231362314623156231662317623186231962320623216232262323623246232562326623276232862329623306233162332623336233462335623366233762338623396234062341623426234362344623456234662347623486234962350623516235262353623546235562356623576235862359623606236162362623636236462365623666236762368623696237062371623726237362374623756237662377623786237962380623816238262383623846238562386623876238862389623906239162392623936239462395623966239762398623996240062401624026240362404624056240662407624086240962410624116241262413624146241562416624176241862419624206242162422624236242462425624266242762428624296243062431624326243362434624356243662437624386243962440624416244262443624446244562446624476244862449624506245162452624536245462455624566245762458624596246062461624626246362464624656246662467624686246962470624716247262473624746247562476624776247862479624806248162482624836248462485624866248762488624896249062491624926249362494624956249662497624986249962500625016250262503625046250562506625076250862509625106251162512625136251462515625166251762518625196252062521625226252362524625256252662527625286252962530625316253262533625346253562536625376253862539625406254162542625436254462545625466254762548625496255062551625526255362554625556255662557625586255962560625616256262563625646256562566625676256862569625706257162572625736257462575625766257762578625796258062581625826258362584625856258662587625886258962590625916259262593625946259562596625976259862599626006260162602626036260462605626066260762608626096261062611626126261362614626156261662617626186261962620626216262262623626246262562626626276262862629626306263162632626336263462635626366263762638626396264062641626426264362644626456264662647626486264962650626516265262653626546265562656626576265862659626606266162662626636266462665626666266762668626696267062671626726267362674626756267662677626786267962680626816268262683626846268562686626876268862689626906269162692626936269462695626966269762698626996270062701627026270362704627056270662707627086270962710627116271262713627146271562716627176271862719627206272162722627236272462725627266272762728627296273062731627326273362734627356273662737627386273962740627416274262743627446274562746627476274862749627506275162752627536275462755627566275762758627596276062761627626276362764627656276662767627686276962770627716277262773627746277562776627776277862779627806278162782627836278462785627866278762788627896279062791627926279362794627956279662797627986279962800628016280262803628046280562806628076280862809628106281162812628136281462815628166281762818628196282062821628226282362824628256282662827628286282962830628316283262833628346283562836628376283862839628406284162842628436284462845628466284762848628496285062851628526285362854628556285662857628586285962860628616286262863628646286562866628676286862869628706287162872628736287462875628766287762878628796288062881628826288362884628856288662887628886288962890628916289262893628946289562896628976289862899629006290162902629036290462905629066290762908629096291062911629126291362914629156291662917629186291962920629216292262923629246292562926629276292862929629306293162932629336293462935629366293762938629396294062941629426294362944629456294662947629486294962950629516295262953629546295562956629576295862959629606296162962629636296462965629666296762968629696297062971629726297362974629756297662977629786297962980629816298262983629846298562986629876298862989629906299162992629936299462995629966299762998629996300063001630026300363004630056300663007630086300963010630116301263013630146301563016630176301863019630206302163022630236302463025630266302763028630296303063031630326303363034630356303663037630386303963040630416304263043630446304563046630476304863049630506305163052630536305463055630566305763058630596306063061630626306363064630656306663067630686306963070630716307263073630746307563076630776307863079630806308163082630836308463085630866308763088630896309063091630926309363094630956309663097630986309963100631016310263103631046310563106631076310863109631106311163112631136311463115631166311763118631196312063121631226312363124631256312663127631286312963130631316313263133631346313563136631376313863139631406314163142631436314463145631466314763148631496315063151631526315363154631556315663157631586315963160631616316263163631646316563166631676316863169631706317163172631736317463175631766317763178631796318063181631826318363184631856318663187631886318963190631916319263193631946319563196631976319863199632006320163202632036320463205632066320763208632096321063211632126321363214632156321663217632186321963220632216322263223632246322563226632276322863229632306323163232632336323463235632366323763238632396324063241632426324363244632456324663247632486324963250632516325263253632546325563256632576325863259632606326163262632636326463265632666326763268632696327063271632726327363274632756327663277632786327963280632816328263283632846328563286632876328863289632906329163292632936329463295632966329763298632996330063301633026330363304633056330663307633086330963310633116331263313633146331563316633176331863319633206332163322633236332463325633266332763328633296333063331633326333363334633356333663337633386333963340633416334263343633446334563346633476334863349633506335163352633536335463355633566335763358633596336063361633626336363364633656336663367633686336963370633716337263373633746337563376633776337863379633806338163382633836338463385633866338763388633896339063391633926339363394633956339663397633986339963400634016340263403634046340563406634076340863409634106341163412634136341463415634166341763418634196342063421634226342363424634256342663427634286342963430634316343263433634346343563436634376343863439634406344163442634436344463445634466344763448634496345063451634526345363454634556345663457634586345963460634616346263463634646346563466634676346863469634706347163472634736347463475634766347763478634796348063481634826348363484634856348663487634886348963490634916349263493634946349563496634976349863499635006350163502635036350463505635066350763508635096351063511635126351363514635156351663517635186351963520635216352263523635246352563526635276352863529635306353163532635336353463535635366353763538635396354063541635426354363544635456354663547635486354963550635516355263553635546355563556635576355863559635606356163562635636356463565635666356763568635696357063571635726357363574635756357663577635786357963580635816358263583635846358563586635876358863589635906359163592635936359463595635966359763598635996360063601636026360363604636056360663607636086360963610636116361263613636146361563616636176361863619636206362163622636236362463625636266362763628636296363063631636326363363634636356363663637636386363963640636416364263643636446364563646636476364863649636506365163652636536365463655636566365763658636596366063661636626366363664636656366663667636686366963670636716367263673636746367563676636776367863679636806368163682636836368463685636866368763688636896369063691636926369363694636956369663697636986369963700637016370263703637046370563706637076370863709637106371163712637136371463715637166371763718637196372063721637226372363724637256372663727637286372963730637316373263733637346373563736637376373863739637406374163742637436374463745637466374763748637496375063751637526375363754637556375663757637586375963760637616376263763637646376563766637676376863769637706377163772637736377463775637766377763778637796378063781637826378363784637856378663787637886378963790637916379263793637946379563796637976379863799638006380163802638036380463805638066380763808638096381063811638126381363814638156381663817638186381963820638216382263823638246382563826638276382863829638306383163832638336383463835638366383763838638396384063841638426384363844638456384663847638486384963850638516385263853638546385563856638576385863859638606386163862638636386463865638666386763868638696387063871638726387363874638756387663877638786387963880638816388263883638846388563886638876388863889638906389163892638936389463895638966389763898638996390063901639026390363904639056390663907639086390963910639116391263913639146391563916639176391863919639206392163922639236392463925639266392763928639296393063931639326393363934639356393663937639386393963940639416394263943639446394563946639476394863949639506395163952639536395463955639566395763958639596396063961639626396363964639656396663967639686396963970639716397263973639746397563976639776397863979639806398163982639836398463985639866398763988639896399063991639926399363994639956399663997639986399964000640016400264003640046400564006640076400864009640106401164012640136401464015640166401764018640196402064021640226402364024640256402664027640286402964030640316403264033640346403564036640376403864039640406404164042640436404464045640466404764048640496405064051640526405364054640556405664057640586405964060640616406264063640646406564066640676406864069640706407164072640736407464075640766407764078640796408064081640826408364084640856408664087640886408964090640916409264093640946409564096640976409864099641006410164102641036410464105641066410764108641096411064111641126411364114641156411664117641186411964120641216412264123641246412564126641276412864129641306413164132641336413464135641366413764138641396414064141641426414364144641456414664147641486414964150641516415264153641546415564156641576415864159641606416164162641636416464165641666416764168641696417064171641726417364174641756417664177641786417964180641816418264183641846418564186641876418864189641906419164192641936419464195641966419764198641996420064201642026420364204642056420664207642086420964210642116421264213642146421564216642176421864219642206422164222642236422464225642266422764228642296423064231642326423364234642356423664237642386423964240642416424264243642446424564246
  1. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  2. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  3. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  4. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  5. return c > 3 && r && Object.defineProperty(target, key, r), r;
  6. };
  7. var __extends = (this && this.__extends) || function (d, b) {
  8. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  9. function __() { this.constructor = d; }
  10. __.prototype = b.prototype;
  11. d.prototype = new __();
  12. };
  13. var BABYLON;
  14. (function (BABYLON) {
  15. BABYLON.ToGammaSpace = 1 / 2.2;
  16. BABYLON.ToLinearSpace = 2.2;
  17. BABYLON.Epsilon = 0.001;
  18. var MathTools = (function () {
  19. function MathTools() {
  20. }
  21. MathTools.WithinEpsilon = function (a, b, epsilon) {
  22. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  23. var num = a - b;
  24. return -epsilon <= num && num <= epsilon;
  25. };
  26. MathTools.ToHex = function (i) {
  27. var str = i.toString(16);
  28. if (i <= 15) {
  29. return ("0" + str).toUpperCase();
  30. }
  31. return str.toUpperCase();
  32. };
  33. // Returns -1 when value is a negative number and
  34. // +1 when value is a positive number.
  35. MathTools.Sign = function (value) {
  36. value = +value; // convert to a number
  37. if (value === 0 || isNaN(value))
  38. return value;
  39. return value > 0 ? 1 : -1;
  40. };
  41. MathTools.Clamp = function (value, min, max) {
  42. if (min === void 0) { min = 0; }
  43. if (max === void 0) { max = 1; }
  44. return Math.min(max, Math.max(min, value));
  45. };
  46. return MathTools;
  47. }());
  48. BABYLON.MathTools = MathTools;
  49. var Color3 = (function () {
  50. function Color3(r, g, b) {
  51. if (r === void 0) { r = 0; }
  52. if (g === void 0) { g = 0; }
  53. if (b === void 0) { b = 0; }
  54. this.r = r;
  55. this.g = g;
  56. this.b = b;
  57. }
  58. Color3.prototype.toString = function () {
  59. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  60. };
  61. Color3.prototype.getClassName = function () {
  62. return "Color3";
  63. };
  64. Color3.prototype.getHashCode = function () {
  65. var hash = this.r || 0;
  66. hash = (hash * 397) ^ (this.g || 0);
  67. hash = (hash * 397) ^ (this.b || 0);
  68. return hash;
  69. };
  70. // Operators
  71. Color3.prototype.toArray = function (array, index) {
  72. if (index === undefined) {
  73. index = 0;
  74. }
  75. array[index] = this.r;
  76. array[index + 1] = this.g;
  77. array[index + 2] = this.b;
  78. return this;
  79. };
  80. Color3.prototype.toColor4 = function (alpha) {
  81. if (alpha === void 0) { alpha = 1; }
  82. return new Color4(this.r, this.g, this.b, alpha);
  83. };
  84. Color3.prototype.asArray = function () {
  85. var result = [];
  86. this.toArray(result, 0);
  87. return result;
  88. };
  89. Color3.prototype.toLuminance = function () {
  90. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  91. };
  92. Color3.prototype.multiply = function (otherColor) {
  93. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  94. };
  95. Color3.prototype.multiplyToRef = function (otherColor, result) {
  96. result.r = this.r * otherColor.r;
  97. result.g = this.g * otherColor.g;
  98. result.b = this.b * otherColor.b;
  99. return this;
  100. };
  101. Color3.prototype.equals = function (otherColor) {
  102. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  103. };
  104. Color3.prototype.equalsFloats = function (r, g, b) {
  105. return this.r === r && this.g === g && this.b === b;
  106. };
  107. Color3.prototype.scale = function (scale) {
  108. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  109. };
  110. Color3.prototype.scaleToRef = function (scale, result) {
  111. result.r = this.r * scale;
  112. result.g = this.g * scale;
  113. result.b = this.b * scale;
  114. return this;
  115. };
  116. Color3.prototype.add = function (otherColor) {
  117. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  118. };
  119. Color3.prototype.addToRef = function (otherColor, result) {
  120. result.r = this.r + otherColor.r;
  121. result.g = this.g + otherColor.g;
  122. result.b = this.b + otherColor.b;
  123. return this;
  124. };
  125. Color3.prototype.subtract = function (otherColor) {
  126. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  127. };
  128. Color3.prototype.subtractToRef = function (otherColor, result) {
  129. result.r = this.r - otherColor.r;
  130. result.g = this.g - otherColor.g;
  131. result.b = this.b - otherColor.b;
  132. return this;
  133. };
  134. Color3.prototype.clone = function () {
  135. return new Color3(this.r, this.g, this.b);
  136. };
  137. Color3.prototype.copyFrom = function (source) {
  138. this.r = source.r;
  139. this.g = source.g;
  140. this.b = source.b;
  141. return this;
  142. };
  143. Color3.prototype.copyFromFloats = function (r, g, b) {
  144. this.r = r;
  145. this.g = g;
  146. this.b = b;
  147. return this;
  148. };
  149. Color3.prototype.toHexString = function () {
  150. var intR = (this.r * 255) | 0;
  151. var intG = (this.g * 255) | 0;
  152. var intB = (this.b * 255) | 0;
  153. return "#" + MathTools.ToHex(intR) + MathTools.ToHex(intG) + MathTools.ToHex(intB);
  154. };
  155. Color3.prototype.toLinearSpace = function () {
  156. var convertedColor = new Color3();
  157. this.toLinearSpaceToRef(convertedColor);
  158. return convertedColor;
  159. };
  160. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  161. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  162. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  163. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  164. return this;
  165. };
  166. Color3.prototype.toGammaSpace = function () {
  167. var convertedColor = new Color3();
  168. this.toGammaSpaceToRef(convertedColor);
  169. return convertedColor;
  170. };
  171. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  172. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  173. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  174. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  175. return this;
  176. };
  177. // Statics
  178. Color3.FromHexString = function (hex) {
  179. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  180. //Tools.Warn("Color3.FromHexString must be called with a string like #FFFFFF");
  181. return new Color3(0, 0, 0);
  182. }
  183. var r = parseInt(hex.substring(1, 3), 16);
  184. var g = parseInt(hex.substring(3, 5), 16);
  185. var b = parseInt(hex.substring(5, 7), 16);
  186. return Color3.FromInts(r, g, b);
  187. };
  188. Color3.FromArray = function (array, offset) {
  189. if (offset === void 0) { offset = 0; }
  190. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  191. };
  192. Color3.FromInts = function (r, g, b) {
  193. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  194. };
  195. Color3.Lerp = function (start, end, amount) {
  196. var r = start.r + ((end.r - start.r) * amount);
  197. var g = start.g + ((end.g - start.g) * amount);
  198. var b = start.b + ((end.b - start.b) * amount);
  199. return new Color3(r, g, b);
  200. };
  201. Color3.Red = function () { return new Color3(1, 0, 0); };
  202. Color3.Green = function () { return new Color3(0, 1, 0); };
  203. Color3.Blue = function () { return new Color3(0, 0, 1); };
  204. Color3.Black = function () { return new Color3(0, 0, 0); };
  205. Color3.White = function () { return new Color3(1, 1, 1); };
  206. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  207. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  208. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  209. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  210. return Color3;
  211. }());
  212. BABYLON.Color3 = Color3;
  213. var Color4 = (function () {
  214. function Color4(r, g, b, a) {
  215. this.r = r;
  216. this.g = g;
  217. this.b = b;
  218. this.a = a;
  219. }
  220. // Operators
  221. Color4.prototype.addInPlace = function (right) {
  222. this.r += right.r;
  223. this.g += right.g;
  224. this.b += right.b;
  225. this.a += right.a;
  226. return this;
  227. };
  228. Color4.prototype.asArray = function () {
  229. var result = [];
  230. this.toArray(result, 0);
  231. return result;
  232. };
  233. Color4.prototype.toArray = function (array, index) {
  234. if (index === undefined) {
  235. index = 0;
  236. }
  237. array[index] = this.r;
  238. array[index + 1] = this.g;
  239. array[index + 2] = this.b;
  240. array[index + 3] = this.a;
  241. return this;
  242. };
  243. Color4.prototype.add = function (right) {
  244. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  245. };
  246. Color4.prototype.subtract = function (right) {
  247. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  248. };
  249. Color4.prototype.subtractToRef = function (right, result) {
  250. result.r = this.r - right.r;
  251. result.g = this.g - right.g;
  252. result.b = this.b - right.b;
  253. result.a = this.a - right.a;
  254. return this;
  255. };
  256. Color4.prototype.scale = function (scale) {
  257. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  258. };
  259. Color4.prototype.scaleToRef = function (scale, result) {
  260. result.r = this.r * scale;
  261. result.g = this.g * scale;
  262. result.b = this.b * scale;
  263. result.a = this.a * scale;
  264. return this;
  265. };
  266. /**
  267. * Multipy an RGBA Color4 value by another and return a new Color4 object
  268. * @param color The Color4 (RGBA) value to multiply by
  269. * @returns A new Color4.
  270. */
  271. Color4.prototype.multiply = function (color) {
  272. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  273. };
  274. /**
  275. * Multipy an RGBA Color4 value by another and push the result in a reference value
  276. * @param color The Color4 (RGBA) value to multiply by
  277. * @param result The Color4 (RGBA) to fill the result in
  278. * @returns the result Color4.
  279. */
  280. Color4.prototype.multiplyToRef = function (color, result) {
  281. result.r = this.r * color.r;
  282. result.g = this.g * color.g;
  283. result.b = this.b * color.b;
  284. result.a = this.a * color.a;
  285. return result;
  286. };
  287. Color4.prototype.toString = function () {
  288. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  289. };
  290. Color4.prototype.getClassName = function () {
  291. return "Color4";
  292. };
  293. Color4.prototype.getHashCode = function () {
  294. var hash = this.r || 0;
  295. hash = (hash * 397) ^ (this.g || 0);
  296. hash = (hash * 397) ^ (this.b || 0);
  297. hash = (hash * 397) ^ (this.a || 0);
  298. return hash;
  299. };
  300. Color4.prototype.clone = function () {
  301. return new Color4(this.r, this.g, this.b, this.a);
  302. };
  303. Color4.prototype.copyFrom = function (source) {
  304. this.r = source.r;
  305. this.g = source.g;
  306. this.b = source.b;
  307. this.a = source.a;
  308. return this;
  309. };
  310. Color4.prototype.toHexString = function () {
  311. var intR = (this.r * 255) | 0;
  312. var intG = (this.g * 255) | 0;
  313. var intB = (this.b * 255) | 0;
  314. var intA = (this.a * 255) | 0;
  315. return "#" + MathTools.ToHex(intR) + MathTools.ToHex(intG) + MathTools.ToHex(intB) + MathTools.ToHex(intA);
  316. };
  317. // Statics
  318. Color4.FromHexString = function (hex) {
  319. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  320. //Tools.Warn("Color4.FromHexString must be called with a string like #FFFFFFFF");
  321. return new Color4(0, 0, 0, 0);
  322. }
  323. var r = parseInt(hex.substring(1, 3), 16);
  324. var g = parseInt(hex.substring(3, 5), 16);
  325. var b = parseInt(hex.substring(5, 7), 16);
  326. var a = parseInt(hex.substring(7, 9), 16);
  327. return Color4.FromInts(r, g, b, a);
  328. };
  329. Color4.Lerp = function (left, right, amount) {
  330. var result = new Color4(0, 0, 0, 0);
  331. Color4.LerpToRef(left, right, amount, result);
  332. return result;
  333. };
  334. Color4.LerpToRef = function (left, right, amount, result) {
  335. result.r = left.r + (right.r - left.r) * amount;
  336. result.g = left.g + (right.g - left.g) * amount;
  337. result.b = left.b + (right.b - left.b) * amount;
  338. result.a = left.a + (right.a - left.a) * amount;
  339. };
  340. Color4.FromArray = function (array, offset) {
  341. if (offset === void 0) { offset = 0; }
  342. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  343. };
  344. Color4.FromInts = function (r, g, b, a) {
  345. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  346. };
  347. Color4.CheckColors4 = function (colors, count) {
  348. // Check if color3 was used
  349. if (colors.length === count * 3) {
  350. var colors4 = [];
  351. for (var index = 0; index < colors.length; index += 3) {
  352. var newIndex = (index / 3) * 4;
  353. colors4[newIndex] = colors[index];
  354. colors4[newIndex + 1] = colors[index + 1];
  355. colors4[newIndex + 2] = colors[index + 2];
  356. colors4[newIndex + 3] = 1.0;
  357. }
  358. return colors4;
  359. }
  360. return colors;
  361. };
  362. return Color4;
  363. }());
  364. BABYLON.Color4 = Color4;
  365. var Vector2 = (function () {
  366. function Vector2(x, y) {
  367. this.x = x;
  368. this.y = y;
  369. }
  370. Vector2.prototype.toString = function () {
  371. return "{X: " + this.x + " Y:" + this.y + "}";
  372. };
  373. Vector2.prototype.getClassName = function () {
  374. return "Vector2";
  375. };
  376. Vector2.prototype.getHashCode = function () {
  377. var hash = this.x || 0;
  378. hash = (hash * 397) ^ (this.y || 0);
  379. return hash;
  380. };
  381. // Operators
  382. Vector2.prototype.toArray = function (array, index) {
  383. if (index === void 0) { index = 0; }
  384. array[index] = this.x;
  385. array[index + 1] = this.y;
  386. return this;
  387. };
  388. Vector2.prototype.asArray = function () {
  389. var result = [];
  390. this.toArray(result, 0);
  391. return result;
  392. };
  393. Vector2.prototype.copyFrom = function (source) {
  394. this.x = source.x;
  395. this.y = source.y;
  396. return this;
  397. };
  398. Vector2.prototype.copyFromFloats = function (x, y) {
  399. this.x = x;
  400. this.y = y;
  401. return this;
  402. };
  403. Vector2.prototype.add = function (otherVector) {
  404. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  405. };
  406. Vector2.prototype.addToRef = function (otherVector, result) {
  407. result.x = this.x + otherVector.x;
  408. result.y = this.y + otherVector.y;
  409. return this;
  410. };
  411. Vector2.prototype.addInPlace = function (otherVector) {
  412. this.x += otherVector.x;
  413. this.y += otherVector.y;
  414. return this;
  415. };
  416. Vector2.prototype.addVector3 = function (otherVector) {
  417. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  418. };
  419. Vector2.prototype.subtract = function (otherVector) {
  420. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  421. };
  422. Vector2.prototype.subtractToRef = function (otherVector, result) {
  423. result.x = this.x - otherVector.x;
  424. result.y = this.y - otherVector.y;
  425. return this;
  426. };
  427. Vector2.prototype.subtractInPlace = function (otherVector) {
  428. this.x -= otherVector.x;
  429. this.y -= otherVector.y;
  430. return this;
  431. };
  432. Vector2.prototype.multiplyInPlace = function (otherVector) {
  433. this.x *= otherVector.x;
  434. this.y *= otherVector.y;
  435. return this;
  436. };
  437. Vector2.prototype.multiply = function (otherVector) {
  438. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  439. };
  440. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  441. result.x = this.x * otherVector.x;
  442. result.y = this.y * otherVector.y;
  443. return this;
  444. };
  445. Vector2.prototype.multiplyByFloats = function (x, y) {
  446. return new Vector2(this.x * x, this.y * y);
  447. };
  448. Vector2.prototype.divide = function (otherVector) {
  449. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  450. };
  451. Vector2.prototype.divideToRef = function (otherVector, result) {
  452. result.x = this.x / otherVector.x;
  453. result.y = this.y / otherVector.y;
  454. return this;
  455. };
  456. Vector2.prototype.negate = function () {
  457. return new Vector2(-this.x, -this.y);
  458. };
  459. Vector2.prototype.scaleInPlace = function (scale) {
  460. this.x *= scale;
  461. this.y *= scale;
  462. return this;
  463. };
  464. Vector2.prototype.scale = function (scale) {
  465. return new Vector2(this.x * scale, this.y * scale);
  466. };
  467. Vector2.prototype.equals = function (otherVector) {
  468. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  469. };
  470. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  471. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  472. return otherVector && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon) && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon);
  473. };
  474. // Properties
  475. Vector2.prototype.length = function () {
  476. return Math.sqrt(this.x * this.x + this.y * this.y);
  477. };
  478. Vector2.prototype.lengthSquared = function () {
  479. return (this.x * this.x + this.y * this.y);
  480. };
  481. // Methods
  482. Vector2.prototype.normalize = function () {
  483. var len = this.length();
  484. if (len === 0)
  485. return this;
  486. var num = 1.0 / len;
  487. this.x *= num;
  488. this.y *= num;
  489. return this;
  490. };
  491. Vector2.prototype.clone = function () {
  492. return new Vector2(this.x, this.y);
  493. };
  494. // Statics
  495. Vector2.Zero = function () {
  496. return new Vector2(0, 0);
  497. };
  498. Vector2.FromArray = function (array, offset) {
  499. if (offset === void 0) { offset = 0; }
  500. return new Vector2(array[offset], array[offset + 1]);
  501. };
  502. Vector2.FromArrayToRef = function (array, offset, result) {
  503. result.x = array[offset];
  504. result.y = array[offset + 1];
  505. };
  506. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  507. var squared = amount * amount;
  508. var cubed = amount * squared;
  509. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  510. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  511. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  512. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  513. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  514. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  515. return new Vector2(x, y);
  516. };
  517. Vector2.Clamp = function (value, min, max) {
  518. var x = value.x;
  519. x = (x > max.x) ? max.x : x;
  520. x = (x < min.x) ? min.x : x;
  521. var y = value.y;
  522. y = (y > max.y) ? max.y : y;
  523. y = (y < min.y) ? min.y : y;
  524. return new Vector2(x, y);
  525. };
  526. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  527. var squared = amount * amount;
  528. var cubed = amount * squared;
  529. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  530. var part2 = (-2.0 * cubed) + (3.0 * squared);
  531. var part3 = (cubed - (2.0 * squared)) + amount;
  532. var part4 = cubed - squared;
  533. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  534. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  535. return new Vector2(x, y);
  536. };
  537. Vector2.Lerp = function (start, end, amount) {
  538. var x = start.x + ((end.x - start.x) * amount);
  539. var y = start.y + ((end.y - start.y) * amount);
  540. return new Vector2(x, y);
  541. };
  542. Vector2.Dot = function (left, right) {
  543. return left.x * right.x + left.y * right.y;
  544. };
  545. Vector2.Normalize = function (vector) {
  546. var newVector = vector.clone();
  547. newVector.normalize();
  548. return newVector;
  549. };
  550. Vector2.Minimize = function (left, right) {
  551. var x = (left.x < right.x) ? left.x : right.x;
  552. var y = (left.y < right.y) ? left.y : right.y;
  553. return new Vector2(x, y);
  554. };
  555. Vector2.Maximize = function (left, right) {
  556. var x = (left.x > right.x) ? left.x : right.x;
  557. var y = (left.y > right.y) ? left.y : right.y;
  558. return new Vector2(x, y);
  559. };
  560. Vector2.Transform = function (vector, transformation) {
  561. var r = Vector2.Zero();
  562. Vector2.TransformToRef(vector, transformation, r);
  563. return r;
  564. };
  565. Vector2.TransformToRef = function (vector, transformation, result) {
  566. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  567. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  568. result.x = x;
  569. result.y = y;
  570. };
  571. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  572. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  573. var sign = a < 0 ? -1 : 1;
  574. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  575. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  576. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  577. };
  578. Vector2.Distance = function (value1, value2) {
  579. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  580. };
  581. Vector2.DistanceSquared = function (value1, value2) {
  582. var x = value1.x - value2.x;
  583. var y = value1.y - value2.y;
  584. return (x * x) + (y * y);
  585. };
  586. Vector2.Center = function (value1, value2) {
  587. var center = value1.add(value2);
  588. center.scaleInPlace(0.5);
  589. return center;
  590. };
  591. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  592. var l2 = Vector2.DistanceSquared(segA, segB);
  593. if (l2 === 0.0) {
  594. return Vector2.Distance(p, segA);
  595. }
  596. var v = segB.subtract(segA);
  597. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  598. var proj = segA.add(v.multiplyByFloats(t, t));
  599. return Vector2.Distance(p, proj);
  600. };
  601. return Vector2;
  602. }());
  603. BABYLON.Vector2 = Vector2;
  604. var Vector3 = (function () {
  605. function Vector3(x, y, z) {
  606. this.x = x;
  607. this.y = y;
  608. this.z = z;
  609. }
  610. Vector3.prototype.toString = function () {
  611. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  612. };
  613. Vector3.prototype.getClassName = function () {
  614. return "Vector3";
  615. };
  616. Vector3.prototype.getHashCode = function () {
  617. var hash = this.x || 0;
  618. hash = (hash * 397) ^ (this.y || 0);
  619. hash = (hash * 397) ^ (this.z || 0);
  620. return hash;
  621. };
  622. // Operators
  623. Vector3.prototype.asArray = function () {
  624. var result = [];
  625. this.toArray(result, 0);
  626. return result;
  627. };
  628. Vector3.prototype.toArray = function (array, index) {
  629. if (index === void 0) { index = 0; }
  630. array[index] = this.x;
  631. array[index + 1] = this.y;
  632. array[index + 2] = this.z;
  633. return this;
  634. };
  635. Vector3.prototype.toQuaternion = function () {
  636. var result = new Quaternion(0, 0, 0, 1);
  637. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  638. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  639. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  640. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  641. var cosy = Math.cos(this.y * 0.5);
  642. var siny = Math.sin(this.y * 0.5);
  643. result.x = coszMinusx * siny;
  644. result.y = -sinzMinusx * siny;
  645. result.z = sinxPlusz * cosy;
  646. result.w = cosxPlusz * cosy;
  647. return result;
  648. };
  649. Vector3.prototype.addInPlace = function (otherVector) {
  650. this.x += otherVector.x;
  651. this.y += otherVector.y;
  652. this.z += otherVector.z;
  653. return this;
  654. };
  655. Vector3.prototype.add = function (otherVector) {
  656. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  657. };
  658. Vector3.prototype.addToRef = function (otherVector, result) {
  659. result.x = this.x + otherVector.x;
  660. result.y = this.y + otherVector.y;
  661. result.z = this.z + otherVector.z;
  662. return this;
  663. };
  664. Vector3.prototype.subtractInPlace = function (otherVector) {
  665. this.x -= otherVector.x;
  666. this.y -= otherVector.y;
  667. this.z -= otherVector.z;
  668. return this;
  669. };
  670. Vector3.prototype.subtract = function (otherVector) {
  671. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  672. };
  673. Vector3.prototype.subtractToRef = function (otherVector, result) {
  674. result.x = this.x - otherVector.x;
  675. result.y = this.y - otherVector.y;
  676. result.z = this.z - otherVector.z;
  677. return this;
  678. };
  679. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  680. return new Vector3(this.x - x, this.y - y, this.z - z);
  681. };
  682. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  683. result.x = this.x - x;
  684. result.y = this.y - y;
  685. result.z = this.z - z;
  686. return this;
  687. };
  688. Vector3.prototype.negate = function () {
  689. return new Vector3(-this.x, -this.y, -this.z);
  690. };
  691. Vector3.prototype.scaleInPlace = function (scale) {
  692. this.x *= scale;
  693. this.y *= scale;
  694. this.z *= scale;
  695. return this;
  696. };
  697. Vector3.prototype.scale = function (scale) {
  698. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  699. };
  700. Vector3.prototype.scaleToRef = function (scale, result) {
  701. result.x = this.x * scale;
  702. result.y = this.y * scale;
  703. result.z = this.z * scale;
  704. };
  705. Vector3.prototype.equals = function (otherVector) {
  706. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  707. };
  708. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  709. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  710. return otherVector && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon) && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon) && MathTools.WithinEpsilon(this.z, otherVector.z, epsilon);
  711. };
  712. Vector3.prototype.equalsToFloats = function (x, y, z) {
  713. return this.x === x && this.y === y && this.z === z;
  714. };
  715. Vector3.prototype.multiplyInPlace = function (otherVector) {
  716. this.x *= otherVector.x;
  717. this.y *= otherVector.y;
  718. this.z *= otherVector.z;
  719. return this;
  720. };
  721. Vector3.prototype.multiply = function (otherVector) {
  722. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  723. };
  724. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  725. result.x = this.x * otherVector.x;
  726. result.y = this.y * otherVector.y;
  727. result.z = this.z * otherVector.z;
  728. return this;
  729. };
  730. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  731. return new Vector3(this.x * x, this.y * y, this.z * z);
  732. };
  733. Vector3.prototype.divide = function (otherVector) {
  734. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  735. };
  736. Vector3.prototype.divideToRef = function (otherVector, result) {
  737. result.x = this.x / otherVector.x;
  738. result.y = this.y / otherVector.y;
  739. result.z = this.z / otherVector.z;
  740. return this;
  741. };
  742. Vector3.prototype.MinimizeInPlace = function (other) {
  743. if (other.x < this.x)
  744. this.x = other.x;
  745. if (other.y < this.y)
  746. this.y = other.y;
  747. if (other.z < this.z)
  748. this.z = other.z;
  749. return this;
  750. };
  751. Vector3.prototype.MaximizeInPlace = function (other) {
  752. if (other.x > this.x)
  753. this.x = other.x;
  754. if (other.y > this.y)
  755. this.y = other.y;
  756. if (other.z > this.z)
  757. this.z = other.z;
  758. return this;
  759. };
  760. // Properties
  761. Vector3.prototype.length = function () {
  762. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  763. };
  764. Vector3.prototype.lengthSquared = function () {
  765. return (this.x * this.x + this.y * this.y + this.z * this.z);
  766. };
  767. // Methods
  768. Vector3.prototype.normalize = function () {
  769. var len = this.length();
  770. if (len === 0 || len === 1.0)
  771. return this;
  772. var num = 1.0 / len;
  773. this.x *= num;
  774. this.y *= num;
  775. this.z *= num;
  776. return this;
  777. };
  778. Vector3.prototype.clone = function () {
  779. return new Vector3(this.x, this.y, this.z);
  780. };
  781. Vector3.prototype.copyFrom = function (source) {
  782. this.x = source.x;
  783. this.y = source.y;
  784. this.z = source.z;
  785. return this;
  786. };
  787. Vector3.prototype.copyFromFloats = function (x, y, z) {
  788. this.x = x;
  789. this.y = y;
  790. this.z = z;
  791. return this;
  792. };
  793. // Statics
  794. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  795. var d0 = Vector3.Dot(vector0, axis) - size;
  796. var d1 = Vector3.Dot(vector1, axis) - size;
  797. var s = d0 / (d0 - d1);
  798. return s;
  799. };
  800. Vector3.FromArray = function (array, offset) {
  801. if (!offset) {
  802. offset = 0;
  803. }
  804. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  805. };
  806. Vector3.FromFloatArray = function (array, offset) {
  807. if (!offset) {
  808. offset = 0;
  809. }
  810. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  811. };
  812. Vector3.FromArrayToRef = function (array, offset, result) {
  813. result.x = array[offset];
  814. result.y = array[offset + 1];
  815. result.z = array[offset + 2];
  816. };
  817. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  818. result.x = array[offset];
  819. result.y = array[offset + 1];
  820. result.z = array[offset + 2];
  821. };
  822. Vector3.FromFloatsToRef = function (x, y, z, result) {
  823. result.x = x;
  824. result.y = y;
  825. result.z = z;
  826. };
  827. Vector3.Zero = function () {
  828. return new Vector3(0, 0, 0);
  829. };
  830. Vector3.Up = function () {
  831. return new Vector3(0, 1.0, 0);
  832. };
  833. Vector3.TransformCoordinates = function (vector, transformation) {
  834. var result = Vector3.Zero();
  835. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  836. return result;
  837. };
  838. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  839. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  840. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  841. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  842. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  843. result.x = x / w;
  844. result.y = y / w;
  845. result.z = z / w;
  846. };
  847. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  848. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  849. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  850. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  851. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  852. result.x = rx / rw;
  853. result.y = ry / rw;
  854. result.z = rz / rw;
  855. };
  856. Vector3.TransformNormal = function (vector, transformation) {
  857. var result = Vector3.Zero();
  858. Vector3.TransformNormalToRef(vector, transformation, result);
  859. return result;
  860. };
  861. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  862. result.x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  863. result.y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  864. result.z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  865. };
  866. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  867. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  868. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  869. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  870. };
  871. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  872. var squared = amount * amount;
  873. var cubed = amount * squared;
  874. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  875. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  876. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  877. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  878. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  879. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  880. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  881. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  882. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  883. return new Vector3(x, y, z);
  884. };
  885. Vector3.Clamp = function (value, min, max) {
  886. var x = value.x;
  887. x = (x > max.x) ? max.x : x;
  888. x = (x < min.x) ? min.x : x;
  889. var y = value.y;
  890. y = (y > max.y) ? max.y : y;
  891. y = (y < min.y) ? min.y : y;
  892. var z = value.z;
  893. z = (z > max.z) ? max.z : z;
  894. z = (z < min.z) ? min.z : z;
  895. return new Vector3(x, y, z);
  896. };
  897. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  898. var squared = amount * amount;
  899. var cubed = amount * squared;
  900. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  901. var part2 = (-2.0 * cubed) + (3.0 * squared);
  902. var part3 = (cubed - (2.0 * squared)) + amount;
  903. var part4 = cubed - squared;
  904. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  905. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  906. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  907. return new Vector3(x, y, z);
  908. };
  909. Vector3.Lerp = function (start, end, amount) {
  910. var x = start.x + ((end.x - start.x) * amount);
  911. var y = start.y + ((end.y - start.y) * amount);
  912. var z = start.z + ((end.z - start.z) * amount);
  913. return new Vector3(x, y, z);
  914. };
  915. Vector3.Dot = function (left, right) {
  916. return (left.x * right.x + left.y * right.y + left.z * right.z);
  917. };
  918. Vector3.Cross = function (left, right) {
  919. var result = Vector3.Zero();
  920. Vector3.CrossToRef(left, right, result);
  921. return result;
  922. };
  923. Vector3.CrossToRef = function (left, right, result) {
  924. Tmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  925. Tmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  926. Tmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  927. result.copyFrom(Tmp.Vector3[0]);
  928. };
  929. Vector3.Normalize = function (vector) {
  930. var result = Vector3.Zero();
  931. Vector3.NormalizeToRef(vector, result);
  932. return result;
  933. };
  934. Vector3.NormalizeToRef = function (vector, result) {
  935. result.copyFrom(vector);
  936. result.normalize();
  937. };
  938. Vector3.Project = function (vector, world, transform, viewport) {
  939. var cw = viewport.width;
  940. var ch = viewport.height;
  941. var cx = viewport.x;
  942. var cy = viewport.y;
  943. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  944. Matrix.FromValuesToRef(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, 1, 0, cx + cw / 2.0, ch / 2.0 + cy, 0, 1, viewportMatrix);
  945. var matrix = Vector3._matrixCache ? Vector3._matrixCache : (Vector3._matrixCache = new Matrix());
  946. world.multiplyToRef(transform, matrix);
  947. matrix.multiplyToRef(viewportMatrix, matrix);
  948. return Vector3.TransformCoordinates(vector, matrix);
  949. };
  950. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  951. var matrix = Vector3._matrixCache ? Vector3._matrixCache : (Vector3._matrixCache = new Matrix());
  952. world.multiplyToRef(transform, matrix);
  953. matrix.invert();
  954. source.x = source.x / viewportWidth * 2 - 1;
  955. source.y = -(source.y / viewportHeight * 2 - 1);
  956. var vector = Vector3.TransformCoordinates(source, matrix);
  957. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  958. if (MathTools.WithinEpsilon(num, 1.0)) {
  959. vector = vector.scale(1.0 / num);
  960. }
  961. return vector;
  962. };
  963. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  964. var matrix = Vector3._matrixCache ? Vector3._matrixCache : (Vector3._matrixCache = new Matrix());
  965. world.multiplyToRef(view, matrix);
  966. matrix.multiplyToRef(projection, matrix);
  967. matrix.invert();
  968. var screenSource = new Vector3(source.x / viewportWidth * 2 - 1, -(source.y / viewportHeight * 2 - 1), source.z);
  969. var vector = Vector3.TransformCoordinates(screenSource, matrix);
  970. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  971. if (MathTools.WithinEpsilon(num, 1.0)) {
  972. vector = vector.scale(1.0 / num);
  973. }
  974. return vector;
  975. };
  976. Vector3.Minimize = function (left, right) {
  977. var min = left.clone();
  978. min.MinimizeInPlace(right);
  979. return min;
  980. };
  981. Vector3.Maximize = function (left, right) {
  982. var max = left.clone();
  983. max.MaximizeInPlace(right);
  984. return max;
  985. };
  986. Vector3.Distance = function (value1, value2) {
  987. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  988. };
  989. Vector3.DistanceSquared = function (value1, value2) {
  990. var x = value1.x - value2.x;
  991. var y = value1.y - value2.y;
  992. var z = value1.z - value2.z;
  993. return (x * x) + (y * y) + (z * z);
  994. };
  995. Vector3.Center = function (value1, value2) {
  996. var center = value1.add(value2);
  997. center.scaleInPlace(0.5);
  998. return center;
  999. };
  1000. /**
  1001. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  1002. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  1003. * to something in order to rotate it from its local system to the given target system.
  1004. */
  1005. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  1006. var rotation = Vector3.Zero();
  1007. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  1008. return rotation;
  1009. };
  1010. /**
  1011. * The same than RotationFromAxis but updates the passed ref Vector3 parameter.
  1012. */
  1013. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  1014. var u = axis1.normalize();
  1015. var w = axis3.normalize();
  1016. // world axis
  1017. var X = Axis.X;
  1018. var Y = Axis.Y;
  1019. // equation unknowns and vars
  1020. var yaw = 0.0;
  1021. var pitch = 0.0;
  1022. var roll = 0.0;
  1023. var x = 0.0;
  1024. var y = 0.0;
  1025. var z = 0.0;
  1026. var t = 0.0;
  1027. var sign = -1.0;
  1028. var nbRevert = 0;
  1029. var cross = Tmp.Vector3[0];
  1030. var dot = 0.0;
  1031. // step 1 : rotation around w
  1032. // Rv3(u) = u1, and u1 belongs to plane xOz
  1033. // Rv3(w) = w1 = w invariant
  1034. var u1 = Tmp.Vector3[1];
  1035. if (MathTools.WithinEpsilon(w.z, 0, BABYLON.Epsilon)) {
  1036. z = 1.0;
  1037. }
  1038. else if (MathTools.WithinEpsilon(w.x, 0, BABYLON.Epsilon)) {
  1039. x = 1.0;
  1040. }
  1041. else {
  1042. t = w.z / w.x;
  1043. x = -t * Math.sqrt(1 / (1 + t * t));
  1044. z = Math.sqrt(1 / (1 + t * t));
  1045. }
  1046. u1.x = x;
  1047. u1.y = y;
  1048. u1.z = z;
  1049. u1.normalize();
  1050. Vector3.CrossToRef(u, u1, cross); // returns same direction as w (=local z) if positive angle : cross(source, image)
  1051. cross.normalize();
  1052. if (Vector3.Dot(w, cross) < 0) {
  1053. sign = 1.0;
  1054. }
  1055. dot = Vector3.Dot(u, u1);
  1056. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  1057. roll = Math.acos(dot) * sign;
  1058. if (Vector3.Dot(u1, X) < 0) {
  1059. roll = Math.PI + roll;
  1060. u1 = u1.scaleInPlace(-1);
  1061. nbRevert++;
  1062. }
  1063. // step 2 : rotate around u1
  1064. // Ru1(w1) = Ru1(w) = w2, and w2 belongs to plane xOz
  1065. // u1 is yet in xOz and invariant by Ru1, so after this step u1 and w2 will be in xOz
  1066. var w2 = Tmp.Vector3[2];
  1067. var v2 = Tmp.Vector3[3];
  1068. x = 0.0;
  1069. y = 0.0;
  1070. z = 0.0;
  1071. sign = -1.0;
  1072. if (MathTools.WithinEpsilon(w.z, 0, BABYLON.Epsilon)) {
  1073. x = 1.0;
  1074. }
  1075. else {
  1076. t = u1.z / u1.x;
  1077. x = -t * Math.sqrt(1 / (1 + t * t));
  1078. z = Math.sqrt(1 / (1 + t * t));
  1079. }
  1080. w2.x = x;
  1081. w2.y = y;
  1082. w2.z = z;
  1083. w2.normalize();
  1084. Vector3.CrossToRef(w2, u1, v2); // v2 image of v1 through rotation around u1
  1085. v2.normalize();
  1086. Vector3.CrossToRef(w, w2, cross); // returns same direction as u1 (=local x) if positive angle : cross(source, image)
  1087. cross.normalize();
  1088. if (Vector3.Dot(u1, cross) < 0) {
  1089. sign = 1.0;
  1090. }
  1091. dot = Vector3.Dot(w, w2);
  1092. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  1093. pitch = Math.acos(dot) * sign;
  1094. if (Vector3.Dot(v2, Y) < 0) {
  1095. pitch = Math.PI + pitch;
  1096. nbRevert++;
  1097. }
  1098. // step 3 : rotate around v2
  1099. // Rv2(u1) = X, same as Rv2(w2) = Z, with X=(1,0,0) and Z=(0,0,1)
  1100. sign = -1.0;
  1101. Vector3.CrossToRef(X, u1, cross); // returns same direction as Y if positive angle : cross(source, image)
  1102. cross.normalize();
  1103. if (Vector3.Dot(cross, Y) < 0) {
  1104. sign = 1.0;
  1105. }
  1106. dot = Vector3.Dot(u1, X);
  1107. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  1108. yaw = -Math.acos(dot) * sign; // negative : plane zOx oriented clockwise
  1109. if (dot < 0 && nbRevert < 2) {
  1110. yaw = Math.PI + yaw;
  1111. }
  1112. ref.x = pitch;
  1113. ref.y = yaw;
  1114. ref.z = roll;
  1115. };
  1116. return Vector3;
  1117. }());
  1118. BABYLON.Vector3 = Vector3;
  1119. //Vector4 class created for EulerAngle class conversion to Quaternion
  1120. var Vector4 = (function () {
  1121. function Vector4(x, y, z, w) {
  1122. this.x = x;
  1123. this.y = y;
  1124. this.z = z;
  1125. this.w = w;
  1126. }
  1127. Vector4.prototype.toString = function () {
  1128. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "W:" + this.w + "}";
  1129. };
  1130. Vector4.prototype.getClassName = function () {
  1131. return "Vector4";
  1132. };
  1133. Vector4.prototype.getHashCode = function () {
  1134. var hash = this.x || 0;
  1135. hash = (hash * 397) ^ (this.y || 0);
  1136. hash = (hash * 397) ^ (this.z || 0);
  1137. hash = (hash * 397) ^ (this.w || 0);
  1138. return hash;
  1139. };
  1140. // Operators
  1141. Vector4.prototype.asArray = function () {
  1142. var result = [];
  1143. this.toArray(result, 0);
  1144. return result;
  1145. };
  1146. Vector4.prototype.toArray = function (array, index) {
  1147. if (index === undefined) {
  1148. index = 0;
  1149. }
  1150. array[index] = this.x;
  1151. array[index + 1] = this.y;
  1152. array[index + 2] = this.z;
  1153. array[index + 3] = this.w;
  1154. return this;
  1155. };
  1156. Vector4.prototype.addInPlace = function (otherVector) {
  1157. this.x += otherVector.x;
  1158. this.y += otherVector.y;
  1159. this.z += otherVector.z;
  1160. this.w += otherVector.w;
  1161. return this;
  1162. };
  1163. Vector4.prototype.add = function (otherVector) {
  1164. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  1165. };
  1166. Vector4.prototype.addToRef = function (otherVector, result) {
  1167. result.x = this.x + otherVector.x;
  1168. result.y = this.y + otherVector.y;
  1169. result.z = this.z + otherVector.z;
  1170. result.w = this.w + otherVector.w;
  1171. return this;
  1172. };
  1173. Vector4.prototype.subtractInPlace = function (otherVector) {
  1174. this.x -= otherVector.x;
  1175. this.y -= otherVector.y;
  1176. this.z -= otherVector.z;
  1177. this.w -= otherVector.w;
  1178. return this;
  1179. };
  1180. Vector4.prototype.subtract = function (otherVector) {
  1181. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  1182. };
  1183. Vector4.prototype.subtractToRef = function (otherVector, result) {
  1184. result.x = this.x - otherVector.x;
  1185. result.y = this.y - otherVector.y;
  1186. result.z = this.z - otherVector.z;
  1187. result.w = this.w - otherVector.w;
  1188. return this;
  1189. };
  1190. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  1191. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  1192. };
  1193. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  1194. result.x = this.x - x;
  1195. result.y = this.y - y;
  1196. result.z = this.z - z;
  1197. result.w = this.w - w;
  1198. return this;
  1199. };
  1200. Vector4.prototype.negate = function () {
  1201. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  1202. };
  1203. Vector4.prototype.scaleInPlace = function (scale) {
  1204. this.x *= scale;
  1205. this.y *= scale;
  1206. this.z *= scale;
  1207. this.w *= scale;
  1208. return this;
  1209. };
  1210. Vector4.prototype.scale = function (scale) {
  1211. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  1212. };
  1213. Vector4.prototype.scaleToRef = function (scale, result) {
  1214. result.x = this.x * scale;
  1215. result.y = this.y * scale;
  1216. result.z = this.z * scale;
  1217. result.w = this.w * scale;
  1218. };
  1219. Vector4.prototype.equals = function (otherVector) {
  1220. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  1221. };
  1222. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1223. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  1224. return otherVector
  1225. && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon)
  1226. && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon)
  1227. && MathTools.WithinEpsilon(this.z, otherVector.z, epsilon)
  1228. && MathTools.WithinEpsilon(this.w, otherVector.w, epsilon);
  1229. };
  1230. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  1231. return this.x === x && this.y === y && this.z === z && this.w === w;
  1232. };
  1233. Vector4.prototype.multiplyInPlace = function (otherVector) {
  1234. this.x *= otherVector.x;
  1235. this.y *= otherVector.y;
  1236. this.z *= otherVector.z;
  1237. this.w *= otherVector.w;
  1238. return this;
  1239. };
  1240. Vector4.prototype.multiply = function (otherVector) {
  1241. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  1242. };
  1243. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  1244. result.x = this.x * otherVector.x;
  1245. result.y = this.y * otherVector.y;
  1246. result.z = this.z * otherVector.z;
  1247. result.w = this.w * otherVector.w;
  1248. return this;
  1249. };
  1250. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  1251. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  1252. };
  1253. Vector4.prototype.divide = function (otherVector) {
  1254. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  1255. };
  1256. Vector4.prototype.divideToRef = function (otherVector, result) {
  1257. result.x = this.x / otherVector.x;
  1258. result.y = this.y / otherVector.y;
  1259. result.z = this.z / otherVector.z;
  1260. result.w = this.w / otherVector.w;
  1261. return this;
  1262. };
  1263. Vector4.prototype.MinimizeInPlace = function (other) {
  1264. if (other.x < this.x)
  1265. this.x = other.x;
  1266. if (other.y < this.y)
  1267. this.y = other.y;
  1268. if (other.z < this.z)
  1269. this.z = other.z;
  1270. if (other.w < this.w)
  1271. this.w = other.w;
  1272. return this;
  1273. };
  1274. Vector4.prototype.MaximizeInPlace = function (other) {
  1275. if (other.x > this.x)
  1276. this.x = other.x;
  1277. if (other.y > this.y)
  1278. this.y = other.y;
  1279. if (other.z > this.z)
  1280. this.z = other.z;
  1281. if (other.w > this.w)
  1282. this.w = other.w;
  1283. return this;
  1284. };
  1285. // Properties
  1286. Vector4.prototype.length = function () {
  1287. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1288. };
  1289. Vector4.prototype.lengthSquared = function () {
  1290. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1291. };
  1292. // Methods
  1293. Vector4.prototype.normalize = function () {
  1294. var len = this.length();
  1295. if (len === 0)
  1296. return this;
  1297. var num = 1.0 / len;
  1298. this.x *= num;
  1299. this.y *= num;
  1300. this.z *= num;
  1301. this.w *= num;
  1302. return this;
  1303. };
  1304. Vector4.prototype.toVector3 = function () {
  1305. return new Vector3(this.x, this.y, this.z);
  1306. };
  1307. Vector4.prototype.clone = function () {
  1308. return new Vector4(this.x, this.y, this.z, this.w);
  1309. };
  1310. Vector4.prototype.copyFrom = function (source) {
  1311. this.x = source.x;
  1312. this.y = source.y;
  1313. this.z = source.z;
  1314. this.w = source.w;
  1315. return this;
  1316. };
  1317. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  1318. this.x = x;
  1319. this.y = y;
  1320. this.z = z;
  1321. this.w = w;
  1322. return this;
  1323. };
  1324. // Statics
  1325. Vector4.FromArray = function (array, offset) {
  1326. if (!offset) {
  1327. offset = 0;
  1328. }
  1329. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1330. };
  1331. Vector4.FromArrayToRef = function (array, offset, result) {
  1332. result.x = array[offset];
  1333. result.y = array[offset + 1];
  1334. result.z = array[offset + 2];
  1335. result.w = array[offset + 3];
  1336. };
  1337. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  1338. result.x = array[offset];
  1339. result.y = array[offset + 1];
  1340. result.z = array[offset + 2];
  1341. result.w = array[offset + 3];
  1342. };
  1343. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  1344. result.x = x;
  1345. result.y = y;
  1346. result.z = z;
  1347. result.w = w;
  1348. };
  1349. Vector4.Zero = function () {
  1350. return new Vector4(0, 0, 0, 0);
  1351. };
  1352. Vector4.Normalize = function (vector) {
  1353. var result = Vector4.Zero();
  1354. Vector4.NormalizeToRef(vector, result);
  1355. return result;
  1356. };
  1357. Vector4.NormalizeToRef = function (vector, result) {
  1358. result.copyFrom(vector);
  1359. result.normalize();
  1360. };
  1361. Vector4.Minimize = function (left, right) {
  1362. var min = left.clone();
  1363. min.MinimizeInPlace(right);
  1364. return min;
  1365. };
  1366. Vector4.Maximize = function (left, right) {
  1367. var max = left.clone();
  1368. max.MaximizeInPlace(right);
  1369. return max;
  1370. };
  1371. Vector4.Distance = function (value1, value2) {
  1372. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  1373. };
  1374. Vector4.DistanceSquared = function (value1, value2) {
  1375. var x = value1.x - value2.x;
  1376. var y = value1.y - value2.y;
  1377. var z = value1.z - value2.z;
  1378. var w = value1.w - value2.w;
  1379. return (x * x) + (y * y) + (z * z) + (w * w);
  1380. };
  1381. Vector4.Center = function (value1, value2) {
  1382. var center = value1.add(value2);
  1383. center.scaleInPlace(0.5);
  1384. return center;
  1385. };
  1386. return Vector4;
  1387. }());
  1388. BABYLON.Vector4 = Vector4;
  1389. var Size = (function () {
  1390. function Size(width, height) {
  1391. this.width = width;
  1392. this.height = height;
  1393. }
  1394. Size.prototype.toString = function () {
  1395. return "{W: " + this.width + ", H: " + this.height + "}";
  1396. };
  1397. Size.prototype.getClassName = function () {
  1398. return "Size";
  1399. };
  1400. Size.prototype.getHashCode = function () {
  1401. var hash = this.width || 0;
  1402. hash = (hash * 397) ^ (this.height || 0);
  1403. return hash;
  1404. };
  1405. Size.prototype.copyFrom = function (src) {
  1406. this.width = src.width;
  1407. this.height = src.height;
  1408. };
  1409. Size.prototype.copyFromFloats = function (width, height) {
  1410. this.width = width;
  1411. this.height = height;
  1412. };
  1413. Size.prototype.multiplyByFloats = function (w, h) {
  1414. return new Size(this.width * w, this.height * h);
  1415. };
  1416. Size.prototype.clone = function () {
  1417. return new Size(this.width, this.height);
  1418. };
  1419. Size.prototype.equals = function (other) {
  1420. if (!other) {
  1421. return false;
  1422. }
  1423. return (this.width === other.width) && (this.height === other.height);
  1424. };
  1425. Object.defineProperty(Size.prototype, "surface", {
  1426. get: function () {
  1427. return this.width * this.height;
  1428. },
  1429. enumerable: true,
  1430. configurable: true
  1431. });
  1432. Size.Zero = function () {
  1433. return new Size(0, 0);
  1434. };
  1435. Size.prototype.add = function (otherSize) {
  1436. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  1437. return r;
  1438. };
  1439. Size.prototype.substract = function (otherSize) {
  1440. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  1441. return r;
  1442. };
  1443. Size.Lerp = function (start, end, amount) {
  1444. var w = start.width + ((end.width - start.width) * amount);
  1445. var h = start.height + ((end.height - start.height) * amount);
  1446. return new Size(w, h);
  1447. };
  1448. return Size;
  1449. }());
  1450. BABYLON.Size = Size;
  1451. var Quaternion = (function () {
  1452. function Quaternion(x, y, z, w) {
  1453. if (x === void 0) { x = 0; }
  1454. if (y === void 0) { y = 0; }
  1455. if (z === void 0) { z = 0; }
  1456. if (w === void 0) { w = 1; }
  1457. this.x = x;
  1458. this.y = y;
  1459. this.z = z;
  1460. this.w = w;
  1461. }
  1462. Quaternion.prototype.toString = function () {
  1463. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1464. };
  1465. Quaternion.prototype.getClassName = function () {
  1466. return "Quaternion";
  1467. };
  1468. Quaternion.prototype.getHashCode = function () {
  1469. var hash = this.x || 0;
  1470. hash = (hash * 397) ^ (this.y || 0);
  1471. hash = (hash * 397) ^ (this.z || 0);
  1472. hash = (hash * 397) ^ (this.w || 0);
  1473. return hash;
  1474. };
  1475. Quaternion.prototype.asArray = function () {
  1476. return [this.x, this.y, this.z, this.w];
  1477. };
  1478. Quaternion.prototype.equals = function (otherQuaternion) {
  1479. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  1480. };
  1481. Quaternion.prototype.clone = function () {
  1482. return new Quaternion(this.x, this.y, this.z, this.w);
  1483. };
  1484. Quaternion.prototype.copyFrom = function (other) {
  1485. this.x = other.x;
  1486. this.y = other.y;
  1487. this.z = other.z;
  1488. this.w = other.w;
  1489. return this;
  1490. };
  1491. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  1492. this.x = x;
  1493. this.y = y;
  1494. this.z = z;
  1495. this.w = w;
  1496. return this;
  1497. };
  1498. Quaternion.prototype.add = function (other) {
  1499. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  1500. };
  1501. Quaternion.prototype.subtract = function (other) {
  1502. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  1503. };
  1504. Quaternion.prototype.scale = function (value) {
  1505. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  1506. };
  1507. Quaternion.prototype.multiply = function (q1) {
  1508. var result = new Quaternion(0, 0, 0, 1.0);
  1509. this.multiplyToRef(q1, result);
  1510. return result;
  1511. };
  1512. Quaternion.prototype.multiplyToRef = function (q1, result) {
  1513. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  1514. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  1515. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  1516. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  1517. result.copyFromFloats(x, y, z, w);
  1518. return this;
  1519. };
  1520. Quaternion.prototype.multiplyInPlace = function (q1) {
  1521. this.multiplyToRef(q1, this);
  1522. return this;
  1523. };
  1524. Quaternion.prototype.conjugateToRef = function (ref) {
  1525. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  1526. return this;
  1527. };
  1528. Quaternion.prototype.conjugateInPlace = function () {
  1529. this.x *= -1;
  1530. this.y *= -1;
  1531. this.z *= -1;
  1532. return this;
  1533. };
  1534. Quaternion.prototype.conjugate = function () {
  1535. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  1536. return result;
  1537. };
  1538. Quaternion.prototype.length = function () {
  1539. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  1540. };
  1541. Quaternion.prototype.normalize = function () {
  1542. var length = 1.0 / this.length();
  1543. this.x *= length;
  1544. this.y *= length;
  1545. this.z *= length;
  1546. this.w *= length;
  1547. return this;
  1548. };
  1549. Quaternion.prototype.toEulerAngles = function (order) {
  1550. if (order === void 0) { order = "YZX"; }
  1551. var result = Vector3.Zero();
  1552. this.toEulerAnglesToRef(result, order);
  1553. return result;
  1554. };
  1555. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  1556. if (order === void 0) { order = "YZX"; }
  1557. var heading, attitude, bank;
  1558. var x = this.x, y = this.y, z = this.z, w = this.w;
  1559. switch (order) {
  1560. case "YZX":
  1561. var test = x * y + z * w;
  1562. if (test > 0.499) {
  1563. heading = 2 * Math.atan2(x, w);
  1564. attitude = Math.PI / 2;
  1565. bank = 0;
  1566. }
  1567. if (test < -0.499) {
  1568. heading = -2 * Math.atan2(x, w);
  1569. attitude = -Math.PI / 2;
  1570. bank = 0;
  1571. }
  1572. if (isNaN(heading)) {
  1573. var sqx = x * x;
  1574. var sqy = y * y;
  1575. var sqz = z * z;
  1576. heading = Math.atan2(2 * y * w - 2 * x * z, 1 - 2 * sqy - 2 * sqz); // Heading
  1577. attitude = Math.asin(2 * test); // attitude
  1578. bank = Math.atan2(2 * x * w - 2 * y * z, 1 - 2 * sqx - 2 * sqz); // bank
  1579. }
  1580. break;
  1581. default:
  1582. throw new Error("Euler order " + order + " not supported yet.");
  1583. }
  1584. result.y = heading;
  1585. result.z = attitude;
  1586. result.x = bank;
  1587. return this;
  1588. };
  1589. ;
  1590. Quaternion.prototype.toRotationMatrix = function (result) {
  1591. var xx = this.x * this.x;
  1592. var yy = this.y * this.y;
  1593. var zz = this.z * this.z;
  1594. var xy = this.x * this.y;
  1595. var zw = this.z * this.w;
  1596. var zx = this.z * this.x;
  1597. var yw = this.y * this.w;
  1598. var yz = this.y * this.z;
  1599. var xw = this.x * this.w;
  1600. result.m[0] = 1.0 - (2.0 * (yy + zz));
  1601. result.m[1] = 2.0 * (xy + zw);
  1602. result.m[2] = 2.0 * (zx - yw);
  1603. result.m[3] = 0;
  1604. result.m[4] = 2.0 * (xy - zw);
  1605. result.m[5] = 1.0 - (2.0 * (zz + xx));
  1606. result.m[6] = 2.0 * (yz + xw);
  1607. result.m[7] = 0;
  1608. result.m[8] = 2.0 * (zx + yw);
  1609. result.m[9] = 2.0 * (yz - xw);
  1610. result.m[10] = 1.0 - (2.0 * (yy + xx));
  1611. result.m[11] = 0;
  1612. result.m[12] = 0;
  1613. result.m[13] = 0;
  1614. result.m[14] = 0;
  1615. result.m[15] = 1.0;
  1616. return this;
  1617. };
  1618. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  1619. Quaternion.FromRotationMatrixToRef(matrix, this);
  1620. return this;
  1621. };
  1622. // Statics
  1623. Quaternion.FromRotationMatrix = function (matrix) {
  1624. var result = new Quaternion();
  1625. Quaternion.FromRotationMatrixToRef(matrix, result);
  1626. return result;
  1627. };
  1628. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  1629. var data = matrix.m;
  1630. var m11 = data[0], m12 = data[4], m13 = data[8];
  1631. var m21 = data[1], m22 = data[5], m23 = data[9];
  1632. var m31 = data[2], m32 = data[6], m33 = data[10];
  1633. var trace = m11 + m22 + m33;
  1634. var s;
  1635. if (trace > 0) {
  1636. s = 0.5 / Math.sqrt(trace + 1.0);
  1637. result.w = 0.25 / s;
  1638. result.x = (m32 - m23) * s;
  1639. result.y = (m13 - m31) * s;
  1640. result.z = (m21 - m12) * s;
  1641. }
  1642. else if (m11 > m22 && m11 > m33) {
  1643. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  1644. result.w = (m32 - m23) / s;
  1645. result.x = 0.25 * s;
  1646. result.y = (m12 + m21) / s;
  1647. result.z = (m13 + m31) / s;
  1648. }
  1649. else if (m22 > m33) {
  1650. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  1651. result.w = (m13 - m31) / s;
  1652. result.x = (m12 + m21) / s;
  1653. result.y = 0.25 * s;
  1654. result.z = (m23 + m32) / s;
  1655. }
  1656. else {
  1657. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  1658. result.w = (m21 - m12) / s;
  1659. result.x = (m13 + m31) / s;
  1660. result.y = (m23 + m32) / s;
  1661. result.z = 0.25 * s;
  1662. }
  1663. };
  1664. Quaternion.Inverse = function (q) {
  1665. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  1666. };
  1667. Quaternion.Identity = function () {
  1668. return new Quaternion(0, 0, 0, 1);
  1669. };
  1670. Quaternion.RotationAxis = function (axis, angle) {
  1671. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  1672. };
  1673. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  1674. var sin = Math.sin(angle / 2);
  1675. axis.normalize();
  1676. result.w = Math.cos(angle / 2);
  1677. result.x = axis.x * sin;
  1678. result.y = axis.y * sin;
  1679. result.z = axis.z * sin;
  1680. return result;
  1681. };
  1682. Quaternion.FromArray = function (array, offset) {
  1683. if (!offset) {
  1684. offset = 0;
  1685. }
  1686. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1687. };
  1688. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1689. var q = new Quaternion();
  1690. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  1691. return q;
  1692. };
  1693. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1694. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  1695. var halfRoll = roll * 0.5;
  1696. var halfPitch = pitch * 0.5;
  1697. var halfYaw = yaw * 0.5;
  1698. var sinRoll = Math.sin(halfRoll);
  1699. var cosRoll = Math.cos(halfRoll);
  1700. var sinPitch = Math.sin(halfPitch);
  1701. var cosPitch = Math.cos(halfPitch);
  1702. var sinYaw = Math.sin(halfYaw);
  1703. var cosYaw = Math.cos(halfYaw);
  1704. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  1705. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  1706. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  1707. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  1708. };
  1709. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  1710. var result = new Quaternion();
  1711. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  1712. return result;
  1713. };
  1714. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  1715. // Produces a quaternion from Euler angles in the z-x-z orientation
  1716. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  1717. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  1718. var halfBeta = beta * 0.5;
  1719. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1720. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1721. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1722. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1723. };
  1724. Quaternion.Slerp = function (left, right, amount) {
  1725. var num2;
  1726. var num3;
  1727. var num = amount;
  1728. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  1729. var flag = false;
  1730. if (num4 < 0) {
  1731. flag = true;
  1732. num4 = -num4;
  1733. }
  1734. if (num4 > 0.999999) {
  1735. num3 = 1 - num;
  1736. num2 = flag ? -num : num;
  1737. }
  1738. else {
  1739. var num5 = Math.acos(num4);
  1740. var num6 = (1.0 / Math.sin(num5));
  1741. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  1742. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  1743. }
  1744. return new Quaternion((num3 * left.x) + (num2 * right.x), (num3 * left.y) + (num2 * right.y), (num3 * left.z) + (num2 * right.z), (num3 * left.w) + (num2 * right.w));
  1745. };
  1746. return Quaternion;
  1747. }());
  1748. BABYLON.Quaternion = Quaternion;
  1749. var Matrix = (function () {
  1750. function Matrix() {
  1751. this.m = new Float32Array(16);
  1752. }
  1753. // Properties
  1754. Matrix.prototype.isIdentity = function () {
  1755. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[10] !== 1.0 || this.m[15] !== 1.0)
  1756. return false;
  1757. if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  1758. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  1759. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  1760. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0)
  1761. return false;
  1762. return true;
  1763. };
  1764. Matrix.prototype.determinant = function () {
  1765. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  1766. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  1767. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  1768. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  1769. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  1770. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  1771. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  1772. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  1773. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  1774. };
  1775. // Methods
  1776. Matrix.prototype.toArray = function () {
  1777. return this.m;
  1778. };
  1779. Matrix.prototype.asArray = function () {
  1780. return this.toArray();
  1781. };
  1782. Matrix.prototype.invert = function () {
  1783. this.invertToRef(this);
  1784. return this;
  1785. };
  1786. Matrix.prototype.reset = function () {
  1787. for (var index = 0; index < 16; index++) {
  1788. this.m[index] = 0;
  1789. }
  1790. return this;
  1791. };
  1792. Matrix.prototype.add = function (other) {
  1793. var result = new Matrix();
  1794. this.addToRef(other, result);
  1795. return result;
  1796. };
  1797. Matrix.prototype.addToRef = function (other, result) {
  1798. for (var index = 0; index < 16; index++) {
  1799. result.m[index] = this.m[index] + other.m[index];
  1800. }
  1801. return this;
  1802. };
  1803. Matrix.prototype.addToSelf = function (other) {
  1804. for (var index = 0; index < 16; index++) {
  1805. this.m[index] += other.m[index];
  1806. }
  1807. return this;
  1808. };
  1809. Matrix.prototype.invertToRef = function (other) {
  1810. var l1 = this.m[0];
  1811. var l2 = this.m[1];
  1812. var l3 = this.m[2];
  1813. var l4 = this.m[3];
  1814. var l5 = this.m[4];
  1815. var l6 = this.m[5];
  1816. var l7 = this.m[6];
  1817. var l8 = this.m[7];
  1818. var l9 = this.m[8];
  1819. var l10 = this.m[9];
  1820. var l11 = this.m[10];
  1821. var l12 = this.m[11];
  1822. var l13 = this.m[12];
  1823. var l14 = this.m[13];
  1824. var l15 = this.m[14];
  1825. var l16 = this.m[15];
  1826. var l17 = (l11 * l16) - (l12 * l15);
  1827. var l18 = (l10 * l16) - (l12 * l14);
  1828. var l19 = (l10 * l15) - (l11 * l14);
  1829. var l20 = (l9 * l16) - (l12 * l13);
  1830. var l21 = (l9 * l15) - (l11 * l13);
  1831. var l22 = (l9 * l14) - (l10 * l13);
  1832. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  1833. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  1834. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  1835. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  1836. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  1837. var l28 = (l7 * l16) - (l8 * l15);
  1838. var l29 = (l6 * l16) - (l8 * l14);
  1839. var l30 = (l6 * l15) - (l7 * l14);
  1840. var l31 = (l5 * l16) - (l8 * l13);
  1841. var l32 = (l5 * l15) - (l7 * l13);
  1842. var l33 = (l5 * l14) - (l6 * l13);
  1843. var l34 = (l7 * l12) - (l8 * l11);
  1844. var l35 = (l6 * l12) - (l8 * l10);
  1845. var l36 = (l6 * l11) - (l7 * l10);
  1846. var l37 = (l5 * l12) - (l8 * l9);
  1847. var l38 = (l5 * l11) - (l7 * l9);
  1848. var l39 = (l5 * l10) - (l6 * l9);
  1849. other.m[0] = l23 * l27;
  1850. other.m[4] = l24 * l27;
  1851. other.m[8] = l25 * l27;
  1852. other.m[12] = l26 * l27;
  1853. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  1854. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  1855. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  1856. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  1857. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  1858. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  1859. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  1860. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  1861. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  1862. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  1863. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  1864. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  1865. return this;
  1866. };
  1867. Matrix.prototype.setTranslation = function (vector3) {
  1868. this.m[12] = vector3.x;
  1869. this.m[13] = vector3.y;
  1870. this.m[14] = vector3.z;
  1871. return this;
  1872. };
  1873. Matrix.prototype.getTranslation = function () {
  1874. return new Vector3(this.m[12], this.m[13], this.m[14]);
  1875. };
  1876. Matrix.prototype.multiply = function (other) {
  1877. var result = new Matrix();
  1878. this.multiplyToRef(other, result);
  1879. return result;
  1880. };
  1881. Matrix.prototype.copyFrom = function (other) {
  1882. for (var index = 0; index < 16; index++) {
  1883. this.m[index] = other.m[index];
  1884. }
  1885. return this;
  1886. };
  1887. Matrix.prototype.copyToArray = function (array, offset) {
  1888. if (offset === void 0) { offset = 0; }
  1889. for (var index = 0; index < 16; index++) {
  1890. array[offset + index] = this.m[index];
  1891. }
  1892. return this;
  1893. };
  1894. Matrix.prototype.multiplyToRef = function (other, result) {
  1895. this.multiplyToArray(other, result.m, 0);
  1896. return this;
  1897. };
  1898. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  1899. var tm0 = this.m[0];
  1900. var tm1 = this.m[1];
  1901. var tm2 = this.m[2];
  1902. var tm3 = this.m[3];
  1903. var tm4 = this.m[4];
  1904. var tm5 = this.m[5];
  1905. var tm6 = this.m[6];
  1906. var tm7 = this.m[7];
  1907. var tm8 = this.m[8];
  1908. var tm9 = this.m[9];
  1909. var tm10 = this.m[10];
  1910. var tm11 = this.m[11];
  1911. var tm12 = this.m[12];
  1912. var tm13 = this.m[13];
  1913. var tm14 = this.m[14];
  1914. var tm15 = this.m[15];
  1915. var om0 = other.m[0];
  1916. var om1 = other.m[1];
  1917. var om2 = other.m[2];
  1918. var om3 = other.m[3];
  1919. var om4 = other.m[4];
  1920. var om5 = other.m[5];
  1921. var om6 = other.m[6];
  1922. var om7 = other.m[7];
  1923. var om8 = other.m[8];
  1924. var om9 = other.m[9];
  1925. var om10 = other.m[10];
  1926. var om11 = other.m[11];
  1927. var om12 = other.m[12];
  1928. var om13 = other.m[13];
  1929. var om14 = other.m[14];
  1930. var om15 = other.m[15];
  1931. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  1932. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  1933. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  1934. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  1935. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  1936. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  1937. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  1938. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  1939. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  1940. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  1941. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  1942. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  1943. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  1944. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  1945. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  1946. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  1947. return this;
  1948. };
  1949. Matrix.prototype.equals = function (value) {
  1950. return value &&
  1951. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  1952. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  1953. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  1954. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  1955. };
  1956. Matrix.prototype.clone = function () {
  1957. return Matrix.FromValues(this.m[0], this.m[1], this.m[2], this.m[3], this.m[4], this.m[5], this.m[6], this.m[7], this.m[8], this.m[9], this.m[10], this.m[11], this.m[12], this.m[13], this.m[14], this.m[15]);
  1958. };
  1959. Matrix.prototype.getClassName = function () {
  1960. return "Matrix";
  1961. };
  1962. Matrix.prototype.getHashCode = function () {
  1963. var hash = this.m[0] || 0;
  1964. for (var i = 1; i < 16; i++) {
  1965. hash = (hash * 397) ^ (this.m[i] || 0);
  1966. }
  1967. return hash;
  1968. };
  1969. Matrix.prototype.decompose = function (scale, rotation, translation) {
  1970. translation.x = this.m[12];
  1971. translation.y = this.m[13];
  1972. translation.z = this.m[14];
  1973. var xs = MathTools.Sign(this.m[0] * this.m[1] * this.m[2] * this.m[3]) < 0 ? -1 : 1;
  1974. var ys = MathTools.Sign(this.m[4] * this.m[5] * this.m[6] * this.m[7]) < 0 ? -1 : 1;
  1975. var zs = MathTools.Sign(this.m[8] * this.m[9] * this.m[10] * this.m[11]) < 0 ? -1 : 1;
  1976. scale.x = xs * Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  1977. scale.y = ys * Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  1978. scale.z = zs * Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  1979. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  1980. rotation.x = 0;
  1981. rotation.y = 0;
  1982. rotation.z = 0;
  1983. rotation.w = 1;
  1984. return false;
  1985. }
  1986. var rotationMatrix = Matrix.FromValues(this.m[0] / scale.x, this.m[1] / scale.x, this.m[2] / scale.x, 0, this.m[4] / scale.y, this.m[5] / scale.y, this.m[6] / scale.y, 0, this.m[8] / scale.z, this.m[9] / scale.z, this.m[10] / scale.z, 0, 0, 0, 0, 1);
  1987. Quaternion.FromRotationMatrixToRef(rotationMatrix, rotation);
  1988. return true;
  1989. };
  1990. // Statics
  1991. Matrix.FromArray = function (array, offset) {
  1992. var result = new Matrix();
  1993. if (!offset) {
  1994. offset = 0;
  1995. }
  1996. Matrix.FromArrayToRef(array, offset, result);
  1997. return result;
  1998. };
  1999. Matrix.FromArrayToRef = function (array, offset, result) {
  2000. for (var index = 0; index < 16; index++) {
  2001. result.m[index] = array[index + offset];
  2002. }
  2003. };
  2004. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  2005. for (var index = 0; index < 16; index++) {
  2006. result.m[index] = array[index + offset] * scale;
  2007. }
  2008. };
  2009. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  2010. result.m[0] = initialM11;
  2011. result.m[1] = initialM12;
  2012. result.m[2] = initialM13;
  2013. result.m[3] = initialM14;
  2014. result.m[4] = initialM21;
  2015. result.m[5] = initialM22;
  2016. result.m[6] = initialM23;
  2017. result.m[7] = initialM24;
  2018. result.m[8] = initialM31;
  2019. result.m[9] = initialM32;
  2020. result.m[10] = initialM33;
  2021. result.m[11] = initialM34;
  2022. result.m[12] = initialM41;
  2023. result.m[13] = initialM42;
  2024. result.m[14] = initialM43;
  2025. result.m[15] = initialM44;
  2026. };
  2027. Matrix.prototype.getRow = function (index) {
  2028. if (index < 0 || index > 3) {
  2029. return null;
  2030. }
  2031. var i = index * 4;
  2032. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  2033. };
  2034. Matrix.prototype.setRow = function (index, row) {
  2035. if (index < 0 || index > 3) {
  2036. return this;
  2037. }
  2038. var i = index * 4;
  2039. this.m[i + 0] = row.x;
  2040. this.m[i + 1] = row.y;
  2041. this.m[i + 2] = row.z;
  2042. this.m[i + 3] = row.w;
  2043. return this;
  2044. };
  2045. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  2046. var result = new Matrix();
  2047. result.m[0] = initialM11;
  2048. result.m[1] = initialM12;
  2049. result.m[2] = initialM13;
  2050. result.m[3] = initialM14;
  2051. result.m[4] = initialM21;
  2052. result.m[5] = initialM22;
  2053. result.m[6] = initialM23;
  2054. result.m[7] = initialM24;
  2055. result.m[8] = initialM31;
  2056. result.m[9] = initialM32;
  2057. result.m[10] = initialM33;
  2058. result.m[11] = initialM34;
  2059. result.m[12] = initialM41;
  2060. result.m[13] = initialM42;
  2061. result.m[14] = initialM43;
  2062. result.m[15] = initialM44;
  2063. return result;
  2064. };
  2065. Matrix.Compose = function (scale, rotation, translation) {
  2066. var result = Matrix.FromValues(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1);
  2067. var rotationMatrix = Matrix.Identity();
  2068. rotation.toRotationMatrix(rotationMatrix);
  2069. result = result.multiply(rotationMatrix);
  2070. result.setTranslation(translation);
  2071. return result;
  2072. };
  2073. Matrix.Identity = function () {
  2074. return Matrix.FromValues(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0);
  2075. };
  2076. Matrix.IdentityToRef = function (result) {
  2077. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, result);
  2078. };
  2079. Matrix.Zero = function () {
  2080. return Matrix.FromValues(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  2081. };
  2082. Matrix.RotationX = function (angle) {
  2083. var result = new Matrix();
  2084. Matrix.RotationXToRef(angle, result);
  2085. return result;
  2086. };
  2087. Matrix.Invert = function (source) {
  2088. var result = new Matrix();
  2089. source.invertToRef(result);
  2090. return result;
  2091. };
  2092. Matrix.RotationXToRef = function (angle, result) {
  2093. var s = Math.sin(angle);
  2094. var c = Math.cos(angle);
  2095. result.m[0] = 1.0;
  2096. result.m[15] = 1.0;
  2097. result.m[5] = c;
  2098. result.m[10] = c;
  2099. result.m[9] = -s;
  2100. result.m[6] = s;
  2101. result.m[1] = 0;
  2102. result.m[2] = 0;
  2103. result.m[3] = 0;
  2104. result.m[4] = 0;
  2105. result.m[7] = 0;
  2106. result.m[8] = 0;
  2107. result.m[11] = 0;
  2108. result.m[12] = 0;
  2109. result.m[13] = 0;
  2110. result.m[14] = 0;
  2111. };
  2112. Matrix.RotationY = function (angle) {
  2113. var result = new Matrix();
  2114. Matrix.RotationYToRef(angle, result);
  2115. return result;
  2116. };
  2117. Matrix.RotationYToRef = function (angle, result) {
  2118. var s = Math.sin(angle);
  2119. var c = Math.cos(angle);
  2120. result.m[5] = 1.0;
  2121. result.m[15] = 1.0;
  2122. result.m[0] = c;
  2123. result.m[2] = -s;
  2124. result.m[8] = s;
  2125. result.m[10] = c;
  2126. result.m[1] = 0;
  2127. result.m[3] = 0;
  2128. result.m[4] = 0;
  2129. result.m[6] = 0;
  2130. result.m[7] = 0;
  2131. result.m[9] = 0;
  2132. result.m[11] = 0;
  2133. result.m[12] = 0;
  2134. result.m[13] = 0;
  2135. result.m[14] = 0;
  2136. };
  2137. Matrix.RotationZ = function (angle) {
  2138. var result = new Matrix();
  2139. Matrix.RotationZToRef(angle, result);
  2140. return result;
  2141. };
  2142. Matrix.RotationZToRef = function (angle, result) {
  2143. var s = Math.sin(angle);
  2144. var c = Math.cos(angle);
  2145. result.m[10] = 1.0;
  2146. result.m[15] = 1.0;
  2147. result.m[0] = c;
  2148. result.m[1] = s;
  2149. result.m[4] = -s;
  2150. result.m[5] = c;
  2151. result.m[2] = 0;
  2152. result.m[3] = 0;
  2153. result.m[6] = 0;
  2154. result.m[7] = 0;
  2155. result.m[8] = 0;
  2156. result.m[9] = 0;
  2157. result.m[11] = 0;
  2158. result.m[12] = 0;
  2159. result.m[13] = 0;
  2160. result.m[14] = 0;
  2161. };
  2162. Matrix.RotationAxis = function (axis, angle) {
  2163. var result = Matrix.Zero();
  2164. Matrix.RotationAxisToRef(axis, angle, result);
  2165. return result;
  2166. };
  2167. Matrix.RotationAxisToRef = function (axis, angle, result) {
  2168. var s = Math.sin(-angle);
  2169. var c = Math.cos(-angle);
  2170. var c1 = 1 - c;
  2171. axis.normalize();
  2172. result.m[0] = (axis.x * axis.x) * c1 + c;
  2173. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  2174. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  2175. result.m[3] = 0.0;
  2176. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  2177. result.m[5] = (axis.y * axis.y) * c1 + c;
  2178. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  2179. result.m[7] = 0.0;
  2180. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  2181. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  2182. result.m[10] = (axis.z * axis.z) * c1 + c;
  2183. result.m[11] = 0.0;
  2184. result.m[15] = 1.0;
  2185. };
  2186. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  2187. var result = new Matrix();
  2188. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  2189. return result;
  2190. };
  2191. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  2192. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  2193. this._tempQuaternion.toRotationMatrix(result);
  2194. };
  2195. Matrix.Scaling = function (x, y, z) {
  2196. var result = Matrix.Zero();
  2197. Matrix.ScalingToRef(x, y, z, result);
  2198. return result;
  2199. };
  2200. Matrix.ScalingToRef = function (x, y, z, result) {
  2201. result.m[0] = x;
  2202. result.m[1] = 0;
  2203. result.m[2] = 0;
  2204. result.m[3] = 0;
  2205. result.m[4] = 0;
  2206. result.m[5] = y;
  2207. result.m[6] = 0;
  2208. result.m[7] = 0;
  2209. result.m[8] = 0;
  2210. result.m[9] = 0;
  2211. result.m[10] = z;
  2212. result.m[11] = 0;
  2213. result.m[12] = 0;
  2214. result.m[13] = 0;
  2215. result.m[14] = 0;
  2216. result.m[15] = 1.0;
  2217. };
  2218. Matrix.Translation = function (x, y, z) {
  2219. var result = Matrix.Identity();
  2220. Matrix.TranslationToRef(x, y, z, result);
  2221. return result;
  2222. };
  2223. Matrix.TranslationToRef = function (x, y, z, result) {
  2224. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, x, y, z, 1.0, result);
  2225. };
  2226. Matrix.Lerp = function (startValue, endValue, gradient) {
  2227. var result = Matrix.Zero();
  2228. for (var index = 0; index < 16; index++) {
  2229. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  2230. }
  2231. return result;
  2232. };
  2233. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  2234. var startScale = new Vector3(0, 0, 0);
  2235. var startRotation = new Quaternion();
  2236. var startTranslation = new Vector3(0, 0, 0);
  2237. startValue.decompose(startScale, startRotation, startTranslation);
  2238. var endScale = new Vector3(0, 0, 0);
  2239. var endRotation = new Quaternion();
  2240. var endTranslation = new Vector3(0, 0, 0);
  2241. endValue.decompose(endScale, endRotation, endTranslation);
  2242. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  2243. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  2244. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  2245. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  2246. };
  2247. Matrix.LookAtLH = function (eye, target, up) {
  2248. var result = Matrix.Zero();
  2249. Matrix.LookAtLHToRef(eye, target, up, result);
  2250. return result;
  2251. };
  2252. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  2253. // Z axis
  2254. target.subtractToRef(eye, this._zAxis);
  2255. this._zAxis.normalize();
  2256. // X axis
  2257. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  2258. if (this._xAxis.lengthSquared() === 0) {
  2259. this._xAxis.x = 1.0;
  2260. }
  2261. else {
  2262. this._xAxis.normalize();
  2263. }
  2264. // Y axis
  2265. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  2266. this._yAxis.normalize();
  2267. // Eye angles
  2268. var ex = -Vector3.Dot(this._xAxis, eye);
  2269. var ey = -Vector3.Dot(this._yAxis, eye);
  2270. var ez = -Vector3.Dot(this._zAxis, eye);
  2271. return Matrix.FromValuesToRef(this._xAxis.x, this._yAxis.x, this._zAxis.x, 0, this._xAxis.y, this._yAxis.y, this._zAxis.y, 0, this._xAxis.z, this._yAxis.z, this._zAxis.z, 0, ex, ey, ez, 1, result);
  2272. };
  2273. Matrix.LookAtRH = function (eye, target, up) {
  2274. var result = Matrix.Zero();
  2275. Matrix.LookAtRHToRef(eye, target, up, result);
  2276. return result;
  2277. };
  2278. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  2279. // Z axis
  2280. eye.subtractToRef(target, this._zAxis);
  2281. this._zAxis.normalize();
  2282. // X axis
  2283. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  2284. if (this._xAxis.lengthSquared() === 0) {
  2285. this._xAxis.x = 1.0;
  2286. }
  2287. else {
  2288. this._xAxis.normalize();
  2289. }
  2290. // Y axis
  2291. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  2292. this._yAxis.normalize();
  2293. // Eye angles
  2294. var ex = -Vector3.Dot(this._xAxis, eye);
  2295. var ey = -Vector3.Dot(this._yAxis, eye);
  2296. var ez = -Vector3.Dot(this._zAxis, eye);
  2297. return Matrix.FromValuesToRef(this._xAxis.x, this._yAxis.x, this._zAxis.x, 0, this._xAxis.y, this._yAxis.y, this._zAxis.y, 0, this._xAxis.z, this._yAxis.z, this._zAxis.z, 0, ex, ey, ez, 1, result);
  2298. };
  2299. Matrix.OrthoLH = function (width, height, znear, zfar) {
  2300. var matrix = Matrix.Zero();
  2301. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  2302. return matrix;
  2303. };
  2304. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  2305. var hw = 2.0 / width;
  2306. var hh = 2.0 / height;
  2307. var id = 1.0 / (zfar - znear);
  2308. var nid = znear / (znear - zfar);
  2309. Matrix.FromValuesToRef(hw, 0, 0, 0, 0, hh, 0, 0, 0, 0, id, 0, 0, 0, nid, 1, result);
  2310. };
  2311. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  2312. var matrix = Matrix.Zero();
  2313. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  2314. return matrix;
  2315. };
  2316. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  2317. result.m[0] = 2.0 / (right - left);
  2318. result.m[1] = result.m[2] = result.m[3] = 0;
  2319. result.m[5] = 2.0 / (top - bottom);
  2320. result.m[4] = result.m[6] = result.m[7] = 0;
  2321. result.m[10] = 1.0 / (zfar - znear);
  2322. result.m[8] = result.m[9] = result.m[11] = 0;
  2323. result.m[12] = (left + right) / (left - right);
  2324. result.m[13] = (top + bottom) / (bottom - top);
  2325. result.m[14] = -znear / (zfar - znear);
  2326. result.m[15] = 1.0;
  2327. };
  2328. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  2329. var matrix = Matrix.Zero();
  2330. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  2331. return matrix;
  2332. };
  2333. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  2334. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  2335. result.m[10] *= -1.0;
  2336. };
  2337. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  2338. var matrix = Matrix.Zero();
  2339. matrix.m[0] = (2.0 * znear) / width;
  2340. matrix.m[1] = matrix.m[2] = matrix.m[3] = 0.0;
  2341. matrix.m[5] = (2.0 * znear) / height;
  2342. matrix.m[4] = matrix.m[6] = matrix.m[7] = 0.0;
  2343. matrix.m[10] = -zfar / (znear - zfar);
  2344. matrix.m[8] = matrix.m[9] = 0.0;
  2345. matrix.m[11] = 1.0;
  2346. matrix.m[12] = matrix.m[13] = matrix.m[15] = 0.0;
  2347. matrix.m[14] = (znear * zfar) / (znear - zfar);
  2348. return matrix;
  2349. };
  2350. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  2351. var matrix = Matrix.Zero();
  2352. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  2353. return matrix;
  2354. };
  2355. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  2356. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  2357. var tan = 1.0 / (Math.tan(fov * 0.5));
  2358. if (isVerticalFovFixed) {
  2359. result.m[0] = tan / aspect;
  2360. }
  2361. else {
  2362. result.m[0] = tan;
  2363. }
  2364. result.m[1] = result.m[2] = result.m[3] = 0.0;
  2365. if (isVerticalFovFixed) {
  2366. result.m[5] = tan;
  2367. }
  2368. else {
  2369. result.m[5] = tan * aspect;
  2370. }
  2371. result.m[4] = result.m[6] = result.m[7] = 0.0;
  2372. result.m[8] = result.m[9] = 0.0;
  2373. result.m[10] = zfar / (zfar - znear);
  2374. result.m[11] = 1.0;
  2375. result.m[12] = result.m[13] = result.m[15] = 0.0;
  2376. result.m[14] = -(znear * zfar) / (zfar - znear);
  2377. };
  2378. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  2379. var matrix = Matrix.Zero();
  2380. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  2381. return matrix;
  2382. };
  2383. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  2384. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  2385. var tan = 1.0 / (Math.tan(fov * 0.5));
  2386. if (isVerticalFovFixed) {
  2387. result.m[0] = tan / aspect;
  2388. }
  2389. else {
  2390. result.m[0] = tan;
  2391. }
  2392. result.m[1] = result.m[2] = result.m[3] = 0.0;
  2393. if (isVerticalFovFixed) {
  2394. result.m[5] = tan;
  2395. }
  2396. else {
  2397. result.m[5] = tan * aspect;
  2398. }
  2399. result.m[4] = result.m[6] = result.m[7] = 0.0;
  2400. result.m[8] = result.m[9] = 0.0;
  2401. result.m[10] = zfar / (znear - zfar);
  2402. result.m[11] = -1.0;
  2403. result.m[12] = result.m[13] = result.m[15] = 0.0;
  2404. result.m[14] = (znear * zfar) / (znear - zfar);
  2405. };
  2406. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, isVerticalFovFixed) {
  2407. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  2408. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  2409. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  2410. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  2411. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  2412. var xScale = 2.0 / (leftTan + rightTan);
  2413. var yScale = 2.0 / (upTan + downTan);
  2414. result.m[0] = xScale;
  2415. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  2416. result.m[5] = yScale;
  2417. result.m[6] = result.m[7] = 0.0;
  2418. result.m[8] = ((leftTan - rightTan) * xScale * 0.5);
  2419. result.m[9] = -((upTan - downTan) * yScale * 0.5);
  2420. //result.m[10] = -(znear + zfar) / (zfar - znear);
  2421. result.m[10] = -zfar / (znear - zfar);
  2422. result.m[11] = 1.0;
  2423. result.m[12] = result.m[13] = result.m[15] = 0.0;
  2424. //result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  2425. result.m[14] = (znear * zfar) / (znear - zfar);
  2426. };
  2427. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  2428. var cw = viewport.width;
  2429. var ch = viewport.height;
  2430. var cx = viewport.x;
  2431. var cy = viewport.y;
  2432. var viewportMatrix = Matrix.FromValues(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, zmax - zmin, 0, cx + cw / 2.0, ch / 2.0 + cy, zmin, 1);
  2433. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  2434. };
  2435. Matrix.GetAsMatrix2x2 = function (matrix) {
  2436. return new Float32Array([
  2437. matrix.m[0], matrix.m[1],
  2438. matrix.m[4], matrix.m[5]
  2439. ]);
  2440. };
  2441. Matrix.GetAsMatrix3x3 = function (matrix) {
  2442. return new Float32Array([
  2443. matrix.m[0], matrix.m[1], matrix.m[2],
  2444. matrix.m[4], matrix.m[5], matrix.m[6],
  2445. matrix.m[8], matrix.m[9], matrix.m[10]
  2446. ]);
  2447. };
  2448. Matrix.Transpose = function (matrix) {
  2449. var result = new Matrix();
  2450. result.m[0] = matrix.m[0];
  2451. result.m[1] = matrix.m[4];
  2452. result.m[2] = matrix.m[8];
  2453. result.m[3] = matrix.m[12];
  2454. result.m[4] = matrix.m[1];
  2455. result.m[5] = matrix.m[5];
  2456. result.m[6] = matrix.m[9];
  2457. result.m[7] = matrix.m[13];
  2458. result.m[8] = matrix.m[2];
  2459. result.m[9] = matrix.m[6];
  2460. result.m[10] = matrix.m[10];
  2461. result.m[11] = matrix.m[14];
  2462. result.m[12] = matrix.m[3];
  2463. result.m[13] = matrix.m[7];
  2464. result.m[14] = matrix.m[11];
  2465. result.m[15] = matrix.m[15];
  2466. return result;
  2467. };
  2468. Matrix.Reflection = function (plane) {
  2469. var matrix = new Matrix();
  2470. Matrix.ReflectionToRef(plane, matrix);
  2471. return matrix;
  2472. };
  2473. Matrix.ReflectionToRef = function (plane, result) {
  2474. plane.normalize();
  2475. var x = plane.normal.x;
  2476. var y = plane.normal.y;
  2477. var z = plane.normal.z;
  2478. var temp = -2 * x;
  2479. var temp2 = -2 * y;
  2480. var temp3 = -2 * z;
  2481. result.m[0] = (temp * x) + 1;
  2482. result.m[1] = temp2 * x;
  2483. result.m[2] = temp3 * x;
  2484. result.m[3] = 0.0;
  2485. result.m[4] = temp * y;
  2486. result.m[5] = (temp2 * y) + 1;
  2487. result.m[6] = temp3 * y;
  2488. result.m[7] = 0.0;
  2489. result.m[8] = temp * z;
  2490. result.m[9] = temp2 * z;
  2491. result.m[10] = (temp3 * z) + 1;
  2492. result.m[11] = 0.0;
  2493. result.m[12] = temp * plane.d;
  2494. result.m[13] = temp2 * plane.d;
  2495. result.m[14] = temp3 * plane.d;
  2496. result.m[15] = 1.0;
  2497. };
  2498. Matrix._tempQuaternion = new Quaternion();
  2499. Matrix._xAxis = Vector3.Zero();
  2500. Matrix._yAxis = Vector3.Zero();
  2501. Matrix._zAxis = Vector3.Zero();
  2502. return Matrix;
  2503. }());
  2504. BABYLON.Matrix = Matrix;
  2505. var Plane = (function () {
  2506. function Plane(a, b, c, d) {
  2507. this.normal = new Vector3(a, b, c);
  2508. this.d = d;
  2509. }
  2510. Plane.prototype.asArray = function () {
  2511. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  2512. };
  2513. // Methods
  2514. Plane.prototype.clone = function () {
  2515. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  2516. };
  2517. Plane.prototype.getClassName = function () {
  2518. return "Plane";
  2519. };
  2520. Plane.prototype.getHashCode = function () {
  2521. var hash = this.normal.getHashCode();
  2522. hash = (hash * 397) ^ (this.d || 0);
  2523. return hash;
  2524. };
  2525. Plane.prototype.normalize = function () {
  2526. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  2527. var magnitude = 0;
  2528. if (norm !== 0) {
  2529. magnitude = 1.0 / norm;
  2530. }
  2531. this.normal.x *= magnitude;
  2532. this.normal.y *= magnitude;
  2533. this.normal.z *= magnitude;
  2534. this.d *= magnitude;
  2535. return this;
  2536. };
  2537. Plane.prototype.transform = function (transformation) {
  2538. var transposedMatrix = Matrix.Transpose(transformation);
  2539. var x = this.normal.x;
  2540. var y = this.normal.y;
  2541. var z = this.normal.z;
  2542. var d = this.d;
  2543. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  2544. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  2545. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  2546. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  2547. return new Plane(normalX, normalY, normalZ, finalD);
  2548. };
  2549. Plane.prototype.dotCoordinate = function (point) {
  2550. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  2551. };
  2552. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  2553. var x1 = point2.x - point1.x;
  2554. var y1 = point2.y - point1.y;
  2555. var z1 = point2.z - point1.z;
  2556. var x2 = point3.x - point1.x;
  2557. var y2 = point3.y - point1.y;
  2558. var z2 = point3.z - point1.z;
  2559. var yz = (y1 * z2) - (z1 * y2);
  2560. var xz = (z1 * x2) - (x1 * z2);
  2561. var xy = (x1 * y2) - (y1 * x2);
  2562. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  2563. var invPyth;
  2564. if (pyth !== 0) {
  2565. invPyth = 1.0 / pyth;
  2566. }
  2567. else {
  2568. invPyth = 0;
  2569. }
  2570. this.normal.x = yz * invPyth;
  2571. this.normal.y = xz * invPyth;
  2572. this.normal.z = xy * invPyth;
  2573. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  2574. return this;
  2575. };
  2576. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  2577. var dot = Vector3.Dot(this.normal, direction);
  2578. return (dot <= epsilon);
  2579. };
  2580. Plane.prototype.signedDistanceTo = function (point) {
  2581. return Vector3.Dot(point, this.normal) + this.d;
  2582. };
  2583. // Statics
  2584. Plane.FromArray = function (array) {
  2585. return new Plane(array[0], array[1], array[2], array[3]);
  2586. };
  2587. Plane.FromPoints = function (point1, point2, point3) {
  2588. var result = new Plane(0, 0, 0, 0);
  2589. result.copyFromPoints(point1, point2, point3);
  2590. return result;
  2591. };
  2592. Plane.FromPositionAndNormal = function (origin, normal) {
  2593. var result = new Plane(0, 0, 0, 0);
  2594. normal.normalize();
  2595. result.normal = normal;
  2596. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2597. return result;
  2598. };
  2599. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  2600. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2601. return Vector3.Dot(point, normal) + d;
  2602. };
  2603. return Plane;
  2604. }());
  2605. BABYLON.Plane = Plane;
  2606. var Viewport = (function () {
  2607. function Viewport(x, y, width, height) {
  2608. this.x = x;
  2609. this.y = y;
  2610. this.width = width;
  2611. this.height = height;
  2612. }
  2613. Viewport.prototype.toGlobal = function (renderWidth, renderHeight) {
  2614. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  2615. };
  2616. return Viewport;
  2617. }());
  2618. BABYLON.Viewport = Viewport;
  2619. var Frustum = (function () {
  2620. function Frustum() {
  2621. }
  2622. Frustum.GetPlanes = function (transform) {
  2623. var frustumPlanes = [];
  2624. for (var index = 0; index < 6; index++) {
  2625. frustumPlanes.push(new Plane(0, 0, 0, 0));
  2626. }
  2627. Frustum.GetPlanesToRef(transform, frustumPlanes);
  2628. return frustumPlanes;
  2629. };
  2630. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  2631. // Near
  2632. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  2633. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  2634. frustumPlanes[0].normal.z = transform.m[11] + transform.m[10];
  2635. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  2636. frustumPlanes[0].normalize();
  2637. // Far
  2638. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  2639. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  2640. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  2641. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  2642. frustumPlanes[1].normalize();
  2643. // Left
  2644. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  2645. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  2646. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  2647. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  2648. frustumPlanes[2].normalize();
  2649. // Right
  2650. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  2651. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  2652. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  2653. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  2654. frustumPlanes[3].normalize();
  2655. // Top
  2656. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  2657. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  2658. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  2659. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  2660. frustumPlanes[4].normalize();
  2661. // Bottom
  2662. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  2663. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  2664. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  2665. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  2666. frustumPlanes[5].normalize();
  2667. };
  2668. return Frustum;
  2669. }());
  2670. BABYLON.Frustum = Frustum;
  2671. (function (Space) {
  2672. Space[Space["LOCAL"] = 0] = "LOCAL";
  2673. Space[Space["WORLD"] = 1] = "WORLD";
  2674. })(BABYLON.Space || (BABYLON.Space = {}));
  2675. var Space = BABYLON.Space;
  2676. var Axis = (function () {
  2677. function Axis() {
  2678. }
  2679. Axis.X = new Vector3(1, 0, 0);
  2680. Axis.Y = new Vector3(0, 1, 0);
  2681. Axis.Z = new Vector3(0, 0, 1);
  2682. return Axis;
  2683. }());
  2684. BABYLON.Axis = Axis;
  2685. ;
  2686. var BezierCurve = (function () {
  2687. function BezierCurve() {
  2688. }
  2689. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  2690. // Extract X (which is equal to time here)
  2691. var f0 = 1 - 3 * x2 + 3 * x1;
  2692. var f1 = 3 * x2 - 6 * x1;
  2693. var f2 = 3 * x1;
  2694. var refinedT = t;
  2695. for (var i = 0; i < 5; i++) {
  2696. var refinedT2 = refinedT * refinedT;
  2697. var refinedT3 = refinedT2 * refinedT;
  2698. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  2699. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  2700. refinedT -= (x - t) * slope;
  2701. refinedT = Math.min(1, Math.max(0, refinedT));
  2702. }
  2703. // Resolve cubic bezier for the given x
  2704. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  2705. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  2706. Math.pow(refinedT, 3);
  2707. };
  2708. return BezierCurve;
  2709. }());
  2710. BABYLON.BezierCurve = BezierCurve;
  2711. (function (Orientation) {
  2712. Orientation[Orientation["CW"] = 0] = "CW";
  2713. Orientation[Orientation["CCW"] = 1] = "CCW";
  2714. })(BABYLON.Orientation || (BABYLON.Orientation = {}));
  2715. var Orientation = BABYLON.Orientation;
  2716. var Angle = (function () {
  2717. function Angle(radians) {
  2718. var _this = this;
  2719. this.degrees = function () { return _this._radians * 180 / Math.PI; };
  2720. this.radians = function () { return _this._radians; };
  2721. this._radians = radians;
  2722. if (this._radians < 0)
  2723. this._radians += (2 * Math.PI);
  2724. }
  2725. Angle.BetweenTwoPoints = function (a, b) {
  2726. var delta = b.subtract(a);
  2727. var theta = Math.atan2(delta.y, delta.x);
  2728. return new Angle(theta);
  2729. };
  2730. Angle.FromRadians = function (radians) {
  2731. return new Angle(radians);
  2732. };
  2733. Angle.FromDegrees = function (degrees) {
  2734. return new Angle(degrees * Math.PI / 180);
  2735. };
  2736. return Angle;
  2737. }());
  2738. BABYLON.Angle = Angle;
  2739. var Arc2 = (function () {
  2740. function Arc2(startPoint, midPoint, endPoint) {
  2741. this.startPoint = startPoint;
  2742. this.midPoint = midPoint;
  2743. this.endPoint = endPoint;
  2744. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  2745. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  2746. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  2747. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  2748. this.centerPoint = new Vector2((startToMid * (midPoint.y - endPoint.y) - midToEnd * (startPoint.y - midPoint.y)) / det, ((startPoint.x - midPoint.x) * midToEnd - (midPoint.x - endPoint.x) * startToMid) / det);
  2749. this.radius = this.centerPoint.subtract(this.startPoint).length();
  2750. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  2751. var a1 = this.startAngle.degrees();
  2752. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  2753. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  2754. // angles correction
  2755. if (a2 - a1 > +180.0)
  2756. a2 -= 360.0;
  2757. if (a2 - a1 < -180.0)
  2758. a2 += 360.0;
  2759. if (a3 - a2 > +180.0)
  2760. a3 -= 360.0;
  2761. if (a3 - a2 < -180.0)
  2762. a3 += 360.0;
  2763. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  2764. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  2765. }
  2766. return Arc2;
  2767. }());
  2768. BABYLON.Arc2 = Arc2;
  2769. var Path2 = (function () {
  2770. function Path2(x, y) {
  2771. this._points = new Array();
  2772. this._length = 0;
  2773. this.closed = false;
  2774. this._points.push(new Vector2(x, y));
  2775. }
  2776. Path2.prototype.addLineTo = function (x, y) {
  2777. if (closed) {
  2778. //Tools.Error("cannot add lines to closed paths");
  2779. return this;
  2780. }
  2781. var newPoint = new Vector2(x, y);
  2782. var previousPoint = this._points[this._points.length - 1];
  2783. this._points.push(newPoint);
  2784. this._length += newPoint.subtract(previousPoint).length();
  2785. return this;
  2786. };
  2787. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  2788. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  2789. if (closed) {
  2790. //Tools.Error("cannot add arcs to closed paths");
  2791. return this;
  2792. }
  2793. var startPoint = this._points[this._points.length - 1];
  2794. var midPoint = new Vector2(midX, midY);
  2795. var endPoint = new Vector2(endX, endY);
  2796. var arc = new Arc2(startPoint, midPoint, endPoint);
  2797. var increment = arc.angle.radians() / numberOfSegments;
  2798. if (arc.orientation === Orientation.CW)
  2799. increment *= -1;
  2800. var currentAngle = arc.startAngle.radians() + increment;
  2801. for (var i = 0; i < numberOfSegments; i++) {
  2802. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  2803. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  2804. this.addLineTo(x, y);
  2805. currentAngle += increment;
  2806. }
  2807. return this;
  2808. };
  2809. Path2.prototype.close = function () {
  2810. this.closed = true;
  2811. return this;
  2812. };
  2813. Path2.prototype.length = function () {
  2814. var result = this._length;
  2815. if (!this.closed) {
  2816. var lastPoint = this._points[this._points.length - 1];
  2817. var firstPoint = this._points[0];
  2818. result += (firstPoint.subtract(lastPoint).length());
  2819. }
  2820. return result;
  2821. };
  2822. Path2.prototype.getPoints = function () {
  2823. return this._points;
  2824. };
  2825. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  2826. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  2827. //Tools.Error("normalized length position should be between 0 and 1.");
  2828. return Vector2.Zero();
  2829. }
  2830. var lengthPosition = normalizedLengthPosition * this.length();
  2831. var previousOffset = 0;
  2832. for (var i = 0; i < this._points.length; i++) {
  2833. var j = (i + 1) % this._points.length;
  2834. var a = this._points[i];
  2835. var b = this._points[j];
  2836. var bToA = b.subtract(a);
  2837. var nextOffset = (bToA.length() + previousOffset);
  2838. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  2839. var dir = bToA.normalize();
  2840. var localOffset = lengthPosition - previousOffset;
  2841. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  2842. }
  2843. previousOffset = nextOffset;
  2844. }
  2845. //Tools.Error("internal error");
  2846. return Vector2.Zero();
  2847. };
  2848. Path2.StartingAt = function (x, y) {
  2849. return new Path2(x, y);
  2850. };
  2851. return Path2;
  2852. }());
  2853. BABYLON.Path2 = Path2;
  2854. var Path3D = (function () {
  2855. /**
  2856. * new Path3D(path, normal, raw)
  2857. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  2858. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  2859. * path : an array of Vector3, the curve axis of the Path3D
  2860. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  2861. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  2862. */
  2863. function Path3D(path, firstNormal, raw) {
  2864. this.path = path;
  2865. this._curve = new Array();
  2866. this._distances = new Array();
  2867. this._tangents = new Array();
  2868. this._normals = new Array();
  2869. this._binormals = new Array();
  2870. for (var p = 0; p < path.length; p++) {
  2871. this._curve[p] = path[p].clone(); // hard copy
  2872. }
  2873. this._raw = raw || false;
  2874. this._compute(firstNormal);
  2875. }
  2876. /**
  2877. * Returns the Path3D array of successive Vector3 designing its curve.
  2878. */
  2879. Path3D.prototype.getCurve = function () {
  2880. return this._curve;
  2881. };
  2882. /**
  2883. * Returns an array populated with tangent vectors on each Path3D curve point.
  2884. */
  2885. Path3D.prototype.getTangents = function () {
  2886. return this._tangents;
  2887. };
  2888. /**
  2889. * Returns an array populated with normal vectors on each Path3D curve point.
  2890. */
  2891. Path3D.prototype.getNormals = function () {
  2892. return this._normals;
  2893. };
  2894. /**
  2895. * Returns an array populated with binormal vectors on each Path3D curve point.
  2896. */
  2897. Path3D.prototype.getBinormals = function () {
  2898. return this._binormals;
  2899. };
  2900. /**
  2901. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  2902. */
  2903. Path3D.prototype.getDistances = function () {
  2904. return this._distances;
  2905. };
  2906. /**
  2907. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  2908. * Returns the same object updated.
  2909. */
  2910. Path3D.prototype.update = function (path, firstNormal) {
  2911. for (var p = 0; p < path.length; p++) {
  2912. this._curve[p].x = path[p].x;
  2913. this._curve[p].y = path[p].y;
  2914. this._curve[p].z = path[p].z;
  2915. }
  2916. this._compute(firstNormal);
  2917. return this;
  2918. };
  2919. // private function compute() : computes tangents, normals and binormals
  2920. Path3D.prototype._compute = function (firstNormal) {
  2921. var l = this._curve.length;
  2922. // first and last tangents
  2923. this._tangents[0] = this._getFirstNonNullVector(0);
  2924. if (!this._raw) {
  2925. this._tangents[0].normalize();
  2926. }
  2927. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  2928. if (!this._raw) {
  2929. this._tangents[l - 1].normalize();
  2930. }
  2931. // normals and binormals at first point : arbitrary vector with _normalVector()
  2932. var tg0 = this._tangents[0];
  2933. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  2934. this._normals[0] = pp0;
  2935. if (!this._raw) {
  2936. this._normals[0].normalize();
  2937. }
  2938. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  2939. if (!this._raw) {
  2940. this._binormals[0].normalize();
  2941. }
  2942. this._distances[0] = 0.0;
  2943. // normals and binormals : next points
  2944. var prev; // previous vector (segment)
  2945. var cur; // current vector (segment)
  2946. var curTang; // current tangent
  2947. // previous normal
  2948. var prevBinor; // previous binormal
  2949. for (var i = 1; i < l; i++) {
  2950. // tangents
  2951. prev = this._getLastNonNullVector(i);
  2952. if (i < l - 1) {
  2953. cur = this._getFirstNonNullVector(i);
  2954. this._tangents[i] = prev.add(cur);
  2955. this._tangents[i].normalize();
  2956. }
  2957. this._distances[i] = this._distances[i - 1] + prev.length();
  2958. // normals and binormals
  2959. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  2960. curTang = this._tangents[i];
  2961. prevBinor = this._binormals[i - 1];
  2962. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  2963. if (!this._raw) {
  2964. this._normals[i].normalize();
  2965. }
  2966. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  2967. if (!this._raw) {
  2968. this._binormals[i].normalize();
  2969. }
  2970. }
  2971. };
  2972. // private function getFirstNonNullVector(index)
  2973. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  2974. Path3D.prototype._getFirstNonNullVector = function (index) {
  2975. var i = 1;
  2976. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  2977. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  2978. i++;
  2979. nNVector = this._curve[index + i].subtract(this._curve[index]);
  2980. }
  2981. return nNVector;
  2982. };
  2983. // private function getLastNonNullVector(index)
  2984. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  2985. Path3D.prototype._getLastNonNullVector = function (index) {
  2986. var i = 1;
  2987. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  2988. while (nLVector.length() === 0 && index > i + 1) {
  2989. i++;
  2990. nLVector = this._curve[index].subtract(this._curve[index - i]);
  2991. }
  2992. return nLVector;
  2993. };
  2994. // private function normalVector(v0, vt, va) :
  2995. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  2996. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  2997. Path3D.prototype._normalVector = function (v0, vt, va) {
  2998. var normal0;
  2999. var tgl = vt.length();
  3000. if (tgl === 0.0) {
  3001. tgl = 1.0;
  3002. }
  3003. if (va === undefined || va === null) {
  3004. var point;
  3005. if (!MathTools.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) {
  3006. point = new Vector3(0.0, -1.0, 0.0);
  3007. }
  3008. else if (!MathTools.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  3009. point = new Vector3(1.0, 0.0, 0.0);
  3010. }
  3011. else if (!MathTools.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  3012. point = new Vector3(0.0, 0.0, 1.0);
  3013. }
  3014. normal0 = Vector3.Cross(vt, point);
  3015. }
  3016. else {
  3017. normal0 = Vector3.Cross(vt, va);
  3018. Vector3.CrossToRef(normal0, vt, normal0);
  3019. }
  3020. normal0.normalize();
  3021. return normal0;
  3022. };
  3023. return Path3D;
  3024. }());
  3025. BABYLON.Path3D = Path3D;
  3026. var Curve3 = (function () {
  3027. /**
  3028. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  3029. * A Curve3 is designed from a series of successive Vector3.
  3030. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  3031. */
  3032. function Curve3(points) {
  3033. this._length = 0.0;
  3034. this._points = points;
  3035. this._length = this._computeLength(points);
  3036. }
  3037. /**
  3038. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  3039. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  3040. * @param v1 (Vector3) the control point
  3041. * @param v2 (Vector3) the end point of the Quadratic Bezier
  3042. * @param nbPoints (integer) the wanted number of points in the curve
  3043. */
  3044. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  3045. nbPoints = nbPoints > 2 ? nbPoints : 3;
  3046. var bez = new Array();
  3047. var equation = function (t, val0, val1, val2) {
  3048. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  3049. return res;
  3050. };
  3051. for (var i = 0; i <= nbPoints; i++) {
  3052. bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x), equation(i / nbPoints, v0.y, v1.y, v2.y), equation(i / nbPoints, v0.z, v1.z, v2.z)));
  3053. }
  3054. return new Curve3(bez);
  3055. };
  3056. /**
  3057. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  3058. * @param v0 (Vector3) the origin point of the Cubic Bezier
  3059. * @param v1 (Vector3) the first control point
  3060. * @param v2 (Vector3) the second control point
  3061. * @param v3 (Vector3) the end point of the Cubic Bezier
  3062. * @param nbPoints (integer) the wanted number of points in the curve
  3063. */
  3064. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  3065. nbPoints = nbPoints > 3 ? nbPoints : 4;
  3066. var bez = new Array();
  3067. var equation = function (t, val0, val1, val2, val3) {
  3068. var res = (1.0 - t) * (1.0 - t) * (1.0 - t) * val0 + 3.0 * t * (1.0 - t) * (1.0 - t) * val1 + 3.0 * t * t * (1.0 - t) * val2 + t * t * t * val3;
  3069. return res;
  3070. };
  3071. for (var i = 0; i <= nbPoints; i++) {
  3072. bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x, v3.x), equation(i / nbPoints, v0.y, v1.y, v2.y, v3.y), equation(i / nbPoints, v0.z, v1.z, v2.z, v3.z)));
  3073. }
  3074. return new Curve3(bez);
  3075. };
  3076. /**
  3077. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  3078. * @param p1 (Vector3) the origin point of the Hermite Spline
  3079. * @param t1 (Vector3) the tangent vector at the origin point
  3080. * @param p2 (Vector3) the end point of the Hermite Spline
  3081. * @param t2 (Vector3) the tangent vector at the end point
  3082. * @param nbPoints (integer) the wanted number of points in the curve
  3083. */
  3084. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  3085. var hermite = new Array();
  3086. var step = 1.0 / nbPoints;
  3087. for (var i = 0; i <= nbPoints; i++) {
  3088. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  3089. }
  3090. return new Curve3(hermite);
  3091. };
  3092. /**
  3093. * Returns the Curve3 stored array of successive Vector3
  3094. */
  3095. Curve3.prototype.getPoints = function () {
  3096. return this._points;
  3097. };
  3098. /**
  3099. * Returns the computed length (float) of the curve.
  3100. */
  3101. Curve3.prototype.length = function () {
  3102. return this._length;
  3103. };
  3104. /**
  3105. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  3106. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  3107. * curveA and curveB keep unchanged.
  3108. */
  3109. Curve3.prototype.continue = function (curve) {
  3110. var lastPoint = this._points[this._points.length - 1];
  3111. var continuedPoints = this._points.slice();
  3112. var curvePoints = curve.getPoints();
  3113. for (var i = 1; i < curvePoints.length; i++) {
  3114. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  3115. }
  3116. var continuedCurve = new Curve3(continuedPoints);
  3117. return continuedCurve;
  3118. };
  3119. Curve3.prototype._computeLength = function (path) {
  3120. var l = 0;
  3121. for (var i = 1; i < path.length; i++) {
  3122. l += (path[i].subtract(path[i - 1])).length();
  3123. }
  3124. return l;
  3125. };
  3126. return Curve3;
  3127. }());
  3128. BABYLON.Curve3 = Curve3;
  3129. // SphericalHarmonics
  3130. var SphericalHarmonics = (function () {
  3131. function SphericalHarmonics() {
  3132. this.L00 = Vector3.Zero();
  3133. this.L1_1 = Vector3.Zero();
  3134. this.L10 = Vector3.Zero();
  3135. this.L11 = Vector3.Zero();
  3136. this.L2_2 = Vector3.Zero();
  3137. this.L2_1 = Vector3.Zero();
  3138. this.L20 = Vector3.Zero();
  3139. this.L21 = Vector3.Zero();
  3140. this.L22 = Vector3.Zero();
  3141. }
  3142. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  3143. var colorVector = new Vector3(color.r, color.g, color.b);
  3144. var c = colorVector.scale(deltaSolidAngle);
  3145. this.L00 = this.L00.add(c.scale(0.282095));
  3146. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  3147. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  3148. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  3149. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  3150. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  3151. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  3152. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  3153. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  3154. };
  3155. SphericalHarmonics.prototype.scale = function (scale) {
  3156. this.L00 = this.L00.scale(scale);
  3157. this.L1_1 = this.L1_1.scale(scale);
  3158. this.L10 = this.L10.scale(scale);
  3159. this.L11 = this.L11.scale(scale);
  3160. this.L2_2 = this.L2_2.scale(scale);
  3161. this.L2_1 = this.L2_1.scale(scale);
  3162. this.L20 = this.L20.scale(scale);
  3163. this.L21 = this.L21.scale(scale);
  3164. this.L22 = this.L22.scale(scale);
  3165. };
  3166. return SphericalHarmonics;
  3167. }());
  3168. BABYLON.SphericalHarmonics = SphericalHarmonics;
  3169. // SphericalPolynomial
  3170. var SphericalPolynomial = (function () {
  3171. function SphericalPolynomial() {
  3172. this.x = Vector3.Zero();
  3173. this.y = Vector3.Zero();
  3174. this.z = Vector3.Zero();
  3175. this.xx = Vector3.Zero();
  3176. this.yy = Vector3.Zero();
  3177. this.zz = Vector3.Zero();
  3178. this.xy = Vector3.Zero();
  3179. this.yz = Vector3.Zero();
  3180. this.zx = Vector3.Zero();
  3181. }
  3182. SphericalPolynomial.prototype.addAmbient = function (color) {
  3183. var colorVector = new Vector3(color.r, color.g, color.b);
  3184. this.xx = this.xx.add(colorVector);
  3185. this.yy = this.yy.add(colorVector);
  3186. this.zz = this.zz.add(colorVector);
  3187. };
  3188. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  3189. var result = new SphericalPolynomial();
  3190. result.x = harmonics.L11.scale(1.02333);
  3191. result.y = harmonics.L1_1.scale(1.02333);
  3192. result.z = harmonics.L10.scale(1.02333);
  3193. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  3194. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  3195. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  3196. result.yz = harmonics.L2_1.scale(0.858086);
  3197. result.zx = harmonics.L21.scale(0.858086);
  3198. result.xy = harmonics.L2_2.scale(0.858086);
  3199. return result;
  3200. };
  3201. return SphericalPolynomial;
  3202. }());
  3203. BABYLON.SphericalPolynomial = SphericalPolynomial;
  3204. // Vertex formats
  3205. var PositionNormalVertex = (function () {
  3206. function PositionNormalVertex(position, normal) {
  3207. if (position === void 0) { position = Vector3.Zero(); }
  3208. if (normal === void 0) { normal = Vector3.Up(); }
  3209. this.position = position;
  3210. this.normal = normal;
  3211. }
  3212. PositionNormalVertex.prototype.clone = function () {
  3213. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  3214. };
  3215. return PositionNormalVertex;
  3216. }());
  3217. BABYLON.PositionNormalVertex = PositionNormalVertex;
  3218. var PositionNormalTextureVertex = (function () {
  3219. function PositionNormalTextureVertex(position, normal, uv) {
  3220. if (position === void 0) { position = Vector3.Zero(); }
  3221. if (normal === void 0) { normal = Vector3.Up(); }
  3222. if (uv === void 0) { uv = Vector2.Zero(); }
  3223. this.position = position;
  3224. this.normal = normal;
  3225. this.uv = uv;
  3226. }
  3227. PositionNormalTextureVertex.prototype.clone = function () {
  3228. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  3229. };
  3230. return PositionNormalTextureVertex;
  3231. }());
  3232. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  3233. // Temporary pre-allocated objects for engine internal use
  3234. // usage in any internal function :
  3235. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  3236. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  3237. var Tmp = (function () {
  3238. function Tmp() {
  3239. }
  3240. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  3241. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  3242. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  3243. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  3244. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  3245. Tmp.Quaternion = [new Quaternion(0, 0, 0, 0)]; // 1 temp Quaternion at once should be enough
  3246. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  3247. Matrix.Zero(), Matrix.Zero(),
  3248. Matrix.Zero(), Matrix.Zero(),
  3249. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  3250. return Tmp;
  3251. }());
  3252. BABYLON.Tmp = Tmp;
  3253. })(BABYLON || (BABYLON = {}));
  3254. var BABYLON;
  3255. (function (BABYLON) {
  3256. function generateSerializableMember(type, sourceName) {
  3257. return function (target, propertyKey) {
  3258. if (!target.__serializableMembers) {
  3259. target.__serializableMembers = {};
  3260. }
  3261. if (!target.__serializableMembers[propertyKey]) {
  3262. target.__serializableMembers[propertyKey] = { type: type, sourceName: sourceName };
  3263. }
  3264. };
  3265. }
  3266. function serialize(sourceName) {
  3267. return generateSerializableMember(0, sourceName); // value member
  3268. }
  3269. BABYLON.serialize = serialize;
  3270. function serializeAsTexture(sourceName) {
  3271. return generateSerializableMember(1, sourceName); // texture member
  3272. }
  3273. BABYLON.serializeAsTexture = serializeAsTexture;
  3274. function serializeAsColor3(sourceName) {
  3275. return generateSerializableMember(2, sourceName); // color3 member
  3276. }
  3277. BABYLON.serializeAsColor3 = serializeAsColor3;
  3278. function serializeAsFresnelParameters(sourceName) {
  3279. return generateSerializableMember(3, sourceName); // fresnel parameters member
  3280. }
  3281. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  3282. function serializeAsVector2(sourceName) {
  3283. return generateSerializableMember(4, sourceName); // vector2 member
  3284. }
  3285. BABYLON.serializeAsVector2 = serializeAsVector2;
  3286. function serializeAsVector3(sourceName) {
  3287. return generateSerializableMember(5, sourceName); // vector3 member
  3288. }
  3289. BABYLON.serializeAsVector3 = serializeAsVector3;
  3290. function serializeAsMeshReference(sourceName) {
  3291. return generateSerializableMember(6, sourceName); // mesh reference member
  3292. }
  3293. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  3294. function serializeAsColorCurves(sourceName) {
  3295. return generateSerializableMember(7, sourceName); // color curves
  3296. }
  3297. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  3298. var SerializationHelper = (function () {
  3299. function SerializationHelper() {
  3300. }
  3301. SerializationHelper.Serialize = function (entity, serializationObject) {
  3302. if (!serializationObject) {
  3303. serializationObject = {};
  3304. }
  3305. // Tags
  3306. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  3307. // Properties
  3308. for (var property in entity.__serializableMembers) {
  3309. var propertyDescriptor = entity.__serializableMembers[property];
  3310. var targetPropertyName = propertyDescriptor.sourceName || property;
  3311. var propertyType = propertyDescriptor.type;
  3312. var sourceProperty = entity[property];
  3313. if (sourceProperty !== undefined && sourceProperty !== null) {
  3314. switch (propertyType) {
  3315. case 0:
  3316. serializationObject[targetPropertyName] = sourceProperty;
  3317. break;
  3318. case 1:
  3319. serializationObject[targetPropertyName] = sourceProperty.serialize();
  3320. break;
  3321. case 2:
  3322. serializationObject[targetPropertyName] = sourceProperty.asArray();
  3323. break;
  3324. case 3:
  3325. serializationObject[targetPropertyName] = sourceProperty.serialize();
  3326. break;
  3327. case 4:
  3328. serializationObject[targetPropertyName] = sourceProperty.asArray();
  3329. break;
  3330. case 5:
  3331. serializationObject[targetPropertyName] = sourceProperty.asArray();
  3332. break;
  3333. case 6:
  3334. serializationObject[targetPropertyName] = sourceProperty.id;
  3335. break;
  3336. case 7:
  3337. serializationObject[targetPropertyName] = sourceProperty.serialize();
  3338. break;
  3339. }
  3340. }
  3341. }
  3342. return serializationObject;
  3343. };
  3344. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  3345. var destination = creationFunction();
  3346. // Tags
  3347. BABYLON.Tags.AddTagsTo(destination, source.tags);
  3348. // Properties
  3349. for (var property in destination.__serializableMembers) {
  3350. var propertyDescriptor = destination.__serializableMembers[property];
  3351. var sourceProperty = source[propertyDescriptor.sourceName || property];
  3352. var propertyType = propertyDescriptor.type;
  3353. if (sourceProperty !== undefined && sourceProperty !== null) {
  3354. switch (propertyType) {
  3355. case 0:
  3356. destination[property] = sourceProperty;
  3357. break;
  3358. case 1:
  3359. destination[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  3360. break;
  3361. case 2:
  3362. destination[property] = BABYLON.Color3.FromArray(sourceProperty);
  3363. break;
  3364. case 3:
  3365. destination[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  3366. break;
  3367. case 4:
  3368. destination[property] = BABYLON.Vector2.FromArray(sourceProperty);
  3369. break;
  3370. case 5:
  3371. destination[property] = BABYLON.Vector3.FromArray(sourceProperty);
  3372. break;
  3373. case 6:
  3374. destination[property] = scene.getLastMeshByID(sourceProperty);
  3375. break;
  3376. case 7:
  3377. destination[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  3378. break;
  3379. }
  3380. }
  3381. }
  3382. return destination;
  3383. };
  3384. SerializationHelper.Clone = function (creationFunction, source) {
  3385. var destination = creationFunction();
  3386. // Tags
  3387. BABYLON.Tags.AddTagsTo(destination, source.tags);
  3388. // Properties
  3389. for (var property in destination.__serializableMembers) {
  3390. var propertyDescriptor = destination.__serializableMembers[property];
  3391. var sourceProperty = source[property];
  3392. var propertyType = propertyDescriptor.type;
  3393. if (sourceProperty !== undefined && sourceProperty !== null) {
  3394. switch (propertyType) {
  3395. case 0: // Value
  3396. case 6:
  3397. destination[property] = sourceProperty;
  3398. break;
  3399. case 1: // Texture
  3400. case 2: // Color3
  3401. case 3: // FresnelParameters
  3402. case 4: // Vector2
  3403. case 5: // Vector3
  3404. case 7:
  3405. destination[property] = sourceProperty.clone();
  3406. break;
  3407. }
  3408. }
  3409. }
  3410. return destination;
  3411. };
  3412. return SerializationHelper;
  3413. }());
  3414. BABYLON.SerializationHelper = SerializationHelper;
  3415. })(BABYLON || (BABYLON = {}));
  3416. var BABYLON;
  3417. (function (BABYLON) {
  3418. /**
  3419. * A class serves as a medium between the observable and its observers
  3420. */
  3421. var EventState = (function () {
  3422. /**
  3423. * If the callback of a given Observer set skipNextObservers to true the following observers will be ignored
  3424. */
  3425. function EventState(mask, skipNextObservers) {
  3426. if (skipNextObservers === void 0) { skipNextObservers = false; }
  3427. this.initalize(mask, skipNextObservers);
  3428. }
  3429. EventState.prototype.initalize = function (mask, skipNextObservers) {
  3430. if (skipNextObservers === void 0) { skipNextObservers = false; }
  3431. this.mask = mask;
  3432. this.skipNextObservers = skipNextObservers;
  3433. return this;
  3434. };
  3435. return EventState;
  3436. }());
  3437. BABYLON.EventState = EventState;
  3438. /**
  3439. * Represent an Observer registered to a given Observable object.
  3440. */
  3441. var Observer = (function () {
  3442. function Observer(callback, mask) {
  3443. this.callback = callback;
  3444. this.mask = mask;
  3445. }
  3446. return Observer;
  3447. }());
  3448. BABYLON.Observer = Observer;
  3449. /**
  3450. * The Observable class is a simple implementation of the Observable pattern.
  3451. * There's one slight particularity though: a given Observable can notify its observer using a particular mask value, only the Observers registered with this mask value will be notified.
  3452. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  3453. * For instance you may have a given Observable that have four different types of notifications: Move (mask = 0x01), Stop (mask = 0x02), Turn Right (mask = 0X04), Turn Left (mask = 0X08).
  3454. * A given observer can register itself with only Move and Stop (mask = 0x03), then it will only be notified when one of these two occurs and will never be for Turn Left/Right.
  3455. */
  3456. var Observable = (function () {
  3457. function Observable() {
  3458. this._observers = new Array();
  3459. this._eventState = new EventState(0);
  3460. }
  3461. /**
  3462. * Create a new Observer with the specified callback
  3463. * @param callback the callback that will be executed for that Observer
  3464. * @param mask the mask used to filter observers
  3465. * @param insertFirst if true the callback will be inserted at the first position, hence executed before the others ones. If false (default behavior) the callback will be inserted at the last position, executed after all the others already present.
  3466. */
  3467. Observable.prototype.add = function (callback, mask, insertFirst) {
  3468. if (mask === void 0) { mask = -1; }
  3469. if (insertFirst === void 0) { insertFirst = false; }
  3470. if (!callback) {
  3471. return null;
  3472. }
  3473. var observer = new Observer(callback, mask);
  3474. if (insertFirst) {
  3475. this._observers.unshift(observer);
  3476. }
  3477. else {
  3478. this._observers.push(observer);
  3479. }
  3480. return observer;
  3481. };
  3482. /**
  3483. * Remove an Observer from the Observable object
  3484. * @param observer the instance of the Observer to remove. If it doesn't belong to this Observable, false will be returned.
  3485. */
  3486. Observable.prototype.remove = function (observer) {
  3487. var index = this._observers.indexOf(observer);
  3488. if (index !== -1) {
  3489. this._observers.splice(index, 1);
  3490. return true;
  3491. }
  3492. return false;
  3493. };
  3494. /**
  3495. * Remove a callback from the Observable object
  3496. * @param callback the callback to remove. If it doesn't belong to this Observable, false will be returned.
  3497. */
  3498. Observable.prototype.removeCallback = function (callback) {
  3499. for (var index = 0; index < this._observers.length; index++) {
  3500. if (this._observers[index].callback === callback) {
  3501. this._observers.splice(index, 1);
  3502. return true;
  3503. }
  3504. }
  3505. return false;
  3506. };
  3507. /**
  3508. * Notify all Observers by calling their respective callback with the given data
  3509. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  3510. * @param eventData
  3511. * @param mask
  3512. */
  3513. Observable.prototype.notifyObservers = function (eventData, mask) {
  3514. if (mask === void 0) { mask = -1; }
  3515. var state = this._eventState;
  3516. state.mask = mask;
  3517. state.skipNextObservers = false;
  3518. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  3519. var obs = _a[_i];
  3520. if (obs.mask & mask) {
  3521. obs.callback(eventData, state);
  3522. }
  3523. if (state.skipNextObservers) {
  3524. return false;
  3525. }
  3526. }
  3527. return true;
  3528. };
  3529. /**
  3530. * return true is the Observable has at least one Observer registered
  3531. */
  3532. Observable.prototype.hasObservers = function () {
  3533. return this._observers.length > 0;
  3534. };
  3535. /**
  3536. * Clear the list of observers
  3537. */
  3538. Observable.prototype.clear = function () {
  3539. this._observers = new Array();
  3540. };
  3541. /**
  3542. * Clone the current observable
  3543. */
  3544. Observable.prototype.clone = function () {
  3545. var result = new Observable();
  3546. result._observers = this._observers.slice(0);
  3547. return result;
  3548. };
  3549. return Observable;
  3550. }());
  3551. BABYLON.Observable = Observable;
  3552. })(BABYLON || (BABYLON = {}));
  3553. var BABYLON;
  3554. (function (BABYLON) {
  3555. var Database = (function () {
  3556. function Database(urlToScene, callbackManifestChecked) {
  3557. // Handling various flavors of prefixed version of IndexedDB
  3558. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  3559. this.callbackManifestChecked = callbackManifestChecked;
  3560. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  3561. this.db = null;
  3562. this.enableSceneOffline = false;
  3563. this.enableTexturesOffline = false;
  3564. this.manifestVersionFound = 0;
  3565. this.mustUpdateRessources = false;
  3566. this.hasReachedQuota = false;
  3567. if (!Database.IDBStorageEnabled) {
  3568. this.callbackManifestChecked(true);
  3569. }
  3570. else {
  3571. this.checkManifestFile();
  3572. }
  3573. }
  3574. Database.prototype.checkManifestFile = function () {
  3575. var _this = this;
  3576. function noManifestFile() {
  3577. that.enableSceneOffline = false;
  3578. that.enableTexturesOffline = false;
  3579. that.callbackManifestChecked(false);
  3580. }
  3581. var that = this;
  3582. var timeStampUsed = false;
  3583. var manifestURL = this.currentSceneUrl + ".manifest";
  3584. var xhr = new XMLHttpRequest();
  3585. if (navigator.onLine) {
  3586. // Adding a timestamp to by-pass browsers' cache
  3587. timeStampUsed = true;
  3588. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  3589. }
  3590. xhr.open("GET", manifestURL, true);
  3591. xhr.addEventListener("load", function () {
  3592. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  3593. try {
  3594. var manifestFile = JSON.parse(xhr.response);
  3595. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  3596. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  3597. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  3598. _this.manifestVersionFound = manifestFile.version;
  3599. }
  3600. if (_this.callbackManifestChecked) {
  3601. _this.callbackManifestChecked(true);
  3602. }
  3603. }
  3604. catch (ex) {
  3605. noManifestFile();
  3606. }
  3607. }
  3608. else {
  3609. noManifestFile();
  3610. }
  3611. }, false);
  3612. xhr.addEventListener("error", function (event) {
  3613. if (timeStampUsed) {
  3614. timeStampUsed = false;
  3615. // Let's retry without the timeStamp
  3616. // It could fail when coupled with HTML5 Offline API
  3617. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  3618. xhr.open("GET", retryManifestURL, true);
  3619. xhr.send();
  3620. }
  3621. else {
  3622. noManifestFile();
  3623. }
  3624. }, false);
  3625. try {
  3626. xhr.send();
  3627. }
  3628. catch (ex) {
  3629. BABYLON.Tools.Error("Error on XHR send request.");
  3630. that.callbackManifestChecked(false);
  3631. }
  3632. };
  3633. Database.prototype.openAsync = function (successCallback, errorCallback) {
  3634. var _this = this;
  3635. function handleError() {
  3636. that.isSupported = false;
  3637. if (errorCallback)
  3638. errorCallback();
  3639. }
  3640. var that = this;
  3641. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  3642. // Your browser doesn't support IndexedDB
  3643. this.isSupported = false;
  3644. if (errorCallback)
  3645. errorCallback();
  3646. }
  3647. else {
  3648. // If the DB hasn't been opened or created yet
  3649. if (!this.db) {
  3650. this.hasReachedQuota = false;
  3651. this.isSupported = true;
  3652. var request = this.idbFactory.open("babylonjs", 1);
  3653. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  3654. request.onerror = function (event) {
  3655. handleError();
  3656. };
  3657. // executes when a version change transaction cannot complete due to other active transactions
  3658. request.onblocked = function (event) {
  3659. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  3660. handleError();
  3661. };
  3662. // DB has been opened successfully
  3663. request.onsuccess = function (event) {
  3664. _this.db = request.result;
  3665. successCallback();
  3666. };
  3667. // Initialization of the DB. Creating Scenes & Textures stores
  3668. request.onupgradeneeded = function (event) {
  3669. _this.db = (event.target).result;
  3670. try {
  3671. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  3672. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  3673. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  3674. }
  3675. catch (ex) {
  3676. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  3677. handleError();
  3678. }
  3679. };
  3680. }
  3681. else {
  3682. if (successCallback)
  3683. successCallback();
  3684. }
  3685. }
  3686. };
  3687. Database.prototype.loadImageFromDB = function (url, image) {
  3688. var _this = this;
  3689. var completeURL = Database.ReturnFullUrlLocation(url);
  3690. var saveAndLoadImage = function () {
  3691. if (!_this.hasReachedQuota && _this.db !== null) {
  3692. // the texture is not yet in the DB, let's try to save it
  3693. _this._saveImageIntoDBAsync(completeURL, image);
  3694. }
  3695. else {
  3696. image.src = url;
  3697. }
  3698. };
  3699. if (!this.mustUpdateRessources) {
  3700. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  3701. }
  3702. else {
  3703. saveAndLoadImage();
  3704. }
  3705. };
  3706. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  3707. if (this.isSupported && this.db !== null) {
  3708. var texture;
  3709. var transaction = this.db.transaction(["textures"]);
  3710. transaction.onabort = function (event) {
  3711. image.src = url;
  3712. };
  3713. transaction.oncomplete = function (event) {
  3714. var blobTextureURL;
  3715. if (texture) {
  3716. var URL = window.URL || window.webkitURL;
  3717. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  3718. image.onerror = function () {
  3719. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  3720. image.src = url;
  3721. };
  3722. image.src = blobTextureURL;
  3723. }
  3724. else {
  3725. notInDBCallback();
  3726. }
  3727. };
  3728. var getRequest = transaction.objectStore("textures").get(url);
  3729. getRequest.onsuccess = function (event) {
  3730. texture = (event.target).result;
  3731. };
  3732. getRequest.onerror = function (event) {
  3733. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  3734. image.src = url;
  3735. };
  3736. }
  3737. else {
  3738. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3739. image.src = url;
  3740. }
  3741. };
  3742. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  3743. var _this = this;
  3744. if (this.isSupported) {
  3745. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  3746. var generateBlobUrl = function () {
  3747. var blobTextureURL;
  3748. if (blob) {
  3749. var URL = window.URL || window.webkitURL;
  3750. try {
  3751. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  3752. }
  3753. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  3754. catch (ex) {
  3755. blobTextureURL = URL.createObjectURL(blob);
  3756. }
  3757. }
  3758. image.src = blobTextureURL;
  3759. };
  3760. if (Database.IsUASupportingBlobStorage) {
  3761. var xhr = new XMLHttpRequest(), blob;
  3762. xhr.open("GET", url, true);
  3763. xhr.responseType = "blob";
  3764. xhr.addEventListener("load", function () {
  3765. if (xhr.status === 200) {
  3766. // Blob as response (XHR2)
  3767. blob = xhr.response;
  3768. var transaction = _this.db.transaction(["textures"], "readwrite");
  3769. // the transaction could abort because of a QuotaExceededError error
  3770. transaction.onabort = function (event) {
  3771. try {
  3772. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3773. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3774. this.hasReachedQuota = true;
  3775. }
  3776. }
  3777. catch (ex) { }
  3778. generateBlobUrl();
  3779. };
  3780. transaction.oncomplete = function (event) {
  3781. generateBlobUrl();
  3782. };
  3783. var newTexture = { textureUrl: url, data: blob };
  3784. try {
  3785. // Put the blob into the dabase
  3786. var addRequest = transaction.objectStore("textures").put(newTexture);
  3787. addRequest.onsuccess = function (event) {
  3788. };
  3789. addRequest.onerror = function (event) {
  3790. generateBlobUrl();
  3791. };
  3792. }
  3793. catch (ex) {
  3794. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  3795. if (ex.code === 25) {
  3796. Database.IsUASupportingBlobStorage = false;
  3797. }
  3798. image.src = url;
  3799. }
  3800. }
  3801. else {
  3802. image.src = url;
  3803. }
  3804. }, false);
  3805. xhr.addEventListener("error", function (event) {
  3806. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  3807. image.src = url;
  3808. }, false);
  3809. xhr.send();
  3810. }
  3811. else {
  3812. image.src = url;
  3813. }
  3814. }
  3815. else {
  3816. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3817. image.src = url;
  3818. }
  3819. };
  3820. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  3821. var _this = this;
  3822. var updateVersion = function (event) {
  3823. // the version is not yet in the DB or we need to update it
  3824. _this._saveVersionIntoDBAsync(url, versionLoaded);
  3825. };
  3826. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  3827. };
  3828. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  3829. var _this = this;
  3830. if (this.isSupported) {
  3831. var version;
  3832. try {
  3833. var transaction = this.db.transaction(["versions"]);
  3834. transaction.oncomplete = function (event) {
  3835. if (version) {
  3836. // If the version in the JSON file is > than the version in DB
  3837. if (_this.manifestVersionFound > version.data) {
  3838. _this.mustUpdateRessources = true;
  3839. updateInDBCallback();
  3840. }
  3841. else {
  3842. callback(version.data);
  3843. }
  3844. }
  3845. else {
  3846. _this.mustUpdateRessources = true;
  3847. updateInDBCallback();
  3848. }
  3849. };
  3850. transaction.onabort = function (event) {
  3851. callback(-1);
  3852. };
  3853. var getRequest = transaction.objectStore("versions").get(url);
  3854. getRequest.onsuccess = function (event) {
  3855. version = (event.target).result;
  3856. };
  3857. getRequest.onerror = function (event) {
  3858. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  3859. callback(-1);
  3860. };
  3861. }
  3862. catch (ex) {
  3863. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  3864. callback(-1);
  3865. }
  3866. }
  3867. else {
  3868. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3869. callback(-1);
  3870. }
  3871. };
  3872. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  3873. var _this = this;
  3874. if (this.isSupported && !this.hasReachedQuota) {
  3875. try {
  3876. // Open a transaction to the database
  3877. var transaction = this.db.transaction(["versions"], "readwrite");
  3878. // the transaction could abort because of a QuotaExceededError error
  3879. transaction.onabort = function (event) {
  3880. try {
  3881. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3882. _this.hasReachedQuota = true;
  3883. }
  3884. }
  3885. catch (ex) { }
  3886. callback(-1);
  3887. };
  3888. transaction.oncomplete = function (event) {
  3889. callback(_this.manifestVersionFound);
  3890. };
  3891. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  3892. // Put the scene into the database
  3893. var addRequest = transaction.objectStore("versions").put(newVersion);
  3894. addRequest.onsuccess = function (event) {
  3895. };
  3896. addRequest.onerror = function (event) {
  3897. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  3898. };
  3899. }
  3900. catch (ex) {
  3901. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  3902. callback(-1);
  3903. }
  3904. }
  3905. else {
  3906. callback(-1);
  3907. }
  3908. };
  3909. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  3910. var _this = this;
  3911. var completeUrl = Database.ReturnFullUrlLocation(url);
  3912. var saveAndLoadFile = function (event) {
  3913. // the scene is not yet in the DB, let's try to save it
  3914. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  3915. };
  3916. this._checkVersionFromDB(completeUrl, function (version) {
  3917. if (version !== -1) {
  3918. if (!_this.mustUpdateRessources) {
  3919. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  3920. }
  3921. else {
  3922. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  3923. }
  3924. }
  3925. else {
  3926. errorCallback();
  3927. }
  3928. });
  3929. };
  3930. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  3931. if (this.isSupported) {
  3932. var targetStore;
  3933. if (url.indexOf(".babylon") !== -1) {
  3934. targetStore = "scenes";
  3935. }
  3936. else {
  3937. targetStore = "textures";
  3938. }
  3939. var file;
  3940. var transaction = this.db.transaction([targetStore]);
  3941. transaction.oncomplete = function (event) {
  3942. if (file) {
  3943. callback(file.data);
  3944. }
  3945. else {
  3946. notInDBCallback();
  3947. }
  3948. };
  3949. transaction.onabort = function (event) {
  3950. notInDBCallback();
  3951. };
  3952. var getRequest = transaction.objectStore(targetStore).get(url);
  3953. getRequest.onsuccess = function (event) {
  3954. file = (event.target).result;
  3955. };
  3956. getRequest.onerror = function (event) {
  3957. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  3958. notInDBCallback();
  3959. };
  3960. }
  3961. else {
  3962. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3963. callback();
  3964. }
  3965. };
  3966. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  3967. var _this = this;
  3968. if (this.isSupported) {
  3969. var targetStore;
  3970. if (url.indexOf(".babylon") !== -1) {
  3971. targetStore = "scenes";
  3972. }
  3973. else {
  3974. targetStore = "textures";
  3975. }
  3976. // Create XHR
  3977. var xhr = new XMLHttpRequest(), fileData;
  3978. xhr.open("GET", url, true);
  3979. if (useArrayBuffer) {
  3980. xhr.responseType = "arraybuffer";
  3981. }
  3982. xhr.onprogress = progressCallback;
  3983. xhr.addEventListener("load", function () {
  3984. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  3985. // Blob as response (XHR2)
  3986. //fileData = xhr.responseText;
  3987. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  3988. if (!_this.hasReachedQuota) {
  3989. // Open a transaction to the database
  3990. var transaction = _this.db.transaction([targetStore], "readwrite");
  3991. // the transaction could abort because of a QuotaExceededError error
  3992. transaction.onabort = function (event) {
  3993. try {
  3994. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3995. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3996. this.hasReachedQuota = true;
  3997. }
  3998. }
  3999. catch (ex) { }
  4000. callback(fileData);
  4001. };
  4002. transaction.oncomplete = function (event) {
  4003. callback(fileData);
  4004. };
  4005. var newFile;
  4006. if (targetStore === "scenes") {
  4007. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  4008. }
  4009. else {
  4010. newFile = { textureUrl: url, data: fileData };
  4011. }
  4012. try {
  4013. // Put the scene into the database
  4014. var addRequest = transaction.objectStore(targetStore).put(newFile);
  4015. addRequest.onsuccess = function (event) {
  4016. };
  4017. addRequest.onerror = function (event) {
  4018. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  4019. };
  4020. }
  4021. catch (ex) {
  4022. callback(fileData);
  4023. }
  4024. }
  4025. else {
  4026. callback(fileData);
  4027. }
  4028. }
  4029. else {
  4030. callback();
  4031. }
  4032. }, false);
  4033. xhr.addEventListener("error", function (event) {
  4034. BABYLON.Tools.Error("error on XHR request.");
  4035. callback();
  4036. }, false);
  4037. xhr.send();
  4038. }
  4039. else {
  4040. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  4041. callback();
  4042. }
  4043. };
  4044. Database.IsUASupportingBlobStorage = true;
  4045. Database.IDBStorageEnabled = true;
  4046. Database.parseURL = function (url) {
  4047. var a = document.createElement('a');
  4048. a.href = url;
  4049. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  4050. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  4051. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  4052. return absLocation;
  4053. };
  4054. Database.ReturnFullUrlLocation = function (url) {
  4055. if (url.indexOf("http:/") === -1) {
  4056. return (Database.parseURL(window.location.href) + url);
  4057. }
  4058. else {
  4059. return url;
  4060. }
  4061. };
  4062. return Database;
  4063. }());
  4064. BABYLON.Database = Database;
  4065. })(BABYLON || (BABYLON = {}));
  4066. var BABYLON;
  4067. (function (BABYLON) {
  4068. var Internals;
  4069. (function (Internals) {
  4070. /*
  4071. * Based on jsTGALoader - Javascript loader for TGA file
  4072. * By Vincent Thibault
  4073. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  4074. */
  4075. var TGATools = (function () {
  4076. function TGATools() {
  4077. }
  4078. TGATools.GetTGAHeader = function (data) {
  4079. var offset = 0;
  4080. var header = {
  4081. id_length: data[offset++],
  4082. colormap_type: data[offset++],
  4083. image_type: data[offset++],
  4084. colormap_index: data[offset++] | data[offset++] << 8,
  4085. colormap_length: data[offset++] | data[offset++] << 8,
  4086. colormap_size: data[offset++],
  4087. origin: [
  4088. data[offset++] | data[offset++] << 8,
  4089. data[offset++] | data[offset++] << 8
  4090. ],
  4091. width: data[offset++] | data[offset++] << 8,
  4092. height: data[offset++] | data[offset++] << 8,
  4093. pixel_size: data[offset++],
  4094. flags: data[offset++]
  4095. };
  4096. return header;
  4097. };
  4098. TGATools.UploadContent = function (gl, data) {
  4099. // Not enough data to contain header ?
  4100. if (data.length < 19) {
  4101. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  4102. return;
  4103. }
  4104. // Read Header
  4105. var offset = 18;
  4106. var header = TGATools.GetTGAHeader(data);
  4107. // Assume it's a valid Targa file.
  4108. if (header.id_length + offset > data.length) {
  4109. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  4110. return;
  4111. }
  4112. // Skip not needed data
  4113. offset += header.id_length;
  4114. var use_rle = false;
  4115. var use_pal = false;
  4116. var use_rgb = false;
  4117. var use_grey = false;
  4118. // Get some informations.
  4119. switch (header.image_type) {
  4120. case TGATools._TYPE_RLE_INDEXED:
  4121. use_rle = true;
  4122. case TGATools._TYPE_INDEXED:
  4123. use_pal = true;
  4124. break;
  4125. case TGATools._TYPE_RLE_RGB:
  4126. use_rle = true;
  4127. case TGATools._TYPE_RGB:
  4128. use_rgb = true;
  4129. break;
  4130. case TGATools._TYPE_RLE_GREY:
  4131. use_rle = true;
  4132. case TGATools._TYPE_GREY:
  4133. use_grey = true;
  4134. break;
  4135. }
  4136. var pixel_data;
  4137. var numAlphaBits = header.flags & 0xf;
  4138. var pixel_size = header.pixel_size >> 3;
  4139. var pixel_total = header.width * header.height * pixel_size;
  4140. // Read palettes
  4141. var palettes;
  4142. if (use_pal) {
  4143. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  4144. }
  4145. // Read LRE
  4146. if (use_rle) {
  4147. pixel_data = new Uint8Array(pixel_total);
  4148. var c, count, i;
  4149. var localOffset = 0;
  4150. var pixels = new Uint8Array(pixel_size);
  4151. while (offset < pixel_total && localOffset < pixel_total) {
  4152. c = data[offset++];
  4153. count = (c & 0x7f) + 1;
  4154. // RLE pixels
  4155. if (c & 0x80) {
  4156. // Bind pixel tmp array
  4157. for (i = 0; i < pixel_size; ++i) {
  4158. pixels[i] = data[offset++];
  4159. }
  4160. // Copy pixel array
  4161. for (i = 0; i < count; ++i) {
  4162. pixel_data.set(pixels, localOffset + i * pixel_size);
  4163. }
  4164. localOffset += pixel_size * count;
  4165. }
  4166. else {
  4167. count *= pixel_size;
  4168. for (i = 0; i < count; ++i) {
  4169. pixel_data[localOffset + i] = data[offset++];
  4170. }
  4171. localOffset += count;
  4172. }
  4173. }
  4174. }
  4175. else {
  4176. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  4177. }
  4178. // Load to texture
  4179. var x_start, y_start, x_step, y_step, y_end, x_end;
  4180. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  4181. default:
  4182. case TGATools._ORIGIN_UL:
  4183. x_start = 0;
  4184. x_step = 1;
  4185. x_end = header.width;
  4186. y_start = 0;
  4187. y_step = 1;
  4188. y_end = header.height;
  4189. break;
  4190. case TGATools._ORIGIN_BL:
  4191. x_start = 0;
  4192. x_step = 1;
  4193. x_end = header.width;
  4194. y_start = header.height - 1;
  4195. y_step = -1;
  4196. y_end = -1;
  4197. break;
  4198. case TGATools._ORIGIN_UR:
  4199. x_start = header.width - 1;
  4200. x_step = -1;
  4201. x_end = -1;
  4202. y_start = 0;
  4203. y_step = 1;
  4204. y_end = header.height;
  4205. break;
  4206. case TGATools._ORIGIN_BR:
  4207. x_start = header.width - 1;
  4208. x_step = -1;
  4209. x_end = -1;
  4210. y_start = header.height - 1;
  4211. y_step = -1;
  4212. y_end = -1;
  4213. break;
  4214. }
  4215. // Load the specify method
  4216. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  4217. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  4218. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  4219. };
  4220. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  4221. var image = pixel_data, colormap = palettes;
  4222. var width = header.width, height = header.height;
  4223. var color, i = 0, x, y;
  4224. var imageData = new Uint8Array(width * height * 4);
  4225. for (y = y_start; y !== y_end; y += y_step) {
  4226. for (x = x_start; x !== x_end; x += x_step, i++) {
  4227. color = image[i];
  4228. imageData[(x + width * y) * 4 + 3] = 255;
  4229. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  4230. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  4231. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  4232. }
  4233. }
  4234. return imageData;
  4235. };
  4236. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  4237. var image = pixel_data;
  4238. var width = header.width, height = header.height;
  4239. var color, i = 0, x, y;
  4240. var imageData = new Uint8Array(width * height * 4);
  4241. for (y = y_start; y !== y_end; y += y_step) {
  4242. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  4243. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  4244. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  4245. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  4246. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  4247. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  4248. }
  4249. }
  4250. return imageData;
  4251. };
  4252. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  4253. var image = pixel_data;
  4254. var width = header.width, height = header.height;
  4255. var i = 0, x, y;
  4256. var imageData = new Uint8Array(width * height * 4);
  4257. for (y = y_start; y !== y_end; y += y_step) {
  4258. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  4259. imageData[(x + width * y) * 4 + 3] = 255;
  4260. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  4261. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  4262. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  4263. }
  4264. }
  4265. return imageData;
  4266. };
  4267. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  4268. var image = pixel_data;
  4269. var width = header.width, height = header.height;
  4270. var i = 0, x, y;
  4271. var imageData = new Uint8Array(width * height * 4);
  4272. for (y = y_start; y !== y_end; y += y_step) {
  4273. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  4274. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  4275. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  4276. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  4277. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  4278. }
  4279. }
  4280. return imageData;
  4281. };
  4282. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  4283. var image = pixel_data;
  4284. var width = header.width, height = header.height;
  4285. var color, i = 0, x, y;
  4286. var imageData = new Uint8Array(width * height * 4);
  4287. for (y = y_start; y !== y_end; y += y_step) {
  4288. for (x = x_start; x !== x_end; x += x_step, i++) {
  4289. color = image[i];
  4290. imageData[(x + width * y) * 4 + 0] = color;
  4291. imageData[(x + width * y) * 4 + 1] = color;
  4292. imageData[(x + width * y) * 4 + 2] = color;
  4293. imageData[(x + width * y) * 4 + 3] = 255;
  4294. }
  4295. }
  4296. return imageData;
  4297. };
  4298. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  4299. var image = pixel_data;
  4300. var width = header.width, height = header.height;
  4301. var i = 0, x, y;
  4302. var imageData = new Uint8Array(width * height * 4);
  4303. for (y = y_start; y !== y_end; y += y_step) {
  4304. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  4305. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  4306. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  4307. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  4308. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  4309. }
  4310. }
  4311. return imageData;
  4312. };
  4313. TGATools._TYPE_NO_DATA = 0;
  4314. TGATools._TYPE_INDEXED = 1;
  4315. TGATools._TYPE_RGB = 2;
  4316. TGATools._TYPE_GREY = 3;
  4317. TGATools._TYPE_RLE_INDEXED = 9;
  4318. TGATools._TYPE_RLE_RGB = 10;
  4319. TGATools._TYPE_RLE_GREY = 11;
  4320. TGATools._ORIGIN_MASK = 0x30;
  4321. TGATools._ORIGIN_SHIFT = 0x04;
  4322. TGATools._ORIGIN_BL = 0x00;
  4323. TGATools._ORIGIN_BR = 0x01;
  4324. TGATools._ORIGIN_UL = 0x02;
  4325. TGATools._ORIGIN_UR = 0x03;
  4326. return TGATools;
  4327. }());
  4328. Internals.TGATools = TGATools;
  4329. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  4330. })(BABYLON || (BABYLON = {}));
  4331. var BABYLON;
  4332. (function (BABYLON) {
  4333. var SmartArray = (function () {
  4334. function SmartArray(capacity) {
  4335. this.length = 0;
  4336. this._duplicateId = 0;
  4337. this.data = new Array(capacity);
  4338. this._id = SmartArray._GlobalId++;
  4339. }
  4340. SmartArray.prototype.push = function (value) {
  4341. this.data[this.length++] = value;
  4342. if (this.length > this.data.length) {
  4343. this.data.length *= 2;
  4344. }
  4345. if (!value.__smartArrayFlags) {
  4346. value.__smartArrayFlags = {};
  4347. }
  4348. value.__smartArrayFlags[this._id] = this._duplicateId;
  4349. };
  4350. SmartArray.prototype.pushNoDuplicate = function (value) {
  4351. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  4352. return false;
  4353. }
  4354. this.push(value);
  4355. return true;
  4356. };
  4357. SmartArray.prototype.sort = function (compareFn) {
  4358. this.data.sort(compareFn);
  4359. };
  4360. SmartArray.prototype.reset = function () {
  4361. this.length = 0;
  4362. this._duplicateId++;
  4363. };
  4364. SmartArray.prototype.concat = function (array) {
  4365. if (array.length === 0) {
  4366. return;
  4367. }
  4368. if (this.length + array.length > this.data.length) {
  4369. this.data.length = (this.length + array.length) * 2;
  4370. }
  4371. for (var index = 0; index < array.length; index++) {
  4372. this.data[this.length++] = (array.data || array)[index];
  4373. }
  4374. };
  4375. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  4376. if (array.length === 0) {
  4377. return;
  4378. }
  4379. if (this.length + array.length > this.data.length) {
  4380. this.data.length = (this.length + array.length) * 2;
  4381. }
  4382. for (var index = 0; index < array.length; index++) {
  4383. var item = (array.data || array)[index];
  4384. this.pushNoDuplicate(item);
  4385. }
  4386. };
  4387. SmartArray.prototype.indexOf = function (value) {
  4388. var position = this.data.indexOf(value);
  4389. if (position >= this.length) {
  4390. return -1;
  4391. }
  4392. return position;
  4393. };
  4394. // Statics
  4395. SmartArray._GlobalId = 0;
  4396. return SmartArray;
  4397. }());
  4398. BABYLON.SmartArray = SmartArray;
  4399. })(BABYLON || (BABYLON = {}));
  4400. var BABYLON;
  4401. (function (BABYLON) {
  4402. /**
  4403. * This class implement a typical dictionary using a string as key and the generic type T as value.
  4404. * The underlying implementation relies on an associative array to ensure the best performances.
  4405. * The value can be anything including 'null' but except 'undefined'
  4406. */
  4407. var StringDictionary = (function () {
  4408. function StringDictionary() {
  4409. this._count = 0;
  4410. this._data = {};
  4411. }
  4412. /**
  4413. * Get a value based from its key
  4414. * @param key the given key to get the matching value from
  4415. * @return the value if found, otherwise undefined is returned
  4416. */
  4417. StringDictionary.prototype.get = function (key) {
  4418. var val = this._data[key];
  4419. if (val !== undefined) {
  4420. return val;
  4421. }
  4422. return undefined;
  4423. };
  4424. /**
  4425. * Get a value from its key or add it if it doesn't exist.
  4426. * This method will ensure you that a given key/data will be present in the dictionary.
  4427. * @param key the given key to get the matching value from
  4428. * @param factory the factory that will create the value if the key is not present in the dictionary.
  4429. * The factory will only be invoked if there's no data for the given key.
  4430. * @return the value corresponding to the key.
  4431. */
  4432. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  4433. var val = this.get(key);
  4434. if (val !== undefined) {
  4435. return val;
  4436. }
  4437. val = factory(key);
  4438. if (val) {
  4439. this.add(key, val);
  4440. }
  4441. return val;
  4442. };
  4443. /**
  4444. * Get a value from its key if present in the dictionary otherwise add it
  4445. * @param key the key to get the value from
  4446. * @param val if there's no such key/value pair in the dictionary add it with this value
  4447. * @return the value corresponding to the key
  4448. */
  4449. StringDictionary.prototype.getOrAdd = function (key, val) {
  4450. var curVal = this.get(key);
  4451. if (curVal !== undefined) {
  4452. return curVal;
  4453. }
  4454. this.add(key, val);
  4455. return val;
  4456. };
  4457. /**
  4458. * Check if there's a given key in the dictionary
  4459. * @param key the key to check for
  4460. * @return true if the key is present, false otherwise
  4461. */
  4462. StringDictionary.prototype.contains = function (key) {
  4463. return this._data[key] !== undefined;
  4464. };
  4465. /**
  4466. * Add a new key and its corresponding value
  4467. * @param key the key to add
  4468. * @param value the value corresponding to the key
  4469. * @return true if the operation completed successfully, false if we couldn't insert the key/value because there was already this key in the dictionary
  4470. */
  4471. StringDictionary.prototype.add = function (key, value) {
  4472. if (this._data[key] !== undefined) {
  4473. return false;
  4474. }
  4475. this._data[key] = value;
  4476. ++this._count;
  4477. return true;
  4478. };
  4479. StringDictionary.prototype.set = function (key, value) {
  4480. if (this._data[key] === undefined) {
  4481. return false;
  4482. }
  4483. this._data[key] = value;
  4484. return true;
  4485. };
  4486. /**
  4487. * Remove a key/value from the dictionary.
  4488. * @param key the key to remove
  4489. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  4490. */
  4491. StringDictionary.prototype.remove = function (key) {
  4492. if (this.contains(key)) {
  4493. delete this._data[key];
  4494. --this._count;
  4495. return true;
  4496. }
  4497. return false;
  4498. };
  4499. /**
  4500. * Clear the whole content of the dictionary
  4501. */
  4502. StringDictionary.prototype.clear = function () {
  4503. this._data = {};
  4504. this._count = 0;
  4505. };
  4506. Object.defineProperty(StringDictionary.prototype, "count", {
  4507. get: function () {
  4508. return this._count;
  4509. },
  4510. enumerable: true,
  4511. configurable: true
  4512. });
  4513. /**
  4514. * Execute a callback on each key/val of the dictionary.
  4515. * Note that you can remove any element in this dictionary in the callback implementation
  4516. * @param callback the callback to execute on a given key/value pair
  4517. */
  4518. StringDictionary.prototype.forEach = function (callback) {
  4519. for (var cur in this._data) {
  4520. var val = this._data[cur];
  4521. callback(cur, val);
  4522. }
  4523. };
  4524. /**
  4525. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  4526. * If the callback returns null or undefined the method will iterate to the next key/value pair
  4527. * Note that you can remove any element in this dictionary in the callback implementation
  4528. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  4529. */
  4530. StringDictionary.prototype.first = function (callback) {
  4531. for (var cur in this._data) {
  4532. var val = this._data[cur];
  4533. var res = callback(cur, val);
  4534. if (res) {
  4535. return res;
  4536. }
  4537. }
  4538. return null;
  4539. };
  4540. return StringDictionary;
  4541. }());
  4542. BABYLON.StringDictionary = StringDictionary;
  4543. })(BABYLON || (BABYLON = {}));
  4544. var BABYLON;
  4545. (function (BABYLON) {
  4546. // Screenshots
  4547. var screenshotCanvas;
  4548. var cloneValue = function (source, destinationObject) {
  4549. if (!source)
  4550. return null;
  4551. if (source instanceof BABYLON.Mesh) {
  4552. return null;
  4553. }
  4554. if (source instanceof BABYLON.SubMesh) {
  4555. return source.clone(destinationObject);
  4556. }
  4557. else if (source.clone) {
  4558. return source.clone();
  4559. }
  4560. return null;
  4561. };
  4562. var Tools = (function () {
  4563. function Tools() {
  4564. }
  4565. Tools.Instantiate = function (className) {
  4566. var arr = className.split(".");
  4567. var fn = (window || this);
  4568. for (var i = 0, len = arr.length; i < len; i++) {
  4569. fn = fn[arr[i]];
  4570. }
  4571. if (typeof fn !== "function") {
  4572. return null;
  4573. }
  4574. return fn;
  4575. };
  4576. Tools.SetImmediate = function (action) {
  4577. if (window.setImmediate) {
  4578. window.setImmediate(action);
  4579. }
  4580. else {
  4581. setTimeout(action, 1);
  4582. }
  4583. };
  4584. Tools.IsExponentOfTwo = function (value) {
  4585. var count = 1;
  4586. do {
  4587. count *= 2;
  4588. } while (count < value);
  4589. return count === value;
  4590. };
  4591. Tools.GetExponentOfTwo = function (value, max) {
  4592. var count = 1;
  4593. do {
  4594. count *= 2;
  4595. } while (count < value);
  4596. if (count > max)
  4597. count = max;
  4598. return count;
  4599. };
  4600. Tools.GetFilename = function (path) {
  4601. var index = path.lastIndexOf("/");
  4602. if (index < 0)
  4603. return path;
  4604. return path.substring(index + 1);
  4605. };
  4606. Tools.GetDOMTextContent = function (element) {
  4607. var result = "";
  4608. var child = element.firstChild;
  4609. while (child) {
  4610. if (child.nodeType === 3) {
  4611. result += child.textContent;
  4612. }
  4613. child = child.nextSibling;
  4614. }
  4615. return result;
  4616. };
  4617. Tools.ToDegrees = function (angle) {
  4618. return angle * 180 / Math.PI;
  4619. };
  4620. Tools.ToRadians = function (angle) {
  4621. return angle * Math.PI / 180;
  4622. };
  4623. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  4624. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  4625. var output = "";
  4626. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  4627. var i = 0;
  4628. var bytes = new Uint8Array(buffer);
  4629. while (i < bytes.length) {
  4630. chr1 = bytes[i++];
  4631. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  4632. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  4633. enc1 = chr1 >> 2;
  4634. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  4635. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  4636. enc4 = chr3 & 63;
  4637. if (isNaN(chr2)) {
  4638. enc3 = enc4 = 64;
  4639. }
  4640. else if (isNaN(chr3)) {
  4641. enc4 = 64;
  4642. }
  4643. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  4644. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  4645. }
  4646. return "data:image/png;base64," + output;
  4647. };
  4648. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  4649. if (bias === void 0) { bias = null; }
  4650. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4651. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4652. for (var index = indexStart; index < indexStart + indexCount; index++) {
  4653. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  4654. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4655. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4656. }
  4657. if (bias) {
  4658. minimum.x -= minimum.x * bias.x + bias.y;
  4659. minimum.y -= minimum.y * bias.x + bias.y;
  4660. minimum.z -= minimum.z * bias.x + bias.y;
  4661. maximum.x += maximum.x * bias.x + bias.y;
  4662. maximum.y += maximum.y * bias.x + bias.y;
  4663. maximum.z += maximum.z * bias.x + bias.y;
  4664. }
  4665. return {
  4666. minimum: minimum,
  4667. maximum: maximum
  4668. };
  4669. };
  4670. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  4671. if (bias === void 0) { bias = null; }
  4672. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4673. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4674. if (!stride) {
  4675. stride = 3;
  4676. }
  4677. for (var index = start; index < start + count; index++) {
  4678. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  4679. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4680. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4681. }
  4682. if (bias) {
  4683. minimum.x -= minimum.x * bias.x + bias.y;
  4684. minimum.y -= minimum.y * bias.x + bias.y;
  4685. minimum.z -= minimum.z * bias.x + bias.y;
  4686. maximum.x += maximum.x * bias.x + bias.y;
  4687. maximum.y += maximum.y * bias.x + bias.y;
  4688. maximum.z += maximum.z * bias.x + bias.y;
  4689. }
  4690. return {
  4691. minimum: minimum,
  4692. maximum: maximum
  4693. };
  4694. };
  4695. Tools.Vector2ArrayFeeder = function (array) {
  4696. return function (index) {
  4697. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  4698. var length = isFloatArray ? array.length / 2 : array.length;
  4699. if (index >= length) {
  4700. return null;
  4701. }
  4702. if (isFloatArray) {
  4703. var fa = array;
  4704. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  4705. }
  4706. var a = array;
  4707. return a[index];
  4708. };
  4709. };
  4710. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  4711. if (bias === void 0) { bias = null; }
  4712. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  4713. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  4714. var i = 0;
  4715. var cur = feeder(i++);
  4716. while (cur) {
  4717. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  4718. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  4719. cur = feeder(i++);
  4720. }
  4721. if (bias) {
  4722. minimum.x -= minimum.x * bias.x + bias.y;
  4723. minimum.y -= minimum.y * bias.x + bias.y;
  4724. maximum.x += maximum.x * bias.x + bias.y;
  4725. maximum.y += maximum.y * bias.x + bias.y;
  4726. }
  4727. return {
  4728. minimum: minimum,
  4729. maximum: maximum
  4730. };
  4731. };
  4732. Tools.MakeArray = function (obj, allowsNullUndefined) {
  4733. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  4734. return undefined;
  4735. return Array.isArray(obj) ? obj : [obj];
  4736. };
  4737. // Misc.
  4738. Tools.GetPointerPrefix = function () {
  4739. var eventPrefix = "pointer";
  4740. // Check if pointer events are supported
  4741. if (!window.PointerEvent && !navigator.pointerEnabled) {
  4742. eventPrefix = "mouse";
  4743. }
  4744. return eventPrefix;
  4745. };
  4746. /**
  4747. * @param func - the function to be called
  4748. * @param requester - the object that will request the next frame. Falls back to window.
  4749. */
  4750. Tools.QueueNewFrame = function (func, requester) {
  4751. if (requester === void 0) { requester = window; }
  4752. //if WebVR is enabled AND presenting, requestAnimationFrame is triggered when enabled.
  4753. /*if(requester.isPresenting) {
  4754. return;
  4755. } else*/ if (requester.requestAnimationFrame)
  4756. requester.requestAnimationFrame(func);
  4757. else if (requester.msRequestAnimationFrame)
  4758. requester.msRequestAnimationFrame(func);
  4759. else if (requester.webkitRequestAnimationFrame)
  4760. requester.webkitRequestAnimationFrame(func);
  4761. else if (requester.mozRequestAnimationFrame)
  4762. requester.mozRequestAnimationFrame(func);
  4763. else if (requester.oRequestAnimationFrame)
  4764. requester.oRequestAnimationFrame(func);
  4765. else {
  4766. window.setTimeout(func, 16);
  4767. }
  4768. };
  4769. Tools.RequestFullscreen = function (element) {
  4770. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  4771. if (!requestFunction)
  4772. return;
  4773. requestFunction.call(element);
  4774. };
  4775. Tools.ExitFullscreen = function () {
  4776. if (document.exitFullscreen) {
  4777. document.exitFullscreen();
  4778. }
  4779. else if (document.mozCancelFullScreen) {
  4780. document.mozCancelFullScreen();
  4781. }
  4782. else if (document.webkitCancelFullScreen) {
  4783. document.webkitCancelFullScreen();
  4784. }
  4785. else if (document.msCancelFullScreen) {
  4786. document.msCancelFullScreen();
  4787. }
  4788. };
  4789. Tools.SetCorsBehavior = function (url, img) {
  4790. if (Tools.CorsBehavior) {
  4791. switch (typeof (Tools.CorsBehavior)) {
  4792. case "function":
  4793. var result = Tools.CorsBehavior(url);
  4794. if (result) {
  4795. return result;
  4796. }
  4797. break;
  4798. case "string":
  4799. default:
  4800. img.crossOrigin = Tools.CorsBehavior;
  4801. break;
  4802. }
  4803. }
  4804. };
  4805. // External files
  4806. Tools.CleanUrl = function (url) {
  4807. url = url.replace(/#/mg, "%23");
  4808. return url;
  4809. };
  4810. Tools.LoadImage = function (url, onload, onerror, database) {
  4811. if (url instanceof ArrayBuffer) {
  4812. url = Tools.EncodeArrayBufferTobase64(url);
  4813. }
  4814. url = Tools.CleanUrl(url);
  4815. var img = new Image();
  4816. if (url.substr(0, 5) !== "data:") {
  4817. Tools.SetCorsBehavior(url, img);
  4818. }
  4819. img.onload = function () {
  4820. onload(img);
  4821. };
  4822. img.onerror = function (err) {
  4823. Tools.Error("Error while trying to load texture: " + url);
  4824. if (Tools.UseFallbackTexture) {
  4825. img.src = "data:image/jpg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD/4QBmRXhpZgAATU0AKgAAAAgABAEaAAUAAAABAAAAPgEbAAUAAAABAAAARgEoAAMAAAABAAIAAAExAAIAAAAQAAAATgAAAAAAAABgAAAAAQAAAGAAAAABcGFpbnQubmV0IDQuMC41AP/bAEMABAIDAwMCBAMDAwQEBAQFCQYFBQUFCwgIBgkNCw0NDQsMDA4QFBEODxMPDAwSGBITFRYXFxcOERkbGRYaFBYXFv/bAEMBBAQEBQUFCgYGChYPDA8WFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFv/AABEIAQABAAMBIgACEQEDEQH/xAAfAAABBQEBAQEBAQAAAAAAAAAAAQIDBAUGBwgJCgv/xAC1EAACAQMDAgQDBQUEBAAAAX0BAgMABBEFEiExQQYTUWEHInEUMoGRoQgjQrHBFVLR8CQzYnKCCQoWFxgZGiUmJygpKjQ1Njc4OTpDREVGR0hJSlNUVVZXWFlaY2RlZmdoaWpzdHV2d3h5eoOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4eLj5OXm5+jp6vHy8/T19vf4+fr/xAAfAQADAQEBAQEBAQEBAAAAAAAAAQIDBAUGBwgJCgv/xAC1EQACAQIEBAMEBwUEBAABAncAAQIDEQQFITEGEkFRB2FxEyIygQgUQpGhscEJIzNS8BVictEKFiQ04SXxFxgZGiYnKCkqNTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqCg4SFhoeIiYqSk5SVlpeYmZqio6Slpqeoqaqys7S1tre4ubrCw8TFxsfIycrS09TV1tfY2dri4+Tl5ufo6ery8/T19vf4+fr/2gAMAwEAAhEDEQA/APH6KKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76P//Z";
  4826. onload(img);
  4827. }
  4828. else {
  4829. onerror();
  4830. }
  4831. };
  4832. var noIndexedDB = function () {
  4833. img.src = url;
  4834. };
  4835. var loadFromIndexedDB = function () {
  4836. database.loadImageFromDB(url, img);
  4837. };
  4838. //ANY database to do!
  4839. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  4840. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4841. }
  4842. else {
  4843. if (url.indexOf("file:") === -1) {
  4844. noIndexedDB();
  4845. }
  4846. else {
  4847. try {
  4848. var textureName = url.substring(5).toLowerCase();
  4849. var blobURL;
  4850. try {
  4851. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  4852. }
  4853. catch (ex) {
  4854. // Chrome doesn't support oneTimeOnly parameter
  4855. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  4856. }
  4857. img.src = blobURL;
  4858. }
  4859. catch (e) {
  4860. img.src = null;
  4861. }
  4862. }
  4863. }
  4864. return img;
  4865. };
  4866. //ANY
  4867. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  4868. url = Tools.CleanUrl(url);
  4869. var noIndexedDB = function () {
  4870. var request = new XMLHttpRequest();
  4871. var loadUrl = Tools.BaseUrl + url;
  4872. request.open('GET', loadUrl, true);
  4873. if (useArrayBuffer) {
  4874. request.responseType = "arraybuffer";
  4875. }
  4876. request.onprogress = progressCallBack;
  4877. request.onreadystatechange = function () {
  4878. if (request.readyState === 4) {
  4879. request.onreadystatechange = null; //some browsers have issues where onreadystatechange can be called multiple times with the same value
  4880. if (request.status >= 200 && request.status < 300 || (navigator.isCocoonJS && (request.status === 0))) {
  4881. callback(!useArrayBuffer ? request.responseText : request.response);
  4882. }
  4883. else {
  4884. if (onError) {
  4885. onError();
  4886. }
  4887. else {
  4888. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  4889. }
  4890. }
  4891. }
  4892. };
  4893. request.send(null);
  4894. };
  4895. var loadFromIndexedDB = function () {
  4896. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  4897. };
  4898. if (url.indexOf("file:") !== -1) {
  4899. var fileName = url.substring(5).toLowerCase();
  4900. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, useArrayBuffer);
  4901. }
  4902. else {
  4903. // Caching all files
  4904. if (database && database.enableSceneOffline) {
  4905. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4906. }
  4907. else {
  4908. noIndexedDB();
  4909. }
  4910. }
  4911. };
  4912. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  4913. var reader = new FileReader();
  4914. reader.onload = function (e) {
  4915. //target doesn't have result from ts 1.3
  4916. callback(e.target['result']);
  4917. };
  4918. reader.onprogress = progressCallback;
  4919. reader.readAsDataURL(fileToLoad);
  4920. };
  4921. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  4922. var reader = new FileReader();
  4923. reader.onerror = function (e) {
  4924. Tools.Log("Error while reading file: " + fileToLoad.name);
  4925. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  4926. };
  4927. reader.onload = function (e) {
  4928. //target doesn't have result from ts 1.3
  4929. callback(e.target['result']);
  4930. };
  4931. reader.onprogress = progressCallBack;
  4932. if (!useArrayBuffer) {
  4933. // Asynchronous read
  4934. reader.readAsText(fileToLoad);
  4935. }
  4936. else {
  4937. reader.readAsArrayBuffer(fileToLoad);
  4938. }
  4939. };
  4940. //returns a downloadable url to a file content.
  4941. Tools.FileAsURL = function (content) {
  4942. var fileBlob = new Blob([content]);
  4943. var url = window.URL || window.webkitURL;
  4944. var link = url.createObjectURL(fileBlob);
  4945. return link;
  4946. };
  4947. // Misc.
  4948. Tools.Format = function (value, decimals) {
  4949. if (decimals === void 0) { decimals = 2; }
  4950. return value.toFixed(decimals);
  4951. };
  4952. Tools.CheckExtends = function (v, min, max) {
  4953. if (v.x < min.x)
  4954. min.x = v.x;
  4955. if (v.y < min.y)
  4956. min.y = v.y;
  4957. if (v.z < min.z)
  4958. min.z = v.z;
  4959. if (v.x > max.x)
  4960. max.x = v.x;
  4961. if (v.y > max.y)
  4962. max.y = v.y;
  4963. if (v.z > max.z)
  4964. max.z = v.z;
  4965. };
  4966. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  4967. for (var prop in source) {
  4968. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  4969. continue;
  4970. }
  4971. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  4972. continue;
  4973. }
  4974. var sourceValue = source[prop];
  4975. var typeOfSourceValue = typeof sourceValue;
  4976. if (typeOfSourceValue === "function") {
  4977. continue;
  4978. }
  4979. if (typeOfSourceValue === "object") {
  4980. if (sourceValue instanceof Array) {
  4981. destination[prop] = [];
  4982. if (sourceValue.length > 0) {
  4983. if (typeof sourceValue[0] == "object") {
  4984. for (var index = 0; index < sourceValue.length; index++) {
  4985. var clonedValue = cloneValue(sourceValue[index], destination);
  4986. if (destination[prop].indexOf(clonedValue) === -1) {
  4987. destination[prop].push(clonedValue);
  4988. }
  4989. }
  4990. }
  4991. else {
  4992. destination[prop] = sourceValue.slice(0);
  4993. }
  4994. }
  4995. }
  4996. else {
  4997. destination[prop] = cloneValue(sourceValue, destination);
  4998. }
  4999. }
  5000. else {
  5001. destination[prop] = sourceValue;
  5002. }
  5003. }
  5004. };
  5005. Tools.IsEmpty = function (obj) {
  5006. for (var i in obj) {
  5007. return false;
  5008. }
  5009. return true;
  5010. };
  5011. Tools.RegisterTopRootEvents = function (events) {
  5012. for (var index = 0; index < events.length; index++) {
  5013. var event = events[index];
  5014. window.addEventListener(event.name, event.handler, false);
  5015. try {
  5016. if (window.parent) {
  5017. window.parent.addEventListener(event.name, event.handler, false);
  5018. }
  5019. }
  5020. catch (e) {
  5021. }
  5022. }
  5023. };
  5024. Tools.UnregisterTopRootEvents = function (events) {
  5025. for (var index = 0; index < events.length; index++) {
  5026. var event = events[index];
  5027. window.removeEventListener(event.name, event.handler);
  5028. try {
  5029. if (window.parent) {
  5030. window.parent.removeEventListener(event.name, event.handler);
  5031. }
  5032. }
  5033. catch (e) {
  5034. }
  5035. }
  5036. };
  5037. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType) {
  5038. if (mimeType === void 0) { mimeType = "image/png"; }
  5039. // Read the contents of the framebuffer
  5040. var numberOfChannelsByLine = width * 4;
  5041. var halfHeight = height / 2;
  5042. //Reading datas from WebGL
  5043. var data = engine.readPixels(0, 0, width, height);
  5044. //To flip image on Y axis.
  5045. for (var i = 0; i < halfHeight; i++) {
  5046. for (var j = 0; j < numberOfChannelsByLine; j++) {
  5047. var currentCell = j + i * numberOfChannelsByLine;
  5048. var targetLine = height - i - 1;
  5049. var targetCell = j + targetLine * numberOfChannelsByLine;
  5050. var temp = data[currentCell];
  5051. data[currentCell] = data[targetCell];
  5052. data[targetCell] = temp;
  5053. }
  5054. }
  5055. // Create a 2D canvas to store the result
  5056. if (!screenshotCanvas) {
  5057. screenshotCanvas = document.createElement('canvas');
  5058. }
  5059. screenshotCanvas.width = width;
  5060. screenshotCanvas.height = height;
  5061. var context = screenshotCanvas.getContext('2d');
  5062. // Copy the pixels to a 2D canvas
  5063. var imageData = context.createImageData(width, height);
  5064. var castData = (imageData.data);
  5065. castData.set(data);
  5066. context.putImageData(imageData, 0, 0);
  5067. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  5068. };
  5069. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType) {
  5070. if (mimeType === void 0) { mimeType = "image/png"; }
  5071. var base64Image = screenshotCanvas.toDataURL(mimeType);
  5072. if (successCallback) {
  5073. successCallback(base64Image);
  5074. }
  5075. else {
  5076. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  5077. if (("download" in document.createElement("a"))) {
  5078. var a = window.document.createElement("a");
  5079. a.href = base64Image;
  5080. var date = new Date();
  5081. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  5082. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  5083. window.document.body.appendChild(a);
  5084. a.addEventListener("click", function () {
  5085. a.parentElement.removeChild(a);
  5086. });
  5087. a.click();
  5088. }
  5089. else {
  5090. var newWindow = window.open("");
  5091. var img = newWindow.document.createElement("img");
  5092. img.src = base64Image;
  5093. newWindow.document.body.appendChild(img);
  5094. }
  5095. }
  5096. };
  5097. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  5098. if (mimeType === void 0) { mimeType = "image/png"; }
  5099. var width;
  5100. var height;
  5101. // If a precision value is specified
  5102. if (size.precision) {
  5103. width = Math.round(engine.getRenderWidth() * size.precision);
  5104. height = Math.round(width / engine.getAspectRatio(camera));
  5105. }
  5106. else if (size.width && size.height) {
  5107. width = size.width;
  5108. height = size.height;
  5109. }
  5110. else if (size.width && !size.height) {
  5111. width = size.width;
  5112. height = Math.round(width / engine.getAspectRatio(camera));
  5113. }
  5114. else if (size.height && !size.width) {
  5115. height = size.height;
  5116. width = Math.round(height * engine.getAspectRatio(camera));
  5117. }
  5118. else if (!isNaN(size)) {
  5119. height = size;
  5120. width = size;
  5121. }
  5122. else {
  5123. Tools.Error("Invalid 'size' parameter !");
  5124. return;
  5125. }
  5126. if (!screenshotCanvas) {
  5127. screenshotCanvas = document.createElement('canvas');
  5128. }
  5129. screenshotCanvas.width = width;
  5130. screenshotCanvas.height = height;
  5131. var renderContext = screenshotCanvas.getContext("2d");
  5132. renderContext.drawImage(engine.getRenderingCanvas(), 0, 0, width, height);
  5133. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  5134. };
  5135. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType) {
  5136. if (mimeType === void 0) { mimeType = "image/png"; }
  5137. var width;
  5138. var height;
  5139. //If a precision value is specified
  5140. if (size.precision) {
  5141. width = Math.round(engine.getRenderWidth() * size.precision);
  5142. height = Math.round(width / engine.getAspectRatio(camera));
  5143. size = { width: width, height: height };
  5144. }
  5145. else if (size.width && size.height) {
  5146. width = size.width;
  5147. height = size.height;
  5148. }
  5149. else if (size.width && !size.height) {
  5150. width = size.width;
  5151. height = Math.round(width / engine.getAspectRatio(camera));
  5152. size = { width: width, height: height };
  5153. }
  5154. else if (size.height && !size.width) {
  5155. height = size.height;
  5156. width = Math.round(height * engine.getAspectRatio(camera));
  5157. size = { width: width, height: height };
  5158. }
  5159. else if (!isNaN(size)) {
  5160. height = size;
  5161. width = size;
  5162. }
  5163. else {
  5164. Tools.Error("Invalid 'size' parameter !");
  5165. return;
  5166. }
  5167. var scene = camera.getScene();
  5168. var previousCamera = null;
  5169. if (scene.activeCamera !== camera) {
  5170. previousCamera = scene.activeCamera;
  5171. scene.activeCamera = camera;
  5172. }
  5173. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  5174. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false);
  5175. texture.renderList = scene.meshes;
  5176. texture.onAfterRenderObservable.add(function () {
  5177. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType);
  5178. });
  5179. scene.incrementRenderId();
  5180. scene.resetCachedMaterial();
  5181. texture.render(true);
  5182. texture.dispose();
  5183. if (previousCamera) {
  5184. scene.activeCamera = previousCamera;
  5185. }
  5186. camera.getProjectionMatrix(true); // Force cache refresh;
  5187. };
  5188. // XHR response validator for local file scenario
  5189. Tools.ValidateXHRData = function (xhr, dataType) {
  5190. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  5191. if (dataType === void 0) { dataType = 7; }
  5192. try {
  5193. if (dataType & 1) {
  5194. if (xhr.responseText && xhr.responseText.length > 0) {
  5195. return true;
  5196. }
  5197. else if (dataType === 1) {
  5198. return false;
  5199. }
  5200. }
  5201. if (dataType & 2) {
  5202. // Check header width and height since there is no "TGA" magic number
  5203. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  5204. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  5205. return true;
  5206. }
  5207. else if (dataType === 2) {
  5208. return false;
  5209. }
  5210. }
  5211. if (dataType & 4) {
  5212. // Check for the "DDS" magic number
  5213. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  5214. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  5215. return true;
  5216. }
  5217. else {
  5218. return false;
  5219. }
  5220. }
  5221. }
  5222. catch (e) {
  5223. }
  5224. return false;
  5225. };
  5226. /**
  5227. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  5228. * Be aware Math.random() could cause collisions, but:
  5229. * "All but 6 of the 128 bits of the ID are randomly generated, which means that for any two ids, there's a 1 in 2^^122 (or 5.3x10^^36) chance they'll collide"
  5230. */
  5231. Tools.RandomId = function () {
  5232. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  5233. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  5234. return v.toString(16);
  5235. });
  5236. };
  5237. Object.defineProperty(Tools, "NoneLogLevel", {
  5238. get: function () {
  5239. return Tools._NoneLogLevel;
  5240. },
  5241. enumerable: true,
  5242. configurable: true
  5243. });
  5244. Object.defineProperty(Tools, "MessageLogLevel", {
  5245. get: function () {
  5246. return Tools._MessageLogLevel;
  5247. },
  5248. enumerable: true,
  5249. configurable: true
  5250. });
  5251. Object.defineProperty(Tools, "WarningLogLevel", {
  5252. get: function () {
  5253. return Tools._WarningLogLevel;
  5254. },
  5255. enumerable: true,
  5256. configurable: true
  5257. });
  5258. Object.defineProperty(Tools, "ErrorLogLevel", {
  5259. get: function () {
  5260. return Tools._ErrorLogLevel;
  5261. },
  5262. enumerable: true,
  5263. configurable: true
  5264. });
  5265. Object.defineProperty(Tools, "AllLogLevel", {
  5266. get: function () {
  5267. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  5268. },
  5269. enumerable: true,
  5270. configurable: true
  5271. });
  5272. Tools._AddLogEntry = function (entry) {
  5273. Tools._LogCache = entry + Tools._LogCache;
  5274. if (Tools.OnNewCacheEntry) {
  5275. Tools.OnNewCacheEntry(entry);
  5276. }
  5277. };
  5278. Tools._FormatMessage = function (message) {
  5279. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  5280. var date = new Date();
  5281. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  5282. };
  5283. Tools._LogDisabled = function (message) {
  5284. // nothing to do
  5285. };
  5286. Tools._LogEnabled = function (message) {
  5287. var formattedMessage = Tools._FormatMessage(message);
  5288. console.log("BJS - " + formattedMessage);
  5289. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  5290. Tools._AddLogEntry(entry);
  5291. };
  5292. Tools._WarnDisabled = function (message) {
  5293. // nothing to do
  5294. };
  5295. Tools._WarnEnabled = function (message) {
  5296. var formattedMessage = Tools._FormatMessage(message);
  5297. console.warn("BJS - " + formattedMessage);
  5298. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  5299. Tools._AddLogEntry(entry);
  5300. };
  5301. Tools._ErrorDisabled = function (message) {
  5302. // nothing to do
  5303. };
  5304. Tools._ErrorEnabled = function (message) {
  5305. Tools.errorsCount++;
  5306. var formattedMessage = Tools._FormatMessage(message);
  5307. console.error("BJS - " + formattedMessage);
  5308. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  5309. Tools._AddLogEntry(entry);
  5310. };
  5311. Object.defineProperty(Tools, "LogCache", {
  5312. get: function () {
  5313. return Tools._LogCache;
  5314. },
  5315. enumerable: true,
  5316. configurable: true
  5317. });
  5318. Tools.ClearLogCache = function () {
  5319. Tools._LogCache = "";
  5320. Tools.errorsCount = 0;
  5321. };
  5322. Object.defineProperty(Tools, "LogLevels", {
  5323. set: function (level) {
  5324. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  5325. Tools.Log = Tools._LogEnabled;
  5326. }
  5327. else {
  5328. Tools.Log = Tools._LogDisabled;
  5329. }
  5330. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  5331. Tools.Warn = Tools._WarnEnabled;
  5332. }
  5333. else {
  5334. Tools.Warn = Tools._WarnDisabled;
  5335. }
  5336. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  5337. Tools.Error = Tools._ErrorEnabled;
  5338. }
  5339. else {
  5340. Tools.Error = Tools._ErrorDisabled;
  5341. }
  5342. },
  5343. enumerable: true,
  5344. configurable: true
  5345. });
  5346. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  5347. get: function () {
  5348. return Tools._PerformanceNoneLogLevel;
  5349. },
  5350. enumerable: true,
  5351. configurable: true
  5352. });
  5353. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  5354. get: function () {
  5355. return Tools._PerformanceUserMarkLogLevel;
  5356. },
  5357. enumerable: true,
  5358. configurable: true
  5359. });
  5360. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  5361. get: function () {
  5362. return Tools._PerformanceConsoleLogLevel;
  5363. },
  5364. enumerable: true,
  5365. configurable: true
  5366. });
  5367. Object.defineProperty(Tools, "PerformanceLogLevel", {
  5368. set: function (level) {
  5369. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  5370. Tools.StartPerformanceCounter = Tools._StartUserMark;
  5371. Tools.EndPerformanceCounter = Tools._EndUserMark;
  5372. return;
  5373. }
  5374. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  5375. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  5376. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  5377. return;
  5378. }
  5379. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  5380. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  5381. },
  5382. enumerable: true,
  5383. configurable: true
  5384. });
  5385. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  5386. };
  5387. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  5388. };
  5389. Tools._StartUserMark = function (counterName, condition) {
  5390. if (condition === void 0) { condition = true; }
  5391. if (!condition || !Tools._performance.mark) {
  5392. return;
  5393. }
  5394. Tools._performance.mark(counterName + "-Begin");
  5395. };
  5396. Tools._EndUserMark = function (counterName, condition) {
  5397. if (condition === void 0) { condition = true; }
  5398. if (!condition || !Tools._performance.mark) {
  5399. return;
  5400. }
  5401. Tools._performance.mark(counterName + "-End");
  5402. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  5403. };
  5404. Tools._StartPerformanceConsole = function (counterName, condition) {
  5405. if (condition === void 0) { condition = true; }
  5406. if (!condition) {
  5407. return;
  5408. }
  5409. Tools._StartUserMark(counterName, condition);
  5410. if (console.time) {
  5411. console.time(counterName);
  5412. }
  5413. };
  5414. Tools._EndPerformanceConsole = function (counterName, condition) {
  5415. if (condition === void 0) { condition = true; }
  5416. if (!condition) {
  5417. return;
  5418. }
  5419. Tools._EndUserMark(counterName, condition);
  5420. if (console.time) {
  5421. console.timeEnd(counterName);
  5422. }
  5423. };
  5424. Object.defineProperty(Tools, "Now", {
  5425. get: function () {
  5426. if (window.performance && window.performance.now) {
  5427. return window.performance.now();
  5428. }
  5429. return new Date().getTime();
  5430. },
  5431. enumerable: true,
  5432. configurable: true
  5433. });
  5434. /**
  5435. * This method will return the name of the class used to create the instance of the given object.
  5436. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  5437. * @param object the object to get the class name from
  5438. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  5439. */
  5440. Tools.getClassName = function (object, isType) {
  5441. if (isType === void 0) { isType = false; }
  5442. var name = null;
  5443. if (!isType && object.getClassName) {
  5444. name = object.getClassName();
  5445. }
  5446. else {
  5447. if (object instanceof Object) {
  5448. var classObj = isType ? object : Object.getPrototypeOf(object);
  5449. name = classObj.constructor["__bjsclassName__"];
  5450. }
  5451. if (!name) {
  5452. name = typeof object;
  5453. }
  5454. }
  5455. return name;
  5456. };
  5457. Tools.first = function (array, predicate) {
  5458. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  5459. var el = array_1[_i];
  5460. if (predicate(el)) {
  5461. return el;
  5462. }
  5463. }
  5464. };
  5465. /**
  5466. * 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.
  5467. * @param array
  5468. */
  5469. Tools.arrayOrStringFeeder = function (array) {
  5470. return function (index) {
  5471. if (index >= array.length) {
  5472. return null;
  5473. }
  5474. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  5475. if (val && val.getHashCode) {
  5476. val = val.getHashCode();
  5477. }
  5478. if (typeof val === "string") {
  5479. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  5480. }
  5481. return val;
  5482. };
  5483. };
  5484. /**
  5485. * Compute the hashCode of a stream of number
  5486. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  5487. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  5488. * @return the hash code computed
  5489. */
  5490. Tools.hashCodeFromStream = function (feeder) {
  5491. // Based from here: http://stackoverflow.com/a/7616484/802124
  5492. var hash = 0;
  5493. var index = 0;
  5494. var chr = feeder(index++);
  5495. while (chr != null) {
  5496. hash = ((hash << 5) - hash) + chr;
  5497. hash |= 0; // Convert to 32bit integer
  5498. chr = feeder(index++);
  5499. }
  5500. return hash;
  5501. };
  5502. Tools.BaseUrl = "";
  5503. Tools.CorsBehavior = "anonymous";
  5504. Tools.UseFallbackTexture = true;
  5505. // Logs
  5506. Tools._NoneLogLevel = 0;
  5507. Tools._MessageLogLevel = 1;
  5508. Tools._WarningLogLevel = 2;
  5509. Tools._ErrorLogLevel = 4;
  5510. Tools._LogCache = "";
  5511. Tools.errorsCount = 0;
  5512. Tools.Log = Tools._LogEnabled;
  5513. Tools.Warn = Tools._WarnEnabled;
  5514. Tools.Error = Tools._ErrorEnabled;
  5515. // Performances
  5516. Tools._PerformanceNoneLogLevel = 0;
  5517. Tools._PerformanceUserMarkLogLevel = 1;
  5518. Tools._PerformanceConsoleLogLevel = 2;
  5519. Tools._performance = window.performance;
  5520. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  5521. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  5522. return Tools;
  5523. }());
  5524. BABYLON.Tools = Tools;
  5525. /**
  5526. * This class is used to track a performance counter which is number based.
  5527. * The user has access to many properties which give statistics of different nature
  5528. *
  5529. * The implementer can track two kinds of Performance Counter: time and count
  5530. * 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.
  5531. * 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.
  5532. */
  5533. var PerfCounter = (function () {
  5534. function PerfCounter() {
  5535. this._startMonitoringTime = 0;
  5536. this._min = 0;
  5537. this._max = 0;
  5538. this._average = 0;
  5539. this._lastSecAverage = 0;
  5540. this._current = 0;
  5541. this._totalValueCount = 0;
  5542. this._totalAccumulated = 0;
  5543. this._lastSecAccumulated = 0;
  5544. this._lastSecTime = 0;
  5545. this._lastSecValueCount = 0;
  5546. }
  5547. Object.defineProperty(PerfCounter.prototype, "min", {
  5548. /**
  5549. * Returns the smallest value ever
  5550. */
  5551. get: function () {
  5552. return this._min;
  5553. },
  5554. enumerable: true,
  5555. configurable: true
  5556. });
  5557. Object.defineProperty(PerfCounter.prototype, "max", {
  5558. /**
  5559. * Returns the biggest value ever
  5560. */
  5561. get: function () {
  5562. return this._max;
  5563. },
  5564. enumerable: true,
  5565. configurable: true
  5566. });
  5567. Object.defineProperty(PerfCounter.prototype, "average", {
  5568. /**
  5569. * Returns the average value since the performance counter is running
  5570. */
  5571. get: function () {
  5572. return this._average;
  5573. },
  5574. enumerable: true,
  5575. configurable: true
  5576. });
  5577. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  5578. /**
  5579. * Returns the average value of the last second the counter was monitored
  5580. */
  5581. get: function () {
  5582. return this._lastSecAverage;
  5583. },
  5584. enumerable: true,
  5585. configurable: true
  5586. });
  5587. Object.defineProperty(PerfCounter.prototype, "current", {
  5588. /**
  5589. * Returns the current value
  5590. */
  5591. get: function () {
  5592. return this._current;
  5593. },
  5594. enumerable: true,
  5595. configurable: true
  5596. });
  5597. Object.defineProperty(PerfCounter.prototype, "total", {
  5598. get: function () {
  5599. return this._totalAccumulated;
  5600. },
  5601. enumerable: true,
  5602. configurable: true
  5603. });
  5604. /**
  5605. * Call this method to start monitoring a new frame.
  5606. * 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.
  5607. */
  5608. PerfCounter.prototype.fetchNewFrame = function () {
  5609. this._totalValueCount++;
  5610. this._current = 0;
  5611. this._lastSecValueCount++;
  5612. };
  5613. /**
  5614. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  5615. * @param newCount the count value to add to the monitored count
  5616. * @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.
  5617. */
  5618. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  5619. this._current += newCount;
  5620. if (fetchResult) {
  5621. this._fetchResult();
  5622. }
  5623. };
  5624. /**
  5625. * Start monitoring this performance counter
  5626. */
  5627. PerfCounter.prototype.beginMonitoring = function () {
  5628. this._startMonitoringTime = Tools.Now;
  5629. };
  5630. /**
  5631. * Compute the time lapsed since the previous beginMonitoring() call.
  5632. * @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
  5633. */
  5634. PerfCounter.prototype.endMonitoring = function (newFrame) {
  5635. if (newFrame === void 0) { newFrame = true; }
  5636. if (newFrame) {
  5637. this.fetchNewFrame();
  5638. }
  5639. var currentTime = Tools.Now;
  5640. this._current = currentTime - this._startMonitoringTime;
  5641. if (newFrame) {
  5642. this._fetchResult();
  5643. }
  5644. };
  5645. PerfCounter.prototype._fetchResult = function () {
  5646. this._totalAccumulated += this._current;
  5647. this._lastSecAccumulated += this._current;
  5648. // Min/Max update
  5649. this._min = Math.min(this._min, this._current);
  5650. this._max = Math.max(this._max, this._current);
  5651. this._average = this._totalAccumulated / this._totalValueCount;
  5652. // Reset last sec?
  5653. var now = Tools.Now;
  5654. if ((now - this._lastSecTime) > 1000) {
  5655. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  5656. this._lastSecTime = now;
  5657. this._lastSecAccumulated = 0;
  5658. this._lastSecValueCount = 0;
  5659. }
  5660. };
  5661. return PerfCounter;
  5662. }());
  5663. BABYLON.PerfCounter = PerfCounter;
  5664. /**
  5665. * Use this className as a decorator on a given class definition to add it a name.
  5666. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  5667. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  5668. * @param name
  5669. */
  5670. function className(name) {
  5671. return function (target) {
  5672. target["__bjsclassName__"] = name;
  5673. };
  5674. }
  5675. BABYLON.className = className;
  5676. /**
  5677. * An implementation of a loop for asynchronous functions.
  5678. */
  5679. var AsyncLoop = (function () {
  5680. /**
  5681. * Constroctor.
  5682. * @param iterations the number of iterations.
  5683. * @param _fn the function to run each iteration
  5684. * @param _successCallback the callback that will be called upon succesful execution
  5685. * @param offset starting offset.
  5686. */
  5687. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  5688. if (offset === void 0) { offset = 0; }
  5689. this.iterations = iterations;
  5690. this._fn = _fn;
  5691. this._successCallback = _successCallback;
  5692. this.index = offset - 1;
  5693. this._done = false;
  5694. }
  5695. /**
  5696. * Execute the next iteration. Must be called after the last iteration was finished.
  5697. */
  5698. AsyncLoop.prototype.executeNext = function () {
  5699. if (!this._done) {
  5700. if (this.index + 1 < this.iterations) {
  5701. ++this.index;
  5702. this._fn(this);
  5703. }
  5704. else {
  5705. this.breakLoop();
  5706. }
  5707. }
  5708. };
  5709. /**
  5710. * Break the loop and run the success callback.
  5711. */
  5712. AsyncLoop.prototype.breakLoop = function () {
  5713. this._done = true;
  5714. this._successCallback();
  5715. };
  5716. /**
  5717. * Helper function
  5718. */
  5719. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  5720. if (offset === void 0) { offset = 0; }
  5721. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  5722. loop.executeNext();
  5723. return loop;
  5724. };
  5725. /**
  5726. * A for-loop that will run a given number of iterations synchronous and the rest async.
  5727. * @param iterations total number of iterations
  5728. * @param syncedIterations number of synchronous iterations in each async iteration.
  5729. * @param fn the function to call each iteration.
  5730. * @param callback a success call back that will be called when iterating stops.
  5731. * @param breakFunction a break condition (optional)
  5732. * @param timeout timeout settings for the setTimeout function. default - 0.
  5733. * @constructor
  5734. */
  5735. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  5736. if (timeout === void 0) { timeout = 0; }
  5737. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  5738. if (breakFunction && breakFunction())
  5739. loop.breakLoop();
  5740. else {
  5741. setTimeout(function () {
  5742. for (var i = 0; i < syncedIterations; ++i) {
  5743. var iteration = (loop.index * syncedIterations) + i;
  5744. if (iteration >= iterations)
  5745. break;
  5746. fn(iteration);
  5747. if (breakFunction && breakFunction()) {
  5748. loop.breakLoop();
  5749. break;
  5750. }
  5751. }
  5752. loop.executeNext();
  5753. }, timeout);
  5754. }
  5755. }, callback);
  5756. };
  5757. return AsyncLoop;
  5758. }());
  5759. BABYLON.AsyncLoop = AsyncLoop;
  5760. })(BABYLON || (BABYLON = {}));
  5761. var BABYLON;
  5762. (function (BABYLON) {
  5763. var Internals;
  5764. (function (Internals) {
  5765. var _AlphaState = (function () {
  5766. function _AlphaState() {
  5767. this._isAlphaBlendDirty = false;
  5768. this._isBlendFunctionParametersDirty = false;
  5769. this._alphaBlend = false;
  5770. this._blendFunctionParameters = new Array(4);
  5771. }
  5772. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  5773. get: function () {
  5774. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  5775. },
  5776. enumerable: true,
  5777. configurable: true
  5778. });
  5779. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  5780. get: function () {
  5781. return this._alphaBlend;
  5782. },
  5783. set: function (value) {
  5784. if (this._alphaBlend === value) {
  5785. return;
  5786. }
  5787. this._alphaBlend = value;
  5788. this._isAlphaBlendDirty = true;
  5789. },
  5790. enumerable: true,
  5791. configurable: true
  5792. });
  5793. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  5794. if (this._blendFunctionParameters[0] === value0 &&
  5795. this._blendFunctionParameters[1] === value1 &&
  5796. this._blendFunctionParameters[2] === value2 &&
  5797. this._blendFunctionParameters[3] === value3) {
  5798. return;
  5799. }
  5800. this._blendFunctionParameters[0] = value0;
  5801. this._blendFunctionParameters[1] = value1;
  5802. this._blendFunctionParameters[2] = value2;
  5803. this._blendFunctionParameters[3] = value3;
  5804. this._isBlendFunctionParametersDirty = true;
  5805. };
  5806. _AlphaState.prototype.reset = function () {
  5807. this._alphaBlend = false;
  5808. this._blendFunctionParameters[0] = null;
  5809. this._blendFunctionParameters[1] = null;
  5810. this._blendFunctionParameters[2] = null;
  5811. this._blendFunctionParameters[3] = null;
  5812. this._isAlphaBlendDirty = true;
  5813. this._isBlendFunctionParametersDirty = false;
  5814. };
  5815. _AlphaState.prototype.apply = function (gl) {
  5816. if (!this.isDirty) {
  5817. return;
  5818. }
  5819. // Alpha blend
  5820. if (this._isAlphaBlendDirty) {
  5821. if (this._alphaBlend) {
  5822. gl.enable(gl.BLEND);
  5823. }
  5824. else {
  5825. gl.disable(gl.BLEND);
  5826. }
  5827. this._isAlphaBlendDirty = false;
  5828. }
  5829. // Alpha function
  5830. if (this._isBlendFunctionParametersDirty) {
  5831. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  5832. this._isBlendFunctionParametersDirty = false;
  5833. }
  5834. };
  5835. return _AlphaState;
  5836. }());
  5837. Internals._AlphaState = _AlphaState;
  5838. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  5839. })(BABYLON || (BABYLON = {}));
  5840. var BABYLON;
  5841. (function (BABYLON) {
  5842. var Internals;
  5843. (function (Internals) {
  5844. var _DepthCullingState = (function () {
  5845. function _DepthCullingState() {
  5846. this._isDepthTestDirty = false;
  5847. this._isDepthMaskDirty = false;
  5848. this._isDepthFuncDirty = false;
  5849. this._isCullFaceDirty = false;
  5850. this._isCullDirty = false;
  5851. this._isZOffsetDirty = false;
  5852. }
  5853. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  5854. get: function () {
  5855. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  5856. },
  5857. enumerable: true,
  5858. configurable: true
  5859. });
  5860. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  5861. get: function () {
  5862. return this._zOffset;
  5863. },
  5864. set: function (value) {
  5865. if (this._zOffset === value) {
  5866. return;
  5867. }
  5868. this._zOffset = value;
  5869. this._isZOffsetDirty = true;
  5870. },
  5871. enumerable: true,
  5872. configurable: true
  5873. });
  5874. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  5875. get: function () {
  5876. return this._cullFace;
  5877. },
  5878. set: function (value) {
  5879. if (this._cullFace === value) {
  5880. return;
  5881. }
  5882. this._cullFace = value;
  5883. this._isCullFaceDirty = true;
  5884. },
  5885. enumerable: true,
  5886. configurable: true
  5887. });
  5888. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  5889. get: function () {
  5890. return this._cull;
  5891. },
  5892. set: function (value) {
  5893. if (this._cull === value) {
  5894. return;
  5895. }
  5896. this._cull = value;
  5897. this._isCullDirty = true;
  5898. },
  5899. enumerable: true,
  5900. configurable: true
  5901. });
  5902. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  5903. get: function () {
  5904. return this._depthFunc;
  5905. },
  5906. set: function (value) {
  5907. if (this._depthFunc === value) {
  5908. return;
  5909. }
  5910. this._depthFunc = value;
  5911. this._isDepthFuncDirty = true;
  5912. },
  5913. enumerable: true,
  5914. configurable: true
  5915. });
  5916. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  5917. get: function () {
  5918. return this._depthMask;
  5919. },
  5920. set: function (value) {
  5921. if (this._depthMask === value) {
  5922. return;
  5923. }
  5924. this._depthMask = value;
  5925. this._isDepthMaskDirty = true;
  5926. },
  5927. enumerable: true,
  5928. configurable: true
  5929. });
  5930. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  5931. get: function () {
  5932. return this._depthTest;
  5933. },
  5934. set: function (value) {
  5935. if (this._depthTest === value) {
  5936. return;
  5937. }
  5938. this._depthTest = value;
  5939. this._isDepthTestDirty = true;
  5940. },
  5941. enumerable: true,
  5942. configurable: true
  5943. });
  5944. _DepthCullingState.prototype.reset = function () {
  5945. this._depthMask = true;
  5946. this._depthTest = true;
  5947. this._depthFunc = null;
  5948. this._cullFace = null;
  5949. this._cull = null;
  5950. this._zOffset = 0;
  5951. this._isDepthTestDirty = true;
  5952. this._isDepthMaskDirty = true;
  5953. this._isDepthFuncDirty = false;
  5954. this._isCullFaceDirty = false;
  5955. this._isCullDirty = false;
  5956. this._isZOffsetDirty = false;
  5957. };
  5958. _DepthCullingState.prototype.apply = function (gl) {
  5959. if (!this.isDirty) {
  5960. return;
  5961. }
  5962. // Cull
  5963. if (this._isCullDirty) {
  5964. if (this.cull) {
  5965. gl.enable(gl.CULL_FACE);
  5966. }
  5967. else {
  5968. gl.disable(gl.CULL_FACE);
  5969. }
  5970. this._isCullDirty = false;
  5971. }
  5972. // Cull face
  5973. if (this._isCullFaceDirty) {
  5974. gl.cullFace(this.cullFace);
  5975. this._isCullFaceDirty = false;
  5976. }
  5977. // Depth mask
  5978. if (this._isDepthMaskDirty) {
  5979. gl.depthMask(this.depthMask);
  5980. this._isDepthMaskDirty = false;
  5981. }
  5982. // Depth test
  5983. if (this._isDepthTestDirty) {
  5984. if (this.depthTest) {
  5985. gl.enable(gl.DEPTH_TEST);
  5986. }
  5987. else {
  5988. gl.disable(gl.DEPTH_TEST);
  5989. }
  5990. this._isDepthTestDirty = false;
  5991. }
  5992. // Depth func
  5993. if (this._isDepthFuncDirty) {
  5994. gl.depthFunc(this.depthFunc);
  5995. this._isDepthFuncDirty = false;
  5996. }
  5997. // zOffset
  5998. if (this._isZOffsetDirty) {
  5999. if (this.zOffset) {
  6000. gl.enable(gl.POLYGON_OFFSET_FILL);
  6001. gl.polygonOffset(this.zOffset, 0);
  6002. }
  6003. else {
  6004. gl.disable(gl.POLYGON_OFFSET_FILL);
  6005. }
  6006. this._isZOffsetDirty = false;
  6007. }
  6008. };
  6009. return _DepthCullingState;
  6010. }());
  6011. Internals._DepthCullingState = _DepthCullingState;
  6012. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  6013. })(BABYLON || (BABYLON = {}));
  6014. var BABYLON;
  6015. (function (BABYLON) {
  6016. var Internals;
  6017. (function (Internals) {
  6018. var _StencilState = (function () {
  6019. function _StencilState() {
  6020. this._isStencilTestDirty = false;
  6021. this._isStencilMaskDirty = false;
  6022. this._isStencilFuncDirty = false;
  6023. this._isStencilOpDirty = false;
  6024. this.reset();
  6025. }
  6026. Object.defineProperty(_StencilState.prototype, "isDirty", {
  6027. get: function () {
  6028. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  6029. },
  6030. enumerable: true,
  6031. configurable: true
  6032. });
  6033. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  6034. get: function () {
  6035. return this._stencilFunc;
  6036. },
  6037. set: function (value) {
  6038. if (this._stencilFunc === value) {
  6039. return;
  6040. }
  6041. this._stencilFunc = value;
  6042. this._isStencilFuncDirty = true;
  6043. },
  6044. enumerable: true,
  6045. configurable: true
  6046. });
  6047. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  6048. get: function () {
  6049. return this._stencilFuncRef;
  6050. },
  6051. set: function (value) {
  6052. if (this._stencilFuncRef === value) {
  6053. return;
  6054. }
  6055. this._stencilFuncRef = value;
  6056. this._isStencilFuncDirty = true;
  6057. },
  6058. enumerable: true,
  6059. configurable: true
  6060. });
  6061. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  6062. get: function () {
  6063. return this._stencilFuncMask;
  6064. },
  6065. set: function (value) {
  6066. if (this._stencilFuncMask === value) {
  6067. return;
  6068. }
  6069. this._stencilFuncMask = value;
  6070. this._isStencilFuncDirty = true;
  6071. },
  6072. enumerable: true,
  6073. configurable: true
  6074. });
  6075. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  6076. get: function () {
  6077. return this._stencilOpStencilFail;
  6078. },
  6079. set: function (value) {
  6080. if (this._stencilOpStencilFail === value) {
  6081. return;
  6082. }
  6083. this._stencilOpStencilFail = value;
  6084. this._isStencilOpDirty = true;
  6085. },
  6086. enumerable: true,
  6087. configurable: true
  6088. });
  6089. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  6090. get: function () {
  6091. return this._stencilOpDepthFail;
  6092. },
  6093. set: function (value) {
  6094. if (this._stencilOpDepthFail === value) {
  6095. return;
  6096. }
  6097. this._stencilOpDepthFail = value;
  6098. this._isStencilOpDirty = true;
  6099. },
  6100. enumerable: true,
  6101. configurable: true
  6102. });
  6103. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  6104. get: function () {
  6105. return this._stencilOpStencilDepthPass;
  6106. },
  6107. set: function (value) {
  6108. if (this._stencilOpStencilDepthPass === value) {
  6109. return;
  6110. }
  6111. this._stencilOpStencilDepthPass = value;
  6112. this._isStencilOpDirty = true;
  6113. },
  6114. enumerable: true,
  6115. configurable: true
  6116. });
  6117. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  6118. get: function () {
  6119. return this._stencilMask;
  6120. },
  6121. set: function (value) {
  6122. if (this._stencilMask === value) {
  6123. return;
  6124. }
  6125. this._stencilMask = value;
  6126. this._isStencilMaskDirty = true;
  6127. },
  6128. enumerable: true,
  6129. configurable: true
  6130. });
  6131. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  6132. get: function () {
  6133. return this._stencilTest;
  6134. },
  6135. set: function (value) {
  6136. if (this._stencilTest === value) {
  6137. return;
  6138. }
  6139. this._stencilTest = value;
  6140. this._isStencilTestDirty = true;
  6141. },
  6142. enumerable: true,
  6143. configurable: true
  6144. });
  6145. _StencilState.prototype.reset = function () {
  6146. this._stencilTest = false;
  6147. this._stencilMask = 0xFF;
  6148. this._stencilFunc = BABYLON.Engine.ALWAYS;
  6149. this._stencilFuncRef = 1;
  6150. this._stencilFuncMask = 0xFF;
  6151. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  6152. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  6153. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  6154. this._isStencilTestDirty = true;
  6155. this._isStencilMaskDirty = true;
  6156. this._isStencilFuncDirty = true;
  6157. this._isStencilOpDirty = true;
  6158. };
  6159. _StencilState.prototype.apply = function (gl) {
  6160. if (!this.isDirty) {
  6161. return;
  6162. }
  6163. // Stencil test
  6164. if (this._isStencilTestDirty) {
  6165. if (this.stencilTest) {
  6166. gl.enable(gl.STENCIL_TEST);
  6167. }
  6168. else {
  6169. gl.disable(gl.STENCIL_TEST);
  6170. }
  6171. this._isStencilTestDirty = false;
  6172. }
  6173. // Stencil mask
  6174. if (this._isStencilMaskDirty) {
  6175. gl.stencilMask(this.stencilMask);
  6176. this._isStencilMaskDirty = false;
  6177. }
  6178. // Stencil func
  6179. if (this._isStencilFuncDirty) {
  6180. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  6181. this._isStencilFuncDirty = false;
  6182. }
  6183. // Stencil op
  6184. if (this._isStencilOpDirty) {
  6185. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  6186. this._isStencilOpDirty = false;
  6187. }
  6188. };
  6189. return _StencilState;
  6190. }());
  6191. Internals._StencilState = _StencilState;
  6192. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  6193. })(BABYLON || (BABYLON = {}));
  6194. var BABYLON;
  6195. (function (BABYLON) {
  6196. var compileShader = function (gl, source, type, defines) {
  6197. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  6198. gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
  6199. gl.compileShader(shader);
  6200. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  6201. throw new Error(gl.getShaderInfoLog(shader));
  6202. }
  6203. return shader;
  6204. };
  6205. var HALF_FLOAT_OES = 0x8D61;
  6206. var getWebGLTextureType = function (gl, type) {
  6207. if (type === Engine.TEXTURETYPE_FLOAT) {
  6208. return gl.FLOAT;
  6209. }
  6210. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  6211. // Add Half Float Constant.
  6212. return HALF_FLOAT_OES;
  6213. }
  6214. return gl.UNSIGNED_BYTE;
  6215. };
  6216. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  6217. var magFilter = gl.NEAREST;
  6218. var minFilter = gl.NEAREST;
  6219. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  6220. magFilter = gl.LINEAR;
  6221. if (generateMipMaps) {
  6222. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  6223. }
  6224. else {
  6225. minFilter = gl.LINEAR;
  6226. }
  6227. }
  6228. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  6229. magFilter = gl.LINEAR;
  6230. if (generateMipMaps) {
  6231. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  6232. }
  6233. else {
  6234. minFilter = gl.LINEAR;
  6235. }
  6236. }
  6237. else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6238. magFilter = gl.NEAREST;
  6239. if (generateMipMaps) {
  6240. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  6241. }
  6242. else {
  6243. minFilter = gl.NEAREST;
  6244. }
  6245. }
  6246. return {
  6247. min: minFilter,
  6248. mag: magFilter
  6249. };
  6250. };
  6251. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  6252. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  6253. var engine = scene.getEngine();
  6254. var potWidth = BABYLON.Tools.GetExponentOfTwo(width, engine.getCaps().maxTextureSize);
  6255. var potHeight = BABYLON.Tools.GetExponentOfTwo(height, engine.getCaps().maxTextureSize);
  6256. engine._bindTextureDirectly(gl.TEXTURE_2D, texture);
  6257. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  6258. texture._baseWidth = width;
  6259. texture._baseHeight = height;
  6260. texture._width = potWidth;
  6261. texture._height = potHeight;
  6262. texture.isReady = true;
  6263. processFunction(potWidth, potHeight);
  6264. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  6265. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  6266. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  6267. if (!noMipmap && !isCompressed) {
  6268. gl.generateMipmap(gl.TEXTURE_2D);
  6269. }
  6270. engine._bindTextureDirectly(gl.TEXTURE_2D, null);
  6271. engine.resetTextureCache();
  6272. scene._removePendingData(texture);
  6273. texture.onLoadedCallbacks.forEach(function (callback) {
  6274. callback();
  6275. });
  6276. texture.onLoadedCallbacks = [];
  6277. };
  6278. var partialLoad = function (url, index, loadedImages, scene, onfinish) {
  6279. var img;
  6280. var onload = function () {
  6281. loadedImages[index] = img;
  6282. loadedImages._internalCount++;
  6283. scene._removePendingData(img);
  6284. if (loadedImages._internalCount === 6) {
  6285. onfinish(loadedImages);
  6286. }
  6287. };
  6288. var onerror = function () {
  6289. scene._removePendingData(img);
  6290. };
  6291. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  6292. scene._addPendingData(img);
  6293. };
  6294. var cascadeLoad = function (rootUrl, scene, onfinish, files) {
  6295. var loadedImages = [];
  6296. loadedImages._internalCount = 0;
  6297. for (var index = 0; index < 6; index++) {
  6298. partialLoad(files[index], index, loadedImages, scene, onfinish);
  6299. }
  6300. };
  6301. var InstancingAttributeInfo = (function () {
  6302. function InstancingAttributeInfo() {
  6303. }
  6304. return InstancingAttributeInfo;
  6305. }());
  6306. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  6307. var EngineCapabilities = (function () {
  6308. function EngineCapabilities() {
  6309. }
  6310. return EngineCapabilities;
  6311. }());
  6312. BABYLON.EngineCapabilities = EngineCapabilities;
  6313. /**
  6314. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  6315. */
  6316. var Engine = (function () {
  6317. /**
  6318. * @constructor
  6319. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  6320. * @param {boolean} [antialias] - enable antialias
  6321. * @param options - further options to be sent to the getContext function
  6322. */
  6323. function Engine(canvas, antialias, options, adaptToDeviceRatio) {
  6324. var _this = this;
  6325. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = true; }
  6326. // Public members
  6327. this.isFullscreen = false;
  6328. this.isPointerLock = false;
  6329. this.cullBackFaces = true;
  6330. this.renderEvenInBackground = true;
  6331. // To enable/disable IDB support and avoid XHR on .manifest
  6332. this.enableOfflineSupport = true;
  6333. this.scenes = new Array();
  6334. this._windowIsBackground = false;
  6335. this._webGLVersion = "1.0";
  6336. this._drawCalls = new BABYLON.PerfCounter();
  6337. this._renderingQueueLaunched = false;
  6338. this._activeRenderLoops = [];
  6339. // FPS
  6340. this.fpsRange = 60;
  6341. this.previousFramesDuration = [];
  6342. this.fps = 60;
  6343. this.deltaTime = 0;
  6344. // States
  6345. this._depthCullingState = new BABYLON.Internals._DepthCullingState();
  6346. this._stencilState = new BABYLON.Internals._StencilState();
  6347. this._alphaState = new BABYLON.Internals._AlphaState();
  6348. this._alphaMode = Engine.ALPHA_DISABLE;
  6349. // Cache
  6350. this._loadedTexturesCache = new Array();
  6351. this._maxTextureChannels = 16;
  6352. this._activeTexturesCache = new Array(this._maxTextureChannels);
  6353. this._compiledEffects = {};
  6354. this._vertexAttribArraysEnabled = [];
  6355. this._uintIndicesCurrentlySet = false;
  6356. this._currentBoundBuffer = new Array();
  6357. this._currentBufferPointers = [];
  6358. this._currentInstanceLocations = new Array();
  6359. this._currentInstanceBuffers = new Array();
  6360. this._onVRFullScreenTriggered = function () {
  6361. if (_this._vrDisplayEnabled && _this._vrDisplayEnabled.isPresenting) {
  6362. //get the old size before we change
  6363. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  6364. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  6365. //according to the WebVR specs, requestAnimationFrame should be triggered only once.
  6366. //But actually, no browser follow the specs...
  6367. //this._vrAnimationFrameHandler = this._vrDisplayEnabled.requestAnimationFrame(this._bindedRenderFunction);
  6368. //get the width and height, change the render size
  6369. var leftEye = _this._vrDisplayEnabled.getEyeParameters('left');
  6370. var width, height;
  6371. _this.setHardwareScalingLevel(1);
  6372. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  6373. }
  6374. else {
  6375. //When the specs are implemented, need to uncomment this.
  6376. //this._vrDisplayEnabled.cancelAnimationFrame(this._vrAnimationFrameHandler);
  6377. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  6378. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  6379. _this._vrDisplayEnabled = undefined;
  6380. }
  6381. };
  6382. this._renderingCanvas = canvas;
  6383. this._externalData = new BABYLON.StringDictionary();
  6384. options = options || {};
  6385. if (antialias != null) {
  6386. options.antialias = antialias;
  6387. }
  6388. if (options.preserveDrawingBuffer === undefined) {
  6389. options.preserveDrawingBuffer = false;
  6390. }
  6391. // Checks if some of the format renders first to allow the use of webgl inspector.
  6392. var renderToFullFloat = this._canRenderToFloatTexture();
  6393. var renderToHalfFloat = this._canRenderToHalfFloatTexture();
  6394. // GL
  6395. //try {
  6396. // this._gl = <WebGLRenderingContext>(canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  6397. // if (this._gl) {
  6398. // this._webGLVersion = "2.0";
  6399. // }
  6400. //} catch (e) {
  6401. // // Do nothing
  6402. //}
  6403. if (!this._gl) {
  6404. try {
  6405. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  6406. }
  6407. catch (e) {
  6408. throw new Error("WebGL not supported");
  6409. }
  6410. }
  6411. if (!this._gl) {
  6412. throw new Error("WebGL not supported");
  6413. }
  6414. this._onBlur = function () {
  6415. _this._windowIsBackground = true;
  6416. };
  6417. this._onFocus = function () {
  6418. _this._windowIsBackground = false;
  6419. };
  6420. window.addEventListener("blur", this._onBlur);
  6421. window.addEventListener("focus", this._onFocus);
  6422. // Viewport
  6423. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  6424. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  6425. this.resize();
  6426. // Caps
  6427. this._isStencilEnable = options.stencil;
  6428. this._caps = new EngineCapabilities();
  6429. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  6430. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  6431. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  6432. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  6433. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  6434. // Infos
  6435. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  6436. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  6437. if (rendererInfo != null) {
  6438. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  6439. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  6440. }
  6441. if (!this._glVendor) {
  6442. this._glVendor = "Unknown vendor";
  6443. }
  6444. if (!this._glRenderer) {
  6445. this._glRenderer = "Unknown renderer";
  6446. }
  6447. // Extensions
  6448. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  6449. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  6450. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  6451. 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');
  6452. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  6453. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  6454. this._caps.uintIndices = this._gl.getExtension('OES_element_index_uint') !== null;
  6455. this._caps.fragmentDepthSupported = this._gl.getExtension('EXT_frag_depth') !== null;
  6456. this._caps.highPrecisionShaderSupported = true;
  6457. this._caps.drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  6458. this._caps.textureFloatLinearFiltering = this._gl.getExtension('OES_texture_float_linear');
  6459. this._caps.textureLOD = this._gl.getExtension('EXT_shader_texture_lod');
  6460. this._caps.textureFloatRender = renderToFullFloat;
  6461. this._caps.textureHalfFloat = (this._gl.getExtension('OES_texture_half_float') !== null);
  6462. this._caps.textureHalfFloatLinearFiltering = this._gl.getExtension('OES_texture_half_float_linear');
  6463. this._caps.textureHalfFloatRender = renderToHalfFloat;
  6464. if (this._gl.getShaderPrecisionFormat) {
  6465. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  6466. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  6467. }
  6468. // Depth buffer
  6469. this.setDepthBuffer(true);
  6470. this.setDepthFunctionToLessOrEqual();
  6471. this.setDepthWrite(true);
  6472. // Fullscreen
  6473. this._onFullscreenChange = function () {
  6474. if (document.fullscreen !== undefined) {
  6475. _this.isFullscreen = document.fullscreen;
  6476. }
  6477. else if (document.mozFullScreen !== undefined) {
  6478. _this.isFullscreen = document.mozFullScreen;
  6479. }
  6480. else if (document.webkitIsFullScreen !== undefined) {
  6481. _this.isFullscreen = document.webkitIsFullScreen;
  6482. }
  6483. else if (document.msIsFullScreen !== undefined) {
  6484. _this.isFullscreen = document.msIsFullScreen;
  6485. }
  6486. // Pointer lock
  6487. if (_this.isFullscreen && _this._pointerLockRequested) {
  6488. canvas.requestPointerLock = canvas.requestPointerLock ||
  6489. canvas.msRequestPointerLock ||
  6490. canvas.mozRequestPointerLock ||
  6491. canvas.webkitRequestPointerLock;
  6492. if (canvas.requestPointerLock) {
  6493. canvas.requestPointerLock();
  6494. }
  6495. }
  6496. };
  6497. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  6498. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  6499. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  6500. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  6501. // Pointer lock
  6502. this._onPointerLockChange = function () {
  6503. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  6504. document.webkitPointerLockElement === canvas ||
  6505. document.msPointerLockElement === canvas ||
  6506. document.pointerLockElement === canvas);
  6507. };
  6508. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  6509. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  6510. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  6511. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  6512. if (BABYLON.AudioEngine && !Engine.audioEngine) {
  6513. Engine.audioEngine = new BABYLON.AudioEngine();
  6514. }
  6515. //default loading screen
  6516. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  6517. //Load WebVR Devices
  6518. if (options.autoEnableWebVR) {
  6519. this.initWebVR();
  6520. }
  6521. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  6522. }
  6523. Object.defineProperty(Engine, "NEVER", {
  6524. get: function () {
  6525. return Engine._NEVER;
  6526. },
  6527. enumerable: true,
  6528. configurable: true
  6529. });
  6530. Object.defineProperty(Engine, "ALWAYS", {
  6531. get: function () {
  6532. return Engine._ALWAYS;
  6533. },
  6534. enumerable: true,
  6535. configurable: true
  6536. });
  6537. Object.defineProperty(Engine, "LESS", {
  6538. get: function () {
  6539. return Engine._LESS;
  6540. },
  6541. enumerable: true,
  6542. configurable: true
  6543. });
  6544. Object.defineProperty(Engine, "EQUAL", {
  6545. get: function () {
  6546. return Engine._EQUAL;
  6547. },
  6548. enumerable: true,
  6549. configurable: true
  6550. });
  6551. Object.defineProperty(Engine, "LEQUAL", {
  6552. get: function () {
  6553. return Engine._LEQUAL;
  6554. },
  6555. enumerable: true,
  6556. configurable: true
  6557. });
  6558. Object.defineProperty(Engine, "GREATER", {
  6559. get: function () {
  6560. return Engine._GREATER;
  6561. },
  6562. enumerable: true,
  6563. configurable: true
  6564. });
  6565. Object.defineProperty(Engine, "GEQUAL", {
  6566. get: function () {
  6567. return Engine._GEQUAL;
  6568. },
  6569. enumerable: true,
  6570. configurable: true
  6571. });
  6572. Object.defineProperty(Engine, "NOTEQUAL", {
  6573. get: function () {
  6574. return Engine._NOTEQUAL;
  6575. },
  6576. enumerable: true,
  6577. configurable: true
  6578. });
  6579. Object.defineProperty(Engine, "KEEP", {
  6580. get: function () {
  6581. return Engine._KEEP;
  6582. },
  6583. enumerable: true,
  6584. configurable: true
  6585. });
  6586. Object.defineProperty(Engine, "REPLACE", {
  6587. get: function () {
  6588. return Engine._REPLACE;
  6589. },
  6590. enumerable: true,
  6591. configurable: true
  6592. });
  6593. Object.defineProperty(Engine, "INCR", {
  6594. get: function () {
  6595. return Engine._INCR;
  6596. },
  6597. enumerable: true,
  6598. configurable: true
  6599. });
  6600. Object.defineProperty(Engine, "DECR", {
  6601. get: function () {
  6602. return Engine._DECR;
  6603. },
  6604. enumerable: true,
  6605. configurable: true
  6606. });
  6607. Object.defineProperty(Engine, "INVERT", {
  6608. get: function () {
  6609. return Engine._INVERT;
  6610. },
  6611. enumerable: true,
  6612. configurable: true
  6613. });
  6614. Object.defineProperty(Engine, "INCR_WRAP", {
  6615. get: function () {
  6616. return Engine._INCR_WRAP;
  6617. },
  6618. enumerable: true,
  6619. configurable: true
  6620. });
  6621. Object.defineProperty(Engine, "DECR_WRAP", {
  6622. get: function () {
  6623. return Engine._DECR_WRAP;
  6624. },
  6625. enumerable: true,
  6626. configurable: true
  6627. });
  6628. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  6629. get: function () {
  6630. return Engine._ALPHA_DISABLE;
  6631. },
  6632. enumerable: true,
  6633. configurable: true
  6634. });
  6635. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  6636. get: function () {
  6637. return Engine._ALPHA_ONEONE;
  6638. },
  6639. enumerable: true,
  6640. configurable: true
  6641. });
  6642. Object.defineProperty(Engine, "ALPHA_ADD", {
  6643. get: function () {
  6644. return Engine._ALPHA_ADD;
  6645. },
  6646. enumerable: true,
  6647. configurable: true
  6648. });
  6649. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  6650. get: function () {
  6651. return Engine._ALPHA_COMBINE;
  6652. },
  6653. enumerable: true,
  6654. configurable: true
  6655. });
  6656. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  6657. get: function () {
  6658. return Engine._ALPHA_SUBTRACT;
  6659. },
  6660. enumerable: true,
  6661. configurable: true
  6662. });
  6663. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  6664. get: function () {
  6665. return Engine._ALPHA_MULTIPLY;
  6666. },
  6667. enumerable: true,
  6668. configurable: true
  6669. });
  6670. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  6671. get: function () {
  6672. return Engine._ALPHA_MAXIMIZED;
  6673. },
  6674. enumerable: true,
  6675. configurable: true
  6676. });
  6677. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  6678. get: function () {
  6679. return Engine._DELAYLOADSTATE_NONE;
  6680. },
  6681. enumerable: true,
  6682. configurable: true
  6683. });
  6684. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  6685. get: function () {
  6686. return Engine._DELAYLOADSTATE_LOADED;
  6687. },
  6688. enumerable: true,
  6689. configurable: true
  6690. });
  6691. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  6692. get: function () {
  6693. return Engine._DELAYLOADSTATE_LOADING;
  6694. },
  6695. enumerable: true,
  6696. configurable: true
  6697. });
  6698. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  6699. get: function () {
  6700. return Engine._DELAYLOADSTATE_NOTLOADED;
  6701. },
  6702. enumerable: true,
  6703. configurable: true
  6704. });
  6705. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  6706. get: function () {
  6707. return Engine._TEXTUREFORMAT_ALPHA;
  6708. },
  6709. enumerable: true,
  6710. configurable: true
  6711. });
  6712. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  6713. get: function () {
  6714. return Engine._TEXTUREFORMAT_LUMINANCE;
  6715. },
  6716. enumerable: true,
  6717. configurable: true
  6718. });
  6719. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  6720. get: function () {
  6721. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  6722. },
  6723. enumerable: true,
  6724. configurable: true
  6725. });
  6726. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  6727. get: function () {
  6728. return Engine._TEXTUREFORMAT_RGB;
  6729. },
  6730. enumerable: true,
  6731. configurable: true
  6732. });
  6733. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  6734. get: function () {
  6735. return Engine._TEXTUREFORMAT_RGBA;
  6736. },
  6737. enumerable: true,
  6738. configurable: true
  6739. });
  6740. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  6741. get: function () {
  6742. return Engine._TEXTURETYPE_UNSIGNED_INT;
  6743. },
  6744. enumerable: true,
  6745. configurable: true
  6746. });
  6747. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  6748. get: function () {
  6749. return Engine._TEXTURETYPE_FLOAT;
  6750. },
  6751. enumerable: true,
  6752. configurable: true
  6753. });
  6754. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  6755. get: function () {
  6756. return Engine._TEXTURETYPE_HALF_FLOAT;
  6757. },
  6758. enumerable: true,
  6759. configurable: true
  6760. });
  6761. Object.defineProperty(Engine, "Version", {
  6762. get: function () {
  6763. return "2.5.-alpha";
  6764. },
  6765. enumerable: true,
  6766. configurable: true
  6767. });
  6768. Object.defineProperty(Engine.prototype, "webGLVersion", {
  6769. get: function () {
  6770. return this._webGLVersion;
  6771. },
  6772. enumerable: true,
  6773. configurable: true
  6774. });
  6775. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  6776. /**
  6777. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  6778. */
  6779. get: function () {
  6780. return this._isStencilEnable;
  6781. },
  6782. enumerable: true,
  6783. configurable: true
  6784. });
  6785. Engine.prototype._prepareWorkingCanvas = function () {
  6786. if (this._workingCanvas) {
  6787. return;
  6788. }
  6789. this._workingCanvas = document.createElement("canvas");
  6790. this._workingContext = this._workingCanvas.getContext("2d");
  6791. };
  6792. Engine.prototype.resetTextureCache = function () {
  6793. for (var index = 0; index < this._maxTextureChannels; index++) {
  6794. this._activeTexturesCache[index] = null;
  6795. }
  6796. };
  6797. Engine.prototype.getGlInfo = function () {
  6798. return {
  6799. vendor: this._glVendor,
  6800. renderer: this._glRenderer,
  6801. version: this._glVersion
  6802. };
  6803. };
  6804. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  6805. if (useScreen === void 0) { useScreen = false; }
  6806. var viewport = camera.viewport;
  6807. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  6808. };
  6809. Engine.prototype.getRenderWidth = function (useScreen) {
  6810. if (useScreen === void 0) { useScreen = false; }
  6811. if (!useScreen && this._currentRenderTarget) {
  6812. return this._currentRenderTarget._width;
  6813. }
  6814. return this._renderingCanvas.width;
  6815. };
  6816. Engine.prototype.getRenderHeight = function (useScreen) {
  6817. if (useScreen === void 0) { useScreen = false; }
  6818. if (!useScreen && this._currentRenderTarget) {
  6819. return this._currentRenderTarget._height;
  6820. }
  6821. return this._renderingCanvas.height;
  6822. };
  6823. Engine.prototype.getRenderingCanvas = function () {
  6824. return this._renderingCanvas;
  6825. };
  6826. Engine.prototype.getRenderingCanvasClientRect = function () {
  6827. return this._renderingCanvas.getBoundingClientRect();
  6828. };
  6829. Engine.prototype.setHardwareScalingLevel = function (level) {
  6830. this._hardwareScalingLevel = level;
  6831. this.resize();
  6832. };
  6833. Engine.prototype.getHardwareScalingLevel = function () {
  6834. return this._hardwareScalingLevel;
  6835. };
  6836. Engine.prototype.getLoadedTexturesCache = function () {
  6837. return this._loadedTexturesCache;
  6838. };
  6839. Engine.prototype.getCaps = function () {
  6840. return this._caps;
  6841. };
  6842. Object.defineProperty(Engine.prototype, "drawCalls", {
  6843. get: function () {
  6844. return this._drawCalls.current;
  6845. },
  6846. enumerable: true,
  6847. configurable: true
  6848. });
  6849. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  6850. get: function () {
  6851. return this._drawCalls;
  6852. },
  6853. enumerable: true,
  6854. configurable: true
  6855. });
  6856. Engine.prototype.getDepthFunction = function () {
  6857. return this._depthCullingState.depthFunc;
  6858. };
  6859. Engine.prototype.setDepthFunction = function (depthFunc) {
  6860. this._depthCullingState.depthFunc = depthFunc;
  6861. };
  6862. Engine.prototype.setDepthFunctionToGreater = function () {
  6863. this._depthCullingState.depthFunc = this._gl.GREATER;
  6864. };
  6865. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  6866. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  6867. };
  6868. Engine.prototype.setDepthFunctionToLess = function () {
  6869. this._depthCullingState.depthFunc = this._gl.LESS;
  6870. };
  6871. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  6872. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  6873. };
  6874. Engine.prototype.getStencilBuffer = function () {
  6875. return this._stencilState.stencilTest;
  6876. };
  6877. Engine.prototype.setStencilBuffer = function (enable) {
  6878. this._stencilState.stencilTest = enable;
  6879. };
  6880. Engine.prototype.getStencilMask = function () {
  6881. return this._stencilState.stencilMask;
  6882. };
  6883. Engine.prototype.setStencilMask = function (mask) {
  6884. this._stencilState.stencilMask = mask;
  6885. };
  6886. Engine.prototype.getStencilFunction = function () {
  6887. return this._stencilState.stencilFunc;
  6888. };
  6889. Engine.prototype.getStencilFunctionReference = function () {
  6890. return this._stencilState.stencilFuncRef;
  6891. };
  6892. Engine.prototype.getStencilFunctionMask = function () {
  6893. return this._stencilState.stencilFuncMask;
  6894. };
  6895. Engine.prototype.setStencilFunction = function (stencilFunc) {
  6896. this._stencilState.stencilFunc = stencilFunc;
  6897. };
  6898. Engine.prototype.setStencilFunctionReference = function (reference) {
  6899. this._stencilState.stencilFuncRef = reference;
  6900. };
  6901. Engine.prototype.setStencilFunctionMask = function (mask) {
  6902. this._stencilState.stencilFuncMask = mask;
  6903. };
  6904. Engine.prototype.getStencilOperationFail = function () {
  6905. return this._stencilState.stencilOpStencilFail;
  6906. };
  6907. Engine.prototype.getStencilOperationDepthFail = function () {
  6908. return this._stencilState.stencilOpDepthFail;
  6909. };
  6910. Engine.prototype.getStencilOperationPass = function () {
  6911. return this._stencilState.stencilOpStencilDepthPass;
  6912. };
  6913. Engine.prototype.setStencilOperationFail = function (operation) {
  6914. this._stencilState.stencilOpStencilFail = operation;
  6915. };
  6916. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  6917. this._stencilState.stencilOpDepthFail = operation;
  6918. };
  6919. Engine.prototype.setStencilOperationPass = function (operation) {
  6920. this._stencilState.stencilOpStencilDepthPass = operation;
  6921. };
  6922. /**
  6923. * stop executing a render loop function and remove it from the execution array
  6924. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  6925. */
  6926. Engine.prototype.stopRenderLoop = function (renderFunction) {
  6927. if (!renderFunction) {
  6928. this._activeRenderLoops = [];
  6929. return;
  6930. }
  6931. var index = this._activeRenderLoops.indexOf(renderFunction);
  6932. if (index >= 0) {
  6933. this._activeRenderLoops.splice(index, 1);
  6934. }
  6935. };
  6936. Engine.prototype._renderLoop = function () {
  6937. var shouldRender = true;
  6938. if (!this.renderEvenInBackground && this._windowIsBackground) {
  6939. shouldRender = false;
  6940. }
  6941. if (shouldRender) {
  6942. // Start new frame
  6943. this.beginFrame();
  6944. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  6945. var renderFunction = this._activeRenderLoops[index];
  6946. renderFunction();
  6947. }
  6948. // Present
  6949. this.endFrame();
  6950. }
  6951. if (this._activeRenderLoops.length > 0) {
  6952. // Register new frame
  6953. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, this._vrDisplayEnabled);
  6954. }
  6955. else {
  6956. this._renderingQueueLaunched = false;
  6957. }
  6958. };
  6959. /**
  6960. * Register and execute a render loop. The engine can have more than one render function.
  6961. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  6962. * @example
  6963. * engine.runRenderLoop(function () {
  6964. * scene.render()
  6965. * })
  6966. */
  6967. Engine.prototype.runRenderLoop = function (renderFunction) {
  6968. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  6969. return;
  6970. }
  6971. this._activeRenderLoops.push(renderFunction);
  6972. if (!this._renderingQueueLaunched) {
  6973. this._renderingQueueLaunched = true;
  6974. this._bindedRenderFunction = this._renderLoop.bind(this);
  6975. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  6976. }
  6977. };
  6978. /**
  6979. * Toggle full screen mode.
  6980. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  6981. * @param {any} options - an options object to be sent to the requestFullscreen function
  6982. */
  6983. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  6984. if (this.isFullscreen) {
  6985. BABYLON.Tools.ExitFullscreen();
  6986. }
  6987. else {
  6988. this._pointerLockRequested = requestPointerLock;
  6989. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  6990. }
  6991. };
  6992. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  6993. if (stencil === void 0) { stencil = false; }
  6994. this.applyStates();
  6995. var mode = 0;
  6996. if (backBuffer) {
  6997. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  6998. mode |= this._gl.COLOR_BUFFER_BIT;
  6999. }
  7000. if (depth) {
  7001. this._gl.clearDepth(1.0);
  7002. mode |= this._gl.DEPTH_BUFFER_BIT;
  7003. }
  7004. if (stencil) {
  7005. this._gl.clearStencil(0);
  7006. mode |= this._gl.STENCIL_BUFFER_BIT;
  7007. }
  7008. this._gl.clear(mode);
  7009. };
  7010. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  7011. var gl = this._gl;
  7012. // Save state
  7013. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  7014. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  7015. // Change state
  7016. gl.enable(gl.SCISSOR_TEST);
  7017. gl.scissor(x, y, width, height);
  7018. // Clear
  7019. this.clear(clearColor, true, true, true);
  7020. // Restore state
  7021. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  7022. if (curScissor === true) {
  7023. gl.enable(gl.SCISSOR_TEST);
  7024. }
  7025. else {
  7026. gl.disable(gl.SCISSOR_TEST);
  7027. }
  7028. };
  7029. /**
  7030. * Set the WebGL's viewport
  7031. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  7032. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  7033. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  7034. */
  7035. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  7036. var width = requiredWidth || (navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.width);
  7037. var height = requiredHeight || (navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.height);
  7038. var x = viewport.x || 0;
  7039. var y = viewport.y || 0;
  7040. this._cachedViewport = viewport;
  7041. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  7042. };
  7043. /**
  7044. * Directly set the WebGL Viewport
  7045. * The x, y, width & height are directly passed to the WebGL call
  7046. * @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.
  7047. */
  7048. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  7049. var currentViewport = this._cachedViewport;
  7050. this._cachedViewport = null;
  7051. this._gl.viewport(x, y, width, height);
  7052. return currentViewport;
  7053. };
  7054. Engine.prototype.beginFrame = function () {
  7055. this._measureFps();
  7056. };
  7057. Engine.prototype.endFrame = function () {
  7058. //this.flushFramebuffer();
  7059. //submit frame to the vr device, if enabled
  7060. if (this._vrDisplayEnabled && this._vrDisplayEnabled.isPresenting) {
  7061. this._vrDisplayEnabled.submitFrame();
  7062. }
  7063. };
  7064. /**
  7065. * resize the view according to the canvas' size.
  7066. * @example
  7067. * window.addEventListener("resize", function () {
  7068. * engine.resize();
  7069. * });
  7070. */
  7071. Engine.prototype.resize = function () {
  7072. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  7073. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  7074. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  7075. for (var index = 0; index < this.scenes.length; index++) {
  7076. var scene = this.scenes[index];
  7077. if (BABYLON.DebugLayer && scene.debugLayer.isVisible()) {
  7078. scene.debugLayer._syncPositions();
  7079. }
  7080. }
  7081. };
  7082. /**
  7083. * force a specific size of the canvas
  7084. * @param {number} width - the new canvas' width
  7085. * @param {number} height - the new canvas' height
  7086. */
  7087. Engine.prototype.setSize = function (width, height) {
  7088. this._renderingCanvas.width = width;
  7089. this._renderingCanvas.height = height;
  7090. for (var index = 0; index < this.scenes.length; index++) {
  7091. var scene = this.scenes[index];
  7092. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  7093. var cam = scene.cameras[camIndex];
  7094. cam._currentRenderId = 0;
  7095. }
  7096. }
  7097. };
  7098. //WebVR functions
  7099. Engine.prototype.initWebVR = function () {
  7100. if (!this.vrDisplaysPromise) {
  7101. this._getVRDisplays();
  7102. }
  7103. };
  7104. Engine.prototype.enableVR = function (vrDevice) {
  7105. this._vrDisplayEnabled = vrDevice;
  7106. this._vrDisplayEnabled.requestPresent([{ source: this.getRenderingCanvas() }]).then(this._onVRFullScreenTriggered);
  7107. };
  7108. Engine.prototype.disableVR = function () {
  7109. if (this._vrDisplayEnabled) {
  7110. this._vrDisplayEnabled.exitPresent().then(this._onVRFullScreenTriggered);
  7111. }
  7112. };
  7113. Engine.prototype._getVRDisplays = function () {
  7114. var _this = this;
  7115. var getWebVRDevices = function (devices) {
  7116. var size = devices.length;
  7117. var i = 0;
  7118. _this._vrDisplays = devices.filter(function (device) {
  7119. return devices[i] instanceof VRDisplay;
  7120. });
  7121. return _this._vrDisplays;
  7122. };
  7123. //using a key due to typescript
  7124. if (navigator.getVRDisplays) {
  7125. this.vrDisplaysPromise = navigator.getVRDisplays().then(getWebVRDevices);
  7126. }
  7127. };
  7128. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight) {
  7129. this._currentRenderTarget = texture;
  7130. this.bindUnboundFramebuffer(texture._framebuffer);
  7131. var gl = this._gl;
  7132. if (texture.isCube) {
  7133. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture, 0);
  7134. }
  7135. gl.viewport(0, 0, requiredWidth || texture._width, requiredHeight || texture._height);
  7136. this.wipeCaches();
  7137. };
  7138. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  7139. if (this._currentFramebuffer !== framebuffer) {
  7140. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  7141. this._currentFramebuffer = framebuffer;
  7142. }
  7143. };
  7144. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps) {
  7145. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  7146. this._currentRenderTarget = null;
  7147. if (texture.generateMipMaps && !disableGenerateMipMaps) {
  7148. var gl = this._gl;
  7149. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  7150. gl.generateMipmap(gl.TEXTURE_2D);
  7151. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  7152. }
  7153. this.bindUnboundFramebuffer(null);
  7154. };
  7155. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  7156. if (texture.generateMipMaps) {
  7157. var gl = this._gl;
  7158. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  7159. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  7160. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  7161. }
  7162. };
  7163. Engine.prototype.flushFramebuffer = function () {
  7164. this._gl.flush();
  7165. };
  7166. Engine.prototype.restoreDefaultFramebuffer = function () {
  7167. this._currentRenderTarget = null;
  7168. this.bindUnboundFramebuffer(null);
  7169. this.setViewport(this._cachedViewport);
  7170. this.wipeCaches();
  7171. };
  7172. // VBOs
  7173. Engine.prototype._resetVertexBufferBinding = function () {
  7174. this.bindArrayBuffer(null);
  7175. this._cachedVertexBuffers = null;
  7176. };
  7177. Engine.prototype.createVertexBuffer = function (vertices) {
  7178. var vbo = this._gl.createBuffer();
  7179. this.bindArrayBuffer(vbo);
  7180. if (vertices instanceof Float32Array) {
  7181. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  7182. }
  7183. else {
  7184. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  7185. }
  7186. this._resetVertexBufferBinding();
  7187. vbo.references = 1;
  7188. return vbo;
  7189. };
  7190. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  7191. var vbo = this._gl.createBuffer();
  7192. this.bindArrayBuffer(vbo);
  7193. if (vertices instanceof Float32Array) {
  7194. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  7195. }
  7196. else {
  7197. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  7198. }
  7199. this._resetVertexBufferBinding();
  7200. vbo.references = 1;
  7201. return vbo;
  7202. };
  7203. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  7204. this.bindArrayBuffer(vertexBuffer);
  7205. if (offset === undefined) {
  7206. offset = 0;
  7207. }
  7208. if (count === undefined) {
  7209. if (vertices instanceof Float32Array) {
  7210. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  7211. }
  7212. else {
  7213. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  7214. }
  7215. }
  7216. else {
  7217. if (vertices instanceof Float32Array) {
  7218. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  7219. }
  7220. else {
  7221. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  7222. }
  7223. }
  7224. this._resetVertexBufferBinding();
  7225. };
  7226. Engine.prototype._resetIndexBufferBinding = function () {
  7227. this.bindIndexBuffer(null);
  7228. this._cachedIndexBuffer = null;
  7229. };
  7230. Engine.prototype.createIndexBuffer = function (indices) {
  7231. var vbo = this._gl.createBuffer();
  7232. this.bindIndexBuffer(vbo);
  7233. // Check for 32 bits indices
  7234. var arrayBuffer;
  7235. var need32Bits = false;
  7236. if (this._caps.uintIndices) {
  7237. for (var index = 0; index < indices.length; index++) {
  7238. if (indices[index] > 65535) {
  7239. need32Bits = true;
  7240. break;
  7241. }
  7242. }
  7243. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  7244. }
  7245. else {
  7246. arrayBuffer = new Uint16Array(indices);
  7247. }
  7248. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  7249. this._resetIndexBufferBinding();
  7250. vbo.references = 1;
  7251. vbo.is32Bits = need32Bits;
  7252. return vbo;
  7253. };
  7254. Engine.prototype.bindArrayBuffer = function (buffer) {
  7255. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  7256. };
  7257. Engine.prototype.bindIndexBuffer = function (buffer) {
  7258. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  7259. };
  7260. Engine.prototype.bindBuffer = function (buffer, target) {
  7261. if (this._currentBoundBuffer[target] !== buffer) {
  7262. this._gl.bindBuffer(target, buffer);
  7263. this._currentBoundBuffer[target] = buffer;
  7264. }
  7265. };
  7266. Engine.prototype.updateArrayBuffer = function (data) {
  7267. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  7268. };
  7269. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  7270. var pointer = this._currentBufferPointers[indx];
  7271. var changed = false;
  7272. if (!pointer) {
  7273. changed = true;
  7274. this._currentBufferPointers[indx] = { indx: indx, size: size, type: type, normalized: normalized, stride: stride, offset: offset, buffer: buffer };
  7275. }
  7276. else {
  7277. if (pointer.buffer !== buffer) {
  7278. pointer.buffer = buffer;
  7279. changed = true;
  7280. }
  7281. if (pointer.size !== size) {
  7282. pointer.size = size;
  7283. changed = true;
  7284. }
  7285. if (pointer.type !== type) {
  7286. pointer.type = type;
  7287. changed = true;
  7288. }
  7289. if (pointer.normalized !== normalized) {
  7290. pointer.normalized = normalized;
  7291. changed = true;
  7292. }
  7293. if (pointer.stride !== stride) {
  7294. pointer.stride = stride;
  7295. changed = true;
  7296. }
  7297. if (pointer.offset !== offset) {
  7298. pointer.offset = offset;
  7299. changed = true;
  7300. }
  7301. }
  7302. if (changed) {
  7303. this.bindArrayBuffer(buffer);
  7304. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  7305. }
  7306. };
  7307. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  7308. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  7309. this._cachedVertexBuffers = vertexBuffer;
  7310. this._cachedEffectForVertexBuffers = effect;
  7311. var attributesCount = effect.getAttributesCount();
  7312. var offset = 0;
  7313. for (var index = 0; index < attributesCount; index++) {
  7314. if (index < vertexDeclaration.length) {
  7315. var order = effect.getAttributeLocation(index);
  7316. if (order >= 0) {
  7317. if (!this._vertexAttribArraysEnabled[order]) {
  7318. this._gl.enableVertexAttribArray(order);
  7319. this._vertexAttribArraysEnabled[order] = true;
  7320. }
  7321. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  7322. }
  7323. offset += vertexDeclaration[index] * 4;
  7324. }
  7325. else {
  7326. //disable effect attributes that have no data
  7327. var order = effect.getAttributeLocation(index);
  7328. if (this._vertexAttribArraysEnabled[order]) {
  7329. this._gl.disableVertexAttribArray(order);
  7330. this._vertexAttribArraysEnabled[order] = false;
  7331. }
  7332. }
  7333. }
  7334. }
  7335. if (this._cachedIndexBuffer !== indexBuffer) {
  7336. this._cachedIndexBuffer = indexBuffer;
  7337. this.bindIndexBuffer(indexBuffer);
  7338. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  7339. }
  7340. };
  7341. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  7342. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  7343. this._cachedVertexBuffers = vertexBuffers;
  7344. this._cachedEffectForVertexBuffers = effect;
  7345. var attributes = effect.getAttributesNames();
  7346. for (var index = 0; index < attributes.length; index++) {
  7347. var order = effect.getAttributeLocation(index);
  7348. if (order >= 0) {
  7349. var vertexBuffer = vertexBuffers[attributes[index]];
  7350. if (!vertexBuffer) {
  7351. if (this._vertexAttribArraysEnabled[order]) {
  7352. this._gl.disableVertexAttribArray(order);
  7353. this._vertexAttribArraysEnabled[order] = false;
  7354. }
  7355. continue;
  7356. }
  7357. if (!this._vertexAttribArraysEnabled[order]) {
  7358. this._gl.enableVertexAttribArray(order);
  7359. this._vertexAttribArraysEnabled[order] = true;
  7360. }
  7361. var buffer = vertexBuffer.getBuffer();
  7362. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  7363. if (vertexBuffer.getIsInstanced()) {
  7364. this._caps.instancedArrays.vertexAttribDivisorANGLE(order, 1);
  7365. this._currentInstanceLocations.push(order);
  7366. this._currentInstanceBuffers.push(buffer);
  7367. }
  7368. }
  7369. }
  7370. }
  7371. if (indexBuffer != null && this._cachedIndexBuffer !== indexBuffer) {
  7372. this._cachedIndexBuffer = indexBuffer;
  7373. this.bindIndexBuffer(indexBuffer);
  7374. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  7375. }
  7376. };
  7377. Engine.prototype.unbindInstanceAttributes = function () {
  7378. var boundBuffer;
  7379. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  7380. var instancesBuffer = this._currentInstanceBuffers[i];
  7381. if (boundBuffer != instancesBuffer) {
  7382. boundBuffer = instancesBuffer;
  7383. this.bindArrayBuffer(instancesBuffer);
  7384. }
  7385. var offsetLocation = this._currentInstanceLocations[i];
  7386. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  7387. }
  7388. this._currentInstanceBuffers.length = 0;
  7389. this._currentInstanceLocations.length = 0;
  7390. };
  7391. Engine.prototype._releaseBuffer = function (buffer) {
  7392. buffer.references--;
  7393. if (buffer.references === 0) {
  7394. this._gl.deleteBuffer(buffer);
  7395. return true;
  7396. }
  7397. return false;
  7398. };
  7399. Engine.prototype.createInstancesBuffer = function (capacity) {
  7400. var buffer = this._gl.createBuffer();
  7401. buffer.capacity = capacity;
  7402. this.bindArrayBuffer(buffer);
  7403. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  7404. return buffer;
  7405. };
  7406. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  7407. this._gl.deleteBuffer(buffer);
  7408. };
  7409. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  7410. this.bindArrayBuffer(instancesBuffer);
  7411. if (data) {
  7412. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  7413. }
  7414. if (offsetLocations[0].index !== undefined) {
  7415. var stride = 0;
  7416. for (var i = 0; i < offsetLocations.length; i++) {
  7417. var ai = offsetLocations[i];
  7418. stride += ai.attributeSize * 4;
  7419. }
  7420. for (var i = 0; i < offsetLocations.length; i++) {
  7421. var ai = offsetLocations[i];
  7422. if (!this._vertexAttribArraysEnabled[ai.index]) {
  7423. this._gl.enableVertexAttribArray(ai.index);
  7424. this._vertexAttribArraysEnabled[ai.index] = true;
  7425. }
  7426. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  7427. this._caps.instancedArrays.vertexAttribDivisorANGLE(ai.index, 1);
  7428. this._currentInstanceLocations.push(ai.index);
  7429. this._currentInstanceBuffers.push(instancesBuffer);
  7430. }
  7431. }
  7432. else {
  7433. for (var index = 0; index < 4; index++) {
  7434. var offsetLocation = offsetLocations[index];
  7435. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  7436. this._gl.enableVertexAttribArray(offsetLocation);
  7437. this._vertexAttribArraysEnabled[offsetLocation] = true;
  7438. }
  7439. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  7440. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  7441. this._currentInstanceLocations.push(offsetLocation);
  7442. this._currentInstanceBuffers.push(instancesBuffer);
  7443. }
  7444. }
  7445. };
  7446. Engine.prototype.applyStates = function () {
  7447. this._depthCullingState.apply(this._gl);
  7448. this._stencilState.apply(this._gl);
  7449. this._alphaState.apply(this._gl);
  7450. };
  7451. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  7452. // Apply states
  7453. this.applyStates();
  7454. this._drawCalls.addCount(1, false);
  7455. // Render
  7456. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  7457. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  7458. if (instancesCount) {
  7459. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  7460. return;
  7461. }
  7462. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  7463. };
  7464. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  7465. // Apply states
  7466. this.applyStates();
  7467. this._drawCalls.addCount(1, false);
  7468. if (instancesCount) {
  7469. this._caps.instancedArrays.drawArraysInstancedANGLE(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  7470. return;
  7471. }
  7472. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  7473. };
  7474. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  7475. // Apply states
  7476. this.applyStates();
  7477. this._drawCalls.addCount(1, false);
  7478. if (instancesCount) {
  7479. this._caps.instancedArrays.drawArraysInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount, instancesCount);
  7480. return;
  7481. }
  7482. this._gl.drawArrays(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount);
  7483. };
  7484. // Shaders
  7485. Engine.prototype._releaseEffect = function (effect) {
  7486. if (this._compiledEffects[effect._key]) {
  7487. delete this._compiledEffects[effect._key];
  7488. if (effect.getProgram()) {
  7489. this._gl.deleteProgram(effect.getProgram());
  7490. }
  7491. }
  7492. };
  7493. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  7494. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  7495. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  7496. var name = vertex + "+" + fragment + "@" + defines;
  7497. if (this._compiledEffects[name]) {
  7498. return this._compiledEffects[name];
  7499. }
  7500. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  7501. effect._key = name;
  7502. this._compiledEffects[name] = effect;
  7503. return effect;
  7504. };
  7505. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  7506. if (uniformsNames === void 0) { uniformsNames = []; }
  7507. if (samplers === void 0) { samplers = []; }
  7508. if (defines === void 0) { defines = ""; }
  7509. return this.createEffect({
  7510. vertex: "particles",
  7511. fragmentElement: fragmentName
  7512. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  7513. };
  7514. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  7515. context = context || this._gl;
  7516. var vertexShader = compileShader(context, vertexCode, "vertex", defines);
  7517. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines);
  7518. var shaderProgram = context.createProgram();
  7519. context.attachShader(shaderProgram, vertexShader);
  7520. context.attachShader(shaderProgram, fragmentShader);
  7521. context.linkProgram(shaderProgram);
  7522. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  7523. if (!linked) {
  7524. var error = context.getProgramInfoLog(shaderProgram);
  7525. if (error) {
  7526. throw new Error(error);
  7527. }
  7528. }
  7529. context.deleteShader(vertexShader);
  7530. context.deleteShader(fragmentShader);
  7531. return shaderProgram;
  7532. };
  7533. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  7534. var results = [];
  7535. for (var index = 0; index < uniformsNames.length; index++) {
  7536. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  7537. }
  7538. return results;
  7539. };
  7540. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  7541. var results = [];
  7542. for (var index = 0; index < attributesNames.length; index++) {
  7543. try {
  7544. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  7545. }
  7546. catch (e) {
  7547. results.push(-1);
  7548. }
  7549. }
  7550. return results;
  7551. };
  7552. Engine.prototype.enableEffect = function (effect) {
  7553. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  7554. if (effect && effect.onBind) {
  7555. effect.onBind(effect);
  7556. }
  7557. return;
  7558. }
  7559. // Use program
  7560. this.setProgram(effect.getProgram());
  7561. this._currentEffect = effect;
  7562. if (effect.onBind) {
  7563. effect.onBind(effect);
  7564. }
  7565. };
  7566. Engine.prototype.setIntArray = function (uniform, array) {
  7567. if (!uniform)
  7568. return;
  7569. this._gl.uniform1iv(uniform, array);
  7570. };
  7571. Engine.prototype.setIntArray2 = function (uniform, array) {
  7572. if (!uniform || array.length % 2 !== 0)
  7573. return;
  7574. this._gl.uniform2iv(uniform, array);
  7575. };
  7576. Engine.prototype.setIntArray3 = function (uniform, array) {
  7577. if (!uniform || array.length % 3 !== 0)
  7578. return;
  7579. this._gl.uniform3iv(uniform, array);
  7580. };
  7581. Engine.prototype.setIntArray4 = function (uniform, array) {
  7582. if (!uniform || array.length % 4 !== 0)
  7583. return;
  7584. this._gl.uniform4iv(uniform, array);
  7585. };
  7586. Engine.prototype.setFloatArray = function (uniform, array) {
  7587. if (!uniform)
  7588. return;
  7589. this._gl.uniform1fv(uniform, array);
  7590. };
  7591. Engine.prototype.setFloatArray2 = function (uniform, array) {
  7592. if (!uniform || array.length % 2 !== 0)
  7593. return;
  7594. this._gl.uniform2fv(uniform, array);
  7595. };
  7596. Engine.prototype.setFloatArray3 = function (uniform, array) {
  7597. if (!uniform || array.length % 3 !== 0)
  7598. return;
  7599. this._gl.uniform3fv(uniform, array);
  7600. };
  7601. Engine.prototype.setFloatArray4 = function (uniform, array) {
  7602. if (!uniform || array.length % 4 !== 0)
  7603. return;
  7604. this._gl.uniform4fv(uniform, array);
  7605. };
  7606. Engine.prototype.setArray = function (uniform, array) {
  7607. if (!uniform)
  7608. return;
  7609. this._gl.uniform1fv(uniform, array);
  7610. };
  7611. Engine.prototype.setArray2 = function (uniform, array) {
  7612. if (!uniform || array.length % 2 !== 0)
  7613. return;
  7614. this._gl.uniform2fv(uniform, array);
  7615. };
  7616. Engine.prototype.setArray3 = function (uniform, array) {
  7617. if (!uniform || array.length % 3 !== 0)
  7618. return;
  7619. this._gl.uniform3fv(uniform, array);
  7620. };
  7621. Engine.prototype.setArray4 = function (uniform, array) {
  7622. if (!uniform || array.length % 4 !== 0)
  7623. return;
  7624. this._gl.uniform4fv(uniform, array);
  7625. };
  7626. Engine.prototype.setMatrices = function (uniform, matrices) {
  7627. if (!uniform)
  7628. return;
  7629. this._gl.uniformMatrix4fv(uniform, false, matrices);
  7630. };
  7631. Engine.prototype.setMatrix = function (uniform, matrix) {
  7632. if (!uniform)
  7633. return;
  7634. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  7635. };
  7636. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  7637. if (!uniform)
  7638. return;
  7639. this._gl.uniformMatrix3fv(uniform, false, matrix);
  7640. };
  7641. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  7642. if (!uniform)
  7643. return;
  7644. this._gl.uniformMatrix2fv(uniform, false, matrix);
  7645. };
  7646. Engine.prototype.setFloat = function (uniform, value) {
  7647. if (!uniform)
  7648. return;
  7649. this._gl.uniform1f(uniform, value);
  7650. };
  7651. Engine.prototype.setFloat2 = function (uniform, x, y) {
  7652. if (!uniform)
  7653. return;
  7654. this._gl.uniform2f(uniform, x, y);
  7655. };
  7656. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  7657. if (!uniform)
  7658. return;
  7659. this._gl.uniform3f(uniform, x, y, z);
  7660. };
  7661. Engine.prototype.setBool = function (uniform, bool) {
  7662. if (!uniform)
  7663. return;
  7664. this._gl.uniform1i(uniform, bool);
  7665. };
  7666. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  7667. if (!uniform)
  7668. return;
  7669. this._gl.uniform4f(uniform, x, y, z, w);
  7670. };
  7671. Engine.prototype.setColor3 = function (uniform, color3) {
  7672. if (!uniform)
  7673. return;
  7674. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  7675. };
  7676. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  7677. if (!uniform)
  7678. return;
  7679. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  7680. };
  7681. // States
  7682. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  7683. if (zOffset === void 0) { zOffset = 0; }
  7684. if (reverseSide === void 0) { reverseSide = false; }
  7685. // Culling
  7686. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  7687. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  7688. var cullFace = this.cullBackFaces ? showSide : hideSide;
  7689. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  7690. if (culling) {
  7691. this._depthCullingState.cullFace = cullFace;
  7692. this._depthCullingState.cull = true;
  7693. }
  7694. else {
  7695. this._depthCullingState.cull = false;
  7696. }
  7697. }
  7698. // Z offset
  7699. this._depthCullingState.zOffset = zOffset;
  7700. };
  7701. Engine.prototype.setDepthBuffer = function (enable) {
  7702. this._depthCullingState.depthTest = enable;
  7703. };
  7704. Engine.prototype.getDepthWrite = function () {
  7705. return this._depthCullingState.depthMask;
  7706. };
  7707. Engine.prototype.setDepthWrite = function (enable) {
  7708. this._depthCullingState.depthMask = enable;
  7709. };
  7710. Engine.prototype.setColorWrite = function (enable) {
  7711. this._gl.colorMask(enable, enable, enable, enable);
  7712. };
  7713. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  7714. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  7715. if (this._alphaMode === mode) {
  7716. return;
  7717. }
  7718. switch (mode) {
  7719. case Engine.ALPHA_DISABLE:
  7720. this._alphaState.alphaBlend = false;
  7721. break;
  7722. case Engine.ALPHA_COMBINE:
  7723. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  7724. this._alphaState.alphaBlend = true;
  7725. break;
  7726. case Engine.ALPHA_ONEONE:
  7727. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  7728. this._alphaState.alphaBlend = true;
  7729. break;
  7730. case Engine.ALPHA_ADD:
  7731. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  7732. this._alphaState.alphaBlend = true;
  7733. break;
  7734. case Engine.ALPHA_SUBTRACT:
  7735. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  7736. this._alphaState.alphaBlend = true;
  7737. break;
  7738. case Engine.ALPHA_MULTIPLY:
  7739. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  7740. this._alphaState.alphaBlend = true;
  7741. break;
  7742. case Engine.ALPHA_MAXIMIZED:
  7743. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  7744. this._alphaState.alphaBlend = true;
  7745. break;
  7746. }
  7747. if (!noDepthWriteChange) {
  7748. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  7749. }
  7750. this._alphaMode = mode;
  7751. };
  7752. Engine.prototype.getAlphaMode = function () {
  7753. return this._alphaMode;
  7754. };
  7755. Engine.prototype.setAlphaTesting = function (enable) {
  7756. this._alphaTest = enable;
  7757. };
  7758. Engine.prototype.getAlphaTesting = function () {
  7759. return this._alphaTest;
  7760. };
  7761. // Textures
  7762. Engine.prototype.wipeCaches = function () {
  7763. this.resetTextureCache();
  7764. this._currentEffect = null;
  7765. this._stencilState.reset();
  7766. this._depthCullingState.reset();
  7767. this.setDepthFunctionToLessOrEqual();
  7768. this._alphaState.reset();
  7769. this._cachedVertexBuffers = null;
  7770. this._cachedIndexBuffer = null;
  7771. this._cachedEffectForVertexBuffers = null;
  7772. };
  7773. Engine.prototype.setSamplingMode = function (texture, samplingMode) {
  7774. var gl = this._gl;
  7775. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  7776. var magFilter = gl.NEAREST;
  7777. var minFilter = gl.NEAREST;
  7778. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  7779. magFilter = gl.LINEAR;
  7780. minFilter = gl.LINEAR;
  7781. }
  7782. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  7783. magFilter = gl.LINEAR;
  7784. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  7785. }
  7786. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  7787. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  7788. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  7789. texture.samplingMode = samplingMode;
  7790. };
  7791. Engine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer) {
  7792. var _this = this;
  7793. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  7794. if (onLoad === void 0) { onLoad = null; }
  7795. if (onError === void 0) { onError = null; }
  7796. if (buffer === void 0) { buffer = null; }
  7797. var texture = this._gl.createTexture();
  7798. var extension;
  7799. var fromData = false;
  7800. if (url.substr(0, 5) === "data:") {
  7801. fromData = true;
  7802. }
  7803. if (!fromData)
  7804. extension = url.substr(url.length - 4, 4).toLowerCase();
  7805. else {
  7806. var oldUrl = url;
  7807. fromData = oldUrl.split(':');
  7808. url = oldUrl;
  7809. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  7810. }
  7811. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  7812. var isTGA = (extension === ".tga");
  7813. scene._addPendingData(texture);
  7814. texture.url = url;
  7815. texture.noMipmap = noMipmap;
  7816. texture.references = 1;
  7817. texture.samplingMode = samplingMode;
  7818. texture.onLoadedCallbacks = [onLoad];
  7819. this._loadedTexturesCache.push(texture);
  7820. var onerror = function () {
  7821. scene._removePendingData(texture);
  7822. if (onError) {
  7823. onError();
  7824. }
  7825. };
  7826. var callback;
  7827. if (isTGA) {
  7828. callback = function (arrayBuffer) {
  7829. var data = new Uint8Array(arrayBuffer);
  7830. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  7831. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  7832. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  7833. }, samplingMode);
  7834. };
  7835. if (!(fromData instanceof Array))
  7836. BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
  7837. callback(arrayBuffer);
  7838. }, null, scene.database, true, onerror);
  7839. else
  7840. callback(buffer);
  7841. }
  7842. else if (isDDS) {
  7843. callback = function (data) {
  7844. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  7845. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  7846. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  7847. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  7848. }, samplingMode);
  7849. };
  7850. if (!(fromData instanceof Array))
  7851. BABYLON.Tools.LoadFile(url, function (data) {
  7852. callback(data);
  7853. }, null, scene.database, true, onerror);
  7854. else
  7855. callback(buffer);
  7856. }
  7857. else {
  7858. var onload = function (img) {
  7859. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  7860. var isPot = (img.width === potWidth && img.height === potHeight);
  7861. if (!isPot) {
  7862. _this._prepareWorkingCanvas();
  7863. _this._workingCanvas.width = potWidth;
  7864. _this._workingCanvas.height = potHeight;
  7865. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  7866. _this._workingContext.imageSmoothingEnabled = false;
  7867. _this._workingContext.mozImageSmoothingEnabled = false;
  7868. _this._workingContext.oImageSmoothingEnabled = false;
  7869. _this._workingContext.webkitImageSmoothingEnabled = false;
  7870. _this._workingContext.msImageSmoothingEnabled = false;
  7871. }
  7872. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  7873. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  7874. _this._workingContext.imageSmoothingEnabled = true;
  7875. _this._workingContext.mozImageSmoothingEnabled = true;
  7876. _this._workingContext.oImageSmoothingEnabled = true;
  7877. _this._workingContext.webkitImageSmoothingEnabled = true;
  7878. _this._workingContext.msImageSmoothingEnabled = true;
  7879. }
  7880. }
  7881. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  7882. }, samplingMode);
  7883. };
  7884. if (!(fromData instanceof Array))
  7885. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  7886. else
  7887. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  7888. }
  7889. return texture;
  7890. };
  7891. Engine.prototype._getInternalFormat = function (format) {
  7892. var internalFormat = this._gl.RGBA;
  7893. switch (format) {
  7894. case Engine.TEXTUREFORMAT_ALPHA:
  7895. internalFormat = this._gl.ALPHA;
  7896. break;
  7897. case Engine.TEXTUREFORMAT_LUMINANCE:
  7898. internalFormat = this._gl.LUMINANCE;
  7899. break;
  7900. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  7901. internalFormat = this._gl.LUMINANCE_ALPHA;
  7902. break;
  7903. case Engine.TEXTUREFORMAT_RGB:
  7904. internalFormat = this._gl.RGB;
  7905. break;
  7906. case Engine.TEXTUREFORMAT_RGBA:
  7907. internalFormat = this._gl.RGBA;
  7908. break;
  7909. }
  7910. return internalFormat;
  7911. };
  7912. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression) {
  7913. if (compression === void 0) { compression = null; }
  7914. var internalFormat = this._getInternalFormat(format);
  7915. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  7916. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  7917. if (texture._width % 4 !== 0) {
  7918. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  7919. }
  7920. if (compression) {
  7921. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture._width, texture._height, 0, data);
  7922. }
  7923. else {
  7924. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture._width, texture._height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  7925. }
  7926. if (texture.generateMipMaps) {
  7927. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  7928. }
  7929. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  7930. this.resetTextureCache();
  7931. texture.isReady = true;
  7932. };
  7933. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression) {
  7934. if (compression === void 0) { compression = null; }
  7935. var texture = this._gl.createTexture();
  7936. texture._baseWidth = width;
  7937. texture._baseHeight = height;
  7938. texture._width = width;
  7939. texture._height = height;
  7940. texture.references = 1;
  7941. this.updateRawTexture(texture, data, format, invertY, compression);
  7942. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  7943. // Filters
  7944. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  7945. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  7946. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  7947. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  7948. texture.samplingMode = samplingMode;
  7949. this._loadedTexturesCache.push(texture);
  7950. return texture;
  7951. };
  7952. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  7953. var texture = this._gl.createTexture();
  7954. texture._baseWidth = width;
  7955. texture._baseHeight = height;
  7956. if (generateMipMaps) {
  7957. width = BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize);
  7958. height = BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize);
  7959. }
  7960. this.resetTextureCache();
  7961. texture._width = width;
  7962. texture._height = height;
  7963. texture.isReady = false;
  7964. texture.generateMipMaps = generateMipMaps;
  7965. texture.references = 1;
  7966. texture.samplingMode = samplingMode;
  7967. this.updateTextureSamplingMode(samplingMode, texture);
  7968. this._loadedTexturesCache.push(texture);
  7969. return texture;
  7970. };
  7971. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  7972. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  7973. if (texture.isCube) {
  7974. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  7975. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  7976. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  7977. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  7978. }
  7979. else {
  7980. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  7981. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  7982. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  7983. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  7984. }
  7985. };
  7986. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha) {
  7987. if (premulAlpha === void 0) { premulAlpha = false; }
  7988. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  7989. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  7990. if (premulAlpha) {
  7991. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  7992. }
  7993. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  7994. if (texture.generateMipMaps) {
  7995. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  7996. }
  7997. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  7998. this.resetTextureCache();
  7999. texture.isReady = true;
  8000. };
  8001. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  8002. if (texture._isDisabled) {
  8003. return;
  8004. }
  8005. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  8006. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  8007. try {
  8008. // Testing video texture support
  8009. if (this._videoTextureSupported === undefined) {
  8010. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  8011. if (this._gl.getError() !== 0) {
  8012. this._videoTextureSupported = false;
  8013. }
  8014. else {
  8015. this._videoTextureSupported = true;
  8016. }
  8017. }
  8018. // Copy video through the current working canvas if video texture is not supported
  8019. if (!this._videoTextureSupported) {
  8020. if (!texture._workingCanvas) {
  8021. texture._workingCanvas = document.createElement("canvas");
  8022. texture._workingContext = texture._workingCanvas.getContext("2d");
  8023. texture._workingCanvas.width = texture._width;
  8024. texture._workingCanvas.height = texture._height;
  8025. }
  8026. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  8027. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  8028. }
  8029. else {
  8030. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  8031. }
  8032. if (texture.generateMipMaps) {
  8033. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  8034. }
  8035. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  8036. this.resetTextureCache();
  8037. texture.isReady = true;
  8038. }
  8039. catch (ex) {
  8040. // Something unexpected
  8041. // Let's disable the texture
  8042. texture._isDisabled = true;
  8043. }
  8044. };
  8045. Engine.prototype.createRenderTargetTexture = function (size, options) {
  8046. // old version had a "generateMipMaps" arg instead of options.
  8047. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  8048. // in the same way, generateDepthBuffer is defaulted to true
  8049. var generateMipMaps = false;
  8050. var generateDepthBuffer = true;
  8051. var generateStencilBuffer = false;
  8052. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  8053. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  8054. if (options !== undefined) {
  8055. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  8056. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  8057. generateStencilBuffer = generateDepthBuffer && options.generateStencilBuffer;
  8058. type = options.type === undefined ? type : options.type;
  8059. if (options.samplingMode !== undefined) {
  8060. samplingMode = options.samplingMode;
  8061. }
  8062. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  8063. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  8064. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  8065. }
  8066. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  8067. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  8068. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  8069. }
  8070. }
  8071. var gl = this._gl;
  8072. var texture = gl.createTexture();
  8073. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  8074. var width = size.width || size;
  8075. var height = size.height || size;
  8076. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  8077. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  8078. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  8079. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  8080. }
  8081. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  8082. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  8083. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  8084. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  8085. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, getWebGLTextureType(gl, type), null);
  8086. var depthStencilBuffer;
  8087. // Create the depth/stencil buffer
  8088. if (generateStencilBuffer) {
  8089. depthStencilBuffer = gl.createRenderbuffer();
  8090. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  8091. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  8092. }
  8093. else if (generateDepthBuffer) {
  8094. depthStencilBuffer = gl.createRenderbuffer();
  8095. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  8096. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  8097. }
  8098. // Create the framebuffer
  8099. var framebuffer = gl.createFramebuffer();
  8100. this.bindUnboundFramebuffer(framebuffer);
  8101. // Manage attachments
  8102. if (generateStencilBuffer) {
  8103. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  8104. }
  8105. else if (generateDepthBuffer) {
  8106. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  8107. }
  8108. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  8109. if (generateMipMaps) {
  8110. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  8111. }
  8112. // Unbind
  8113. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  8114. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  8115. this.bindUnboundFramebuffer(null);
  8116. texture._framebuffer = framebuffer;
  8117. if (generateDepthBuffer) {
  8118. texture._depthBuffer = depthStencilBuffer;
  8119. }
  8120. texture._baseWidth = width;
  8121. texture._baseHeight = height;
  8122. texture._width = width;
  8123. texture._height = height;
  8124. texture.isReady = true;
  8125. texture.generateMipMaps = generateMipMaps;
  8126. texture.references = 1;
  8127. texture.samplingMode = samplingMode;
  8128. texture.type = type;
  8129. this.resetTextureCache();
  8130. this._loadedTexturesCache.push(texture);
  8131. return texture;
  8132. };
  8133. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  8134. var gl = this._gl;
  8135. var texture = gl.createTexture();
  8136. var generateMipMaps = true;
  8137. var generateDepthBuffer = true;
  8138. var generateStencilBuffer = false;
  8139. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  8140. if (options !== undefined) {
  8141. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  8142. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  8143. generateStencilBuffer = generateDepthBuffer && options.generateStencilBuffer;
  8144. if (options.samplingMode !== undefined) {
  8145. samplingMode = options.samplingMode;
  8146. }
  8147. }
  8148. texture.isCube = true;
  8149. texture.references = 1;
  8150. texture.generateMipMaps = generateMipMaps;
  8151. texture.references = 1;
  8152. texture.samplingMode = samplingMode;
  8153. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  8154. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  8155. for (var face = 0; face < 6; face++) {
  8156. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  8157. }
  8158. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  8159. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  8160. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  8161. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  8162. // Create the depth buffer
  8163. var depthStencilBuffer;
  8164. // Create the depth/stencil buffer
  8165. if (generateStencilBuffer) {
  8166. depthStencilBuffer = gl.createRenderbuffer();
  8167. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  8168. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, size, size);
  8169. }
  8170. else if (generateDepthBuffer) {
  8171. depthStencilBuffer = gl.createRenderbuffer();
  8172. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  8173. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, size, size);
  8174. }
  8175. // Create the framebuffer
  8176. var framebuffer = gl.createFramebuffer();
  8177. this.bindUnboundFramebuffer(framebuffer);
  8178. // Manage attachments
  8179. if (generateStencilBuffer) {
  8180. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  8181. }
  8182. else if (generateDepthBuffer) {
  8183. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  8184. }
  8185. // Mipmaps
  8186. if (texture.generateMipMaps) {
  8187. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  8188. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  8189. }
  8190. // Unbind
  8191. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  8192. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  8193. this.bindUnboundFramebuffer(null);
  8194. texture._framebuffer = framebuffer;
  8195. if (generateDepthBuffer) {
  8196. texture._depthBuffer = depthStencilBuffer;
  8197. }
  8198. texture._width = size;
  8199. texture._height = size;
  8200. texture.isReady = true;
  8201. this.resetTextureCache();
  8202. this._loadedTexturesCache.push(texture);
  8203. return texture;
  8204. };
  8205. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap) {
  8206. var _this = this;
  8207. var gl = this._gl;
  8208. var texture = gl.createTexture();
  8209. texture.isCube = true;
  8210. texture.url = rootUrl;
  8211. texture.references = 1;
  8212. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  8213. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  8214. if (isDDS) {
  8215. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  8216. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  8217. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  8218. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  8219. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  8220. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  8221. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  8222. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  8223. }
  8224. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  8225. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  8226. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  8227. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  8228. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  8229. _this.resetTextureCache();
  8230. texture._width = info.width;
  8231. texture._height = info.height;
  8232. texture.isReady = true;
  8233. }, null, null, true);
  8234. }
  8235. else {
  8236. cascadeLoad(rootUrl, scene, function (imgs) {
  8237. var width = BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  8238. var height = width;
  8239. _this._prepareWorkingCanvas();
  8240. _this._workingCanvas.width = width;
  8241. _this._workingCanvas.height = height;
  8242. var faces = [
  8243. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  8244. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  8245. ];
  8246. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  8247. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  8248. for (var index = 0; index < faces.length; index++) {
  8249. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  8250. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  8251. }
  8252. if (!noMipmap) {
  8253. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  8254. }
  8255. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  8256. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  8257. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  8258. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  8259. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  8260. _this.resetTextureCache();
  8261. texture._width = width;
  8262. texture._height = height;
  8263. texture.isReady = true;
  8264. }, files);
  8265. }
  8266. this._loadedTexturesCache.push(texture);
  8267. return texture;
  8268. };
  8269. Engine.prototype.updateTextureSize = function (texture, width, height) {
  8270. texture._width = width;
  8271. texture._height = height;
  8272. texture._size = width * height;
  8273. texture._baseWidth = width;
  8274. texture._baseHeight = height;
  8275. };
  8276. Engine.prototype.createRawCubeTexture = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator) {
  8277. var _this = this;
  8278. var gl = this._gl;
  8279. var texture = gl.createTexture();
  8280. scene._addPendingData(texture);
  8281. texture.isCube = true;
  8282. texture.references = 1;
  8283. texture.url = url;
  8284. var internalFormat = this._getInternalFormat(format);
  8285. var textureType = gl.UNSIGNED_BYTE;
  8286. if (type === Engine.TEXTURETYPE_FLOAT) {
  8287. textureType = gl.FLOAT;
  8288. }
  8289. var width = size;
  8290. var height = width;
  8291. var isPot = (BABYLON.Tools.IsExponentOfTwo(width) && BABYLON.Tools.IsExponentOfTwo(height));
  8292. texture._width = width;
  8293. texture._height = height;
  8294. var onerror = function () {
  8295. scene._removePendingData(texture);
  8296. };
  8297. var internalCallback = function (data) {
  8298. var rgbeDataArrays = callback(data);
  8299. var facesIndex = [
  8300. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  8301. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  8302. ];
  8303. width = texture._width;
  8304. height = texture._height;
  8305. isPot = (BABYLON.Tools.IsExponentOfTwo(width) && BABYLON.Tools.IsExponentOfTwo(height));
  8306. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  8307. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  8308. if (!noMipmap && isPot) {
  8309. if (mipmmapGenerator) {
  8310. var arrayTemp = [];
  8311. // Data are known to be in +X +Y +Z -X -Y -Z
  8312. // mipmmapGenerator data is expected to be order in +X -X +Y -Y +Z -Z
  8313. arrayTemp.push(rgbeDataArrays[0]); // +X
  8314. arrayTemp.push(rgbeDataArrays[3]); // -X
  8315. arrayTemp.push(rgbeDataArrays[1]); // +Y
  8316. arrayTemp.push(rgbeDataArrays[4]); // -Y
  8317. arrayTemp.push(rgbeDataArrays[2]); // +Z
  8318. arrayTemp.push(rgbeDataArrays[5]); // -Z
  8319. var mipData = mipmmapGenerator(arrayTemp);
  8320. for (var level = 0; level < mipData.length; level++) {
  8321. var mipSize = width >> level;
  8322. // mipData is order in +X -X +Y -Y +Z -Z
  8323. gl.texImage2D(facesIndex[0], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][0]);
  8324. gl.texImage2D(facesIndex[1], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][2]);
  8325. gl.texImage2D(facesIndex[2], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][4]);
  8326. gl.texImage2D(facesIndex[3], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][1]);
  8327. gl.texImage2D(facesIndex[4], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][3]);
  8328. gl.texImage2D(facesIndex[5], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][5]);
  8329. }
  8330. }
  8331. else {
  8332. // Data are known to be in +X +Y +Z -X -Y -Z
  8333. for (var index = 0; index < facesIndex.length; index++) {
  8334. var faceData = rgbeDataArrays[index];
  8335. gl.texImage2D(facesIndex[index], 0, internalFormat, width, height, 0, internalFormat, textureType, faceData);
  8336. }
  8337. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  8338. // Workaround firefox bug fix https://bugzilla.mozilla.org/show_bug.cgi?id=1221822
  8339. // By following the webgl standard changes from Revision 7, 2014/11/24
  8340. // Firefox Removed the support for RGB32F, since it is not natively supported on all platforms where WebGL is implemented.
  8341. if (textureType === gl.FLOAT && internalFormat === gl.RGB && gl.getError() === 1282) {
  8342. BABYLON.Tools.Log("RGB32F not renderable on Firefox, trying fallback to RGBA32F.");
  8343. // Data are known to be in +X +Y +Z -X -Y -Z
  8344. for (var index = 0; index < facesIndex.length; index++) {
  8345. var faceData = rgbeDataArrays[index];
  8346. // Create a new RGBA Face.
  8347. var newFaceData = new Float32Array(width * height * 4);
  8348. for (var x = 0; x < width; x++) {
  8349. for (var y = 0; y < height; y++) {
  8350. var index_1 = (y * width + x) * 3;
  8351. var newIndex = (y * width + x) * 4;
  8352. // Map Old Value to new value.
  8353. newFaceData[newIndex + 0] = faceData[index_1 + 0];
  8354. newFaceData[newIndex + 1] = faceData[index_1 + 1];
  8355. newFaceData[newIndex + 2] = faceData[index_1 + 2];
  8356. // Add fully opaque alpha channel.
  8357. newFaceData[newIndex + 3] = 1;
  8358. }
  8359. }
  8360. // Reupload the face.
  8361. gl.texImage2D(facesIndex[index], 0, gl.RGBA, width, height, 0, gl.RGBA, textureType, newFaceData);
  8362. }
  8363. // Try to generate mipmap again.
  8364. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  8365. }
  8366. }
  8367. }
  8368. else {
  8369. noMipmap = true;
  8370. }
  8371. if (textureType === gl.FLOAT && !_this._caps.textureFloatLinearFiltering) {
  8372. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  8373. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  8374. }
  8375. else if (textureType === HALF_FLOAT_OES && !_this._caps.textureHalfFloatLinearFiltering) {
  8376. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  8377. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  8378. }
  8379. else {
  8380. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  8381. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  8382. }
  8383. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  8384. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  8385. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  8386. texture.isReady = true;
  8387. _this.resetTextureCache();
  8388. scene._removePendingData(texture);
  8389. };
  8390. BABYLON.Tools.LoadFile(url, function (data) {
  8391. internalCallback(data);
  8392. }, onerror, scene.database, true);
  8393. return texture;
  8394. };
  8395. ;
  8396. Engine.prototype._releaseTexture = function (texture) {
  8397. var gl = this._gl;
  8398. if (texture._framebuffer) {
  8399. gl.deleteFramebuffer(texture._framebuffer);
  8400. }
  8401. if (texture._depthBuffer) {
  8402. gl.deleteRenderbuffer(texture._depthBuffer);
  8403. }
  8404. gl.deleteTexture(texture);
  8405. // Unbind channels
  8406. this.unbindAllTextures();
  8407. var index = this._loadedTexturesCache.indexOf(texture);
  8408. if (index !== -1) {
  8409. this._loadedTexturesCache.splice(index, 1);
  8410. }
  8411. };
  8412. Engine.prototype.setProgram = function (program) {
  8413. if (this._currentProgram !== program) {
  8414. this._gl.useProgram(program);
  8415. this._currentProgram = program;
  8416. }
  8417. };
  8418. Engine.prototype.bindSamplers = function (effect) {
  8419. this.setProgram(effect.getProgram());
  8420. var samplers = effect.getSamplers();
  8421. for (var index = 0; index < samplers.length; index++) {
  8422. var uniform = effect.getUniform(samplers[index]);
  8423. this._gl.uniform1i(uniform, index);
  8424. }
  8425. this._currentEffect = null;
  8426. };
  8427. Engine.prototype.activateTexture = function (texture) {
  8428. if (this._activeTexture !== texture) {
  8429. this._gl.activeTexture(texture);
  8430. this._activeTexture = texture;
  8431. }
  8432. };
  8433. Engine.prototype._bindTextureDirectly = function (target, texture) {
  8434. if (this._activeTexturesCache[this._activeTexture] !== texture) {
  8435. this._gl.bindTexture(target, texture);
  8436. this._activeTexturesCache[this._activeTexture] = texture;
  8437. }
  8438. };
  8439. Engine.prototype._bindTexture = function (channel, texture) {
  8440. if (channel < 0) {
  8441. return;
  8442. }
  8443. this.activateTexture(this._gl["TEXTURE" + channel]);
  8444. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  8445. };
  8446. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  8447. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  8448. };
  8449. Engine.prototype.unbindAllTextures = function () {
  8450. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  8451. this.activateTexture(this._gl["TEXTURE" + channel]);
  8452. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  8453. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  8454. }
  8455. };
  8456. Engine.prototype.setTexture = function (channel, uniform, texture) {
  8457. if (channel < 0) {
  8458. return;
  8459. }
  8460. this._gl.uniform1i(uniform, channel);
  8461. this._setTexture(channel, texture);
  8462. };
  8463. Engine.prototype._setTexture = function (channel, texture) {
  8464. // Not ready?
  8465. if (!texture || !texture.isReady()) {
  8466. if (this._activeTexturesCache[channel] != null) {
  8467. this.activateTexture(this._gl["TEXTURE" + channel]);
  8468. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  8469. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  8470. }
  8471. return;
  8472. }
  8473. // Video
  8474. var alreadyActivated = false;
  8475. if (texture instanceof BABYLON.VideoTexture) {
  8476. this.activateTexture(this._gl["TEXTURE" + channel]);
  8477. alreadyActivated = true;
  8478. texture.update();
  8479. }
  8480. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  8481. texture.delayLoad();
  8482. return;
  8483. }
  8484. var internalTexture = texture.getInternalTexture();
  8485. if (this._activeTexturesCache[channel] === internalTexture) {
  8486. return;
  8487. }
  8488. if (!alreadyActivated) {
  8489. this.activateTexture(this._gl["TEXTURE" + channel]);
  8490. }
  8491. if (internalTexture.isCube) {
  8492. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  8493. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  8494. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  8495. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  8496. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  8497. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  8498. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  8499. }
  8500. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  8501. }
  8502. else {
  8503. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture);
  8504. if (internalTexture._cachedWrapU !== texture.wrapU) {
  8505. internalTexture._cachedWrapU = texture.wrapU;
  8506. switch (texture.wrapU) {
  8507. case BABYLON.Texture.WRAP_ADDRESSMODE:
  8508. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  8509. break;
  8510. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  8511. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  8512. break;
  8513. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  8514. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  8515. break;
  8516. }
  8517. }
  8518. if (internalTexture._cachedWrapV !== texture.wrapV) {
  8519. internalTexture._cachedWrapV = texture.wrapV;
  8520. switch (texture.wrapV) {
  8521. case BABYLON.Texture.WRAP_ADDRESSMODE:
  8522. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  8523. break;
  8524. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  8525. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  8526. break;
  8527. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  8528. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  8529. break;
  8530. }
  8531. }
  8532. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  8533. }
  8534. };
  8535. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  8536. if (channel < 0) {
  8537. return;
  8538. }
  8539. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  8540. this._textureUnits = new Int32Array(textures.length);
  8541. }
  8542. for (var i = 0; i < textures.length; i++) {
  8543. this._textureUnits[i] = channel + i;
  8544. }
  8545. this._gl.uniform1iv(uniform, this._textureUnits);
  8546. for (var index = 0; index < textures.length; index++) {
  8547. this._setTexture(channel + index, textures[index]);
  8548. }
  8549. };
  8550. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  8551. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  8552. var value = texture.anisotropicFilteringLevel;
  8553. if (texture.getInternalTexture().samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  8554. value = 1;
  8555. }
  8556. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  8557. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  8558. texture._cachedAnisotropicFilteringLevel = value;
  8559. }
  8560. };
  8561. Engine.prototype.readPixels = function (x, y, width, height) {
  8562. var data = new Uint8Array(height * width * 4);
  8563. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  8564. return data;
  8565. };
  8566. /**
  8567. * Add an externaly attached data from its key.
  8568. * This method call will fail and return false, if such key already exists.
  8569. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  8570. * @param key the unique key that identifies the data
  8571. * @param data the data object to associate to the key for this Engine instance
  8572. * @return true if no such key were already present and the data was added successfully, false otherwise
  8573. */
  8574. Engine.prototype.addExternalData = function (key, data) {
  8575. return this._externalData.add(key, data);
  8576. };
  8577. /**
  8578. * Get an externaly attached data from its key
  8579. * @param key the unique key that identifies the data
  8580. * @return the associated data, if present (can be null), or undefined if not present
  8581. */
  8582. Engine.prototype.getExternalData = function (key) {
  8583. return this._externalData.get(key);
  8584. };
  8585. /**
  8586. * Get an externaly attached data from its key, create it using a factory if it's not already present
  8587. * @param key the unique key that identifies the data
  8588. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  8589. * @return the associated data, can be null if the factory returned null.
  8590. */
  8591. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  8592. return this._externalData.getOrAddWithFactory(key, factory);
  8593. };
  8594. /**
  8595. * Remove an externaly attached data from the Engine instance
  8596. * @param key the unique key that identifies the data
  8597. * @return true if the data was successfully removed, false if it doesn't exist
  8598. */
  8599. Engine.prototype.removeExternalData = function (key) {
  8600. return this._externalData.remove(key);
  8601. };
  8602. Engine.prototype.releaseInternalTexture = function (texture) {
  8603. if (!texture) {
  8604. return;
  8605. }
  8606. texture.references--;
  8607. // Final reference ?
  8608. if (texture.references === 0) {
  8609. var texturesCache = this.getLoadedTexturesCache();
  8610. var index = texturesCache.indexOf(texture);
  8611. if (index > -1) {
  8612. texturesCache.splice(index, 1);
  8613. }
  8614. this._releaseTexture(texture);
  8615. }
  8616. };
  8617. // Dispose
  8618. Engine.prototype.dispose = function () {
  8619. this.hideLoadingUI();
  8620. this.stopRenderLoop();
  8621. // Release scenes
  8622. while (this.scenes.length) {
  8623. this.scenes[0].dispose();
  8624. }
  8625. // Release audio engine
  8626. Engine.audioEngine.dispose();
  8627. // Release effects
  8628. for (var name in this._compiledEffects) {
  8629. this._gl.deleteProgram(this._compiledEffects[name]._program);
  8630. }
  8631. // Unbind
  8632. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  8633. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  8634. continue;
  8635. }
  8636. this._gl.disableVertexAttribArray(i);
  8637. }
  8638. this._gl = null;
  8639. //WebVR
  8640. this.disableVR();
  8641. // Events
  8642. window.removeEventListener("blur", this._onBlur);
  8643. window.removeEventListener("focus", this._onFocus);
  8644. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  8645. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  8646. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  8647. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  8648. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  8649. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  8650. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  8651. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  8652. };
  8653. // Loading screen
  8654. Engine.prototype.displayLoadingUI = function () {
  8655. this._loadingScreen.displayLoadingUI();
  8656. };
  8657. Engine.prototype.hideLoadingUI = function () {
  8658. this._loadingScreen.hideLoadingUI();
  8659. };
  8660. Object.defineProperty(Engine.prototype, "loadingScreen", {
  8661. get: function () {
  8662. return this._loadingScreen;
  8663. },
  8664. set: function (loadingScreen) {
  8665. this._loadingScreen = loadingScreen;
  8666. },
  8667. enumerable: true,
  8668. configurable: true
  8669. });
  8670. Object.defineProperty(Engine.prototype, "loadingUIText", {
  8671. set: function (text) {
  8672. this._loadingScreen.loadingUIText = text;
  8673. },
  8674. enumerable: true,
  8675. configurable: true
  8676. });
  8677. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  8678. set: function (color) {
  8679. this._loadingScreen.loadingUIBackgroundColor = color;
  8680. },
  8681. enumerable: true,
  8682. configurable: true
  8683. });
  8684. Engine.prototype.attachContextLostEvent = function (callback) {
  8685. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  8686. };
  8687. Engine.prototype.attachContextRestoredEvent = function (callback) {
  8688. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  8689. };
  8690. // FPS
  8691. Engine.prototype.getFps = function () {
  8692. return this.fps;
  8693. };
  8694. Engine.prototype.getDeltaTime = function () {
  8695. return this.deltaTime;
  8696. };
  8697. Engine.prototype._measureFps = function () {
  8698. this.previousFramesDuration.push(BABYLON.Tools.Now);
  8699. var length = this.previousFramesDuration.length;
  8700. if (length >= 2) {
  8701. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  8702. }
  8703. if (length >= this.fpsRange) {
  8704. if (length > this.fpsRange) {
  8705. this.previousFramesDuration.splice(0, 1);
  8706. length = this.previousFramesDuration.length;
  8707. }
  8708. var sum = 0;
  8709. for (var id = 0; id < length - 1; id++) {
  8710. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  8711. }
  8712. this.fps = 1000.0 / (sum / (length - 1));
  8713. }
  8714. };
  8715. Engine.prototype._canRenderToFloatTexture = function () {
  8716. return this._canRenderToTextureOfType(BABYLON.Engine.TEXTURETYPE_FLOAT, 'OES_texture_float');
  8717. };
  8718. Engine.prototype._canRenderToHalfFloatTexture = function () {
  8719. return this._canRenderToTextureOfType(BABYLON.Engine.TEXTURETYPE_HALF_FLOAT, 'OES_texture_half_float');
  8720. };
  8721. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  8722. Engine.prototype._canRenderToTextureOfType = function (format, extension) {
  8723. var tempcanvas = document.createElement("canvas");
  8724. tempcanvas.height = 16;
  8725. tempcanvas.width = 16;
  8726. var gl = (tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl"));
  8727. // extension.
  8728. var ext = gl.getExtension(extension);
  8729. if (!ext) {
  8730. return false;
  8731. }
  8732. // setup GLSL program
  8733. var vertexCode = "attribute vec4 a_position;\n void main() {\n gl_Position = a_position;\n }";
  8734. 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 }";
  8735. var program = this.createShaderProgram(vertexCode, fragmentCode, null, gl);
  8736. gl.useProgram(program);
  8737. // look up where the vertex data needs to go.
  8738. var positionLocation = gl.getAttribLocation(program, "a_position");
  8739. var colorLoc = gl.getUniformLocation(program, "u_color");
  8740. // provide texture coordinates for the rectangle.
  8741. var positionBuffer = gl.createBuffer();
  8742. gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);
  8743. gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([
  8744. -1.0, -1.0,
  8745. 1.0, -1.0,
  8746. -1.0, 1.0,
  8747. -1.0, 1.0,
  8748. 1.0, -1.0,
  8749. 1.0, 1.0]), gl.STATIC_DRAW);
  8750. gl.enableVertexAttribArray(positionLocation);
  8751. gl.vertexAttribPointer(positionLocation, 2, gl.FLOAT, false, 0, 0);
  8752. var whiteTex = gl.createTexture();
  8753. gl.bindTexture(gl.TEXTURE_2D, whiteTex);
  8754. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, new Uint8Array([255, 255, 255, 255]));
  8755. var tex = gl.createTexture();
  8756. gl.bindTexture(gl.TEXTURE_2D, tex);
  8757. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 1, 1, 0, gl.RGBA, getWebGLTextureType(gl, format), null);
  8758. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  8759. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  8760. var fb = gl.createFramebuffer();
  8761. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  8762. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, tex, 0);
  8763. var cleanup = function () {
  8764. gl.deleteProgram(program);
  8765. gl.disableVertexAttribArray(positionLocation);
  8766. gl.deleteBuffer(positionBuffer);
  8767. gl.deleteFramebuffer(fb);
  8768. gl.deleteTexture(whiteTex);
  8769. gl.deleteTexture(tex);
  8770. };
  8771. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  8772. if (status !== gl.FRAMEBUFFER_COMPLETE) {
  8773. BABYLON.Tools.Log("GL Support: can **NOT** render to " + format + " texture");
  8774. cleanup();
  8775. return false;
  8776. }
  8777. // Draw the rectangle.
  8778. gl.bindTexture(gl.TEXTURE_2D, whiteTex);
  8779. gl.uniform4fv(colorLoc, [0, 10, 20, 1]);
  8780. gl.drawArrays(gl.TRIANGLES, 0, 6);
  8781. gl.bindTexture(gl.TEXTURE_2D, tex);
  8782. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  8783. gl.clearColor(1, 0, 0, 1);
  8784. gl.clear(gl.COLOR_BUFFER_BIT);
  8785. gl.uniform4fv(colorLoc, [0, 1 / 10, 1 / 20, 1]);
  8786. gl.drawArrays(gl.TRIANGLES, 0, 6);
  8787. var pixel = new Uint8Array(4);
  8788. gl.readPixels(0, 0, 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, pixel);
  8789. if (pixel[0] !== 0 ||
  8790. pixel[1] < 248 ||
  8791. pixel[2] < 248 ||
  8792. pixel[3] < 254) {
  8793. BABYLON.Tools.Log("GL Support: Was not able to actually render to " + format + " texture");
  8794. cleanup();
  8795. return false;
  8796. }
  8797. // Succesfully rendered to "format" texture.
  8798. cleanup();
  8799. return true;
  8800. };
  8801. // Statics
  8802. Engine.isSupported = function () {
  8803. try {
  8804. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  8805. if (navigator.isCocoonJS) {
  8806. return true;
  8807. }
  8808. var tempcanvas = document.createElement("canvas");
  8809. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  8810. return gl != null && !!window.WebGLRenderingContext;
  8811. }
  8812. catch (e) {
  8813. return false;
  8814. }
  8815. };
  8816. // Const statics
  8817. Engine._ALPHA_DISABLE = 0;
  8818. Engine._ALPHA_ADD = 1;
  8819. Engine._ALPHA_COMBINE = 2;
  8820. Engine._ALPHA_SUBTRACT = 3;
  8821. Engine._ALPHA_MULTIPLY = 4;
  8822. Engine._ALPHA_MAXIMIZED = 5;
  8823. Engine._ALPHA_ONEONE = 6;
  8824. Engine._DELAYLOADSTATE_NONE = 0;
  8825. Engine._DELAYLOADSTATE_LOADED = 1;
  8826. Engine._DELAYLOADSTATE_LOADING = 2;
  8827. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  8828. Engine._TEXTUREFORMAT_ALPHA = 0;
  8829. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  8830. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  8831. Engine._TEXTUREFORMAT_RGB = 4;
  8832. Engine._TEXTUREFORMAT_RGBA = 5;
  8833. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  8834. Engine._TEXTURETYPE_FLOAT = 1;
  8835. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  8836. // Depht or Stencil test Constants.
  8837. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  8838. Engine._ALWAYS = 0x0207; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will always pass. i.e. Pixels will be drawn in the order they are drawn.
  8839. Engine._LESS = 0x0201; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value.
  8840. Engine._EQUAL = 0x0202; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value.
  8841. Engine._LEQUAL = 0x0203; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than or equal to the stored value.
  8842. Engine._GREATER = 0x0204; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value.
  8843. Engine._GEQUAL = 0x0206; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than or equal to the stored value.
  8844. Engine._NOTEQUAL = 0x0205; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is not equal to the stored value.
  8845. // Stencil Actions Constants.
  8846. Engine._KEEP = 0x1E00;
  8847. Engine._REPLACE = 0x1E01;
  8848. Engine._INCR = 0x1E02;
  8849. Engine._DECR = 0x1E03;
  8850. Engine._INVERT = 0x150A;
  8851. Engine._INCR_WRAP = 0x8507;
  8852. Engine._DECR_WRAP = 0x8508;
  8853. // Updatable statics so stick with vars here
  8854. Engine.CollisionsEpsilon = 0.001;
  8855. Engine.CodeRepository = "src/";
  8856. Engine.ShadersRepository = "src/Shaders/";
  8857. return Engine;
  8858. }());
  8859. BABYLON.Engine = Engine;
  8860. })(BABYLON || (BABYLON = {}));
  8861. var BABYLON;
  8862. (function (BABYLON) {
  8863. /**
  8864. * Node is the basic class for all scene objects (Mesh, Light Camera).
  8865. */
  8866. var Node = (function () {
  8867. /**
  8868. * @constructor
  8869. * @param {string} name - the name and id to be given to this node
  8870. * @param {BABYLON.Scene} the scene this node will be added to
  8871. */
  8872. function Node(name, scene) {
  8873. this.state = "";
  8874. this.animations = new Array();
  8875. this._ranges = {};
  8876. this._childrenFlag = -1;
  8877. this._isEnabled = true;
  8878. this._isReady = true;
  8879. this._currentRenderId = -1;
  8880. this._parentRenderId = -1;
  8881. this.name = name;
  8882. this.id = name;
  8883. this._scene = scene;
  8884. this._initCache();
  8885. }
  8886. Object.defineProperty(Node.prototype, "parent", {
  8887. get: function () {
  8888. return this._parentNode;
  8889. },
  8890. set: function (parent) {
  8891. if (this._parentNode === parent) {
  8892. return;
  8893. }
  8894. if (this._parentNode) {
  8895. var index = this._parentNode._children.indexOf(this);
  8896. if (index !== -1) {
  8897. this._parentNode._children.splice(index, 1);
  8898. }
  8899. }
  8900. this._parentNode = parent;
  8901. if (this._parentNode) {
  8902. if (!this._parentNode._children) {
  8903. this._parentNode._children = new Array();
  8904. }
  8905. this._parentNode._children.push(this);
  8906. }
  8907. },
  8908. enumerable: true,
  8909. configurable: true
  8910. });
  8911. Node.prototype.getScene = function () {
  8912. return this._scene;
  8913. };
  8914. Node.prototype.getEngine = function () {
  8915. return this._scene.getEngine();
  8916. };
  8917. // override it in derived class
  8918. Node.prototype.getWorldMatrix = function () {
  8919. return BABYLON.Matrix.Identity();
  8920. };
  8921. // override it in derived class if you add new variables to the cache
  8922. // and call the parent class method
  8923. Node.prototype._initCache = function () {
  8924. this._cache = {};
  8925. this._cache.parent = undefined;
  8926. };
  8927. Node.prototype.updateCache = function (force) {
  8928. if (!force && this.isSynchronized())
  8929. return;
  8930. this._cache.parent = this.parent;
  8931. this._updateCache();
  8932. };
  8933. // override it in derived class if you add new variables to the cache
  8934. // and call the parent class method if !ignoreParentClass
  8935. Node.prototype._updateCache = function (ignoreParentClass) {
  8936. };
  8937. // override it in derived class if you add new variables to the cache
  8938. Node.prototype._isSynchronized = function () {
  8939. return true;
  8940. };
  8941. Node.prototype._markSyncedWithParent = function () {
  8942. this._parentRenderId = this.parent._currentRenderId;
  8943. };
  8944. Node.prototype.isSynchronizedWithParent = function () {
  8945. if (!this.parent) {
  8946. return true;
  8947. }
  8948. if (this._parentRenderId !== this.parent._currentRenderId) {
  8949. return false;
  8950. }
  8951. return this.parent.isSynchronized();
  8952. };
  8953. Node.prototype.isSynchronized = function (updateCache) {
  8954. var check = this.hasNewParent();
  8955. check = check || !this.isSynchronizedWithParent();
  8956. check = check || !this._isSynchronized();
  8957. if (updateCache)
  8958. this.updateCache(true);
  8959. return !check;
  8960. };
  8961. Node.prototype.hasNewParent = function (update) {
  8962. if (this._cache.parent === this.parent)
  8963. return false;
  8964. if (update)
  8965. this._cache.parent = this.parent;
  8966. return true;
  8967. };
  8968. /**
  8969. * Is this node ready to be used/rendered
  8970. * @return {boolean} is it ready
  8971. */
  8972. Node.prototype.isReady = function () {
  8973. return this._isReady;
  8974. };
  8975. /**
  8976. * Is this node enabled.
  8977. * If the node has a parent and is enabled, the parent will be inspected as well.
  8978. * @return {boolean} whether this node (and its parent) is enabled.
  8979. * @see setEnabled
  8980. */
  8981. Node.prototype.isEnabled = function () {
  8982. if (!this._isEnabled) {
  8983. return false;
  8984. }
  8985. if (this.parent) {
  8986. return this.parent.isEnabled();
  8987. }
  8988. return true;
  8989. };
  8990. /**
  8991. * Set the enabled state of this node.
  8992. * @param {boolean} value - the new enabled state
  8993. * @see isEnabled
  8994. */
  8995. Node.prototype.setEnabled = function (value) {
  8996. this._isEnabled = value;
  8997. };
  8998. /**
  8999. * Is this node a descendant of the given node.
  9000. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  9001. * @param {BABYLON.Node} ancestor - The parent node to inspect
  9002. * @see parent
  9003. */
  9004. Node.prototype.isDescendantOf = function (ancestor) {
  9005. if (this.parent) {
  9006. if (this.parent === ancestor) {
  9007. return true;
  9008. }
  9009. return this.parent.isDescendantOf(ancestor);
  9010. }
  9011. return false;
  9012. };
  9013. /**
  9014. * Evaluate the list of children and determine if they should be considered as descendants considering the given criterias
  9015. * @param {BABYLON.Node[]} results the result array containing the nodes matching the given criterias
  9016. * @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.
  9017. * @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.
  9018. */
  9019. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  9020. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  9021. if (!this._children) {
  9022. return;
  9023. }
  9024. for (var index = 0; index < this._children.length; index++) {
  9025. var item = this._children[index];
  9026. if (!predicate || predicate(item)) {
  9027. results.push(item);
  9028. }
  9029. if (!directDescendantsOnly) {
  9030. item._getDescendants(results, false, predicate);
  9031. }
  9032. }
  9033. };
  9034. /**
  9035. * Will return all nodes that have this node as ascendant.
  9036. * @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.
  9037. * @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.
  9038. * @return {BABYLON.Node[]} all children nodes of all types.
  9039. */
  9040. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  9041. var results = [];
  9042. this._getDescendants(results, directDescendantsOnly, predicate);
  9043. return results;
  9044. };
  9045. /**
  9046. * @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.
  9047. * @Deprecated, legacy support.
  9048. * use getDecendants instead.
  9049. */
  9050. Node.prototype.getChildren = function (predicate) {
  9051. return this.getDescendants(true, predicate);
  9052. };
  9053. /**
  9054. * Get all child-meshes of this node.
  9055. */
  9056. Node.prototype.getChildMeshes = function (directDecendantsOnly, predicate) {
  9057. var results = [];
  9058. this._getDescendants(results, directDecendantsOnly, function (node) {
  9059. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  9060. });
  9061. return results;
  9062. };
  9063. Node.prototype._setReady = function (state) {
  9064. if (state === this._isReady) {
  9065. return;
  9066. }
  9067. if (!state) {
  9068. this._isReady = false;
  9069. return;
  9070. }
  9071. this._isReady = true;
  9072. if (this.onReady) {
  9073. this.onReady(this);
  9074. }
  9075. };
  9076. Node.prototype.getAnimationByName = function (name) {
  9077. for (var i = 0; i < this.animations.length; i++) {
  9078. var animation = this.animations[i];
  9079. if (animation.name === name) {
  9080. return animation;
  9081. }
  9082. }
  9083. return null;
  9084. };
  9085. Node.prototype.createAnimationRange = function (name, from, to) {
  9086. // check name not already in use
  9087. if (!this._ranges[name]) {
  9088. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  9089. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  9090. if (this.animations[i]) {
  9091. this.animations[i].createRange(name, from, to);
  9092. }
  9093. }
  9094. }
  9095. };
  9096. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  9097. if (deleteFrames === void 0) { deleteFrames = true; }
  9098. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  9099. if (this.animations[i]) {
  9100. this.animations[i].deleteRange(name, deleteFrames);
  9101. }
  9102. }
  9103. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  9104. };
  9105. Node.prototype.getAnimationRange = function (name) {
  9106. return this._ranges[name];
  9107. };
  9108. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  9109. var range = this.getAnimationRange(name);
  9110. if (!range) {
  9111. return null;
  9112. }
  9113. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  9114. };
  9115. Node.prototype.serializeAnimationRanges = function () {
  9116. var serializationRanges = [];
  9117. for (var name in this._ranges) {
  9118. var range = {};
  9119. range.name = name;
  9120. range.from = this._ranges[name].from;
  9121. range.to = this._ranges[name].to;
  9122. serializationRanges.push(range);
  9123. }
  9124. return serializationRanges;
  9125. };
  9126. Node.prototype.dispose = function () {
  9127. this.parent = null;
  9128. };
  9129. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  9130. if (parsedNode.ranges) {
  9131. for (var index = 0; index < parsedNode.ranges.length; index++) {
  9132. var data = parsedNode.ranges[index];
  9133. node.createAnimationRange(data.name, data.from, data.to);
  9134. }
  9135. }
  9136. };
  9137. __decorate([
  9138. BABYLON.serialize()
  9139. ], Node.prototype, "name", void 0);
  9140. __decorate([
  9141. BABYLON.serialize()
  9142. ], Node.prototype, "id", void 0);
  9143. __decorate([
  9144. BABYLON.serialize()
  9145. ], Node.prototype, "uniqueId", void 0);
  9146. __decorate([
  9147. BABYLON.serialize()
  9148. ], Node.prototype, "state", void 0);
  9149. return Node;
  9150. }());
  9151. BABYLON.Node = Node;
  9152. })(BABYLON || (BABYLON = {}));
  9153. var BABYLON;
  9154. (function (BABYLON) {
  9155. var FilesInput = (function () {
  9156. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  9157. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  9158. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  9159. this._engine = p_engine;
  9160. this._canvas = p_canvas;
  9161. this._currentScene = p_scene;
  9162. this._sceneLoadedCallback = p_sceneLoadedCallback;
  9163. this._progressCallback = p_progressCallback;
  9164. this._additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  9165. this._textureLoadingCallback = p_textureLoadingCallback;
  9166. this._startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  9167. }
  9168. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  9169. var _this = this;
  9170. if (p_elementToMonitor) {
  9171. this._elementToMonitor = p_elementToMonitor;
  9172. this._elementToMonitor.addEventListener("dragenter", function (e) { _this.drag(e); }, false);
  9173. this._elementToMonitor.addEventListener("dragover", function (e) { _this.drag(e); }, false);
  9174. this._elementToMonitor.addEventListener("drop", function (e) { _this.drop(e); }, false);
  9175. }
  9176. };
  9177. FilesInput.prototype.renderFunction = function () {
  9178. if (this._additionnalRenderLoopLogicCallback) {
  9179. this._additionnalRenderLoopLogicCallback();
  9180. }
  9181. if (this._currentScene) {
  9182. if (this._textureLoadingCallback) {
  9183. var remaining = this._currentScene.getWaitingItemsCount();
  9184. if (remaining > 0) {
  9185. this._textureLoadingCallback(remaining);
  9186. }
  9187. }
  9188. this._currentScene.render();
  9189. }
  9190. };
  9191. FilesInput.prototype.drag = function (e) {
  9192. e.stopPropagation();
  9193. e.preventDefault();
  9194. };
  9195. FilesInput.prototype.drop = function (eventDrop) {
  9196. eventDrop.stopPropagation();
  9197. eventDrop.preventDefault();
  9198. this.loadFiles(eventDrop);
  9199. };
  9200. FilesInput.prototype.loadFiles = function (event) {
  9201. if (this._startingProcessingFilesCallback)
  9202. this._startingProcessingFilesCallback();
  9203. // Handling data transfer via drag'n'drop
  9204. if (event && event.dataTransfer && event.dataTransfer.files) {
  9205. this._filesToLoad = event.dataTransfer.files;
  9206. }
  9207. // Handling files from input files
  9208. if (event && event.target && event.target.files) {
  9209. this._filesToLoad = event.target.files;
  9210. }
  9211. if (this._filesToLoad && this._filesToLoad.length > 0) {
  9212. for (var i = 0; i < this._filesToLoad.length; i++) {
  9213. switch (this._filesToLoad[i].type) {
  9214. case "image/jpeg":
  9215. case "image/png":
  9216. case "image/bmp":
  9217. FilesInput.FilesTextures[this._filesToLoad[i].name.toLowerCase()] = this._filesToLoad[i];
  9218. break;
  9219. case "image/targa":
  9220. case "image/vnd.ms-dds":
  9221. case "audio/wav":
  9222. case "audio/x-wav":
  9223. case "audio/mp3":
  9224. case "audio/mpeg":
  9225. case "audio/mpeg3":
  9226. case "audio/x-mpeg-3":
  9227. case "audio/ogg":
  9228. FilesInput.FilesToLoad[this._filesToLoad[i].name.toLowerCase()] = this._filesToLoad[i];
  9229. break;
  9230. default:
  9231. if (this._filesToLoad[i].name.indexOf(".mtl") !== -1) {
  9232. FilesInput.FilesToLoad[this._filesToLoad[i].name.toLowerCase()] = this._filesToLoad[i];
  9233. }
  9234. else if ((this._filesToLoad[i].name.indexOf(".babylon") !== -1 ||
  9235. this._filesToLoad[i].name.indexOf(".stl") !== -1 ||
  9236. this._filesToLoad[i].name.indexOf(".obj") !== -1)
  9237. && this._filesToLoad[i].name.indexOf(".manifest") === -1
  9238. && this._filesToLoad[i].name.indexOf(".incremental") === -1 && this._filesToLoad[i].name.indexOf(".babylonmeshdata") === -1
  9239. && this._filesToLoad[i].name.indexOf(".babylongeometrydata") === -1 && this._filesToLoad[i].name.indexOf(".babylonbinarymeshdata") === -1 &&
  9240. this._filesToLoad[i].name.indexOf(".binary.babylon") === -1) {
  9241. this._sceneFileToLoad = this._filesToLoad[i];
  9242. }
  9243. break;
  9244. }
  9245. }
  9246. this.reload();
  9247. }
  9248. };
  9249. FilesInput.prototype.reload = function () {
  9250. var _this = this;
  9251. var that = this;
  9252. // If a ".babylon" file has been provided
  9253. if (this._sceneFileToLoad) {
  9254. if (this._currentScene) {
  9255. if (BABYLON.Tools.errorsCount > 0) {
  9256. BABYLON.Tools.ClearLogCache();
  9257. BABYLON.Tools.Log("Babylon.js engine (v" + BABYLON.Engine.Version + ") launched");
  9258. }
  9259. this._engine.stopRenderLoop();
  9260. this._currentScene.dispose();
  9261. }
  9262. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  9263. that._currentScene = newScene;
  9264. // Wait for textures and shaders to be ready
  9265. that._currentScene.executeWhenReady(function () {
  9266. // Attach camera to canvas inputs
  9267. if (!that._currentScene.activeCamera || that._currentScene.lights.length === 0) {
  9268. that._currentScene.createDefaultCameraOrLight();
  9269. }
  9270. that._currentScene.activeCamera.attachControl(that._canvas);
  9271. if (that._sceneLoadedCallback) {
  9272. that._sceneLoadedCallback(_this._sceneFileToLoad, that._currentScene);
  9273. }
  9274. that._engine.runRenderLoop(function () { that.renderFunction(); });
  9275. });
  9276. }, function (progress) {
  9277. if (_this._progressCallback) {
  9278. _this._progressCallback(progress);
  9279. }
  9280. });
  9281. }
  9282. else {
  9283. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  9284. }
  9285. };
  9286. FilesInput.FilesTextures = new Array();
  9287. FilesInput.FilesToLoad = new Array();
  9288. return FilesInput;
  9289. }());
  9290. BABYLON.FilesInput = FilesInput;
  9291. })(BABYLON || (BABYLON = {}));
  9292. var BABYLON;
  9293. (function (BABYLON) {
  9294. var IntersectionInfo = (function () {
  9295. function IntersectionInfo(bu, bv, distance) {
  9296. this.bu = bu;
  9297. this.bv = bv;
  9298. this.distance = distance;
  9299. this.faceId = 0;
  9300. this.subMeshId = 0;
  9301. }
  9302. return IntersectionInfo;
  9303. }());
  9304. BABYLON.IntersectionInfo = IntersectionInfo;
  9305. var PickingInfo = (function () {
  9306. function PickingInfo() {
  9307. this.hit = false;
  9308. this.distance = 0;
  9309. this.pickedPoint = null;
  9310. this.pickedMesh = null;
  9311. this.bu = 0;
  9312. this.bv = 0;
  9313. this.faceId = -1;
  9314. this.subMeshId = 0;
  9315. this.pickedSprite = null;
  9316. }
  9317. // Methods
  9318. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  9319. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  9320. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  9321. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  9322. return null;
  9323. }
  9324. var indices = this.pickedMesh.getIndices();
  9325. var result;
  9326. if (useVerticesNormals) {
  9327. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  9328. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  9329. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  9330. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  9331. normal0 = normal0.scale(this.bu);
  9332. normal1 = normal1.scale(this.bv);
  9333. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  9334. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  9335. }
  9336. else {
  9337. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  9338. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  9339. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  9340. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  9341. var p1p2 = vertex1.subtract(vertex2);
  9342. var p3p2 = vertex3.subtract(vertex2);
  9343. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  9344. }
  9345. if (useWorldCoordinates) {
  9346. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  9347. }
  9348. return BABYLON.Vector3.Normalize(result);
  9349. };
  9350. PickingInfo.prototype.getTextureCoordinates = function () {
  9351. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  9352. return null;
  9353. }
  9354. var indices = this.pickedMesh.getIndices();
  9355. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  9356. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  9357. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  9358. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  9359. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  9360. uv1 = uv1.scale(this.bu);
  9361. uv2 = uv2.scale(this.bv);
  9362. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  9363. };
  9364. return PickingInfo;
  9365. }());
  9366. BABYLON.PickingInfo = PickingInfo;
  9367. })(BABYLON || (BABYLON = {}));
  9368. var BABYLON;
  9369. (function (BABYLON) {
  9370. var BoundingSphere = (function () {
  9371. function BoundingSphere(minimum, maximum) {
  9372. this.minimum = minimum;
  9373. this.maximum = maximum;
  9374. this._tempRadiusVector = BABYLON.Vector3.Zero();
  9375. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  9376. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  9377. this.radius = distance * 0.5;
  9378. this.centerWorld = BABYLON.Vector3.Zero();
  9379. this._update(BABYLON.Matrix.Identity());
  9380. }
  9381. // Methods
  9382. BoundingSphere.prototype._update = function (world) {
  9383. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  9384. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  9385. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  9386. };
  9387. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  9388. for (var i = 0; i < 6; i++) {
  9389. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  9390. return false;
  9391. }
  9392. return true;
  9393. };
  9394. BoundingSphere.prototype.intersectsPoint = function (point) {
  9395. var x = this.centerWorld.x - point.x;
  9396. var y = this.centerWorld.y - point.y;
  9397. var z = this.centerWorld.z - point.z;
  9398. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  9399. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  9400. return false;
  9401. return true;
  9402. };
  9403. // Statics
  9404. BoundingSphere.Intersects = function (sphere0, sphere1) {
  9405. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  9406. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  9407. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  9408. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  9409. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  9410. return false;
  9411. return true;
  9412. };
  9413. return BoundingSphere;
  9414. }());
  9415. BABYLON.BoundingSphere = BoundingSphere;
  9416. })(BABYLON || (BABYLON = {}));
  9417. var BABYLON;
  9418. (function (BABYLON) {
  9419. var BoundingBox = (function () {
  9420. function BoundingBox(minimum, maximum) {
  9421. this.minimum = minimum;
  9422. this.maximum = maximum;
  9423. this.vectors = new Array();
  9424. this.vectorsWorld = new Array();
  9425. // Bounding vectors
  9426. this.vectors.push(this.minimum.clone());
  9427. this.vectors.push(this.maximum.clone());
  9428. this.vectors.push(this.minimum.clone());
  9429. this.vectors[2].x = this.maximum.x;
  9430. this.vectors.push(this.minimum.clone());
  9431. this.vectors[3].y = this.maximum.y;
  9432. this.vectors.push(this.minimum.clone());
  9433. this.vectors[4].z = this.maximum.z;
  9434. this.vectors.push(this.maximum.clone());
  9435. this.vectors[5].z = this.minimum.z;
  9436. this.vectors.push(this.maximum.clone());
  9437. this.vectors[6].x = this.minimum.x;
  9438. this.vectors.push(this.maximum.clone());
  9439. this.vectors[7].y = this.minimum.y;
  9440. // OBB
  9441. this.center = this.maximum.add(this.minimum).scale(0.5);
  9442. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  9443. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  9444. // World
  9445. for (var index = 0; index < this.vectors.length; index++) {
  9446. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  9447. }
  9448. this.minimumWorld = BABYLON.Vector3.Zero();
  9449. this.maximumWorld = BABYLON.Vector3.Zero();
  9450. this._update(BABYLON.Matrix.Identity());
  9451. }
  9452. // Methods
  9453. BoundingBox.prototype.getWorldMatrix = function () {
  9454. return this._worldMatrix;
  9455. };
  9456. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  9457. this._worldMatrix.copyFrom(matrix);
  9458. return this;
  9459. };
  9460. BoundingBox.prototype._update = function (world) {
  9461. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  9462. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  9463. for (var index = 0; index < this.vectors.length; index++) {
  9464. var v = this.vectorsWorld[index];
  9465. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  9466. if (v.x < this.minimumWorld.x)
  9467. this.minimumWorld.x = v.x;
  9468. if (v.y < this.minimumWorld.y)
  9469. this.minimumWorld.y = v.y;
  9470. if (v.z < this.minimumWorld.z)
  9471. this.minimumWorld.z = v.z;
  9472. if (v.x > this.maximumWorld.x)
  9473. this.maximumWorld.x = v.x;
  9474. if (v.y > this.maximumWorld.y)
  9475. this.maximumWorld.y = v.y;
  9476. if (v.z > this.maximumWorld.z)
  9477. this.maximumWorld.z = v.z;
  9478. }
  9479. // OBB
  9480. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  9481. this.center.scaleInPlace(0.5);
  9482. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  9483. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  9484. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  9485. this._worldMatrix = world;
  9486. };
  9487. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  9488. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  9489. };
  9490. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  9491. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  9492. };
  9493. BoundingBox.prototype.intersectsPoint = function (point) {
  9494. var delta = -BABYLON.Epsilon;
  9495. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  9496. return false;
  9497. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  9498. return false;
  9499. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  9500. return false;
  9501. return true;
  9502. };
  9503. BoundingBox.prototype.intersectsSphere = function (sphere) {
  9504. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  9505. };
  9506. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  9507. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  9508. return false;
  9509. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  9510. return false;
  9511. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  9512. return false;
  9513. return true;
  9514. };
  9515. // Statics
  9516. BoundingBox.Intersects = function (box0, box1) {
  9517. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  9518. return false;
  9519. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  9520. return false;
  9521. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  9522. return false;
  9523. return true;
  9524. };
  9525. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  9526. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  9527. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  9528. return (num <= (sphereRadius * sphereRadius));
  9529. };
  9530. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  9531. for (var p = 0; p < 6; p++) {
  9532. for (var i = 0; i < 8; i++) {
  9533. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  9534. return false;
  9535. }
  9536. }
  9537. }
  9538. return true;
  9539. };
  9540. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  9541. for (var p = 0; p < 6; p++) {
  9542. var inCount = 8;
  9543. for (var i = 0; i < 8; i++) {
  9544. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  9545. --inCount;
  9546. }
  9547. else {
  9548. break;
  9549. }
  9550. }
  9551. if (inCount === 0)
  9552. return false;
  9553. }
  9554. return true;
  9555. };
  9556. return BoundingBox;
  9557. }());
  9558. BABYLON.BoundingBox = BoundingBox;
  9559. })(BABYLON || (BABYLON = {}));
  9560. var BABYLON;
  9561. (function (BABYLON) {
  9562. var computeBoxExtents = function (axis, box) {
  9563. var p = BABYLON.Vector3.Dot(box.center, axis);
  9564. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  9565. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  9566. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  9567. var r = r0 + r1 + r2;
  9568. return {
  9569. min: p - r,
  9570. max: p + r
  9571. };
  9572. };
  9573. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  9574. var axisOverlap = function (axis, box0, box1) {
  9575. var result0 = computeBoxExtents(axis, box0);
  9576. var result1 = computeBoxExtents(axis, box1);
  9577. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  9578. };
  9579. var BoundingInfo = (function () {
  9580. function BoundingInfo(minimum, maximum) {
  9581. this.minimum = minimum;
  9582. this.maximum = maximum;
  9583. this._isLocked = false;
  9584. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  9585. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  9586. }
  9587. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  9588. get: function () {
  9589. return this._isLocked;
  9590. },
  9591. set: function (value) {
  9592. this._isLocked = value;
  9593. },
  9594. enumerable: true,
  9595. configurable: true
  9596. });
  9597. // Methods
  9598. BoundingInfo.prototype.update = function (world) {
  9599. if (this._isLocked) {
  9600. return;
  9601. }
  9602. this.boundingBox._update(world);
  9603. this.boundingSphere._update(world);
  9604. };
  9605. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  9606. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  9607. return false;
  9608. return this.boundingBox.isInFrustum(frustumPlanes);
  9609. };
  9610. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  9611. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  9612. };
  9613. BoundingInfo.prototype._checkCollision = function (collider) {
  9614. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  9615. };
  9616. BoundingInfo.prototype.intersectsPoint = function (point) {
  9617. if (!this.boundingSphere.centerWorld) {
  9618. return false;
  9619. }
  9620. if (!this.boundingSphere.intersectsPoint(point)) {
  9621. return false;
  9622. }
  9623. if (!this.boundingBox.intersectsPoint(point)) {
  9624. return false;
  9625. }
  9626. return true;
  9627. };
  9628. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  9629. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  9630. return false;
  9631. }
  9632. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  9633. return false;
  9634. }
  9635. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  9636. return false;
  9637. }
  9638. if (!precise) {
  9639. return true;
  9640. }
  9641. var box0 = this.boundingBox;
  9642. var box1 = boundingInfo.boundingBox;
  9643. if (!axisOverlap(box0.directions[0], box0, box1))
  9644. return false;
  9645. if (!axisOverlap(box0.directions[1], box0, box1))
  9646. return false;
  9647. if (!axisOverlap(box0.directions[2], box0, box1))
  9648. return false;
  9649. if (!axisOverlap(box1.directions[0], box0, box1))
  9650. return false;
  9651. if (!axisOverlap(box1.directions[1], box0, box1))
  9652. return false;
  9653. if (!axisOverlap(box1.directions[2], box0, box1))
  9654. return false;
  9655. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  9656. return false;
  9657. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  9658. return false;
  9659. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  9660. return false;
  9661. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  9662. return false;
  9663. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  9664. return false;
  9665. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  9666. return false;
  9667. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  9668. return false;
  9669. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  9670. return false;
  9671. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  9672. return false;
  9673. return true;
  9674. };
  9675. return BoundingInfo;
  9676. }());
  9677. BABYLON.BoundingInfo = BoundingInfo;
  9678. })(BABYLON || (BABYLON = {}));
  9679. var BABYLON;
  9680. (function (BABYLON) {
  9681. var Ray = (function () {
  9682. function Ray(origin, direction, length) {
  9683. if (length === void 0) { length = Number.MAX_VALUE; }
  9684. this.origin = origin;
  9685. this.direction = direction;
  9686. this.length = length;
  9687. }
  9688. // Methods
  9689. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  9690. var d = 0.0;
  9691. var maxValue = Number.MAX_VALUE;
  9692. var inv;
  9693. var min;
  9694. var max;
  9695. var temp;
  9696. if (Math.abs(this.direction.x) < 0.0000001) {
  9697. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  9698. return false;
  9699. }
  9700. }
  9701. else {
  9702. inv = 1.0 / this.direction.x;
  9703. min = (minimum.x - this.origin.x) * inv;
  9704. max = (maximum.x - this.origin.x) * inv;
  9705. if (max === -Infinity) {
  9706. max = Infinity;
  9707. }
  9708. if (min > max) {
  9709. temp = min;
  9710. min = max;
  9711. max = temp;
  9712. }
  9713. d = Math.max(min, d);
  9714. maxValue = Math.min(max, maxValue);
  9715. if (d > maxValue) {
  9716. return false;
  9717. }
  9718. }
  9719. if (Math.abs(this.direction.y) < 0.0000001) {
  9720. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  9721. return false;
  9722. }
  9723. }
  9724. else {
  9725. inv = 1.0 / this.direction.y;
  9726. min = (minimum.y - this.origin.y) * inv;
  9727. max = (maximum.y - this.origin.y) * inv;
  9728. if (max === -Infinity) {
  9729. max = Infinity;
  9730. }
  9731. if (min > max) {
  9732. temp = min;
  9733. min = max;
  9734. max = temp;
  9735. }
  9736. d = Math.max(min, d);
  9737. maxValue = Math.min(max, maxValue);
  9738. if (d > maxValue) {
  9739. return false;
  9740. }
  9741. }
  9742. if (Math.abs(this.direction.z) < 0.0000001) {
  9743. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  9744. return false;
  9745. }
  9746. }
  9747. else {
  9748. inv = 1.0 / this.direction.z;
  9749. min = (minimum.z - this.origin.z) * inv;
  9750. max = (maximum.z - this.origin.z) * inv;
  9751. if (max === -Infinity) {
  9752. max = Infinity;
  9753. }
  9754. if (min > max) {
  9755. temp = min;
  9756. min = max;
  9757. max = temp;
  9758. }
  9759. d = Math.max(min, d);
  9760. maxValue = Math.min(max, maxValue);
  9761. if (d > maxValue) {
  9762. return false;
  9763. }
  9764. }
  9765. return true;
  9766. };
  9767. Ray.prototype.intersectsBox = function (box) {
  9768. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  9769. };
  9770. Ray.prototype.intersectsSphere = function (sphere) {
  9771. var x = sphere.center.x - this.origin.x;
  9772. var y = sphere.center.y - this.origin.y;
  9773. var z = sphere.center.z - this.origin.z;
  9774. var pyth = (x * x) + (y * y) + (z * z);
  9775. var rr = sphere.radius * sphere.radius;
  9776. if (pyth <= rr) {
  9777. return true;
  9778. }
  9779. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  9780. if (dot < 0.0) {
  9781. return false;
  9782. }
  9783. var temp = pyth - (dot * dot);
  9784. return temp <= rr;
  9785. };
  9786. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  9787. if (!this._edge1) {
  9788. this._edge1 = BABYLON.Vector3.Zero();
  9789. this._edge2 = BABYLON.Vector3.Zero();
  9790. this._pvec = BABYLON.Vector3.Zero();
  9791. this._tvec = BABYLON.Vector3.Zero();
  9792. this._qvec = BABYLON.Vector3.Zero();
  9793. }
  9794. vertex1.subtractToRef(vertex0, this._edge1);
  9795. vertex2.subtractToRef(vertex0, this._edge2);
  9796. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  9797. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  9798. if (det === 0) {
  9799. return null;
  9800. }
  9801. var invdet = 1 / det;
  9802. this.origin.subtractToRef(vertex0, this._tvec);
  9803. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  9804. if (bu < 0 || bu > 1.0) {
  9805. return null;
  9806. }
  9807. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  9808. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  9809. if (bv < 0 || bu + bv > 1.0) {
  9810. return null;
  9811. }
  9812. //check if the distance is longer than the predefined length.
  9813. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  9814. if (distance > this.length) {
  9815. return null;
  9816. }
  9817. return new BABYLON.IntersectionInfo(bu, bv, distance);
  9818. };
  9819. Ray.prototype.intersectsPlane = function (plane) {
  9820. var distance;
  9821. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  9822. if (Math.abs(result1) < 9.99999997475243E-07) {
  9823. return null;
  9824. }
  9825. else {
  9826. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  9827. distance = (-plane.d - result2) / result1;
  9828. if (distance < 0.0) {
  9829. if (distance < -9.99999997475243E-07) {
  9830. return null;
  9831. }
  9832. else {
  9833. return 0;
  9834. }
  9835. }
  9836. return distance;
  9837. }
  9838. };
  9839. /**
  9840. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  9841. * @param sega the first point of the segment to test the intersection against
  9842. * @param segb the second point of the segment to test the intersection against
  9843. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  9844. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  9845. */
  9846. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  9847. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  9848. var u = segb.subtract(sega);
  9849. var v = rsegb.subtract(this.origin);
  9850. var w = sega.subtract(this.origin);
  9851. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  9852. var b = BABYLON.Vector3.Dot(u, v);
  9853. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  9854. var d = BABYLON.Vector3.Dot(u, w);
  9855. var e = BABYLON.Vector3.Dot(v, w);
  9856. var D = a * c - b * b; // always >= 0
  9857. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  9858. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  9859. // compute the line parameters of the two closest points
  9860. if (D < Ray.smallnum) {
  9861. sN = 0.0; // force using point P0 on segment S1
  9862. sD = 1.0; // to prevent possible division by 0.0 later
  9863. tN = e;
  9864. tD = c;
  9865. }
  9866. else {
  9867. sN = (b * e - c * d);
  9868. tN = (a * e - b * d);
  9869. if (sN < 0.0) {
  9870. sN = 0.0;
  9871. tN = e;
  9872. tD = c;
  9873. }
  9874. else if (sN > sD) {
  9875. sN = sD;
  9876. tN = e + b;
  9877. tD = c;
  9878. }
  9879. }
  9880. if (tN < 0.0) {
  9881. tN = 0.0;
  9882. // recompute sc for this edge
  9883. if (-d < 0.0) {
  9884. sN = 0.0;
  9885. }
  9886. else if (-d > a)
  9887. sN = sD;
  9888. else {
  9889. sN = -d;
  9890. sD = a;
  9891. }
  9892. }
  9893. else if (tN > tD) {
  9894. tN = tD;
  9895. // recompute sc for this edge
  9896. if ((-d + b) < 0.0) {
  9897. sN = 0;
  9898. }
  9899. else if ((-d + b) > a) {
  9900. sN = sD;
  9901. }
  9902. else {
  9903. sN = (-d + b);
  9904. sD = a;
  9905. }
  9906. }
  9907. // finally do the division to get sc and tc
  9908. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  9909. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  9910. // get the difference of the two closest points
  9911. var qtc = v.multiplyByFloats(tc, tc, tc);
  9912. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  9913. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  9914. if (isIntersected) {
  9915. return qtc.length();
  9916. }
  9917. return -1;
  9918. };
  9919. // Statics
  9920. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  9921. var start = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  9922. var end = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  9923. var direction = end.subtract(start);
  9924. direction.normalize();
  9925. return new Ray(start, direction);
  9926. };
  9927. /**
  9928. * 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
  9929. * transformed to the given world matrix.
  9930. * @param origin The origin point
  9931. * @param end The end point
  9932. * @param world a matrix to transform the ray to. Default is the identity matrix.
  9933. */
  9934. Ray.CreateNewFromTo = function (origin, end, world) {
  9935. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  9936. var direction = end.subtract(origin);
  9937. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  9938. direction.normalize();
  9939. return Ray.Transform(new Ray(origin, direction, length), world);
  9940. };
  9941. Ray.Transform = function (ray, matrix) {
  9942. var newOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, matrix);
  9943. var newDirection = BABYLON.Vector3.TransformNormal(ray.direction, matrix);
  9944. newDirection.normalize();
  9945. return new Ray(newOrigin, newDirection, ray.length);
  9946. };
  9947. Ray.smallnum = 0.00000001;
  9948. Ray.rayl = 10e8;
  9949. return Ray;
  9950. }());
  9951. BABYLON.Ray = Ray;
  9952. })(BABYLON || (BABYLON = {}));
  9953. var BABYLON;
  9954. (function (BABYLON) {
  9955. var AbstractMesh = (function (_super) {
  9956. __extends(AbstractMesh, _super);
  9957. // Constructor
  9958. function AbstractMesh(name, scene) {
  9959. var _this = this;
  9960. _super.call(this, name, scene);
  9961. // Events
  9962. /**
  9963. * An event triggered when the mesh is disposed.
  9964. * @type {BABYLON.Observable}
  9965. */
  9966. this.onDisposeObservable = new BABYLON.Observable();
  9967. /**
  9968. * An event triggered when this mesh collides with another one
  9969. * @type {BABYLON.Observable}
  9970. */
  9971. this.onCollideObservable = new BABYLON.Observable();
  9972. /**
  9973. * An event triggered when the collision's position changes
  9974. * @type {BABYLON.Observable}
  9975. */
  9976. this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  9977. /**
  9978. * An event triggered after the world matrix is updated
  9979. * @type {BABYLON.Observable}
  9980. */
  9981. this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  9982. // Properties
  9983. this.definedFacingForward = true; // orientation for POV movement & rotation
  9984. this.position = new BABYLON.Vector3(0, 0, 0);
  9985. this._rotation = new BABYLON.Vector3(0, 0, 0);
  9986. this._scaling = new BABYLON.Vector3(1, 1, 1);
  9987. this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  9988. this.visibility = 1.0;
  9989. this.alphaIndex = Number.MAX_VALUE;
  9990. this.infiniteDistance = false;
  9991. this.isVisible = true;
  9992. this.isPickable = true;
  9993. this.showBoundingBox = false;
  9994. this.showSubMeshesBoundingBox = false;
  9995. this.isBlocker = false;
  9996. this.renderingGroupId = 0;
  9997. this.receiveShadows = false;
  9998. this.renderOutline = false;
  9999. this.outlineColor = BABYLON.Color3.Red();
  10000. this.outlineWidth = 0.02;
  10001. this.renderOverlay = false;
  10002. this.overlayColor = BABYLON.Color3.Red();
  10003. this.overlayAlpha = 0.5;
  10004. this.hasVertexAlpha = false;
  10005. this.useVertexColors = true;
  10006. this.applyFog = true;
  10007. this.computeBonesUsingShaders = true;
  10008. this.scalingDeterminant = 1;
  10009. this.numBoneInfluencers = 4;
  10010. this.useOctreeForRenderingSelection = true;
  10011. this.useOctreeForPicking = true;
  10012. this.useOctreeForCollisions = true;
  10013. this.layerMask = 0x0FFFFFFF;
  10014. this.alwaysSelectAsActiveMesh = false;
  10015. // Collisions
  10016. this._checkCollisions = false;
  10017. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  10018. this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  10019. this._collider = new BABYLON.Collider();
  10020. this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  10021. this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  10022. this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  10023. // Edges
  10024. this.edgesWidth = 1;
  10025. this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  10026. // Cache
  10027. this._localWorld = BABYLON.Matrix.Zero();
  10028. this._worldMatrix = BABYLON.Matrix.Zero();
  10029. this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  10030. this._absolutePosition = BABYLON.Vector3.Zero();
  10031. this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  10032. this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  10033. this._isDirty = false;
  10034. this._pivotMatrix = BABYLON.Matrix.Identity();
  10035. this._isDisposed = false;
  10036. this._renderId = 0;
  10037. this._intersectionsInProgress = new Array();
  10038. this._isWorldMatrixFrozen = false;
  10039. this._unIndexed = false;
  10040. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  10041. if (collidedMesh === void 0) { collidedMesh = null; }
  10042. //TODO move this to the collision coordinator!
  10043. if (_this.getScene().workerCollisions)
  10044. newPosition.multiplyInPlace(_this._collider.radius);
  10045. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  10046. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  10047. _this.position.addInPlace(_this._diffPositionForCollisions);
  10048. }
  10049. if (collidedMesh) {
  10050. _this.onCollideObservable.notifyObservers(collidedMesh);
  10051. }
  10052. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  10053. };
  10054. scene.addMesh(this);
  10055. }
  10056. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  10057. get: function () {
  10058. return AbstractMesh._BILLBOARDMODE_NONE;
  10059. },
  10060. enumerable: true,
  10061. configurable: true
  10062. });
  10063. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  10064. get: function () {
  10065. return AbstractMesh._BILLBOARDMODE_X;
  10066. },
  10067. enumerable: true,
  10068. configurable: true
  10069. });
  10070. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  10071. get: function () {
  10072. return AbstractMesh._BILLBOARDMODE_Y;
  10073. },
  10074. enumerable: true,
  10075. configurable: true
  10076. });
  10077. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  10078. get: function () {
  10079. return AbstractMesh._BILLBOARDMODE_Z;
  10080. },
  10081. enumerable: true,
  10082. configurable: true
  10083. });
  10084. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  10085. get: function () {
  10086. return AbstractMesh._BILLBOARDMODE_ALL;
  10087. },
  10088. enumerable: true,
  10089. configurable: true
  10090. });
  10091. Object.defineProperty(AbstractMesh.prototype, "onDispose", {
  10092. set: function (callback) {
  10093. if (this._onDisposeObserver) {
  10094. this.onDisposeObservable.remove(this._onDisposeObserver);
  10095. }
  10096. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  10097. },
  10098. enumerable: true,
  10099. configurable: true
  10100. });
  10101. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  10102. set: function (callback) {
  10103. if (this._onCollideObserver) {
  10104. this.onCollideObservable.remove(this._onCollideObserver);
  10105. }
  10106. this._onCollideObserver = this.onCollideObservable.add(callback);
  10107. },
  10108. enumerable: true,
  10109. configurable: true
  10110. });
  10111. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  10112. set: function (callback) {
  10113. if (this._onCollisionPositionChangeObserver) {
  10114. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  10115. }
  10116. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  10117. },
  10118. enumerable: true,
  10119. configurable: true
  10120. });
  10121. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  10122. get: function () {
  10123. return this._skeleton;
  10124. },
  10125. set: function (value) {
  10126. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  10127. this._skeleton._unregisterMeshWithPoseMatrix(this);
  10128. }
  10129. if (value && value.needInitialSkinMatrix) {
  10130. value._registerMeshWithPoseMatrix(this);
  10131. }
  10132. this._skeleton = value;
  10133. if (!this._skeleton) {
  10134. this._bonesTransformMatrices = null;
  10135. }
  10136. },
  10137. enumerable: true,
  10138. configurable: true
  10139. });
  10140. /**
  10141. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  10142. */
  10143. AbstractMesh.prototype.toString = function (fullDetails) {
  10144. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  10145. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  10146. if (this._skeleton) {
  10147. ret += ", skeleton: " + this._skeleton.name;
  10148. }
  10149. if (fullDetails) {
  10150. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  10151. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  10152. }
  10153. return ret;
  10154. };
  10155. Object.defineProperty(AbstractMesh.prototype, "rotation", {
  10156. /**
  10157. * Getting the rotation object.
  10158. * If rotation quaternion is set, this vector will (almost always) be the Zero vector!
  10159. */
  10160. get: function () {
  10161. return this._rotation;
  10162. },
  10163. set: function (newRotation) {
  10164. this._rotation = newRotation;
  10165. },
  10166. enumerable: true,
  10167. configurable: true
  10168. });
  10169. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  10170. get: function () {
  10171. return this._scaling;
  10172. },
  10173. set: function (newScaling) {
  10174. this._scaling = newScaling;
  10175. if (this.physicsImpostor) {
  10176. this.physicsImpostor.forceUpdate();
  10177. }
  10178. },
  10179. enumerable: true,
  10180. configurable: true
  10181. });
  10182. Object.defineProperty(AbstractMesh.prototype, "rotationQuaternion", {
  10183. get: function () {
  10184. return this._rotationQuaternion;
  10185. },
  10186. set: function (quaternion) {
  10187. this._rotationQuaternion = quaternion;
  10188. //reset the rotation vector.
  10189. if (quaternion && this.rotation.length()) {
  10190. this.rotation.copyFromFloats(0, 0, 0);
  10191. }
  10192. },
  10193. enumerable: true,
  10194. configurable: true
  10195. });
  10196. // Methods
  10197. AbstractMesh.prototype.updatePoseMatrix = function (matrix) {
  10198. this._poseMatrix.copyFrom(matrix);
  10199. };
  10200. AbstractMesh.prototype.getPoseMatrix = function () {
  10201. return this._poseMatrix;
  10202. };
  10203. AbstractMesh.prototype.disableEdgesRendering = function () {
  10204. if (this._edgesRenderer !== undefined) {
  10205. this._edgesRenderer.dispose();
  10206. this._edgesRenderer = undefined;
  10207. }
  10208. };
  10209. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  10210. if (epsilon === void 0) { epsilon = 0.95; }
  10211. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  10212. this.disableEdgesRendering();
  10213. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  10214. };
  10215. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  10216. get: function () {
  10217. return false;
  10218. },
  10219. enumerable: true,
  10220. configurable: true
  10221. });
  10222. AbstractMesh.prototype.getLOD = function (camera) {
  10223. return this;
  10224. };
  10225. AbstractMesh.prototype.getTotalVertices = function () {
  10226. return 0;
  10227. };
  10228. AbstractMesh.prototype.getIndices = function () {
  10229. return null;
  10230. };
  10231. AbstractMesh.prototype.getVerticesData = function (kind) {
  10232. return null;
  10233. };
  10234. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  10235. return false;
  10236. };
  10237. AbstractMesh.prototype.getBoundingInfo = function () {
  10238. if (this._masterMesh) {
  10239. return this._masterMesh.getBoundingInfo();
  10240. }
  10241. if (!this._boundingInfo) {
  10242. this._updateBoundingInfo();
  10243. }
  10244. return this._boundingInfo;
  10245. };
  10246. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  10247. this._boundingInfo = boundingInfo;
  10248. };
  10249. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  10250. get: function () {
  10251. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  10252. },
  10253. enumerable: true,
  10254. configurable: true
  10255. });
  10256. AbstractMesh.prototype._preActivate = function () {
  10257. };
  10258. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  10259. };
  10260. AbstractMesh.prototype._activate = function (renderId) {
  10261. this._renderId = renderId;
  10262. };
  10263. AbstractMesh.prototype.getWorldMatrix = function () {
  10264. if (this._masterMesh) {
  10265. return this._masterMesh.getWorldMatrix();
  10266. }
  10267. if (this._currentRenderId !== this.getScene().getRenderId()) {
  10268. this.computeWorldMatrix();
  10269. }
  10270. return this._worldMatrix;
  10271. };
  10272. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  10273. get: function () {
  10274. return this._worldMatrix;
  10275. },
  10276. enumerable: true,
  10277. configurable: true
  10278. });
  10279. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  10280. get: function () {
  10281. return this._absolutePosition;
  10282. },
  10283. enumerable: true,
  10284. configurable: true
  10285. });
  10286. AbstractMesh.prototype.freezeWorldMatrix = function () {
  10287. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  10288. this.computeWorldMatrix(true);
  10289. this._isWorldMatrixFrozen = true;
  10290. };
  10291. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  10292. this._isWorldMatrixFrozen = false;
  10293. this.computeWorldMatrix(true);
  10294. };
  10295. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  10296. get: function () {
  10297. return this._isWorldMatrixFrozen;
  10298. },
  10299. enumerable: true,
  10300. configurable: true
  10301. });
  10302. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  10303. axis.normalize();
  10304. if (!this.rotationQuaternion) {
  10305. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  10306. this.rotation = BABYLON.Vector3.Zero();
  10307. }
  10308. var rotationQuaternion;
  10309. if (!space || space === BABYLON.Space.LOCAL) {
  10310. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  10311. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  10312. }
  10313. else {
  10314. if (this.parent) {
  10315. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  10316. invertParentWorldMatrix.invert();
  10317. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  10318. }
  10319. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  10320. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  10321. }
  10322. };
  10323. AbstractMesh.prototype.translate = function (axis, distance, space) {
  10324. var displacementVector = axis.scale(distance);
  10325. if (!space || space === BABYLON.Space.LOCAL) {
  10326. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  10327. this.setPositionWithLocalVector(tempV3);
  10328. }
  10329. else {
  10330. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  10331. }
  10332. };
  10333. AbstractMesh.prototype.getAbsolutePosition = function () {
  10334. this.computeWorldMatrix();
  10335. return this._absolutePosition;
  10336. };
  10337. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  10338. if (!absolutePosition) {
  10339. return;
  10340. }
  10341. var absolutePositionX;
  10342. var absolutePositionY;
  10343. var absolutePositionZ;
  10344. if (absolutePosition.x === undefined) {
  10345. if (arguments.length < 3) {
  10346. return;
  10347. }
  10348. absolutePositionX = arguments[0];
  10349. absolutePositionY = arguments[1];
  10350. absolutePositionZ = arguments[2];
  10351. }
  10352. else {
  10353. absolutePositionX = absolutePosition.x;
  10354. absolutePositionY = absolutePosition.y;
  10355. absolutePositionZ = absolutePosition.z;
  10356. }
  10357. if (this.parent) {
  10358. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  10359. invertParentWorldMatrix.invert();
  10360. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  10361. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  10362. }
  10363. else {
  10364. this.position.x = absolutePositionX;
  10365. this.position.y = absolutePositionY;
  10366. this.position.z = absolutePositionZ;
  10367. }
  10368. };
  10369. // ================================== Point of View Movement =================================
  10370. /**
  10371. * Perform relative position change from the point of view of behind the front of the mesh.
  10372. * This is performed taking into account the meshes current rotation, so you do not have to care.
  10373. * Supports definition of mesh facing forward or backward.
  10374. * @param {number} amountRight
  10375. * @param {number} amountUp
  10376. * @param {number} amountForward
  10377. */
  10378. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  10379. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  10380. };
  10381. /**
  10382. * Calculate relative position change from the point of view of behind the front of the mesh.
  10383. * This is performed taking into account the meshes current rotation, so you do not have to care.
  10384. * Supports definition of mesh facing forward or backward.
  10385. * @param {number} amountRight
  10386. * @param {number} amountUp
  10387. * @param {number} amountForward
  10388. */
  10389. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  10390. var rotMatrix = new BABYLON.Matrix();
  10391. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  10392. rotQuaternion.toRotationMatrix(rotMatrix);
  10393. var translationDelta = BABYLON.Vector3.Zero();
  10394. var defForwardMult = this.definedFacingForward ? -1 : 1;
  10395. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  10396. return translationDelta;
  10397. };
  10398. // ================================== Point of View Rotation =================================
  10399. /**
  10400. * Perform relative rotation change from the point of view of behind the front of the mesh.
  10401. * Supports definition of mesh facing forward or backward.
  10402. * @param {number} flipBack
  10403. * @param {number} twirlClockwise
  10404. * @param {number} tiltRight
  10405. */
  10406. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  10407. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  10408. };
  10409. /**
  10410. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  10411. * Supports definition of mesh facing forward or backward.
  10412. * @param {number} flipBack
  10413. * @param {number} twirlClockwise
  10414. * @param {number} tiltRight
  10415. */
  10416. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  10417. var defForwardMult = this.definedFacingForward ? 1 : -1;
  10418. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  10419. };
  10420. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  10421. this._pivotMatrix = matrix;
  10422. this._cache.pivotMatrixUpdated = true;
  10423. };
  10424. AbstractMesh.prototype.getPivotMatrix = function () {
  10425. return this._pivotMatrix;
  10426. };
  10427. AbstractMesh.prototype._isSynchronized = function () {
  10428. if (this._isDirty) {
  10429. return false;
  10430. }
  10431. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  10432. return false;
  10433. if (this._cache.pivotMatrixUpdated) {
  10434. return false;
  10435. }
  10436. if (this.infiniteDistance) {
  10437. return false;
  10438. }
  10439. if (!this._cache.position.equals(this.position))
  10440. return false;
  10441. if (this.rotationQuaternion) {
  10442. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  10443. return false;
  10444. }
  10445. if (!this._cache.rotation.equals(this.rotation))
  10446. return false;
  10447. if (!this._cache.scaling.equals(this.scaling))
  10448. return false;
  10449. return true;
  10450. };
  10451. AbstractMesh.prototype._initCache = function () {
  10452. _super.prototype._initCache.call(this);
  10453. this._cache.localMatrixUpdated = false;
  10454. this._cache.position = BABYLON.Vector3.Zero();
  10455. this._cache.scaling = BABYLON.Vector3.Zero();
  10456. this._cache.rotation = BABYLON.Vector3.Zero();
  10457. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  10458. this._cache.billboardMode = -1;
  10459. };
  10460. AbstractMesh.prototype.markAsDirty = function (property) {
  10461. if (property === "rotation") {
  10462. this.rotationQuaternion = null;
  10463. }
  10464. this._currentRenderId = Number.MAX_VALUE;
  10465. this._isDirty = true;
  10466. };
  10467. AbstractMesh.prototype._updateBoundingInfo = function () {
  10468. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  10469. this._boundingInfo.update(this.worldMatrixFromCache);
  10470. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  10471. };
  10472. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  10473. if (!this.subMeshes) {
  10474. return;
  10475. }
  10476. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  10477. var subMesh = this.subMeshes[subIndex];
  10478. if (!subMesh.IsGlobal) {
  10479. subMesh.updateBoundingInfo(matrix);
  10480. }
  10481. }
  10482. };
  10483. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  10484. if (this._isWorldMatrixFrozen) {
  10485. return this._worldMatrix;
  10486. }
  10487. if (!force && (this._currentRenderId === this.getScene().getRenderId() || this.isSynchronized(true))) {
  10488. this._currentRenderId = this.getScene().getRenderId();
  10489. return this._worldMatrix;
  10490. }
  10491. this._cache.position.copyFrom(this.position);
  10492. this._cache.scaling.copyFrom(this.scaling);
  10493. this._cache.pivotMatrixUpdated = false;
  10494. this._cache.billboardMode = this.billboardMode;
  10495. this._currentRenderId = this.getScene().getRenderId();
  10496. this._isDirty = false;
  10497. // Scaling
  10498. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  10499. // Rotation
  10500. //rotate, if quaternion is set and rotation was used
  10501. if (this.rotationQuaternion) {
  10502. var len = this.rotation.length();
  10503. if (len) {
  10504. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  10505. this.rotation.copyFromFloats(0, 0, 0);
  10506. }
  10507. }
  10508. if (this.rotationQuaternion) {
  10509. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  10510. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  10511. }
  10512. else {
  10513. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  10514. this._cache.rotation.copyFrom(this.rotation);
  10515. }
  10516. // Translation
  10517. if (this.infiniteDistance && !this.parent) {
  10518. var camera = this.getScene().activeCamera;
  10519. if (camera) {
  10520. var cameraWorldMatrix = camera.getWorldMatrix();
  10521. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  10522. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  10523. }
  10524. }
  10525. else {
  10526. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  10527. }
  10528. // Composing transformations
  10529. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  10530. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  10531. // Billboarding
  10532. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  10533. BABYLON.Tmp.Vector3[0].copyFrom(this.position);
  10534. var localPosition = BABYLON.Tmp.Vector3[0];
  10535. if (this.parent && this.parent.getWorldMatrix) {
  10536. this._markSyncedWithParent();
  10537. var parentMatrix;
  10538. if (this._meshToBoneReferal) {
  10539. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  10540. parentMatrix = BABYLON.Tmp.Matrix[6];
  10541. }
  10542. else {
  10543. parentMatrix = this.parent.getWorldMatrix();
  10544. }
  10545. BABYLON.Vector3.TransformNormalToRef(localPosition, parentMatrix, BABYLON.Tmp.Vector3[1]);
  10546. localPosition = BABYLON.Tmp.Vector3[1];
  10547. }
  10548. var zero = this.getScene().activeCamera.globalPosition.clone();
  10549. if (this.parent && this.parent.position) {
  10550. localPosition.addInPlace(this.parent.position);
  10551. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, BABYLON.Tmp.Matrix[2]);
  10552. }
  10553. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) !== AbstractMesh.BILLBOARDMODE_ALL) {
  10554. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_X)
  10555. zero.x = localPosition.x + BABYLON.Epsilon;
  10556. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Y)
  10557. zero.y = localPosition.y + BABYLON.Epsilon;
  10558. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Z)
  10559. zero.z = localPosition.z + BABYLON.Epsilon;
  10560. }
  10561. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), BABYLON.Tmp.Matrix[3]);
  10562. BABYLON.Tmp.Matrix[3].m[12] = BABYLON.Tmp.Matrix[3].m[13] = BABYLON.Tmp.Matrix[3].m[14] = 0;
  10563. BABYLON.Tmp.Matrix[3].invert();
  10564. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[3], this._localWorld);
  10565. this._rotateYByPI.multiplyToRef(this._localWorld, BABYLON.Tmp.Matrix[5]);
  10566. }
  10567. // Local world
  10568. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  10569. // Parent
  10570. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === AbstractMesh.BILLBOARDMODE_NONE) {
  10571. this._markSyncedWithParent();
  10572. if (this._meshToBoneReferal) {
  10573. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  10574. BABYLON.Tmp.Matrix[6].multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), this._worldMatrix);
  10575. }
  10576. else {
  10577. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  10578. }
  10579. }
  10580. else {
  10581. this._worldMatrix.copyFrom(this._localWorld);
  10582. }
  10583. // Bounding info
  10584. this._updateBoundingInfo();
  10585. // Absolute position
  10586. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  10587. // Callbacks
  10588. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  10589. if (!this._poseMatrix) {
  10590. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  10591. }
  10592. return this._worldMatrix;
  10593. };
  10594. /**
  10595. * If you'd like to be callbacked after the mesh position, rotation or scaling has been updated
  10596. * @param func: callback function to add
  10597. */
  10598. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  10599. this.onAfterWorldMatrixUpdateObservable.add(func);
  10600. };
  10601. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  10602. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  10603. };
  10604. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  10605. this.computeWorldMatrix();
  10606. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  10607. };
  10608. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  10609. this.computeWorldMatrix();
  10610. var invLocalWorldMatrix = this._localWorld.clone();
  10611. invLocalWorldMatrix.invert();
  10612. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  10613. };
  10614. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  10615. this.computeWorldMatrix(true);
  10616. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  10617. };
  10618. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  10619. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  10620. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  10621. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  10622. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  10623. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  10624. /// <returns>Mesh oriented towards targetMesh</returns>
  10625. if (yawCor === void 0) { yawCor = 0; }
  10626. if (pitchCor === void 0) { pitchCor = 0; }
  10627. if (rollCor === void 0) { rollCor = 0; }
  10628. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  10629. var dv = AbstractMesh._lookAtVectorCache;
  10630. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  10631. targetPoint.subtractToRef(pos, dv);
  10632. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  10633. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  10634. var pitch = Math.atan2(dv.y, len);
  10635. this.rotationQuaternion = this.rotationQuaternion || new BABYLON.Quaternion();
  10636. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  10637. };
  10638. AbstractMesh.prototype.attachToBone = function (bone, affectedMesh) {
  10639. this._meshToBoneReferal = affectedMesh;
  10640. this.parent = bone;
  10641. if (bone.getWorldMatrix().determinant() < 0) {
  10642. this.scalingDeterminant *= -1;
  10643. }
  10644. };
  10645. AbstractMesh.prototype.detachFromBone = function () {
  10646. if (this.parent.getWorldMatrix().determinant() < 0) {
  10647. this.scalingDeterminant *= -1;
  10648. }
  10649. this._meshToBoneReferal = null;
  10650. this.parent = null;
  10651. };
  10652. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  10653. return this._boundingInfo.isInFrustum(frustumPlanes);
  10654. };
  10655. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  10656. return this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  10657. ;
  10658. };
  10659. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  10660. if (!this._boundingInfo || !mesh._boundingInfo) {
  10661. return false;
  10662. }
  10663. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  10664. };
  10665. AbstractMesh.prototype.intersectsPoint = function (point) {
  10666. if (!this._boundingInfo) {
  10667. return false;
  10668. }
  10669. return this._boundingInfo.intersectsPoint(point);
  10670. };
  10671. // Physics
  10672. /**
  10673. * @Deprecated. Use new PhysicsImpostor instead.
  10674. * */
  10675. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  10676. //legacy support
  10677. if (impostor.impostor) {
  10678. options = impostor;
  10679. impostor = impostor.impostor;
  10680. }
  10681. this.physicsImpostor = new BABYLON.PhysicsImpostor(this, impostor, options, this.getScene());
  10682. return this.physicsImpostor.physicsBody;
  10683. };
  10684. AbstractMesh.prototype.getPhysicsImpostor = function () {
  10685. return this.physicsImpostor;
  10686. };
  10687. /**
  10688. * @Deprecated. Use getPhysicsImpostor().getParam("mass");
  10689. */
  10690. AbstractMesh.prototype.getPhysicsMass = function () {
  10691. return this.physicsImpostor.getParam("mass");
  10692. };
  10693. /**
  10694. * @Deprecated. Use getPhysicsImpostor().getParam("friction");
  10695. */
  10696. AbstractMesh.prototype.getPhysicsFriction = function () {
  10697. return this.physicsImpostor.getParam("friction");
  10698. };
  10699. /**
  10700. * @Deprecated. Use getPhysicsImpostor().getParam("restitution");
  10701. */
  10702. AbstractMesh.prototype.getPhysicsRestitution = function () {
  10703. return this.physicsImpostor.getParam("restitution");
  10704. };
  10705. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  10706. if (!camera) {
  10707. camera = this.getScene().activeCamera;
  10708. }
  10709. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  10710. };
  10711. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  10712. if (!camera) {
  10713. camera = this.getScene().activeCamera;
  10714. }
  10715. return this.absolutePosition.subtract(camera.position).length();
  10716. };
  10717. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  10718. if (!this.physicsImpostor) {
  10719. return;
  10720. }
  10721. this.physicsImpostor.applyImpulse(force, contactPoint);
  10722. };
  10723. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  10724. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  10725. return;
  10726. }
  10727. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  10728. mainPivot: pivot1,
  10729. connectedPivot: pivot2,
  10730. nativeParams: options
  10731. });
  10732. };
  10733. /**
  10734. * @Deprecated
  10735. */
  10736. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  10737. BABYLON.Tools.Warn("updatePhysicsBodyPosition() is deprecated, please use updatePhysicsBody()");
  10738. this.updatePhysicsBody();
  10739. };
  10740. /**
  10741. * @Deprecated
  10742. * Calling this function is not needed anymore.
  10743. * The physics engine takes care of transofmration automatically.
  10744. */
  10745. AbstractMesh.prototype.updatePhysicsBody = function () {
  10746. //Unneeded
  10747. };
  10748. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  10749. // Collisions
  10750. get: function () {
  10751. return this._checkCollisions;
  10752. },
  10753. set: function (collisionEnabled) {
  10754. this._checkCollisions = collisionEnabled;
  10755. if (this.getScene().workerCollisions) {
  10756. this.getScene().collisionCoordinator.onMeshUpdated(this);
  10757. }
  10758. },
  10759. enumerable: true,
  10760. configurable: true
  10761. });
  10762. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  10763. var globalPosition = this.getAbsolutePosition();
  10764. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  10765. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  10766. this._collider.radius = this.ellipsoid;
  10767. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  10768. };
  10769. // Submeshes octree
  10770. /**
  10771. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  10772. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  10773. */
  10774. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  10775. if (maxCapacity === void 0) { maxCapacity = 64; }
  10776. if (maxDepth === void 0) { maxDepth = 2; }
  10777. if (!this._submeshesOctree) {
  10778. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  10779. }
  10780. this.computeWorldMatrix(true);
  10781. // Update octree
  10782. var bbox = this.getBoundingInfo().boundingBox;
  10783. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  10784. return this._submeshesOctree;
  10785. };
  10786. // Collisions
  10787. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  10788. this._generatePointsArray();
  10789. // Transformation
  10790. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  10791. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  10792. subMesh._lastColliderWorldVertices = [];
  10793. subMesh._trianglePlanes = [];
  10794. var start = subMesh.verticesStart;
  10795. var end = (subMesh.verticesStart + subMesh.verticesCount);
  10796. for (var i = start; i < end; i++) {
  10797. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  10798. }
  10799. }
  10800. // Collide
  10801. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  10802. if (collider.collisionFound) {
  10803. collider.collidedMesh = this;
  10804. }
  10805. };
  10806. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  10807. var subMeshes;
  10808. var len;
  10809. // Octrees
  10810. if (this._submeshesOctree && this.useOctreeForCollisions) {
  10811. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  10812. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  10813. len = intersections.length;
  10814. subMeshes = intersections.data;
  10815. }
  10816. else {
  10817. subMeshes = this.subMeshes;
  10818. len = subMeshes.length;
  10819. }
  10820. for (var index = 0; index < len; index++) {
  10821. var subMesh = subMeshes[index];
  10822. // Bounding test
  10823. if (len > 1 && !subMesh._checkCollision(collider))
  10824. continue;
  10825. this._collideForSubMesh(subMesh, transformMatrix, collider);
  10826. }
  10827. };
  10828. AbstractMesh.prototype._checkCollision = function (collider) {
  10829. // Bounding box test
  10830. if (!this._boundingInfo._checkCollision(collider))
  10831. return;
  10832. // Transformation matrix
  10833. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  10834. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  10835. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  10836. };
  10837. // Picking
  10838. AbstractMesh.prototype._generatePointsArray = function () {
  10839. return false;
  10840. };
  10841. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  10842. var pickingInfo = new BABYLON.PickingInfo();
  10843. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  10844. return pickingInfo;
  10845. }
  10846. if (!this._generatePointsArray()) {
  10847. return pickingInfo;
  10848. }
  10849. var intersectInfo = null;
  10850. // Octrees
  10851. var subMeshes;
  10852. var len;
  10853. if (this._submeshesOctree && this.useOctreeForPicking) {
  10854. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  10855. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  10856. len = intersections.length;
  10857. subMeshes = intersections.data;
  10858. }
  10859. else {
  10860. subMeshes = this.subMeshes;
  10861. len = subMeshes.length;
  10862. }
  10863. for (var index = 0; index < len; index++) {
  10864. var subMesh = subMeshes[index];
  10865. // Bounding test
  10866. if (len > 1 && !subMesh.canIntersects(ray))
  10867. continue;
  10868. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  10869. if (currentIntersectInfo) {
  10870. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  10871. intersectInfo = currentIntersectInfo;
  10872. intersectInfo.subMeshId = index;
  10873. if (fastCheck) {
  10874. break;
  10875. }
  10876. }
  10877. }
  10878. }
  10879. if (intersectInfo) {
  10880. // Get picked point
  10881. var world = this.getWorldMatrix();
  10882. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  10883. var direction = ray.direction.clone();
  10884. direction = direction.scale(intersectInfo.distance);
  10885. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  10886. var pickedPoint = worldOrigin.add(worldDirection);
  10887. // Return result
  10888. pickingInfo.hit = true;
  10889. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  10890. pickingInfo.pickedPoint = pickedPoint;
  10891. pickingInfo.pickedMesh = this;
  10892. pickingInfo.bu = intersectInfo.bu;
  10893. pickingInfo.bv = intersectInfo.bv;
  10894. pickingInfo.faceId = intersectInfo.faceId;
  10895. pickingInfo.subMeshId = intersectInfo.subMeshId;
  10896. return pickingInfo;
  10897. }
  10898. return pickingInfo;
  10899. };
  10900. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  10901. return null;
  10902. };
  10903. AbstractMesh.prototype.releaseSubMeshes = function () {
  10904. if (this.subMeshes) {
  10905. while (this.subMeshes.length) {
  10906. this.subMeshes[0].dispose();
  10907. }
  10908. }
  10909. else {
  10910. this.subMeshes = new Array();
  10911. }
  10912. };
  10913. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  10914. var _this = this;
  10915. var index;
  10916. // Action manager
  10917. if (this.actionManager) {
  10918. this.actionManager.dispose();
  10919. this.actionManager = null;
  10920. }
  10921. // Skeleton
  10922. this.skeleton = null;
  10923. // Animations
  10924. this.getScene().stopAnimation(this);
  10925. // Physics
  10926. if (this.physicsImpostor) {
  10927. this.physicsImpostor.dispose();
  10928. }
  10929. // Intersections in progress
  10930. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  10931. var other = this._intersectionsInProgress[index];
  10932. var pos = other._intersectionsInProgress.indexOf(this);
  10933. other._intersectionsInProgress.splice(pos, 1);
  10934. }
  10935. this._intersectionsInProgress = [];
  10936. // Lights
  10937. var lights = this.getScene().lights;
  10938. lights.forEach(function (light) {
  10939. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  10940. if (meshIndex !== -1) {
  10941. light.includedOnlyMeshes.splice(meshIndex, 1);
  10942. }
  10943. meshIndex = light.excludedMeshes.indexOf(_this);
  10944. if (meshIndex !== -1) {
  10945. light.excludedMeshes.splice(meshIndex, 1);
  10946. }
  10947. // Shadow generators
  10948. var generator = light.getShadowGenerator();
  10949. if (generator) {
  10950. meshIndex = generator.getShadowMap().renderList.indexOf(_this);
  10951. if (meshIndex !== -1) {
  10952. generator.getShadowMap().renderList.splice(meshIndex, 1);
  10953. }
  10954. }
  10955. });
  10956. // Edges
  10957. if (this._edgesRenderer) {
  10958. this._edgesRenderer.dispose();
  10959. this._edgesRenderer = null;
  10960. }
  10961. // SubMeshes
  10962. this.releaseSubMeshes();
  10963. // Remove from scene
  10964. this.getScene().removeMesh(this);
  10965. if (!doNotRecurse) {
  10966. // Particles
  10967. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  10968. if (this.getScene().particleSystems[index].emitter === this) {
  10969. this.getScene().particleSystems[index].dispose();
  10970. index--;
  10971. }
  10972. }
  10973. // Children
  10974. var objects = this.getDescendants(true);
  10975. for (index = 0; index < objects.length; index++) {
  10976. objects[index].dispose();
  10977. }
  10978. }
  10979. else {
  10980. var childMeshes = this.getChildMeshes(true);
  10981. for (index = 0; index < childMeshes.length; index++) {
  10982. var child = childMeshes[index];
  10983. child.parent = null;
  10984. child.computeWorldMatrix(true);
  10985. }
  10986. }
  10987. _super.prototype.dispose.call(this);
  10988. this.onAfterWorldMatrixUpdateObservable.clear();
  10989. this.onCollideObservable.clear();
  10990. this.onCollisionPositionChangeObservable.clear();
  10991. this._isDisposed = true;
  10992. // Callback
  10993. this.onDisposeObservable.notifyObservers(this);
  10994. this.onDisposeObservable.clear();
  10995. };
  10996. // Statics
  10997. AbstractMesh._BILLBOARDMODE_NONE = 0;
  10998. AbstractMesh._BILLBOARDMODE_X = 1;
  10999. AbstractMesh._BILLBOARDMODE_Y = 2;
  11000. AbstractMesh._BILLBOARDMODE_Z = 4;
  11001. AbstractMesh._BILLBOARDMODE_ALL = 7;
  11002. AbstractMesh._rotationAxisCache = new BABYLON.Quaternion();
  11003. AbstractMesh._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  11004. return AbstractMesh;
  11005. }(BABYLON.Node));
  11006. BABYLON.AbstractMesh = AbstractMesh;
  11007. })(BABYLON || (BABYLON = {}));
  11008. var BABYLON;
  11009. (function (BABYLON) {
  11010. var Light = (function (_super) {
  11011. __extends(Light, _super);
  11012. function Light(name, scene) {
  11013. _super.call(this, name, scene);
  11014. this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  11015. this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  11016. this.intensity = 1.0;
  11017. this.range = Number.MAX_VALUE;
  11018. this.includeOnlyWithLayerMask = 0;
  11019. this.includedOnlyMeshes = new Array();
  11020. this.excludedMeshes = new Array();
  11021. this.excludeWithLayerMask = 0;
  11022. this.lightmapMode = 0;
  11023. // PBR Properties.
  11024. this.radius = 0.00001;
  11025. this._excludedMeshesIds = new Array();
  11026. this._includedOnlyMeshesIds = new Array();
  11027. scene.addLight(this);
  11028. }
  11029. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  11030. /**
  11031. * If every light affecting the material is in this lightmapMode,
  11032. * material.lightmapTexture adds or multiplies
  11033. * (depends on material.useLightmapAsShadowmap)
  11034. * after every other light calculations.
  11035. */
  11036. get: function () {
  11037. return Light._LIGHTMAP_DEFAULT;
  11038. },
  11039. enumerable: true,
  11040. configurable: true
  11041. });
  11042. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  11043. /**
  11044. * material.lightmapTexture as only diffuse lighting from this light
  11045. * adds pnly specular lighting from this light
  11046. * adds dynamic shadows
  11047. */
  11048. get: function () {
  11049. return Light._LIGHTMAP_SPECULAR;
  11050. },
  11051. enumerable: true,
  11052. configurable: true
  11053. });
  11054. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  11055. /**
  11056. * material.lightmapTexture as only lighting
  11057. * no light calculation from this light
  11058. * only adds dynamic shadows from this light
  11059. */
  11060. get: function () {
  11061. return Light._LIGHTMAP_SHADOWSONLY;
  11062. },
  11063. enumerable: true,
  11064. configurable: true
  11065. });
  11066. /**
  11067. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  11068. */
  11069. Light.prototype.toString = function (fullDetails) {
  11070. var ret = "Name: " + this.name;
  11071. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  11072. if (this.animations) {
  11073. for (var i = 0; i < this.animations.length; i++) {
  11074. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  11075. }
  11076. }
  11077. if (fullDetails) {
  11078. }
  11079. return ret;
  11080. };
  11081. Light.prototype.getShadowGenerator = function () {
  11082. return this._shadowGenerator;
  11083. };
  11084. Light.prototype.getAbsolutePosition = function () {
  11085. return BABYLON.Vector3.Zero();
  11086. };
  11087. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  11088. };
  11089. Light.prototype._getWorldMatrix = function () {
  11090. return BABYLON.Matrix.Identity();
  11091. };
  11092. Light.prototype.canAffectMesh = function (mesh) {
  11093. if (!mesh) {
  11094. return true;
  11095. }
  11096. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  11097. return false;
  11098. }
  11099. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  11100. return false;
  11101. }
  11102. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  11103. return false;
  11104. }
  11105. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  11106. return false;
  11107. }
  11108. return true;
  11109. };
  11110. Light.prototype.getWorldMatrix = function () {
  11111. this._currentRenderId = this.getScene().getRenderId();
  11112. var worldMatrix = this._getWorldMatrix();
  11113. if (this.parent && this.parent.getWorldMatrix) {
  11114. if (!this._parentedWorldMatrix) {
  11115. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  11116. }
  11117. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  11118. this._markSyncedWithParent();
  11119. return this._parentedWorldMatrix;
  11120. }
  11121. return worldMatrix;
  11122. };
  11123. Light.prototype.dispose = function () {
  11124. if (this._shadowGenerator) {
  11125. this._shadowGenerator.dispose();
  11126. this._shadowGenerator = null;
  11127. }
  11128. // Animations
  11129. this.getScene().stopAnimation(this);
  11130. // Remove from scene
  11131. this.getScene().removeLight(this);
  11132. _super.prototype.dispose.call(this);
  11133. };
  11134. Light.prototype.getTypeID = function () {
  11135. return 0;
  11136. };
  11137. Light.prototype.clone = function (name) {
  11138. return BABYLON.SerializationHelper.Clone(Light.GetConstructorFromName(this.getTypeID(), name, this.getScene()), this);
  11139. };
  11140. Light.prototype.serialize = function () {
  11141. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  11142. // Type
  11143. serializationObject.type = this.getTypeID();
  11144. // Parent
  11145. if (this.parent) {
  11146. serializationObject.parentId = this.parent.id;
  11147. }
  11148. // Inclusion / exclusions
  11149. if (this.excludedMeshes.length > 0) {
  11150. serializationObject.excludedMeshesIds = [];
  11151. this.excludedMeshes.forEach(function (mesh) {
  11152. serializationObject.excludedMeshesIds.push(mesh.id);
  11153. });
  11154. }
  11155. if (this.includedOnlyMeshes.length > 0) {
  11156. serializationObject.includedOnlyMeshesIds = [];
  11157. this.includedOnlyMeshes.forEach(function (mesh) {
  11158. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  11159. });
  11160. }
  11161. // Animations
  11162. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  11163. serializationObject.ranges = this.serializeAnimationRanges();
  11164. return serializationObject;
  11165. };
  11166. Light.GetConstructorFromName = function (type, name, scene) {
  11167. switch (type) {
  11168. case 0:
  11169. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  11170. case 1:
  11171. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  11172. case 2:
  11173. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  11174. case 3:
  11175. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  11176. }
  11177. };
  11178. Light.Parse = function (parsedLight, scene) {
  11179. var light = BABYLON.SerializationHelper.Parse(Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene), parsedLight, scene);
  11180. // Inclusion / exclusions
  11181. if (parsedLight.excludedMeshesIds) {
  11182. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  11183. }
  11184. if (parsedLight.includedOnlyMeshesIds) {
  11185. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  11186. }
  11187. // Parent
  11188. if (parsedLight.parentId) {
  11189. light._waitingParentId = parsedLight.parentId;
  11190. }
  11191. // Animations
  11192. if (parsedLight.animations) {
  11193. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  11194. var parsedAnimation = parsedLight.animations[animationIndex];
  11195. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  11196. }
  11197. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  11198. }
  11199. if (parsedLight.autoAnimate) {
  11200. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  11201. }
  11202. return light;
  11203. };
  11204. //lightmapMode Consts
  11205. Light._LIGHTMAP_DEFAULT = 0;
  11206. Light._LIGHTMAP_SPECULAR = 1;
  11207. Light._LIGHTMAP_SHADOWSONLY = 2;
  11208. __decorate([
  11209. BABYLON.serializeAsColor3()
  11210. ], Light.prototype, "diffuse", void 0);
  11211. __decorate([
  11212. BABYLON.serializeAsColor3()
  11213. ], Light.prototype, "specular", void 0);
  11214. __decorate([
  11215. BABYLON.serialize()
  11216. ], Light.prototype, "intensity", void 0);
  11217. __decorate([
  11218. BABYLON.serialize()
  11219. ], Light.prototype, "range", void 0);
  11220. __decorate([
  11221. BABYLON.serialize()
  11222. ], Light.prototype, "includeOnlyWithLayerMask", void 0);
  11223. __decorate([
  11224. BABYLON.serialize()
  11225. ], Light.prototype, "excludeWithLayerMask", void 0);
  11226. __decorate([
  11227. BABYLON.serialize()
  11228. ], Light.prototype, "lightmapMode", void 0);
  11229. __decorate([
  11230. BABYLON.serialize()
  11231. ], Light.prototype, "radius", void 0);
  11232. return Light;
  11233. }(BABYLON.Node));
  11234. BABYLON.Light = Light;
  11235. })(BABYLON || (BABYLON = {}));
  11236. var BABYLON;
  11237. (function (BABYLON) {
  11238. var PointLight = (function (_super) {
  11239. __extends(PointLight, _super);
  11240. function PointLight(name, position, scene) {
  11241. _super.call(this, name, scene);
  11242. this.position = position;
  11243. }
  11244. PointLight.prototype.getAbsolutePosition = function () {
  11245. return this.transformedPosition ? this.transformedPosition : this.position;
  11246. };
  11247. PointLight.prototype.computeTransformedPosition = function () {
  11248. if (this.parent && this.parent.getWorldMatrix) {
  11249. if (!this.transformedPosition) {
  11250. this.transformedPosition = BABYLON.Vector3.Zero();
  11251. }
  11252. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  11253. return true;
  11254. }
  11255. return false;
  11256. };
  11257. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  11258. if (this.parent && this.parent.getWorldMatrix) {
  11259. this.computeTransformedPosition();
  11260. if (this.getScene().useRightHandedSystem) {
  11261. effect.setFloat4(positionUniformName, -this.transformedPosition.x, -this.transformedPosition.y, -this.transformedPosition.z, 0);
  11262. }
  11263. else {
  11264. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0);
  11265. }
  11266. return;
  11267. }
  11268. if (this.getScene().useRightHandedSystem) {
  11269. effect.setFloat4(positionUniformName, -this.position.x, -this.position.y, -this.position.z, 0);
  11270. }
  11271. else {
  11272. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  11273. }
  11274. };
  11275. PointLight.prototype.needCube = function () {
  11276. return true;
  11277. };
  11278. PointLight.prototype.supportsVSM = function () {
  11279. return false;
  11280. };
  11281. PointLight.prototype.needRefreshPerFrame = function () {
  11282. return false;
  11283. };
  11284. PointLight.prototype.getShadowDirection = function (faceIndex) {
  11285. switch (faceIndex) {
  11286. case 0:
  11287. return new BABYLON.Vector3(1, 0, 0);
  11288. case 1:
  11289. return new BABYLON.Vector3(-1, 0, 0);
  11290. case 2:
  11291. return new BABYLON.Vector3(0, -1, 0);
  11292. case 3:
  11293. return new BABYLON.Vector3(0, 1, 0);
  11294. case 4:
  11295. return new BABYLON.Vector3(0, 0, 1);
  11296. case 5:
  11297. return new BABYLON.Vector3(0, 0, -1);
  11298. }
  11299. return BABYLON.Vector3.Zero();
  11300. };
  11301. PointLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  11302. var activeCamera = this.getScene().activeCamera;
  11303. BABYLON.Matrix.PerspectiveFovLHToRef(Math.PI / 2, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  11304. };
  11305. PointLight.prototype._getWorldMatrix = function () {
  11306. if (!this._worldMatrix) {
  11307. this._worldMatrix = BABYLON.Matrix.Identity();
  11308. }
  11309. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  11310. return this._worldMatrix;
  11311. };
  11312. PointLight.prototype.getTypeID = function () {
  11313. return 0;
  11314. };
  11315. __decorate([
  11316. BABYLON.serializeAsVector3()
  11317. ], PointLight.prototype, "position", void 0);
  11318. return PointLight;
  11319. }(BABYLON.Light));
  11320. BABYLON.PointLight = PointLight;
  11321. })(BABYLON || (BABYLON = {}));
  11322. var BABYLON;
  11323. (function (BABYLON) {
  11324. var SpotLight = (function (_super) {
  11325. __extends(SpotLight, _super);
  11326. function SpotLight(name, position, direction, angle, exponent, scene) {
  11327. _super.call(this, name, scene);
  11328. this.position = position;
  11329. this.direction = direction;
  11330. this.angle = angle;
  11331. this.exponent = exponent;
  11332. }
  11333. SpotLight.prototype.getAbsolutePosition = function () {
  11334. return this.transformedPosition ? this.transformedPosition : this.position;
  11335. };
  11336. SpotLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  11337. var activeCamera = this.getScene().activeCamera;
  11338. BABYLON.Matrix.PerspectiveFovLHToRef(this.angle, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  11339. };
  11340. SpotLight.prototype.needCube = function () {
  11341. return false;
  11342. };
  11343. SpotLight.prototype.supportsVSM = function () {
  11344. return true;
  11345. };
  11346. SpotLight.prototype.needRefreshPerFrame = function () {
  11347. return false;
  11348. };
  11349. SpotLight.prototype.getShadowDirection = function (faceIndex) {
  11350. return this.direction;
  11351. };
  11352. SpotLight.prototype.setDirectionToTarget = function (target) {
  11353. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  11354. return this.direction;
  11355. };
  11356. SpotLight.prototype.computeTransformedPosition = function () {
  11357. if (this.parent && this.parent.getWorldMatrix) {
  11358. if (!this.transformedPosition) {
  11359. this.transformedPosition = BABYLON.Vector3.Zero();
  11360. }
  11361. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  11362. return true;
  11363. }
  11364. return false;
  11365. };
  11366. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  11367. var normalizeDirection;
  11368. if (this.parent && this.parent.getWorldMatrix) {
  11369. if (!this._transformedDirection) {
  11370. this._transformedDirection = BABYLON.Vector3.Zero();
  11371. }
  11372. this.computeTransformedPosition();
  11373. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  11374. if (this.getScene().useRightHandedSystem) {
  11375. effect.setFloat4(positionUniformName, -this.transformedPosition.x, -this.transformedPosition.y, -this.transformedPosition.z, this.exponent);
  11376. }
  11377. else {
  11378. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent);
  11379. }
  11380. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  11381. }
  11382. else {
  11383. if (this.getScene().useRightHandedSystem) {
  11384. effect.setFloat4(positionUniformName, -this.position.x, -this.position.y, -this.position.z, this.exponent);
  11385. }
  11386. else {
  11387. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  11388. }
  11389. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  11390. }
  11391. if (this.getScene().useRightHandedSystem) {
  11392. effect.setFloat4(directionUniformName, -normalizeDirection.x, -normalizeDirection.y, -normalizeDirection.z, Math.cos(this.angle * 0.5));
  11393. }
  11394. else {
  11395. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  11396. }
  11397. };
  11398. SpotLight.prototype._getWorldMatrix = function () {
  11399. if (!this._worldMatrix) {
  11400. this._worldMatrix = BABYLON.Matrix.Identity();
  11401. }
  11402. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  11403. return this._worldMatrix;
  11404. };
  11405. SpotLight.prototype.getTypeID = function () {
  11406. return 2;
  11407. };
  11408. __decorate([
  11409. BABYLON.serializeAsVector3()
  11410. ], SpotLight.prototype, "position", void 0);
  11411. __decorate([
  11412. BABYLON.serializeAsVector3()
  11413. ], SpotLight.prototype, "direction", void 0);
  11414. __decorate([
  11415. BABYLON.serialize()
  11416. ], SpotLight.prototype, "angle", void 0);
  11417. __decorate([
  11418. BABYLON.serialize()
  11419. ], SpotLight.prototype, "exponent", void 0);
  11420. return SpotLight;
  11421. }(BABYLON.Light));
  11422. BABYLON.SpotLight = SpotLight;
  11423. })(BABYLON || (BABYLON = {}));
  11424. var BABYLON;
  11425. (function (BABYLON) {
  11426. var HemisphericLight = (function (_super) {
  11427. __extends(HemisphericLight, _super);
  11428. function HemisphericLight(name, direction, scene) {
  11429. _super.call(this, name, scene);
  11430. this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  11431. this.direction = direction;
  11432. }
  11433. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  11434. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  11435. return this.direction;
  11436. };
  11437. HemisphericLight.prototype.getShadowGenerator = function () {
  11438. return null;
  11439. };
  11440. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  11441. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  11442. if (this.getScene().useRightHandedSystem) {
  11443. effect.setFloat4(directionUniformName, -normalizeDirection.x, -normalizeDirection.y, -normalizeDirection.z, 0);
  11444. }
  11445. else {
  11446. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  11447. }
  11448. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  11449. };
  11450. HemisphericLight.prototype._getWorldMatrix = function () {
  11451. if (!this._worldMatrix) {
  11452. this._worldMatrix = BABYLON.Matrix.Identity();
  11453. }
  11454. return this._worldMatrix;
  11455. };
  11456. HemisphericLight.prototype.getTypeID = function () {
  11457. return 3;
  11458. };
  11459. __decorate([
  11460. BABYLON.serializeAsColor3()
  11461. ], HemisphericLight.prototype, "groundColor", void 0);
  11462. __decorate([
  11463. BABYLON.serializeAsVector3()
  11464. ], HemisphericLight.prototype, "direction", void 0);
  11465. return HemisphericLight;
  11466. }(BABYLON.Light));
  11467. BABYLON.HemisphericLight = HemisphericLight;
  11468. })(BABYLON || (BABYLON = {}));
  11469. var BABYLON;
  11470. (function (BABYLON) {
  11471. var DirectionalLight = (function (_super) {
  11472. __extends(DirectionalLight, _super);
  11473. function DirectionalLight(name, direction, scene) {
  11474. _super.call(this, name, scene);
  11475. this.shadowOrthoScale = 0.5;
  11476. this.autoUpdateExtends = true;
  11477. // Cache
  11478. this._orthoLeft = Number.MAX_VALUE;
  11479. this._orthoRight = Number.MIN_VALUE;
  11480. this._orthoTop = Number.MIN_VALUE;
  11481. this._orthoBottom = Number.MAX_VALUE;
  11482. this.position = direction.scale(-1);
  11483. this.direction = direction;
  11484. }
  11485. DirectionalLight.prototype.getAbsolutePosition = function () {
  11486. return this.transformedPosition ? this.transformedPosition : this.position;
  11487. };
  11488. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  11489. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  11490. return this.direction;
  11491. };
  11492. DirectionalLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  11493. var activeCamera = this.getScene().activeCamera;
  11494. // Check extends
  11495. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  11496. var tempVector3 = BABYLON.Vector3.Zero();
  11497. this._orthoLeft = Number.MAX_VALUE;
  11498. this._orthoRight = Number.MIN_VALUE;
  11499. this._orthoTop = Number.MIN_VALUE;
  11500. this._orthoBottom = Number.MAX_VALUE;
  11501. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  11502. var mesh = renderList[meshIndex];
  11503. if (!mesh) {
  11504. continue;
  11505. }
  11506. var boundingInfo = mesh.getBoundingInfo();
  11507. if (!boundingInfo) {
  11508. continue;
  11509. }
  11510. var boundingBox = boundingInfo.boundingBox;
  11511. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  11512. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  11513. if (tempVector3.x < this._orthoLeft)
  11514. this._orthoLeft = tempVector3.x;
  11515. if (tempVector3.y < this._orthoBottom)
  11516. this._orthoBottom = tempVector3.y;
  11517. if (tempVector3.x > this._orthoRight)
  11518. this._orthoRight = tempVector3.x;
  11519. if (tempVector3.y > this._orthoTop)
  11520. this._orthoTop = tempVector3.y;
  11521. }
  11522. }
  11523. }
  11524. var xOffset = this._orthoRight - this._orthoLeft;
  11525. var yOffset = this._orthoTop - this._orthoBottom;
  11526. 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);
  11527. };
  11528. DirectionalLight.prototype.supportsVSM = function () {
  11529. return true;
  11530. };
  11531. DirectionalLight.prototype.needRefreshPerFrame = function () {
  11532. return true;
  11533. };
  11534. DirectionalLight.prototype.needCube = function () {
  11535. return false;
  11536. };
  11537. DirectionalLight.prototype.getShadowDirection = function (faceIndex) {
  11538. return this.direction;
  11539. };
  11540. DirectionalLight.prototype.computeTransformedPosition = function () {
  11541. if (this.parent && this.parent.getWorldMatrix) {
  11542. if (!this.transformedPosition) {
  11543. this.transformedPosition = BABYLON.Vector3.Zero();
  11544. }
  11545. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  11546. return true;
  11547. }
  11548. return false;
  11549. };
  11550. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  11551. if (this.parent && this.parent.getWorldMatrix) {
  11552. if (!this._transformedDirection) {
  11553. this._transformedDirection = BABYLON.Vector3.Zero();
  11554. }
  11555. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  11556. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  11557. return;
  11558. }
  11559. if (this.getScene().useRightHandedSystem) {
  11560. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, -1);
  11561. }
  11562. else {
  11563. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  11564. }
  11565. };
  11566. DirectionalLight.prototype._getWorldMatrix = function () {
  11567. if (!this._worldMatrix) {
  11568. this._worldMatrix = BABYLON.Matrix.Identity();
  11569. }
  11570. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  11571. return this._worldMatrix;
  11572. };
  11573. DirectionalLight.prototype.getTypeID = function () {
  11574. return 1;
  11575. };
  11576. __decorate([
  11577. BABYLON.serializeAsVector3()
  11578. ], DirectionalLight.prototype, "position", void 0);
  11579. __decorate([
  11580. BABYLON.serializeAsVector3()
  11581. ], DirectionalLight.prototype, "direction", void 0);
  11582. __decorate([
  11583. BABYLON.serialize()
  11584. ], DirectionalLight.prototype, "shadowOrthoScale", void 0);
  11585. __decorate([
  11586. BABYLON.serialize()
  11587. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  11588. return DirectionalLight;
  11589. }(BABYLON.Light));
  11590. BABYLON.DirectionalLight = DirectionalLight;
  11591. })(BABYLON || (BABYLON = {}));
  11592. var BABYLON;
  11593. (function (BABYLON) {
  11594. var ShadowGenerator = (function () {
  11595. function ShadowGenerator(mapSize, light) {
  11596. var _this = this;
  11597. // Members
  11598. this._filter = ShadowGenerator.FILTER_NONE;
  11599. this.blurScale = 2;
  11600. this._blurBoxOffset = 0;
  11601. this._bias = 0.00005;
  11602. this._lightDirection = BABYLON.Vector3.Zero();
  11603. this.forceBackFacesOnly = false;
  11604. this._darkness = 0;
  11605. this._transparencyShadow = false;
  11606. this._viewMatrix = BABYLON.Matrix.Zero();
  11607. this._projectionMatrix = BABYLON.Matrix.Zero();
  11608. this._transformMatrix = BABYLON.Matrix.Zero();
  11609. this._worldViewProjection = BABYLON.Matrix.Zero();
  11610. this._currentFaceIndex = 0;
  11611. this._currentFaceIndexCache = 0;
  11612. this._useFullFloat = true;
  11613. this._light = light;
  11614. this._scene = light.getScene();
  11615. this._mapSize = mapSize;
  11616. light._shadowGenerator = this;
  11617. // Texture type fallback from float to int if not supported.
  11618. var textureType;
  11619. var caps = this._scene.getEngine().getCaps();
  11620. if (caps.textureFloat && caps.textureFloatLinearFiltering && caps.textureFloatRender) {
  11621. this._useFullFloat = true;
  11622. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  11623. }
  11624. else {
  11625. this._useFullFloat = false;
  11626. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  11627. }
  11628. // Render target
  11629. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false, true, textureType, light.needCube());
  11630. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  11631. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  11632. this._shadowMap.anisotropicFilteringLevel = 1;
  11633. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11634. this._shadowMap.renderParticles = false;
  11635. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  11636. _this._currentFaceIndex = faceIndex;
  11637. });
  11638. this._shadowMap.onAfterUnbindObservable.add(function () {
  11639. if (!_this.useBlurVarianceShadowMap) {
  11640. return;
  11641. }
  11642. if (!_this._shadowMap2) {
  11643. _this._shadowMap2 = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, _this._scene, false, true, textureType);
  11644. _this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  11645. _this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  11646. _this._shadowMap2.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  11647. _this._downSamplePostprocess = new BABYLON.PassPostProcess("downScale", 1.0 / _this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, _this._scene.getEngine());
  11648. _this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  11649. effect.setTexture("textureSampler", _this._shadowMap);
  11650. });
  11651. _this.blurBoxOffset = 1;
  11652. }
  11653. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._boxBlurPostprocess], _this._shadowMap2.getInternalTexture());
  11654. });
  11655. // Custom render function
  11656. var renderSubMesh = function (subMesh) {
  11657. var mesh = subMesh.getRenderingMesh();
  11658. var scene = _this._scene;
  11659. var engine = scene.getEngine();
  11660. // Culling
  11661. engine.setState(subMesh.getMaterial().backFaceCulling);
  11662. // Managing instances
  11663. var batch = mesh._getInstancesRenderList(subMesh._id);
  11664. if (batch.mustReturn) {
  11665. return;
  11666. }
  11667. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  11668. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  11669. engine.enableEffect(_this._effect);
  11670. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  11671. var material = subMesh.getMaterial();
  11672. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  11673. _this._effect.setVector3("lightPosition", _this.getLight().position);
  11674. if (_this.getLight().needCube()) {
  11675. _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  11676. }
  11677. // Alpha test
  11678. if (material && material.needAlphaTesting()) {
  11679. var alphaTexture = material.getAlphaTestTexture();
  11680. _this._effect.setTexture("diffuseSampler", alphaTexture);
  11681. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  11682. }
  11683. // Bones
  11684. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  11685. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  11686. }
  11687. if (_this.forceBackFacesOnly) {
  11688. engine.setState(true, 0, false, true);
  11689. }
  11690. // Draw
  11691. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  11692. if (_this.forceBackFacesOnly) {
  11693. engine.setState(true, 0, false, false);
  11694. }
  11695. }
  11696. else {
  11697. // Need to reset refresh rate of the shadowMap
  11698. _this._shadowMap.resetRefreshCounter();
  11699. }
  11700. };
  11701. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  11702. var index;
  11703. for (index = 0; index < opaqueSubMeshes.length; index++) {
  11704. renderSubMesh(opaqueSubMeshes.data[index]);
  11705. }
  11706. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  11707. renderSubMesh(alphaTestSubMeshes.data[index]);
  11708. }
  11709. if (_this._transparencyShadow) {
  11710. for (index = 0; index < transparentSubMeshes.length; index++) {
  11711. renderSubMesh(transparentSubMeshes.data[index]);
  11712. }
  11713. }
  11714. };
  11715. this._shadowMap.onClearObservable.add(function (engine) {
  11716. if (_this.useBlurVarianceShadowMap || _this.useVarianceShadowMap) {
  11717. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true, true);
  11718. }
  11719. else {
  11720. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  11721. }
  11722. });
  11723. }
  11724. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  11725. // Static
  11726. get: function () {
  11727. return ShadowGenerator._FILTER_NONE;
  11728. },
  11729. enumerable: true,
  11730. configurable: true
  11731. });
  11732. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  11733. get: function () {
  11734. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  11735. },
  11736. enumerable: true,
  11737. configurable: true
  11738. });
  11739. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  11740. get: function () {
  11741. return ShadowGenerator._FILTER_POISSONSAMPLING;
  11742. },
  11743. enumerable: true,
  11744. configurable: true
  11745. });
  11746. Object.defineProperty(ShadowGenerator, "FILTER_BLURVARIANCESHADOWMAP", {
  11747. get: function () {
  11748. return ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP;
  11749. },
  11750. enumerable: true,
  11751. configurable: true
  11752. });
  11753. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  11754. get: function () {
  11755. return this._bias;
  11756. },
  11757. set: function (bias) {
  11758. this._bias = bias;
  11759. },
  11760. enumerable: true,
  11761. configurable: true
  11762. });
  11763. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  11764. get: function () {
  11765. return this._blurBoxOffset;
  11766. },
  11767. set: function (value) {
  11768. var _this = this;
  11769. if (this._blurBoxOffset === value) {
  11770. return;
  11771. }
  11772. this._blurBoxOffset = value;
  11773. if (this._boxBlurPostprocess) {
  11774. this._boxBlurPostprocess.dispose();
  11775. }
  11776. 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);
  11777. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  11778. effect.setFloat2("screenSize", _this._mapSize / _this.blurScale, _this._mapSize / _this.blurScale);
  11779. });
  11780. },
  11781. enumerable: true,
  11782. configurable: true
  11783. });
  11784. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  11785. get: function () {
  11786. return this._filter;
  11787. },
  11788. set: function (value) {
  11789. if (this._filter === value) {
  11790. return;
  11791. }
  11792. this._filter = value;
  11793. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap || this.usePoissonSampling) {
  11794. this._shadowMap.anisotropicFilteringLevel = 16;
  11795. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  11796. }
  11797. else {
  11798. this._shadowMap.anisotropicFilteringLevel = 1;
  11799. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11800. }
  11801. },
  11802. enumerable: true,
  11803. configurable: true
  11804. });
  11805. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  11806. get: function () {
  11807. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP && this._light.supportsVSM();
  11808. },
  11809. set: function (value) {
  11810. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  11811. },
  11812. enumerable: true,
  11813. configurable: true
  11814. });
  11815. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  11816. get: function () {
  11817. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING ||
  11818. (!this._light.supportsVSM() && (this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP ||
  11819. this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP));
  11820. },
  11821. set: function (value) {
  11822. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  11823. },
  11824. enumerable: true,
  11825. configurable: true
  11826. });
  11827. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  11828. get: function () {
  11829. return this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP && this._light.supportsVSM();
  11830. },
  11831. set: function (value) {
  11832. this.filter = (value ? ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  11833. },
  11834. enumerable: true,
  11835. configurable: true
  11836. });
  11837. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  11838. var defines = [];
  11839. if (this._useFullFloat) {
  11840. defines.push("#define FULLFLOAT");
  11841. }
  11842. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  11843. defines.push("#define VSM");
  11844. }
  11845. if (this.getLight().needCube()) {
  11846. defines.push("#define CUBEMAP");
  11847. }
  11848. var attribs = [BABYLON.VertexBuffer.PositionKind];
  11849. var mesh = subMesh.getMesh();
  11850. var material = subMesh.getMaterial();
  11851. // Alpha test
  11852. if (material && material.needAlphaTesting()) {
  11853. defines.push("#define ALPHATEST");
  11854. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  11855. attribs.push(BABYLON.VertexBuffer.UVKind);
  11856. defines.push("#define UV1");
  11857. }
  11858. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  11859. var alphaTexture = material.getAlphaTestTexture();
  11860. if (alphaTexture.coordinatesIndex === 1) {
  11861. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  11862. defines.push("#define UV2");
  11863. }
  11864. }
  11865. }
  11866. // Bones
  11867. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  11868. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  11869. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  11870. if (mesh.numBoneInfluencers > 4) {
  11871. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  11872. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  11873. }
  11874. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  11875. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  11876. }
  11877. else {
  11878. defines.push("#define NUM_BONE_INFLUENCERS 0");
  11879. }
  11880. // Instances
  11881. if (useInstances) {
  11882. defines.push("#define INSTANCES");
  11883. attribs.push("world0");
  11884. attribs.push("world1");
  11885. attribs.push("world2");
  11886. attribs.push("world3");
  11887. }
  11888. // Get correct effect
  11889. var join = defines.join("\n");
  11890. if (this._cachedDefines !== join) {
  11891. this._cachedDefines = join;
  11892. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues"], ["diffuseSampler"], join);
  11893. }
  11894. return this._effect.isReady();
  11895. };
  11896. ShadowGenerator.prototype.getShadowMap = function () {
  11897. return this._shadowMap;
  11898. };
  11899. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  11900. if (this._shadowMap2) {
  11901. return this._shadowMap2;
  11902. }
  11903. return this._shadowMap;
  11904. };
  11905. ShadowGenerator.prototype.getLight = function () {
  11906. return this._light;
  11907. };
  11908. // Methods
  11909. ShadowGenerator.prototype.getTransformMatrix = function () {
  11910. var scene = this._scene;
  11911. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  11912. return this._transformMatrix;
  11913. }
  11914. this._currentRenderID = scene.getRenderId();
  11915. this._currentFaceIndexCache = this._currentFaceIndex;
  11916. var lightPosition = this._light.position;
  11917. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  11918. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  11919. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  11920. }
  11921. if (this._light.computeTransformedPosition()) {
  11922. lightPosition = this._light.transformedPosition;
  11923. }
  11924. if (this._light.needRefreshPerFrame() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  11925. this._cachedPosition = lightPosition.clone();
  11926. this._cachedDirection = this._lightDirection.clone();
  11927. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  11928. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  11929. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  11930. }
  11931. return this._transformMatrix;
  11932. };
  11933. ShadowGenerator.prototype.getDarkness = function () {
  11934. return this._darkness;
  11935. };
  11936. ShadowGenerator.prototype.setDarkness = function (darkness) {
  11937. if (darkness >= 1.0)
  11938. this._darkness = 1.0;
  11939. else if (darkness <= 0.0)
  11940. this._darkness = 0.0;
  11941. else
  11942. this._darkness = darkness;
  11943. };
  11944. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  11945. this._transparencyShadow = hasShadow;
  11946. };
  11947. ShadowGenerator.prototype._packHalf = function (depth) {
  11948. var scale = depth * 255.0;
  11949. var fract = scale - Math.floor(scale);
  11950. return new BABYLON.Vector2(depth - fract / 255.0, fract);
  11951. };
  11952. ShadowGenerator.prototype.dispose = function () {
  11953. this._shadowMap.dispose();
  11954. if (this._shadowMap2) {
  11955. this._shadowMap2.dispose();
  11956. }
  11957. if (this._downSamplePostprocess) {
  11958. this._downSamplePostprocess.dispose();
  11959. }
  11960. if (this._boxBlurPostprocess) {
  11961. this._boxBlurPostprocess.dispose();
  11962. }
  11963. };
  11964. ShadowGenerator.prototype.serialize = function () {
  11965. var serializationObject = {};
  11966. serializationObject.lightId = this._light.id;
  11967. serializationObject.mapSize = this.getShadowMap().getRenderSize();
  11968. serializationObject.useVarianceShadowMap = this.useVarianceShadowMap;
  11969. serializationObject.usePoissonSampling = this.usePoissonSampling;
  11970. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  11971. serializationObject.renderList = [];
  11972. for (var meshIndex = 0; meshIndex < this.getShadowMap().renderList.length; meshIndex++) {
  11973. var mesh = this.getShadowMap().renderList[meshIndex];
  11974. serializationObject.renderList.push(mesh.id);
  11975. }
  11976. return serializationObject;
  11977. };
  11978. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  11979. //casting to point light, as light is missing the position attr and typescript complains.
  11980. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  11981. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  11982. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  11983. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  11984. meshes.forEach(function (mesh) {
  11985. shadowGenerator.getShadowMap().renderList.push(mesh);
  11986. });
  11987. }
  11988. if (parsedShadowGenerator.usePoissonSampling) {
  11989. shadowGenerator.usePoissonSampling = true;
  11990. }
  11991. else if (parsedShadowGenerator.useVarianceShadowMap) {
  11992. shadowGenerator.useVarianceShadowMap = true;
  11993. }
  11994. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  11995. shadowGenerator.useBlurVarianceShadowMap = true;
  11996. if (parsedShadowGenerator.blurScale) {
  11997. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  11998. }
  11999. if (parsedShadowGenerator.blurBoxOffset) {
  12000. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  12001. }
  12002. }
  12003. if (parsedShadowGenerator.bias !== undefined) {
  12004. shadowGenerator.bias = parsedShadowGenerator.bias;
  12005. }
  12006. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  12007. return shadowGenerator;
  12008. };
  12009. ShadowGenerator._FILTER_NONE = 0;
  12010. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  12011. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  12012. ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP = 3;
  12013. return ShadowGenerator;
  12014. }());
  12015. BABYLON.ShadowGenerator = ShadowGenerator;
  12016. })(BABYLON || (BABYLON = {}));
  12017. var BABYLON;
  12018. (function (BABYLON) {
  12019. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  12020. if (boxMin.x > sphereCenter.x + sphereRadius)
  12021. return false;
  12022. if (sphereCenter.x - sphereRadius > boxMax.x)
  12023. return false;
  12024. if (boxMin.y > sphereCenter.y + sphereRadius)
  12025. return false;
  12026. if (sphereCenter.y - sphereRadius > boxMax.y)
  12027. return false;
  12028. if (boxMin.z > sphereCenter.z + sphereRadius)
  12029. return false;
  12030. if (sphereCenter.z - sphereRadius > boxMax.z)
  12031. return false;
  12032. return true;
  12033. };
  12034. var getLowestRoot = (function () {
  12035. var result = { root: 0, found: false };
  12036. return function (a, b, c, maxR) {
  12037. result.root = 0;
  12038. result.found = false;
  12039. var determinant = b * b - 4.0 * a * c;
  12040. if (determinant < 0)
  12041. return result;
  12042. var sqrtD = Math.sqrt(determinant);
  12043. var r1 = (-b - sqrtD) / (2.0 * a);
  12044. var r2 = (-b + sqrtD) / (2.0 * a);
  12045. if (r1 > r2) {
  12046. var temp = r2;
  12047. r2 = r1;
  12048. r1 = temp;
  12049. }
  12050. if (r1 > 0 && r1 < maxR) {
  12051. result.root = r1;
  12052. result.found = true;
  12053. return result;
  12054. }
  12055. if (r2 > 0 && r2 < maxR) {
  12056. result.root = r2;
  12057. result.found = true;
  12058. return result;
  12059. }
  12060. return result;
  12061. };
  12062. })();
  12063. var Collider = (function () {
  12064. function Collider() {
  12065. this.radius = new BABYLON.Vector3(1, 1, 1);
  12066. this.retry = 0;
  12067. this.basePointWorld = BABYLON.Vector3.Zero();
  12068. this.velocityWorld = BABYLON.Vector3.Zero();
  12069. this.normalizedVelocity = BABYLON.Vector3.Zero();
  12070. this._collisionPoint = BABYLON.Vector3.Zero();
  12071. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  12072. this._tempVector = BABYLON.Vector3.Zero();
  12073. this._tempVector2 = BABYLON.Vector3.Zero();
  12074. this._tempVector3 = BABYLON.Vector3.Zero();
  12075. this._tempVector4 = BABYLON.Vector3.Zero();
  12076. this._edge = BABYLON.Vector3.Zero();
  12077. this._baseToVertex = BABYLON.Vector3.Zero();
  12078. this._destinationPoint = BABYLON.Vector3.Zero();
  12079. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  12080. this._displacementVector = BABYLON.Vector3.Zero();
  12081. }
  12082. // Methods
  12083. Collider.prototype._initialize = function (source, dir, e) {
  12084. this.velocity = dir;
  12085. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  12086. this.basePoint = source;
  12087. source.multiplyToRef(this.radius, this.basePointWorld);
  12088. dir.multiplyToRef(this.radius, this.velocityWorld);
  12089. this.velocityWorldLength = this.velocityWorld.length();
  12090. this.epsilon = e;
  12091. this.collisionFound = false;
  12092. };
  12093. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  12094. pa.subtractToRef(point, this._tempVector);
  12095. pb.subtractToRef(point, this._tempVector2);
  12096. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  12097. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  12098. if (d < 0)
  12099. return false;
  12100. pc.subtractToRef(point, this._tempVector3);
  12101. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  12102. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  12103. if (d < 0)
  12104. return false;
  12105. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  12106. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  12107. return d >= 0;
  12108. };
  12109. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  12110. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  12111. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  12112. if (distance > this.velocityWorldLength + max + sphereRadius) {
  12113. return false;
  12114. }
  12115. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  12116. return false;
  12117. return true;
  12118. };
  12119. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  12120. var t0;
  12121. var embeddedInPlane = false;
  12122. //defensive programming, actually not needed.
  12123. if (!trianglePlaneArray) {
  12124. trianglePlaneArray = [];
  12125. }
  12126. if (!trianglePlaneArray[faceIndex]) {
  12127. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  12128. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  12129. }
  12130. var trianglePlane = trianglePlaneArray[faceIndex];
  12131. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  12132. return;
  12133. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  12134. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  12135. if (normalDotVelocity == 0) {
  12136. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  12137. return;
  12138. embeddedInPlane = true;
  12139. t0 = 0;
  12140. }
  12141. else {
  12142. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  12143. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  12144. if (t0 > t1) {
  12145. var temp = t1;
  12146. t1 = t0;
  12147. t0 = temp;
  12148. }
  12149. if (t0 > 1.0 || t1 < 0.0)
  12150. return;
  12151. if (t0 < 0)
  12152. t0 = 0;
  12153. if (t0 > 1.0)
  12154. t0 = 1.0;
  12155. }
  12156. this._collisionPoint.copyFromFloats(0, 0, 0);
  12157. var found = false;
  12158. var t = 1.0;
  12159. if (!embeddedInPlane) {
  12160. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  12161. this.velocity.scaleToRef(t0, this._tempVector);
  12162. this._planeIntersectionPoint.addInPlace(this._tempVector);
  12163. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  12164. found = true;
  12165. t = t0;
  12166. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  12167. }
  12168. }
  12169. if (!found) {
  12170. var velocitySquaredLength = this.velocity.lengthSquared();
  12171. var a = velocitySquaredLength;
  12172. this.basePoint.subtractToRef(p1, this._tempVector);
  12173. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  12174. var c = this._tempVector.lengthSquared() - 1.0;
  12175. var lowestRoot = getLowestRoot(a, b, c, t);
  12176. if (lowestRoot.found) {
  12177. t = lowestRoot.root;
  12178. found = true;
  12179. this._collisionPoint.copyFrom(p1);
  12180. }
  12181. this.basePoint.subtractToRef(p2, this._tempVector);
  12182. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  12183. c = this._tempVector.lengthSquared() - 1.0;
  12184. lowestRoot = getLowestRoot(a, b, c, t);
  12185. if (lowestRoot.found) {
  12186. t = lowestRoot.root;
  12187. found = true;
  12188. this._collisionPoint.copyFrom(p2);
  12189. }
  12190. this.basePoint.subtractToRef(p3, this._tempVector);
  12191. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  12192. c = this._tempVector.lengthSquared() - 1.0;
  12193. lowestRoot = getLowestRoot(a, b, c, t);
  12194. if (lowestRoot.found) {
  12195. t = lowestRoot.root;
  12196. found = true;
  12197. this._collisionPoint.copyFrom(p3);
  12198. }
  12199. p2.subtractToRef(p1, this._edge);
  12200. p1.subtractToRef(this.basePoint, this._baseToVertex);
  12201. var edgeSquaredLength = this._edge.lengthSquared();
  12202. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  12203. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  12204. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  12205. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  12206. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  12207. lowestRoot = getLowestRoot(a, b, c, t);
  12208. if (lowestRoot.found) {
  12209. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  12210. if (f >= 0.0 && f <= 1.0) {
  12211. t = lowestRoot.root;
  12212. found = true;
  12213. this._edge.scaleInPlace(f);
  12214. p1.addToRef(this._edge, this._collisionPoint);
  12215. }
  12216. }
  12217. p3.subtractToRef(p2, this._edge);
  12218. p2.subtractToRef(this.basePoint, this._baseToVertex);
  12219. edgeSquaredLength = this._edge.lengthSquared();
  12220. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  12221. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  12222. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  12223. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  12224. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  12225. lowestRoot = getLowestRoot(a, b, c, t);
  12226. if (lowestRoot.found) {
  12227. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  12228. if (f >= 0.0 && f <= 1.0) {
  12229. t = lowestRoot.root;
  12230. found = true;
  12231. this._edge.scaleInPlace(f);
  12232. p2.addToRef(this._edge, this._collisionPoint);
  12233. }
  12234. }
  12235. p1.subtractToRef(p3, this._edge);
  12236. p3.subtractToRef(this.basePoint, this._baseToVertex);
  12237. edgeSquaredLength = this._edge.lengthSquared();
  12238. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  12239. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  12240. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  12241. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  12242. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  12243. lowestRoot = getLowestRoot(a, b, c, t);
  12244. if (lowestRoot.found) {
  12245. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  12246. if (f >= 0.0 && f <= 1.0) {
  12247. t = lowestRoot.root;
  12248. found = true;
  12249. this._edge.scaleInPlace(f);
  12250. p3.addToRef(this._edge, this._collisionPoint);
  12251. }
  12252. }
  12253. }
  12254. if (found) {
  12255. var distToCollision = t * this.velocity.length();
  12256. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  12257. if (!this.intersectionPoint) {
  12258. this.intersectionPoint = this._collisionPoint.clone();
  12259. }
  12260. else {
  12261. this.intersectionPoint.copyFrom(this._collisionPoint);
  12262. }
  12263. this.nearestDistance = distToCollision;
  12264. this.collisionFound = true;
  12265. }
  12266. }
  12267. };
  12268. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  12269. for (var i = indexStart; i < indexEnd; i += 3) {
  12270. var p1 = pts[indices[i] - decal];
  12271. var p2 = pts[indices[i + 1] - decal];
  12272. var p3 = pts[indices[i + 2] - decal];
  12273. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  12274. }
  12275. };
  12276. Collider.prototype._getResponse = function (pos, vel) {
  12277. pos.addToRef(vel, this._destinationPoint);
  12278. vel.scaleInPlace((this.nearestDistance / vel.length()));
  12279. this.basePoint.addToRef(vel, pos);
  12280. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  12281. this._slidePlaneNormal.normalize();
  12282. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  12283. pos.addInPlace(this._displacementVector);
  12284. this.intersectionPoint.addInPlace(this._displacementVector);
  12285. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  12286. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  12287. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  12288. };
  12289. return Collider;
  12290. }());
  12291. BABYLON.Collider = Collider;
  12292. })(BABYLON || (BABYLON = {}));
  12293. var BABYLON;
  12294. (function (BABYLON) {
  12295. //WebWorker code will be inserted to this variable.
  12296. BABYLON.CollisionWorker = "";
  12297. (function (WorkerTaskType) {
  12298. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  12299. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  12300. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  12301. })(BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  12302. var WorkerTaskType = BABYLON.WorkerTaskType;
  12303. (function (WorkerReplyType) {
  12304. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  12305. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  12306. })(BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  12307. var WorkerReplyType = BABYLON.WorkerReplyType;
  12308. var CollisionCoordinatorWorker = (function () {
  12309. function CollisionCoordinatorWorker() {
  12310. var _this = this;
  12311. this._scaledPosition = BABYLON.Vector3.Zero();
  12312. this._scaledVelocity = BABYLON.Vector3.Zero();
  12313. this.onMeshUpdated = function (mesh) {
  12314. _this._addUpdateMeshesList[mesh.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(mesh);
  12315. };
  12316. this.onGeometryUpdated = function (geometry) {
  12317. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  12318. };
  12319. this._afterRender = function () {
  12320. if (!_this._init)
  12321. return;
  12322. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  12323. return;
  12324. }
  12325. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  12326. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  12327. if (_this._runningUpdated > 4) {
  12328. return;
  12329. }
  12330. ++_this._runningUpdated;
  12331. var payload = {
  12332. updatedMeshes: _this._addUpdateMeshesList,
  12333. updatedGeometries: _this._addUpdateGeometriesList,
  12334. removedGeometries: _this._toRemoveGeometryArray,
  12335. removedMeshes: _this._toRemoveMeshesArray
  12336. };
  12337. var message = {
  12338. payload: payload,
  12339. taskType: WorkerTaskType.UPDATE
  12340. };
  12341. var serializable = [];
  12342. for (var id in payload.updatedGeometries) {
  12343. if (payload.updatedGeometries.hasOwnProperty(id)) {
  12344. //prepare transferables
  12345. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  12346. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  12347. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  12348. }
  12349. }
  12350. _this._worker.postMessage(message, serializable);
  12351. _this._addUpdateMeshesList = {};
  12352. _this._addUpdateGeometriesList = {};
  12353. _this._toRemoveGeometryArray = [];
  12354. _this._toRemoveMeshesArray = [];
  12355. };
  12356. this._onMessageFromWorker = function (e) {
  12357. var returnData = e.data;
  12358. if (returnData.error != WorkerReplyType.SUCCESS) {
  12359. //TODO what errors can be returned from the worker?
  12360. BABYLON.Tools.Warn("error returned from worker!");
  12361. return;
  12362. }
  12363. switch (returnData.taskType) {
  12364. case WorkerTaskType.INIT:
  12365. _this._init = true;
  12366. //Update the worked with ALL of the scene's current state
  12367. _this._scene.meshes.forEach(function (mesh) {
  12368. _this.onMeshAdded(mesh);
  12369. });
  12370. _this._scene.getGeometries().forEach(function (geometry) {
  12371. _this.onGeometryAdded(geometry);
  12372. });
  12373. break;
  12374. case WorkerTaskType.UPDATE:
  12375. _this._runningUpdated--;
  12376. break;
  12377. case WorkerTaskType.COLLIDE:
  12378. _this._runningCollisionTask = false;
  12379. var returnPayload = returnData.payload;
  12380. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  12381. return;
  12382. _this._collisionsCallbackArray[returnPayload.collisionId](returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId));
  12383. //cleanup
  12384. _this._collisionsCallbackArray[returnPayload.collisionId] = undefined;
  12385. break;
  12386. }
  12387. };
  12388. this._collisionsCallbackArray = [];
  12389. this._init = false;
  12390. this._runningUpdated = 0;
  12391. this._runningCollisionTask = false;
  12392. this._addUpdateMeshesList = {};
  12393. this._addUpdateGeometriesList = {};
  12394. this._toRemoveGeometryArray = [];
  12395. this._toRemoveMeshesArray = [];
  12396. }
  12397. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  12398. if (!this._init)
  12399. return;
  12400. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  12401. return;
  12402. position.divideToRef(collider.radius, this._scaledPosition);
  12403. velocity.divideToRef(collider.radius, this._scaledVelocity);
  12404. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  12405. var payload = {
  12406. collider: {
  12407. position: this._scaledPosition.asArray(),
  12408. velocity: this._scaledVelocity.asArray(),
  12409. radius: collider.radius.asArray()
  12410. },
  12411. collisionId: collisionIndex,
  12412. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  12413. maximumRetry: maximumRetry
  12414. };
  12415. var message = {
  12416. payload: payload,
  12417. taskType: WorkerTaskType.COLLIDE
  12418. };
  12419. this._worker.postMessage(message);
  12420. };
  12421. CollisionCoordinatorWorker.prototype.init = function (scene) {
  12422. this._scene = scene;
  12423. this._scene.registerAfterRender(this._afterRender);
  12424. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  12425. this._worker = new Worker(workerUrl);
  12426. this._worker.onmessage = this._onMessageFromWorker;
  12427. var message = {
  12428. payload: {},
  12429. taskType: WorkerTaskType.INIT
  12430. };
  12431. this._worker.postMessage(message);
  12432. };
  12433. CollisionCoordinatorWorker.prototype.destroy = function () {
  12434. this._scene.unregisterAfterRender(this._afterRender);
  12435. this._worker.terminate();
  12436. };
  12437. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  12438. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  12439. this.onMeshUpdated(mesh);
  12440. };
  12441. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  12442. this._toRemoveMeshesArray.push(mesh.uniqueId);
  12443. };
  12444. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  12445. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  12446. geometry.onGeometryUpdated = this.onGeometryUpdated;
  12447. this.onGeometryUpdated(geometry);
  12448. };
  12449. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  12450. this._toRemoveGeometryArray.push(geometry.id);
  12451. };
  12452. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  12453. var submeshes = [];
  12454. if (mesh.subMeshes) {
  12455. submeshes = mesh.subMeshes.map(function (sm, idx) {
  12456. return {
  12457. position: idx,
  12458. verticesStart: sm.verticesStart,
  12459. verticesCount: sm.verticesCount,
  12460. indexStart: sm.indexStart,
  12461. indexCount: sm.indexCount,
  12462. hasMaterial: !!sm.getMaterial(),
  12463. sphereCenter: sm.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  12464. sphereRadius: sm.getBoundingInfo().boundingSphere.radiusWorld,
  12465. boxMinimum: sm.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  12466. boxMaximum: sm.getBoundingInfo().boundingBox.maximumWorld.asArray()
  12467. };
  12468. });
  12469. }
  12470. var geometryId = null;
  12471. if (mesh instanceof BABYLON.Mesh) {
  12472. geometryId = mesh.geometry ? mesh.geometry.id : null;
  12473. }
  12474. else if (mesh instanceof BABYLON.InstancedMesh) {
  12475. geometryId = (mesh.sourceMesh && mesh.sourceMesh.geometry) ? mesh.sourceMesh.geometry.id : null;
  12476. }
  12477. return {
  12478. uniqueId: mesh.uniqueId,
  12479. id: mesh.id,
  12480. name: mesh.name,
  12481. geometryId: geometryId,
  12482. sphereCenter: mesh.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  12483. sphereRadius: mesh.getBoundingInfo().boundingSphere.radiusWorld,
  12484. boxMinimum: mesh.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  12485. boxMaximum: mesh.getBoundingInfo().boundingBox.maximumWorld.asArray(),
  12486. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  12487. subMeshes: submeshes,
  12488. checkCollisions: mesh.checkCollisions
  12489. };
  12490. };
  12491. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  12492. return {
  12493. id: geometry.id,
  12494. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  12495. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  12496. indices: new Int32Array(geometry.getIndices() || []),
  12497. };
  12498. };
  12499. return CollisionCoordinatorWorker;
  12500. }());
  12501. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  12502. var CollisionCoordinatorLegacy = (function () {
  12503. function CollisionCoordinatorLegacy() {
  12504. this._scaledPosition = BABYLON.Vector3.Zero();
  12505. this._scaledVelocity = BABYLON.Vector3.Zero();
  12506. this._finalPosition = BABYLON.Vector3.Zero();
  12507. }
  12508. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  12509. position.divideToRef(collider.radius, this._scaledPosition);
  12510. velocity.divideToRef(collider.radius, this._scaledVelocity);
  12511. collider.collidedMesh = null;
  12512. collider.retry = 0;
  12513. collider.initialVelocity = this._scaledVelocity;
  12514. collider.initialPosition = this._scaledPosition;
  12515. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  12516. this._finalPosition.multiplyInPlace(collider.radius);
  12517. //run the callback
  12518. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  12519. };
  12520. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  12521. this._scene = scene;
  12522. };
  12523. CollisionCoordinatorLegacy.prototype.destroy = function () {
  12524. //Legacy need no destruction method.
  12525. };
  12526. //No update in legacy mode
  12527. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  12528. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  12529. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  12530. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  12531. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  12532. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  12533. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  12534. if (excludedMesh === void 0) { excludedMesh = null; }
  12535. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  12536. if (collider.retry >= maximumRetry) {
  12537. finalPosition.copyFrom(position);
  12538. return;
  12539. }
  12540. collider._initialize(position, velocity, closeDistance);
  12541. // Check all meshes
  12542. for (var index = 0; index < this._scene.meshes.length; index++) {
  12543. var mesh = this._scene.meshes[index];
  12544. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  12545. mesh._checkCollision(collider);
  12546. }
  12547. }
  12548. if (!collider.collisionFound) {
  12549. position.addToRef(velocity, finalPosition);
  12550. return;
  12551. }
  12552. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  12553. collider._getResponse(position, velocity);
  12554. }
  12555. if (velocity.length() <= closeDistance) {
  12556. finalPosition.copyFrom(position);
  12557. return;
  12558. }
  12559. collider.retry++;
  12560. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  12561. };
  12562. return CollisionCoordinatorLegacy;
  12563. }());
  12564. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  12565. })(BABYLON || (BABYLON = {}));
  12566. var BABYLON;
  12567. (function (BABYLON) {
  12568. var Camera = (function (_super) {
  12569. __extends(Camera, _super);
  12570. function Camera(name, position, scene) {
  12571. _super.call(this, name, scene);
  12572. this.upVector = BABYLON.Vector3.Up();
  12573. this.orthoLeft = null;
  12574. this.orthoRight = null;
  12575. this.orthoBottom = null;
  12576. this.orthoTop = null;
  12577. this.fov = 0.8;
  12578. this.minZ = 1.0;
  12579. this.maxZ = 10000.0;
  12580. this.inertia = 0.9;
  12581. this.mode = Camera.PERSPECTIVE_CAMERA;
  12582. this.isIntermediate = false;
  12583. this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  12584. this.layerMask = 0x0FFFFFFF;
  12585. this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  12586. // Camera rig members
  12587. this.cameraRigMode = Camera.RIG_MODE_NONE;
  12588. this._rigCameras = new Array();
  12589. // Cache
  12590. this._computedViewMatrix = BABYLON.Matrix.Identity();
  12591. this._projectionMatrix = new BABYLON.Matrix();
  12592. this._postProcesses = new Array();
  12593. this._transformMatrix = BABYLON.Matrix.Zero();
  12594. this._activeMeshes = new BABYLON.SmartArray(256);
  12595. this._globalPosition = BABYLON.Vector3.Zero();
  12596. this._refreshFrustumPlanes = true;
  12597. scene.addCamera(this);
  12598. if (!scene.activeCamera) {
  12599. scene.activeCamera = this;
  12600. }
  12601. this.position = position;
  12602. }
  12603. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  12604. get: function () {
  12605. return Camera._PERSPECTIVE_CAMERA;
  12606. },
  12607. enumerable: true,
  12608. configurable: true
  12609. });
  12610. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  12611. get: function () {
  12612. return Camera._ORTHOGRAPHIC_CAMERA;
  12613. },
  12614. enumerable: true,
  12615. configurable: true
  12616. });
  12617. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  12618. get: function () {
  12619. return Camera._FOVMODE_VERTICAL_FIXED;
  12620. },
  12621. enumerable: true,
  12622. configurable: true
  12623. });
  12624. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  12625. get: function () {
  12626. return Camera._FOVMODE_HORIZONTAL_FIXED;
  12627. },
  12628. enumerable: true,
  12629. configurable: true
  12630. });
  12631. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  12632. get: function () {
  12633. return Camera._RIG_MODE_NONE;
  12634. },
  12635. enumerable: true,
  12636. configurable: true
  12637. });
  12638. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  12639. get: function () {
  12640. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  12641. },
  12642. enumerable: true,
  12643. configurable: true
  12644. });
  12645. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  12646. get: function () {
  12647. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  12648. },
  12649. enumerable: true,
  12650. configurable: true
  12651. });
  12652. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  12653. get: function () {
  12654. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  12655. },
  12656. enumerable: true,
  12657. configurable: true
  12658. });
  12659. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  12660. get: function () {
  12661. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  12662. },
  12663. enumerable: true,
  12664. configurable: true
  12665. });
  12666. Object.defineProperty(Camera, "RIG_MODE_VR", {
  12667. get: function () {
  12668. return Camera._RIG_MODE_VR;
  12669. },
  12670. enumerable: true,
  12671. configurable: true
  12672. });
  12673. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  12674. get: function () {
  12675. return Camera._RIG_MODE_WEBVR;
  12676. },
  12677. enumerable: true,
  12678. configurable: true
  12679. });
  12680. /**
  12681. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  12682. */
  12683. Camera.prototype.toString = function (fullDetails) {
  12684. var ret = "Name: " + this.name;
  12685. ret += ", type: " + this.getTypeName();
  12686. if (this.animations) {
  12687. for (var i = 0; i < this.animations.length; i++) {
  12688. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  12689. }
  12690. }
  12691. if (fullDetails) {
  12692. }
  12693. return ret;
  12694. };
  12695. Object.defineProperty(Camera.prototype, "globalPosition", {
  12696. get: function () {
  12697. return this._globalPosition;
  12698. },
  12699. enumerable: true,
  12700. configurable: true
  12701. });
  12702. Camera.prototype.getActiveMeshes = function () {
  12703. return this._activeMeshes;
  12704. };
  12705. Camera.prototype.isActiveMesh = function (mesh) {
  12706. return (this._activeMeshes.indexOf(mesh) !== -1);
  12707. };
  12708. //Cache
  12709. Camera.prototype._initCache = function () {
  12710. _super.prototype._initCache.call(this);
  12711. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  12712. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  12713. this._cache.mode = undefined;
  12714. this._cache.minZ = undefined;
  12715. this._cache.maxZ = undefined;
  12716. this._cache.fov = undefined;
  12717. this._cache.fovMode = undefined;
  12718. this._cache.aspectRatio = undefined;
  12719. this._cache.orthoLeft = undefined;
  12720. this._cache.orthoRight = undefined;
  12721. this._cache.orthoBottom = undefined;
  12722. this._cache.orthoTop = undefined;
  12723. this._cache.renderWidth = undefined;
  12724. this._cache.renderHeight = undefined;
  12725. };
  12726. Camera.prototype._updateCache = function (ignoreParentClass) {
  12727. if (!ignoreParentClass) {
  12728. _super.prototype._updateCache.call(this);
  12729. }
  12730. var engine = this.getEngine();
  12731. this._cache.position.copyFrom(this.position);
  12732. this._cache.upVector.copyFrom(this.upVector);
  12733. this._cache.mode = this.mode;
  12734. this._cache.minZ = this.minZ;
  12735. this._cache.maxZ = this.maxZ;
  12736. this._cache.fov = this.fov;
  12737. this._cache.fovMode = this.fovMode;
  12738. this._cache.aspectRatio = engine.getAspectRatio(this);
  12739. this._cache.orthoLeft = this.orthoLeft;
  12740. this._cache.orthoRight = this.orthoRight;
  12741. this._cache.orthoBottom = this.orthoBottom;
  12742. this._cache.orthoTop = this.orthoTop;
  12743. this._cache.renderWidth = engine.getRenderWidth();
  12744. this._cache.renderHeight = engine.getRenderHeight();
  12745. };
  12746. Camera.prototype._updateFromScene = function () {
  12747. this.updateCache();
  12748. this.update();
  12749. };
  12750. // Synchronized
  12751. Camera.prototype._isSynchronized = function () {
  12752. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  12753. };
  12754. Camera.prototype._isSynchronizedViewMatrix = function () {
  12755. if (!_super.prototype._isSynchronized.call(this))
  12756. return false;
  12757. return this._cache.position.equals(this.position)
  12758. && this._cache.upVector.equals(this.upVector)
  12759. && this.isSynchronizedWithParent();
  12760. };
  12761. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  12762. var check = this._cache.mode === this.mode
  12763. && this._cache.minZ === this.minZ
  12764. && this._cache.maxZ === this.maxZ;
  12765. if (!check) {
  12766. return false;
  12767. }
  12768. var engine = this.getEngine();
  12769. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  12770. check = this._cache.fov === this.fov
  12771. && this._cache.fovMode === this.fovMode
  12772. && this._cache.aspectRatio === engine.getAspectRatio(this);
  12773. }
  12774. else {
  12775. check = this._cache.orthoLeft === this.orthoLeft
  12776. && this._cache.orthoRight === this.orthoRight
  12777. && this._cache.orthoBottom === this.orthoBottom
  12778. && this._cache.orthoTop === this.orthoTop
  12779. && this._cache.renderWidth === engine.getRenderWidth()
  12780. && this._cache.renderHeight === engine.getRenderHeight();
  12781. }
  12782. return check;
  12783. };
  12784. // Controls
  12785. Camera.prototype.attachControl = function (element, noPreventDefault) {
  12786. };
  12787. Camera.prototype.detachControl = function (element) {
  12788. };
  12789. Camera.prototype.update = function () {
  12790. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  12791. this._updateRigCameras();
  12792. }
  12793. this._checkInputs();
  12794. };
  12795. Camera.prototype._checkInputs = function () {
  12796. };
  12797. Camera.prototype._cascadePostProcessesToRigCams = function () {
  12798. // invalidate framebuffer
  12799. if (this._postProcesses.length > 0) {
  12800. this._postProcesses[0].markTextureDirty();
  12801. }
  12802. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  12803. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  12804. var cam = this._rigCameras[i];
  12805. var rigPostProcess = cam._rigPostProcess;
  12806. // for VR rig, there does not have to be a post process
  12807. if (rigPostProcess) {
  12808. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  12809. if (isPass) {
  12810. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  12811. cam.isIntermediate = this._postProcesses.length === 0;
  12812. }
  12813. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  12814. rigPostProcess.markTextureDirty();
  12815. }
  12816. else {
  12817. cam._postProcesses = this._postProcesses.slice(0);
  12818. }
  12819. }
  12820. };
  12821. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  12822. if (insertAt === void 0) { insertAt = null; }
  12823. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  12824. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  12825. return 0;
  12826. }
  12827. if (insertAt == null || insertAt < 0) {
  12828. this._postProcesses.push(postProcess);
  12829. }
  12830. else {
  12831. this._postProcesses.splice(insertAt, 0, postProcess);
  12832. }
  12833. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  12834. return this._postProcesses.indexOf(postProcess);
  12835. };
  12836. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  12837. if (atIndices === void 0) { atIndices = null; }
  12838. var result = [];
  12839. var i;
  12840. var index;
  12841. if (!atIndices) {
  12842. var idx = this._postProcesses.indexOf(postProcess);
  12843. if (idx !== -1) {
  12844. this._postProcesses.splice(idx, 1);
  12845. }
  12846. }
  12847. else {
  12848. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  12849. // iterate descending, so can just splice as we go
  12850. for (i = atIndices.length - 1; i >= 0; i--) {
  12851. if (this._postProcesses[atIndices[i]] !== postProcess) {
  12852. result.push(i);
  12853. continue;
  12854. }
  12855. this._postProcesses.splice(index, 1);
  12856. }
  12857. }
  12858. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  12859. return result;
  12860. };
  12861. Camera.prototype.getWorldMatrix = function () {
  12862. if (!this._worldMatrix) {
  12863. this._worldMatrix = BABYLON.Matrix.Identity();
  12864. }
  12865. var viewMatrix = this.getViewMatrix();
  12866. viewMatrix.invertToRef(this._worldMatrix);
  12867. return this._worldMatrix;
  12868. };
  12869. Camera.prototype._getViewMatrix = function () {
  12870. return BABYLON.Matrix.Identity();
  12871. };
  12872. Camera.prototype.getViewMatrix = function (force) {
  12873. this._computedViewMatrix = this._computeViewMatrix(force);
  12874. if (!force && this._isSynchronizedViewMatrix()) {
  12875. return this._computedViewMatrix;
  12876. }
  12877. this._refreshFrustumPlanes = true;
  12878. if (!this.parent || !this.parent.getWorldMatrix) {
  12879. this._globalPosition.copyFrom(this.position);
  12880. }
  12881. else {
  12882. if (!this._worldMatrix) {
  12883. this._worldMatrix = BABYLON.Matrix.Identity();
  12884. }
  12885. this._computedViewMatrix.invertToRef(this._worldMatrix);
  12886. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  12887. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  12888. this._computedViewMatrix.invert();
  12889. this._markSyncedWithParent();
  12890. }
  12891. this._currentRenderId = this.getScene().getRenderId();
  12892. return this._computedViewMatrix;
  12893. };
  12894. Camera.prototype._computeViewMatrix = function (force) {
  12895. if (!force && this._isSynchronizedViewMatrix()) {
  12896. return this._computedViewMatrix;
  12897. }
  12898. this._computedViewMatrix = this._getViewMatrix();
  12899. this._currentRenderId = this.getScene().getRenderId();
  12900. return this._computedViewMatrix;
  12901. };
  12902. Camera.prototype.getProjectionMatrix = function (force) {
  12903. if (!force && this._isSynchronizedProjectionMatrix()) {
  12904. return this._projectionMatrix;
  12905. }
  12906. this._refreshFrustumPlanes = true;
  12907. var engine = this.getEngine();
  12908. var scene = this.getScene();
  12909. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  12910. if (this.minZ <= 0) {
  12911. this.minZ = 0.1;
  12912. }
  12913. if (scene.useRightHandedSystem) {
  12914. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  12915. }
  12916. else {
  12917. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  12918. }
  12919. return this._projectionMatrix;
  12920. }
  12921. var halfWidth = engine.getRenderWidth() / 2.0;
  12922. var halfHeight = engine.getRenderHeight() / 2.0;
  12923. if (scene.useRightHandedSystem) {
  12924. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  12925. }
  12926. else {
  12927. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  12928. }
  12929. return this._projectionMatrix;
  12930. };
  12931. Camera.prototype.getTranformationMatrix = function () {
  12932. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  12933. return this._transformMatrix;
  12934. };
  12935. Camera.prototype.updateFrustumPlanes = function () {
  12936. if (!this._refreshFrustumPlanes) {
  12937. return;
  12938. }
  12939. this.getTranformationMatrix();
  12940. if (!this._frustumPlanes) {
  12941. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  12942. }
  12943. else {
  12944. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  12945. }
  12946. this._refreshFrustumPlanes = false;
  12947. };
  12948. Camera.prototype.isInFrustum = function (target) {
  12949. this.updateFrustumPlanes();
  12950. return target.isInFrustum(this._frustumPlanes);
  12951. };
  12952. Camera.prototype.isCompletelyInFrustum = function (target) {
  12953. this.updateFrustumPlanes();
  12954. return target.isCompletelyInFrustum(this._frustumPlanes);
  12955. };
  12956. Camera.prototype.dispose = function () {
  12957. // Animations
  12958. this.getScene().stopAnimation(this);
  12959. // Remove from scene
  12960. this.getScene().removeCamera(this);
  12961. while (this._rigCameras.length > 0) {
  12962. this._rigCameras.pop().dispose();
  12963. }
  12964. // Postprocesses
  12965. for (var i = 0; i < this._postProcesses.length; ++i) {
  12966. this._postProcesses[i].dispose(this);
  12967. }
  12968. _super.prototype.dispose.call(this);
  12969. };
  12970. // ---- Camera rigs section ----
  12971. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  12972. while (this._rigCameras.length > 0) {
  12973. this._rigCameras.pop().dispose();
  12974. }
  12975. this.cameraRigMode = mode;
  12976. this._cameraRigParams = {};
  12977. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  12978. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  12979. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  12980. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  12981. // create the rig cameras, unless none
  12982. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  12983. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  12984. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  12985. }
  12986. switch (this.cameraRigMode) {
  12987. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  12988. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  12989. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  12990. break;
  12991. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  12992. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  12993. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  12994. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  12995. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  12996. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  12997. break;
  12998. case Camera.RIG_MODE_VR:
  12999. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  13000. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  13001. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  13002. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  13003. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  13004. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  13005. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  13006. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  13007. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  13008. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  13009. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  13010. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  13011. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  13012. if (metrics.compensateDistortion) {
  13013. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  13014. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  13015. }
  13016. break;
  13017. case Camera.RIG_MODE_WEBVR:
  13018. if (rigParams.vrDisplay) {
  13019. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  13020. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  13021. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  13022. this._rigCameras[0].setCameraRigParameter("vrFieldOfView", leftEye.fieldOfView);
  13023. this._rigCameras[0].setCameraRigParameter("vrOffsetMatrix", BABYLON.Matrix.Translation(-leftEye.offset[0], leftEye.offset[1], -leftEye.offset[2]));
  13024. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  13025. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  13026. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  13027. this._rigCameras[1].setCameraRigParameter("vrFieldOfView", rightEye.fieldOfView);
  13028. this._rigCameras[1].setCameraRigParameter("vrOffsetMatrix", BABYLON.Matrix.Translation(-rightEye.offset[0], rightEye.offset[1], -rightEye.offset[2]));
  13029. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  13030. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  13031. }
  13032. break;
  13033. }
  13034. this._cascadePostProcessesToRigCams();
  13035. this.
  13036. update();
  13037. };
  13038. Camera.prototype._getVRProjectionMatrix = function () {
  13039. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  13040. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  13041. return this._projectionMatrix;
  13042. };
  13043. Camera.prototype._getWebVRProjectionMatrix = function () {
  13044. BABYLON.Matrix.PerspectiveFovWebVRToRef(this._cameraRigParams['vrFieldOfView'], this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  13045. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams['vrOffsetMatrix'], this._projectionMatrix);
  13046. return this._projectionMatrix;
  13047. };
  13048. Camera.prototype.setCameraRigParameter = function (name, value) {
  13049. if (!this._cameraRigParams) {
  13050. this._cameraRigParams = {};
  13051. }
  13052. this._cameraRigParams[name] = value;
  13053. //provisionnally:
  13054. if (name === "interaxialDistance") {
  13055. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  13056. }
  13057. };
  13058. /**
  13059. * needs to be overridden by children so sub has required properties to be copied
  13060. */
  13061. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  13062. return null;
  13063. };
  13064. /**
  13065. * May need to be overridden by children
  13066. */
  13067. Camera.prototype._updateRigCameras = function () {
  13068. for (var i = 0; i < this._rigCameras.length; i++) {
  13069. this._rigCameras[i].minZ = this.minZ;
  13070. this._rigCameras[i].maxZ = this.maxZ;
  13071. this._rigCameras[i].fov = this.fov;
  13072. }
  13073. // only update viewport when ANAGLYPH
  13074. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  13075. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  13076. }
  13077. };
  13078. Camera.prototype._setupInputs = function () {
  13079. };
  13080. Camera.prototype.serialize = function () {
  13081. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  13082. // Type
  13083. serializationObject.type = this.getTypeName();
  13084. // Parent
  13085. if (this.parent) {
  13086. serializationObject.parentId = this.parent.id;
  13087. }
  13088. if (this.inputs) {
  13089. this.inputs.serialize(serializationObject);
  13090. }
  13091. // Animations
  13092. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  13093. serializationObject.ranges = this.serializeAnimationRanges();
  13094. return serializationObject;
  13095. };
  13096. Camera.prototype.getTypeName = function () {
  13097. return "Camera";
  13098. };
  13099. Camera.prototype.clone = function (name) {
  13100. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getTypeName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  13101. };
  13102. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  13103. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  13104. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  13105. switch (type) {
  13106. case "ArcRotateCamera":
  13107. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  13108. case "DeviceOrientationCamera":
  13109. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  13110. case "FollowCamera":
  13111. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  13112. case "ArcFollowCamera":
  13113. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  13114. case "GamepadCamera":
  13115. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  13116. case "TouchCamera":
  13117. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  13118. case "VirtualJoysticksCamera":
  13119. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  13120. case "WebVRFreeCamera":
  13121. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  13122. case "VRDeviceOrientationFreeCamera":
  13123. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  13124. case "AnaglyphArcRotateCamera":
  13125. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  13126. case "AnaglyphFreeCamera":
  13127. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  13128. case "AnaglyphGamepadCamera":
  13129. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  13130. case "AnaglyphUniversalCamera":
  13131. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  13132. case "StereoscopicArcRotateCamera":
  13133. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  13134. case "StereoscopicFreeCamera":
  13135. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  13136. case "StereoscopicGamepadCamera":
  13137. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  13138. case "StereoscopicUniversalCamera":
  13139. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  13140. case "FreeCamera":
  13141. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  13142. default:
  13143. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  13144. }
  13145. };
  13146. Camera.Parse = function (parsedCamera, scene) {
  13147. var type = parsedCamera.type;
  13148. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  13149. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  13150. // Parent
  13151. if (parsedCamera.parentId) {
  13152. camera._waitingParentId = parsedCamera.parentId;
  13153. }
  13154. //If camera has an input manager, let it parse inputs settings
  13155. if (camera.inputs) {
  13156. camera.inputs.parse(parsedCamera);
  13157. camera._setupInputs();
  13158. }
  13159. // Target
  13160. if (parsedCamera.target) {
  13161. if (camera.setTarget) {
  13162. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  13163. }
  13164. }
  13165. // Apply 3d rig, when found
  13166. if (parsedCamera.cameraRigMode) {
  13167. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  13168. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  13169. }
  13170. // Animations
  13171. if (parsedCamera.animations) {
  13172. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  13173. var parsedAnimation = parsedCamera.animations[animationIndex];
  13174. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  13175. }
  13176. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  13177. }
  13178. if (parsedCamera.autoAnimate) {
  13179. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  13180. }
  13181. return camera;
  13182. };
  13183. // Statics
  13184. Camera._PERSPECTIVE_CAMERA = 0;
  13185. Camera._ORTHOGRAPHIC_CAMERA = 1;
  13186. Camera._FOVMODE_VERTICAL_FIXED = 0;
  13187. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  13188. Camera._RIG_MODE_NONE = 0;
  13189. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  13190. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  13191. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  13192. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  13193. Camera._RIG_MODE_VR = 20;
  13194. Camera._RIG_MODE_WEBVR = 21;
  13195. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  13196. __decorate([
  13197. BABYLON.serializeAsVector3()
  13198. ], Camera.prototype, "position", void 0);
  13199. __decorate([
  13200. BABYLON.serializeAsVector3()
  13201. ], Camera.prototype, "upVector", void 0);
  13202. __decorate([
  13203. BABYLON.serialize()
  13204. ], Camera.prototype, "orthoLeft", void 0);
  13205. __decorate([
  13206. BABYLON.serialize()
  13207. ], Camera.prototype, "orthoRight", void 0);
  13208. __decorate([
  13209. BABYLON.serialize()
  13210. ], Camera.prototype, "orthoBottom", void 0);
  13211. __decorate([
  13212. BABYLON.serialize()
  13213. ], Camera.prototype, "orthoTop", void 0);
  13214. __decorate([
  13215. BABYLON.serialize()
  13216. ], Camera.prototype, "fov", void 0);
  13217. __decorate([
  13218. BABYLON.serialize()
  13219. ], Camera.prototype, "minZ", void 0);
  13220. __decorate([
  13221. BABYLON.serialize()
  13222. ], Camera.prototype, "maxZ", void 0);
  13223. __decorate([
  13224. BABYLON.serialize()
  13225. ], Camera.prototype, "inertia", void 0);
  13226. __decorate([
  13227. BABYLON.serialize()
  13228. ], Camera.prototype, "mode", void 0);
  13229. __decorate([
  13230. BABYLON.serialize()
  13231. ], Camera.prototype, "layerMask", void 0);
  13232. __decorate([
  13233. BABYLON.serialize()
  13234. ], Camera.prototype, "fovMode", void 0);
  13235. __decorate([
  13236. BABYLON.serialize()
  13237. ], Camera.prototype, "cameraRigMode", void 0);
  13238. __decorate([
  13239. BABYLON.serialize()
  13240. ], Camera.prototype, "interaxialDistance", void 0);
  13241. __decorate([
  13242. BABYLON.serialize()
  13243. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  13244. return Camera;
  13245. }(BABYLON.Node));
  13246. BABYLON.Camera = Camera;
  13247. })(BABYLON || (BABYLON = {}));
  13248. var BABYLON;
  13249. (function (BABYLON) {
  13250. BABYLON.CameraInputTypes = {};
  13251. var CameraInputsManager = (function () {
  13252. function CameraInputsManager(camera) {
  13253. this.attached = {};
  13254. this.camera = camera;
  13255. this.checkInputs = function () { };
  13256. }
  13257. CameraInputsManager.prototype.add = function (input) {
  13258. var type = input.getSimpleName();
  13259. if (this.attached[type]) {
  13260. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  13261. return;
  13262. }
  13263. this.attached[type] = input;
  13264. input.camera = this.camera;
  13265. //for checkInputs, we are dynamically creating a function
  13266. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  13267. if (input.checkInputs) {
  13268. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  13269. }
  13270. if (this.attachedElement) {
  13271. input.attachControl(this.attachedElement);
  13272. }
  13273. };
  13274. CameraInputsManager.prototype.remove = function (inputToRemove) {
  13275. for (var cam in this.attached) {
  13276. var input = this.attached[cam];
  13277. if (input === inputToRemove) {
  13278. input.detachControl(this.attachedElement);
  13279. delete this.attached[cam];
  13280. this.rebuildInputCheck();
  13281. }
  13282. }
  13283. };
  13284. CameraInputsManager.prototype.removeByType = function (inputType) {
  13285. for (var cam in this.attached) {
  13286. var input = this.attached[cam];
  13287. if (input.getTypeName() === inputType) {
  13288. input.detachControl(this.attachedElement);
  13289. delete this.attached[cam];
  13290. this.rebuildInputCheck();
  13291. }
  13292. }
  13293. };
  13294. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  13295. var current = this.checkInputs;
  13296. return function () {
  13297. current();
  13298. fn();
  13299. };
  13300. };
  13301. CameraInputsManager.prototype.attachInput = function (input) {
  13302. input.attachControl(this.attachedElement, this.noPreventDefault);
  13303. };
  13304. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  13305. if (this.attachedElement) {
  13306. return;
  13307. }
  13308. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  13309. this.attachedElement = element;
  13310. this.noPreventDefault = noPreventDefault;
  13311. for (var cam in this.attached) {
  13312. var input = this.attached[cam];
  13313. this.attached[cam].attachControl(element, noPreventDefault);
  13314. }
  13315. };
  13316. CameraInputsManager.prototype.detachElement = function (element) {
  13317. if (this.attachedElement !== element) {
  13318. return;
  13319. }
  13320. for (var cam in this.attached) {
  13321. var input = this.attached[cam];
  13322. this.attached[cam].detachControl(element);
  13323. }
  13324. this.attachedElement = null;
  13325. };
  13326. CameraInputsManager.prototype.rebuildInputCheck = function () {
  13327. this.checkInputs = function () { };
  13328. for (var cam in this.attached) {
  13329. var input = this.attached[cam];
  13330. if (input.checkInputs) {
  13331. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  13332. }
  13333. }
  13334. };
  13335. CameraInputsManager.prototype.clear = function () {
  13336. if (this.attachedElement) {
  13337. this.detachElement(this.attachedElement);
  13338. }
  13339. this.attached = {};
  13340. this.attachedElement = null;
  13341. this.checkInputs = function () { };
  13342. };
  13343. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  13344. var inputs = {};
  13345. for (var cam in this.attached) {
  13346. var input = this.attached[cam];
  13347. var res = BABYLON.SerializationHelper.Serialize(input);
  13348. inputs[input.getTypeName()] = res;
  13349. }
  13350. serializedCamera.inputsmgr = inputs;
  13351. };
  13352. CameraInputsManager.prototype.parse = function (parsedCamera) {
  13353. var parsedInputs = parsedCamera.inputsmgr;
  13354. if (parsedInputs) {
  13355. this.clear();
  13356. for (var n in parsedInputs) {
  13357. var construct = BABYLON.CameraInputTypes[n];
  13358. if (construct) {
  13359. var parsedinput = parsedInputs[n];
  13360. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  13361. this.add(input);
  13362. }
  13363. }
  13364. }
  13365. else {
  13366. //2016-03-08 this part is for managing backward compatibility
  13367. for (var n in this.attached) {
  13368. var construct = BABYLON.CameraInputTypes[this.attached[n].getTypeName()];
  13369. if (construct) {
  13370. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  13371. this.remove(this.attached[n]);
  13372. this.add(input);
  13373. }
  13374. }
  13375. }
  13376. };
  13377. return CameraInputsManager;
  13378. }());
  13379. BABYLON.CameraInputsManager = CameraInputsManager;
  13380. })(BABYLON || (BABYLON = {}));
  13381. var BABYLON;
  13382. (function (BABYLON) {
  13383. var FreeCameraMouseInput = (function () {
  13384. function FreeCameraMouseInput(touchEnabled) {
  13385. if (touchEnabled === void 0) { touchEnabled = true; }
  13386. this.touchEnabled = touchEnabled;
  13387. this.angularSensibility = 2000.0;
  13388. }
  13389. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  13390. var _this = this;
  13391. if (!this._pointerInput) {
  13392. var camera = this.camera;
  13393. var engine = this.camera.getEngine();
  13394. this._pointerInput = function (p, s) {
  13395. var evt = p.event;
  13396. if (!_this.touchEnabled && evt.pointerType === "touch") {
  13397. return;
  13398. }
  13399. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  13400. try {
  13401. evt.srcElement.setPointerCapture(evt.pointerId);
  13402. }
  13403. catch (e) {
  13404. }
  13405. _this.previousPosition = {
  13406. x: evt.clientX,
  13407. y: evt.clientY
  13408. };
  13409. if (!noPreventDefault) {
  13410. evt.preventDefault();
  13411. element.focus();
  13412. }
  13413. }
  13414. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  13415. try {
  13416. evt.srcElement.releasePointerCapture(evt.pointerId);
  13417. }
  13418. catch (e) {
  13419. }
  13420. _this.previousPosition = null;
  13421. if (!noPreventDefault) {
  13422. evt.preventDefault();
  13423. }
  13424. }
  13425. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  13426. if (!_this.previousPosition || engine.isPointerLock) {
  13427. return;
  13428. }
  13429. var offsetX = evt.clientX - _this.previousPosition.x;
  13430. var offsetY = evt.clientY - _this.previousPosition.y;
  13431. if (_this.camera.getScene().useRightHandedSystem) {
  13432. camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  13433. }
  13434. else {
  13435. camera.cameraRotation.y += offsetX / _this.angularSensibility;
  13436. }
  13437. camera.cameraRotation.x += offsetY / _this.angularSensibility;
  13438. _this.previousPosition = {
  13439. x: evt.clientX,
  13440. y: evt.clientY
  13441. };
  13442. if (!noPreventDefault) {
  13443. evt.preventDefault();
  13444. }
  13445. }
  13446. };
  13447. }
  13448. this._onMouseMove = function (evt) {
  13449. if (!engine.isPointerLock) {
  13450. return;
  13451. }
  13452. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  13453. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  13454. if (_this.camera.getScene().useRightHandedSystem) {
  13455. camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  13456. }
  13457. else {
  13458. camera.cameraRotation.y += offsetX / _this.angularSensibility;
  13459. }
  13460. camera.cameraRotation.x += offsetY / _this.angularSensibility;
  13461. _this.previousPosition = null;
  13462. if (!noPreventDefault) {
  13463. evt.preventDefault();
  13464. }
  13465. };
  13466. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  13467. element.addEventListener("mousemove", this._onMouseMove, false);
  13468. };
  13469. FreeCameraMouseInput.prototype.detachControl = function (element) {
  13470. if (this._observer && element) {
  13471. this.camera.getScene().onPointerObservable.remove(this._observer);
  13472. element.removeEventListener("mousemove", this._onMouseMove);
  13473. this._observer = null;
  13474. this._onMouseMove = null;
  13475. this.previousPosition = null;
  13476. }
  13477. };
  13478. FreeCameraMouseInput.prototype.getTypeName = function () {
  13479. return "FreeCameraMouseInput";
  13480. };
  13481. FreeCameraMouseInput.prototype.getSimpleName = function () {
  13482. return "mouse";
  13483. };
  13484. __decorate([
  13485. BABYLON.serialize()
  13486. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  13487. return FreeCameraMouseInput;
  13488. }());
  13489. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  13490. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  13491. })(BABYLON || (BABYLON = {}));
  13492. var BABYLON;
  13493. (function (BABYLON) {
  13494. var FreeCameraKeyboardMoveInput = (function () {
  13495. function FreeCameraKeyboardMoveInput() {
  13496. this._keys = [];
  13497. this.keysUp = [38];
  13498. this.keysDown = [40];
  13499. this.keysLeft = [37];
  13500. this.keysRight = [39];
  13501. }
  13502. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  13503. var _this = this;
  13504. if (!this._onKeyDown) {
  13505. element.tabIndex = 1;
  13506. this._onKeyDown = function (evt) {
  13507. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  13508. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  13509. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  13510. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  13511. var index = _this._keys.indexOf(evt.keyCode);
  13512. if (index === -1) {
  13513. _this._keys.push(evt.keyCode);
  13514. }
  13515. if (!noPreventDefault) {
  13516. evt.preventDefault();
  13517. }
  13518. }
  13519. };
  13520. this._onKeyUp = function (evt) {
  13521. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  13522. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  13523. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  13524. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  13525. var index = _this._keys.indexOf(evt.keyCode);
  13526. if (index >= 0) {
  13527. _this._keys.splice(index, 1);
  13528. }
  13529. if (!noPreventDefault) {
  13530. evt.preventDefault();
  13531. }
  13532. }
  13533. };
  13534. element.addEventListener("keydown", this._onKeyDown, false);
  13535. element.addEventListener("keyup", this._onKeyUp, false);
  13536. BABYLON.Tools.RegisterTopRootEvents([
  13537. { name: "blur", handler: this._onLostFocus }
  13538. ]);
  13539. }
  13540. };
  13541. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  13542. if (this._onKeyDown) {
  13543. element.removeEventListener("keydown", this._onKeyDown);
  13544. element.removeEventListener("keyup", this._onKeyUp);
  13545. BABYLON.Tools.UnregisterTopRootEvents([
  13546. { name: "blur", handler: this._onLostFocus }
  13547. ]);
  13548. this._keys = [];
  13549. this._onKeyDown = null;
  13550. this._onKeyUp = null;
  13551. }
  13552. };
  13553. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  13554. if (this._onKeyDown) {
  13555. var camera = this.camera;
  13556. // Keyboard
  13557. for (var index = 0; index < this._keys.length; index++) {
  13558. var keyCode = this._keys[index];
  13559. var speed = camera._computeLocalCameraSpeed();
  13560. if (this.keysLeft.indexOf(keyCode) !== -1) {
  13561. camera._localDirection.copyFromFloats(-speed, 0, 0);
  13562. }
  13563. else if (this.keysUp.indexOf(keyCode) !== -1) {
  13564. camera._localDirection.copyFromFloats(0, 0, speed);
  13565. }
  13566. else if (this.keysRight.indexOf(keyCode) !== -1) {
  13567. camera._localDirection.copyFromFloats(speed, 0, 0);
  13568. }
  13569. else if (this.keysDown.indexOf(keyCode) !== -1) {
  13570. camera._localDirection.copyFromFloats(0, 0, -speed);
  13571. }
  13572. if (camera.getScene().useRightHandedSystem) {
  13573. camera._localDirection.z *= -1;
  13574. }
  13575. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  13576. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  13577. camera.cameraDirection.addInPlace(camera._transformedDirection);
  13578. }
  13579. }
  13580. };
  13581. FreeCameraKeyboardMoveInput.prototype.getTypeName = function () {
  13582. return "FreeCameraKeyboardMoveInput";
  13583. };
  13584. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  13585. this._keys = [];
  13586. };
  13587. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  13588. return "keyboard";
  13589. };
  13590. __decorate([
  13591. BABYLON.serialize()
  13592. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  13593. __decorate([
  13594. BABYLON.serialize()
  13595. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  13596. __decorate([
  13597. BABYLON.serialize()
  13598. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  13599. __decorate([
  13600. BABYLON.serialize()
  13601. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  13602. return FreeCameraKeyboardMoveInput;
  13603. }());
  13604. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  13605. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  13606. })(BABYLON || (BABYLON = {}));
  13607. var BABYLON;
  13608. (function (BABYLON) {
  13609. var FreeCameraTouchInput = (function () {
  13610. function FreeCameraTouchInput() {
  13611. this._offsetX = null;
  13612. this._offsetY = null;
  13613. this._pointerCount = 0;
  13614. this._pointerPressed = [];
  13615. this.touchAngularSensibility = 200000.0;
  13616. this.touchMoveSensibility = 250.0;
  13617. }
  13618. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  13619. var _this = this;
  13620. var previousPosition;
  13621. if (this._pointerInput === undefined) {
  13622. this._onLostFocus = function (evt) {
  13623. _this._offsetX = null;
  13624. _this._offsetY = null;
  13625. };
  13626. this._pointerInput = function (p, s) {
  13627. var evt = p.event;
  13628. if (evt.pointerType === "mouse") {
  13629. return;
  13630. }
  13631. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  13632. if (!noPreventDefault) {
  13633. evt.preventDefault();
  13634. }
  13635. _this._pointerPressed.push(evt.pointerId);
  13636. if (_this._pointerPressed.length !== 1) {
  13637. return;
  13638. }
  13639. previousPosition = {
  13640. x: evt.clientX,
  13641. y: evt.clientY
  13642. };
  13643. }
  13644. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  13645. if (!noPreventDefault) {
  13646. evt.preventDefault();
  13647. }
  13648. var index = _this._pointerPressed.indexOf(evt.pointerId);
  13649. if (index === -1) {
  13650. return;
  13651. }
  13652. _this._pointerPressed.splice(index, 1);
  13653. if (index != 0) {
  13654. return;
  13655. }
  13656. previousPosition = null;
  13657. _this._offsetX = null;
  13658. _this._offsetY = null;
  13659. }
  13660. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  13661. if (!noPreventDefault) {
  13662. evt.preventDefault();
  13663. }
  13664. if (!previousPosition) {
  13665. return;
  13666. }
  13667. var index = _this._pointerPressed.indexOf(evt.pointerId);
  13668. if (index != 0) {
  13669. return;
  13670. }
  13671. _this._offsetX = evt.clientX - previousPosition.x;
  13672. _this._offsetY = -(evt.clientY - previousPosition.y);
  13673. }
  13674. };
  13675. }
  13676. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  13677. element.addEventListener("blur", this._onLostFocus);
  13678. };
  13679. FreeCameraTouchInput.prototype.detachControl = function (element) {
  13680. if (this._pointerInput && element) {
  13681. this.camera.getScene().onPointerObservable.remove(this._observer);
  13682. this._observer = null;
  13683. element.removeEventListener("blur", this._onLostFocus);
  13684. this._onLostFocus = null;
  13685. this._pointerPressed = [];
  13686. this._offsetX = null;
  13687. this._offsetY = null;
  13688. this._pointerCount = 0;
  13689. }
  13690. };
  13691. FreeCameraTouchInput.prototype.checkInputs = function () {
  13692. if (this._offsetX) {
  13693. var camera = this.camera;
  13694. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  13695. if (this._pointerPressed.length > 1) {
  13696. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  13697. }
  13698. else {
  13699. var speed = camera._computeLocalCameraSpeed();
  13700. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  13701. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  13702. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  13703. }
  13704. }
  13705. };
  13706. FreeCameraTouchInput.prototype.getTypeName = function () {
  13707. return "FreeCameraTouchInput";
  13708. };
  13709. FreeCameraTouchInput.prototype.getSimpleName = function () {
  13710. return "touch";
  13711. };
  13712. __decorate([
  13713. BABYLON.serialize()
  13714. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  13715. __decorate([
  13716. BABYLON.serialize()
  13717. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  13718. return FreeCameraTouchInput;
  13719. }());
  13720. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  13721. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  13722. })(BABYLON || (BABYLON = {}));
  13723. var BABYLON;
  13724. (function (BABYLON) {
  13725. var FreeCameraDeviceOrientationInput = (function () {
  13726. function FreeCameraDeviceOrientationInput() {
  13727. var _this = this;
  13728. this._screenOrientationAngle = 0;
  13729. this._screenQuaternion = new BABYLON.Quaternion();
  13730. this._alpha = 0;
  13731. this._beta = 0;
  13732. this._gamma = 0;
  13733. this._orientationChanged = function () {
  13734. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  13735. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  13736. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  13737. };
  13738. this._deviceOrientation = function (evt) {
  13739. _this._alpha = evt.alpha;
  13740. _this._beta = evt.beta;
  13741. _this._gamma = evt.gamma;
  13742. };
  13743. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  13744. this._orientationChanged();
  13745. }
  13746. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  13747. get: function () {
  13748. return this._camera;
  13749. },
  13750. set: function (camera) {
  13751. this._camera = camera;
  13752. if (!this._camera.rotationQuaternion)
  13753. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  13754. },
  13755. enumerable: true,
  13756. configurable: true
  13757. });
  13758. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  13759. window.addEventListener("orientationchange", this._orientationChanged);
  13760. window.addEventListener("deviceorientation", this._deviceOrientation);
  13761. //In certain cases, the attach control is called AFTER orientation was changed,
  13762. //So this is needed.
  13763. this._orientationChanged();
  13764. };
  13765. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  13766. window.removeEventListener("orientationchange", this._orientationChanged);
  13767. window.removeEventListener("deviceorientation", this._deviceOrientation);
  13768. };
  13769. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  13770. //if no device orientation provided, don't update the rotation.
  13771. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  13772. if (!this._alpha)
  13773. return;
  13774. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  13775. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  13776. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  13777. //Mirror on XY Plane
  13778. this._camera.rotationQuaternion.z *= -1;
  13779. this._camera.rotationQuaternion.w *= -1;
  13780. };
  13781. FreeCameraDeviceOrientationInput.prototype.getTypeName = function () {
  13782. return "FreeCameraDeviceOrientationInput";
  13783. };
  13784. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  13785. return "deviceOrientation";
  13786. };
  13787. return FreeCameraDeviceOrientationInput;
  13788. }());
  13789. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  13790. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  13791. })(BABYLON || (BABYLON = {}));
  13792. var BABYLON;
  13793. (function (BABYLON) {
  13794. var FreeCameraGamepadInput = (function () {
  13795. function FreeCameraGamepadInput() {
  13796. this.gamepadAngularSensibility = 200;
  13797. this.gamepadMoveSensibility = 40;
  13798. }
  13799. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  13800. var _this = this;
  13801. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  13802. };
  13803. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  13804. if (this._gamepads) {
  13805. this._gamepads.dispose();
  13806. }
  13807. this.gamepad = null;
  13808. };
  13809. FreeCameraGamepadInput.prototype.checkInputs = function () {
  13810. if (this.gamepad) {
  13811. var camera = this.camera;
  13812. var LSValues = this.gamepad.leftStick;
  13813. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  13814. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  13815. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  13816. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  13817. var RSValues = this.gamepad.rightStick;
  13818. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  13819. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  13820. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  13821. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  13822. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  13823. var speed = camera._computeLocalCameraSpeed() * 50.0;
  13824. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x * speed, 0, -LSValues.y * speed), cameraTransform);
  13825. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  13826. camera.cameraRotation = camera.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  13827. }
  13828. };
  13829. FreeCameraGamepadInput.prototype._onNewGameConnected = function (gamepad) {
  13830. // Only the first gamepad can control the camera
  13831. if (gamepad.index === 0) {
  13832. this.gamepad = gamepad;
  13833. }
  13834. };
  13835. FreeCameraGamepadInput.prototype.getTypeName = function () {
  13836. return "FreeCameraGamepadInput";
  13837. };
  13838. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  13839. return "gamepad";
  13840. };
  13841. __decorate([
  13842. BABYLON.serialize()
  13843. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  13844. __decorate([
  13845. BABYLON.serialize()
  13846. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  13847. return FreeCameraGamepadInput;
  13848. }());
  13849. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  13850. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  13851. })(BABYLON || (BABYLON = {}));
  13852. var BABYLON;
  13853. (function (BABYLON) {
  13854. var ArcRotateCameraKeyboardMoveInput = (function () {
  13855. function ArcRotateCameraKeyboardMoveInput() {
  13856. this._keys = [];
  13857. this.keysUp = [38];
  13858. this.keysDown = [40];
  13859. this.keysLeft = [37];
  13860. this.keysRight = [39];
  13861. }
  13862. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  13863. var _this = this;
  13864. element.tabIndex = 1;
  13865. this._onKeyDown = function (evt) {
  13866. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  13867. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  13868. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  13869. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  13870. var index = _this._keys.indexOf(evt.keyCode);
  13871. if (index === -1) {
  13872. _this._keys.push(evt.keyCode);
  13873. }
  13874. if (evt.preventDefault) {
  13875. if (!noPreventDefault) {
  13876. evt.preventDefault();
  13877. }
  13878. }
  13879. }
  13880. };
  13881. this._onKeyUp = function (evt) {
  13882. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  13883. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  13884. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  13885. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  13886. var index = _this._keys.indexOf(evt.keyCode);
  13887. if (index >= 0) {
  13888. _this._keys.splice(index, 1);
  13889. }
  13890. if (evt.preventDefault) {
  13891. if (!noPreventDefault) {
  13892. evt.preventDefault();
  13893. }
  13894. }
  13895. }
  13896. };
  13897. this._onLostFocus = function () {
  13898. _this._keys = [];
  13899. };
  13900. element.addEventListener("keydown", this._onKeyDown, false);
  13901. element.addEventListener("keyup", this._onKeyUp, false);
  13902. BABYLON.Tools.RegisterTopRootEvents([
  13903. { name: "blur", handler: this._onLostFocus }
  13904. ]);
  13905. };
  13906. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  13907. if (element) {
  13908. element.removeEventListener("keydown", this._onKeyDown);
  13909. element.removeEventListener("keyup", this._onKeyUp);
  13910. }
  13911. BABYLON.Tools.UnregisterTopRootEvents([
  13912. { name: "blur", handler: this._onLostFocus }
  13913. ]);
  13914. this._keys = [];
  13915. this._onKeyDown = null;
  13916. this._onKeyUp = null;
  13917. this._onLostFocus = null;
  13918. };
  13919. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  13920. if (this._onKeyDown) {
  13921. var camera = this.camera;
  13922. for (var index = 0; index < this._keys.length; index++) {
  13923. var keyCode = this._keys[index];
  13924. if (this.keysLeft.indexOf(keyCode) !== -1) {
  13925. camera.inertialAlphaOffset -= 0.01;
  13926. }
  13927. else if (this.keysUp.indexOf(keyCode) !== -1) {
  13928. camera.inertialBetaOffset -= 0.01;
  13929. }
  13930. else if (this.keysRight.indexOf(keyCode) !== -1) {
  13931. camera.inertialAlphaOffset += 0.01;
  13932. }
  13933. else if (this.keysDown.indexOf(keyCode) !== -1) {
  13934. camera.inertialBetaOffset += 0.01;
  13935. }
  13936. }
  13937. }
  13938. };
  13939. ArcRotateCameraKeyboardMoveInput.prototype.getTypeName = function () {
  13940. return "ArcRotateCameraKeyboardMoveInput";
  13941. };
  13942. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  13943. return "keyboard";
  13944. };
  13945. __decorate([
  13946. BABYLON.serialize()
  13947. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  13948. __decorate([
  13949. BABYLON.serialize()
  13950. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  13951. __decorate([
  13952. BABYLON.serialize()
  13953. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  13954. __decorate([
  13955. BABYLON.serialize()
  13956. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  13957. return ArcRotateCameraKeyboardMoveInput;
  13958. }());
  13959. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  13960. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  13961. })(BABYLON || (BABYLON = {}));
  13962. var BABYLON;
  13963. (function (BABYLON) {
  13964. var ArcRotateCameraMouseWheelInput = (function () {
  13965. function ArcRotateCameraMouseWheelInput() {
  13966. this.wheelPrecision = 3.0;
  13967. }
  13968. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  13969. var _this = this;
  13970. this._wheel = function (p, s) {
  13971. //sanity check - this should be a PointerWheel event.
  13972. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  13973. return;
  13974. var event = p.event;
  13975. var delta = 0;
  13976. if (event.wheelDelta) {
  13977. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  13978. }
  13979. else if (event.detail) {
  13980. delta = -event.detail / _this.wheelPrecision;
  13981. }
  13982. if (delta)
  13983. _this.camera.inertialRadiusOffset += delta;
  13984. if (event.preventDefault) {
  13985. if (!noPreventDefault) {
  13986. event.preventDefault();
  13987. }
  13988. }
  13989. };
  13990. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  13991. };
  13992. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  13993. if (this._observer && element) {
  13994. this.camera.getScene().onPointerObservable.remove(this._observer);
  13995. this._observer = null;
  13996. this._wheel = null;
  13997. }
  13998. };
  13999. ArcRotateCameraMouseWheelInput.prototype.getTypeName = function () {
  14000. return "ArcRotateCameraMouseWheelInput";
  14001. };
  14002. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  14003. return "mousewheel";
  14004. };
  14005. __decorate([
  14006. BABYLON.serialize()
  14007. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  14008. return ArcRotateCameraMouseWheelInput;
  14009. }());
  14010. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  14011. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  14012. })(BABYLON || (BABYLON = {}));
  14013. var BABYLON;
  14014. (function (BABYLON) {
  14015. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  14016. var ArcRotateCameraPointersInput = (function () {
  14017. function ArcRotateCameraPointersInput() {
  14018. this.angularSensibilityX = 1000.0;
  14019. this.angularSensibilityY = 1000.0;
  14020. this.pinchPrecision = 6.0;
  14021. this.panningSensibility = 50.0;
  14022. this._isPanClick = false;
  14023. this.pinchInwards = true;
  14024. }
  14025. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  14026. var _this = this;
  14027. var engine = this.camera.getEngine();
  14028. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  14029. var pointA, pointB;
  14030. var previousPinchDistance = 0;
  14031. this._pointerInput = function (p, s) {
  14032. var evt = p.event;
  14033. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  14034. try {
  14035. evt.srcElement.setPointerCapture(evt.pointerId);
  14036. }
  14037. catch (e) {
  14038. }
  14039. // Manage panning with pan button click
  14040. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  14041. // manage pointers
  14042. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  14043. if (pointA === undefined) {
  14044. pointA = cacheSoloPointer;
  14045. }
  14046. else if (pointB === undefined) {
  14047. pointB = cacheSoloPointer;
  14048. }
  14049. if (!noPreventDefault) {
  14050. evt.preventDefault();
  14051. element.focus();
  14052. }
  14053. }
  14054. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  14055. try {
  14056. evt.srcElement.releasePointerCapture(evt.pointerId);
  14057. }
  14058. catch (e) {
  14059. }
  14060. cacheSoloPointer = null;
  14061. previousPinchDistance = 0;
  14062. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  14063. //but emptying completly pointers collection is required to fix a bug on iPhone :
  14064. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  14065. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  14066. pointA = pointB = undefined;
  14067. if (!noPreventDefault) {
  14068. evt.preventDefault();
  14069. }
  14070. }
  14071. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  14072. if (!noPreventDefault) {
  14073. evt.preventDefault();
  14074. }
  14075. // One button down
  14076. if (pointA && pointB === undefined) {
  14077. if (_this.panningSensibility !== 0 &&
  14078. ((evt.ctrlKey && _this.camera._useCtrlForPanning) ||
  14079. (!_this.camera._useCtrlForPanning && _this._isPanClick))) {
  14080. _this.camera
  14081. .inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  14082. _this.camera
  14083. .inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  14084. }
  14085. else {
  14086. var offsetX = evt.clientX - cacheSoloPointer.x;
  14087. var offsetY = evt.clientY - cacheSoloPointer.y;
  14088. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  14089. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  14090. }
  14091. cacheSoloPointer.x = evt.clientX;
  14092. cacheSoloPointer.y = evt.clientY;
  14093. }
  14094. else if (pointA && pointB) {
  14095. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  14096. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  14097. ed.x = evt.clientX;
  14098. ed.y = evt.clientY;
  14099. var direction = _this.pinchInwards ? 1 : -1;
  14100. var distX = pointA.x - pointB.x;
  14101. var distY = pointA.y - pointB.y;
  14102. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  14103. if (previousPinchDistance === 0) {
  14104. previousPinchDistance = pinchSquaredDistance;
  14105. return;
  14106. }
  14107. if (pinchSquaredDistance !== previousPinchDistance) {
  14108. _this.camera
  14109. .inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) /
  14110. (_this.pinchPrecision *
  14111. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  14112. direction);
  14113. previousPinchDistance = pinchSquaredDistance;
  14114. }
  14115. }
  14116. }
  14117. };
  14118. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  14119. this._onContextMenu = function (evt) {
  14120. evt.preventDefault();
  14121. };
  14122. if (!this.camera._useCtrlForPanning) {
  14123. element.addEventListener("contextmenu", this._onContextMenu, false);
  14124. }
  14125. this._onLostFocus = function () {
  14126. //this._keys = [];
  14127. pointA = pointB = undefined;
  14128. previousPinchDistance = 0;
  14129. cacheSoloPointer = null;
  14130. };
  14131. this._onMouseMove = function (evt) {
  14132. if (!engine.isPointerLock) {
  14133. return;
  14134. }
  14135. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  14136. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  14137. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  14138. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  14139. if (!noPreventDefault) {
  14140. evt.preventDefault();
  14141. }
  14142. };
  14143. this._onGestureStart = function (e) {
  14144. if (window.MSGesture === undefined) {
  14145. return;
  14146. }
  14147. if (!_this._MSGestureHandler) {
  14148. _this._MSGestureHandler = new MSGesture();
  14149. _this._MSGestureHandler.target = element;
  14150. }
  14151. _this._MSGestureHandler.addPointer(e.pointerId);
  14152. };
  14153. this._onGesture = function (e) {
  14154. _this.camera.radius *= e.scale;
  14155. if (e.preventDefault) {
  14156. if (!noPreventDefault) {
  14157. e.stopPropagation();
  14158. e.preventDefault();
  14159. }
  14160. }
  14161. };
  14162. element.addEventListener("mousemove", this._onMouseMove, false);
  14163. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  14164. element.addEventListener("MSGestureChange", this._onGesture, false);
  14165. element.addEventListener("keydown", this._onKeyDown, false);
  14166. element.addEventListener("keyup", this._onKeyUp, false);
  14167. BABYLON.Tools.RegisterTopRootEvents([
  14168. { name: "blur", handler: this._onLostFocus }
  14169. ]);
  14170. };
  14171. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  14172. if (element && this._observer) {
  14173. this.camera.getScene().onPointerObservable.remove(this._observer);
  14174. this._observer = null;
  14175. element.removeEventListener("contextmenu", this._onContextMenu);
  14176. element.removeEventListener("mousemove", this._onMouseMove);
  14177. element.removeEventListener("MSPointerDown", this._onGestureStart);
  14178. element.removeEventListener("MSGestureChange", this._onGesture);
  14179. element.removeEventListener("keydown", this._onKeyDown);
  14180. element.removeEventListener("keyup", this._onKeyUp);
  14181. this._isPanClick = false;
  14182. this.pinchInwards = true;
  14183. this._onKeyDown = null;
  14184. this._onKeyUp = null;
  14185. this._onMouseMove = null;
  14186. this._onGestureStart = null;
  14187. this._onGesture = null;
  14188. this._MSGestureHandler = null;
  14189. this._onLostFocus = null;
  14190. this._onContextMenu = null;
  14191. }
  14192. BABYLON.Tools.UnregisterTopRootEvents([
  14193. { name: "blur", handler: this._onLostFocus }
  14194. ]);
  14195. };
  14196. ArcRotateCameraPointersInput.prototype.getTypeName = function () {
  14197. return "ArcRotateCameraPointersInput";
  14198. };
  14199. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  14200. return "pointers";
  14201. };
  14202. __decorate([
  14203. BABYLON.serialize()
  14204. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  14205. __decorate([
  14206. BABYLON.serialize()
  14207. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  14208. __decorate([
  14209. BABYLON.serialize()
  14210. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  14211. __decorate([
  14212. BABYLON.serialize()
  14213. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  14214. return ArcRotateCameraPointersInput;
  14215. }());
  14216. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  14217. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  14218. })(BABYLON || (BABYLON = {}));
  14219. var BABYLON;
  14220. (function (BABYLON) {
  14221. var ArcRotateCameraGamepadInput = (function () {
  14222. function ArcRotateCameraGamepadInput() {
  14223. this.gamepadRotationSensibility = 80;
  14224. this.gamepadMoveSensibility = 40;
  14225. }
  14226. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  14227. var _this = this;
  14228. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  14229. };
  14230. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  14231. if (this._gamepads) {
  14232. this._gamepads.dispose();
  14233. }
  14234. this.gamepad = null;
  14235. };
  14236. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  14237. if (this.gamepad) {
  14238. var camera = this.camera;
  14239. var RSValues = this.gamepad.rightStick;
  14240. if (RSValues.x != 0) {
  14241. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  14242. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  14243. camera.inertialAlphaOffset += normalizedRX;
  14244. }
  14245. }
  14246. if (RSValues.y != 0) {
  14247. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  14248. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  14249. camera.inertialBetaOffset += normalizedRY;
  14250. }
  14251. }
  14252. var LSValues = this.gamepad.leftStick;
  14253. if (LSValues.y != 0) {
  14254. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  14255. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  14256. this.camera.inertialRadiusOffset -= normalizedLY;
  14257. }
  14258. }
  14259. }
  14260. };
  14261. ArcRotateCameraGamepadInput.prototype._onNewGameConnected = function (gamepad) {
  14262. // Only the first gamepad can control the camera
  14263. if (gamepad.index === 0) {
  14264. this.gamepad = gamepad;
  14265. }
  14266. };
  14267. ArcRotateCameraGamepadInput.prototype.getTypeName = function () {
  14268. return "ArcRotateCameraGamepadInput";
  14269. };
  14270. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  14271. return "gamepad";
  14272. };
  14273. __decorate([
  14274. BABYLON.serialize()
  14275. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  14276. __decorate([
  14277. BABYLON.serialize()
  14278. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  14279. return ArcRotateCameraGamepadInput;
  14280. }());
  14281. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  14282. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  14283. })(BABYLON || (BABYLON = {}));
  14284. var BABYLON;
  14285. (function (BABYLON) {
  14286. var ArcRotateCameraVRDeviceOrientationInput = (function () {
  14287. function ArcRotateCameraVRDeviceOrientationInput() {
  14288. this.alphaCorrection = 1;
  14289. this.betaCorrection = 1;
  14290. this.gammaCorrection = 1;
  14291. this._alpha = 0;
  14292. this._beta = 0;
  14293. this._gamma = 0;
  14294. this._dirty = false;
  14295. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  14296. }
  14297. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  14298. this.camera.attachControl(element, noPreventDefault);
  14299. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  14300. };
  14301. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  14302. var camera = this.camera;
  14303. this._alpha = +evt.alpha | 0;
  14304. this._beta = +evt.beta | 0;
  14305. this._gamma = +evt.gamma | 0;
  14306. this._dirty = true;
  14307. };
  14308. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  14309. if (this._dirty) {
  14310. this._dirty = false;
  14311. if (this._gamma < 0) {
  14312. this._gamma = 180 + this._gamma;
  14313. }
  14314. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  14315. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  14316. }
  14317. };
  14318. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  14319. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  14320. };
  14321. ArcRotateCameraVRDeviceOrientationInput.prototype.getTypeName = function () {
  14322. return "ArcRotateCameraVRDeviceOrientationInput";
  14323. };
  14324. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  14325. return "VRDeviceOrientation";
  14326. };
  14327. return ArcRotateCameraVRDeviceOrientationInput;
  14328. }());
  14329. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  14330. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  14331. })(BABYLON || (BABYLON = {}));
  14332. var BABYLON;
  14333. (function (BABYLON) {
  14334. var TargetCamera = (function (_super) {
  14335. __extends(TargetCamera, _super);
  14336. function TargetCamera(name, position, scene) {
  14337. _super.call(this, name, position, scene);
  14338. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  14339. this.cameraRotation = new BABYLON.Vector2(0, 0);
  14340. this.rotation = new BABYLON.Vector3(0, 0, 0);
  14341. this.speed = 2.0;
  14342. this.noRotationConstraint = false;
  14343. this.lockedTarget = null;
  14344. this._currentTarget = BABYLON.Vector3.Zero();
  14345. this._viewMatrix = BABYLON.Matrix.Zero();
  14346. this._camMatrix = BABYLON.Matrix.Zero();
  14347. this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  14348. this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  14349. this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  14350. this._defaultUpVector = new BABYLON.Vector3(0, 1, 0);
  14351. this._transformedReferencePoint = BABYLON.Vector3.Zero();
  14352. this._lookAtTemp = BABYLON.Matrix.Zero();
  14353. this._tempMatrix = BABYLON.Matrix.Zero();
  14354. }
  14355. TargetCamera.prototype.getFrontPosition = function (distance) {
  14356. var direction = this.getTarget().subtract(this.position);
  14357. direction.normalize();
  14358. direction.scaleInPlace(distance);
  14359. return this.globalPosition.add(direction);
  14360. };
  14361. TargetCamera.prototype._getLockedTargetPosition = function () {
  14362. if (!this.lockedTarget) {
  14363. return null;
  14364. }
  14365. return this.lockedTarget.position || this.lockedTarget;
  14366. };
  14367. // Cache
  14368. TargetCamera.prototype._initCache = function () {
  14369. _super.prototype._initCache.call(this);
  14370. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  14371. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  14372. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  14373. };
  14374. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  14375. if (!ignoreParentClass) {
  14376. _super.prototype._updateCache.call(this);
  14377. }
  14378. var lockedTargetPosition = this._getLockedTargetPosition();
  14379. if (!lockedTargetPosition) {
  14380. this._cache.lockedTarget = null;
  14381. }
  14382. else {
  14383. if (!this._cache.lockedTarget) {
  14384. this._cache.lockedTarget = lockedTargetPosition.clone();
  14385. }
  14386. else {
  14387. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  14388. }
  14389. }
  14390. this._cache.rotation.copyFrom(this.rotation);
  14391. if (this.rotationQuaternion)
  14392. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  14393. };
  14394. // Synchronized
  14395. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  14396. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  14397. return false;
  14398. }
  14399. var lockedTargetPosition = this._getLockedTargetPosition();
  14400. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  14401. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  14402. };
  14403. // Methods
  14404. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  14405. var engine = this.getEngine();
  14406. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  14407. };
  14408. // Target
  14409. TargetCamera.prototype.setTarget = function (target) {
  14410. this.upVector.normalize();
  14411. BABYLON.Matrix.LookAtLHToRef(this.position, target, this._defaultUpVector, this._camMatrix);
  14412. this._camMatrix.invert();
  14413. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  14414. var vDir = target.subtract(this.position);
  14415. if (vDir.x >= 0.0) {
  14416. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  14417. }
  14418. else {
  14419. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  14420. }
  14421. this.rotation.z = 0;
  14422. if (isNaN(this.rotation.x)) {
  14423. this.rotation.x = 0;
  14424. }
  14425. if (isNaN(this.rotation.y)) {
  14426. this.rotation.y = 0;
  14427. }
  14428. if (isNaN(this.rotation.z)) {
  14429. this.rotation.z = 0;
  14430. }
  14431. if (this.rotationQuaternion) {
  14432. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  14433. }
  14434. };
  14435. TargetCamera.prototype.getTarget = function () {
  14436. return this._currentTarget;
  14437. };
  14438. TargetCamera.prototype._decideIfNeedsToMove = function () {
  14439. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  14440. };
  14441. TargetCamera.prototype._updatePosition = function () {
  14442. this.position.addInPlace(this.cameraDirection);
  14443. };
  14444. TargetCamera.prototype._checkInputs = function () {
  14445. var needToMove = this._decideIfNeedsToMove();
  14446. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  14447. // Move
  14448. if (needToMove) {
  14449. this._updatePosition();
  14450. }
  14451. // Rotate
  14452. if (needToRotate) {
  14453. this.rotation.x += this.cameraRotation.x;
  14454. this.rotation.y += this.cameraRotation.y;
  14455. if (!this.noRotationConstraint) {
  14456. var limit = (Math.PI / 2) * 0.95;
  14457. if (this.rotation.x > limit)
  14458. this.rotation.x = limit;
  14459. if (this.rotation.x < -limit)
  14460. this.rotation.x = -limit;
  14461. }
  14462. }
  14463. // Inertia
  14464. if (needToMove) {
  14465. if (Math.abs(this.cameraDirection.x) < BABYLON.Epsilon) {
  14466. this.cameraDirection.x = 0;
  14467. }
  14468. if (Math.abs(this.cameraDirection.y) < BABYLON.Epsilon) {
  14469. this.cameraDirection.y = 0;
  14470. }
  14471. if (Math.abs(this.cameraDirection.z) < BABYLON.Epsilon) {
  14472. this.cameraDirection.z = 0;
  14473. }
  14474. this.cameraDirection.scaleInPlace(this.inertia);
  14475. }
  14476. if (needToRotate) {
  14477. if (Math.abs(this.cameraRotation.x) < BABYLON.Epsilon) {
  14478. this.cameraRotation.x = 0;
  14479. }
  14480. if (Math.abs(this.cameraRotation.y) < BABYLON.Epsilon) {
  14481. this.cameraRotation.y = 0;
  14482. }
  14483. this.cameraRotation.scaleInPlace(this.inertia);
  14484. }
  14485. _super.prototype._checkInputs.call(this);
  14486. };
  14487. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  14488. if (this.rotationQuaternion) {
  14489. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  14490. //update the up vector!
  14491. BABYLON.Vector3.TransformNormalToRef(this._defaultUpVector, this._cameraRotationMatrix, this.upVector);
  14492. }
  14493. else {
  14494. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  14495. }
  14496. };
  14497. TargetCamera.prototype._getViewMatrix = function () {
  14498. if (!this.lockedTarget) {
  14499. // Compute
  14500. this._updateCameraRotationMatrix();
  14501. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  14502. // Computing target and final matrix
  14503. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  14504. }
  14505. else {
  14506. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  14507. }
  14508. if (this.getScene().useRightHandedSystem) {
  14509. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  14510. }
  14511. else {
  14512. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  14513. }
  14514. return this._viewMatrix;
  14515. };
  14516. /**
  14517. * @override
  14518. * Override Camera.createRigCamera
  14519. */
  14520. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  14521. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  14522. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  14523. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  14524. if (!this.rotationQuaternion) {
  14525. this.rotationQuaternion = new BABYLON.Quaternion();
  14526. }
  14527. rigCamera._cameraRigParams = {};
  14528. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  14529. }
  14530. return rigCamera;
  14531. }
  14532. return null;
  14533. };
  14534. /**
  14535. * @override
  14536. * Override Camera._updateRigCameras
  14537. */
  14538. TargetCamera.prototype._updateRigCameras = function () {
  14539. var camLeft = this._rigCameras[0];
  14540. var camRight = this._rigCameras[1];
  14541. switch (this.cameraRigMode) {
  14542. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  14543. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  14544. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  14545. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  14546. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  14547. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  14548. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  14549. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  14550. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  14551. camLeft.setTarget(this.getTarget());
  14552. camRight.setTarget(this.getTarget());
  14553. break;
  14554. case BABYLON.Camera.RIG_MODE_VR:
  14555. case BABYLON.Camera.RIG_MODE_WEBVR:
  14556. if (camLeft.rotationQuaternion) {
  14557. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  14558. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  14559. }
  14560. else {
  14561. camLeft.rotation.copyFrom(this.rotation);
  14562. camRight.rotation.copyFrom(this.rotation);
  14563. }
  14564. camLeft.position.copyFrom(this.position);
  14565. camRight.position.copyFrom(this.position);
  14566. break;
  14567. }
  14568. _super.prototype._updateRigCameras.call(this);
  14569. };
  14570. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  14571. if (!this._rigCamTransformMatrix) {
  14572. this._rigCamTransformMatrix = new BABYLON.Matrix();
  14573. }
  14574. var target = this.getTarget();
  14575. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  14576. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  14577. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  14578. };
  14579. TargetCamera.prototype.getTypeName = function () {
  14580. return "TargetCamera";
  14581. };
  14582. __decorate([
  14583. BABYLON.serializeAsVector3()
  14584. ], TargetCamera.prototype, "rotation", void 0);
  14585. __decorate([
  14586. BABYLON.serialize()
  14587. ], TargetCamera.prototype, "speed", void 0);
  14588. __decorate([
  14589. BABYLON.serializeAsMeshReference("lockedTargetId")
  14590. ], TargetCamera.prototype, "lockedTarget", void 0);
  14591. return TargetCamera;
  14592. }(BABYLON.Camera));
  14593. BABYLON.TargetCamera = TargetCamera;
  14594. })(BABYLON || (BABYLON = {}));
  14595. var BABYLON;
  14596. (function (BABYLON) {
  14597. var FreeCamera = (function (_super) {
  14598. __extends(FreeCamera, _super);
  14599. function FreeCamera(name, position, scene) {
  14600. var _this = this;
  14601. _super.call(this, name, position, scene);
  14602. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  14603. this.checkCollisions = false;
  14604. this.applyGravity = false;
  14605. this._collider = new BABYLON.Collider();
  14606. this._needMoveForGravity = false;
  14607. this._oldPosition = BABYLON.Vector3.Zero();
  14608. this._diffPosition = BABYLON.Vector3.Zero();
  14609. this._newPosition = BABYLON.Vector3.Zero();
  14610. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  14611. if (collidedMesh === void 0) { collidedMesh = null; }
  14612. //TODO move this to the collision coordinator!
  14613. if (_this.getScene().workerCollisions)
  14614. newPosition.multiplyInPlace(_this._collider.radius);
  14615. var updatePosition = function (newPos) {
  14616. _this._newPosition.copyFrom(newPos);
  14617. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  14618. var oldPosition = _this.position.clone();
  14619. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  14620. _this.position.addInPlace(_this._diffPosition);
  14621. if (_this.onCollide && collidedMesh) {
  14622. _this.onCollide(collidedMesh);
  14623. }
  14624. }
  14625. };
  14626. updatePosition(newPosition);
  14627. };
  14628. this.inputs = new BABYLON.FreeCameraInputsManager(this);
  14629. this.inputs.addKeyboard().addMouse();
  14630. }
  14631. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  14632. //-- begin properties for backward compatibility for inputs
  14633. get: function () {
  14634. var mouse = this.inputs.attached["mouse"];
  14635. if (mouse)
  14636. return mouse.angularSensibility;
  14637. },
  14638. set: function (value) {
  14639. var mouse = this.inputs.attached["mouse"];
  14640. if (mouse)
  14641. mouse.angularSensibility = value;
  14642. },
  14643. enumerable: true,
  14644. configurable: true
  14645. });
  14646. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  14647. get: function () {
  14648. var keyboard = this.inputs.attached["keyboard"];
  14649. if (keyboard)
  14650. return keyboard.keysUp;
  14651. },
  14652. set: function (value) {
  14653. var keyboard = this.inputs.attached["keyboard"];
  14654. if (keyboard)
  14655. keyboard.keysUp = value;
  14656. },
  14657. enumerable: true,
  14658. configurable: true
  14659. });
  14660. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  14661. get: function () {
  14662. var keyboard = this.inputs.attached["keyboard"];
  14663. if (keyboard)
  14664. return keyboard.keysDown;
  14665. },
  14666. set: function (value) {
  14667. var keyboard = this.inputs.attached["keyboard"];
  14668. if (keyboard)
  14669. keyboard.keysDown = value;
  14670. },
  14671. enumerable: true,
  14672. configurable: true
  14673. });
  14674. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  14675. get: function () {
  14676. var keyboard = this.inputs.attached["keyboard"];
  14677. if (keyboard)
  14678. return keyboard.keysLeft;
  14679. },
  14680. set: function (value) {
  14681. var keyboard = this.inputs.attached["keyboard"];
  14682. if (keyboard)
  14683. keyboard.keysLeft = value;
  14684. },
  14685. enumerable: true,
  14686. configurable: true
  14687. });
  14688. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  14689. get: function () {
  14690. var keyboard = this.inputs.attached["keyboard"];
  14691. if (keyboard)
  14692. return keyboard.keysRight;
  14693. },
  14694. set: function (value) {
  14695. var keyboard = this.inputs.attached["keyboard"];
  14696. if (keyboard)
  14697. keyboard.keysRight = value;
  14698. },
  14699. enumerable: true,
  14700. configurable: true
  14701. });
  14702. // Controls
  14703. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  14704. this.inputs.attachElement(element, noPreventDefault);
  14705. };
  14706. FreeCamera.prototype.detachControl = function (element) {
  14707. this.inputs.detachElement(element);
  14708. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  14709. this.cameraRotation = new BABYLON.Vector2(0, 0);
  14710. };
  14711. FreeCamera.prototype._collideWithWorld = function (velocity) {
  14712. var globalPosition;
  14713. if (this.parent) {
  14714. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  14715. }
  14716. else {
  14717. globalPosition = this.position;
  14718. }
  14719. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  14720. this._collider.radius = this.ellipsoid;
  14721. //no need for clone, as long as gravity is not on.
  14722. var actualVelocity = velocity;
  14723. //add gravity to the velocity to prevent the dual-collision checking
  14724. if (this.applyGravity) {
  14725. //this prevents mending with cameraDirection, a global variable of the free camera class.
  14726. actualVelocity = velocity.add(this.getScene().gravity);
  14727. }
  14728. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  14729. };
  14730. FreeCamera.prototype._checkInputs = function () {
  14731. if (!this._localDirection) {
  14732. this._localDirection = BABYLON.Vector3.Zero();
  14733. this._transformedDirection = BABYLON.Vector3.Zero();
  14734. }
  14735. this.inputs.checkInputs();
  14736. _super.prototype._checkInputs.call(this);
  14737. };
  14738. FreeCamera.prototype._decideIfNeedsToMove = function () {
  14739. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  14740. };
  14741. FreeCamera.prototype._updatePosition = function () {
  14742. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  14743. this._collideWithWorld(this.cameraDirection);
  14744. }
  14745. else {
  14746. this.position.addInPlace(this.cameraDirection);
  14747. }
  14748. };
  14749. FreeCamera.prototype.dispose = function () {
  14750. this.inputs.clear();
  14751. _super.prototype.dispose.call(this);
  14752. };
  14753. FreeCamera.prototype.getTypeName = function () {
  14754. return "FreeCamera";
  14755. };
  14756. __decorate([
  14757. BABYLON.serializeAsVector3()
  14758. ], FreeCamera.prototype, "ellipsoid", void 0);
  14759. __decorate([
  14760. BABYLON.serialize()
  14761. ], FreeCamera.prototype, "checkCollisions", void 0);
  14762. __decorate([
  14763. BABYLON.serialize()
  14764. ], FreeCamera.prototype, "applyGravity", void 0);
  14765. return FreeCamera;
  14766. }(BABYLON.TargetCamera));
  14767. BABYLON.FreeCamera = FreeCamera;
  14768. })(BABYLON || (BABYLON = {}));
  14769. var BABYLON;
  14770. (function (BABYLON) {
  14771. var FreeCameraInputsManager = (function (_super) {
  14772. __extends(FreeCameraInputsManager, _super);
  14773. function FreeCameraInputsManager(camera) {
  14774. _super.call(this, camera);
  14775. }
  14776. FreeCameraInputsManager.prototype.addKeyboard = function () {
  14777. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  14778. return this;
  14779. };
  14780. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  14781. if (touchEnabled === void 0) { touchEnabled = true; }
  14782. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  14783. return this;
  14784. };
  14785. FreeCameraInputsManager.prototype.addGamepad = function () {
  14786. this.add(new BABYLON.FreeCameraGamepadInput());
  14787. return this;
  14788. };
  14789. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  14790. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  14791. return this;
  14792. };
  14793. FreeCameraInputsManager.prototype.addTouch = function () {
  14794. this.add(new BABYLON.FreeCameraTouchInput());
  14795. return this;
  14796. };
  14797. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  14798. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  14799. return this;
  14800. };
  14801. return FreeCameraInputsManager;
  14802. }(BABYLON.CameraInputsManager));
  14803. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  14804. })(BABYLON || (BABYLON = {}));
  14805. var BABYLON;
  14806. (function (BABYLON) {
  14807. var FollowCamera = (function (_super) {
  14808. __extends(FollowCamera, _super);
  14809. function FollowCamera(name, position, scene, target) {
  14810. _super.call(this, name, position, scene);
  14811. this.radius = 12;
  14812. this.rotationOffset = 0;
  14813. this.heightOffset = 4;
  14814. this.cameraAcceleration = 0.05;
  14815. this.maxCameraSpeed = 20;
  14816. this.target = target;
  14817. }
  14818. FollowCamera.prototype.getRadians = function (degrees) {
  14819. return degrees * Math.PI / 180;
  14820. };
  14821. FollowCamera.prototype.follow = function (cameraTarget) {
  14822. if (!cameraTarget)
  14823. return;
  14824. var yRotation;
  14825. if (cameraTarget.rotationQuaternion) {
  14826. var rotMatrix = new BABYLON.Matrix();
  14827. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  14828. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  14829. }
  14830. else {
  14831. yRotation = cameraTarget.rotation.y;
  14832. }
  14833. var radians = this.getRadians(this.rotationOffset) + yRotation;
  14834. var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
  14835. var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
  14836. var dx = targetX - this.position.x;
  14837. var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
  14838. var dz = (targetZ) - this.position.z;
  14839. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  14840. var vy = dy * this.cameraAcceleration;
  14841. var vz = dz * this.cameraAcceleration * 2;
  14842. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  14843. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  14844. }
  14845. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  14846. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  14847. }
  14848. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  14849. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  14850. }
  14851. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  14852. this.setTarget(cameraTarget.position);
  14853. };
  14854. FollowCamera.prototype._checkInputs = function () {
  14855. _super.prototype._checkInputs.call(this);
  14856. this.follow(this.target);
  14857. };
  14858. FollowCamera.prototype.getTypeName = function () {
  14859. return "FollowCamera";
  14860. };
  14861. __decorate([
  14862. BABYLON.serialize()
  14863. ], FollowCamera.prototype, "radius", void 0);
  14864. __decorate([
  14865. BABYLON.serialize()
  14866. ], FollowCamera.prototype, "rotationOffset", void 0);
  14867. __decorate([
  14868. BABYLON.serialize()
  14869. ], FollowCamera.prototype, "heightOffset", void 0);
  14870. __decorate([
  14871. BABYLON.serialize()
  14872. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  14873. __decorate([
  14874. BABYLON.serialize()
  14875. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  14876. __decorate([
  14877. BABYLON.serializeAsMeshReference("lockedTargetId")
  14878. ], FollowCamera.prototype, "target", void 0);
  14879. return FollowCamera;
  14880. }(BABYLON.TargetCamera));
  14881. BABYLON.FollowCamera = FollowCamera;
  14882. var ArcFollowCamera = (function (_super) {
  14883. __extends(ArcFollowCamera, _super);
  14884. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  14885. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  14886. this.alpha = alpha;
  14887. this.beta = beta;
  14888. this.radius = radius;
  14889. this.target = target;
  14890. this._cartesianCoordinates = BABYLON.Vector3.Zero();
  14891. this.follow();
  14892. }
  14893. ArcFollowCamera.prototype.follow = function () {
  14894. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  14895. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  14896. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  14897. this.position = this.target.position.add(this._cartesianCoordinates);
  14898. this.setTarget(this.target.position);
  14899. };
  14900. ArcFollowCamera.prototype._checkInputs = function () {
  14901. _super.prototype._checkInputs.call(this);
  14902. this.follow();
  14903. };
  14904. ArcFollowCamera.prototype.getTypeName = function () {
  14905. return "ArcFollowCamera";
  14906. };
  14907. return ArcFollowCamera;
  14908. }(BABYLON.TargetCamera));
  14909. BABYLON.ArcFollowCamera = ArcFollowCamera;
  14910. })(BABYLON || (BABYLON = {}));
  14911. var BABYLON;
  14912. (function (BABYLON) {
  14913. // We're mainly based on the logic defined into the FreeCamera code
  14914. var TouchCamera = (function (_super) {
  14915. __extends(TouchCamera, _super);
  14916. //-- end properties for backward compatibility for inputs
  14917. function TouchCamera(name, position, scene) {
  14918. _super.call(this, name, position, scene);
  14919. this.inputs.addTouch();
  14920. this._setupInputs();
  14921. }
  14922. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  14923. //-- Begin properties for backward compatibility for inputs
  14924. get: function () {
  14925. var touch = this.inputs.attached["touch"];
  14926. if (touch)
  14927. return touch.touchAngularSensibility;
  14928. },
  14929. set: function (value) {
  14930. var touch = this.inputs.attached["touch"];
  14931. if (touch)
  14932. touch.touchAngularSensibility = value;
  14933. },
  14934. enumerable: true,
  14935. configurable: true
  14936. });
  14937. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  14938. get: function () {
  14939. var touch = this.inputs.attached["touch"];
  14940. if (touch)
  14941. return touch.touchMoveSensibility;
  14942. },
  14943. set: function (value) {
  14944. var touch = this.inputs.attached["touch"];
  14945. if (touch)
  14946. touch.touchMoveSensibility = value;
  14947. },
  14948. enumerable: true,
  14949. configurable: true
  14950. });
  14951. TouchCamera.prototype.getTypeName = function () {
  14952. return "TouchCamera";
  14953. };
  14954. TouchCamera.prototype._setupInputs = function () {
  14955. var mouse = this.inputs.attached["mouse"];
  14956. if (mouse) {
  14957. mouse.touchEnabled = false;
  14958. }
  14959. };
  14960. return TouchCamera;
  14961. }(BABYLON.FreeCamera));
  14962. BABYLON.TouchCamera = TouchCamera;
  14963. })(BABYLON || (BABYLON = {}));
  14964. var BABYLON;
  14965. (function (BABYLON) {
  14966. var ArcRotateCamera = (function (_super) {
  14967. __extends(ArcRotateCamera, _super);
  14968. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  14969. var _this = this;
  14970. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  14971. this.inertialAlphaOffset = 0;
  14972. this.inertialBetaOffset = 0;
  14973. this.inertialRadiusOffset = 0;
  14974. this.lowerAlphaLimit = null;
  14975. this.upperAlphaLimit = null;
  14976. this.lowerBetaLimit = 0.01;
  14977. this.upperBetaLimit = Math.PI;
  14978. this.lowerRadiusLimit = null;
  14979. this.upperRadiusLimit = null;
  14980. this.inertialPanningX = 0;
  14981. this.inertialPanningY = 0;
  14982. //-- end properties for backward compatibility for inputs
  14983. this.zoomOnFactor = 1;
  14984. this.targetScreenOffset = BABYLON.Vector2.Zero();
  14985. this.allowUpsideDown = true;
  14986. this._viewMatrix = new BABYLON.Matrix();
  14987. // Panning
  14988. this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  14989. this.checkCollisions = false;
  14990. this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  14991. this._collider = new BABYLON.Collider();
  14992. this._previousPosition = BABYLON.Vector3.Zero();
  14993. this._collisionVelocity = BABYLON.Vector3.Zero();
  14994. this._newPosition = BABYLON.Vector3.Zero();
  14995. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  14996. if (collidedMesh === void 0) { collidedMesh = null; }
  14997. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  14998. newPosition.multiplyInPlace(_this._collider.radius);
  14999. }
  15000. if (!collidedMesh) {
  15001. _this._previousPosition.copyFrom(_this.position);
  15002. }
  15003. else {
  15004. _this.setPosition(newPosition);
  15005. if (_this.onCollide) {
  15006. _this.onCollide(collidedMesh);
  15007. }
  15008. }
  15009. // Recompute because of constraints
  15010. var cosa = Math.cos(_this.alpha);
  15011. var sina = Math.sin(_this.alpha);
  15012. var cosb = Math.cos(_this.beta);
  15013. var sinb = Math.sin(_this.beta);
  15014. if (sinb === 0) {
  15015. sinb = 0.0001;
  15016. }
  15017. var target = _this._getTargetPosition();
  15018. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  15019. _this.position.copyFrom(_this._newPosition);
  15020. var up = _this.upVector;
  15021. if (_this.allowUpsideDown && _this.beta < 0) {
  15022. up = up.clone();
  15023. up = up.negate();
  15024. }
  15025. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  15026. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  15027. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  15028. _this._collisionTriggered = false;
  15029. };
  15030. if (!target) {
  15031. this.target = BABYLON.Vector3.Zero();
  15032. }
  15033. else {
  15034. this.target = target;
  15035. }
  15036. this.alpha = alpha;
  15037. this.beta = beta;
  15038. this.radius = radius;
  15039. this.getViewMatrix();
  15040. this.inputs = new BABYLON.ArcRotateCameraInputsManager(this);
  15041. this.inputs.addKeyboard().addMouseWheel().addPointers().addGamepad();
  15042. }
  15043. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  15044. //-- begin properties for backward compatibility for inputs
  15045. get: function () {
  15046. var pointers = this.inputs.attached["pointers"];
  15047. if (pointers)
  15048. return pointers.angularSensibilityX;
  15049. },
  15050. set: function (value) {
  15051. var pointers = this.inputs.attached["pointers"];
  15052. if (pointers) {
  15053. pointers.angularSensibilityX = value;
  15054. }
  15055. },
  15056. enumerable: true,
  15057. configurable: true
  15058. });
  15059. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  15060. get: function () {
  15061. var pointers = this.inputs.attached["pointers"];
  15062. if (pointers)
  15063. return pointers.angularSensibilityY;
  15064. },
  15065. set: function (value) {
  15066. var pointers = this.inputs.attached["pointers"];
  15067. if (pointers) {
  15068. pointers.angularSensibilityY = value;
  15069. }
  15070. },
  15071. enumerable: true,
  15072. configurable: true
  15073. });
  15074. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  15075. get: function () {
  15076. var pointers = this.inputs.attached["pointers"];
  15077. if (pointers)
  15078. return pointers.pinchPrecision;
  15079. },
  15080. set: function (value) {
  15081. var pointers = this.inputs.attached["pointers"];
  15082. if (pointers) {
  15083. pointers.pinchPrecision = value;
  15084. }
  15085. },
  15086. enumerable: true,
  15087. configurable: true
  15088. });
  15089. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  15090. get: function () {
  15091. var pointers = this.inputs.attached["pointers"];
  15092. if (pointers)
  15093. return pointers.panningSensibility;
  15094. },
  15095. set: function (value) {
  15096. var pointers = this.inputs.attached["pointers"];
  15097. if (pointers) {
  15098. pointers.panningSensibility = value;
  15099. }
  15100. },
  15101. enumerable: true,
  15102. configurable: true
  15103. });
  15104. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  15105. get: function () {
  15106. var keyboard = this.inputs.attached["keyboard"];
  15107. if (keyboard)
  15108. return keyboard.keysUp;
  15109. },
  15110. set: function (value) {
  15111. var keyboard = this.inputs.attached["keyboard"];
  15112. if (keyboard)
  15113. keyboard.keysUp = value;
  15114. },
  15115. enumerable: true,
  15116. configurable: true
  15117. });
  15118. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  15119. get: function () {
  15120. var keyboard = this.inputs.attached["keyboard"];
  15121. if (keyboard)
  15122. return keyboard.keysDown;
  15123. },
  15124. set: function (value) {
  15125. var keyboard = this.inputs.attached["keyboard"];
  15126. if (keyboard)
  15127. keyboard.keysDown = value;
  15128. },
  15129. enumerable: true,
  15130. configurable: true
  15131. });
  15132. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  15133. get: function () {
  15134. var keyboard = this.inputs.attached["keyboard"];
  15135. if (keyboard)
  15136. return keyboard.keysLeft;
  15137. },
  15138. set: function (value) {
  15139. var keyboard = this.inputs.attached["keyboard"];
  15140. if (keyboard)
  15141. keyboard.keysLeft = value;
  15142. },
  15143. enumerable: true,
  15144. configurable: true
  15145. });
  15146. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  15147. get: function () {
  15148. var keyboard = this.inputs.attached["keyboard"];
  15149. if (keyboard)
  15150. return keyboard.keysRight;
  15151. },
  15152. set: function (value) {
  15153. var keyboard = this.inputs.attached["keyboard"];
  15154. if (keyboard)
  15155. keyboard.keysRight = value;
  15156. },
  15157. enumerable: true,
  15158. configurable: true
  15159. });
  15160. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  15161. get: function () {
  15162. var mousewheel = this.inputs.attached["mousewheel"];
  15163. if (mousewheel)
  15164. return mousewheel.wheelPrecision;
  15165. },
  15166. set: function (value) {
  15167. var mousewheel = this.inputs.attached["mousewheel"];
  15168. if (mousewheel)
  15169. mousewheel.wheelPrecision = value;
  15170. },
  15171. enumerable: true,
  15172. configurable: true
  15173. });
  15174. // Cache
  15175. ArcRotateCamera.prototype._initCache = function () {
  15176. _super.prototype._initCache.call(this);
  15177. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  15178. this._cache.alpha = undefined;
  15179. this._cache.beta = undefined;
  15180. this._cache.radius = undefined;
  15181. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  15182. };
  15183. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  15184. if (!ignoreParentClass) {
  15185. _super.prototype._updateCache.call(this);
  15186. }
  15187. this._cache.target.copyFrom(this._getTargetPosition());
  15188. this._cache.alpha = this.alpha;
  15189. this._cache.beta = this.beta;
  15190. this._cache.radius = this.radius;
  15191. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  15192. };
  15193. ArcRotateCamera.prototype._getTargetPosition = function () {
  15194. if (this.target.getAbsolutePosition) {
  15195. var pos = this.target.getAbsolutePosition();
  15196. return this._targetBoundingCenter ? pos.add(this._targetBoundingCenter) : pos;
  15197. }
  15198. return this.target;
  15199. };
  15200. // Synchronized
  15201. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  15202. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  15203. return false;
  15204. return this._cache.target.equals(this.target)
  15205. && this._cache.alpha === this.alpha
  15206. && this._cache.beta === this.beta
  15207. && this._cache.radius === this.radius
  15208. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  15209. };
  15210. // Methods
  15211. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  15212. var _this = this;
  15213. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  15214. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  15215. this._useCtrlForPanning = useCtrlForPanning;
  15216. this._panningMouseButton = panningMouseButton;
  15217. this.inputs.attachElement(element, noPreventDefault);
  15218. this._reset = function () {
  15219. _this.inertialAlphaOffset = 0;
  15220. _this.inertialBetaOffset = 0;
  15221. _this.inertialRadiusOffset = 0;
  15222. };
  15223. };
  15224. ArcRotateCamera.prototype.detachControl = function (element) {
  15225. this.inputs.detachElement(element);
  15226. if (this._reset) {
  15227. this._reset();
  15228. }
  15229. };
  15230. ArcRotateCamera.prototype._checkInputs = function () {
  15231. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  15232. if (this._collisionTriggered) {
  15233. return;
  15234. }
  15235. this.inputs.checkInputs();
  15236. // Inertia
  15237. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  15238. this.beta += this.inertialBetaOffset;
  15239. if (this.getScene().useRightHandedSystem) {
  15240. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  15241. }
  15242. else {
  15243. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  15244. }
  15245. this.radius -= this.inertialRadiusOffset;
  15246. this.inertialAlphaOffset *= this.inertia;
  15247. this.inertialBetaOffset *= this.inertia;
  15248. this.inertialRadiusOffset *= this.inertia;
  15249. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  15250. this.inertialAlphaOffset = 0;
  15251. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  15252. this.inertialBetaOffset = 0;
  15253. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Epsilon)
  15254. this.inertialRadiusOffset = 0;
  15255. }
  15256. // Panning inertia
  15257. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  15258. if (!this._localDirection) {
  15259. this._localDirection = BABYLON.Vector3.Zero();
  15260. this._transformedDirection = BABYLON.Vector3.Zero();
  15261. }
  15262. this.inertialPanningX *= this.inertia;
  15263. this.inertialPanningY *= this.inertia;
  15264. if (Math.abs(this.inertialPanningX) < BABYLON.Epsilon)
  15265. this.inertialPanningX = 0;
  15266. if (Math.abs(this.inertialPanningY) < BABYLON.Epsilon)
  15267. this.inertialPanningY = 0;
  15268. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  15269. this._localDirection.multiplyInPlace(this.panningAxis);
  15270. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  15271. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  15272. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  15273. if (!this.panningAxis.y) {
  15274. this._transformedDirection.y = 0;
  15275. }
  15276. if (!this.target.getAbsolutePosition) {
  15277. this.target.addInPlace(this._transformedDirection);
  15278. }
  15279. }
  15280. // Limits
  15281. this._checkLimits();
  15282. _super.prototype._checkInputs.call(this);
  15283. };
  15284. ArcRotateCamera.prototype._checkLimits = function () {
  15285. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  15286. if (this.allowUpsideDown && this.beta > Math.PI) {
  15287. this.beta = this.beta - (2 * Math.PI);
  15288. }
  15289. }
  15290. else {
  15291. if (this.beta < this.lowerBetaLimit) {
  15292. this.beta = this.lowerBetaLimit;
  15293. }
  15294. }
  15295. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  15296. if (this.allowUpsideDown && this.beta < -Math.PI) {
  15297. this.beta = this.beta + (2 * Math.PI);
  15298. }
  15299. }
  15300. else {
  15301. if (this.beta > this.upperBetaLimit) {
  15302. this.beta = this.upperBetaLimit;
  15303. }
  15304. }
  15305. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  15306. this.alpha = this.lowerAlphaLimit;
  15307. }
  15308. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  15309. this.alpha = this.upperAlphaLimit;
  15310. }
  15311. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  15312. this.radius = this.lowerRadiusLimit;
  15313. }
  15314. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  15315. this.radius = this.upperRadiusLimit;
  15316. }
  15317. };
  15318. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  15319. var radiusv3 = this.position.subtract(this._getTargetPosition());
  15320. this.radius = radiusv3.length();
  15321. // Alpha
  15322. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  15323. if (radiusv3.z < 0) {
  15324. this.alpha = 2 * Math.PI - this.alpha;
  15325. }
  15326. // Beta
  15327. this.beta = Math.acos(radiusv3.y / this.radius);
  15328. this._checkLimits();
  15329. };
  15330. ArcRotateCamera.prototype.setPosition = function (position) {
  15331. if (this.position.equals(position)) {
  15332. return;
  15333. }
  15334. this.position.copyFrom(position);
  15335. this.rebuildAnglesAndRadius();
  15336. };
  15337. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter) {
  15338. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  15339. if (this._getTargetPosition().equals(target)) {
  15340. return;
  15341. }
  15342. if (toBoundingCenter && target.getBoundingInfo) {
  15343. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.center.clone();
  15344. }
  15345. else {
  15346. this._targetBoundingCenter = null;
  15347. }
  15348. this.target = target;
  15349. this.rebuildAnglesAndRadius();
  15350. };
  15351. ArcRotateCamera.prototype._getViewMatrix = function () {
  15352. // Compute
  15353. var cosa = Math.cos(this.alpha);
  15354. var sina = Math.sin(this.alpha);
  15355. var cosb = Math.cos(this.beta);
  15356. var sinb = Math.sin(this.beta);
  15357. if (sinb === 0) {
  15358. sinb = 0.0001;
  15359. }
  15360. var target = this._getTargetPosition();
  15361. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  15362. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  15363. this._collider.radius = this.collisionRadius;
  15364. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  15365. this._collisionTriggered = true;
  15366. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  15367. }
  15368. else {
  15369. this.position.copyFrom(this._newPosition);
  15370. var up = this.upVector;
  15371. if (this.allowUpsideDown && this.beta < 0) {
  15372. up = up.clone();
  15373. up = up.negate();
  15374. }
  15375. if (this.getScene().useRightHandedSystem) {
  15376. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  15377. }
  15378. else {
  15379. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  15380. }
  15381. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  15382. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  15383. }
  15384. return this._viewMatrix;
  15385. };
  15386. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  15387. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  15388. meshes = meshes || this.getScene().meshes;
  15389. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  15390. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  15391. this.radius = distance * this.zoomOnFactor;
  15392. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  15393. };
  15394. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  15395. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  15396. var meshesOrMinMaxVector;
  15397. var distance;
  15398. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  15399. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  15400. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  15401. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  15402. }
  15403. else {
  15404. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  15405. distance = meshesOrMinMaxVectorAndDistance.distance;
  15406. }
  15407. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  15408. if (!doNotUpdateMaxZ) {
  15409. this.maxZ = distance * 2;
  15410. }
  15411. };
  15412. /**
  15413. * @override
  15414. * Override Camera.createRigCamera
  15415. */
  15416. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  15417. var alphaShift;
  15418. switch (this.cameraRigMode) {
  15419. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  15420. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  15421. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  15422. case BABYLON.Camera.RIG_MODE_VR:
  15423. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  15424. break;
  15425. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  15426. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  15427. break;
  15428. }
  15429. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this.target, this.getScene());
  15430. rigCam._cameraRigParams = {};
  15431. return rigCam;
  15432. };
  15433. /**
  15434. * @override
  15435. * Override Camera._updateRigCameras
  15436. */
  15437. ArcRotateCamera.prototype._updateRigCameras = function () {
  15438. var camLeft = this._rigCameras[0];
  15439. var camRight = this._rigCameras[1];
  15440. camLeft.beta = camRight.beta = this.beta;
  15441. camLeft.radius = camRight.radius = this.radius;
  15442. switch (this.cameraRigMode) {
  15443. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  15444. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  15445. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  15446. case BABYLON.Camera.RIG_MODE_VR:
  15447. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  15448. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  15449. break;
  15450. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  15451. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  15452. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  15453. break;
  15454. }
  15455. _super.prototype._updateRigCameras.call(this);
  15456. };
  15457. ArcRotateCamera.prototype.dispose = function () {
  15458. this.inputs.clear();
  15459. _super.prototype.dispose.call(this);
  15460. };
  15461. ArcRotateCamera.prototype.getTypeName = function () {
  15462. return "ArcRotateCamera";
  15463. };
  15464. __decorate([
  15465. BABYLON.serialize()
  15466. ], ArcRotateCamera.prototype, "alpha", void 0);
  15467. __decorate([
  15468. BABYLON.serialize()
  15469. ], ArcRotateCamera.prototype, "beta", void 0);
  15470. __decorate([
  15471. BABYLON.serialize()
  15472. ], ArcRotateCamera.prototype, "radius", void 0);
  15473. __decorate([
  15474. BABYLON.serializeAsVector3()
  15475. ], ArcRotateCamera.prototype, "target", void 0);
  15476. __decorate([
  15477. BABYLON.serialize()
  15478. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  15479. __decorate([
  15480. BABYLON.serialize()
  15481. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  15482. __decorate([
  15483. BABYLON.serialize()
  15484. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  15485. __decorate([
  15486. BABYLON.serialize()
  15487. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  15488. __decorate([
  15489. BABYLON.serialize()
  15490. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  15491. __decorate([
  15492. BABYLON.serialize()
  15493. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  15494. __decorate([
  15495. BABYLON.serialize()
  15496. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  15497. __decorate([
  15498. BABYLON.serialize()
  15499. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  15500. __decorate([
  15501. BABYLON.serialize()
  15502. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  15503. __decorate([
  15504. BABYLON.serialize()
  15505. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  15506. __decorate([
  15507. BABYLON.serialize()
  15508. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  15509. __decorate([
  15510. BABYLON.serialize()
  15511. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  15512. __decorate([
  15513. BABYLON.serialize()
  15514. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  15515. return ArcRotateCamera;
  15516. }(BABYLON.TargetCamera));
  15517. BABYLON.ArcRotateCamera = ArcRotateCamera;
  15518. })(BABYLON || (BABYLON = {}));
  15519. var BABYLON;
  15520. (function (BABYLON) {
  15521. var ArcRotateCameraInputsManager = (function (_super) {
  15522. __extends(ArcRotateCameraInputsManager, _super);
  15523. function ArcRotateCameraInputsManager(camera) {
  15524. _super.call(this, camera);
  15525. }
  15526. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  15527. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  15528. return this;
  15529. };
  15530. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  15531. this.add(new BABYLON.ArcRotateCameraPointersInput());
  15532. return this;
  15533. };
  15534. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  15535. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  15536. return this;
  15537. };
  15538. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  15539. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  15540. return this;
  15541. };
  15542. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  15543. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  15544. return this;
  15545. };
  15546. return ArcRotateCameraInputsManager;
  15547. }(BABYLON.CameraInputsManager));
  15548. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  15549. })(BABYLON || (BABYLON = {}));
  15550. var BABYLON;
  15551. (function (BABYLON) {
  15552. var RenderingManager = (function () {
  15553. function RenderingManager(scene) {
  15554. this._renderingGroups = new Array();
  15555. this._autoClearDepthStencil = {};
  15556. this._customOpaqueSortCompareFn = {};
  15557. this._customAlphaTestSortCompareFn = {};
  15558. this._customTransparentSortCompareFn = {};
  15559. this._scene = scene;
  15560. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  15561. this._autoClearDepthStencil[i] = true;
  15562. }
  15563. }
  15564. RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
  15565. if (this._scene._activeParticleSystems.length === 0) {
  15566. return;
  15567. }
  15568. // Particles
  15569. var activeCamera = this._scene.activeCamera;
  15570. this._scene._particlesDuration.beginMonitoring();
  15571. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  15572. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  15573. if (particleSystem.renderingGroupId !== index) {
  15574. continue;
  15575. }
  15576. if ((activeCamera.layerMask & particleSystem.layerMask) === 0) {
  15577. continue;
  15578. }
  15579. this._clearDepthStencilBuffer();
  15580. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  15581. this._scene._activeParticles.addCount(particleSystem.render(), false);
  15582. }
  15583. }
  15584. this._scene._particlesDuration.endMonitoring(false);
  15585. };
  15586. RenderingManager.prototype._renderSprites = function (index) {
  15587. if (!this._scene.spritesEnabled || this._scene.spriteManagers.length === 0) {
  15588. return;
  15589. }
  15590. // Sprites
  15591. var activeCamera = this._scene.activeCamera;
  15592. this._scene._spritesDuration.beginMonitoring();
  15593. for (var id = 0; id < this._scene.spriteManagers.length; id++) {
  15594. var spriteManager = this._scene.spriteManagers[id];
  15595. if (spriteManager.renderingGroupId === index && ((activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  15596. this._clearDepthStencilBuffer();
  15597. spriteManager.render();
  15598. }
  15599. }
  15600. this._scene._spritesDuration.endMonitoring(false);
  15601. };
  15602. RenderingManager.prototype._clearDepthStencilBuffer = function () {
  15603. if (this._depthStencilBufferAlreadyCleaned) {
  15604. return;
  15605. }
  15606. this._scene.getEngine().clear(0, false, true, true);
  15607. this._depthStencilBufferAlreadyCleaned = true;
  15608. };
  15609. RenderingManager.prototype._renderSpritesAndParticles = function () {
  15610. if (this._currentRenderSprites) {
  15611. this._renderSprites(this._currentIndex);
  15612. }
  15613. if (this._currentRenderParticles) {
  15614. this._renderParticles(this._currentIndex, this._currentActiveMeshes);
  15615. }
  15616. };
  15617. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  15618. this._currentActiveMeshes = activeMeshes;
  15619. this._currentRenderParticles = renderParticles;
  15620. this._currentRenderSprites = renderSprites;
  15621. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  15622. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  15623. var renderingGroup = this._renderingGroups[index];
  15624. var needToStepBack = false;
  15625. this._currentIndex = index;
  15626. if (renderingGroup) {
  15627. if (this._autoClearDepthStencil[index]) {
  15628. this._clearDepthStencilBuffer();
  15629. }
  15630. if (!renderingGroup.onBeforeTransparentRendering) {
  15631. renderingGroup.onBeforeTransparentRendering = this._renderSpritesAndParticles.bind(this);
  15632. }
  15633. if (!renderingGroup.render(customRenderFunction)) {
  15634. this._renderingGroups.splice(index, 1);
  15635. needToStepBack = true;
  15636. this._renderSpritesAndParticles();
  15637. }
  15638. }
  15639. else {
  15640. this._renderSpritesAndParticles();
  15641. }
  15642. if (needToStepBack) {
  15643. index--;
  15644. }
  15645. }
  15646. };
  15647. RenderingManager.prototype.reset = function () {
  15648. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  15649. var renderingGroup = this._renderingGroups[index];
  15650. if (renderingGroup) {
  15651. renderingGroup.prepare();
  15652. }
  15653. }
  15654. };
  15655. RenderingManager.prototype.dispatch = function (subMesh) {
  15656. var mesh = subMesh.getMesh();
  15657. var renderingGroupId = mesh.renderingGroupId || 0;
  15658. if (!this._renderingGroups[renderingGroupId]) {
  15659. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  15660. }
  15661. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  15662. };
  15663. /**
  15664. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  15665. * This allowed control for front to back rendering or reversly depending of the special needs.
  15666. *
  15667. * @param renderingGroupId The rendering group id corresponding to its index
  15668. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  15669. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  15670. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  15671. */
  15672. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  15673. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  15674. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  15675. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  15676. if (this._renderingGroups[renderingGroupId]) {
  15677. var group = this._renderingGroups[renderingGroupId];
  15678. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  15679. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  15680. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  15681. }
  15682. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  15683. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  15684. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  15685. };
  15686. /**
  15687. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  15688. *
  15689. * @param renderingGroupId The rendering group id corresponding to its index
  15690. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  15691. */
  15692. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  15693. this._autoClearDepthStencil[renderingGroupId] = autoClearDepthStencil;
  15694. };
  15695. /**
  15696. * The max id used for rendering groups (not included)
  15697. */
  15698. RenderingManager.MAX_RENDERINGGROUPS = 4;
  15699. /**
  15700. * The min id used for rendering groups (included)
  15701. */
  15702. RenderingManager.MIN_RENDERINGGROUPS = 0;
  15703. return RenderingManager;
  15704. }());
  15705. BABYLON.RenderingManager = RenderingManager;
  15706. })(BABYLON || (BABYLON = {}));
  15707. var BABYLON;
  15708. (function (BABYLON) {
  15709. var RenderingGroup = (function () {
  15710. /**
  15711. * Creates a new rendering group.
  15712. * @param index The rendering group index
  15713. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  15714. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  15715. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  15716. */
  15717. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  15718. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  15719. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  15720. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  15721. this.index = index;
  15722. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  15723. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  15724. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  15725. this._scene = scene;
  15726. this.opaqueSortCompareFn = opaqueSortCompareFn;
  15727. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  15728. this.transparentSortCompareFn = transparentSortCompareFn;
  15729. }
  15730. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  15731. /**
  15732. * Set the opaque sort comparison function.
  15733. * If null the sub meshes will be render in the order they were created
  15734. */
  15735. set: function (value) {
  15736. this._opaqueSortCompareFn = value;
  15737. if (value) {
  15738. this._renderOpaque = this.renderOpaqueSorted;
  15739. }
  15740. else {
  15741. this._renderOpaque = RenderingGroup.renderUnsorted;
  15742. }
  15743. },
  15744. enumerable: true,
  15745. configurable: true
  15746. });
  15747. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  15748. /**
  15749. * Set the alpha test sort comparison function.
  15750. * If null the sub meshes will be render in the order they were created
  15751. */
  15752. set: function (value) {
  15753. this._alphaTestSortCompareFn = value;
  15754. if (value) {
  15755. this._renderAlphaTest = this.renderAlphaTestSorted;
  15756. }
  15757. else {
  15758. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  15759. }
  15760. },
  15761. enumerable: true,
  15762. configurable: true
  15763. });
  15764. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  15765. /**
  15766. * Set the transparent sort comparison function.
  15767. * If null the sub meshes will be render in the order they were created
  15768. */
  15769. set: function (value) {
  15770. if (value) {
  15771. this._transparentSortCompareFn = value;
  15772. }
  15773. else {
  15774. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  15775. }
  15776. this._renderTransparent = this.renderTransparentSorted;
  15777. },
  15778. enumerable: true,
  15779. configurable: true
  15780. });
  15781. /**
  15782. * Render all the sub meshes contained in the group.
  15783. * @param customRenderFunction Used to override the default render behaviour of the group.
  15784. * @returns true if rendered some submeshes.
  15785. */
  15786. RenderingGroup.prototype.render = function (customRenderFunction) {
  15787. if (customRenderFunction) {
  15788. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  15789. return true;
  15790. }
  15791. if (this._opaqueSubMeshes.length === 0 && this._alphaTestSubMeshes.length === 0 && this._transparentSubMeshes.length === 0) {
  15792. if (this.onBeforeTransparentRendering) {
  15793. this.onBeforeTransparentRendering();
  15794. }
  15795. return false;
  15796. }
  15797. var engine = this._scene.getEngine();
  15798. // Opaque
  15799. this._renderOpaque(this._opaqueSubMeshes);
  15800. // Alpha test
  15801. engine.setAlphaTesting(true);
  15802. this._renderAlphaTest(this._alphaTestSubMeshes);
  15803. engine.setAlphaTesting(false);
  15804. if (this.onBeforeTransparentRendering) {
  15805. this.onBeforeTransparentRendering();
  15806. }
  15807. // Transparent
  15808. this._renderTransparent(this._transparentSubMeshes);
  15809. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  15810. return true;
  15811. };
  15812. /**
  15813. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  15814. * @param subMeshes The submeshes to render
  15815. */
  15816. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  15817. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera.globalPosition, false);
  15818. };
  15819. /**
  15820. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  15821. * @param subMeshes The submeshes to render
  15822. */
  15823. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  15824. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera.globalPosition, false);
  15825. };
  15826. /**
  15827. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  15828. * @param subMeshes The submeshes to render
  15829. */
  15830. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  15831. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera.globalPosition, true);
  15832. };
  15833. /**
  15834. * Renders the submeshes in a specified order.
  15835. * @param subMeshes The submeshes to sort before render
  15836. * @param sortCompareFn The comparison function use to sort
  15837. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  15838. * @param transparent Specifies to activate blending if true
  15839. */
  15840. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, cameraPosition, transparent) {
  15841. var subIndex = 0;
  15842. var subMesh;
  15843. for (; subIndex < subMeshes.length; subIndex++) {
  15844. subMesh = subMeshes.data[subIndex];
  15845. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  15846. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  15847. }
  15848. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  15849. sortedArray.sort(sortCompareFn);
  15850. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  15851. subMesh = sortedArray[subIndex];
  15852. subMesh.render(transparent);
  15853. }
  15854. };
  15855. /**
  15856. * Renders the submeshes in the order they were dispatched (no sort applied).
  15857. * @param subMeshes The submeshes to render
  15858. */
  15859. RenderingGroup.renderUnsorted = function (subMeshes) {
  15860. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  15861. var submesh = subMeshes.data[subIndex];
  15862. submesh.render(false);
  15863. }
  15864. };
  15865. /**
  15866. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  15867. * are rendered back to front if in the same alpha index.
  15868. *
  15869. * @param a The first submesh
  15870. * @param b The second submesh
  15871. * @returns The result of the comparison
  15872. */
  15873. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  15874. // Alpha index first
  15875. if (a._alphaIndex > b._alphaIndex) {
  15876. return 1;
  15877. }
  15878. if (a._alphaIndex < b._alphaIndex) {
  15879. return -1;
  15880. }
  15881. // Then distance to camera
  15882. return RenderingGroup.backToFrontSortCompare(a, b);
  15883. };
  15884. /**
  15885. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  15886. * are rendered back to front.
  15887. *
  15888. * @param a The first submesh
  15889. * @param b The second submesh
  15890. * @returns The result of the comparison
  15891. */
  15892. RenderingGroup.backToFrontSortCompare = function (a, b) {
  15893. // Then distance to camera
  15894. if (a._distanceToCamera < b._distanceToCamera) {
  15895. return 1;
  15896. }
  15897. if (a._distanceToCamera > b._distanceToCamera) {
  15898. return -1;
  15899. }
  15900. return 0;
  15901. };
  15902. /**
  15903. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  15904. * are rendered front to back (prevent overdraw).
  15905. *
  15906. * @param a The first submesh
  15907. * @param b The second submesh
  15908. * @returns The result of the comparison
  15909. */
  15910. RenderingGroup.frontToBackSortCompare = function (a, b) {
  15911. // Then distance to camera
  15912. if (a._distanceToCamera < b._distanceToCamera) {
  15913. return -1;
  15914. }
  15915. if (a._distanceToCamera > b._distanceToCamera) {
  15916. return 1;
  15917. }
  15918. return 0;
  15919. };
  15920. /**
  15921. * Resets the different lists of submeshes to prepare a new frame.
  15922. */
  15923. RenderingGroup.prototype.prepare = function () {
  15924. this._opaqueSubMeshes.reset();
  15925. this._transparentSubMeshes.reset();
  15926. this._alphaTestSubMeshes.reset();
  15927. };
  15928. /**
  15929. * Inserts the submesh in its correct queue depending on its material.
  15930. * @param subMesh The submesh to dispatch
  15931. */
  15932. RenderingGroup.prototype.dispatch = function (subMesh) {
  15933. var material = subMesh.getMaterial();
  15934. var mesh = subMesh.getMesh();
  15935. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  15936. this._transparentSubMeshes.push(subMesh);
  15937. }
  15938. else if (material.needAlphaTesting()) {
  15939. this._alphaTestSubMeshes.push(subMesh);
  15940. }
  15941. else {
  15942. this._opaqueSubMeshes.push(subMesh); // Opaque
  15943. }
  15944. };
  15945. return RenderingGroup;
  15946. }());
  15947. BABYLON.RenderingGroup = RenderingGroup;
  15948. })(BABYLON || (BABYLON = {}));
  15949. var BABYLON;
  15950. (function (BABYLON) {
  15951. var PointerEventTypes = (function () {
  15952. function PointerEventTypes() {
  15953. }
  15954. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  15955. get: function () {
  15956. return PointerEventTypes._POINTERDOWN;
  15957. },
  15958. enumerable: true,
  15959. configurable: true
  15960. });
  15961. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  15962. get: function () {
  15963. return PointerEventTypes._POINTERUP;
  15964. },
  15965. enumerable: true,
  15966. configurable: true
  15967. });
  15968. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  15969. get: function () {
  15970. return PointerEventTypes._POINTERMOVE;
  15971. },
  15972. enumerable: true,
  15973. configurable: true
  15974. });
  15975. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  15976. get: function () {
  15977. return PointerEventTypes._POINTERWHEEL;
  15978. },
  15979. enumerable: true,
  15980. configurable: true
  15981. });
  15982. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  15983. get: function () {
  15984. return PointerEventTypes._POINTERPICK;
  15985. },
  15986. enumerable: true,
  15987. configurable: true
  15988. });
  15989. PointerEventTypes._POINTERDOWN = 0x01;
  15990. PointerEventTypes._POINTERUP = 0x02;
  15991. PointerEventTypes._POINTERMOVE = 0x04;
  15992. PointerEventTypes._POINTERWHEEL = 0x08;
  15993. PointerEventTypes._POINTERPICK = 0x10;
  15994. return PointerEventTypes;
  15995. }());
  15996. BABYLON.PointerEventTypes = PointerEventTypes;
  15997. var PointerInfoBase = (function () {
  15998. function PointerInfoBase(type, event) {
  15999. this.type = type;
  16000. this.event = event;
  16001. }
  16002. return PointerInfoBase;
  16003. }());
  16004. BABYLON.PointerInfoBase = PointerInfoBase;
  16005. /**
  16006. * This class is used to store pointer related info for the onPrePointerObservable event.
  16007. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  16008. */
  16009. var PointerInfoPre = (function (_super) {
  16010. __extends(PointerInfoPre, _super);
  16011. function PointerInfoPre(type, event, localX, localY) {
  16012. _super.call(this, type, event);
  16013. this.skipOnPointerObservable = false;
  16014. this.localPosition = new BABYLON.Vector2(localX, localY);
  16015. }
  16016. return PointerInfoPre;
  16017. }(PointerInfoBase));
  16018. BABYLON.PointerInfoPre = PointerInfoPre;
  16019. /**
  16020. * This type contains all the data related to a pointer event in Babylon.js.
  16021. * 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.
  16022. */
  16023. var PointerInfo = (function (_super) {
  16024. __extends(PointerInfo, _super);
  16025. function PointerInfo(type, event, pickInfo) {
  16026. _super.call(this, type, event);
  16027. this.pickInfo = pickInfo;
  16028. }
  16029. return PointerInfo;
  16030. }(PointerInfoBase));
  16031. BABYLON.PointerInfo = PointerInfo;
  16032. /**
  16033. * Represents a scene to be rendered by the engine.
  16034. * @see http://doc.babylonjs.com/page.php?p=21911
  16035. */
  16036. var Scene = (function () {
  16037. /**
  16038. * @constructor
  16039. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  16040. */
  16041. function Scene(engine) {
  16042. // Members
  16043. this.autoClear = true;
  16044. this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  16045. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  16046. this.forceWireframe = false;
  16047. this.forcePointsCloud = false;
  16048. this.forceShowBoundingBoxes = false;
  16049. this.animationsEnabled = true;
  16050. this.constantlyUpdateMeshUnderPointer = false;
  16051. this.useRightHandedSystem = false;
  16052. this.hoverCursor = "pointer";
  16053. // Events
  16054. /**
  16055. * An event triggered when the scene is disposed.
  16056. * @type {BABYLON.Observable}
  16057. */
  16058. this.onDisposeObservable = new BABYLON.Observable();
  16059. /**
  16060. * An event triggered before rendering the scene
  16061. * @type {BABYLON.Observable}
  16062. */
  16063. this.onBeforeRenderObservable = new BABYLON.Observable();
  16064. /**
  16065. * An event triggered after rendering the scene
  16066. * @type {BABYLON.Observable}
  16067. */
  16068. this.onAfterRenderObservable = new BABYLON.Observable();
  16069. /**
  16070. * An event triggered when the scene is ready
  16071. * @type {BABYLON.Observable}
  16072. */
  16073. this.onReadyObservable = new BABYLON.Observable();
  16074. /**
  16075. * An event triggered before rendering a camera
  16076. * @type {BABYLON.Observable}
  16077. */
  16078. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  16079. /**
  16080. * An event triggered after rendering a camera
  16081. * @type {BABYLON.Observable}
  16082. */
  16083. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  16084. /**
  16085. * An event triggered when a camera is created
  16086. * @type {BABYLON.Observable}
  16087. */
  16088. this.onNewCameraAddedObservable = new BABYLON.Observable();
  16089. /**
  16090. * An event triggered when a camera is removed
  16091. * @type {BABYLON.Observable}
  16092. */
  16093. this.onCameraRemovedObservable = new BABYLON.Observable();
  16094. /**
  16095. * An event triggered when a light is created
  16096. * @type {BABYLON.Observable}
  16097. */
  16098. this.onNewLightAddedObservable = new BABYLON.Observable();
  16099. /**
  16100. * An event triggered when a light is removed
  16101. * @type {BABYLON.Observable}
  16102. */
  16103. this.onLightRemovedObservable = new BABYLON.Observable();
  16104. /**
  16105. * An event triggered when a geometry is created
  16106. * @type {BABYLON.Observable}
  16107. */
  16108. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  16109. /**
  16110. * An event triggered when a geometry is removed
  16111. * @type {BABYLON.Observable}
  16112. */
  16113. this.onGeometryRemovedObservable = new BABYLON.Observable();
  16114. /**
  16115. * An event triggered when a mesh is created
  16116. * @type {BABYLON.Observable}
  16117. */
  16118. this.onNewMeshAddedObservable = new BABYLON.Observable();
  16119. /**
  16120. * An event triggered when a mesh is removed
  16121. * @type {BABYLON.Observable}
  16122. */
  16123. this.onMeshRemovedObservable = new BABYLON.Observable();
  16124. // Animations
  16125. this.animations = [];
  16126. /**
  16127. * 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).
  16128. * You have the possibility to skip the 3D Engine process and the call to onPointerObservable by setting PointerInfoBase.skipOnPointerObservable to true
  16129. */
  16130. this.onPrePointerObservable = new BABYLON.Observable();
  16131. /**
  16132. * Observable event triggered each time an input event is received from the rendering canvas
  16133. */
  16134. this.onPointerObservable = new BABYLON.Observable();
  16135. 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
  16136. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  16137. this._startingPointerTime = 0;
  16138. // Fog
  16139. /**
  16140. * is fog enabled on this scene.
  16141. * @type {boolean}
  16142. */
  16143. this.fogEnabled = true;
  16144. this.fogMode = Scene.FOGMODE_NONE;
  16145. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  16146. this.fogDensity = 0.1;
  16147. this.fogStart = 0;
  16148. this.fogEnd = 1000.0;
  16149. // Lights
  16150. /**
  16151. * is shadow enabled on this scene.
  16152. * @type {boolean}
  16153. */
  16154. this.shadowsEnabled = true;
  16155. /**
  16156. * is light enabled on this scene.
  16157. * @type {boolean}
  16158. */
  16159. this.lightsEnabled = true;
  16160. /**
  16161. * All of the lights added to this scene.
  16162. * @see BABYLON.Light
  16163. * @type {BABYLON.Light[]}
  16164. */
  16165. this.lights = new Array();
  16166. // Cameras
  16167. /**
  16168. * All of the cameras added to this scene.
  16169. * @see BABYLON.Camera
  16170. * @type {BABYLON.Camera[]}
  16171. */
  16172. this.cameras = new Array();
  16173. this.activeCameras = new Array();
  16174. // Meshes
  16175. /**
  16176. * All of the (abstract) meshes added to this scene.
  16177. * @see BABYLON.AbstractMesh
  16178. * @type {BABYLON.AbstractMesh[]}
  16179. */
  16180. this.meshes = new Array();
  16181. // Geometries
  16182. this._geometries = new Array();
  16183. this.materials = new Array();
  16184. this.multiMaterials = new Array();
  16185. this.defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  16186. // Textures
  16187. this.texturesEnabled = true;
  16188. this.textures = new Array();
  16189. // Particles
  16190. this.particlesEnabled = true;
  16191. this.particleSystems = new Array();
  16192. // Sprites
  16193. this.spritesEnabled = true;
  16194. this.spriteManagers = new Array();
  16195. // Layers
  16196. this.layers = new Array();
  16197. this.highlightLayers = new Array();
  16198. // Skeletons
  16199. this.skeletonsEnabled = true;
  16200. this.skeletons = new Array();
  16201. // Lens flares
  16202. this.lensFlaresEnabled = true;
  16203. this.lensFlareSystems = new Array();
  16204. // Collisions
  16205. this.collisionsEnabled = true;
  16206. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  16207. // Postprocesses
  16208. this.postProcessesEnabled = true;
  16209. // Customs render targets
  16210. this.renderTargetsEnabled = true;
  16211. this.dumpNextRenderTargets = false;
  16212. this.customRenderTargets = new Array();
  16213. // Imported meshes
  16214. this.importedMeshesFiles = new Array();
  16215. // Probes
  16216. this.probesEnabled = true;
  16217. this.reflectionProbes = new Array();
  16218. this._actionManagers = new Array();
  16219. this._meshesForIntersections = new BABYLON.SmartArray(256);
  16220. // Procedural textures
  16221. this.proceduralTexturesEnabled = true;
  16222. this._proceduralTextures = new Array();
  16223. this.soundTracks = new Array();
  16224. this._audioEnabled = true;
  16225. this._headphone = false;
  16226. // Performance counters
  16227. this._totalMeshesCounter = new BABYLON.PerfCounter();
  16228. this._totalLightsCounter = new BABYLON.PerfCounter();
  16229. this._totalMaterialsCounter = new BABYLON.PerfCounter();
  16230. this._totalTexturesCounter = new BABYLON.PerfCounter();
  16231. this._totalVertices = new BABYLON.PerfCounter();
  16232. this._activeIndices = new BABYLON.PerfCounter();
  16233. this._activeParticles = new BABYLON.PerfCounter();
  16234. this._lastFrameDuration = new BABYLON.PerfCounter();
  16235. this._evaluateActiveMeshesDuration = new BABYLON.PerfCounter();
  16236. this._renderTargetsDuration = new BABYLON.PerfCounter();
  16237. this._particlesDuration = new BABYLON.PerfCounter();
  16238. this._renderDuration = new BABYLON.PerfCounter();
  16239. this._spritesDuration = new BABYLON.PerfCounter();
  16240. this._activeBones = new BABYLON.PerfCounter();
  16241. this._renderId = 0;
  16242. this._executeWhenReadyTimeoutId = -1;
  16243. this._intermediateRendering = false;
  16244. this._toBeDisposed = new BABYLON.SmartArray(256);
  16245. this._pendingData = []; //ANY
  16246. this._activeMeshes = new BABYLON.SmartArray(256);
  16247. this._processedMaterials = new BABYLON.SmartArray(256);
  16248. this._renderTargets = new BABYLON.SmartArray(256);
  16249. this._activeParticleSystems = new BABYLON.SmartArray(256);
  16250. this._activeSkeletons = new BABYLON.SmartArray(32);
  16251. this._softwareSkinnedMeshes = new BABYLON.SmartArray(32);
  16252. this._activeAnimatables = new Array();
  16253. this._transformMatrix = BABYLON.Matrix.Zero();
  16254. this._edgesRenderers = new BABYLON.SmartArray(16);
  16255. this._uniqueIdCounter = 0;
  16256. this._engine = engine;
  16257. engine.scenes.push(this);
  16258. this._renderingManager = new BABYLON.RenderingManager(this);
  16259. this.postProcessManager = new BABYLON.PostProcessManager(this);
  16260. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  16261. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  16262. if (BABYLON.OutlineRenderer) {
  16263. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  16264. }
  16265. this.attachControl();
  16266. if (BABYLON.SoundTrack) {
  16267. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  16268. }
  16269. //simplification queue
  16270. if (BABYLON.SimplificationQueue) {
  16271. this.simplificationQueue = new BABYLON.SimplificationQueue();
  16272. }
  16273. //collision coordinator initialization. For now legacy per default.
  16274. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  16275. }
  16276. Object.defineProperty(Scene, "FOGMODE_NONE", {
  16277. get: function () {
  16278. return Scene._FOGMODE_NONE;
  16279. },
  16280. enumerable: true,
  16281. configurable: true
  16282. });
  16283. Object.defineProperty(Scene, "FOGMODE_EXP", {
  16284. get: function () {
  16285. return Scene._FOGMODE_EXP;
  16286. },
  16287. enumerable: true,
  16288. configurable: true
  16289. });
  16290. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  16291. get: function () {
  16292. return Scene._FOGMODE_EXP2;
  16293. },
  16294. enumerable: true,
  16295. configurable: true
  16296. });
  16297. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  16298. get: function () {
  16299. return Scene._FOGMODE_LINEAR;
  16300. },
  16301. enumerable: true,
  16302. configurable: true
  16303. });
  16304. Object.defineProperty(Scene.prototype, "onDispose", {
  16305. set: function (callback) {
  16306. if (this._onDisposeObserver) {
  16307. this.onDisposeObservable.remove(this._onDisposeObserver);
  16308. }
  16309. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  16310. },
  16311. enumerable: true,
  16312. configurable: true
  16313. });
  16314. Object.defineProperty(Scene.prototype, "beforeRender", {
  16315. set: function (callback) {
  16316. if (this._onBeforeRenderObserver) {
  16317. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  16318. }
  16319. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  16320. },
  16321. enumerable: true,
  16322. configurable: true
  16323. });
  16324. Object.defineProperty(Scene.prototype, "afterRender", {
  16325. set: function (callback) {
  16326. if (this._onAfterRenderObserver) {
  16327. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  16328. }
  16329. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  16330. },
  16331. enumerable: true,
  16332. configurable: true
  16333. });
  16334. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  16335. set: function (callback) {
  16336. if (this._onBeforeCameraRenderObserver) {
  16337. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  16338. }
  16339. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  16340. },
  16341. enumerable: true,
  16342. configurable: true
  16343. });
  16344. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  16345. set: function (callback) {
  16346. if (this._onAfterCameraRenderObserver) {
  16347. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  16348. }
  16349. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  16350. },
  16351. enumerable: true,
  16352. configurable: true
  16353. });
  16354. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  16355. get: function () {
  16356. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  16357. },
  16358. enumerable: true,
  16359. configurable: true
  16360. });
  16361. Object.defineProperty(Scene.prototype, "debugLayer", {
  16362. // Properties
  16363. get: function () {
  16364. if (!this._debugLayer) {
  16365. this._debugLayer = new BABYLON.DebugLayer(this);
  16366. }
  16367. return this._debugLayer;
  16368. },
  16369. enumerable: true,
  16370. configurable: true
  16371. });
  16372. Object.defineProperty(Scene.prototype, "workerCollisions", {
  16373. get: function () {
  16374. return this._workerCollisions;
  16375. },
  16376. set: function (enabled) {
  16377. enabled = (enabled && !!Worker);
  16378. this._workerCollisions = enabled;
  16379. if (this.collisionCoordinator) {
  16380. this.collisionCoordinator.destroy();
  16381. }
  16382. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  16383. this.collisionCoordinator.init(this);
  16384. },
  16385. enumerable: true,
  16386. configurable: true
  16387. });
  16388. Object.defineProperty(Scene.prototype, "SelectionOctree", {
  16389. get: function () {
  16390. return this._selectionOctree;
  16391. },
  16392. enumerable: true,
  16393. configurable: true
  16394. });
  16395. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  16396. /**
  16397. * The mesh that is currently under the pointer.
  16398. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  16399. */
  16400. get: function () {
  16401. return this._pointerOverMesh;
  16402. },
  16403. enumerable: true,
  16404. configurable: true
  16405. });
  16406. Object.defineProperty(Scene.prototype, "pointerX", {
  16407. /**
  16408. * Current on-screen X position of the pointer
  16409. * @return {number} X position of the pointer
  16410. */
  16411. get: function () {
  16412. return this._pointerX;
  16413. },
  16414. enumerable: true,
  16415. configurable: true
  16416. });
  16417. Object.defineProperty(Scene.prototype, "pointerY", {
  16418. /**
  16419. * Current on-screen Y position of the pointer
  16420. * @return {number} Y position of the pointer
  16421. */
  16422. get: function () {
  16423. return this._pointerY;
  16424. },
  16425. enumerable: true,
  16426. configurable: true
  16427. });
  16428. Scene.prototype.getCachedMaterial = function () {
  16429. return this._cachedMaterial;
  16430. };
  16431. Scene.prototype.getBoundingBoxRenderer = function () {
  16432. return this._boundingBoxRenderer;
  16433. };
  16434. Scene.prototype.getOutlineRenderer = function () {
  16435. return this._outlineRenderer;
  16436. };
  16437. Scene.prototype.getEngine = function () {
  16438. return this._engine;
  16439. };
  16440. Scene.prototype.getTotalVertices = function () {
  16441. return this._totalVertices.current;
  16442. };
  16443. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  16444. get: function () {
  16445. return this._totalVertices;
  16446. },
  16447. enumerable: true,
  16448. configurable: true
  16449. });
  16450. Scene.prototype.getActiveIndices = function () {
  16451. return this._activeIndices.current;
  16452. };
  16453. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  16454. get: function () {
  16455. return this._activeIndices;
  16456. },
  16457. enumerable: true,
  16458. configurable: true
  16459. });
  16460. Scene.prototype.getActiveParticles = function () {
  16461. return this._activeParticles.current;
  16462. };
  16463. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  16464. get: function () {
  16465. return this._activeParticles;
  16466. },
  16467. enumerable: true,
  16468. configurable: true
  16469. });
  16470. Scene.prototype.getActiveBones = function () {
  16471. return this._activeBones.current;
  16472. };
  16473. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  16474. get: function () {
  16475. return this._activeBones;
  16476. },
  16477. enumerable: true,
  16478. configurable: true
  16479. });
  16480. // Stats
  16481. Scene.prototype.getLastFrameDuration = function () {
  16482. return this._lastFrameDuration.current;
  16483. };
  16484. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  16485. get: function () {
  16486. return this._lastFrameDuration;
  16487. },
  16488. enumerable: true,
  16489. configurable: true
  16490. });
  16491. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  16492. return this._evaluateActiveMeshesDuration.current;
  16493. };
  16494. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  16495. get: function () {
  16496. return this._evaluateActiveMeshesDuration;
  16497. },
  16498. enumerable: true,
  16499. configurable: true
  16500. });
  16501. Scene.prototype.getActiveMeshes = function () {
  16502. return this._activeMeshes;
  16503. };
  16504. Scene.prototype.getRenderTargetsDuration = function () {
  16505. return this._renderTargetsDuration.current;
  16506. };
  16507. Scene.prototype.getRenderDuration = function () {
  16508. return this._renderDuration.current;
  16509. };
  16510. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  16511. get: function () {
  16512. return this._renderDuration;
  16513. },
  16514. enumerable: true,
  16515. configurable: true
  16516. });
  16517. Scene.prototype.getParticlesDuration = function () {
  16518. return this._particlesDuration.current;
  16519. };
  16520. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  16521. get: function () {
  16522. return this._particlesDuration;
  16523. },
  16524. enumerable: true,
  16525. configurable: true
  16526. });
  16527. Scene.prototype.getSpritesDuration = function () {
  16528. return this._spritesDuration.current;
  16529. };
  16530. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  16531. get: function () {
  16532. return this._spritesDuration;
  16533. },
  16534. enumerable: true,
  16535. configurable: true
  16536. });
  16537. Scene.prototype.getAnimationRatio = function () {
  16538. return this._animationRatio;
  16539. };
  16540. Scene.prototype.getRenderId = function () {
  16541. return this._renderId;
  16542. };
  16543. Scene.prototype.incrementRenderId = function () {
  16544. this._renderId++;
  16545. };
  16546. Scene.prototype._updatePointerPosition = function (evt) {
  16547. var canvasRect = this._engine.getRenderingCanvasClientRect();
  16548. this._pointerX = evt.clientX - canvasRect.left;
  16549. this._pointerY = evt.clientY - canvasRect.top;
  16550. this._unTranslatedPointerX = this._pointerX;
  16551. this._unTranslatedPointerY = this._pointerY;
  16552. if (this.cameraToUseForPointers) {
  16553. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  16554. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  16555. }
  16556. };
  16557. // Pointers handling
  16558. /**
  16559. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  16560. * @param attachUp defines if you want to attach events to pointerup
  16561. * @param attachDown defines if you want to attach events to pointerdown
  16562. * @param attachMove defines if you want to attach events to pointermove
  16563. */
  16564. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  16565. var _this = this;
  16566. if (attachUp === void 0) { attachUp = true; }
  16567. if (attachDown === void 0) { attachDown = true; }
  16568. if (attachMove === void 0) { attachMove = true; }
  16569. var spritePredicate = function (sprite) {
  16570. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  16571. };
  16572. this._onPointerMove = function (evt) {
  16573. _this._updatePointerPosition(evt);
  16574. // PreObservable support
  16575. if (_this.onPrePointerObservable.hasObservers()) {
  16576. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  16577. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  16578. _this.onPrePointerObservable.notifyObservers(pi, type);
  16579. if (pi.skipOnPointerObservable) {
  16580. return;
  16581. }
  16582. }
  16583. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  16584. return;
  16585. }
  16586. var canvas = _this._engine.getRenderingCanvas();
  16587. if (!_this.pointerMovePredicate) {
  16588. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && (_this.constantlyUpdateMeshUnderPointer || mesh.actionManager !== null && mesh.actionManager !== undefined); };
  16589. }
  16590. // Meshes
  16591. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  16592. if (pickResult.hit && pickResult.pickedMesh) {
  16593. _this.setPointerOverSprite(null);
  16594. _this.setPointerOverMesh(pickResult.pickedMesh);
  16595. if (_this._pointerOverMesh.actionManager && _this._pointerOverMesh.actionManager.hasPointerTriggers) {
  16596. canvas.style.cursor = _this.hoverCursor;
  16597. }
  16598. else {
  16599. canvas.style.cursor = "";
  16600. }
  16601. }
  16602. else {
  16603. _this.setPointerOverMesh(null);
  16604. // Sprites
  16605. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  16606. if (pickResult.hit && pickResult.pickedSprite) {
  16607. canvas.style.cursor = _this.hoverCursor;
  16608. _this.setPointerOverSprite(pickResult.pickedSprite);
  16609. }
  16610. else {
  16611. _this.setPointerOverSprite(null);
  16612. // Restore pointer
  16613. canvas.style.cursor = "";
  16614. }
  16615. }
  16616. if (_this.onPointerMove) {
  16617. _this.onPointerMove(evt, pickResult);
  16618. }
  16619. if (_this.onPointerObservable.hasObservers()) {
  16620. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  16621. var pi = new PointerInfo(type, evt, pickResult);
  16622. _this.onPointerObservable.notifyObservers(pi, type);
  16623. }
  16624. };
  16625. this._onPointerDown = function (evt) {
  16626. _this._updatePointerPosition(evt);
  16627. // PreObservable support
  16628. if (_this.onPrePointerObservable.hasObservers()) {
  16629. var type = PointerEventTypes.POINTERDOWN;
  16630. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  16631. _this.onPrePointerObservable.notifyObservers(pi, type);
  16632. if (pi.skipOnPointerObservable) {
  16633. return;
  16634. }
  16635. }
  16636. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  16637. return;
  16638. }
  16639. _this._startingPointerPosition.x = _this._pointerX;
  16640. _this._startingPointerPosition.y = _this._pointerY;
  16641. _this._startingPointerTime = new Date().getTime();
  16642. if (!_this.pointerDownPredicate) {
  16643. _this.pointerDownPredicate = function (mesh) {
  16644. return mesh.isPickable && mesh.isVisible && mesh.isReady() && (!mesh.actionManager || mesh.actionManager.hasPointerTriggers);
  16645. };
  16646. }
  16647. // Meshes
  16648. _this._pickedDownMesh = null;
  16649. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  16650. if (pickResult.hit && pickResult.pickedMesh) {
  16651. if (pickResult.pickedMesh.actionManager) {
  16652. _this._pickedDownMesh = pickResult.pickedMesh;
  16653. if (pickResult.pickedMesh.actionManager.hasPickTriggers) {
  16654. switch (evt.button) {
  16655. case 0:
  16656. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16657. break;
  16658. case 1:
  16659. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16660. break;
  16661. case 2:
  16662. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16663. break;
  16664. }
  16665. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16666. }
  16667. if (pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  16668. var that = _this;
  16669. window.setTimeout(function () {
  16670. 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);
  16671. if (pickResult.hit && pickResult.pickedMesh) {
  16672. if (pickResult.pickedMesh.actionManager) {
  16673. 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)) {
  16674. that._startingPointerTime = 0;
  16675. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16676. }
  16677. }
  16678. }
  16679. }, BABYLON.ActionManager.LongPressDelay);
  16680. }
  16681. }
  16682. }
  16683. if (_this.onPointerDown) {
  16684. _this.onPointerDown(evt, pickResult);
  16685. }
  16686. if (_this.onPointerObservable.hasObservers()) {
  16687. var type = PointerEventTypes.POINTERDOWN;
  16688. var pi = new PointerInfo(type, evt, pickResult);
  16689. _this.onPointerObservable.notifyObservers(pi, type);
  16690. }
  16691. // Sprites
  16692. _this._pickedDownSprite = null;
  16693. if (_this.spriteManagers.length > 0) {
  16694. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  16695. if (pickResult.hit && pickResult.pickedSprite) {
  16696. if (pickResult.pickedSprite.actionManager) {
  16697. _this._pickedDownSprite = pickResult.pickedSprite;
  16698. switch (evt.button) {
  16699. case 0:
  16700. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  16701. break;
  16702. case 1:
  16703. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  16704. break;
  16705. case 2:
  16706. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  16707. break;
  16708. }
  16709. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  16710. }
  16711. }
  16712. }
  16713. };
  16714. this._onPointerUp = function (evt) {
  16715. _this._updatePointerPosition(evt);
  16716. // PreObservable support
  16717. if (_this.onPrePointerObservable.hasObservers()) {
  16718. var type = PointerEventTypes.POINTERUP;
  16719. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  16720. _this.onPrePointerObservable.notifyObservers(pi, type);
  16721. if (pi.skipOnPointerObservable) {
  16722. return;
  16723. }
  16724. }
  16725. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  16726. return;
  16727. }
  16728. if (!_this.pointerUpPredicate) {
  16729. _this.pointerUpPredicate = function (mesh) {
  16730. return mesh.isPickable && mesh.isVisible && mesh.isReady() && (!mesh.actionManager || (mesh.actionManager.hasPickTriggers || mesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)));
  16731. };
  16732. }
  16733. // Meshes
  16734. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerUpPredicate, false, _this.cameraToUseForPointers);
  16735. if (pickResult.hit && pickResult.pickedMesh) {
  16736. if (_this._pickedDownMesh != null && pickResult.pickedMesh == _this._pickedDownMesh) {
  16737. if (_this.onPointerPick) {
  16738. _this.onPointerPick(evt, pickResult);
  16739. }
  16740. if (_this.onPointerObservable.hasObservers()) {
  16741. var type = PointerEventTypes.POINTERPICK;
  16742. var pi = new PointerInfo(type, evt, pickResult);
  16743. _this.onPointerObservable.notifyObservers(pi, type);
  16744. }
  16745. }
  16746. if (pickResult.pickedMesh.actionManager) {
  16747. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16748. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < BABYLON.ActionManager.DragMovementThreshold) {
  16749. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16750. }
  16751. }
  16752. }
  16753. if (_this._pickedDownMesh && _this._pickedDownMesh !== pickResult.pickedMesh) {
  16754. _this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(_this._pickedDownMesh, evt));
  16755. }
  16756. if (_this.onPointerUp) {
  16757. _this.onPointerUp(evt, pickResult);
  16758. }
  16759. if (_this.onPointerObservable.hasObservers()) {
  16760. var type = PointerEventTypes.POINTERUP;
  16761. var pi = new PointerInfo(type, evt, pickResult);
  16762. _this.onPointerObservable.notifyObservers(pi, type);
  16763. }
  16764. _this._startingPointerTime = 0;
  16765. // Sprites
  16766. if (_this.spriteManagers.length > 0) {
  16767. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  16768. if (pickResult.hit && pickResult.pickedSprite) {
  16769. if (pickResult.pickedSprite.actionManager) {
  16770. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  16771. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < BABYLON.ActionManager.DragMovementThreshold) {
  16772. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  16773. }
  16774. }
  16775. }
  16776. if (_this._pickedDownSprite && _this._pickedDownSprite !== pickResult.pickedSprite) {
  16777. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  16778. }
  16779. }
  16780. };
  16781. this._onKeyDown = function (evt) {
  16782. if (_this.actionManager) {
  16783. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  16784. }
  16785. };
  16786. this._onKeyUp = function (evt) {
  16787. if (_this.actionManager) {
  16788. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  16789. }
  16790. };
  16791. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  16792. var canvas = this._engine.getRenderingCanvas();
  16793. if (attachMove) {
  16794. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  16795. // Wheel
  16796. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  16797. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  16798. }
  16799. if (attachDown) {
  16800. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  16801. }
  16802. if (attachUp) {
  16803. canvas.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  16804. }
  16805. canvas.tabIndex = 1;
  16806. canvas.addEventListener("keydown", this._onKeyDown, false);
  16807. canvas.addEventListener("keyup", this._onKeyUp, false);
  16808. };
  16809. Scene.prototype.detachControl = function () {
  16810. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  16811. var canvas = this._engine.getRenderingCanvas();
  16812. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  16813. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  16814. canvas.removeEventListener(eventPrefix + "up", this._onPointerUp);
  16815. // Wheel
  16816. canvas.removeEventListener('mousewheel', this._onPointerMove);
  16817. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  16818. canvas.removeEventListener("keydown", this._onKeyDown);
  16819. canvas.removeEventListener("keyup", this._onKeyUp);
  16820. };
  16821. // Ready
  16822. Scene.prototype.isReady = function () {
  16823. if (this._pendingData.length > 0) {
  16824. return false;
  16825. }
  16826. var index;
  16827. for (index = 0; index < this._geometries.length; index++) {
  16828. var geometry = this._geometries[index];
  16829. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  16830. return false;
  16831. }
  16832. }
  16833. for (index = 0; index < this.meshes.length; index++) {
  16834. var mesh = this.meshes[index];
  16835. if (!mesh.isReady()) {
  16836. return false;
  16837. }
  16838. var mat = mesh.material;
  16839. if (mat) {
  16840. if (!mat.isReady(mesh)) {
  16841. return false;
  16842. }
  16843. }
  16844. }
  16845. return true;
  16846. };
  16847. Scene.prototype.resetCachedMaterial = function () {
  16848. this._cachedMaterial = null;
  16849. };
  16850. Scene.prototype.registerBeforeRender = function (func) {
  16851. this.onBeforeRenderObservable.add(func);
  16852. };
  16853. Scene.prototype.unregisterBeforeRender = function (func) {
  16854. this.onBeforeRenderObservable.removeCallback(func);
  16855. };
  16856. Scene.prototype.registerAfterRender = function (func) {
  16857. this.onAfterRenderObservable.add(func);
  16858. };
  16859. Scene.prototype.unregisterAfterRender = function (func) {
  16860. this.onAfterRenderObservable.removeCallback(func);
  16861. };
  16862. Scene.prototype._addPendingData = function (data) {
  16863. this._pendingData.push(data);
  16864. };
  16865. Scene.prototype._removePendingData = function (data) {
  16866. var index = this._pendingData.indexOf(data);
  16867. if (index !== -1) {
  16868. this._pendingData.splice(index, 1);
  16869. }
  16870. };
  16871. Scene.prototype.getWaitingItemsCount = function () {
  16872. return this._pendingData.length;
  16873. };
  16874. /**
  16875. * Registers a function to be executed when the scene is ready.
  16876. * @param {Function} func - the function to be executed.
  16877. */
  16878. Scene.prototype.executeWhenReady = function (func) {
  16879. var _this = this;
  16880. this.onReadyObservable.add(func);
  16881. if (this._executeWhenReadyTimeoutId !== -1) {
  16882. return;
  16883. }
  16884. this._executeWhenReadyTimeoutId = setTimeout(function () {
  16885. _this._checkIsReady();
  16886. }, 150);
  16887. };
  16888. Scene.prototype._checkIsReady = function () {
  16889. var _this = this;
  16890. if (this.isReady()) {
  16891. this.onReadyObservable.notifyObservers(this);
  16892. this.onReadyObservable.clear();
  16893. this._executeWhenReadyTimeoutId = -1;
  16894. return;
  16895. }
  16896. this._executeWhenReadyTimeoutId = setTimeout(function () {
  16897. _this._checkIsReady();
  16898. }, 150);
  16899. };
  16900. // Animations
  16901. /**
  16902. * Will start the animation sequence of a given target
  16903. * @param target - the target
  16904. * @param {number} from - from which frame should animation start
  16905. * @param {number} to - till which frame should animation run.
  16906. * @param {boolean} [loop] - should the animation loop
  16907. * @param {number} [speedRatio] - the speed in which to run the animation
  16908. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  16909. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  16910. * @return {BABYLON.Animatable} the animatable object created for this animation
  16911. * @see BABYLON.Animatable
  16912. * @see http://doc.babylonjs.com/page.php?p=22081
  16913. */
  16914. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  16915. if (speedRatio === void 0) { speedRatio = 1.0; }
  16916. this.stopAnimation(target);
  16917. if (!animatable) {
  16918. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  16919. }
  16920. // Local animations
  16921. if (target.animations) {
  16922. animatable.appendAnimations(target, target.animations);
  16923. }
  16924. // Children animations
  16925. if (target.getAnimatables) {
  16926. var animatables = target.getAnimatables();
  16927. for (var index = 0; index < animatables.length; index++) {
  16928. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  16929. }
  16930. }
  16931. animatable.reset();
  16932. return animatable;
  16933. };
  16934. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  16935. if (speedRatio === undefined) {
  16936. speedRatio = 1.0;
  16937. }
  16938. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  16939. return animatable;
  16940. };
  16941. Scene.prototype.getAnimatableByTarget = function (target) {
  16942. for (var index = 0; index < this._activeAnimatables.length; index++) {
  16943. if (this._activeAnimatables[index].target === target) {
  16944. return this._activeAnimatables[index];
  16945. }
  16946. }
  16947. return null;
  16948. };
  16949. Object.defineProperty(Scene.prototype, "Animatables", {
  16950. get: function () {
  16951. return this._activeAnimatables;
  16952. },
  16953. enumerable: true,
  16954. configurable: true
  16955. });
  16956. /**
  16957. * Will stop the animation of the given target
  16958. * @param target - the target
  16959. * @see beginAnimation
  16960. */
  16961. Scene.prototype.stopAnimation = function (target) {
  16962. var animatable = this.getAnimatableByTarget(target);
  16963. if (animatable) {
  16964. animatable.stop();
  16965. }
  16966. };
  16967. Scene.prototype._animate = function () {
  16968. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  16969. return;
  16970. }
  16971. if (!this._animationStartDate) {
  16972. if (this._pendingData.length > 0) {
  16973. return;
  16974. }
  16975. this._animationStartDate = BABYLON.Tools.Now;
  16976. }
  16977. // Getting time
  16978. var now = BABYLON.Tools.Now;
  16979. var delay = now - this._animationStartDate;
  16980. for (var index = 0; index < this._activeAnimatables.length; index++) {
  16981. this._activeAnimatables[index]._animate(delay);
  16982. }
  16983. };
  16984. // Matrix
  16985. Scene.prototype.getViewMatrix = function () {
  16986. return this._viewMatrix;
  16987. };
  16988. Scene.prototype.getProjectionMatrix = function () {
  16989. return this._projectionMatrix;
  16990. };
  16991. Scene.prototype.getTransformMatrix = function () {
  16992. return this._transformMatrix;
  16993. };
  16994. Scene.prototype.setTransformMatrix = function (view, projection) {
  16995. this._viewMatrix = view;
  16996. this._projectionMatrix = projection;
  16997. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  16998. // Update frustum
  16999. if (!this._frustumPlanes) {
  17000. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  17001. }
  17002. else {
  17003. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  17004. }
  17005. };
  17006. // Methods
  17007. Scene.prototype.addMesh = function (newMesh) {
  17008. newMesh.uniqueId = this._uniqueIdCounter++;
  17009. var position = this.meshes.push(newMesh);
  17010. //notify the collision coordinator
  17011. this.collisionCoordinator.onMeshAdded(newMesh);
  17012. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  17013. };
  17014. Scene.prototype.removeMesh = function (toRemove) {
  17015. var index = this.meshes.indexOf(toRemove);
  17016. if (index !== -1) {
  17017. // Remove from the scene if mesh found
  17018. this.meshes.splice(index, 1);
  17019. }
  17020. //notify the collision coordinator
  17021. this.collisionCoordinator.onMeshRemoved(toRemove);
  17022. this.onMeshRemovedObservable.notifyObservers(toRemove);
  17023. return index;
  17024. };
  17025. Scene.prototype.removeSkeleton = function (toRemove) {
  17026. var index = this.skeletons.indexOf(toRemove);
  17027. if (index !== -1) {
  17028. // Remove from the scene if mesh found
  17029. this.skeletons.splice(index, 1);
  17030. }
  17031. return index;
  17032. };
  17033. Scene.prototype.removeLight = function (toRemove) {
  17034. var index = this.lights.indexOf(toRemove);
  17035. if (index !== -1) {
  17036. // Remove from the scene if mesh found
  17037. this.lights.splice(index, 1);
  17038. }
  17039. this.onLightRemovedObservable.notifyObservers(toRemove);
  17040. return index;
  17041. };
  17042. Scene.prototype.removeCamera = function (toRemove) {
  17043. var index = this.cameras.indexOf(toRemove);
  17044. if (index !== -1) {
  17045. // Remove from the scene if mesh found
  17046. this.cameras.splice(index, 1);
  17047. }
  17048. // Remove from activeCameras
  17049. var index2 = this.activeCameras.indexOf(toRemove);
  17050. if (index2 !== -1) {
  17051. // Remove from the scene if mesh found
  17052. this.activeCameras.splice(index2, 1);
  17053. }
  17054. // Reset the activeCamera
  17055. if (this.activeCamera === toRemove) {
  17056. if (this.cameras.length > 0) {
  17057. this.activeCamera = this.cameras[0];
  17058. }
  17059. else {
  17060. this.activeCamera = null;
  17061. }
  17062. }
  17063. this.onCameraRemovedObservable.notifyObservers(toRemove);
  17064. return index;
  17065. };
  17066. Scene.prototype.addLight = function (newLight) {
  17067. newLight.uniqueId = this._uniqueIdCounter++;
  17068. var position = this.lights.push(newLight);
  17069. this.onNewLightAddedObservable.notifyObservers(newLight);
  17070. };
  17071. Scene.prototype.addCamera = function (newCamera) {
  17072. newCamera.uniqueId = this._uniqueIdCounter++;
  17073. var position = this.cameras.push(newCamera);
  17074. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  17075. };
  17076. /**
  17077. * Switch active camera
  17078. * @param {Camera} newCamera - new active camera
  17079. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  17080. */
  17081. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  17082. if (attachControl === void 0) { attachControl = true; }
  17083. var canvas = this._engine.getRenderingCanvas();
  17084. this.activeCamera.detachControl(canvas);
  17085. this.activeCamera = newCamera;
  17086. if (attachControl) {
  17087. newCamera.attachControl(canvas);
  17088. }
  17089. };
  17090. /**
  17091. * sets the active camera of the scene using its ID
  17092. * @param {string} id - the camera's ID
  17093. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  17094. * @see activeCamera
  17095. */
  17096. Scene.prototype.setActiveCameraByID = function (id) {
  17097. var camera = this.getCameraByID(id);
  17098. if (camera) {
  17099. this.activeCamera = camera;
  17100. return camera;
  17101. }
  17102. return null;
  17103. };
  17104. /**
  17105. * sets the active camera of the scene using its name
  17106. * @param {string} name - the camera's name
  17107. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  17108. * @see activeCamera
  17109. */
  17110. Scene.prototype.setActiveCameraByName = function (name) {
  17111. var camera = this.getCameraByName(name);
  17112. if (camera) {
  17113. this.activeCamera = camera;
  17114. return camera;
  17115. }
  17116. return null;
  17117. };
  17118. /**
  17119. * get a material using its id
  17120. * @param {string} the material's ID
  17121. * @return {BABYLON.Material|null} the material or null if none found.
  17122. */
  17123. Scene.prototype.getMaterialByID = function (id) {
  17124. for (var index = 0; index < this.materials.length; index++) {
  17125. if (this.materials[index].id === id) {
  17126. return this.materials[index];
  17127. }
  17128. }
  17129. return null;
  17130. };
  17131. /**
  17132. * get a material using its name
  17133. * @param {string} the material's name
  17134. * @return {BABYLON.Material|null} the material or null if none found.
  17135. */
  17136. Scene.prototype.getMaterialByName = function (name) {
  17137. for (var index = 0; index < this.materials.length; index++) {
  17138. if (this.materials[index].name === name) {
  17139. return this.materials[index];
  17140. }
  17141. }
  17142. return null;
  17143. };
  17144. Scene.prototype.getLensFlareSystemByName = function (name) {
  17145. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  17146. if (this.lensFlareSystems[index].name === name) {
  17147. return this.lensFlareSystems[index];
  17148. }
  17149. }
  17150. return null;
  17151. };
  17152. Scene.prototype.getLensFlareSystemByID = function (id) {
  17153. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  17154. if (this.lensFlareSystems[index].id === id) {
  17155. return this.lensFlareSystems[index];
  17156. }
  17157. }
  17158. return null;
  17159. };
  17160. Scene.prototype.getCameraByID = function (id) {
  17161. for (var index = 0; index < this.cameras.length; index++) {
  17162. if (this.cameras[index].id === id) {
  17163. return this.cameras[index];
  17164. }
  17165. }
  17166. return null;
  17167. };
  17168. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  17169. for (var index = 0; index < this.cameras.length; index++) {
  17170. if (this.cameras[index].uniqueId === uniqueId) {
  17171. return this.cameras[index];
  17172. }
  17173. }
  17174. return null;
  17175. };
  17176. /**
  17177. * get a camera using its name
  17178. * @param {string} the camera's name
  17179. * @return {BABYLON.Camera|null} the camera or null if none found.
  17180. */
  17181. Scene.prototype.getCameraByName = function (name) {
  17182. for (var index = 0; index < this.cameras.length; index++) {
  17183. if (this.cameras[index].name === name) {
  17184. return this.cameras[index];
  17185. }
  17186. }
  17187. return null;
  17188. };
  17189. /**
  17190. * get a bone using its id
  17191. * @param {string} the bone's id
  17192. * @return {BABYLON.Bone|null} the bone or null if not found
  17193. */
  17194. Scene.prototype.getBoneByID = function (id) {
  17195. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  17196. var skeleton = this.skeletons[skeletonIndex];
  17197. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  17198. if (skeleton.bones[boneIndex].id === id) {
  17199. return skeleton.bones[boneIndex];
  17200. }
  17201. }
  17202. }
  17203. return null;
  17204. };
  17205. /**
  17206. * get a bone using its id
  17207. * @param {string} the bone's name
  17208. * @return {BABYLON.Bone|null} the bone or null if not found
  17209. */
  17210. Scene.prototype.getBoneByName = function (name) {
  17211. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  17212. var skeleton = this.skeletons[skeletonIndex];
  17213. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  17214. if (skeleton.bones[boneIndex].name === name) {
  17215. return skeleton.bones[boneIndex];
  17216. }
  17217. }
  17218. }
  17219. return null;
  17220. };
  17221. /**
  17222. * get a light node using its name
  17223. * @param {string} the light's name
  17224. * @return {BABYLON.Light|null} the light or null if none found.
  17225. */
  17226. Scene.prototype.getLightByName = function (name) {
  17227. for (var index = 0; index < this.lights.length; index++) {
  17228. if (this.lights[index].name === name) {
  17229. return this.lights[index];
  17230. }
  17231. }
  17232. return null;
  17233. };
  17234. /**
  17235. * get a light node using its ID
  17236. * @param {string} the light's id
  17237. * @return {BABYLON.Light|null} the light or null if none found.
  17238. */
  17239. Scene.prototype.getLightByID = function (id) {
  17240. for (var index = 0; index < this.lights.length; index++) {
  17241. if (this.lights[index].id === id) {
  17242. return this.lights[index];
  17243. }
  17244. }
  17245. return null;
  17246. };
  17247. /**
  17248. * get a light node using its scene-generated unique ID
  17249. * @param {number} the light's unique id
  17250. * @return {BABYLON.Light|null} the light or null if none found.
  17251. */
  17252. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  17253. for (var index = 0; index < this.lights.length; index++) {
  17254. if (this.lights[index].uniqueId === uniqueId) {
  17255. return this.lights[index];
  17256. }
  17257. }
  17258. return null;
  17259. };
  17260. /**
  17261. * get a particle system by id
  17262. * @param id {number} the particle system id
  17263. * @return {BABYLON.ParticleSystem|null} the corresponding system or null if none found.
  17264. */
  17265. Scene.prototype.getParticleSystemByID = function (id) {
  17266. for (var index = 0; index < this.particleSystems.length; index++) {
  17267. if (this.particleSystems[index].id === id) {
  17268. return this.particleSystems[index];
  17269. }
  17270. }
  17271. return null;
  17272. };
  17273. /**
  17274. * get a geometry using its ID
  17275. * @param {string} the geometry's id
  17276. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  17277. */
  17278. Scene.prototype.getGeometryByID = function (id) {
  17279. for (var index = 0; index < this._geometries.length; index++) {
  17280. if (this._geometries[index].id === id) {
  17281. return this._geometries[index];
  17282. }
  17283. }
  17284. return null;
  17285. };
  17286. /**
  17287. * add a new geometry to this scene.
  17288. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  17289. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  17290. * @return {boolean} was the geometry added or not
  17291. */
  17292. Scene.prototype.pushGeometry = function (geometry, force) {
  17293. if (!force && this.getGeometryByID(geometry.id)) {
  17294. return false;
  17295. }
  17296. this._geometries.push(geometry);
  17297. //notify the collision coordinator
  17298. this.collisionCoordinator.onGeometryAdded(geometry);
  17299. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  17300. return true;
  17301. };
  17302. /**
  17303. * Removes an existing geometry
  17304. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  17305. * @return {boolean} was the geometry removed or not
  17306. */
  17307. Scene.prototype.removeGeometry = function (geometry) {
  17308. var index = this._geometries.indexOf(geometry);
  17309. if (index > -1) {
  17310. this._geometries.splice(index, 1);
  17311. //notify the collision coordinator
  17312. this.collisionCoordinator.onGeometryDeleted(geometry);
  17313. this.onGeometryRemovedObservable.notifyObservers(geometry);
  17314. return true;
  17315. }
  17316. return false;
  17317. };
  17318. Scene.prototype.getGeometries = function () {
  17319. return this._geometries;
  17320. };
  17321. /**
  17322. * Get the first added mesh found of a given ID
  17323. * @param {string} id - the id to search for
  17324. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  17325. */
  17326. Scene.prototype.getMeshByID = function (id) {
  17327. for (var index = 0; index < this.meshes.length; index++) {
  17328. if (this.meshes[index].id === id) {
  17329. return this.meshes[index];
  17330. }
  17331. }
  17332. return null;
  17333. };
  17334. Scene.prototype.getMeshesByID = function (id) {
  17335. return this.meshes.filter(function (m) {
  17336. return m.id === id;
  17337. });
  17338. };
  17339. /**
  17340. * Get a mesh with its auto-generated unique id
  17341. * @param {number} uniqueId - the unique id to search for
  17342. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  17343. */
  17344. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  17345. for (var index = 0; index < this.meshes.length; index++) {
  17346. if (this.meshes[index].uniqueId === uniqueId) {
  17347. return this.meshes[index];
  17348. }
  17349. }
  17350. return null;
  17351. };
  17352. /**
  17353. * Get a the last added mesh found of a given ID
  17354. * @param {string} id - the id to search for
  17355. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  17356. */
  17357. Scene.prototype.getLastMeshByID = function (id) {
  17358. for (var index = this.meshes.length - 1; index >= 0; index--) {
  17359. if (this.meshes[index].id === id) {
  17360. return this.meshes[index];
  17361. }
  17362. }
  17363. return null;
  17364. };
  17365. /**
  17366. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  17367. * @param {string} id - the id to search for
  17368. * @return {BABYLON.Node|null} the node found or null if not found at all.
  17369. */
  17370. Scene.prototype.getLastEntryByID = function (id) {
  17371. var index;
  17372. for (index = this.meshes.length - 1; index >= 0; index--) {
  17373. if (this.meshes[index].id === id) {
  17374. return this.meshes[index];
  17375. }
  17376. }
  17377. for (index = this.cameras.length - 1; index >= 0; index--) {
  17378. if (this.cameras[index].id === id) {
  17379. return this.cameras[index];
  17380. }
  17381. }
  17382. for (index = this.lights.length - 1; index >= 0; index--) {
  17383. if (this.lights[index].id === id) {
  17384. return this.lights[index];
  17385. }
  17386. }
  17387. return null;
  17388. };
  17389. Scene.prototype.getNodeByID = function (id) {
  17390. var mesh = this.getMeshByID(id);
  17391. if (mesh) {
  17392. return mesh;
  17393. }
  17394. var light = this.getLightByID(id);
  17395. if (light) {
  17396. return light;
  17397. }
  17398. var camera = this.getCameraByID(id);
  17399. if (camera) {
  17400. return camera;
  17401. }
  17402. var bone = this.getBoneByID(id);
  17403. return bone;
  17404. };
  17405. Scene.prototype.getNodeByName = function (name) {
  17406. var mesh = this.getMeshByName(name);
  17407. if (mesh) {
  17408. return mesh;
  17409. }
  17410. var light = this.getLightByName(name);
  17411. if (light) {
  17412. return light;
  17413. }
  17414. var camera = this.getCameraByName(name);
  17415. if (camera) {
  17416. return camera;
  17417. }
  17418. var bone = this.getBoneByName(name);
  17419. return bone;
  17420. };
  17421. Scene.prototype.getMeshByName = function (name) {
  17422. for (var index = 0; index < this.meshes.length; index++) {
  17423. if (this.meshes[index].name === name) {
  17424. return this.meshes[index];
  17425. }
  17426. }
  17427. return null;
  17428. };
  17429. Scene.prototype.getSoundByName = function (name) {
  17430. var index;
  17431. if (BABYLON.AudioEngine) {
  17432. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  17433. if (this.mainSoundTrack.soundCollection[index].name === name) {
  17434. return this.mainSoundTrack.soundCollection[index];
  17435. }
  17436. }
  17437. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  17438. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  17439. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  17440. return this.soundTracks[sdIndex].soundCollection[index];
  17441. }
  17442. }
  17443. }
  17444. }
  17445. return null;
  17446. };
  17447. Scene.prototype.getLastSkeletonByID = function (id) {
  17448. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  17449. if (this.skeletons[index].id === id) {
  17450. return this.skeletons[index];
  17451. }
  17452. }
  17453. return null;
  17454. };
  17455. Scene.prototype.getSkeletonById = function (id) {
  17456. for (var index = 0; index < this.skeletons.length; index++) {
  17457. if (this.skeletons[index].id === id) {
  17458. return this.skeletons[index];
  17459. }
  17460. }
  17461. return null;
  17462. };
  17463. Scene.prototype.getSkeletonByName = function (name) {
  17464. for (var index = 0; index < this.skeletons.length; index++) {
  17465. if (this.skeletons[index].name === name) {
  17466. return this.skeletons[index];
  17467. }
  17468. }
  17469. return null;
  17470. };
  17471. Scene.prototype.isActiveMesh = function (mesh) {
  17472. return (this._activeMeshes.indexOf(mesh) !== -1);
  17473. };
  17474. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  17475. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  17476. var material = subMesh.getMaterial();
  17477. if (mesh.showSubMeshesBoundingBox) {
  17478. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  17479. }
  17480. if (material) {
  17481. // Render targets
  17482. if (material.getRenderTargetTextures) {
  17483. if (this._processedMaterials.indexOf(material) === -1) {
  17484. this._processedMaterials.push(material);
  17485. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  17486. }
  17487. }
  17488. // Dispatch
  17489. this._activeIndices.addCount(subMesh.indexCount, false);
  17490. this._renderingManager.dispatch(subMesh);
  17491. }
  17492. }
  17493. };
  17494. Scene.prototype._isInIntermediateRendering = function () {
  17495. return this._intermediateRendering;
  17496. };
  17497. Scene.prototype._evaluateActiveMeshes = function () {
  17498. this.activeCamera._activeMeshes.reset();
  17499. this._activeMeshes.reset();
  17500. this._renderingManager.reset();
  17501. this._processedMaterials.reset();
  17502. this._activeParticleSystems.reset();
  17503. this._activeSkeletons.reset();
  17504. this._softwareSkinnedMeshes.reset();
  17505. this._boundingBoxRenderer.reset();
  17506. this._edgesRenderers.reset();
  17507. // Meshes
  17508. var meshes;
  17509. var len;
  17510. if (this._selectionOctree) {
  17511. var selection = this._selectionOctree.select(this._frustumPlanes);
  17512. meshes = selection.data;
  17513. len = selection.length;
  17514. }
  17515. else {
  17516. len = this.meshes.length;
  17517. meshes = this.meshes;
  17518. }
  17519. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  17520. var mesh = meshes[meshIndex];
  17521. if (mesh.isBlocked) {
  17522. continue;
  17523. }
  17524. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  17525. if (!mesh.isReady() || !mesh.isEnabled()) {
  17526. continue;
  17527. }
  17528. mesh.computeWorldMatrix();
  17529. // Intersections
  17530. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  17531. this._meshesForIntersections.pushNoDuplicate(mesh);
  17532. }
  17533. // Switch to current LOD
  17534. var meshLOD = mesh.getLOD(this.activeCamera);
  17535. if (!meshLOD) {
  17536. continue;
  17537. }
  17538. mesh._preActivate();
  17539. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  17540. this._activeMeshes.push(mesh);
  17541. this.activeCamera._activeMeshes.push(mesh);
  17542. mesh._activate(this._renderId);
  17543. this._activeMesh(mesh, meshLOD);
  17544. }
  17545. }
  17546. // Particle systems
  17547. this._particlesDuration.beginMonitoring();
  17548. var beforeParticlesDate = BABYLON.Tools.Now;
  17549. if (this.particlesEnabled) {
  17550. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  17551. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  17552. var particleSystem = this.particleSystems[particleIndex];
  17553. if (!particleSystem.isStarted()) {
  17554. continue;
  17555. }
  17556. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  17557. this._activeParticleSystems.push(particleSystem);
  17558. particleSystem.animate();
  17559. }
  17560. }
  17561. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  17562. }
  17563. this._particlesDuration.endMonitoring(false);
  17564. };
  17565. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  17566. if (mesh.skeleton && this.skeletonsEnabled) {
  17567. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  17568. mesh.skeleton.prepare();
  17569. }
  17570. if (!mesh.computeBonesUsingShaders) {
  17571. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  17572. }
  17573. }
  17574. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  17575. this._boundingBoxRenderer.renderList.push(sourceMesh.getBoundingInfo().boundingBox);
  17576. }
  17577. if (sourceMesh._edgesRenderer) {
  17578. this._edgesRenderers.push(sourceMesh._edgesRenderer);
  17579. }
  17580. if (mesh && mesh.subMeshes) {
  17581. // Submeshes Octrees
  17582. var len;
  17583. var subMeshes;
  17584. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  17585. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  17586. len = intersections.length;
  17587. subMeshes = intersections.data;
  17588. }
  17589. else {
  17590. subMeshes = mesh.subMeshes;
  17591. len = subMeshes.length;
  17592. }
  17593. for (var subIndex = 0; subIndex < len; subIndex++) {
  17594. var subMesh = subMeshes[subIndex];
  17595. this._evaluateSubMesh(subMesh, mesh);
  17596. }
  17597. }
  17598. };
  17599. Scene.prototype.updateTransformMatrix = function (force) {
  17600. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  17601. };
  17602. Scene.prototype._renderForCamera = function (camera) {
  17603. var engine = this._engine;
  17604. var startTime = BABYLON.Tools.Now;
  17605. this.activeCamera = camera;
  17606. if (!this.activeCamera)
  17607. throw new Error("Active camera not set");
  17608. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  17609. // Viewport
  17610. engine.setViewport(this.activeCamera.viewport);
  17611. // Camera
  17612. this.resetCachedMaterial();
  17613. this._renderId++;
  17614. this.updateTransformMatrix();
  17615. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  17616. // Meshes
  17617. this._evaluateActiveMeshesDuration.beginMonitoring();
  17618. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  17619. this._evaluateActiveMeshes();
  17620. this._evaluateActiveMeshesDuration.endMonitoring(false);
  17621. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  17622. // Software skinning
  17623. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  17624. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  17625. mesh.applySkeleton(mesh.skeleton);
  17626. }
  17627. // Render targets
  17628. this._renderTargetsDuration.beginMonitoring();
  17629. var beforeRenderTargetDate = BABYLON.Tools.Now;
  17630. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  17631. this._intermediateRendering = true;
  17632. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  17633. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  17634. var renderTarget = this._renderTargets.data[renderIndex];
  17635. if (renderTarget._shouldRender()) {
  17636. this._renderId++;
  17637. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  17638. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  17639. }
  17640. }
  17641. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  17642. this._intermediateRendering = false;
  17643. this._renderId++;
  17644. engine.restoreDefaultFramebuffer(); // Restore back buffer
  17645. }
  17646. this._renderTargetsDuration.endMonitoring(false);
  17647. // Prepare Frame
  17648. this.postProcessManager._prepareFrame();
  17649. this._renderDuration.beginMonitoring();
  17650. // Backgrounds
  17651. var layerIndex;
  17652. var layer;
  17653. if (this.layers.length) {
  17654. engine.setDepthBuffer(false);
  17655. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  17656. layer = this.layers[layerIndex];
  17657. if (layer.isBackground) {
  17658. layer.render();
  17659. }
  17660. }
  17661. engine.setDepthBuffer(true);
  17662. }
  17663. // Render
  17664. BABYLON.Tools.StartPerformanceCounter("Main render");
  17665. // Activate HighlightLayer stencil
  17666. var stencilState = this._engine.getStencilBuffer();
  17667. var renderhighlights = false;
  17668. if (this.highlightLayers && this.highlightLayers.length > 0) {
  17669. for (var i = 0; i < this.highlightLayers.length; i++) {
  17670. if (this.highlightLayers[i].shouldRender()) {
  17671. renderhighlights = true;
  17672. this._engine.setStencilBuffer(true);
  17673. break;
  17674. }
  17675. }
  17676. }
  17677. this._renderingManager.render(null, null, true, true);
  17678. // Restore HighlightLayer stencil
  17679. if (renderhighlights) {
  17680. this._engine.setStencilBuffer(stencilState);
  17681. }
  17682. BABYLON.Tools.EndPerformanceCounter("Main render");
  17683. // Bounding boxes
  17684. this._boundingBoxRenderer.render();
  17685. // Edges
  17686. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  17687. this._edgesRenderers.data[edgesRendererIndex].render();
  17688. }
  17689. // Lens flares
  17690. if (this.lensFlaresEnabled) {
  17691. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  17692. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  17693. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  17694. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  17695. lensFlareSystem.render();
  17696. }
  17697. }
  17698. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  17699. }
  17700. // Foregrounds
  17701. if (this.layers.length) {
  17702. engine.setDepthBuffer(false);
  17703. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  17704. layer = this.layers[layerIndex];
  17705. if (!layer.isBackground) {
  17706. layer.render();
  17707. }
  17708. }
  17709. engine.setDepthBuffer(true);
  17710. }
  17711. // Highlight Layer
  17712. if (renderhighlights) {
  17713. engine.setDepthBuffer(false);
  17714. for (var i = 0; i < this.highlightLayers.length; i++) {
  17715. if (this.highlightLayers[i].shouldRender()) {
  17716. this.highlightLayers[i].render();
  17717. }
  17718. }
  17719. engine.setDepthBuffer(true);
  17720. }
  17721. this._renderDuration.endMonitoring(false);
  17722. // Finalize frame
  17723. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  17724. // Update camera
  17725. this.activeCamera._updateFromScene();
  17726. // Reset some special arrays
  17727. this._renderTargets.reset();
  17728. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  17729. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  17730. };
  17731. Scene.prototype._processSubCameras = function (camera) {
  17732. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  17733. this._renderForCamera(camera);
  17734. return;
  17735. }
  17736. // rig cameras
  17737. for (var index = 0; index < camera._rigCameras.length; index++) {
  17738. this._renderForCamera(camera._rigCameras[index]);
  17739. }
  17740. this.activeCamera = camera;
  17741. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  17742. // Update camera
  17743. this.activeCamera._updateFromScene();
  17744. };
  17745. Scene.prototype._checkIntersections = function () {
  17746. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  17747. var sourceMesh = this._meshesForIntersections.data[index];
  17748. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  17749. var action = sourceMesh.actionManager.actions[actionIndex];
  17750. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  17751. var parameters = action.getTriggerParameter();
  17752. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  17753. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  17754. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  17755. if (areIntersecting && currentIntersectionInProgress === -1) {
  17756. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  17757. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  17758. sourceMesh._intersectionsInProgress.push(otherMesh);
  17759. }
  17760. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  17761. sourceMesh._intersectionsInProgress.push(otherMesh);
  17762. }
  17763. }
  17764. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  17765. //They intersected, and now they don't.
  17766. //is this trigger an exit trigger? execute an event.
  17767. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  17768. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  17769. }
  17770. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  17771. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  17772. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  17773. }
  17774. }
  17775. }
  17776. }
  17777. }
  17778. };
  17779. Scene.prototype.render = function () {
  17780. this._lastFrameDuration.beginMonitoring();
  17781. this._particlesDuration.fetchNewFrame();
  17782. this._spritesDuration.fetchNewFrame();
  17783. this._activeParticles.fetchNewFrame();
  17784. this._renderDuration.fetchNewFrame();
  17785. this._renderTargetsDuration.fetchNewFrame();
  17786. this._evaluateActiveMeshesDuration.fetchNewFrame();
  17787. this._totalVertices.fetchNewFrame();
  17788. this._activeIndices.fetchNewFrame();
  17789. this._activeBones.fetchNewFrame();
  17790. this.getEngine().drawCallsPerfCounter.fetchNewFrame();
  17791. this._meshesForIntersections.reset();
  17792. this.resetCachedMaterial();
  17793. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  17794. // Actions
  17795. if (this.actionManager) {
  17796. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  17797. }
  17798. //Simplification Queue
  17799. if (this.simplificationQueue && !this.simplificationQueue.running) {
  17800. this.simplificationQueue.executeNext();
  17801. }
  17802. // Animations
  17803. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  17804. this._animationRatio = deltaTime * (60.0 / 1000.0);
  17805. this._animate();
  17806. // Physics
  17807. if (this._physicsEngine) {
  17808. BABYLON.Tools.StartPerformanceCounter("Physics");
  17809. this._physicsEngine._step(deltaTime / 1000.0);
  17810. BABYLON.Tools.EndPerformanceCounter("Physics");
  17811. }
  17812. // Before render
  17813. this.onBeforeRenderObservable.notifyObservers(this);
  17814. // Customs render targets
  17815. this._renderTargetsDuration.beginMonitoring();
  17816. var beforeRenderTargetDate = BABYLON.Tools.Now;
  17817. var engine = this.getEngine();
  17818. var currentActiveCamera = this.activeCamera;
  17819. if (this.renderTargetsEnabled) {
  17820. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  17821. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  17822. var renderTarget = this.customRenderTargets[customIndex];
  17823. if (renderTarget._shouldRender()) {
  17824. this._renderId++;
  17825. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  17826. if (!this.activeCamera)
  17827. throw new Error("Active camera not set");
  17828. // Viewport
  17829. engine.setViewport(this.activeCamera.viewport);
  17830. // Camera
  17831. this.updateTransformMatrix();
  17832. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  17833. }
  17834. }
  17835. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  17836. this._renderId++;
  17837. }
  17838. if (this.customRenderTargets.length > 0) {
  17839. engine.restoreDefaultFramebuffer();
  17840. }
  17841. this._renderTargetsDuration.endMonitoring();
  17842. this.activeCamera = currentActiveCamera;
  17843. // Procedural textures
  17844. if (this.proceduralTexturesEnabled) {
  17845. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  17846. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  17847. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  17848. if (proceduralTexture._shouldRender()) {
  17849. proceduralTexture.render();
  17850. }
  17851. }
  17852. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  17853. }
  17854. // Clear
  17855. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true, true);
  17856. // Shadows
  17857. if (this.shadowsEnabled) {
  17858. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  17859. var light = this.lights[lightIndex];
  17860. var shadowGenerator = light.getShadowGenerator();
  17861. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  17862. this._renderTargets.push(shadowGenerator.getShadowMap());
  17863. }
  17864. }
  17865. }
  17866. // Depth renderer
  17867. if (this._depthRenderer) {
  17868. this._renderTargets.push(this._depthRenderer.getDepthMap());
  17869. }
  17870. // HighlightLayer
  17871. if (this.highlightLayers && this.highlightLayers.length > 0) {
  17872. for (var i = 0; i < this.highlightLayers.length; i++) {
  17873. if (this.highlightLayers[i].shouldRender()) {
  17874. this._renderTargets.push(this.highlightLayers[i]._mainTexture);
  17875. }
  17876. }
  17877. }
  17878. // RenderPipeline
  17879. this.postProcessRenderPipelineManager.update();
  17880. // Multi-cameras?
  17881. if (this.activeCameras.length > 0) {
  17882. var currentRenderId = this._renderId;
  17883. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  17884. this._renderId = currentRenderId;
  17885. if (cameraIndex > 0) {
  17886. this._engine.clear(0, false, true, true);
  17887. }
  17888. this._processSubCameras(this.activeCameras[cameraIndex]);
  17889. }
  17890. }
  17891. else {
  17892. if (!this.activeCamera) {
  17893. throw new Error("No camera defined");
  17894. }
  17895. this._processSubCameras(this.activeCamera);
  17896. }
  17897. // Intersection checks
  17898. this._checkIntersections();
  17899. // Update the audio listener attached to the camera
  17900. if (BABYLON.AudioEngine) {
  17901. this._updateAudioParameters();
  17902. }
  17903. // After render
  17904. if (this.afterRender) {
  17905. this.afterRender();
  17906. }
  17907. this.onAfterRenderObservable.notifyObservers(this);
  17908. // Cleaning
  17909. for (var index = 0; index < this._toBeDisposed.length; index++) {
  17910. this._toBeDisposed.data[index].dispose();
  17911. this._toBeDisposed[index] = null;
  17912. }
  17913. this._toBeDisposed.reset();
  17914. if (this.dumpNextRenderTargets) {
  17915. this.dumpNextRenderTargets = false;
  17916. }
  17917. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  17918. this._lastFrameDuration.endMonitoring();
  17919. this._totalMeshesCounter.addCount(this.meshes.length, true);
  17920. this._totalLightsCounter.addCount(this.lights.length, true);
  17921. this._totalMaterialsCounter.addCount(this.materials.length, true);
  17922. this._totalTexturesCounter.addCount(this.textures.length, true);
  17923. this._activeBones.addCount(0, true);
  17924. this._activeIndices.addCount(0, true);
  17925. this._activeParticles.addCount(0, true);
  17926. };
  17927. Scene.prototype._updateAudioParameters = function () {
  17928. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  17929. return;
  17930. }
  17931. var listeningCamera;
  17932. var audioEngine = BABYLON.Engine.audioEngine;
  17933. if (this.activeCameras.length > 0) {
  17934. listeningCamera = this.activeCameras[0];
  17935. }
  17936. else {
  17937. listeningCamera = this.activeCamera;
  17938. }
  17939. if (listeningCamera && audioEngine.canUseWebAudio) {
  17940. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  17941. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  17942. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  17943. cameraDirection.normalize();
  17944. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  17945. var i;
  17946. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  17947. var sound = this.mainSoundTrack.soundCollection[i];
  17948. if (sound.useCustomAttenuation) {
  17949. sound.updateDistanceFromListener();
  17950. }
  17951. }
  17952. for (i = 0; i < this.soundTracks.length; i++) {
  17953. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  17954. sound = this.soundTracks[i].soundCollection[j];
  17955. if (sound.useCustomAttenuation) {
  17956. sound.updateDistanceFromListener();
  17957. }
  17958. }
  17959. }
  17960. }
  17961. };
  17962. Object.defineProperty(Scene.prototype, "audioEnabled", {
  17963. // Audio
  17964. get: function () {
  17965. return this._audioEnabled;
  17966. },
  17967. set: function (value) {
  17968. this._audioEnabled = value;
  17969. if (BABYLON.AudioEngine) {
  17970. if (this._audioEnabled) {
  17971. this._enableAudio();
  17972. }
  17973. else {
  17974. this._disableAudio();
  17975. }
  17976. }
  17977. },
  17978. enumerable: true,
  17979. configurable: true
  17980. });
  17981. Scene.prototype._disableAudio = function () {
  17982. var i;
  17983. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  17984. this.mainSoundTrack.soundCollection[i].pause();
  17985. }
  17986. for (i = 0; i < this.soundTracks.length; i++) {
  17987. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  17988. this.soundTracks[i].soundCollection[j].pause();
  17989. }
  17990. }
  17991. };
  17992. Scene.prototype._enableAudio = function () {
  17993. var i;
  17994. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  17995. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  17996. this.mainSoundTrack.soundCollection[i].play();
  17997. }
  17998. }
  17999. for (i = 0; i < this.soundTracks.length; i++) {
  18000. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  18001. if (this.soundTracks[i].soundCollection[j].isPaused) {
  18002. this.soundTracks[i].soundCollection[j].play();
  18003. }
  18004. }
  18005. }
  18006. };
  18007. Object.defineProperty(Scene.prototype, "headphone", {
  18008. get: function () {
  18009. return this._headphone;
  18010. },
  18011. set: function (value) {
  18012. this._headphone = value;
  18013. if (BABYLON.AudioEngine) {
  18014. if (this._headphone) {
  18015. this._switchAudioModeForHeadphones();
  18016. }
  18017. else {
  18018. this._switchAudioModeForNormalSpeakers();
  18019. }
  18020. }
  18021. },
  18022. enumerable: true,
  18023. configurable: true
  18024. });
  18025. Scene.prototype._switchAudioModeForHeadphones = function () {
  18026. this.mainSoundTrack.switchPanningModelToHRTF();
  18027. for (var i = 0; i < this.soundTracks.length; i++) {
  18028. this.soundTracks[i].switchPanningModelToHRTF();
  18029. }
  18030. };
  18031. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  18032. this.mainSoundTrack.switchPanningModelToEqualPower();
  18033. for (var i = 0; i < this.soundTracks.length; i++) {
  18034. this.soundTracks[i].switchPanningModelToEqualPower();
  18035. }
  18036. };
  18037. Scene.prototype.enableDepthRenderer = function () {
  18038. if (this._depthRenderer) {
  18039. return this._depthRenderer;
  18040. }
  18041. this._depthRenderer = new BABYLON.DepthRenderer(this);
  18042. return this._depthRenderer;
  18043. };
  18044. Scene.prototype.disableDepthRenderer = function () {
  18045. if (!this._depthRenderer) {
  18046. return;
  18047. }
  18048. this._depthRenderer.dispose();
  18049. this._depthRenderer = null;
  18050. };
  18051. Scene.prototype.freezeMaterials = function () {
  18052. for (var i = 0; i < this.materials.length; i++) {
  18053. this.materials[i].freeze();
  18054. }
  18055. };
  18056. Scene.prototype.unfreezeMaterials = function () {
  18057. for (var i = 0; i < this.materials.length; i++) {
  18058. this.materials[i].unfreeze();
  18059. }
  18060. };
  18061. Scene.prototype.dispose = function () {
  18062. this.beforeRender = null;
  18063. this.afterRender = null;
  18064. this.skeletons = [];
  18065. this._boundingBoxRenderer.dispose();
  18066. if (this._depthRenderer) {
  18067. this._depthRenderer.dispose();
  18068. }
  18069. // Debug layer
  18070. if (this._debugLayer) {
  18071. this._debugLayer.hide();
  18072. }
  18073. // Events
  18074. this.onDisposeObservable.notifyObservers(this);
  18075. this.onDisposeObservable.clear();
  18076. this.onBeforeRenderObservable.clear();
  18077. this.onAfterRenderObservable.clear();
  18078. this.detachControl();
  18079. // Release sounds & sounds tracks
  18080. if (BABYLON.AudioEngine) {
  18081. this.disposeSounds();
  18082. }
  18083. // Detach cameras
  18084. var canvas = this._engine.getRenderingCanvas();
  18085. var index;
  18086. for (index = 0; index < this.cameras.length; index++) {
  18087. this.cameras[index].detachControl(canvas);
  18088. }
  18089. // Release lights
  18090. while (this.lights.length) {
  18091. this.lights[0].dispose();
  18092. }
  18093. // Release meshes
  18094. while (this.meshes.length) {
  18095. this.meshes[0].dispose(true);
  18096. }
  18097. // Release cameras
  18098. while (this.cameras.length) {
  18099. this.cameras[0].dispose();
  18100. }
  18101. // Release materials
  18102. while (this.materials.length) {
  18103. this.materials[0].dispose();
  18104. }
  18105. // Release particles
  18106. while (this.particleSystems.length) {
  18107. this.particleSystems[0].dispose();
  18108. }
  18109. // Release sprites
  18110. while (this.spriteManagers.length) {
  18111. this.spriteManagers[0].dispose();
  18112. }
  18113. // Release layers
  18114. while (this.layers.length) {
  18115. this.layers[0].dispose();
  18116. }
  18117. while (this.highlightLayers.length) {
  18118. this.highlightLayers[0].dispose();
  18119. }
  18120. // Release textures
  18121. while (this.textures.length) {
  18122. this.textures[0].dispose();
  18123. }
  18124. // Post-processes
  18125. this.postProcessManager.dispose();
  18126. // Physics
  18127. if (this._physicsEngine) {
  18128. this.disablePhysicsEngine();
  18129. }
  18130. // Remove from engine
  18131. index = this._engine.scenes.indexOf(this);
  18132. if (index > -1) {
  18133. this._engine.scenes.splice(index, 1);
  18134. }
  18135. this._engine.wipeCaches();
  18136. };
  18137. // Release sounds & sounds tracks
  18138. Scene.prototype.disposeSounds = function () {
  18139. this.mainSoundTrack.dispose();
  18140. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  18141. this.soundTracks[scIndex].dispose();
  18142. }
  18143. };
  18144. // Octrees
  18145. Scene.prototype.getWorldExtends = function () {
  18146. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  18147. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  18148. for (var index = 0; index < this.meshes.length; index++) {
  18149. var mesh = this.meshes[index];
  18150. mesh.computeWorldMatrix(true);
  18151. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  18152. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  18153. BABYLON.Tools.CheckExtends(minBox, min, max);
  18154. BABYLON.Tools.CheckExtends(maxBox, min, max);
  18155. }
  18156. return {
  18157. min: min,
  18158. max: max
  18159. };
  18160. };
  18161. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  18162. if (maxCapacity === void 0) { maxCapacity = 64; }
  18163. if (maxDepth === void 0) { maxDepth = 2; }
  18164. if (!this._selectionOctree) {
  18165. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  18166. }
  18167. var worldExtends = this.getWorldExtends();
  18168. // Update octree
  18169. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  18170. return this._selectionOctree;
  18171. };
  18172. // Picking
  18173. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  18174. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  18175. var engine = this._engine;
  18176. if (!camera) {
  18177. if (!this.activeCamera)
  18178. throw new Error("Active camera not set");
  18179. camera = this.activeCamera;
  18180. }
  18181. var cameraViewport = camera.viewport;
  18182. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  18183. // Moving coordinates to local viewport world
  18184. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  18185. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  18186. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  18187. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  18188. };
  18189. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  18190. var engine = this._engine;
  18191. if (!camera) {
  18192. if (!this.activeCamera)
  18193. throw new Error("Active camera not set");
  18194. camera = this.activeCamera;
  18195. }
  18196. var cameraViewport = camera.viewport;
  18197. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  18198. var identity = BABYLON.Matrix.Identity();
  18199. // Moving coordinates to local viewport world
  18200. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  18201. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  18202. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  18203. };
  18204. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  18205. var pickingInfo = null;
  18206. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  18207. var mesh = this.meshes[meshIndex];
  18208. if (predicate) {
  18209. if (!predicate(mesh)) {
  18210. continue;
  18211. }
  18212. }
  18213. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  18214. continue;
  18215. }
  18216. var world = mesh.getWorldMatrix();
  18217. var ray = rayFunction(world);
  18218. var result = mesh.intersects(ray, fastCheck);
  18219. if (!result || !result.hit)
  18220. continue;
  18221. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  18222. continue;
  18223. pickingInfo = result;
  18224. if (fastCheck) {
  18225. break;
  18226. }
  18227. }
  18228. return pickingInfo || new BABYLON.PickingInfo();
  18229. };
  18230. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  18231. var pickingInfo = null;
  18232. camera = camera || this.activeCamera;
  18233. if (this.spriteManagers.length > 0) {
  18234. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  18235. var spriteManager = this.spriteManagers[spriteIndex];
  18236. if (!spriteManager.isPickable) {
  18237. continue;
  18238. }
  18239. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  18240. if (!result || !result.hit)
  18241. continue;
  18242. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  18243. continue;
  18244. pickingInfo = result;
  18245. if (fastCheck) {
  18246. break;
  18247. }
  18248. }
  18249. }
  18250. return pickingInfo || new BABYLON.PickingInfo();
  18251. };
  18252. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  18253. var _this = this;
  18254. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  18255. /// <param name="x">X position on screen</param>
  18256. /// <param name="y">Y position on screen</param>
  18257. /// <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>
  18258. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  18259. /// <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>
  18260. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  18261. };
  18262. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  18263. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  18264. /// <param name="x">X position on screen</param>
  18265. /// <param name="y">Y position on screen</param>
  18266. /// <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>
  18267. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  18268. /// <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>
  18269. return this._internalPickSprites(this.createPickingRayInCameraSpace(x, y, camera), predicate, fastCheck, camera);
  18270. };
  18271. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  18272. var _this = this;
  18273. return this._internalPick(function (world) {
  18274. if (!_this._pickWithRayInverseMatrix) {
  18275. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  18276. }
  18277. world.invertToRef(_this._pickWithRayInverseMatrix);
  18278. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  18279. }, predicate, fastCheck);
  18280. };
  18281. Scene.prototype.setPointerOverMesh = function (mesh) {
  18282. if (this._pointerOverMesh === mesh) {
  18283. return;
  18284. }
  18285. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  18286. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  18287. }
  18288. this._pointerOverMesh = mesh;
  18289. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  18290. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  18291. }
  18292. };
  18293. Scene.prototype.getPointerOverMesh = function () {
  18294. return this._pointerOverMesh;
  18295. };
  18296. Scene.prototype.setPointerOverSprite = function (sprite) {
  18297. if (this._pointerOverSprite === sprite) {
  18298. return;
  18299. }
  18300. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  18301. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  18302. }
  18303. this._pointerOverSprite = sprite;
  18304. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  18305. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  18306. }
  18307. };
  18308. Scene.prototype.getPointerOverSprite = function () {
  18309. return this._pointerOverSprite;
  18310. };
  18311. // Physics
  18312. Scene.prototype.getPhysicsEngine = function () {
  18313. return this._physicsEngine;
  18314. };
  18315. /**
  18316. * Enables physics to the current scene
  18317. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  18318. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  18319. * @return {boolean} was the physics engine initialized
  18320. */
  18321. Scene.prototype.enablePhysics = function (gravity, plugin) {
  18322. if (this._physicsEngine) {
  18323. return true;
  18324. }
  18325. try {
  18326. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  18327. return true;
  18328. }
  18329. catch (e) {
  18330. BABYLON.Tools.Error(e.message);
  18331. return false;
  18332. }
  18333. };
  18334. Scene.prototype.disablePhysicsEngine = function () {
  18335. if (!this._physicsEngine) {
  18336. return;
  18337. }
  18338. this._physicsEngine.dispose();
  18339. this._physicsEngine = undefined;
  18340. };
  18341. Scene.prototype.isPhysicsEnabled = function () {
  18342. return this._physicsEngine !== undefined;
  18343. };
  18344. /**
  18345. *
  18346. * Sets the gravity of the physics engine (and NOT of the scene)
  18347. * @param {BABYLON.Vector3} [gravity] - the new gravity to be used
  18348. */
  18349. Scene.prototype.setGravity = function (gravity) {
  18350. BABYLON.Tools.Warn("Deprecated, please use 'scene.getPhysicsEngine().setGravity()'");
  18351. if (!this._physicsEngine) {
  18352. return;
  18353. }
  18354. this._physicsEngine.setGravity(gravity);
  18355. };
  18356. /**
  18357. * Legacy support, using the new API
  18358. * @Deprecated
  18359. */
  18360. Scene.prototype.createCompoundImpostor = function (parts, options) {
  18361. BABYLON.Tools.Warn("Scene.createCompoundImpostor is deprecated. Please use PhysicsImpostor parent/child");
  18362. if (parts.parts) {
  18363. options = parts;
  18364. parts = parts.parts;
  18365. }
  18366. var mainMesh = parts[0].mesh;
  18367. mainMesh.physicsImpostor = new BABYLON.PhysicsImpostor(mainMesh, parts[0].impostor, options, this);
  18368. for (var index = 1; index < parts.length; index++) {
  18369. var mesh = parts[index].mesh;
  18370. if (mesh.parent !== mainMesh) {
  18371. mesh.position = mesh.position.subtract(mainMesh.position);
  18372. mesh.parent = mainMesh;
  18373. }
  18374. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parts[index].impostor, options, this);
  18375. }
  18376. mainMesh.physicsImpostor.forceUpdate();
  18377. };
  18378. Scene.prototype.deleteCompoundImpostor = function (compound) {
  18379. var mesh = compound.parts[0].mesh;
  18380. mesh.physicsImpostor.dispose();
  18381. mesh.physicsImpostor = null;
  18382. };
  18383. // Misc.
  18384. Scene.prototype.createDefaultCameraOrLight = function () {
  18385. // Light
  18386. if (this.lights.length === 0) {
  18387. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  18388. }
  18389. // Camera
  18390. if (!this.activeCamera) {
  18391. var camera = new BABYLON.FreeCamera("default camera", BABYLON.Vector3.Zero(), this);
  18392. // Compute position
  18393. var worldExtends = this.getWorldExtends();
  18394. var worldCenter = worldExtends.min.add(worldExtends.max.subtract(worldExtends.min).scale(0.5));
  18395. camera.position = new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z));
  18396. camera.setTarget(worldCenter);
  18397. this.activeCamera = camera;
  18398. }
  18399. };
  18400. // Tags
  18401. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  18402. if (tagsQuery === undefined) {
  18403. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  18404. return list;
  18405. }
  18406. var listByTags = [];
  18407. forEach = forEach || (function (item) { return; });
  18408. for (var i in list) {
  18409. var item = list[i];
  18410. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  18411. listByTags.push(item);
  18412. forEach(item);
  18413. }
  18414. }
  18415. return listByTags;
  18416. };
  18417. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  18418. return this._getByTags(this.meshes, tagsQuery, forEach);
  18419. };
  18420. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  18421. return this._getByTags(this.cameras, tagsQuery, forEach);
  18422. };
  18423. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  18424. return this._getByTags(this.lights, tagsQuery, forEach);
  18425. };
  18426. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  18427. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  18428. };
  18429. /**
  18430. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  18431. * This allowed control for front to back rendering or reversly depending of the special needs.
  18432. *
  18433. * @param renderingGroupId The rendering group id corresponding to its index
  18434. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  18435. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  18436. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  18437. */
  18438. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  18439. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  18440. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  18441. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  18442. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  18443. };
  18444. /**
  18445. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  18446. *
  18447. * @param renderingGroupId The rendering group id corresponding to its index
  18448. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  18449. */
  18450. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  18451. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  18452. };
  18453. // Statics
  18454. Scene._FOGMODE_NONE = 0;
  18455. Scene._FOGMODE_EXP = 1;
  18456. Scene._FOGMODE_EXP2 = 2;
  18457. Scene._FOGMODE_LINEAR = 3;
  18458. Scene.MinDeltaTime = 1.0;
  18459. Scene.MaxDeltaTime = 1000.0;
  18460. return Scene;
  18461. }());
  18462. BABYLON.Scene = Scene;
  18463. })(BABYLON || (BABYLON = {}));
  18464. var BABYLON;
  18465. (function (BABYLON) {
  18466. var Buffer = (function () {
  18467. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  18468. if (engine instanceof BABYLON.Mesh) {
  18469. this._engine = engine.getScene().getEngine();
  18470. }
  18471. else {
  18472. this._engine = engine;
  18473. }
  18474. this._updatable = updatable;
  18475. this._data = data;
  18476. this._strideSize = stride;
  18477. if (!postponeInternalCreation) {
  18478. this.create();
  18479. }
  18480. this._instanced = instanced;
  18481. }
  18482. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride) {
  18483. // a lot of these parameters are ignored as they are overriden by the buffer
  18484. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, this._instanced, offset, size);
  18485. };
  18486. // Properties
  18487. Buffer.prototype.isUpdatable = function () {
  18488. return this._updatable;
  18489. };
  18490. Buffer.prototype.getData = function () {
  18491. return this._data;
  18492. };
  18493. Buffer.prototype.getBuffer = function () {
  18494. return this._buffer;
  18495. };
  18496. Buffer.prototype.getStrideSize = function () {
  18497. return this._strideSize;
  18498. };
  18499. Buffer.prototype.getIsInstanced = function () {
  18500. return this._instanced;
  18501. };
  18502. // Methods
  18503. Buffer.prototype.create = function (data) {
  18504. if (!data && this._buffer) {
  18505. return; // nothing to do
  18506. }
  18507. data = data || this._data;
  18508. if (!this._buffer) {
  18509. if (this._updatable) {
  18510. this._buffer = this._engine.createDynamicVertexBuffer(data);
  18511. this._data = data;
  18512. }
  18513. else {
  18514. this._buffer = this._engine.createVertexBuffer(data);
  18515. }
  18516. }
  18517. else if (this._updatable) {
  18518. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  18519. this._data = data;
  18520. }
  18521. };
  18522. Buffer.prototype.update = function (data) {
  18523. this.create(data);
  18524. };
  18525. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  18526. if (!this._buffer) {
  18527. return;
  18528. }
  18529. if (this._updatable) {
  18530. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  18531. this._data = null;
  18532. }
  18533. };
  18534. Buffer.prototype.dispose = function () {
  18535. if (!this._buffer) {
  18536. return;
  18537. }
  18538. if (this._engine._releaseBuffer(this._buffer)) {
  18539. this._buffer = null;
  18540. }
  18541. };
  18542. return Buffer;
  18543. }());
  18544. BABYLON.Buffer = Buffer;
  18545. })(BABYLON || (BABYLON = {}));
  18546. var BABYLON;
  18547. (function (BABYLON) {
  18548. var VertexBuffer = (function () {
  18549. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  18550. if (!stride) {
  18551. // Deduce stride from kind
  18552. switch (kind) {
  18553. case VertexBuffer.PositionKind:
  18554. stride = 3;
  18555. break;
  18556. case VertexBuffer.NormalKind:
  18557. stride = 3;
  18558. break;
  18559. case VertexBuffer.UVKind:
  18560. case VertexBuffer.UV2Kind:
  18561. case VertexBuffer.UV3Kind:
  18562. case VertexBuffer.UV4Kind:
  18563. case VertexBuffer.UV5Kind:
  18564. case VertexBuffer.UV6Kind:
  18565. stride = 2;
  18566. break;
  18567. case VertexBuffer.ColorKind:
  18568. stride = 4;
  18569. break;
  18570. case VertexBuffer.MatricesIndicesKind:
  18571. case VertexBuffer.MatricesIndicesExtraKind:
  18572. stride = 4;
  18573. break;
  18574. case VertexBuffer.MatricesWeightsKind:
  18575. case VertexBuffer.MatricesWeightsExtraKind:
  18576. stride = 4;
  18577. break;
  18578. }
  18579. }
  18580. if (data instanceof BABYLON.Buffer) {
  18581. if (!stride) {
  18582. stride = data.getStrideSize();
  18583. }
  18584. this._buffer = data;
  18585. this._ownsBuffer = false;
  18586. }
  18587. else {
  18588. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  18589. this._ownsBuffer = true;
  18590. }
  18591. this._stride = stride;
  18592. this._offset = offset ? offset : 0;
  18593. this._size = size ? size : stride;
  18594. this._kind = kind;
  18595. }
  18596. VertexBuffer.prototype.getKind = function () {
  18597. return this._kind;
  18598. };
  18599. // Properties
  18600. VertexBuffer.prototype.isUpdatable = function () {
  18601. return this._buffer.isUpdatable();
  18602. };
  18603. VertexBuffer.prototype.getData = function () {
  18604. return this._buffer.getData();
  18605. };
  18606. VertexBuffer.prototype.getBuffer = function () {
  18607. return this._buffer.getBuffer();
  18608. };
  18609. VertexBuffer.prototype.getStrideSize = function () {
  18610. return this._stride;
  18611. };
  18612. VertexBuffer.prototype.getOffset = function () {
  18613. return this._offset;
  18614. };
  18615. VertexBuffer.prototype.getSize = function () {
  18616. return this._size;
  18617. };
  18618. VertexBuffer.prototype.getIsInstanced = function () {
  18619. return this._buffer.getIsInstanced();
  18620. };
  18621. // Methods
  18622. VertexBuffer.prototype.create = function (data) {
  18623. return this._buffer.create(data);
  18624. };
  18625. VertexBuffer.prototype.update = function (data) {
  18626. return this._buffer.update(data);
  18627. };
  18628. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  18629. return this._buffer.updateDirectly(data, offset);
  18630. };
  18631. VertexBuffer.prototype.dispose = function () {
  18632. if (this._ownsBuffer) {
  18633. this._buffer.dispose();
  18634. }
  18635. };
  18636. Object.defineProperty(VertexBuffer, "PositionKind", {
  18637. get: function () {
  18638. return VertexBuffer._PositionKind;
  18639. },
  18640. enumerable: true,
  18641. configurable: true
  18642. });
  18643. Object.defineProperty(VertexBuffer, "NormalKind", {
  18644. get: function () {
  18645. return VertexBuffer._NormalKind;
  18646. },
  18647. enumerable: true,
  18648. configurable: true
  18649. });
  18650. Object.defineProperty(VertexBuffer, "UVKind", {
  18651. get: function () {
  18652. return VertexBuffer._UVKind;
  18653. },
  18654. enumerable: true,
  18655. configurable: true
  18656. });
  18657. Object.defineProperty(VertexBuffer, "UV2Kind", {
  18658. get: function () {
  18659. return VertexBuffer._UV2Kind;
  18660. },
  18661. enumerable: true,
  18662. configurable: true
  18663. });
  18664. Object.defineProperty(VertexBuffer, "UV3Kind", {
  18665. get: function () {
  18666. return VertexBuffer._UV3Kind;
  18667. },
  18668. enumerable: true,
  18669. configurable: true
  18670. });
  18671. Object.defineProperty(VertexBuffer, "UV4Kind", {
  18672. get: function () {
  18673. return VertexBuffer._UV4Kind;
  18674. },
  18675. enumerable: true,
  18676. configurable: true
  18677. });
  18678. Object.defineProperty(VertexBuffer, "UV5Kind", {
  18679. get: function () {
  18680. return VertexBuffer._UV5Kind;
  18681. },
  18682. enumerable: true,
  18683. configurable: true
  18684. });
  18685. Object.defineProperty(VertexBuffer, "UV6Kind", {
  18686. get: function () {
  18687. return VertexBuffer._UV6Kind;
  18688. },
  18689. enumerable: true,
  18690. configurable: true
  18691. });
  18692. Object.defineProperty(VertexBuffer, "ColorKind", {
  18693. get: function () {
  18694. return VertexBuffer._ColorKind;
  18695. },
  18696. enumerable: true,
  18697. configurable: true
  18698. });
  18699. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  18700. get: function () {
  18701. return VertexBuffer._MatricesIndicesKind;
  18702. },
  18703. enumerable: true,
  18704. configurable: true
  18705. });
  18706. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  18707. get: function () {
  18708. return VertexBuffer._MatricesWeightsKind;
  18709. },
  18710. enumerable: true,
  18711. configurable: true
  18712. });
  18713. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  18714. get: function () {
  18715. return VertexBuffer._MatricesIndicesExtraKind;
  18716. },
  18717. enumerable: true,
  18718. configurable: true
  18719. });
  18720. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  18721. get: function () {
  18722. return VertexBuffer._MatricesWeightsExtraKind;
  18723. },
  18724. enumerable: true,
  18725. configurable: true
  18726. });
  18727. // Enums
  18728. VertexBuffer._PositionKind = "position";
  18729. VertexBuffer._NormalKind = "normal";
  18730. VertexBuffer._UVKind = "uv";
  18731. VertexBuffer._UV2Kind = "uv2";
  18732. VertexBuffer._UV3Kind = "uv3";
  18733. VertexBuffer._UV4Kind = "uv4";
  18734. VertexBuffer._UV5Kind = "uv5";
  18735. VertexBuffer._UV6Kind = "uv6";
  18736. VertexBuffer._ColorKind = "color";
  18737. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  18738. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  18739. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  18740. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  18741. return VertexBuffer;
  18742. }());
  18743. BABYLON.VertexBuffer = VertexBuffer;
  18744. })(BABYLON || (BABYLON = {}));
  18745. var BABYLON;
  18746. (function (BABYLON) {
  18747. /**
  18748. * Creates an instance based on a source mesh.
  18749. */
  18750. var InstancedMesh = (function (_super) {
  18751. __extends(InstancedMesh, _super);
  18752. function InstancedMesh(name, source) {
  18753. _super.call(this, name, source.getScene());
  18754. source.instances.push(this);
  18755. this._sourceMesh = source;
  18756. this.position.copyFrom(source.position);
  18757. this.rotation.copyFrom(source.rotation);
  18758. this.scaling.copyFrom(source.scaling);
  18759. if (source.rotationQuaternion) {
  18760. this.rotationQuaternion = source.rotationQuaternion.clone();
  18761. }
  18762. this.infiniteDistance = source.infiniteDistance;
  18763. this.setPivotMatrix(source.getPivotMatrix());
  18764. this.refreshBoundingInfo();
  18765. this._syncSubMeshes();
  18766. }
  18767. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  18768. // Methods
  18769. get: function () {
  18770. return this._sourceMesh.receiveShadows;
  18771. },
  18772. enumerable: true,
  18773. configurable: true
  18774. });
  18775. Object.defineProperty(InstancedMesh.prototype, "material", {
  18776. get: function () {
  18777. return this._sourceMesh.material;
  18778. },
  18779. enumerable: true,
  18780. configurable: true
  18781. });
  18782. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  18783. get: function () {
  18784. return this._sourceMesh.visibility;
  18785. },
  18786. enumerable: true,
  18787. configurable: true
  18788. });
  18789. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  18790. get: function () {
  18791. return this._sourceMesh.skeleton;
  18792. },
  18793. enumerable: true,
  18794. configurable: true
  18795. });
  18796. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  18797. get: function () {
  18798. return this._sourceMesh.renderingGroupId;
  18799. },
  18800. enumerable: true,
  18801. configurable: true
  18802. });
  18803. InstancedMesh.prototype.getTotalVertices = function () {
  18804. return this._sourceMesh.getTotalVertices();
  18805. };
  18806. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  18807. get: function () {
  18808. return this._sourceMesh;
  18809. },
  18810. enumerable: true,
  18811. configurable: true
  18812. });
  18813. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  18814. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  18815. };
  18816. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  18817. return this._sourceMesh.isVerticesDataPresent(kind);
  18818. };
  18819. InstancedMesh.prototype.getIndices = function () {
  18820. return this._sourceMesh.getIndices();
  18821. };
  18822. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  18823. get: function () {
  18824. return this._sourceMesh._positions;
  18825. },
  18826. enumerable: true,
  18827. configurable: true
  18828. });
  18829. InstancedMesh.prototype.refreshBoundingInfo = function () {
  18830. var meshBB = this._sourceMesh.getBoundingInfo();
  18831. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  18832. this._updateBoundingInfo();
  18833. };
  18834. InstancedMesh.prototype._preActivate = function () {
  18835. if (this._currentLOD) {
  18836. this._currentLOD._preActivate();
  18837. }
  18838. };
  18839. InstancedMesh.prototype._activate = function (renderId) {
  18840. if (this._currentLOD) {
  18841. this._currentLOD._registerInstanceForRenderId(this, renderId);
  18842. }
  18843. };
  18844. InstancedMesh.prototype.getLOD = function (camera) {
  18845. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  18846. if (this._currentLOD === this.sourceMesh) {
  18847. return this;
  18848. }
  18849. return this._currentLOD;
  18850. };
  18851. InstancedMesh.prototype._syncSubMeshes = function () {
  18852. this.releaseSubMeshes();
  18853. if (this._sourceMesh.subMeshes) {
  18854. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  18855. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  18856. }
  18857. }
  18858. };
  18859. InstancedMesh.prototype._generatePointsArray = function () {
  18860. return this._sourceMesh._generatePointsArray();
  18861. };
  18862. // Clone
  18863. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  18864. var result = this._sourceMesh.createInstance(name);
  18865. // Deep copy
  18866. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes"], []);
  18867. // Bounding info
  18868. this.refreshBoundingInfo();
  18869. // Parent
  18870. if (newParent) {
  18871. result.parent = newParent;
  18872. }
  18873. if (!doNotCloneChildren) {
  18874. // Children
  18875. for (var index = 0; index < this.getScene().meshes.length; index++) {
  18876. var mesh = this.getScene().meshes[index];
  18877. if (mesh.parent === this) {
  18878. mesh.clone(mesh.name, result);
  18879. }
  18880. }
  18881. }
  18882. result.computeWorldMatrix(true);
  18883. return result;
  18884. };
  18885. // Dispoe
  18886. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  18887. // Remove from mesh
  18888. var index = this._sourceMesh.instances.indexOf(this);
  18889. this._sourceMesh.instances.splice(index, 1);
  18890. _super.prototype.dispose.call(this, doNotRecurse);
  18891. };
  18892. return InstancedMesh;
  18893. }(BABYLON.AbstractMesh));
  18894. BABYLON.InstancedMesh = InstancedMesh;
  18895. })(BABYLON || (BABYLON = {}));
  18896. var BABYLON;
  18897. (function (BABYLON) {
  18898. var _InstancesBatch = (function () {
  18899. function _InstancesBatch() {
  18900. this.mustReturn = false;
  18901. this.visibleInstances = new Array();
  18902. this.renderSelf = new Array();
  18903. }
  18904. return _InstancesBatch;
  18905. }());
  18906. BABYLON._InstancesBatch = _InstancesBatch;
  18907. var Mesh = (function (_super) {
  18908. __extends(Mesh, _super);
  18909. /**
  18910. * @constructor
  18911. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  18912. * @param {Scene} scene The scene to add this mesh to.
  18913. * @param {Node} parent The parent of this mesh, if it has one
  18914. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  18915. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  18916. * When false, achieved by calling a clone(), also passing False.
  18917. * This will make creation of children, recursive.
  18918. */
  18919. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  18920. if (parent === void 0) { parent = null; }
  18921. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  18922. _super.call(this, name, scene);
  18923. // Events
  18924. /**
  18925. * An event triggered before rendering the mesh
  18926. * @type {BABYLON.Observable}
  18927. */
  18928. this.onBeforeRenderObservable = new BABYLON.Observable();
  18929. /**
  18930. * An event triggered after rendering the mesh
  18931. * @type {BABYLON.Observable}
  18932. */
  18933. this.onAfterRenderObservable = new BABYLON.Observable();
  18934. /**
  18935. * An event triggered before drawing the mesh
  18936. * @type {BABYLON.Observable}
  18937. */
  18938. this.onBeforeDrawObservable = new BABYLON.Observable();
  18939. // Members
  18940. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  18941. this.instances = new Array();
  18942. this._LODLevels = new Array();
  18943. this._visibleInstances = {};
  18944. this._renderIdForInstances = new Array();
  18945. this._batchCache = new _InstancesBatch();
  18946. this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  18947. this._sideOrientation = Mesh._DEFAULTSIDE;
  18948. this._areNormalsFrozen = false; // Will be used by ribbons mainly
  18949. if (source) {
  18950. // Geometry
  18951. if (source._geometry) {
  18952. source._geometry.applyToMesh(this);
  18953. }
  18954. // Deep copy
  18955. BABYLON.Tools.DeepCopy(source, this, ["name", "material", "skeleton", "instances"], ["_poseMatrix"]);
  18956. // Pivot
  18957. this.setPivotMatrix(source.getPivotMatrix());
  18958. this.id = name + "." + source.id;
  18959. // Material
  18960. this.material = source.material;
  18961. var index;
  18962. if (!doNotCloneChildren) {
  18963. // Children
  18964. for (index = 0; index < scene.meshes.length; index++) {
  18965. var mesh = scene.meshes[index];
  18966. if (mesh.parent === source) {
  18967. // doNotCloneChildren is always going to be False
  18968. var newChild = mesh.clone(name + "." + mesh.name, this, doNotCloneChildren);
  18969. }
  18970. }
  18971. }
  18972. // Physics clone
  18973. var physicsEngine = this.getScene().getPhysicsEngine();
  18974. if (clonePhysicsImpostor && physicsEngine) {
  18975. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  18976. if (impostor) {
  18977. this.physicsImpostor = impostor.clone(this);
  18978. }
  18979. }
  18980. // Particles
  18981. for (index = 0; index < scene.particleSystems.length; index++) {
  18982. var system = scene.particleSystems[index];
  18983. if (system.emitter === source) {
  18984. system.clone(system.name, this);
  18985. }
  18986. }
  18987. this.computeWorldMatrix(true);
  18988. }
  18989. // Parent
  18990. if (parent !== null) {
  18991. this.parent = parent;
  18992. }
  18993. }
  18994. Object.defineProperty(Mesh, "FRONTSIDE", {
  18995. /**
  18996. * Mesh side orientation : usually the external or front surface
  18997. */
  18998. get: function () {
  18999. return Mesh._FRONTSIDE;
  19000. },
  19001. enumerable: true,
  19002. configurable: true
  19003. });
  19004. Object.defineProperty(Mesh, "BACKSIDE", {
  19005. /**
  19006. * Mesh side orientation : usually the internal or back surface
  19007. */
  19008. get: function () {
  19009. return Mesh._BACKSIDE;
  19010. },
  19011. enumerable: true,
  19012. configurable: true
  19013. });
  19014. Object.defineProperty(Mesh, "DOUBLESIDE", {
  19015. /**
  19016. * Mesh side orientation : both internal and external or front and back surfaces
  19017. */
  19018. get: function () {
  19019. return Mesh._DOUBLESIDE;
  19020. },
  19021. enumerable: true,
  19022. configurable: true
  19023. });
  19024. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  19025. /**
  19026. * Mesh side orientation : by default, `FRONTSIDE`
  19027. */
  19028. get: function () {
  19029. return Mesh._DEFAULTSIDE;
  19030. },
  19031. enumerable: true,
  19032. configurable: true
  19033. });
  19034. Object.defineProperty(Mesh, "NO_CAP", {
  19035. /**
  19036. * Mesh cap setting : no cap
  19037. */
  19038. get: function () {
  19039. return Mesh._NO_CAP;
  19040. },
  19041. enumerable: true,
  19042. configurable: true
  19043. });
  19044. Object.defineProperty(Mesh, "CAP_START", {
  19045. /**
  19046. * Mesh cap setting : one cap at the beginning of the mesh
  19047. */
  19048. get: function () {
  19049. return Mesh._CAP_START;
  19050. },
  19051. enumerable: true,
  19052. configurable: true
  19053. });
  19054. Object.defineProperty(Mesh, "CAP_END", {
  19055. /**
  19056. * Mesh cap setting : one cap at the end of the mesh
  19057. */
  19058. get: function () {
  19059. return Mesh._CAP_END;
  19060. },
  19061. enumerable: true,
  19062. configurable: true
  19063. });
  19064. Object.defineProperty(Mesh, "CAP_ALL", {
  19065. /**
  19066. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  19067. */
  19068. get: function () {
  19069. return Mesh._CAP_ALL;
  19070. },
  19071. enumerable: true,
  19072. configurable: true
  19073. });
  19074. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  19075. set: function (callback) {
  19076. if (this._onBeforeDrawObserver) {
  19077. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  19078. }
  19079. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  19080. },
  19081. enumerable: true,
  19082. configurable: true
  19083. });
  19084. // Methods
  19085. /**
  19086. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  19087. */
  19088. Mesh.prototype.toString = function (fullDetails) {
  19089. var ret = _super.prototype.toString.call(this, fullDetails);
  19090. ret += ", n vertices: " + this.getTotalVertices();
  19091. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  19092. if (this.animations) {
  19093. for (var i = 0; i < this.animations.length; i++) {
  19094. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  19095. }
  19096. }
  19097. if (fullDetails) {
  19098. ret += ", flat shading: " + (this._geometry ? (this.getVerticesData(BABYLON.VertexBuffer.PositionKind).length / 3 === this.getIndices().length ? "YES" : "NO") : "UNKNOWN");
  19099. }
  19100. return ret;
  19101. };
  19102. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  19103. get: function () {
  19104. return this._LODLevels.length > 0;
  19105. },
  19106. enumerable: true,
  19107. configurable: true
  19108. });
  19109. Mesh.prototype._sortLODLevels = function () {
  19110. this._LODLevels.sort(function (a, b) {
  19111. if (a.distance < b.distance) {
  19112. return 1;
  19113. }
  19114. if (a.distance > b.distance) {
  19115. return -1;
  19116. }
  19117. return 0;
  19118. });
  19119. };
  19120. /**
  19121. * Add a mesh as LOD level triggered at the given distance.
  19122. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  19123. * @param {number} distance The distance from the center of the object to show this level
  19124. * @param {Mesh} mesh The mesh to be added as LOD level
  19125. * @return {Mesh} This mesh (for chaining)
  19126. */
  19127. Mesh.prototype.addLODLevel = function (distance, mesh) {
  19128. if (mesh && mesh._masterMesh) {
  19129. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  19130. return this;
  19131. }
  19132. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  19133. this._LODLevels.push(level);
  19134. if (mesh) {
  19135. mesh._masterMesh = this;
  19136. }
  19137. this._sortLODLevels();
  19138. return this;
  19139. };
  19140. /**
  19141. * Returns the LOD level mesh at the passed distance or null if not found.
  19142. * It is related to the method `addLODLevel(distance, mesh)`.
  19143. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  19144. */
  19145. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  19146. for (var index = 0; index < this._LODLevels.length; index++) {
  19147. var level = this._LODLevels[index];
  19148. if (level.distance === distance) {
  19149. return level.mesh;
  19150. }
  19151. }
  19152. return null;
  19153. };
  19154. /**
  19155. * Remove a mesh from the LOD array
  19156. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  19157. * @param {Mesh} mesh The mesh to be removed.
  19158. * @return {Mesh} This mesh (for chaining)
  19159. */
  19160. Mesh.prototype.removeLODLevel = function (mesh) {
  19161. for (var index = 0; index < this._LODLevels.length; index++) {
  19162. if (this._LODLevels[index].mesh === mesh) {
  19163. this._LODLevels.splice(index, 1);
  19164. if (mesh) {
  19165. mesh._masterMesh = null;
  19166. }
  19167. }
  19168. }
  19169. this._sortLODLevels();
  19170. return this;
  19171. };
  19172. /**
  19173. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  19174. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  19175. */
  19176. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  19177. if (!this._LODLevels || this._LODLevels.length === 0) {
  19178. return this;
  19179. }
  19180. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.globalPosition).length();
  19181. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  19182. if (this.onLODLevelSelection) {
  19183. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  19184. }
  19185. return this;
  19186. }
  19187. for (var index = 0; index < this._LODLevels.length; index++) {
  19188. var level = this._LODLevels[index];
  19189. if (level.distance < distanceToCamera) {
  19190. if (level.mesh) {
  19191. level.mesh._preActivate();
  19192. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  19193. }
  19194. if (this.onLODLevelSelection) {
  19195. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  19196. }
  19197. return level.mesh;
  19198. }
  19199. }
  19200. if (this.onLODLevelSelection) {
  19201. this.onLODLevelSelection(distanceToCamera, this, this);
  19202. }
  19203. return this;
  19204. };
  19205. Object.defineProperty(Mesh.prototype, "geometry", {
  19206. /**
  19207. * Returns the mesh internal Geometry object.
  19208. */
  19209. get: function () {
  19210. return this._geometry;
  19211. },
  19212. enumerable: true,
  19213. configurable: true
  19214. });
  19215. /**
  19216. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  19217. */
  19218. Mesh.prototype.getTotalVertices = function () {
  19219. if (!this._geometry) {
  19220. return 0;
  19221. }
  19222. return this._geometry.getTotalVertices();
  19223. };
  19224. /**
  19225. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  19226. * 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.
  19227. * Returns null if the mesh has no geometry or no vertex buffer.
  19228. * Possible `kind` values :
  19229. * - BABYLON.VertexBuffer.PositionKind
  19230. * - BABYLON.VertexBuffer.UVKind
  19231. * - BABYLON.VertexBuffer.UV2Kind
  19232. * - BABYLON.VertexBuffer.UV3Kind
  19233. * - BABYLON.VertexBuffer.UV4Kind
  19234. * - BABYLON.VertexBuffer.UV5Kind
  19235. * - BABYLON.VertexBuffer.UV6Kind
  19236. * - BABYLON.VertexBuffer.ColorKind
  19237. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19238. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19239. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19240. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19241. */
  19242. Mesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  19243. if (!this._geometry) {
  19244. return null;
  19245. }
  19246. return this._geometry.getVerticesData(kind, copyWhenShared);
  19247. };
  19248. /**
  19249. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  19250. * Returns `undefined` if the mesh has no geometry.
  19251. * Possible `kind` values :
  19252. * - BABYLON.VertexBuffer.PositionKind
  19253. * - BABYLON.VertexBuffer.UVKind
  19254. * - BABYLON.VertexBuffer.UV2Kind
  19255. * - BABYLON.VertexBuffer.UV3Kind
  19256. * - BABYLON.VertexBuffer.UV4Kind
  19257. * - BABYLON.VertexBuffer.UV5Kind
  19258. * - BABYLON.VertexBuffer.UV6Kind
  19259. * - BABYLON.VertexBuffer.ColorKind
  19260. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19261. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19262. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19263. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19264. */
  19265. Mesh.prototype.getVertexBuffer = function (kind) {
  19266. if (!this._geometry) {
  19267. return undefined;
  19268. }
  19269. return this._geometry.getVertexBuffer(kind);
  19270. };
  19271. /**
  19272. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  19273. * Possible `kind` values :
  19274. * - BABYLON.VertexBuffer.PositionKind
  19275. * - BABYLON.VertexBuffer.UVKind
  19276. * - BABYLON.VertexBuffer.UV2Kind
  19277. * - BABYLON.VertexBuffer.UV3Kind
  19278. * - BABYLON.VertexBuffer.UV4Kind
  19279. * - BABYLON.VertexBuffer.UV5Kind
  19280. * - BABYLON.VertexBuffer.UV6Kind
  19281. * - BABYLON.VertexBuffer.ColorKind
  19282. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19283. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19284. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19285. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19286. */
  19287. Mesh.prototype.isVerticesDataPresent = function (kind) {
  19288. if (!this._geometry) {
  19289. if (this._delayInfo) {
  19290. return this._delayInfo.indexOf(kind) !== -1;
  19291. }
  19292. return false;
  19293. }
  19294. return this._geometry.isVerticesDataPresent(kind);
  19295. };
  19296. /**
  19297. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  19298. * Possible `kind` values :
  19299. * - BABYLON.VertexBuffer.PositionKind
  19300. * - BABYLON.VertexBuffer.UVKind
  19301. * - BABYLON.VertexBuffer.UV2Kind
  19302. * - BABYLON.VertexBuffer.UV3Kind
  19303. * - BABYLON.VertexBuffer.UV4Kind
  19304. * - BABYLON.VertexBuffer.UV5Kind
  19305. * - BABYLON.VertexBuffer.UV6Kind
  19306. * - BABYLON.VertexBuffer.ColorKind
  19307. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19308. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19309. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19310. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19311. */
  19312. Mesh.prototype.getVerticesDataKinds = function () {
  19313. if (!this._geometry) {
  19314. var result = [];
  19315. if (this._delayInfo) {
  19316. for (var kind in this._delayInfo) {
  19317. result.push(kind);
  19318. }
  19319. }
  19320. return result;
  19321. }
  19322. return this._geometry.getVerticesDataKinds();
  19323. };
  19324. /**
  19325. * Returns a positive integer : the total number of indices in this mesh geometry.
  19326. * Returns zero if the mesh has no geometry.
  19327. */
  19328. Mesh.prototype.getTotalIndices = function () {
  19329. if (!this._geometry) {
  19330. return 0;
  19331. }
  19332. return this._geometry.getTotalIndices();
  19333. };
  19334. /**
  19335. * Returns an array of integers or a Int32Array populated with the mesh indices.
  19336. * 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.
  19337. * Returns an empty array if the mesh has no geometry.
  19338. */
  19339. Mesh.prototype.getIndices = function (copyWhenShared) {
  19340. if (!this._geometry) {
  19341. return [];
  19342. }
  19343. return this._geometry.getIndices(copyWhenShared);
  19344. };
  19345. Object.defineProperty(Mesh.prototype, "isBlocked", {
  19346. get: function () {
  19347. return this._masterMesh !== null && this._masterMesh !== undefined;
  19348. },
  19349. enumerable: true,
  19350. configurable: true
  19351. });
  19352. /**
  19353. * Boolean : true once the mesh is ready after all the delayed process (loading, etc) are complete.
  19354. */
  19355. Mesh.prototype.isReady = function () {
  19356. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  19357. return false;
  19358. }
  19359. return _super.prototype.isReady.call(this);
  19360. };
  19361. /**
  19362. * Boolean : true if the mesh has been disposed.
  19363. */
  19364. Mesh.prototype.isDisposed = function () {
  19365. return this._isDisposed;
  19366. };
  19367. Object.defineProperty(Mesh.prototype, "sideOrientation", {
  19368. get: function () {
  19369. return this._sideOrientation;
  19370. },
  19371. /**
  19372. * Sets the mesh side orientation : BABYLON.Mesh.FRONTSIDE, BABYLON.Mesh.BACKSIDE, BABYLON.Mesh.DOUBLESIDE or BABYLON.Mesh.DEFAULTSIDE
  19373. * tuto : http://doc.babylonjs.com/tutorials/Discover_Basic_Elements#side-orientation
  19374. */
  19375. set: function (sideO) {
  19376. this._sideOrientation = sideO;
  19377. },
  19378. enumerable: true,
  19379. configurable: true
  19380. });
  19381. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  19382. /**
  19383. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  19384. * This property is pertinent only for updatable parametric shapes.
  19385. */
  19386. get: function () {
  19387. return this._areNormalsFrozen;
  19388. },
  19389. enumerable: true,
  19390. configurable: true
  19391. });
  19392. /**
  19393. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  19394. * It has no effect at all on other shapes.
  19395. * It prevents the mesh normals from being recomputed on next `positions` array update.
  19396. */
  19397. Mesh.prototype.freezeNormals = function () {
  19398. this._areNormalsFrozen = true;
  19399. };
  19400. /**
  19401. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  19402. * It has no effect at all on other shapes.
  19403. * It reactivates the mesh normals computation if it was previously frozen.
  19404. */
  19405. Mesh.prototype.unfreezeNormals = function () {
  19406. this._areNormalsFrozen = false;
  19407. };
  19408. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  19409. /**
  19410. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  19411. */
  19412. set: function (count) {
  19413. this._overridenInstanceCount = count;
  19414. },
  19415. enumerable: true,
  19416. configurable: true
  19417. });
  19418. // Methods
  19419. Mesh.prototype._preActivate = function () {
  19420. var sceneRenderId = this.getScene().getRenderId();
  19421. if (this._preActivateId === sceneRenderId) {
  19422. return;
  19423. }
  19424. this._preActivateId = sceneRenderId;
  19425. this._visibleInstances = null;
  19426. };
  19427. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  19428. if (this._visibleInstances) {
  19429. this._visibleInstances.intermediateDefaultRenderId = renderId;
  19430. }
  19431. };
  19432. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  19433. if (!this._visibleInstances) {
  19434. this._visibleInstances = {};
  19435. this._visibleInstances.defaultRenderId = renderId;
  19436. this._visibleInstances.selfDefaultRenderId = this._renderId;
  19437. }
  19438. if (!this._visibleInstances[renderId]) {
  19439. this._visibleInstances[renderId] = new Array();
  19440. }
  19441. this._visibleInstances[renderId].push(instance);
  19442. };
  19443. /**
  19444. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  19445. * This means the mesh underlying bounding box and sphere are recomputed.
  19446. */
  19447. Mesh.prototype.refreshBoundingInfo = function () {
  19448. if (this._boundingInfo.isLocked) {
  19449. return;
  19450. }
  19451. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19452. if (data) {
  19453. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  19454. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  19455. }
  19456. if (this.subMeshes) {
  19457. for (var index = 0; index < this.subMeshes.length; index++) {
  19458. this.subMeshes[index].refreshBoundingInfo();
  19459. }
  19460. }
  19461. this._updateBoundingInfo();
  19462. };
  19463. Mesh.prototype._createGlobalSubMesh = function () {
  19464. var totalVertices = this.getTotalVertices();
  19465. if (!totalVertices || !this.getIndices()) {
  19466. return null;
  19467. }
  19468. this.releaseSubMeshes();
  19469. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  19470. };
  19471. Mesh.prototype.subdivide = function (count) {
  19472. if (count < 1) {
  19473. return;
  19474. }
  19475. var totalIndices = this.getTotalIndices();
  19476. var subdivisionSize = (totalIndices / count) | 0;
  19477. var offset = 0;
  19478. // Ensure that subdivisionSize is a multiple of 3
  19479. while (subdivisionSize % 3 !== 0) {
  19480. subdivisionSize++;
  19481. }
  19482. this.releaseSubMeshes();
  19483. for (var index = 0; index < count; index++) {
  19484. if (offset >= totalIndices) {
  19485. break;
  19486. }
  19487. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  19488. offset += subdivisionSize;
  19489. }
  19490. this.synchronizeInstances();
  19491. };
  19492. /**
  19493. * Sets the vertex data of the mesh geometry for the requested `kind`.
  19494. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  19495. * The `data` are either a numeric array either a Float32Array.
  19496. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  19497. * 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).
  19498. * Note that a new underlying VertexBuffer object is created each call.
  19499. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  19500. *
  19501. * Possible `kind` values :
  19502. * - BABYLON.VertexBuffer.PositionKind
  19503. * - BABYLON.VertexBuffer.UVKind
  19504. * - BABYLON.VertexBuffer.UV2Kind
  19505. * - BABYLON.VertexBuffer.UV3Kind
  19506. * - BABYLON.VertexBuffer.UV4Kind
  19507. * - BABYLON.VertexBuffer.UV5Kind
  19508. * - BABYLON.VertexBuffer.UV6Kind
  19509. * - BABYLON.VertexBuffer.ColorKind
  19510. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19511. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19512. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19513. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19514. */
  19515. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  19516. if (!this._geometry) {
  19517. var vertexData = new BABYLON.VertexData();
  19518. vertexData.set(data, kind);
  19519. var scene = this.getScene();
  19520. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  19521. }
  19522. else {
  19523. this._geometry.setVerticesData(kind, data, updatable, stride);
  19524. }
  19525. };
  19526. Mesh.prototype.setVerticesBuffer = function (buffer) {
  19527. if (!this._geometry) {
  19528. var scene = this.getScene();
  19529. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene).applyToMesh(this);
  19530. }
  19531. this._geometry.setVerticesBuffer(buffer);
  19532. };
  19533. /**
  19534. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  19535. * If the mesh has no geometry, it is simply returned as it is.
  19536. * The `data` are either a numeric array either a Float32Array.
  19537. * No new underlying VertexBuffer object is created.
  19538. * 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.
  19539. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  19540. *
  19541. * Possible `kind` values :
  19542. * - BABYLON.VertexBuffer.PositionKind
  19543. * - BABYLON.VertexBuffer.UVKind
  19544. * - BABYLON.VertexBuffer.UV2Kind
  19545. * - BABYLON.VertexBuffer.UV3Kind
  19546. * - BABYLON.VertexBuffer.UV4Kind
  19547. * - BABYLON.VertexBuffer.UV5Kind
  19548. * - BABYLON.VertexBuffer.UV6Kind
  19549. * - BABYLON.VertexBuffer.ColorKind
  19550. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19551. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19552. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19553. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19554. */
  19555. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  19556. if (!this._geometry) {
  19557. return;
  19558. }
  19559. if (!makeItUnique) {
  19560. this._geometry.updateVerticesData(kind, data, updateExtends);
  19561. }
  19562. else {
  19563. this.makeGeometryUnique();
  19564. this.updateVerticesData(kind, data, updateExtends, false);
  19565. }
  19566. };
  19567. /**
  19568. * Deprecated since BabylonJS v2.3
  19569. */
  19570. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, offset, makeItUnique) {
  19571. BABYLON.Tools.Warn("Mesh.updateVerticesDataDirectly deprecated since 2.3.");
  19572. if (!this._geometry) {
  19573. return;
  19574. }
  19575. if (!makeItUnique) {
  19576. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  19577. }
  19578. else {
  19579. this.makeGeometryUnique();
  19580. this.updateVerticesDataDirectly(kind, data, offset, false);
  19581. }
  19582. };
  19583. /**
  19584. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  19585. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  19586. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  19587. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  19588. */
  19589. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  19590. if (computeNormals === void 0) { computeNormals = true; }
  19591. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19592. positionFunction(positions);
  19593. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  19594. if (computeNormals) {
  19595. var indices = this.getIndices();
  19596. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  19597. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  19598. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  19599. }
  19600. };
  19601. Mesh.prototype.makeGeometryUnique = function () {
  19602. if (!this._geometry) {
  19603. return;
  19604. }
  19605. var oldGeometry = this._geometry;
  19606. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  19607. oldGeometry.releaseForMesh(this, true);
  19608. geometry.applyToMesh(this);
  19609. };
  19610. /**
  19611. * Sets the mesh indices.
  19612. * Expects an array populated with integers or a Int32Array.
  19613. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  19614. * This method creates a new index buffer each call.
  19615. */
  19616. Mesh.prototype.setIndices = function (indices, totalVertices) {
  19617. if (!this._geometry) {
  19618. var vertexData = new BABYLON.VertexData();
  19619. vertexData.indices = indices;
  19620. var scene = this.getScene();
  19621. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  19622. }
  19623. else {
  19624. this._geometry.setIndices(indices, totalVertices);
  19625. }
  19626. };
  19627. /**
  19628. * Invert the geometry to move from a right handed system to a left handed one.
  19629. */
  19630. Mesh.prototype.toLeftHanded = function () {
  19631. if (!this._geometry) {
  19632. return;
  19633. }
  19634. this._geometry.toLeftHanded();
  19635. };
  19636. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  19637. var engine = this.getScene().getEngine();
  19638. // Wireframe
  19639. var indexToBind;
  19640. if (this._unIndexed) {
  19641. indexToBind = null;
  19642. }
  19643. else {
  19644. switch (fillMode) {
  19645. case BABYLON.Material.PointFillMode:
  19646. indexToBind = null;
  19647. break;
  19648. case BABYLON.Material.WireFrameFillMode:
  19649. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  19650. break;
  19651. default:
  19652. case BABYLON.Material.TriangleFillMode:
  19653. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  19654. break;
  19655. }
  19656. }
  19657. // VBOs
  19658. engine.bindBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  19659. };
  19660. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  19661. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  19662. return;
  19663. }
  19664. this.onBeforeDrawObservable.notifyObservers(this);
  19665. var engine = this.getScene().getEngine();
  19666. // Draw order
  19667. switch (fillMode) {
  19668. case BABYLON.Material.PointFillMode:
  19669. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  19670. break;
  19671. case BABYLON.Material.WireFrameFillMode:
  19672. if (this._unIndexed) {
  19673. engine.drawUnIndexed(false, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  19674. }
  19675. else {
  19676. engine.draw(false, 0, instancesCount > 0 ? subMesh.linesIndexCount / 2 : subMesh.linesIndexCount, instancesCount);
  19677. }
  19678. break;
  19679. default:
  19680. if (this._unIndexed) {
  19681. engine.drawUnIndexed(true, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  19682. }
  19683. else {
  19684. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  19685. }
  19686. }
  19687. };
  19688. /**
  19689. * Registers for this mesh a javascript function called just before the rendering process.
  19690. * This function is passed the current mesh and doesn't return anything.
  19691. */
  19692. Mesh.prototype.registerBeforeRender = function (func) {
  19693. this.onBeforeRenderObservable.add(func);
  19694. };
  19695. /**
  19696. * Disposes a previously registered javascript function called before the rendering.
  19697. * This function is passed the current mesh and doesn't return anything.
  19698. */
  19699. Mesh.prototype.unregisterBeforeRender = function (func) {
  19700. this.onBeforeRenderObservable.removeCallback(func);
  19701. };
  19702. /**
  19703. * Registers for this mesh a javascript function called just after the rendering is complete.
  19704. * This function is passed the current mesh and doesn't return anything.
  19705. */
  19706. Mesh.prototype.registerAfterRender = function (func) {
  19707. this.onAfterRenderObservable.add(func);
  19708. };
  19709. /**
  19710. * Disposes a previously registered javascript function called after the rendering.
  19711. * This function is passed the current mesh and doesn't return anything.
  19712. */
  19713. Mesh.prototype.unregisterAfterRender = function (func) {
  19714. this.onAfterRenderObservable.removeCallback(func);
  19715. };
  19716. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  19717. var scene = this.getScene();
  19718. this._batchCache.mustReturn = false;
  19719. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  19720. this._batchCache.visibleInstances[subMeshId] = null;
  19721. if (this._visibleInstances) {
  19722. var currentRenderId = scene.getRenderId();
  19723. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  19724. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  19725. var selfRenderId = this._renderId;
  19726. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  19727. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  19728. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  19729. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  19730. }
  19731. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  19732. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  19733. this._batchCache.mustReturn = true;
  19734. return this._batchCache;
  19735. }
  19736. if (currentRenderId !== selfRenderId) {
  19737. this._batchCache.renderSelf[subMeshId] = false;
  19738. }
  19739. }
  19740. this._renderIdForInstances[subMeshId] = currentRenderId;
  19741. }
  19742. return this._batchCache;
  19743. };
  19744. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  19745. var visibleInstances = batch.visibleInstances[subMesh._id];
  19746. var matricesCount = visibleInstances.length + 1;
  19747. var bufferSize = matricesCount * 16 * 4;
  19748. var currentInstancesBufferSize = this._instancesBufferSize;
  19749. var instancesBuffer = this._instancesBuffer;
  19750. while (this._instancesBufferSize < bufferSize) {
  19751. this._instancesBufferSize *= 2;
  19752. }
  19753. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  19754. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  19755. }
  19756. var offset = 0;
  19757. var instancesCount = 0;
  19758. var world = this.getWorldMatrix();
  19759. if (batch.renderSelf[subMesh._id]) {
  19760. world.copyToArray(this._instancesData, offset);
  19761. offset += 16;
  19762. instancesCount++;
  19763. }
  19764. if (visibleInstances) {
  19765. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  19766. var instance = visibleInstances[instanceIndex];
  19767. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  19768. offset += 16;
  19769. instancesCount++;
  19770. }
  19771. }
  19772. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  19773. if (instancesBuffer) {
  19774. instancesBuffer.dispose();
  19775. }
  19776. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  19777. this._instancesBuffer = instancesBuffer;
  19778. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  19779. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  19780. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  19781. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  19782. }
  19783. else {
  19784. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  19785. }
  19786. engine.bindBuffers(this.geometry.getVertexBuffers(), this.geometry.getIndexBuffer(), effect);
  19787. this._draw(subMesh, fillMode, instancesCount);
  19788. engine.unbindInstanceAttributes();
  19789. };
  19790. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  19791. var scene = this.getScene();
  19792. var engine = scene.getEngine();
  19793. if (hardwareInstancedRendering) {
  19794. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  19795. }
  19796. else {
  19797. if (batch.renderSelf[subMesh._id]) {
  19798. // Draw
  19799. if (onBeforeDraw) {
  19800. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  19801. }
  19802. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  19803. }
  19804. if (batch.visibleInstances[subMesh._id]) {
  19805. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  19806. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  19807. // World
  19808. var world = instance.getWorldMatrix();
  19809. if (onBeforeDraw) {
  19810. onBeforeDraw(true, world, effectiveMaterial);
  19811. }
  19812. // Draw
  19813. this._draw(subMesh, fillMode);
  19814. }
  19815. }
  19816. }
  19817. };
  19818. /**
  19819. * Triggers the draw call for the mesh.
  19820. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  19821. */
  19822. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  19823. var scene = this.getScene();
  19824. // Managing instances
  19825. var batch = this._getInstancesRenderList(subMesh._id);
  19826. if (batch.mustReturn) {
  19827. return;
  19828. }
  19829. // Checking geometry state
  19830. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  19831. return;
  19832. }
  19833. var callbackIndex;
  19834. this.onBeforeRenderObservable.notifyObservers(this);
  19835. var engine = scene.getEngine();
  19836. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  19837. // Material
  19838. var effectiveMaterial = subMesh.getMaterial();
  19839. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  19840. return;
  19841. }
  19842. // Outline - step 1
  19843. var savedDepthWrite = engine.getDepthWrite();
  19844. if (this.renderOutline) {
  19845. engine.setDepthWrite(false);
  19846. scene.getOutlineRenderer().render(subMesh, batch);
  19847. engine.setDepthWrite(savedDepthWrite);
  19848. }
  19849. effectiveMaterial._preBind();
  19850. var effect = effectiveMaterial.getEffect();
  19851. // Bind
  19852. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  19853. this._bind(subMesh, effect, fillMode);
  19854. var world = this.getWorldMatrix();
  19855. effectiveMaterial.bind(world, this);
  19856. // Alpha mode
  19857. if (enableAlphaMode) {
  19858. engine.setAlphaMode(effectiveMaterial.alphaMode);
  19859. }
  19860. // Draw
  19861. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw);
  19862. // Unbind
  19863. effectiveMaterial.unbind();
  19864. // Outline - step 2
  19865. if (this.renderOutline && savedDepthWrite) {
  19866. engine.setDepthWrite(true);
  19867. engine.setColorWrite(false);
  19868. scene.getOutlineRenderer().render(subMesh, batch);
  19869. engine.setColorWrite(true);
  19870. }
  19871. // Overlay
  19872. if (this.renderOverlay) {
  19873. var currentMode = engine.getAlphaMode();
  19874. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  19875. scene.getOutlineRenderer().render(subMesh, batch, true);
  19876. engine.setAlphaMode(currentMode);
  19877. }
  19878. this.onAfterRenderObservable.notifyObservers(this);
  19879. };
  19880. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  19881. if (isInstance) {
  19882. effectiveMaterial.bindOnlyWorldMatrix(world);
  19883. }
  19884. };
  19885. /**
  19886. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  19887. */
  19888. Mesh.prototype.getEmittedParticleSystems = function () {
  19889. var results = new Array();
  19890. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  19891. var particleSystem = this.getScene().particleSystems[index];
  19892. if (particleSystem.emitter === this) {
  19893. results.push(particleSystem);
  19894. }
  19895. }
  19896. return results;
  19897. };
  19898. /**
  19899. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  19900. */
  19901. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  19902. var results = new Array();
  19903. var descendants = this.getDescendants();
  19904. descendants.push(this);
  19905. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  19906. var particleSystem = this.getScene().particleSystems[index];
  19907. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  19908. results.push(particleSystem);
  19909. }
  19910. }
  19911. return results;
  19912. };
  19913. Mesh.prototype._checkDelayState = function () {
  19914. var scene = this.getScene();
  19915. if (this._geometry) {
  19916. this._geometry.load(scene);
  19917. }
  19918. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  19919. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  19920. this._queueLoad(this, scene);
  19921. }
  19922. };
  19923. Mesh.prototype._queueLoad = function (mesh, scene) {
  19924. var _this = this;
  19925. scene._addPendingData(mesh);
  19926. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  19927. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  19928. if (data instanceof ArrayBuffer) {
  19929. _this._delayLoadingFunction(data, _this);
  19930. }
  19931. else {
  19932. _this._delayLoadingFunction(JSON.parse(data), _this);
  19933. }
  19934. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  19935. scene._removePendingData(_this);
  19936. }, function () { }, scene.database, getBinaryData);
  19937. };
  19938. /**
  19939. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  19940. */
  19941. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  19942. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  19943. return false;
  19944. }
  19945. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  19946. return false;
  19947. }
  19948. this._checkDelayState();
  19949. return true;
  19950. };
  19951. /**
  19952. * Sets the mesh material by the material or multiMaterial `id` property.
  19953. * The material `id` is a string identifying the material or the multiMaterial.
  19954. * This method returns nothing.
  19955. */
  19956. Mesh.prototype.setMaterialByID = function (id) {
  19957. var materials = this.getScene().materials;
  19958. var index;
  19959. for (index = 0; index < materials.length; index++) {
  19960. if (materials[index].id === id) {
  19961. this.material = materials[index];
  19962. return;
  19963. }
  19964. }
  19965. // Multi
  19966. var multiMaterials = this.getScene().multiMaterials;
  19967. for (index = 0; index < multiMaterials.length; index++) {
  19968. if (multiMaterials[index].id === id) {
  19969. this.material = multiMaterials[index];
  19970. return;
  19971. }
  19972. }
  19973. };
  19974. /**
  19975. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  19976. */
  19977. Mesh.prototype.getAnimatables = function () {
  19978. var results = [];
  19979. if (this.material) {
  19980. results.push(this.material);
  19981. }
  19982. if (this.skeleton) {
  19983. results.push(this.skeleton);
  19984. }
  19985. return results;
  19986. };
  19987. /**
  19988. * Modifies the mesh geometry according to the passed transformation matrix.
  19989. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  19990. * The mesh normals are modified accordingly the same transformation.
  19991. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  19992. * Note that, under the hood, this method sets a new VertexBuffer each call.
  19993. */
  19994. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  19995. // Position
  19996. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  19997. return;
  19998. }
  19999. var submeshes = this.subMeshes.splice(0);
  20000. this._resetPointsArrayCache();
  20001. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20002. var temp = [];
  20003. var index;
  20004. for (index = 0; index < data.length; index += 3) {
  20005. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  20006. }
  20007. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  20008. // Normals
  20009. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  20010. return;
  20011. }
  20012. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20013. temp = [];
  20014. for (index = 0; index < data.length; index += 3) {
  20015. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  20016. }
  20017. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  20018. // flip faces?
  20019. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  20020. this.flipFaces();
  20021. }
  20022. // Restore submeshes
  20023. this.releaseSubMeshes();
  20024. this.subMeshes = submeshes;
  20025. };
  20026. /**
  20027. * Modifies the mesh geometry according to its own current World Matrix.
  20028. * The mesh World Matrix is then reset.
  20029. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  20030. * tuto : tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  20031. * Note that, under the hood, this method sets a new VertexBuffer each call.
  20032. */
  20033. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  20034. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  20035. this.scaling.copyFromFloats(1, 1, 1);
  20036. this.position.copyFromFloats(0, 0, 0);
  20037. this.rotation.copyFromFloats(0, 0, 0);
  20038. //only if quaternion is already set
  20039. if (this.rotationQuaternion) {
  20040. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  20041. }
  20042. this._worldMatrix = BABYLON.Matrix.Identity();
  20043. };
  20044. // Cache
  20045. Mesh.prototype._resetPointsArrayCache = function () {
  20046. this._positions = null;
  20047. };
  20048. Mesh.prototype._generatePointsArray = function () {
  20049. if (this._positions)
  20050. return true;
  20051. this._positions = [];
  20052. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20053. if (!data) {
  20054. return false;
  20055. }
  20056. for (var index = 0; index < data.length; index += 3) {
  20057. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  20058. }
  20059. return true;
  20060. };
  20061. /**
  20062. * Returns a new Mesh object generated from the current mesh properties.
  20063. * This method must not get confused with createInstance().
  20064. * The parameter `name` is a string, the name given to the new mesh.
  20065. * The optional parameter `newParent` can be any Node object (default `null`).
  20066. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  20067. * 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.
  20068. */
  20069. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  20070. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  20071. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  20072. };
  20073. /**
  20074. * Disposes the mesh.
  20075. * This also frees the memory allocated under the hood to all the buffers used by WebGL.
  20076. */
  20077. Mesh.prototype.dispose = function (doNotRecurse) {
  20078. if (this._geometry) {
  20079. this._geometry.releaseForMesh(this, true);
  20080. }
  20081. // Instances
  20082. if (this._instancesBuffer) {
  20083. this._instancesBuffer.dispose();
  20084. this._instancesBuffer = null;
  20085. }
  20086. while (this.instances.length) {
  20087. this.instances[0].dispose();
  20088. }
  20089. // Highlight layers.
  20090. var highlightLayers = this.getScene().highlightLayers;
  20091. for (var i = 0; i < highlightLayers.length; i++) {
  20092. var highlightLayer = highlightLayers[i];
  20093. if (highlightLayer) {
  20094. highlightLayer.removeMesh(this);
  20095. }
  20096. }
  20097. _super.prototype.dispose.call(this, doNotRecurse);
  20098. };
  20099. /**
  20100. * Modifies the mesh geometry according to a displacement map.
  20101. * 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.
  20102. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  20103. * This method returns nothing.
  20104. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  20105. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  20106. * 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.
  20107. */
  20108. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess) {
  20109. var _this = this;
  20110. var scene = this.getScene();
  20111. var onload = function (img) {
  20112. // Getting height map data
  20113. var canvas = document.createElement("canvas");
  20114. var context = canvas.getContext("2d");
  20115. var heightMapWidth = img.width;
  20116. var heightMapHeight = img.height;
  20117. canvas.width = heightMapWidth;
  20118. canvas.height = heightMapHeight;
  20119. context.drawImage(img, 0, 0);
  20120. // Create VertexData from map data
  20121. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  20122. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  20123. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  20124. //execute success callback, if set
  20125. if (onSuccess) {
  20126. onSuccess(_this);
  20127. }
  20128. };
  20129. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  20130. };
  20131. /**
  20132. * Modifies the mesh geometry according to a displacementMap buffer.
  20133. * 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.
  20134. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  20135. * This method returns nothing.
  20136. * 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.
  20137. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  20138. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  20139. */
  20140. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  20141. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  20142. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  20143. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  20144. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  20145. return;
  20146. }
  20147. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20148. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20149. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  20150. var position = BABYLON.Vector3.Zero();
  20151. var normal = BABYLON.Vector3.Zero();
  20152. var uv = BABYLON.Vector2.Zero();
  20153. for (var index = 0; index < positions.length; index += 3) {
  20154. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  20155. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  20156. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  20157. // Compute height
  20158. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  20159. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  20160. var pos = (u + v * heightMapWidth) * 4;
  20161. var r = buffer[pos] / 255.0;
  20162. var g = buffer[pos + 1] / 255.0;
  20163. var b = buffer[pos + 2] / 255.0;
  20164. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  20165. normal.normalize();
  20166. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  20167. position = position.add(normal);
  20168. position.toArray(positions, index);
  20169. }
  20170. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  20171. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  20172. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  20173. };
  20174. /**
  20175. * Modify the mesh to get a flat shading rendering.
  20176. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  20177. * This method returns nothing.
  20178. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  20179. */
  20180. Mesh.prototype.convertToFlatShadedMesh = function () {
  20181. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  20182. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  20183. var kinds = this.getVerticesDataKinds();
  20184. var vbs = [];
  20185. var data = [];
  20186. var newdata = [];
  20187. var updatableNormals = false;
  20188. var kindIndex;
  20189. var kind;
  20190. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  20191. kind = kinds[kindIndex];
  20192. var vertexBuffer = this.getVertexBuffer(kind);
  20193. if (kind === BABYLON.VertexBuffer.NormalKind) {
  20194. updatableNormals = vertexBuffer.isUpdatable();
  20195. kinds.splice(kindIndex, 1);
  20196. kindIndex--;
  20197. continue;
  20198. }
  20199. vbs[kind] = vertexBuffer;
  20200. data[kind] = vbs[kind].getData();
  20201. newdata[kind] = [];
  20202. }
  20203. // Save previous submeshes
  20204. var previousSubmeshes = this.subMeshes.slice(0);
  20205. var indices = this.getIndices();
  20206. var totalIndices = this.getTotalIndices();
  20207. // Generating unique vertices per face
  20208. var index;
  20209. for (index = 0; index < totalIndices; index++) {
  20210. var vertexIndex = indices[index];
  20211. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  20212. kind = kinds[kindIndex];
  20213. var stride = vbs[kind].getStrideSize();
  20214. for (var offset = 0; offset < stride; offset++) {
  20215. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  20216. }
  20217. }
  20218. }
  20219. // Updating faces & normal
  20220. var normals = [];
  20221. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  20222. for (index = 0; index < totalIndices; index += 3) {
  20223. indices[index] = index;
  20224. indices[index + 1] = index + 1;
  20225. indices[index + 2] = index + 2;
  20226. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  20227. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  20228. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  20229. var p1p2 = p1.subtract(p2);
  20230. var p3p2 = p3.subtract(p2);
  20231. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  20232. // Store same normals for every vertex
  20233. for (var localIndex = 0; localIndex < 3; localIndex++) {
  20234. normals.push(normal.x);
  20235. normals.push(normal.y);
  20236. normals.push(normal.z);
  20237. }
  20238. }
  20239. this.setIndices(indices);
  20240. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  20241. // Updating vertex buffers
  20242. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  20243. kind = kinds[kindIndex];
  20244. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  20245. }
  20246. // Updating submeshes
  20247. this.releaseSubMeshes();
  20248. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  20249. var previousOne = previousSubmeshes[submeshIndex];
  20250. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  20251. }
  20252. this.synchronizeInstances();
  20253. };
  20254. /**
  20255. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  20256. * In other words, more vertices, no more indices and a single bigger VBO.
  20257. * This method returns nothing.
  20258. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  20259. *
  20260. */
  20261. Mesh.prototype.convertToUnIndexedMesh = function () {
  20262. /// <summary>Remove indices by unfolding faces into buffers</summary>
  20263. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  20264. var kinds = this.getVerticesDataKinds();
  20265. var vbs = [];
  20266. var data = [];
  20267. var newdata = [];
  20268. var updatableNormals = false;
  20269. var kindIndex;
  20270. var kind;
  20271. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  20272. kind = kinds[kindIndex];
  20273. var vertexBuffer = this.getVertexBuffer(kind);
  20274. vbs[kind] = vertexBuffer;
  20275. data[kind] = vbs[kind].getData();
  20276. newdata[kind] = [];
  20277. }
  20278. // Save previous submeshes
  20279. var previousSubmeshes = this.subMeshes.slice(0);
  20280. var indices = this.getIndices();
  20281. var totalIndices = this.getTotalIndices();
  20282. // Generating unique vertices per face
  20283. var index;
  20284. for (index = 0; index < totalIndices; index++) {
  20285. var vertexIndex = indices[index];
  20286. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  20287. kind = kinds[kindIndex];
  20288. var stride = vbs[kind].getStrideSize();
  20289. for (var offset = 0; offset < stride; offset++) {
  20290. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  20291. }
  20292. }
  20293. }
  20294. // Updating indices
  20295. for (index = 0; index < totalIndices; index += 3) {
  20296. indices[index] = index;
  20297. indices[index + 1] = index + 1;
  20298. indices[index + 2] = index + 2;
  20299. }
  20300. this.setIndices(indices);
  20301. // Updating vertex buffers
  20302. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  20303. kind = kinds[kindIndex];
  20304. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  20305. }
  20306. // Updating submeshes
  20307. this.releaseSubMeshes();
  20308. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  20309. var previousOne = previousSubmeshes[submeshIndex];
  20310. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  20311. }
  20312. this._unIndexed = true;
  20313. this.synchronizeInstances();
  20314. };
  20315. /**
  20316. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  20317. * This method returns nothing.
  20318. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  20319. */
  20320. Mesh.prototype.flipFaces = function (flipNormals) {
  20321. if (flipNormals === void 0) { flipNormals = false; }
  20322. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  20323. var i;
  20324. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  20325. for (i = 0; i < vertex_data.normals.length; i++) {
  20326. vertex_data.normals[i] *= -1;
  20327. }
  20328. }
  20329. var temp;
  20330. for (i = 0; i < vertex_data.indices.length; i += 3) {
  20331. // reassign indices
  20332. temp = vertex_data.indices[i + 1];
  20333. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  20334. vertex_data.indices[i + 2] = temp;
  20335. }
  20336. vertex_data.applyToMesh(this);
  20337. };
  20338. // Instances
  20339. /**
  20340. * Creates a new InstancedMesh object from the mesh model.
  20341. * An instance shares the same properties and the same material than its model.
  20342. * Only these properties of each instance can then be set individually :
  20343. * - position
  20344. * - rotation
  20345. * - rotationQuaternion
  20346. * - setPivotMatrix
  20347. * - scaling
  20348. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  20349. * Warning : this method is not supported for Line mesh and LineSystem
  20350. */
  20351. Mesh.prototype.createInstance = function (name) {
  20352. return new BABYLON.InstancedMesh(name, this);
  20353. };
  20354. /**
  20355. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  20356. * After this call, all the mesh instances have the same submeshes than the current mesh.
  20357. * This method returns nothing.
  20358. */
  20359. Mesh.prototype.synchronizeInstances = function () {
  20360. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  20361. var instance = this.instances[instanceIndex];
  20362. instance._syncSubMeshes();
  20363. }
  20364. };
  20365. /**
  20366. * Simplify the mesh according to the given array of settings.
  20367. * Function will return immediately and will simplify async. It returns nothing.
  20368. * @param settings a collection of simplification settings.
  20369. * @param parallelProcessing should all levels calculate parallel or one after the other.
  20370. * @param type the type of simplification to run.
  20371. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  20372. */
  20373. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  20374. if (parallelProcessing === void 0) { parallelProcessing = true; }
  20375. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  20376. this.getScene().simplificationQueue.addTask({
  20377. settings: settings,
  20378. parallelProcessing: parallelProcessing,
  20379. mesh: this,
  20380. simplificationType: simplificationType,
  20381. successCallback: successCallback
  20382. });
  20383. };
  20384. /**
  20385. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  20386. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  20387. * This should be used together with the simplification to avoid disappearing triangles.
  20388. * @param successCallback an optional success callback to be called after the optimization finished.
  20389. */
  20390. Mesh.prototype.optimizeIndices = function (successCallback) {
  20391. var _this = this;
  20392. var indices = this.getIndices();
  20393. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20394. var vectorPositions = [];
  20395. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  20396. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  20397. }
  20398. var dupes = [];
  20399. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  20400. var realPos = vectorPositions.length - 1 - iteration;
  20401. var testedPosition = vectorPositions[realPos];
  20402. for (var j = 0; j < realPos; ++j) {
  20403. var againstPosition = vectorPositions[j];
  20404. if (testedPosition.equals(againstPosition)) {
  20405. dupes[realPos] = j;
  20406. break;
  20407. }
  20408. }
  20409. }, function () {
  20410. for (var i = 0; i < indices.length; ++i) {
  20411. indices[i] = dupes[indices[i]] || indices[i];
  20412. }
  20413. //indices are now reordered
  20414. var originalSubMeshes = _this.subMeshes.slice(0);
  20415. _this.setIndices(indices);
  20416. _this.subMeshes = originalSubMeshes;
  20417. if (successCallback) {
  20418. successCallback(_this);
  20419. }
  20420. });
  20421. };
  20422. // Statics
  20423. /**
  20424. * Returns a new Mesh object what is a deep copy of the passed mesh.
  20425. * The parameter `parsedMesh` is the mesh to be copied.
  20426. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  20427. */
  20428. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  20429. var mesh = new Mesh(parsedMesh.name, scene);
  20430. mesh.id = parsedMesh.id;
  20431. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  20432. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  20433. if (parsedMesh.rotationQuaternion) {
  20434. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  20435. }
  20436. else if (parsedMesh.rotation) {
  20437. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  20438. }
  20439. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  20440. if (parsedMesh.localMatrix) {
  20441. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  20442. }
  20443. else if (parsedMesh.pivotMatrix) {
  20444. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  20445. }
  20446. mesh.setEnabled(parsedMesh.isEnabled);
  20447. mesh.isVisible = parsedMesh.isVisible;
  20448. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  20449. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  20450. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  20451. if (parsedMesh.applyFog !== undefined) {
  20452. mesh.applyFog = parsedMesh.applyFog;
  20453. }
  20454. if (parsedMesh.pickable !== undefined) {
  20455. mesh.isPickable = parsedMesh.pickable;
  20456. }
  20457. if (parsedMesh.alphaIndex !== undefined) {
  20458. mesh.alphaIndex = parsedMesh.alphaIndex;
  20459. }
  20460. mesh.receiveShadows = parsedMesh.receiveShadows;
  20461. mesh.billboardMode = parsedMesh.billboardMode;
  20462. if (parsedMesh.visibility !== undefined) {
  20463. mesh.visibility = parsedMesh.visibility;
  20464. }
  20465. mesh.checkCollisions = parsedMesh.checkCollisions;
  20466. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  20467. // freezeWorldMatrix
  20468. if (parsedMesh.freezeWorldMatrix) {
  20469. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  20470. }
  20471. // Parent
  20472. if (parsedMesh.parentId) {
  20473. mesh._waitingParentId = parsedMesh.parentId;
  20474. }
  20475. // Actions
  20476. if (parsedMesh.actions !== undefined) {
  20477. mesh._waitingActions = parsedMesh.actions;
  20478. }
  20479. // Geometry
  20480. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  20481. if (parsedMesh.delayLoadingFile) {
  20482. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  20483. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  20484. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  20485. if (parsedMesh._binaryInfo) {
  20486. mesh._binaryInfo = parsedMesh._binaryInfo;
  20487. }
  20488. mesh._delayInfo = [];
  20489. if (parsedMesh.hasUVs) {
  20490. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  20491. }
  20492. if (parsedMesh.hasUVs2) {
  20493. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  20494. }
  20495. if (parsedMesh.hasUVs3) {
  20496. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  20497. }
  20498. if (parsedMesh.hasUVs4) {
  20499. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  20500. }
  20501. if (parsedMesh.hasUVs5) {
  20502. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  20503. }
  20504. if (parsedMesh.hasUVs6) {
  20505. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  20506. }
  20507. if (parsedMesh.hasColors) {
  20508. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  20509. }
  20510. if (parsedMesh.hasMatricesIndices) {
  20511. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  20512. }
  20513. if (parsedMesh.hasMatricesWeights) {
  20514. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  20515. }
  20516. mesh._delayLoadingFunction = BABYLON.Geometry.ImportGeometry;
  20517. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  20518. mesh._checkDelayState();
  20519. }
  20520. }
  20521. else {
  20522. BABYLON.Geometry.ImportGeometry(parsedMesh, mesh);
  20523. }
  20524. // Material
  20525. if (parsedMesh.materialId) {
  20526. mesh.setMaterialByID(parsedMesh.materialId);
  20527. }
  20528. else {
  20529. mesh.material = null;
  20530. }
  20531. // Skeleton
  20532. if (parsedMesh.skeletonId > -1) {
  20533. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  20534. if (parsedMesh.numBoneInfluencers) {
  20535. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  20536. }
  20537. }
  20538. // Animations
  20539. if (parsedMesh.animations) {
  20540. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  20541. var parsedAnimation = parsedMesh.animations[animationIndex];
  20542. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  20543. }
  20544. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  20545. }
  20546. if (parsedMesh.autoAnimate) {
  20547. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  20548. }
  20549. // Layer Mask
  20550. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  20551. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  20552. }
  20553. else {
  20554. mesh.layerMask = 0x0FFFFFFF;
  20555. }
  20556. //(Deprecated) physics
  20557. if (parsedMesh.physicsImpostor) {
  20558. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  20559. mass: parsedMesh.physicsMass,
  20560. friction: parsedMesh.physicsFriction,
  20561. restitution: parsedMesh.physicsRestitution
  20562. }, scene);
  20563. }
  20564. // Instances
  20565. if (parsedMesh.instances) {
  20566. for (var index = 0; index < parsedMesh.instances.length; index++) {
  20567. var parsedInstance = parsedMesh.instances[index];
  20568. var instance = mesh.createInstance(parsedInstance.name);
  20569. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  20570. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  20571. if (parsedInstance.parentId) {
  20572. instance._waitingParentId = parsedInstance.parentId;
  20573. }
  20574. if (parsedInstance.rotationQuaternion) {
  20575. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  20576. }
  20577. else if (parsedInstance.rotation) {
  20578. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  20579. }
  20580. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  20581. instance.checkCollisions = mesh.checkCollisions;
  20582. if (parsedMesh.animations) {
  20583. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  20584. parsedAnimation = parsedMesh.animations[animationIndex];
  20585. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  20586. }
  20587. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  20588. }
  20589. }
  20590. }
  20591. return mesh;
  20592. };
  20593. /**
  20594. * Creates a ribbon mesh.
  20595. * Please consider using the same method from the MeshBuilder class instead.
  20596. * 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.
  20597. *
  20598. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  20599. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  20600. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  20601. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  20602. * 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.
  20603. * 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.
  20604. * 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
  20605. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20606. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20607. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20608. */
  20609. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  20610. return BABYLON.MeshBuilder.CreateRibbon(name, {
  20611. pathArray: pathArray,
  20612. closeArray: closeArray,
  20613. closePath: closePath,
  20614. offset: offset,
  20615. updatable: updatable,
  20616. sideOrientation: sideOrientation,
  20617. instance: instance
  20618. }, scene);
  20619. };
  20620. /**
  20621. * Creates a plane polygonal mesh. By default, this is a disc.
  20622. * Please consider using the same method from the MeshBuilder class instead.
  20623. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  20624. * 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.
  20625. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20626. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20627. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20628. */
  20629. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  20630. var options = {
  20631. radius: radius,
  20632. tessellation: tessellation,
  20633. sideOrientation: sideOrientation,
  20634. updatable: updatable
  20635. };
  20636. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  20637. };
  20638. /**
  20639. * Creates a box mesh.
  20640. * Please consider using the same method from the MeshBuilder class instead.
  20641. * The parameter `size` sets the size (float) of each box side (default 1).
  20642. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20643. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20644. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20645. */
  20646. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  20647. var options = {
  20648. size: size,
  20649. sideOrientation: sideOrientation,
  20650. updatable: updatable
  20651. };
  20652. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  20653. };
  20654. /**
  20655. * Creates a sphere mesh.
  20656. * Please consider using the same method from the MeshBuilder class instead.
  20657. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  20658. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  20659. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20660. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20661. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20662. */
  20663. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  20664. var options = {
  20665. segments: segments,
  20666. diameterX: diameter,
  20667. diameterY: diameter,
  20668. diameterZ: diameter,
  20669. sideOrientation: sideOrientation,
  20670. updatable: updatable
  20671. };
  20672. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  20673. };
  20674. /**
  20675. * Creates a cylinder or a cone mesh.
  20676. * Please consider using the same method from the MeshBuilder class instead.
  20677. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  20678. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  20679. * 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.
  20680. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  20681. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  20682. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20683. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20684. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20685. */
  20686. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  20687. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  20688. if (scene !== undefined) {
  20689. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  20690. updatable = scene;
  20691. }
  20692. scene = subdivisions;
  20693. subdivisions = 1;
  20694. }
  20695. var options = {
  20696. height: height,
  20697. diameterTop: diameterTop,
  20698. diameterBottom: diameterBottom,
  20699. tessellation: tessellation,
  20700. subdivisions: subdivisions,
  20701. sideOrientation: sideOrientation,
  20702. updatable: updatable
  20703. };
  20704. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  20705. };
  20706. // Torus (Code from SharpDX.org)
  20707. /**
  20708. * Creates a torus mesh.
  20709. * Please consider using the same method from the MeshBuilder class instead.
  20710. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  20711. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  20712. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  20713. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20714. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20715. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20716. */
  20717. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  20718. var options = {
  20719. diameter: diameter,
  20720. thickness: thickness,
  20721. tessellation: tessellation,
  20722. sideOrientation: sideOrientation,
  20723. updatable: updatable
  20724. };
  20725. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  20726. };
  20727. /**
  20728. * Creates a torus knot mesh.
  20729. * Please consider using the same method from the MeshBuilder class instead.
  20730. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  20731. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  20732. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  20733. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  20734. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20735. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20736. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20737. */
  20738. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  20739. var options = {
  20740. radius: radius,
  20741. tube: tube,
  20742. radialSegments: radialSegments,
  20743. tubularSegments: tubularSegments,
  20744. p: p,
  20745. q: q,
  20746. sideOrientation: sideOrientation,
  20747. updatable: updatable
  20748. };
  20749. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  20750. };
  20751. /**
  20752. * Creates a line mesh.
  20753. * Please consider using the same method from the MeshBuilder class instead.
  20754. * 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.
  20755. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  20756. * The parameter `points` is an array successive Vector3.
  20757. * 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
  20758. * When updating an instance, remember that only point positions can change, not the number of points.
  20759. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20760. */
  20761. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  20762. var options = {
  20763. points: points,
  20764. updatable: updatable,
  20765. instance: instance
  20766. };
  20767. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  20768. };
  20769. /**
  20770. * Creates a dashed line mesh.
  20771. * Please consider using the same method from the MeshBuilder class instead.
  20772. * 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.
  20773. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  20774. * The parameter `points` is an array successive Vector3.
  20775. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  20776. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  20777. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  20778. * 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
  20779. * When updating an instance, remember that only point positions can change, not the number of points.
  20780. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20781. */
  20782. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  20783. var options = {
  20784. points: points,
  20785. dashSize: dashSize,
  20786. gapSize: gapSize,
  20787. dashNb: dashNb,
  20788. updatable: updatable,
  20789. instance: instance
  20790. };
  20791. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  20792. };
  20793. /**
  20794. * Creates an extruded shape mesh.
  20795. * 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.
  20796. * Please consider using the same method from the MeshBuilder class instead.
  20797. *
  20798. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  20799. * 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
  20800. * extruded along the Z axis.
  20801. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  20802. * 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.
  20803. * The parameter `scale` (float, default 1) is the value to scale the shape.
  20804. * 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
  20805. * 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
  20806. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  20807. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20808. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20809. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20810. */
  20811. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  20812. var options = {
  20813. shape: shape,
  20814. path: path,
  20815. scale: scale,
  20816. rotation: rotation,
  20817. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  20818. sideOrientation: sideOrientation,
  20819. instance: instance,
  20820. updatable: updatable
  20821. };
  20822. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  20823. };
  20824. /**
  20825. * Creates an custom extruded shape mesh.
  20826. * 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.
  20827. * Please consider using the same method from the MeshBuilder class instead.
  20828. *
  20829. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  20830. * 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
  20831. * extruded along the Z axis.
  20832. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  20833. * 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
  20834. * and the distance of this point from the begining of the path :
  20835. * ```javascript
  20836. * var rotationFunction = function(i, distance) {
  20837. * // do things
  20838. * return rotationValue; }
  20839. * ```
  20840. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  20841. * 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
  20842. * and the distance of this point from the begining of the path :
  20843. * ```javascript
  20844. * var scaleFunction = function(i, distance) {
  20845. * // do things
  20846. * return scaleValue;}
  20847. * ```
  20848. * It must returns a float value that will be the scale value applied to the shape on each path point.
  20849. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  20850. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  20851. * 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
  20852. * 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
  20853. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  20854. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20855. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20856. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20857. */
  20858. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  20859. var options = {
  20860. shape: shape,
  20861. path: path,
  20862. scaleFunction: scaleFunction,
  20863. rotationFunction: rotationFunction,
  20864. ribbonCloseArray: ribbonCloseArray,
  20865. ribbonClosePath: ribbonClosePath,
  20866. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  20867. sideOrientation: sideOrientation,
  20868. instance: instance,
  20869. updatable: updatable
  20870. };
  20871. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  20872. };
  20873. /**
  20874. * Creates lathe mesh.
  20875. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  20876. * Please consider using the same method from the MeshBuilder class instead.
  20877. * 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
  20878. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  20879. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  20880. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  20881. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20882. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20883. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20884. */
  20885. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  20886. var options = {
  20887. shape: shape,
  20888. radius: radius,
  20889. tessellation: tessellation,
  20890. sideOrientation: sideOrientation,
  20891. updatable: updatable
  20892. };
  20893. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  20894. };
  20895. /**
  20896. * Creates a plane mesh.
  20897. * Please consider using the same method from the MeshBuilder class instead.
  20898. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  20899. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20900. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20901. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20902. */
  20903. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  20904. var options = {
  20905. size: size,
  20906. width: size,
  20907. height: size,
  20908. sideOrientation: sideOrientation,
  20909. updatable: updatable
  20910. };
  20911. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  20912. };
  20913. /**
  20914. * Creates a ground mesh.
  20915. * Please consider using the same method from the MeshBuilder class instead.
  20916. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  20917. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  20918. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20919. */
  20920. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  20921. var options = {
  20922. width: width,
  20923. height: height,
  20924. subdivisions: subdivisions,
  20925. updatable: updatable
  20926. };
  20927. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  20928. };
  20929. /**
  20930. * Creates a tiled ground mesh.
  20931. * Please consider using the same method from the MeshBuilder class instead.
  20932. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  20933. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  20934. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  20935. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  20936. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  20937. * numbers of subdivisions on the ground width and height of each tile.
  20938. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20939. */
  20940. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  20941. var options = {
  20942. xmin: xmin,
  20943. zmin: zmin,
  20944. xmax: xmax,
  20945. zmax: zmax,
  20946. subdivisions: subdivisions,
  20947. precision: precision,
  20948. updatable: updatable
  20949. };
  20950. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  20951. };
  20952. /**
  20953. * Creates a ground mesh from a height map.
  20954. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  20955. * Please consider using the same method from the MeshBuilder class instead.
  20956. * The parameter `url` sets the URL of the height map image resource.
  20957. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  20958. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  20959. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  20960. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  20961. * The parameter `onReady` is a javascript callback function that will be called once the mesh is just built (the height map download can last some time).
  20962. * This function is passed the newly built mesh :
  20963. * ```javascript
  20964. * function(mesh) { // do things
  20965. * return; }
  20966. * ```
  20967. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20968. */
  20969. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  20970. var options = {
  20971. width: width,
  20972. height: height,
  20973. subdivisions: subdivisions,
  20974. minHeight: minHeight,
  20975. maxHeight: maxHeight,
  20976. updatable: updatable,
  20977. onReady: onReady
  20978. };
  20979. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  20980. };
  20981. /**
  20982. * Creates a tube mesh.
  20983. * 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.
  20984. * Please consider using the same method from the MeshBuilder class instead.
  20985. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  20986. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  20987. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  20988. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  20989. * 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.
  20990. * It must return a radius value (positive float) :
  20991. * ```javascript
  20992. * var radiusFunction = function(i, distance) {
  20993. * // do things
  20994. * return radius; }
  20995. * ```
  20996. * 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
  20997. * 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
  20998. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20999. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21000. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21001. */
  21002. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  21003. var options = {
  21004. path: path,
  21005. radius: radius,
  21006. tessellation: tessellation,
  21007. radiusFunction: radiusFunction,
  21008. arc: 1,
  21009. cap: cap,
  21010. updatable: updatable,
  21011. sideOrientation: sideOrientation,
  21012. instance: instance
  21013. };
  21014. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  21015. };
  21016. /**
  21017. * Creates a polyhedron mesh.
  21018. * Please consider using the same method from the MeshBuilder class instead.
  21019. * 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
  21020. * to choose the wanted type.
  21021. * The parameter `size` (positive float, default 1) sets the polygon size.
  21022. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  21023. * 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`.
  21024. * 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
  21025. * 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)`).
  21026. * 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
  21027. * 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.
  21028. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21029. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21030. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21031. */
  21032. Mesh.CreatePolyhedron = function (name, options, scene) {
  21033. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  21034. };
  21035. /**
  21036. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  21037. * Please consider using the same method from the MeshBuilder class instead.
  21038. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  21039. * 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`).
  21040. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  21041. * 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.
  21042. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21043. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21044. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21045. */
  21046. Mesh.CreateIcoSphere = function (name, options, scene) {
  21047. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  21048. };
  21049. /**
  21050. * Creates a decal mesh.
  21051. * Please consider using the same method from the MeshBuilder class instead.
  21052. * 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.
  21053. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  21054. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  21055. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  21056. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  21057. */
  21058. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  21059. var options = {
  21060. position: position,
  21061. normal: normal,
  21062. size: size,
  21063. angle: angle
  21064. };
  21065. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  21066. };
  21067. // Skeletons
  21068. /**
  21069. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  21070. */
  21071. Mesh.prototype.setPositionsForCPUSkinning = function () {
  21072. var source;
  21073. if (!this._sourcePositions) {
  21074. source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21075. this._sourcePositions = new Float32Array(source);
  21076. if (!this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable()) {
  21077. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  21078. }
  21079. }
  21080. return this._sourcePositions;
  21081. };
  21082. /**
  21083. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  21084. */
  21085. Mesh.prototype.setNormalsForCPUSkinning = function () {
  21086. var source;
  21087. if (!this._sourceNormals) {
  21088. source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21089. this._sourceNormals = new Float32Array(source);
  21090. if (!this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable()) {
  21091. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  21092. }
  21093. }
  21094. return this._sourceNormals;
  21095. };
  21096. /**
  21097. * Update the vertex buffers by applying transformation from the bones
  21098. * @param {skeleton} skeleton to apply
  21099. */
  21100. Mesh.prototype.applySkeleton = function (skeleton) {
  21101. if (!this.geometry) {
  21102. return;
  21103. }
  21104. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  21105. return;
  21106. }
  21107. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  21108. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  21109. return this;
  21110. }
  21111. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  21112. return this;
  21113. }
  21114. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  21115. return this;
  21116. }
  21117. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  21118. return this;
  21119. }
  21120. if (!this._sourcePositions) {
  21121. this.setPositionsForCPUSkinning();
  21122. }
  21123. if (!this._sourceNormals) {
  21124. this.setNormalsForCPUSkinning();
  21125. }
  21126. // positionsData checks for not being Float32Array will only pass at most once
  21127. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21128. if (!(positionsData instanceof Float32Array)) {
  21129. positionsData = new Float32Array(positionsData);
  21130. }
  21131. // normalsData checks for not being Float32Array will only pass at most once
  21132. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21133. if (!(normalsData instanceof Float32Array)) {
  21134. normalsData = new Float32Array(normalsData);
  21135. }
  21136. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  21137. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  21138. var needExtras = this.numBoneInfluencers > 4;
  21139. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  21140. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  21141. var skeletonMatrices = skeleton.getTransformMatrices(this);
  21142. var tempVector3 = BABYLON.Vector3.Zero();
  21143. var finalMatrix = new BABYLON.Matrix();
  21144. var tempMatrix = new BABYLON.Matrix();
  21145. var matWeightIdx = 0;
  21146. var inf;
  21147. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  21148. var weight;
  21149. for (inf = 0; inf < 4; inf++) {
  21150. weight = matricesWeightsData[matWeightIdx + inf];
  21151. if (weight > 0) {
  21152. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  21153. finalMatrix.addToSelf(tempMatrix);
  21154. }
  21155. else
  21156. break;
  21157. }
  21158. if (needExtras) {
  21159. for (inf = 0; inf < 4; inf++) {
  21160. weight = matricesWeightsExtraData[matWeightIdx + inf];
  21161. if (weight > 0) {
  21162. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  21163. finalMatrix.addToSelf(tempMatrix);
  21164. }
  21165. else
  21166. break;
  21167. }
  21168. }
  21169. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  21170. tempVector3.toArray(positionsData, index);
  21171. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  21172. tempVector3.toArray(normalsData, index);
  21173. finalMatrix.reset();
  21174. }
  21175. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  21176. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  21177. return this;
  21178. };
  21179. // Tools
  21180. /**
  21181. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  21182. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  21183. */
  21184. Mesh.MinMax = function (meshes) {
  21185. var minVector = null;
  21186. var maxVector = null;
  21187. for (var i in meshes) {
  21188. var mesh = meshes[i];
  21189. var boundingBox = mesh.getBoundingInfo().boundingBox;
  21190. if (!minVector) {
  21191. minVector = boundingBox.minimumWorld;
  21192. maxVector = boundingBox.maximumWorld;
  21193. continue;
  21194. }
  21195. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  21196. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  21197. }
  21198. return {
  21199. min: minVector,
  21200. max: maxVector
  21201. };
  21202. };
  21203. /**
  21204. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  21205. */
  21206. Mesh.Center = function (meshesOrMinMaxVector) {
  21207. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : Mesh.MinMax(meshesOrMinMaxVector);
  21208. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  21209. };
  21210. /**
  21211. * Merge the array of meshes into a single mesh for performance reasons.
  21212. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  21213. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  21214. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  21215. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  21216. */
  21217. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass) {
  21218. if (disposeSource === void 0) { disposeSource = true; }
  21219. var index;
  21220. if (!allow32BitsIndices) {
  21221. var totalVertices = 0;
  21222. // Counting vertices
  21223. for (index = 0; index < meshes.length; index++) {
  21224. if (meshes[index]) {
  21225. totalVertices += meshes[index].getTotalVertices();
  21226. if (totalVertices > 65536) {
  21227. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  21228. return null;
  21229. }
  21230. }
  21231. }
  21232. }
  21233. // Merge
  21234. var vertexData;
  21235. var otherVertexData;
  21236. var source;
  21237. for (index = 0; index < meshes.length; index++) {
  21238. if (meshes[index]) {
  21239. meshes[index].computeWorldMatrix(true);
  21240. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  21241. otherVertexData.transform(meshes[index].getWorldMatrix());
  21242. if (vertexData) {
  21243. vertexData.merge(otherVertexData);
  21244. }
  21245. else {
  21246. vertexData = otherVertexData;
  21247. source = meshes[index];
  21248. }
  21249. }
  21250. }
  21251. if (!meshSubclass) {
  21252. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  21253. }
  21254. vertexData.applyToMesh(meshSubclass);
  21255. // Setting properties
  21256. meshSubclass.material = source.material;
  21257. meshSubclass.checkCollisions = source.checkCollisions;
  21258. // Cleaning
  21259. if (disposeSource) {
  21260. for (index = 0; index < meshes.length; index++) {
  21261. if (meshes[index]) {
  21262. meshes[index].dispose();
  21263. }
  21264. }
  21265. }
  21266. return meshSubclass;
  21267. };
  21268. // Consts
  21269. Mesh._FRONTSIDE = 0;
  21270. Mesh._BACKSIDE = 1;
  21271. Mesh._DOUBLESIDE = 2;
  21272. Mesh._DEFAULTSIDE = 0;
  21273. Mesh._NO_CAP = 0;
  21274. Mesh._CAP_START = 1;
  21275. Mesh._CAP_END = 2;
  21276. Mesh._CAP_ALL = 3;
  21277. return Mesh;
  21278. }(BABYLON.AbstractMesh));
  21279. BABYLON.Mesh = Mesh;
  21280. })(BABYLON || (BABYLON = {}));
  21281. var BABYLON;
  21282. (function (BABYLON) {
  21283. var SubMesh = (function () {
  21284. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  21285. if (createBoundingBox === void 0) { createBoundingBox = true; }
  21286. this.materialIndex = materialIndex;
  21287. this.verticesStart = verticesStart;
  21288. this.verticesCount = verticesCount;
  21289. this.indexStart = indexStart;
  21290. this.indexCount = indexCount;
  21291. this._renderId = 0;
  21292. this._mesh = mesh;
  21293. this._renderingMesh = renderingMesh || mesh;
  21294. mesh.subMeshes.push(this);
  21295. this._trianglePlanes = [];
  21296. this._id = mesh.subMeshes.length - 1;
  21297. if (createBoundingBox) {
  21298. this.refreshBoundingInfo();
  21299. mesh.computeWorldMatrix(true);
  21300. }
  21301. }
  21302. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  21303. get: function () {
  21304. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  21305. },
  21306. enumerable: true,
  21307. configurable: true
  21308. });
  21309. SubMesh.prototype.getBoundingInfo = function () {
  21310. if (this.IsGlobal) {
  21311. return this._mesh.getBoundingInfo();
  21312. }
  21313. return this._boundingInfo;
  21314. };
  21315. SubMesh.prototype.getMesh = function () {
  21316. return this._mesh;
  21317. };
  21318. SubMesh.prototype.getRenderingMesh = function () {
  21319. return this._renderingMesh;
  21320. };
  21321. SubMesh.prototype.getMaterial = function () {
  21322. var rootMaterial = this._renderingMesh.material;
  21323. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  21324. var multiMaterial = rootMaterial;
  21325. return multiMaterial.getSubMaterial(this.materialIndex);
  21326. }
  21327. if (!rootMaterial) {
  21328. return this._mesh.getScene().defaultMaterial;
  21329. }
  21330. return rootMaterial;
  21331. };
  21332. // Methods
  21333. SubMesh.prototype.refreshBoundingInfo = function () {
  21334. this._lastColliderWorldVertices = null;
  21335. if (this.IsGlobal) {
  21336. return;
  21337. }
  21338. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21339. if (!data) {
  21340. this._boundingInfo = this._mesh._boundingInfo;
  21341. return;
  21342. }
  21343. var indices = this._renderingMesh.getIndices();
  21344. var extend;
  21345. //is this the only submesh?
  21346. if (this.indexStart === 0 && this.indexCount === indices.length) {
  21347. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  21348. extend = { minimum: this._renderingMesh.getBoundingInfo().minimum.clone(), maximum: this._renderingMesh.getBoundingInfo().maximum.clone() };
  21349. }
  21350. else {
  21351. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  21352. }
  21353. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  21354. };
  21355. SubMesh.prototype._checkCollision = function (collider) {
  21356. return this.getBoundingInfo()._checkCollision(collider);
  21357. };
  21358. SubMesh.prototype.updateBoundingInfo = function (world) {
  21359. if (!this.getBoundingInfo()) {
  21360. this.refreshBoundingInfo();
  21361. }
  21362. this.getBoundingInfo().update(world);
  21363. };
  21364. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  21365. return this.getBoundingInfo().isInFrustum(frustumPlanes);
  21366. };
  21367. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  21368. return this.getBoundingInfo().isCompletelyInFrustum(frustumPlanes);
  21369. };
  21370. SubMesh.prototype.render = function (enableAlphaMode) {
  21371. this._renderingMesh.render(this, enableAlphaMode);
  21372. };
  21373. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  21374. if (!this._linesIndexBuffer) {
  21375. var linesIndices = [];
  21376. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  21377. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  21378. }
  21379. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  21380. this.linesIndexCount = linesIndices.length;
  21381. }
  21382. return this._linesIndexBuffer;
  21383. };
  21384. SubMesh.prototype.canIntersects = function (ray) {
  21385. return ray.intersectsBox(this.getBoundingInfo().boundingBox);
  21386. };
  21387. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  21388. var intersectInfo = null;
  21389. // LineMesh first as it's also a Mesh...
  21390. if (this._mesh instanceof BABYLON.LinesMesh) {
  21391. var lineMesh = this._mesh;
  21392. // Line test
  21393. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  21394. var p0 = positions[indices[index]];
  21395. var p1 = positions[indices[index + 1]];
  21396. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  21397. if (length < 0) {
  21398. continue;
  21399. }
  21400. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  21401. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  21402. if (fastCheck) {
  21403. break;
  21404. }
  21405. }
  21406. }
  21407. }
  21408. else {
  21409. // Triangles test
  21410. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  21411. var p0 = positions[indices[index]];
  21412. var p1 = positions[indices[index + 1]];
  21413. var p2 = positions[indices[index + 2]];
  21414. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  21415. if (currentIntersectInfo) {
  21416. if (currentIntersectInfo.distance < 0) {
  21417. continue;
  21418. }
  21419. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  21420. intersectInfo = currentIntersectInfo;
  21421. intersectInfo.faceId = index / 3;
  21422. if (fastCheck) {
  21423. break;
  21424. }
  21425. }
  21426. }
  21427. }
  21428. }
  21429. return intersectInfo;
  21430. };
  21431. // Clone
  21432. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  21433. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  21434. if (!this.IsGlobal) {
  21435. result._boundingInfo = new BABYLON.BoundingInfo(this.getBoundingInfo().minimum, this.getBoundingInfo().maximum);
  21436. }
  21437. return result;
  21438. };
  21439. // Dispose
  21440. SubMesh.prototype.dispose = function () {
  21441. if (this._linesIndexBuffer) {
  21442. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  21443. this._linesIndexBuffer = null;
  21444. }
  21445. // Remove from mesh
  21446. var index = this._mesh.subMeshes.indexOf(this);
  21447. this._mesh.subMeshes.splice(index, 1);
  21448. };
  21449. // Statics
  21450. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  21451. var minVertexIndex = Number.MAX_VALUE;
  21452. var maxVertexIndex = -Number.MAX_VALUE;
  21453. renderingMesh = renderingMesh || mesh;
  21454. var indices = renderingMesh.getIndices();
  21455. for (var index = startIndex; index < startIndex + indexCount; index++) {
  21456. var vertexIndex = indices[index];
  21457. if (vertexIndex < minVertexIndex)
  21458. minVertexIndex = vertexIndex;
  21459. if (vertexIndex > maxVertexIndex)
  21460. maxVertexIndex = vertexIndex;
  21461. }
  21462. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  21463. };
  21464. return SubMesh;
  21465. }());
  21466. BABYLON.SubMesh = SubMesh;
  21467. })(BABYLON || (BABYLON = {}));
  21468. var BABYLON;
  21469. (function (BABYLON) {
  21470. var MeshBuilder = (function () {
  21471. function MeshBuilder() {
  21472. }
  21473. MeshBuilder.updateSideOrientationForRightHandedSystem = function (orientation, scene) {
  21474. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  21475. return BABYLON.Mesh.DOUBLESIDE;
  21476. }
  21477. if (!scene.useRightHandedSystem) {
  21478. if (orientation === undefined || orientation === null) {
  21479. return BABYLON.Mesh.FRONTSIDE;
  21480. }
  21481. switch (orientation) {
  21482. case BABYLON.Mesh.FRONTSIDE:
  21483. case BABYLON.Mesh.DEFAULTSIDE:
  21484. return BABYLON.Mesh.FRONTSIDE;
  21485. default:
  21486. return BABYLON.Mesh.BACKSIDE;
  21487. }
  21488. }
  21489. if (orientation === undefined || orientation === null) {
  21490. return BABYLON.Mesh.BACKSIDE;
  21491. }
  21492. switch (orientation) {
  21493. case BABYLON.Mesh.FRONTSIDE:
  21494. case BABYLON.Mesh.DEFAULTSIDE:
  21495. return BABYLON.Mesh.BACKSIDE;
  21496. default:
  21497. return BABYLON.Mesh.FRONTSIDE;
  21498. }
  21499. };
  21500. /**
  21501. * Creates a box mesh.
  21502. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  21503. * The parameter `size` sets the size (float) of each box side (default 1).
  21504. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  21505. * 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).
  21506. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  21507. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21508. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21509. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21510. */
  21511. MeshBuilder.CreateBox = function (name, options, scene) {
  21512. var box = new BABYLON.Mesh(name, scene);
  21513. options.sideOrientation = this.updateSideOrientationForRightHandedSystem(options.sideOrientation, scene);
  21514. var vertexData = BABYLON.VertexData.CreateBox(options);
  21515. vertexData.applyToMesh(box, options.updatable);
  21516. return box;
  21517. };
  21518. /**
  21519. * Creates a sphere mesh.
  21520. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  21521. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  21522. * 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`).
  21523. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  21524. * 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
  21525. * 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).
  21526. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21527. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21528. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21529. */
  21530. MeshBuilder.CreateSphere = function (name, options, scene) {
  21531. var sphere = new BABYLON.Mesh(name, scene);
  21532. options.sideOrientation = this.updateSideOrientationForRightHandedSystem(options.sideOrientation, scene);
  21533. var vertexData = BABYLON.VertexData.CreateSphere(options);
  21534. vertexData.applyToMesh(sphere, options.updatable);
  21535. return sphere;
  21536. };
  21537. /**
  21538. * Creates a plane polygonal mesh. By default, this is a disc.
  21539. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  21540. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  21541. * 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.
  21542. * 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
  21543. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21544. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21545. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21546. */
  21547. MeshBuilder.CreateDisc = function (name, options, scene) {
  21548. var disc = new BABYLON.Mesh(name, scene);
  21549. options.sideOrientation = this.updateSideOrientationForRightHandedSystem(options.sideOrientation, scene);
  21550. var vertexData = BABYLON.VertexData.CreateDisc(options);
  21551. vertexData.applyToMesh(disc, options.updatable);
  21552. return disc;
  21553. };
  21554. /**
  21555. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  21556. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  21557. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  21558. * 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`).
  21559. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  21560. * 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.
  21561. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21562. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21563. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21564. */
  21565. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  21566. var sphere = new BABYLON.Mesh(name, scene);
  21567. options.sideOrientation = this.updateSideOrientationForRightHandedSystem(options.sideOrientation, scene);
  21568. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  21569. vertexData.applyToMesh(sphere, options.updatable);
  21570. return sphere;
  21571. };
  21572. ;
  21573. /**
  21574. * Creates a ribbon mesh.
  21575. * 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.
  21576. *
  21577. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  21578. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  21579. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  21580. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  21581. * 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.
  21582. * 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.
  21583. * 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
  21584. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21585. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21586. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  21587. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21588. */
  21589. MeshBuilder.CreateRibbon = function (name, options, scene) {
  21590. var pathArray = options.pathArray;
  21591. var closeArray = options.closeArray;
  21592. var closePath = options.closePath;
  21593. var offset = options.offset;
  21594. var sideOrientation = this.updateSideOrientationForRightHandedSystem(options.sideOrientation, scene);
  21595. var instance = options.instance;
  21596. var updatable = options.updatable;
  21597. if (instance) {
  21598. // positionFunction : ribbon case
  21599. // only pathArray and sideOrientation parameters are taken into account for positions update
  21600. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  21601. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  21602. var positionFunction = function (positions) {
  21603. var minlg = pathArray[0].length;
  21604. var i = 0;
  21605. var ns = (instance.sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  21606. for (var si = 1; si <= ns; si++) {
  21607. for (var p = 0; p < pathArray.length; p++) {
  21608. var path = pathArray[p];
  21609. var l = path.length;
  21610. minlg = (minlg < l) ? minlg : l;
  21611. var j = 0;
  21612. while (j < minlg) {
  21613. positions[i] = path[j].x;
  21614. positions[i + 1] = path[j].y;
  21615. positions[i + 2] = path[j].z;
  21616. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  21617. BABYLON.Tmp.Vector3[0].x = path[j].x;
  21618. }
  21619. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  21620. BABYLON.Tmp.Vector3[1].x = path[j].x;
  21621. }
  21622. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  21623. BABYLON.Tmp.Vector3[0].y = path[j].y;
  21624. }
  21625. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  21626. BABYLON.Tmp.Vector3[1].y = path[j].y;
  21627. }
  21628. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  21629. BABYLON.Tmp.Vector3[0].z = path[j].z;
  21630. }
  21631. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  21632. BABYLON.Tmp.Vector3[1].z = path[j].z;
  21633. }
  21634. j++;
  21635. i += 3;
  21636. }
  21637. if (instance._closePath) {
  21638. positions[i] = path[0].x;
  21639. positions[i + 1] = path[0].y;
  21640. positions[i + 2] = path[0].z;
  21641. i += 3;
  21642. }
  21643. }
  21644. }
  21645. };
  21646. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21647. positionFunction(positions);
  21648. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  21649. instance._boundingInfo.update(instance._worldMatrix);
  21650. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  21651. if (!(instance.areNormalsFrozen)) {
  21652. var indices = instance.getIndices();
  21653. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21654. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  21655. if (instance._closePath) {
  21656. var indexFirst = 0;
  21657. var indexLast = 0;
  21658. for (var p = 0; p < pathArray.length; p++) {
  21659. indexFirst = instance._idx[p] * 3;
  21660. if (p + 1 < pathArray.length) {
  21661. indexLast = (instance._idx[p + 1] - 1) * 3;
  21662. }
  21663. else {
  21664. indexLast = normals.length - 3;
  21665. }
  21666. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  21667. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  21668. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  21669. normals[indexLast] = normals[indexFirst];
  21670. normals[indexLast + 1] = normals[indexFirst + 1];
  21671. normals[indexLast + 2] = normals[indexFirst + 2];
  21672. }
  21673. }
  21674. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  21675. }
  21676. return instance;
  21677. }
  21678. else {
  21679. var ribbon = new BABYLON.Mesh(name, scene);
  21680. ribbon.sideOrientation = sideOrientation;
  21681. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  21682. if (closePath) {
  21683. ribbon._idx = vertexData._idx;
  21684. }
  21685. ribbon._closePath = closePath;
  21686. ribbon._closeArray = closeArray;
  21687. vertexData.applyToMesh(ribbon, updatable);
  21688. return ribbon;
  21689. }
  21690. };
  21691. /**
  21692. * Creates a cylinder or a cone mesh.
  21693. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  21694. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  21695. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  21696. * 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.
  21697. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  21698. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  21699. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  21700. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  21701. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  21702. * 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).
  21703. * 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
  21704. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  21705. * 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
  21706. * 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.
  21707. * If `enclose` is false, a ring surface is one element.
  21708. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  21709. * 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
  21710. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21711. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21712. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21713. */
  21714. MeshBuilder.CreateCylinder = function (name, options, scene) {
  21715. var cylinder = new BABYLON.Mesh(name, scene);
  21716. options.sideOrientation = this.updateSideOrientationForRightHandedSystem(options.sideOrientation, scene);
  21717. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  21718. vertexData.applyToMesh(cylinder, options.updatable);
  21719. return cylinder;
  21720. };
  21721. /**
  21722. * Creates a torus mesh.
  21723. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  21724. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  21725. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  21726. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  21727. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21728. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21729. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21730. */
  21731. MeshBuilder.CreateTorus = function (name, options, scene) {
  21732. var torus = new BABYLON.Mesh(name, scene);
  21733. options.sideOrientation = this.updateSideOrientationForRightHandedSystem(options.sideOrientation, scene);
  21734. var vertexData = BABYLON.VertexData.CreateTorus(options);
  21735. vertexData.applyToMesh(torus, options.updatable);
  21736. return torus;
  21737. };
  21738. /**
  21739. * Creates a torus knot mesh.
  21740. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  21741. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  21742. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  21743. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  21744. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  21745. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21746. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21747. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21748. */
  21749. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  21750. var torusKnot = new BABYLON.Mesh(name, scene);
  21751. options.sideOrientation = this.updateSideOrientationForRightHandedSystem(options.sideOrientation, scene);
  21752. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  21753. vertexData.applyToMesh(torusKnot, options.updatable);
  21754. return torusKnot;
  21755. };
  21756. /**
  21757. * Creates a line system mesh.
  21758. * A line system is a pool of many lines gathered in a single mesh.
  21759. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  21760. * 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.
  21761. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  21762. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  21763. * 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
  21764. * 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
  21765. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  21766. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21767. */
  21768. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  21769. var instance = options.instance;
  21770. var lines = options.lines;
  21771. if (instance) {
  21772. var positionFunction = function (positions) {
  21773. var i = 0;
  21774. for (var l = 0; l < lines.length; l++) {
  21775. var points = lines[l];
  21776. for (var p = 0; p < points.length; p++) {
  21777. positions[i] = points[p].x;
  21778. positions[i + 1] = points[p].y;
  21779. positions[i + 2] = points[p].z;
  21780. i += 3;
  21781. }
  21782. }
  21783. };
  21784. instance.updateMeshPositions(positionFunction, false);
  21785. return instance;
  21786. }
  21787. // line system creation
  21788. var lineSystem = new BABYLON.LinesMesh(name, scene);
  21789. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  21790. vertexData.applyToMesh(lineSystem, options.updatable);
  21791. return lineSystem;
  21792. };
  21793. /**
  21794. * Creates a line mesh.
  21795. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  21796. * 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.
  21797. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  21798. * The parameter `points` is an array successive Vector3.
  21799. * 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
  21800. * When updating an instance, remember that only point positions can change, not the number of points.
  21801. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21802. */
  21803. MeshBuilder.CreateLines = function (name, options, scene) {
  21804. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance }, scene);
  21805. return lines;
  21806. };
  21807. /**
  21808. * Creates a dashed line mesh.
  21809. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  21810. * 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.
  21811. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  21812. * The parameter `points` is an array successive Vector3.
  21813. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  21814. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  21815. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  21816. * 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
  21817. * When updating an instance, remember that only point positions can change, not the number of points.
  21818. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21819. */
  21820. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  21821. var points = options.points;
  21822. var instance = options.instance;
  21823. var gapSize = options.gapSize;
  21824. var dashNb = options.dashNb;
  21825. var dashSize = options.dashSize;
  21826. if (instance) {
  21827. var positionFunction = function (positions) {
  21828. var curvect = BABYLON.Vector3.Zero();
  21829. var nbSeg = positions.length / 6;
  21830. var lg = 0;
  21831. var nb = 0;
  21832. var shft = 0;
  21833. var dashshft = 0;
  21834. var curshft = 0;
  21835. var p = 0;
  21836. var i = 0;
  21837. var j = 0;
  21838. for (i = 0; i < points.length - 1; i++) {
  21839. points[i + 1].subtractToRef(points[i], curvect);
  21840. lg += curvect.length();
  21841. }
  21842. shft = lg / nbSeg;
  21843. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  21844. for (i = 0; i < points.length - 1; i++) {
  21845. points[i + 1].subtractToRef(points[i], curvect);
  21846. nb = Math.floor(curvect.length() / shft);
  21847. curvect.normalize();
  21848. j = 0;
  21849. while (j < nb && p < positions.length) {
  21850. curshft = shft * j;
  21851. positions[p] = points[i].x + curshft * curvect.x;
  21852. positions[p + 1] = points[i].y + curshft * curvect.y;
  21853. positions[p + 2] = points[i].z + curshft * curvect.z;
  21854. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  21855. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  21856. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  21857. p += 6;
  21858. j++;
  21859. }
  21860. }
  21861. while (p < positions.length) {
  21862. positions[p] = points[i].x;
  21863. positions[p + 1] = points[i].y;
  21864. positions[p + 2] = points[i].z;
  21865. p += 3;
  21866. }
  21867. };
  21868. instance.updateMeshPositions(positionFunction, false);
  21869. return instance;
  21870. }
  21871. // dashed lines creation
  21872. var dashedLines = new BABYLON.LinesMesh(name, scene);
  21873. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  21874. vertexData.applyToMesh(dashedLines, options.updatable);
  21875. dashedLines.dashSize = dashSize;
  21876. dashedLines.gapSize = gapSize;
  21877. return dashedLines;
  21878. };
  21879. /**
  21880. * Creates an extruded shape mesh.
  21881. * 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.
  21882. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  21883. *
  21884. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  21885. * 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
  21886. * extruded along the Z axis.
  21887. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  21888. * 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.
  21889. * The parameter `scale` (float, default 1) is the value to scale the shape.
  21890. * 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
  21891. * 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
  21892. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  21893. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21894. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21895. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  21896. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21897. */
  21898. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  21899. var path = options.path;
  21900. var shape = options.shape;
  21901. var scale = options.scale || 1;
  21902. var rotation = options.rotation || 0;
  21903. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  21904. var updatable = options.updatable;
  21905. var sideOrientation = this.updateSideOrientationForRightHandedSystem(options.sideOrientation, scene);
  21906. var instance = options.instance;
  21907. var invertUV = options.invertUV || false;
  21908. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, instance, invertUV);
  21909. };
  21910. /**
  21911. * Creates an custom extruded shape mesh.
  21912. * 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.
  21913. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  21914. *
  21915. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  21916. * 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
  21917. * extruded along the Z axis.
  21918. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  21919. * 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
  21920. * and the distance of this point from the begining of the path :
  21921. * ```javascript
  21922. * var rotationFunction = function(i, distance) {
  21923. * // do things
  21924. * return rotationValue; }
  21925. * ```
  21926. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  21927. * 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
  21928. * and the distance of this point from the begining of the path :
  21929. * ```javascript
  21930. * var scaleFunction = function(i, distance) {
  21931. * // do things
  21932. * return scaleValue;}
  21933. * ```
  21934. * It must returns a float value that will be the scale value applied to the shape on each path point.
  21935. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  21936. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  21937. * 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
  21938. * 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
  21939. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  21940. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21941. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21942. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  21943. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21944. */
  21945. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  21946. var path = options.path;
  21947. var shape = options.shape;
  21948. var scaleFunction = options.scaleFunction || (function () { return 1; });
  21949. var rotationFunction = options.rotationFunction || (function () { return 0; });
  21950. var ribbonCloseArray = options.ribbonCloseArray || false;
  21951. var ribbonClosePath = options.ribbonClosePath || false;
  21952. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  21953. var updatable = options.updatable;
  21954. var sideOrientation = this.updateSideOrientationForRightHandedSystem(options.sideOrientation, scene);
  21955. var instance = options.instance;
  21956. var invertUV = options.invertUV || false;
  21957. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, instance, invertUV);
  21958. };
  21959. /**
  21960. * Creates lathe mesh.
  21961. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  21962. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  21963. *
  21964. * 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
  21965. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  21966. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  21967. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  21968. * 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.
  21969. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  21970. * 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
  21971. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21972. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21973. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  21974. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21975. */
  21976. MeshBuilder.CreateLathe = function (name, options, scene) {
  21977. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  21978. var closed = (options.closed === undefined) ? true : options.closed;
  21979. var shape = options.shape;
  21980. var radius = options.radius || 1;
  21981. var tessellation = options.tessellation || 64;
  21982. var updatable = options.updatable;
  21983. var sideOrientation = this.updateSideOrientationForRightHandedSystem(options.sideOrientation, scene);
  21984. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  21985. var pi2 = Math.PI * 2;
  21986. var paths = new Array();
  21987. var invertUV = options.invertUV || false;
  21988. var i = 0;
  21989. var p = 0;
  21990. var step = pi2 / tessellation * arc;
  21991. var rotated;
  21992. var path = new Array();
  21993. ;
  21994. for (i = 0; i <= tessellation; i++) {
  21995. var path = [];
  21996. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  21997. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  21998. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  21999. }
  22000. for (p = 0; p < shape.length; p++) {
  22001. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  22002. path.push(rotated);
  22003. }
  22004. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  22005. 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));
  22006. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  22007. }
  22008. paths.push(path);
  22009. }
  22010. // lathe ribbon
  22011. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV }, scene);
  22012. return lathe;
  22013. };
  22014. /**
  22015. * Creates a plane mesh.
  22016. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  22017. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  22018. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  22019. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  22020. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22021. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22022. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22023. */
  22024. MeshBuilder.CreatePlane = function (name, options, scene) {
  22025. var plane = new BABYLON.Mesh(name, scene);
  22026. options.sideOrientation = this.updateSideOrientationForRightHandedSystem(options.sideOrientation, scene);
  22027. var vertexData = BABYLON.VertexData.CreatePlane(options);
  22028. vertexData.applyToMesh(plane, options.updatable);
  22029. if (options.sourcePlane) {
  22030. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  22031. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  22032. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  22033. plane.rotate(vectorProduct, product);
  22034. }
  22035. return plane;
  22036. };
  22037. /**
  22038. * Creates a ground mesh.
  22039. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  22040. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  22041. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  22042. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22043. */
  22044. MeshBuilder.CreateGround = function (name, options, scene) {
  22045. var ground = new BABYLON.GroundMesh(name, scene);
  22046. ground._setReady(false);
  22047. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  22048. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  22049. ground._width = options.width || 1;
  22050. ground._height = options.height || 1;
  22051. ground._maxX = ground._width / 2;
  22052. ground._maxZ = ground._height / 2;
  22053. ground._minX = -ground._maxX;
  22054. ground._minZ = -ground._maxZ;
  22055. var vertexData = BABYLON.VertexData.CreateGround(options);
  22056. vertexData.applyToMesh(ground, options.updatable);
  22057. ground._setReady(true);
  22058. return ground;
  22059. };
  22060. /**
  22061. * Creates a tiled ground mesh.
  22062. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  22063. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  22064. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  22065. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  22066. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  22067. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  22068. * numbers of subdivisions on the ground width and height of each tile.
  22069. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22070. */
  22071. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  22072. var tiledGround = new BABYLON.Mesh(name, scene);
  22073. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  22074. vertexData.applyToMesh(tiledGround, options.updatable);
  22075. return tiledGround;
  22076. };
  22077. /**
  22078. * Creates a ground mesh from a height map.
  22079. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  22080. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  22081. * The parameter `url` sets the URL of the height map image resource.
  22082. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  22083. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  22084. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  22085. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  22086. * 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).
  22087. * This function is passed the newly built mesh :
  22088. * ```javascript
  22089. * function(mesh) { // do things
  22090. * return; }
  22091. * ```
  22092. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22093. */
  22094. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  22095. var width = options.width || 10.0;
  22096. var height = options.height || 10.0;
  22097. var subdivisions = options.subdivisions || 1 | 0;
  22098. var minHeight = options.minHeight || 0.0;
  22099. var maxHeight = options.maxHeight || 10.0;
  22100. var updatable = options.updatable;
  22101. var onReady = options.onReady;
  22102. var ground = new BABYLON.GroundMesh(name, scene);
  22103. ground._subdivisionsX = subdivisions;
  22104. ground._subdivisionsY = subdivisions;
  22105. ground._width = width;
  22106. ground._height = height;
  22107. ground._maxX = ground._width / 2.0;
  22108. ground._maxZ = ground._height / 2.0;
  22109. ground._minX = -ground._maxX;
  22110. ground._minZ = -ground._maxZ;
  22111. ground._setReady(false);
  22112. var onload = function (img) {
  22113. // Getting height map data
  22114. var canvas = document.createElement("canvas");
  22115. var context = canvas.getContext("2d");
  22116. var bufferWidth = img.width;
  22117. var bufferHeight = img.height;
  22118. canvas.width = bufferWidth;
  22119. canvas.height = bufferHeight;
  22120. context.drawImage(img, 0, 0);
  22121. // Create VertexData from map data
  22122. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  22123. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  22124. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  22125. width: width, height: height,
  22126. subdivisions: subdivisions,
  22127. minHeight: minHeight, maxHeight: maxHeight,
  22128. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  22129. });
  22130. vertexData.applyToMesh(ground, updatable);
  22131. ground._setReady(true);
  22132. //execute ready callback, if set
  22133. if (onReady) {
  22134. onReady(ground);
  22135. }
  22136. };
  22137. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  22138. return ground;
  22139. };
  22140. /**
  22141. * Creates a tube mesh.
  22142. * 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.
  22143. *
  22144. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  22145. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  22146. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  22147. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  22148. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  22149. * 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.
  22150. * It must return a radius value (positive float) :
  22151. * ```javascript
  22152. * var radiusFunction = function(i, distance) {
  22153. * // do things
  22154. * return radius; }
  22155. * ```
  22156. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  22157. * 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
  22158. * 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
  22159. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22160. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22161. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  22162. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22163. */
  22164. MeshBuilder.CreateTube = function (name, options, scene) {
  22165. var path = options.path;
  22166. var radius = options.radius || 1.0;
  22167. var tessellation = options.tessellation || 64 | 0;
  22168. var radiusFunction = options.radiusFunction;
  22169. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  22170. var invertUV = options.invertUV || false;
  22171. var updatable = options.updatable;
  22172. var sideOrientation = this.updateSideOrientationForRightHandedSystem(options.sideOrientation, scene);
  22173. var instance = options.instance;
  22174. options.arc = (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  22175. // tube geometry
  22176. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  22177. var tangents = path3D.getTangents();
  22178. var normals = path3D.getNormals();
  22179. var distances = path3D.getDistances();
  22180. var pi2 = Math.PI * 2;
  22181. var step = pi2 / tessellation * arc;
  22182. var returnRadius = function () { return radius; };
  22183. var radiusFunctionFinal = radiusFunction || returnRadius;
  22184. var circlePath;
  22185. var rad;
  22186. var normal;
  22187. var rotated;
  22188. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  22189. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  22190. for (var i = 0; i < path.length; i++) {
  22191. rad = radiusFunctionFinal(i, distances[i]); // current radius
  22192. circlePath = Array(); // current circle array
  22193. normal = normals[i]; // current normal
  22194. for (var t = 0; t < tessellation; t++) {
  22195. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  22196. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  22197. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  22198. rotated.scaleInPlace(rad).addInPlace(path[i]);
  22199. circlePath[t] = rotated;
  22200. }
  22201. circlePaths[index] = circlePath;
  22202. index++;
  22203. }
  22204. // cap
  22205. var capPath = function (nbPoints, pathIndex) {
  22206. var pointCap = Array();
  22207. for (var i = 0; i < nbPoints; i++) {
  22208. pointCap.push(path[pathIndex]);
  22209. }
  22210. return pointCap;
  22211. };
  22212. switch (cap) {
  22213. case BABYLON.Mesh.NO_CAP:
  22214. break;
  22215. case BABYLON.Mesh.CAP_START:
  22216. circlePaths[0] = capPath(tessellation, 0);
  22217. circlePaths[1] = circlePaths[2].slice(0);
  22218. break;
  22219. case BABYLON.Mesh.CAP_END:
  22220. circlePaths[index] = circlePaths[index - 1].slice(0);
  22221. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  22222. break;
  22223. case BABYLON.Mesh.CAP_ALL:
  22224. circlePaths[0] = capPath(tessellation, 0);
  22225. circlePaths[1] = circlePaths[2].slice(0);
  22226. circlePaths[index] = circlePaths[index - 1].slice(0);
  22227. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  22228. break;
  22229. default:
  22230. break;
  22231. }
  22232. return circlePaths;
  22233. };
  22234. var path3D;
  22235. var pathArray;
  22236. if (instance) {
  22237. var arc = options.arc || instance.arc;
  22238. path3D = (instance.path3D).update(path);
  22239. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  22240. instance = MeshBuilder.CreateRibbon(null, { pathArray: pathArray, instance: instance });
  22241. instance.path3D = path3D;
  22242. instance.pathArray = pathArray;
  22243. instance.arc = arc;
  22244. return instance;
  22245. }
  22246. // tube creation
  22247. path3D = new BABYLON.Path3D(path);
  22248. var newPathArray = new Array();
  22249. cap = (cap < 0 || cap > 3) ? 0 : cap;
  22250. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  22251. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV }, scene);
  22252. tube.pathArray = pathArray;
  22253. tube.path3D = path3D;
  22254. tube.tessellation = tessellation;
  22255. tube.cap = cap;
  22256. tube.arc = options.arc;
  22257. return tube;
  22258. };
  22259. /**
  22260. * Creates a polyhedron mesh.
  22261. *
  22262. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  22263. * 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
  22264. * to choose the wanted type.
  22265. * The parameter `size` (positive float, default 1) sets the polygon size.
  22266. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  22267. * 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`.
  22268. * 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
  22269. * 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)`).
  22270. * 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
  22271. * 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.
  22272. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22273. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22274. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22275. */
  22276. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  22277. var polyhedron = new BABYLON.Mesh(name, scene);
  22278. options.sideOrientation = this.updateSideOrientationForRightHandedSystem(options.sideOrientation, scene);
  22279. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  22280. vertexData.applyToMesh(polyhedron, options.updatable);
  22281. return polyhedron;
  22282. };
  22283. /**
  22284. * Creates a decal mesh.
  22285. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  22286. * 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.
  22287. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  22288. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  22289. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  22290. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  22291. */
  22292. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  22293. var indices = sourceMesh.getIndices();
  22294. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22295. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  22296. var position = options.position || BABYLON.Vector3.Zero();
  22297. var normal = options.normal || BABYLON.Vector3.Up();
  22298. var size = options.size || new BABYLON.Vector3(1, 1, 1);
  22299. var angle = options.angle || 0;
  22300. // Getting correct rotation
  22301. if (!normal) {
  22302. var target = new BABYLON.Vector3(0, 0, 1);
  22303. var camera = sourceMesh.getScene().activeCamera;
  22304. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  22305. normal = camera.globalPosition.subtract(cameraWorldTarget);
  22306. }
  22307. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  22308. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  22309. var pitch = Math.atan2(normal.y, len);
  22310. // Matrix
  22311. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  22312. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  22313. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  22314. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  22315. var vertexData = new BABYLON.VertexData();
  22316. vertexData.indices = [];
  22317. vertexData.positions = [];
  22318. vertexData.normals = [];
  22319. vertexData.uvs = [];
  22320. var currentVertexDataIndex = 0;
  22321. var extractDecalVector3 = function (indexId) {
  22322. var vertexId = indices[indexId];
  22323. var result = new BABYLON.PositionNormalVertex();
  22324. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  22325. // Send vector to decal local world
  22326. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  22327. // Get normal
  22328. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  22329. return result;
  22330. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  22331. var clip = function (vertices, axis) {
  22332. if (vertices.length === 0) {
  22333. return vertices;
  22334. }
  22335. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  22336. var clipVertices = function (v0, v1) {
  22337. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  22338. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  22339. };
  22340. var result = new Array();
  22341. for (var index = 0; index < vertices.length; index += 3) {
  22342. var v1Out;
  22343. var v2Out;
  22344. var v3Out;
  22345. var total = 0;
  22346. var nV1, nV2, nV3, nV4;
  22347. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  22348. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  22349. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  22350. v1Out = d1 > 0;
  22351. v2Out = d2 > 0;
  22352. v3Out = d3 > 0;
  22353. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  22354. switch (total) {
  22355. case 0:
  22356. result.push(vertices[index]);
  22357. result.push(vertices[index + 1]);
  22358. result.push(vertices[index + 2]);
  22359. break;
  22360. case 1:
  22361. if (v1Out) {
  22362. nV1 = vertices[index + 1];
  22363. nV2 = vertices[index + 2];
  22364. nV3 = clipVertices(vertices[index], nV1);
  22365. nV4 = clipVertices(vertices[index], nV2);
  22366. }
  22367. if (v2Out) {
  22368. nV1 = vertices[index];
  22369. nV2 = vertices[index + 2];
  22370. nV3 = clipVertices(vertices[index + 1], nV1);
  22371. nV4 = clipVertices(vertices[index + 1], nV2);
  22372. result.push(nV3);
  22373. result.push(nV2.clone());
  22374. result.push(nV1.clone());
  22375. result.push(nV2.clone());
  22376. result.push(nV3.clone());
  22377. result.push(nV4);
  22378. break;
  22379. }
  22380. if (v3Out) {
  22381. nV1 = vertices[index];
  22382. nV2 = vertices[index + 1];
  22383. nV3 = clipVertices(vertices[index + 2], nV1);
  22384. nV4 = clipVertices(vertices[index + 2], nV2);
  22385. }
  22386. result.push(nV1.clone());
  22387. result.push(nV2.clone());
  22388. result.push(nV3);
  22389. result.push(nV4);
  22390. result.push(nV3.clone());
  22391. result.push(nV2.clone());
  22392. break;
  22393. case 2:
  22394. if (!v1Out) {
  22395. nV1 = vertices[index].clone();
  22396. nV2 = clipVertices(nV1, vertices[index + 1]);
  22397. nV3 = clipVertices(nV1, vertices[index + 2]);
  22398. result.push(nV1);
  22399. result.push(nV2);
  22400. result.push(nV3);
  22401. }
  22402. if (!v2Out) {
  22403. nV1 = vertices[index + 1].clone();
  22404. nV2 = clipVertices(nV1, vertices[index + 2]);
  22405. nV3 = clipVertices(nV1, vertices[index]);
  22406. result.push(nV1);
  22407. result.push(nV2);
  22408. result.push(nV3);
  22409. }
  22410. if (!v3Out) {
  22411. nV1 = vertices[index + 2].clone();
  22412. nV2 = clipVertices(nV1, vertices[index]);
  22413. nV3 = clipVertices(nV1, vertices[index + 1]);
  22414. result.push(nV1);
  22415. result.push(nV2);
  22416. result.push(nV3);
  22417. }
  22418. break;
  22419. case 3:
  22420. break;
  22421. }
  22422. }
  22423. return result;
  22424. };
  22425. for (var index = 0; index < indices.length; index += 3) {
  22426. var faceVertices = new Array();
  22427. faceVertices.push(extractDecalVector3(index));
  22428. faceVertices.push(extractDecalVector3(index + 1));
  22429. faceVertices.push(extractDecalVector3(index + 2));
  22430. // Clip
  22431. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  22432. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  22433. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  22434. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  22435. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  22436. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  22437. if (faceVertices.length === 0) {
  22438. continue;
  22439. }
  22440. // Add UVs and get back to world
  22441. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  22442. var vertex = faceVertices[vIndex];
  22443. //TODO check for Int32Array
  22444. vertexData.indices.push(currentVertexDataIndex);
  22445. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  22446. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  22447. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  22448. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  22449. currentVertexDataIndex++;
  22450. }
  22451. }
  22452. // Return mesh
  22453. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  22454. vertexData.applyToMesh(decal);
  22455. decal.position = position.clone();
  22456. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  22457. return decal;
  22458. };
  22459. // Privates
  22460. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV) {
  22461. // extrusion geometry
  22462. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  22463. var tangents = path3D.getTangents();
  22464. var normals = path3D.getNormals();
  22465. var binormals = path3D.getBinormals();
  22466. var distances = path3D.getDistances();
  22467. var angle = 0;
  22468. var returnScale = function () { return scale; };
  22469. var returnRotation = function () { return rotation; };
  22470. var rotate = custom ? rotateFunction : returnRotation;
  22471. var scl = custom ? scaleFunction : returnScale;
  22472. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  22473. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  22474. for (var i = 0; i < curve.length; i++) {
  22475. var shapePath = new Array();
  22476. var angleStep = rotate(i, distances[i]);
  22477. var scaleRatio = scl(i, distances[i]);
  22478. for (var p = 0; p < shape.length; p++) {
  22479. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  22480. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  22481. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  22482. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  22483. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  22484. shapePath[p] = rotated;
  22485. }
  22486. shapePaths[index] = shapePath;
  22487. angle += angleStep;
  22488. index++;
  22489. }
  22490. // cap
  22491. var capPath = function (shapePath) {
  22492. var pointCap = Array();
  22493. var barycenter = BABYLON.Vector3.Zero();
  22494. var i;
  22495. for (i = 0; i < shapePath.length; i++) {
  22496. barycenter.addInPlace(shapePath[i]);
  22497. }
  22498. barycenter.scaleInPlace(1 / shapePath.length);
  22499. for (i = 0; i < shapePath.length; i++) {
  22500. pointCap.push(barycenter);
  22501. }
  22502. return pointCap;
  22503. };
  22504. switch (cap) {
  22505. case BABYLON.Mesh.NO_CAP:
  22506. break;
  22507. case BABYLON.Mesh.CAP_START:
  22508. shapePaths[0] = capPath(shapePaths[2]);
  22509. shapePaths[1] = shapePaths[2].slice(0);
  22510. break;
  22511. case BABYLON.Mesh.CAP_END:
  22512. shapePaths[index] = shapePaths[index - 1];
  22513. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  22514. break;
  22515. case BABYLON.Mesh.CAP_ALL:
  22516. shapePaths[0] = capPath(shapePaths[2]);
  22517. shapePaths[1] = shapePaths[2].slice(0);
  22518. shapePaths[index] = shapePaths[index - 1];
  22519. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  22520. break;
  22521. default:
  22522. break;
  22523. }
  22524. return shapePaths;
  22525. };
  22526. var path3D;
  22527. var pathArray;
  22528. if (instance) {
  22529. path3D = (instance.path3D).update(curve);
  22530. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  22531. instance = BABYLON.Mesh.CreateRibbon(null, pathArray, null, null, null, null, null, null, instance);
  22532. return instance;
  22533. }
  22534. // extruded shape creation
  22535. path3D = new BABYLON.Path3D(curve);
  22536. var newShapePaths = new Array();
  22537. cap = (cap < 0 || cap > 3) ? 0 : cap;
  22538. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  22539. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV }, scene);
  22540. extrudedGeneric.pathArray = pathArray;
  22541. extrudedGeneric.path3D = path3D;
  22542. extrudedGeneric.cap = cap;
  22543. return extrudedGeneric;
  22544. };
  22545. return MeshBuilder;
  22546. }());
  22547. BABYLON.MeshBuilder = MeshBuilder;
  22548. })(BABYLON || (BABYLON = {}));
  22549. var BABYLON;
  22550. (function (BABYLON) {
  22551. var BaseTexture = (function () {
  22552. function BaseTexture(scene) {
  22553. this.hasAlpha = false;
  22554. this.getAlphaFromRGB = false;
  22555. this.level = 1;
  22556. this.coordinatesIndex = 0;
  22557. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  22558. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  22559. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  22560. this.anisotropicFilteringLevel = 4;
  22561. this.isCube = false;
  22562. this.isRenderTarget = false;
  22563. this.animations = new Array();
  22564. /**
  22565. * An event triggered when the texture is disposed.
  22566. * @type {BABYLON.Observable}
  22567. */
  22568. this.onDisposeObservable = new BABYLON.Observable();
  22569. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  22570. this._scene = scene;
  22571. this._scene.textures.push(this);
  22572. }
  22573. BaseTexture.prototype.toString = function () {
  22574. return this.name;
  22575. };
  22576. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  22577. set: function (callback) {
  22578. if (this._onDisposeObserver) {
  22579. this.onDisposeObservable.remove(this._onDisposeObserver);
  22580. }
  22581. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  22582. },
  22583. enumerable: true,
  22584. configurable: true
  22585. });
  22586. BaseTexture.prototype.getScene = function () {
  22587. return this._scene;
  22588. };
  22589. BaseTexture.prototype.getTextureMatrix = function () {
  22590. return null;
  22591. };
  22592. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  22593. return null;
  22594. };
  22595. BaseTexture.prototype.getInternalTexture = function () {
  22596. return this._texture;
  22597. };
  22598. BaseTexture.prototype.isReady = function () {
  22599. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  22600. return true;
  22601. }
  22602. if (this._texture) {
  22603. return this._texture.isReady;
  22604. }
  22605. return false;
  22606. };
  22607. BaseTexture.prototype.getSize = function () {
  22608. if (this._texture._width) {
  22609. return new BABYLON.Size(this._texture._width, this._texture._height);
  22610. }
  22611. if (this._texture._size) {
  22612. return new BABYLON.Size(this._texture._size, this._texture._size);
  22613. }
  22614. return BABYLON.Size.Zero();
  22615. };
  22616. BaseTexture.prototype.getBaseSize = function () {
  22617. if (!this.isReady() || !this._texture)
  22618. return BABYLON.Size.Zero();
  22619. if (this._texture._size) {
  22620. return new BABYLON.Size(this._texture._size, this._texture._size);
  22621. }
  22622. return new BABYLON.Size(this._texture._baseWidth, this._texture._baseHeight);
  22623. };
  22624. BaseTexture.prototype.scale = function (ratio) {
  22625. };
  22626. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  22627. get: function () {
  22628. return false;
  22629. },
  22630. enumerable: true,
  22631. configurable: true
  22632. });
  22633. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  22634. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  22635. for (var index = 0; index < texturesCache.length; index++) {
  22636. var texturesCacheEntry = texturesCache[index];
  22637. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  22638. texturesCache.splice(index, 1);
  22639. return;
  22640. }
  22641. }
  22642. };
  22643. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  22644. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  22645. for (var index = 0; index < texturesCache.length; index++) {
  22646. var texturesCacheEntry = texturesCache[index];
  22647. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  22648. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  22649. texturesCacheEntry.references++;
  22650. return texturesCacheEntry;
  22651. }
  22652. }
  22653. }
  22654. return null;
  22655. };
  22656. BaseTexture.prototype.delayLoad = function () {
  22657. };
  22658. BaseTexture.prototype.clone = function () {
  22659. return null;
  22660. };
  22661. BaseTexture.prototype.releaseInternalTexture = function () {
  22662. if (this._texture) {
  22663. this._scene.getEngine().releaseInternalTexture(this._texture);
  22664. delete this._texture;
  22665. }
  22666. };
  22667. BaseTexture.prototype.dispose = function () {
  22668. // Animations
  22669. this.getScene().stopAnimation(this);
  22670. // Remove from scene
  22671. var index = this._scene.textures.indexOf(this);
  22672. if (index >= 0) {
  22673. this._scene.textures.splice(index, 1);
  22674. }
  22675. if (this._texture === undefined) {
  22676. return;
  22677. }
  22678. // Release
  22679. this.releaseInternalTexture();
  22680. // Callback
  22681. this.onDisposeObservable.notifyObservers(this);
  22682. this.onDisposeObservable.clear();
  22683. };
  22684. BaseTexture.prototype.serialize = function () {
  22685. if (!this.name) {
  22686. return null;
  22687. }
  22688. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  22689. // Animations
  22690. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  22691. return serializationObject;
  22692. };
  22693. __decorate([
  22694. BABYLON.serialize()
  22695. ], BaseTexture.prototype, "name", void 0);
  22696. __decorate([
  22697. BABYLON.serialize()
  22698. ], BaseTexture.prototype, "hasAlpha", void 0);
  22699. __decorate([
  22700. BABYLON.serialize()
  22701. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  22702. __decorate([
  22703. BABYLON.serialize()
  22704. ], BaseTexture.prototype, "level", void 0);
  22705. __decorate([
  22706. BABYLON.serialize()
  22707. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  22708. __decorate([
  22709. BABYLON.serialize()
  22710. ], BaseTexture.prototype, "coordinatesMode", void 0);
  22711. __decorate([
  22712. BABYLON.serialize()
  22713. ], BaseTexture.prototype, "wrapU", void 0);
  22714. __decorate([
  22715. BABYLON.serialize()
  22716. ], BaseTexture.prototype, "wrapV", void 0);
  22717. __decorate([
  22718. BABYLON.serialize()
  22719. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  22720. __decorate([
  22721. BABYLON.serialize()
  22722. ], BaseTexture.prototype, "isCube", void 0);
  22723. __decorate([
  22724. BABYLON.serialize()
  22725. ], BaseTexture.prototype, "isRenderTarget", void 0);
  22726. return BaseTexture;
  22727. }());
  22728. BABYLON.BaseTexture = BaseTexture;
  22729. })(BABYLON || (BABYLON = {}));
  22730. var BABYLON;
  22731. (function (BABYLON) {
  22732. var Texture = (function (_super) {
  22733. __extends(Texture, _super);
  22734. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
  22735. var _this = this;
  22736. if (noMipmap === void 0) { noMipmap = false; }
  22737. if (invertY === void 0) { invertY = true; }
  22738. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  22739. if (onLoad === void 0) { onLoad = null; }
  22740. if (onError === void 0) { onError = null; }
  22741. if (buffer === void 0) { buffer = null; }
  22742. if (deleteBuffer === void 0) { deleteBuffer = false; }
  22743. _super.call(this, scene);
  22744. this.uOffset = 0;
  22745. this.vOffset = 0;
  22746. this.uScale = 1.0;
  22747. this.vScale = 1.0;
  22748. this.uAng = 0;
  22749. this.vAng = 0;
  22750. this.wAng = 0;
  22751. this.name = url;
  22752. this.url = url;
  22753. this._noMipmap = noMipmap;
  22754. this._invertY = invertY;
  22755. this._samplingMode = samplingMode;
  22756. this._buffer = buffer;
  22757. this._deleteBuffer = deleteBuffer;
  22758. if (!url) {
  22759. return;
  22760. }
  22761. this._texture = this._getFromCache(url, noMipmap, samplingMode);
  22762. var load = function () {
  22763. if (_this._onLoadObservarble && _this._onLoadObservarble.hasObservers()) {
  22764. _this.onLoadObservable.notifyObservers(true);
  22765. }
  22766. if (onLoad) {
  22767. onLoad();
  22768. }
  22769. };
  22770. if (!this._texture) {
  22771. if (!scene.useDelayedTextureLoading) {
  22772. this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, this._samplingMode, load, onError, this._buffer);
  22773. if (deleteBuffer) {
  22774. delete this._buffer;
  22775. }
  22776. }
  22777. else {
  22778. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  22779. this._delayedOnLoad = load;
  22780. this._delayedOnError = onError;
  22781. }
  22782. }
  22783. else {
  22784. if (this._texture.isReady) {
  22785. BABYLON.Tools.SetImmediate(function () { return load(); });
  22786. }
  22787. else {
  22788. this._texture.onLoadedCallbacks.push(load);
  22789. }
  22790. }
  22791. }
  22792. Object.defineProperty(Texture.prototype, "noMipmap", {
  22793. get: function () {
  22794. return this._noMipmap;
  22795. },
  22796. enumerable: true,
  22797. configurable: true
  22798. });
  22799. Texture.prototype.delayLoad = function () {
  22800. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  22801. return;
  22802. }
  22803. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  22804. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  22805. if (!this._texture) {
  22806. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer);
  22807. if (this._deleteBuffer) {
  22808. delete this._buffer;
  22809. }
  22810. }
  22811. };
  22812. Texture.prototype.updateSamplingMode = function (samplingMode) {
  22813. if (!this._texture) {
  22814. return;
  22815. }
  22816. this._samplingMode = samplingMode;
  22817. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  22818. };
  22819. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  22820. x *= this.uScale;
  22821. y *= this.vScale;
  22822. x -= 0.5 * this.uScale;
  22823. y -= 0.5 * this.vScale;
  22824. z -= 0.5;
  22825. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  22826. t.x += 0.5 * this.uScale + this.uOffset;
  22827. t.y += 0.5 * this.vScale + this.vOffset;
  22828. t.z += 0.5;
  22829. };
  22830. Texture.prototype.getTextureMatrix = function () {
  22831. if (this.uOffset === this._cachedUOffset &&
  22832. this.vOffset === this._cachedVOffset &&
  22833. this.uScale === this._cachedUScale &&
  22834. this.vScale === this._cachedVScale &&
  22835. this.uAng === this._cachedUAng &&
  22836. this.vAng === this._cachedVAng &&
  22837. this.wAng === this._cachedWAng) {
  22838. return this._cachedTextureMatrix;
  22839. }
  22840. this._cachedUOffset = this.uOffset;
  22841. this._cachedVOffset = this.vOffset;
  22842. this._cachedUScale = this.uScale;
  22843. this._cachedVScale = this.vScale;
  22844. this._cachedUAng = this.uAng;
  22845. this._cachedVAng = this.vAng;
  22846. this._cachedWAng = this.wAng;
  22847. if (!this._cachedTextureMatrix) {
  22848. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  22849. this._rowGenerationMatrix = new BABYLON.Matrix();
  22850. this._t0 = BABYLON.Vector3.Zero();
  22851. this._t1 = BABYLON.Vector3.Zero();
  22852. this._t2 = BABYLON.Vector3.Zero();
  22853. }
  22854. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  22855. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  22856. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  22857. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  22858. this._t1.subtractInPlace(this._t0);
  22859. this._t2.subtractInPlace(this._t0);
  22860. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  22861. this._cachedTextureMatrix.m[0] = this._t1.x;
  22862. this._cachedTextureMatrix.m[1] = this._t1.y;
  22863. this._cachedTextureMatrix.m[2] = this._t1.z;
  22864. this._cachedTextureMatrix.m[4] = this._t2.x;
  22865. this._cachedTextureMatrix.m[5] = this._t2.y;
  22866. this._cachedTextureMatrix.m[6] = this._t2.z;
  22867. this._cachedTextureMatrix.m[8] = this._t0.x;
  22868. this._cachedTextureMatrix.m[9] = this._t0.y;
  22869. this._cachedTextureMatrix.m[10] = this._t0.z;
  22870. return this._cachedTextureMatrix;
  22871. };
  22872. Texture.prototype.getReflectionTextureMatrix = function () {
  22873. if (this.uOffset === this._cachedUOffset &&
  22874. this.vOffset === this._cachedVOffset &&
  22875. this.uScale === this._cachedUScale &&
  22876. this.vScale === this._cachedVScale &&
  22877. this.coordinatesMode === this._cachedCoordinatesMode) {
  22878. return this._cachedTextureMatrix;
  22879. }
  22880. if (!this._cachedTextureMatrix) {
  22881. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  22882. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  22883. }
  22884. this._cachedCoordinatesMode = this.coordinatesMode;
  22885. switch (this.coordinatesMode) {
  22886. case Texture.PLANAR_MODE:
  22887. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  22888. this._cachedTextureMatrix[0] = this.uScale;
  22889. this._cachedTextureMatrix[5] = this.vScale;
  22890. this._cachedTextureMatrix[12] = this.uOffset;
  22891. this._cachedTextureMatrix[13] = this.vOffset;
  22892. break;
  22893. case Texture.PROJECTION_MODE:
  22894. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  22895. this._projectionModeMatrix.m[0] = 0.5;
  22896. this._projectionModeMatrix.m[5] = -0.5;
  22897. this._projectionModeMatrix.m[10] = 0.0;
  22898. this._projectionModeMatrix.m[12] = 0.5;
  22899. this._projectionModeMatrix.m[13] = 0.5;
  22900. this._projectionModeMatrix.m[14] = 1.0;
  22901. this._projectionModeMatrix.m[15] = 1.0;
  22902. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  22903. break;
  22904. default:
  22905. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  22906. break;
  22907. }
  22908. return this._cachedTextureMatrix;
  22909. };
  22910. Texture.prototype.clone = function () {
  22911. var _this = this;
  22912. return BABYLON.SerializationHelper.Clone(function () {
  22913. return new Texture(_this._texture.url, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  22914. }, this);
  22915. };
  22916. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  22917. get: function () {
  22918. if (!this._onLoadObservarble) {
  22919. this._onLoadObservarble = new BABYLON.Observable();
  22920. }
  22921. return this._onLoadObservarble;
  22922. },
  22923. enumerable: true,
  22924. configurable: true
  22925. });
  22926. // Statics
  22927. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError) {
  22928. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  22929. if (onLoad === void 0) { onLoad = null; }
  22930. if (onError === void 0) { onError = null; }
  22931. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data);
  22932. };
  22933. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  22934. if (parsedTexture.isCube) {
  22935. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  22936. }
  22937. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  22938. return null;
  22939. }
  22940. var texture = BABYLON.SerializationHelper.Parse(function () {
  22941. if (parsedTexture.customType) {
  22942. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  22943. return customTexture.Parse(parsedTexture, scene, rootUrl);
  22944. }
  22945. else if (parsedTexture.mirrorPlane) {
  22946. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  22947. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  22948. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  22949. return mirrorTexture;
  22950. }
  22951. else if (parsedTexture.isRenderTarget) {
  22952. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  22953. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  22954. return renderTargetTexture;
  22955. }
  22956. else {
  22957. var texture;
  22958. if (parsedTexture.base64String) {
  22959. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
  22960. }
  22961. else {
  22962. texture = new Texture(rootUrl + parsedTexture.name, scene);
  22963. }
  22964. return texture;
  22965. }
  22966. }, parsedTexture, scene);
  22967. // Animations
  22968. if (parsedTexture.animations) {
  22969. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  22970. var parsedAnimation = parsedTexture.animations[animationIndex];
  22971. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  22972. }
  22973. }
  22974. return texture;
  22975. };
  22976. // Constants
  22977. Texture.NEAREST_SAMPLINGMODE = 1;
  22978. Texture.BILINEAR_SAMPLINGMODE = 2;
  22979. Texture.TRILINEAR_SAMPLINGMODE = 3;
  22980. Texture.EXPLICIT_MODE = 0;
  22981. Texture.SPHERICAL_MODE = 1;
  22982. Texture.PLANAR_MODE = 2;
  22983. Texture.CUBIC_MODE = 3;
  22984. Texture.PROJECTION_MODE = 4;
  22985. Texture.SKYBOX_MODE = 5;
  22986. Texture.INVCUBIC_MODE = 6;
  22987. Texture.EQUIRECTANGULAR_MODE = 7;
  22988. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  22989. Texture.CLAMP_ADDRESSMODE = 0;
  22990. Texture.WRAP_ADDRESSMODE = 1;
  22991. Texture.MIRROR_ADDRESSMODE = 2;
  22992. __decorate([
  22993. BABYLON.serialize()
  22994. ], Texture.prototype, "url", void 0);
  22995. __decorate([
  22996. BABYLON.serialize()
  22997. ], Texture.prototype, "uOffset", void 0);
  22998. __decorate([
  22999. BABYLON.serialize()
  23000. ], Texture.prototype, "vOffset", void 0);
  23001. __decorate([
  23002. BABYLON.serialize()
  23003. ], Texture.prototype, "uScale", void 0);
  23004. __decorate([
  23005. BABYLON.serialize()
  23006. ], Texture.prototype, "vScale", void 0);
  23007. __decorate([
  23008. BABYLON.serialize()
  23009. ], Texture.prototype, "uAng", void 0);
  23010. __decorate([
  23011. BABYLON.serialize()
  23012. ], Texture.prototype, "vAng", void 0);
  23013. __decorate([
  23014. BABYLON.serialize()
  23015. ], Texture.prototype, "wAng", void 0);
  23016. return Texture;
  23017. }(BABYLON.BaseTexture));
  23018. BABYLON.Texture = Texture;
  23019. })(BABYLON || (BABYLON = {}));
  23020. var BABYLON;
  23021. (function (BABYLON) {
  23022. var CubeTexture = (function (_super) {
  23023. __extends(CubeTexture, _super);
  23024. function CubeTexture(rootUrl, scene, extensions, noMipmap, files) {
  23025. _super.call(this, scene);
  23026. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  23027. this.name = rootUrl;
  23028. this.url = rootUrl;
  23029. this._noMipmap = noMipmap;
  23030. this.hasAlpha = false;
  23031. if (!rootUrl && !files) {
  23032. return;
  23033. }
  23034. this._texture = this._getFromCache(rootUrl, noMipmap);
  23035. if (!files) {
  23036. if (!extensions) {
  23037. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  23038. }
  23039. files = [];
  23040. for (var index = 0; index < extensions.length; index++) {
  23041. files.push(rootUrl + extensions[index]);
  23042. }
  23043. this._extensions = extensions;
  23044. }
  23045. this._files = files;
  23046. if (!this._texture) {
  23047. if (!scene.useDelayedTextureLoading) {
  23048. this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap);
  23049. }
  23050. else {
  23051. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  23052. }
  23053. }
  23054. this.isCube = true;
  23055. this._textureMatrix = BABYLON.Matrix.Identity();
  23056. }
  23057. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  23058. return new CubeTexture("", scene, null, noMipmap, files);
  23059. };
  23060. // Methods
  23061. CubeTexture.prototype.delayLoad = function () {
  23062. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  23063. return;
  23064. }
  23065. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  23066. this._texture = this._getFromCache(this.url, this._noMipmap);
  23067. if (!this._texture) {
  23068. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._files, this._noMipmap);
  23069. }
  23070. };
  23071. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  23072. return this._textureMatrix;
  23073. };
  23074. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  23075. var texture = BABYLON.SerializationHelper.Parse(function () {
  23076. return new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  23077. }, parsedTexture, scene);
  23078. // Animations
  23079. if (parsedTexture.animations) {
  23080. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  23081. var parsedAnimation = parsedTexture.animations[animationIndex];
  23082. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  23083. }
  23084. }
  23085. return texture;
  23086. };
  23087. CubeTexture.prototype.clone = function () {
  23088. var _this = this;
  23089. return BABYLON.SerializationHelper.Clone(function () {
  23090. return new CubeTexture(_this.url, _this.getScene(), _this._extensions, _this._noMipmap, _this._files);
  23091. }, this);
  23092. };
  23093. return CubeTexture;
  23094. }(BABYLON.BaseTexture));
  23095. BABYLON.CubeTexture = CubeTexture;
  23096. })(BABYLON || (BABYLON = {}));
  23097. var BABYLON;
  23098. (function (BABYLON) {
  23099. var RenderTargetTexture = (function (_super) {
  23100. __extends(RenderTargetTexture, _super);
  23101. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer) {
  23102. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  23103. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  23104. if (isCube === void 0) { isCube = false; }
  23105. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  23106. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  23107. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  23108. _super.call(this, null, scene, !generateMipMaps);
  23109. this.isCube = isCube;
  23110. /**
  23111. * Use this list to define the list of mesh you want to render.
  23112. */
  23113. this.renderList = new Array();
  23114. this.renderParticles = true;
  23115. this.renderSprites = false;
  23116. this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  23117. // Events
  23118. /**
  23119. * An event triggered when the texture is unbind.
  23120. * @type {BABYLON.Observable}
  23121. */
  23122. this.onAfterUnbindObservable = new BABYLON.Observable();
  23123. /**
  23124. * An event triggered before rendering the texture
  23125. * @type {BABYLON.Observable}
  23126. */
  23127. this.onBeforeRenderObservable = new BABYLON.Observable();
  23128. /**
  23129. * An event triggered after rendering the texture
  23130. * @type {BABYLON.Observable}
  23131. */
  23132. this.onAfterRenderObservable = new BABYLON.Observable();
  23133. /**
  23134. * An event triggered after the texture clear
  23135. * @type {BABYLON.Observable}
  23136. */
  23137. this.onClearObservable = new BABYLON.Observable();
  23138. this._currentRefreshId = -1;
  23139. this._refreshRate = 1;
  23140. this.name = name;
  23141. this.isRenderTarget = true;
  23142. this._size = size;
  23143. this._generateMipMaps = generateMipMaps;
  23144. this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  23145. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  23146. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  23147. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  23148. }
  23149. if (isCube) {
  23150. this._texture = scene.getEngine().createRenderTargetCubeTexture(size, {
  23151. generateMipMaps: generateMipMaps,
  23152. samplingMode: samplingMode,
  23153. generateDepthBuffer: generateDepthBuffer,
  23154. generateStencilBuffer: generateStencilBuffer
  23155. });
  23156. this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  23157. this._textureMatrix = BABYLON.Matrix.Identity();
  23158. }
  23159. else {
  23160. this._texture = scene.getEngine().createRenderTargetTexture(size, {
  23161. generateMipMaps: generateMipMaps,
  23162. type: type,
  23163. samplingMode: samplingMode,
  23164. generateDepthBuffer: generateDepthBuffer,
  23165. generateStencilBuffer: generateStencilBuffer
  23166. });
  23167. }
  23168. // Rendering groups
  23169. this._renderingManager = new BABYLON.RenderingManager(scene);
  23170. }
  23171. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  23172. get: function () {
  23173. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  23174. },
  23175. enumerable: true,
  23176. configurable: true
  23177. });
  23178. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  23179. get: function () {
  23180. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  23181. },
  23182. enumerable: true,
  23183. configurable: true
  23184. });
  23185. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  23186. get: function () {
  23187. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  23188. },
  23189. enumerable: true,
  23190. configurable: true
  23191. });
  23192. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  23193. set: function (callback) {
  23194. if (this._onAfterUnbindObserver) {
  23195. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  23196. }
  23197. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  23198. },
  23199. enumerable: true,
  23200. configurable: true
  23201. });
  23202. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  23203. set: function (callback) {
  23204. if (this._onBeforeRenderObserver) {
  23205. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  23206. }
  23207. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  23208. },
  23209. enumerable: true,
  23210. configurable: true
  23211. });
  23212. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  23213. set: function (callback) {
  23214. if (this._onAfterRenderObserver) {
  23215. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  23216. }
  23217. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  23218. },
  23219. enumerable: true,
  23220. configurable: true
  23221. });
  23222. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  23223. set: function (callback) {
  23224. if (this._onClearObserver) {
  23225. this.onClearObservable.remove(this._onClearObserver);
  23226. }
  23227. this._onClearObserver = this.onClearObservable.add(callback);
  23228. },
  23229. enumerable: true,
  23230. configurable: true
  23231. });
  23232. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  23233. this._currentRefreshId = -1;
  23234. };
  23235. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  23236. get: function () {
  23237. return this._refreshRate;
  23238. },
  23239. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  23240. set: function (value) {
  23241. this._refreshRate = value;
  23242. this.resetRefreshCounter();
  23243. },
  23244. enumerable: true,
  23245. configurable: true
  23246. });
  23247. RenderTargetTexture.prototype._shouldRender = function () {
  23248. if (this._currentRefreshId === -1) {
  23249. this._currentRefreshId = 1;
  23250. return true;
  23251. }
  23252. if (this.refreshRate === this._currentRefreshId) {
  23253. this._currentRefreshId = 1;
  23254. return true;
  23255. }
  23256. this._currentRefreshId++;
  23257. return false;
  23258. };
  23259. RenderTargetTexture.prototype.isReady = function () {
  23260. if (!this.getScene().renderTargetsEnabled) {
  23261. return false;
  23262. }
  23263. return _super.prototype.isReady.call(this);
  23264. };
  23265. RenderTargetTexture.prototype.getRenderSize = function () {
  23266. return this._size;
  23267. };
  23268. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  23269. get: function () {
  23270. return true;
  23271. },
  23272. enumerable: true,
  23273. configurable: true
  23274. });
  23275. RenderTargetTexture.prototype.scale = function (ratio) {
  23276. var newSize = this._size * ratio;
  23277. this.resize(newSize, this._generateMipMaps);
  23278. };
  23279. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  23280. if (this.isCube) {
  23281. return this._textureMatrix;
  23282. }
  23283. return _super.prototype.getReflectionTextureMatrix.call(this);
  23284. };
  23285. RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
  23286. this.releaseInternalTexture();
  23287. if (this.isCube) {
  23288. this._texture = this.getScene().getEngine().createRenderTargetCubeTexture(size);
  23289. }
  23290. else {
  23291. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  23292. }
  23293. };
  23294. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  23295. var scene = this.getScene();
  23296. if (this.useCameraPostProcesses !== undefined) {
  23297. useCameraPostProcess = this.useCameraPostProcesses;
  23298. }
  23299. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  23300. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  23301. }
  23302. if (this._waitingRenderList) {
  23303. this.renderList = [];
  23304. for (var index = 0; index < this._waitingRenderList.length; index++) {
  23305. var id = this._waitingRenderList[index];
  23306. this.renderList.push(scene.getMeshByID(id));
  23307. }
  23308. delete this._waitingRenderList;
  23309. }
  23310. // Is predicate defined?
  23311. if (this.renderListPredicate) {
  23312. this.renderList.splice(0); // Clear previous renderList
  23313. var sceneMeshes = this.getScene().meshes;
  23314. for (var index = 0; index < sceneMeshes.length; index++) {
  23315. var mesh = sceneMeshes[index];
  23316. if (this.renderListPredicate(mesh)) {
  23317. this.renderList.push(mesh);
  23318. }
  23319. }
  23320. }
  23321. if (this.renderList && this.renderList.length === 0) {
  23322. return;
  23323. }
  23324. // Prepare renderingManager
  23325. this._renderingManager.reset();
  23326. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  23327. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  23328. var sceneRenderId = scene.getRenderId();
  23329. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  23330. var mesh = currentRenderList[meshIndex];
  23331. if (mesh) {
  23332. if (!mesh.isReady()) {
  23333. // Reset _currentRefreshId
  23334. this.resetRefreshCounter();
  23335. continue;
  23336. }
  23337. mesh._preActivateForIntermediateRendering(sceneRenderId);
  23338. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
  23339. mesh._activate(sceneRenderId);
  23340. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  23341. var subMesh = mesh.subMeshes[subIndex];
  23342. scene._activeIndices.addCount(subMesh.indexCount, false);
  23343. this._renderingManager.dispatch(subMesh);
  23344. }
  23345. }
  23346. }
  23347. }
  23348. if (this.isCube) {
  23349. for (var face = 0; face < 6; face++) {
  23350. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  23351. scene.incrementRenderId();
  23352. scene.resetCachedMaterial();
  23353. }
  23354. }
  23355. else {
  23356. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  23357. }
  23358. this.onAfterUnbindObservable.notifyObservers(this);
  23359. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  23360. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  23361. }
  23362. scene.resetCachedMaterial();
  23363. };
  23364. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  23365. var scene = this.getScene();
  23366. var engine = scene.getEngine();
  23367. // Bind
  23368. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  23369. if (this.isCube) {
  23370. engine.bindFramebuffer(this._texture, faceIndex);
  23371. }
  23372. else {
  23373. engine.bindFramebuffer(this._texture);
  23374. }
  23375. }
  23376. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  23377. // Clear
  23378. if (this.onClearObservable.hasObservers()) {
  23379. this.onClearObservable.notifyObservers(engine);
  23380. }
  23381. else {
  23382. engine.clear(scene.clearColor, true, true, true);
  23383. }
  23384. if (!this._doNotChangeAspectRatio) {
  23385. scene.updateTransformMatrix(true);
  23386. }
  23387. // Render
  23388. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  23389. if (useCameraPostProcess) {
  23390. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  23391. }
  23392. if (!this._doNotChangeAspectRatio) {
  23393. scene.updateTransformMatrix(true);
  23394. }
  23395. this.onAfterRenderObservable.notifyObservers(faceIndex);
  23396. // Dump ?
  23397. if (dumpForDebug) {
  23398. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  23399. }
  23400. // Unbind
  23401. if (!this.isCube || faceIndex === 5) {
  23402. if (this.isCube) {
  23403. if (faceIndex === 5) {
  23404. engine.generateMipMapsForCubemap(this._texture);
  23405. }
  23406. }
  23407. engine.unBindFramebuffer(this._texture, this.isCube);
  23408. }
  23409. };
  23410. /**
  23411. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  23412. * This allowed control for front to back rendering or reversly depending of the special needs.
  23413. *
  23414. * @param renderingGroupId The rendering group id corresponding to its index
  23415. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  23416. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  23417. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  23418. */
  23419. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23420. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23421. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23422. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23423. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  23424. };
  23425. /**
  23426. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  23427. *
  23428. * @param renderingGroupId The rendering group id corresponding to its index
  23429. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  23430. */
  23431. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  23432. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  23433. };
  23434. RenderTargetTexture.prototype.clone = function () {
  23435. var textureSize = this.getSize();
  23436. var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  23437. // Base texture
  23438. newTexture.hasAlpha = this.hasAlpha;
  23439. newTexture.level = this.level;
  23440. // RenderTarget Texture
  23441. newTexture.coordinatesMode = this.coordinatesMode;
  23442. newTexture.renderList = this.renderList.slice(0);
  23443. return newTexture;
  23444. };
  23445. RenderTargetTexture.prototype.serialize = function () {
  23446. if (!this.name) {
  23447. return null;
  23448. }
  23449. var serializationObject = _super.prototype.serialize.call(this);
  23450. serializationObject.renderTargetSize = this.getRenderSize();
  23451. serializationObject.renderList = [];
  23452. for (var index = 0; index < this.renderList.length; index++) {
  23453. serializationObject.renderList.push(this.renderList[index].id);
  23454. }
  23455. return serializationObject;
  23456. };
  23457. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  23458. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  23459. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  23460. return RenderTargetTexture;
  23461. }(BABYLON.Texture));
  23462. BABYLON.RenderTargetTexture = RenderTargetTexture;
  23463. })(BABYLON || (BABYLON = {}));
  23464. var BABYLON;
  23465. (function (BABYLON) {
  23466. var ProceduralTexture = (function (_super) {
  23467. __extends(ProceduralTexture, _super);
  23468. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  23469. if (generateMipMaps === void 0) { generateMipMaps = true; }
  23470. if (isCube === void 0) { isCube = false; }
  23471. _super.call(this, null, scene, !generateMipMaps);
  23472. this.isCube = isCube;
  23473. this.isEnabled = true;
  23474. this._currentRefreshId = -1;
  23475. this._refreshRate = 1;
  23476. this._vertexBuffers = {};
  23477. this._uniforms = new Array();
  23478. this._samplers = new Array();
  23479. this._textures = new Array();
  23480. this._floats = new Array();
  23481. this._floatsArrays = {};
  23482. this._colors3 = new Array();
  23483. this._colors4 = new Array();
  23484. this._vectors2 = new Array();
  23485. this._vectors3 = new Array();
  23486. this._matrices = new Array();
  23487. this._fallbackTextureUsed = false;
  23488. scene._proceduralTextures.push(this);
  23489. this.name = name;
  23490. this.isRenderTarget = true;
  23491. this._size = size;
  23492. this._generateMipMaps = generateMipMaps;
  23493. this.setFragment(fragment);
  23494. this._fallbackTexture = fallbackTexture;
  23495. var engine = scene.getEngine();
  23496. if (isCube) {
  23497. this._texture = engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  23498. this.setFloat("face", 0);
  23499. }
  23500. else {
  23501. this._texture = engine.createRenderTargetTexture(size, generateMipMaps);
  23502. }
  23503. // VBO
  23504. var vertices = [];
  23505. vertices.push(1, 1);
  23506. vertices.push(-1, 1);
  23507. vertices.push(-1, -1);
  23508. vertices.push(1, -1);
  23509. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  23510. // Indices
  23511. var indices = [];
  23512. indices.push(0);
  23513. indices.push(1);
  23514. indices.push(2);
  23515. indices.push(0);
  23516. indices.push(2);
  23517. indices.push(3);
  23518. this._indexBuffer = engine.createIndexBuffer(indices);
  23519. }
  23520. ProceduralTexture.prototype.reset = function () {
  23521. if (this._effect === undefined) {
  23522. return;
  23523. }
  23524. var engine = this.getScene().getEngine();
  23525. engine._releaseEffect(this._effect);
  23526. };
  23527. ProceduralTexture.prototype.isReady = function () {
  23528. var _this = this;
  23529. var engine = this.getScene().getEngine();
  23530. var shaders;
  23531. if (!this._fragment) {
  23532. return false;
  23533. }
  23534. if (this._fallbackTextureUsed) {
  23535. return true;
  23536. }
  23537. if (this._fragment.fragmentElement !== undefined) {
  23538. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  23539. }
  23540. else {
  23541. shaders = { vertex: "procedural", fragment: this._fragment };
  23542. }
  23543. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", null, null, function () {
  23544. _this.releaseInternalTexture();
  23545. if (_this._fallbackTexture) {
  23546. _this._texture = _this._fallbackTexture._texture;
  23547. _this._texture.references++;
  23548. }
  23549. _this._fallbackTextureUsed = true;
  23550. });
  23551. return this._effect.isReady();
  23552. };
  23553. ProceduralTexture.prototype.resetRefreshCounter = function () {
  23554. this._currentRefreshId = -1;
  23555. };
  23556. ProceduralTexture.prototype.setFragment = function (fragment) {
  23557. this._fragment = fragment;
  23558. };
  23559. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  23560. get: function () {
  23561. return this._refreshRate;
  23562. },
  23563. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  23564. set: function (value) {
  23565. this._refreshRate = value;
  23566. this.resetRefreshCounter();
  23567. },
  23568. enumerable: true,
  23569. configurable: true
  23570. });
  23571. ProceduralTexture.prototype._shouldRender = function () {
  23572. if (!this.isEnabled || !this.isReady() || !this._texture) {
  23573. return false;
  23574. }
  23575. if (this._fallbackTextureUsed) {
  23576. return false;
  23577. }
  23578. if (this._currentRefreshId === -1) {
  23579. this._currentRefreshId = 1;
  23580. return true;
  23581. }
  23582. if (this.refreshRate === this._currentRefreshId) {
  23583. this._currentRefreshId = 1;
  23584. return true;
  23585. }
  23586. this._currentRefreshId++;
  23587. return false;
  23588. };
  23589. ProceduralTexture.prototype.getRenderSize = function () {
  23590. return this._size;
  23591. };
  23592. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  23593. if (this._fallbackTextureUsed) {
  23594. return;
  23595. }
  23596. this.releaseInternalTexture();
  23597. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  23598. };
  23599. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  23600. if (this._uniforms.indexOf(uniformName) === -1) {
  23601. this._uniforms.push(uniformName);
  23602. }
  23603. };
  23604. ProceduralTexture.prototype.setTexture = function (name, texture) {
  23605. if (this._samplers.indexOf(name) === -1) {
  23606. this._samplers.push(name);
  23607. }
  23608. this._textures[name] = texture;
  23609. return this;
  23610. };
  23611. ProceduralTexture.prototype.setFloat = function (name, value) {
  23612. this._checkUniform(name);
  23613. this._floats[name] = value;
  23614. return this;
  23615. };
  23616. ProceduralTexture.prototype.setFloats = function (name, value) {
  23617. this._checkUniform(name);
  23618. this._floatsArrays[name] = value;
  23619. return this;
  23620. };
  23621. ProceduralTexture.prototype.setColor3 = function (name, value) {
  23622. this._checkUniform(name);
  23623. this._colors3[name] = value;
  23624. return this;
  23625. };
  23626. ProceduralTexture.prototype.setColor4 = function (name, value) {
  23627. this._checkUniform(name);
  23628. this._colors4[name] = value;
  23629. return this;
  23630. };
  23631. ProceduralTexture.prototype.setVector2 = function (name, value) {
  23632. this._checkUniform(name);
  23633. this._vectors2[name] = value;
  23634. return this;
  23635. };
  23636. ProceduralTexture.prototype.setVector3 = function (name, value) {
  23637. this._checkUniform(name);
  23638. this._vectors3[name] = value;
  23639. return this;
  23640. };
  23641. ProceduralTexture.prototype.setMatrix = function (name, value) {
  23642. this._checkUniform(name);
  23643. this._matrices[name] = value;
  23644. return this;
  23645. };
  23646. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  23647. var scene = this.getScene();
  23648. var engine = scene.getEngine();
  23649. // Render
  23650. engine.enableEffect(this._effect);
  23651. engine.setState(false);
  23652. // Texture
  23653. for (var name in this._textures) {
  23654. this._effect.setTexture(name, this._textures[name]);
  23655. }
  23656. // Float
  23657. for (name in this._floats) {
  23658. this._effect.setFloat(name, this._floats[name]);
  23659. }
  23660. // Floats
  23661. for (name in this._floatsArrays) {
  23662. this._effect.setArray(name, this._floatsArrays[name]);
  23663. }
  23664. // Color3
  23665. for (name in this._colors3) {
  23666. this._effect.setColor3(name, this._colors3[name]);
  23667. }
  23668. // Color4
  23669. for (name in this._colors4) {
  23670. var color = this._colors4[name];
  23671. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  23672. }
  23673. // Vector2
  23674. for (name in this._vectors2) {
  23675. this._effect.setVector2(name, this._vectors2[name]);
  23676. }
  23677. // Vector3
  23678. for (name in this._vectors3) {
  23679. this._effect.setVector3(name, this._vectors3[name]);
  23680. }
  23681. // Matrix
  23682. for (name in this._matrices) {
  23683. this._effect.setMatrix(name, this._matrices[name]);
  23684. }
  23685. // VBOs
  23686. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  23687. if (this.isCube) {
  23688. for (var face = 0; face < 6; face++) {
  23689. engine.bindFramebuffer(this._texture, face);
  23690. this._effect.setFloat("face", face);
  23691. // Clear
  23692. engine.clear(scene.clearColor, true, true, true);
  23693. // Draw order
  23694. engine.draw(true, 0, 6);
  23695. // Mipmaps
  23696. if (face === 5) {
  23697. engine.generateMipMapsForCubemap(this._texture);
  23698. }
  23699. }
  23700. }
  23701. else {
  23702. engine.bindFramebuffer(this._texture);
  23703. // Clear
  23704. engine.clear(scene.clearColor, true, true, true);
  23705. // Draw order
  23706. engine.draw(true, 0, 6);
  23707. }
  23708. // Unbind
  23709. engine.unBindFramebuffer(this._texture, this.isCube);
  23710. if (this.onGenerated) {
  23711. this.onGenerated();
  23712. }
  23713. };
  23714. ProceduralTexture.prototype.clone = function () {
  23715. var textureSize = this.getSize();
  23716. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  23717. // Base texture
  23718. newTexture.hasAlpha = this.hasAlpha;
  23719. newTexture.level = this.level;
  23720. // RenderTarget Texture
  23721. newTexture.coordinatesMode = this.coordinatesMode;
  23722. return newTexture;
  23723. };
  23724. ProceduralTexture.prototype.dispose = function () {
  23725. var index = this.getScene()._proceduralTextures.indexOf(this);
  23726. if (index >= 0) {
  23727. this.getScene()._proceduralTextures.splice(index, 1);
  23728. }
  23729. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  23730. if (vertexBuffer) {
  23731. vertexBuffer.dispose();
  23732. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  23733. }
  23734. if (this._indexBuffer && this.getScene().getEngine()._releaseBuffer(this._indexBuffer)) {
  23735. this._indexBuffer = null;
  23736. }
  23737. _super.prototype.dispose.call(this);
  23738. };
  23739. return ProceduralTexture;
  23740. }(BABYLON.Texture));
  23741. BABYLON.ProceduralTexture = ProceduralTexture;
  23742. })(BABYLON || (BABYLON = {}));
  23743. var BABYLON;
  23744. (function (BABYLON) {
  23745. var MirrorTexture = (function (_super) {
  23746. __extends(MirrorTexture, _super);
  23747. function MirrorTexture(name, size, scene, generateMipMaps) {
  23748. var _this = this;
  23749. _super.call(this, name, size, scene, generateMipMaps, true);
  23750. this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  23751. this._transformMatrix = BABYLON.Matrix.Zero();
  23752. this._mirrorMatrix = BABYLON.Matrix.Zero();
  23753. this.onBeforeRenderObservable.add(function () {
  23754. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  23755. _this._savedViewMatrix = scene.getViewMatrix();
  23756. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  23757. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  23758. scene.clipPlane = _this.mirrorPlane;
  23759. scene.getEngine().cullBackFaces = false;
  23760. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.position, _this._mirrorMatrix);
  23761. });
  23762. this.onAfterRenderObservable.add(function () {
  23763. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  23764. scene.getEngine().cullBackFaces = true;
  23765. scene._mirroredCameraPosition = null;
  23766. delete scene.clipPlane;
  23767. });
  23768. }
  23769. MirrorTexture.prototype.clone = function () {
  23770. var textureSize = this.getSize();
  23771. var newTexture = new MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  23772. // Base texture
  23773. newTexture.hasAlpha = this.hasAlpha;
  23774. newTexture.level = this.level;
  23775. // Mirror Texture
  23776. newTexture.mirrorPlane = this.mirrorPlane.clone();
  23777. newTexture.renderList = this.renderList.slice(0);
  23778. return newTexture;
  23779. };
  23780. MirrorTexture.prototype.serialize = function () {
  23781. if (!this.name) {
  23782. return null;
  23783. }
  23784. var serializationObject = _super.prototype.serialize.call(this);
  23785. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  23786. return serializationObject;
  23787. };
  23788. return MirrorTexture;
  23789. }(BABYLON.RenderTargetTexture));
  23790. BABYLON.MirrorTexture = MirrorTexture;
  23791. })(BABYLON || (BABYLON = {}));
  23792. var BABYLON;
  23793. (function (BABYLON) {
  23794. /**
  23795. * Creates a refraction texture used by refraction channel of the standard material.
  23796. * @param name the texture name
  23797. * @param size size of the underlying texture
  23798. * @param scene root scene
  23799. */
  23800. var RefractionTexture = (function (_super) {
  23801. __extends(RefractionTexture, _super);
  23802. function RefractionTexture(name, size, scene, generateMipMaps) {
  23803. var _this = this;
  23804. _super.call(this, name, size, scene, generateMipMaps, true);
  23805. this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  23806. this.depth = 2.0;
  23807. this.onBeforeRenderObservable.add(function () {
  23808. scene.clipPlane = _this.refractionPlane;
  23809. });
  23810. this.onAfterRenderObservable.add(function () {
  23811. delete scene.clipPlane;
  23812. });
  23813. }
  23814. RefractionTexture.prototype.clone = function () {
  23815. var textureSize = this.getSize();
  23816. var newTexture = new RefractionTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  23817. // Base texture
  23818. newTexture.hasAlpha = this.hasAlpha;
  23819. newTexture.level = this.level;
  23820. // Refraction Texture
  23821. newTexture.refractionPlane = this.refractionPlane.clone();
  23822. newTexture.renderList = this.renderList.slice(0);
  23823. newTexture.depth = this.depth;
  23824. return newTexture;
  23825. };
  23826. RefractionTexture.prototype.serialize = function () {
  23827. if (!this.name) {
  23828. return null;
  23829. }
  23830. var serializationObject = _super.prototype.serialize.call(this);
  23831. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  23832. serializationObject.depth = this.depth;
  23833. return serializationObject;
  23834. };
  23835. return RefractionTexture;
  23836. }(BABYLON.RenderTargetTexture));
  23837. BABYLON.RefractionTexture = RefractionTexture;
  23838. })(BABYLON || (BABYLON = {}));
  23839. var BABYLON;
  23840. (function (BABYLON) {
  23841. var DynamicTexture = (function (_super) {
  23842. __extends(DynamicTexture, _super);
  23843. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  23844. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  23845. _super.call(this, null, scene, !generateMipMaps);
  23846. this.name = name;
  23847. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  23848. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  23849. this._generateMipMaps = generateMipMaps;
  23850. if (options.getContext) {
  23851. this._canvas = options;
  23852. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  23853. }
  23854. else {
  23855. this._canvas = document.createElement("canvas");
  23856. if (options.width) {
  23857. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  23858. }
  23859. else {
  23860. this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  23861. }
  23862. }
  23863. var textureSize = this.getSize();
  23864. this._canvas.width = textureSize.width;
  23865. this._canvas.height = textureSize.height;
  23866. this._context = this._canvas.getContext("2d");
  23867. }
  23868. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  23869. get: function () {
  23870. return true;
  23871. },
  23872. enumerable: true,
  23873. configurable: true
  23874. });
  23875. DynamicTexture.prototype.scale = function (ratio) {
  23876. var textureSize = this.getSize();
  23877. textureSize.width *= ratio;
  23878. textureSize.height *= ratio;
  23879. this._canvas.width = textureSize.width;
  23880. this._canvas.height = textureSize.height;
  23881. this.releaseInternalTexture();
  23882. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  23883. };
  23884. DynamicTexture.prototype.getContext = function () {
  23885. return this._context;
  23886. };
  23887. DynamicTexture.prototype.clear = function () {
  23888. var size = this.getSize();
  23889. this._context.fillRect(0, 0, size.width, size.height);
  23890. };
  23891. DynamicTexture.prototype.update = function (invertY) {
  23892. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  23893. };
  23894. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  23895. if (update === void 0) { update = true; }
  23896. var size = this.getSize();
  23897. if (clearColor) {
  23898. this._context.fillStyle = clearColor;
  23899. this._context.fillRect(0, 0, size.width, size.height);
  23900. }
  23901. this._context.font = font;
  23902. if (x === null) {
  23903. var textSize = this._context.measureText(text);
  23904. x = (size.width - textSize.width) / 2;
  23905. }
  23906. this._context.fillStyle = color;
  23907. this._context.fillText(text, x, y);
  23908. if (update) {
  23909. this.update(invertY);
  23910. }
  23911. };
  23912. DynamicTexture.prototype.clone = function () {
  23913. var textureSize = this.getSize();
  23914. var newTexture = new DynamicTexture(this.name, textureSize, this.getScene(), this._generateMipMaps);
  23915. // Base texture
  23916. newTexture.hasAlpha = this.hasAlpha;
  23917. newTexture.level = this.level;
  23918. // Dynamic Texture
  23919. newTexture.wrapU = this.wrapU;
  23920. newTexture.wrapV = this.wrapV;
  23921. return newTexture;
  23922. };
  23923. return DynamicTexture;
  23924. }(BABYLON.Texture));
  23925. BABYLON.DynamicTexture = DynamicTexture;
  23926. })(BABYLON || (BABYLON = {}));
  23927. var BABYLON;
  23928. (function (BABYLON) {
  23929. var VideoTexture = (function (_super) {
  23930. __extends(VideoTexture, _super);
  23931. /**
  23932. * Creates a video texture.
  23933. * Sample : https://doc.babylonjs.com/tutorials/01._Advanced_Texturing
  23934. * @param {Array} urlsOrVideo can be used to provide an array of urls or an already setup HTML video element.
  23935. * @param {BABYLON.Scene} scene is obviously the current scene.
  23936. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  23937. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  23938. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  23939. */
  23940. function VideoTexture(name, urlsOrVideo, scene, generateMipMaps, invertY, samplingMode) {
  23941. var _this = this;
  23942. if (generateMipMaps === void 0) { generateMipMaps = false; }
  23943. if (invertY === void 0) { invertY = false; }
  23944. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  23945. _super.call(this, null, scene, !generateMipMaps, invertY);
  23946. this._autoLaunch = true;
  23947. var urls;
  23948. this.name = name;
  23949. if (urlsOrVideo instanceof HTMLVideoElement) {
  23950. this.video = urlsOrVideo;
  23951. }
  23952. else {
  23953. urls = urlsOrVideo;
  23954. this.video = document.createElement("video");
  23955. this.video.autoplay = false;
  23956. this.video.loop = true;
  23957. }
  23958. this._generateMipMaps = generateMipMaps;
  23959. this._samplingMode = samplingMode;
  23960. if (BABYLON.Tools.IsExponentOfTwo(this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(this.video.videoHeight)) {
  23961. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  23962. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  23963. }
  23964. else {
  23965. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  23966. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  23967. this._generateMipMaps = false;
  23968. }
  23969. if (urls) {
  23970. this.video.addEventListener("canplaythrough", function () {
  23971. _this._createTexture();
  23972. });
  23973. urls.forEach(function (url) {
  23974. var source = document.createElement("source");
  23975. source.src = url;
  23976. _this.video.appendChild(source);
  23977. });
  23978. }
  23979. else {
  23980. this._createTexture();
  23981. }
  23982. this._lastUpdate = BABYLON.Tools.Now;
  23983. }
  23984. VideoTexture.prototype._createTexture = function () {
  23985. this._texture = this.getScene().getEngine().createDynamicTexture(this.video.videoWidth, this.video.videoHeight, this._generateMipMaps, this._samplingMode);
  23986. this._texture.isReady = true;
  23987. };
  23988. VideoTexture.prototype.update = function () {
  23989. if (this._autoLaunch) {
  23990. this._autoLaunch = false;
  23991. this.video.play();
  23992. }
  23993. var now = BABYLON.Tools.Now;
  23994. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  23995. return false;
  23996. }
  23997. this._lastUpdate = now;
  23998. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  23999. return true;
  24000. };
  24001. return VideoTexture;
  24002. }(BABYLON.Texture));
  24003. BABYLON.VideoTexture = VideoTexture;
  24004. })(BABYLON || (BABYLON = {}));
  24005. var BABYLON;
  24006. (function (BABYLON) {
  24007. var CustomProceduralTexture = (function (_super) {
  24008. __extends(CustomProceduralTexture, _super);
  24009. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  24010. _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps);
  24011. this._animate = true;
  24012. this._time = 0;
  24013. this._texturePath = texturePath;
  24014. //Try to load json
  24015. this.loadJson(texturePath);
  24016. this.refreshRate = 1;
  24017. }
  24018. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  24019. var _this = this;
  24020. var that = this;
  24021. function noConfigFile() {
  24022. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  24023. try {
  24024. that.setFragment(that._texturePath);
  24025. }
  24026. catch (ex) {
  24027. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  24028. }
  24029. }
  24030. var configFileUrl = jsonUrl + "/config.json";
  24031. var xhr = new XMLHttpRequest();
  24032. xhr.open("GET", configFileUrl, true);
  24033. xhr.addEventListener("load", function () {
  24034. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  24035. try {
  24036. _this._config = JSON.parse(xhr.response);
  24037. _this.updateShaderUniforms();
  24038. _this.updateTextures();
  24039. _this.setFragment(_this._texturePath + "/custom");
  24040. _this._animate = _this._config.animate;
  24041. _this.refreshRate = _this._config.refreshrate;
  24042. }
  24043. catch (ex) {
  24044. noConfigFile();
  24045. }
  24046. }
  24047. else {
  24048. noConfigFile();
  24049. }
  24050. }, false);
  24051. xhr.addEventListener("error", function () {
  24052. noConfigFile();
  24053. }, false);
  24054. try {
  24055. xhr.send();
  24056. }
  24057. catch (ex) {
  24058. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  24059. }
  24060. };
  24061. CustomProceduralTexture.prototype.isReady = function () {
  24062. if (!_super.prototype.isReady.call(this)) {
  24063. return false;
  24064. }
  24065. for (var name in this._textures) {
  24066. var texture = this._textures[name];
  24067. if (!texture.isReady()) {
  24068. return false;
  24069. }
  24070. }
  24071. return true;
  24072. };
  24073. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  24074. if (this._animate) {
  24075. this._time += this.getScene().getAnimationRatio() * 0.03;
  24076. this.updateShaderUniforms();
  24077. }
  24078. _super.prototype.render.call(this, useCameraPostProcess);
  24079. };
  24080. CustomProceduralTexture.prototype.updateTextures = function () {
  24081. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  24082. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  24083. }
  24084. };
  24085. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  24086. if (this._config) {
  24087. for (var j = 0; j < this._config.uniforms.length; j++) {
  24088. var uniform = this._config.uniforms[j];
  24089. switch (uniform.type) {
  24090. case "float":
  24091. this.setFloat(uniform.name, uniform.value);
  24092. break;
  24093. case "color3":
  24094. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  24095. break;
  24096. case "color4":
  24097. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  24098. break;
  24099. case "vector2":
  24100. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  24101. break;
  24102. case "vector3":
  24103. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  24104. break;
  24105. }
  24106. }
  24107. }
  24108. this.setFloat("time", this._time);
  24109. };
  24110. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  24111. get: function () {
  24112. return this._animate;
  24113. },
  24114. set: function (value) {
  24115. this._animate = value;
  24116. },
  24117. enumerable: true,
  24118. configurable: true
  24119. });
  24120. return CustomProceduralTexture;
  24121. }(BABYLON.ProceduralTexture));
  24122. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  24123. })(BABYLON || (BABYLON = {}));
  24124. var BABYLON;
  24125. (function (BABYLON) {
  24126. var EffectFallbacks = (function () {
  24127. function EffectFallbacks() {
  24128. this._defines = {};
  24129. this._currentRank = 32;
  24130. this._maxRank = -1;
  24131. }
  24132. EffectFallbacks.prototype.addFallback = function (rank, define) {
  24133. if (!this._defines[rank]) {
  24134. if (rank < this._currentRank) {
  24135. this._currentRank = rank;
  24136. }
  24137. if (rank > this._maxRank) {
  24138. this._maxRank = rank;
  24139. }
  24140. this._defines[rank] = new Array();
  24141. }
  24142. this._defines[rank].push(define);
  24143. };
  24144. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  24145. this._meshRank = rank;
  24146. this._mesh = mesh;
  24147. if (rank > this._maxRank) {
  24148. this._maxRank = rank;
  24149. }
  24150. };
  24151. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  24152. get: function () {
  24153. return this._currentRank <= this._maxRank;
  24154. },
  24155. enumerable: true,
  24156. configurable: true
  24157. });
  24158. EffectFallbacks.prototype.reduce = function (currentDefines) {
  24159. var currentFallbacks = this._defines[this._currentRank];
  24160. for (var index = 0; index < currentFallbacks.length; index++) {
  24161. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  24162. }
  24163. if (this._mesh && this._currentRank === this._meshRank) {
  24164. this._mesh.computeBonesUsingShaders = false;
  24165. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  24166. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  24167. }
  24168. this._currentRank++;
  24169. return currentDefines;
  24170. };
  24171. return EffectFallbacks;
  24172. }());
  24173. BABYLON.EffectFallbacks = EffectFallbacks;
  24174. var Effect = (function () {
  24175. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  24176. var _this = this;
  24177. this._isReady = false;
  24178. this._compilationError = "";
  24179. this._valueCache = {};
  24180. this._engine = engine;
  24181. this.name = baseName;
  24182. this.defines = defines;
  24183. this._uniformsNames = uniformsNames.concat(samplers);
  24184. this._samplers = samplers;
  24185. this._attributesNames = attributesNames;
  24186. this.onError = onError;
  24187. this.onCompiled = onCompiled;
  24188. this._indexParameters = indexParameters;
  24189. var vertexSource;
  24190. var fragmentSource;
  24191. if (baseName.vertexElement) {
  24192. vertexSource = document.getElementById(baseName.vertexElement);
  24193. if (!vertexSource) {
  24194. vertexSource = baseName.vertexElement;
  24195. }
  24196. }
  24197. else {
  24198. vertexSource = baseName.vertex || baseName;
  24199. }
  24200. if (baseName.fragmentElement) {
  24201. fragmentSource = document.getElementById(baseName.fragmentElement);
  24202. if (!fragmentSource) {
  24203. fragmentSource = baseName.fragmentElement;
  24204. }
  24205. }
  24206. else {
  24207. fragmentSource = baseName.fragment || baseName;
  24208. }
  24209. this._loadVertexShader(vertexSource, function (vertexCode) {
  24210. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  24211. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  24212. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  24213. _this._prepareEffect(vertexCodeWithIncludes, fragmentCodeWithIncludes, attributesNames, defines, fallbacks);
  24214. });
  24215. });
  24216. });
  24217. });
  24218. }
  24219. // Properties
  24220. Effect.prototype.isReady = function () {
  24221. return this._isReady;
  24222. };
  24223. Effect.prototype.getProgram = function () {
  24224. return this._program;
  24225. };
  24226. Effect.prototype.getAttributesNames = function () {
  24227. return this._attributesNames;
  24228. };
  24229. Effect.prototype.getAttributeLocation = function (index) {
  24230. return this._attributes[index];
  24231. };
  24232. Effect.prototype.getAttributeLocationByName = function (name) {
  24233. var index = this._attributesNames.indexOf(name);
  24234. return this._attributes[index];
  24235. };
  24236. Effect.prototype.getAttributesCount = function () {
  24237. return this._attributes.length;
  24238. };
  24239. Effect.prototype.getUniformIndex = function (uniformName) {
  24240. return this._uniformsNames.indexOf(uniformName);
  24241. };
  24242. Effect.prototype.getUniform = function (uniformName) {
  24243. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  24244. };
  24245. Effect.prototype.getSamplers = function () {
  24246. return this._samplers;
  24247. };
  24248. Effect.prototype.getCompilationError = function () {
  24249. return this._compilationError;
  24250. };
  24251. // Methods
  24252. Effect.prototype._loadVertexShader = function (vertex, callback) {
  24253. // DOM element ?
  24254. if (vertex instanceof HTMLElement) {
  24255. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  24256. callback(vertexCode);
  24257. return;
  24258. }
  24259. // Is in local store ?
  24260. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  24261. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  24262. return;
  24263. }
  24264. var vertexShaderUrl;
  24265. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  24266. vertexShaderUrl = vertex;
  24267. }
  24268. else {
  24269. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  24270. }
  24271. // Vertex shader
  24272. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  24273. };
  24274. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  24275. // DOM element ?
  24276. if (fragment instanceof HTMLElement) {
  24277. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  24278. callback(fragmentCode);
  24279. return;
  24280. }
  24281. // Is in local store ?
  24282. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  24283. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  24284. return;
  24285. }
  24286. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  24287. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  24288. return;
  24289. }
  24290. var fragmentShaderUrl;
  24291. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  24292. fragmentShaderUrl = fragment;
  24293. }
  24294. else {
  24295. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  24296. }
  24297. // Fragment shader
  24298. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  24299. };
  24300. Effect.prototype._dumpShadersName = function () {
  24301. if (this.name.vertexElement) {
  24302. BABYLON.Tools.Error("Vertex shader:" + this.name.vertexElement);
  24303. BABYLON.Tools.Error("Fragment shader:" + this.name.fragmentElement);
  24304. }
  24305. else if (this.name.vertex) {
  24306. BABYLON.Tools.Error("Vertex shader:" + this.name.vertex);
  24307. BABYLON.Tools.Error("Fragment shader:" + this.name.fragment);
  24308. }
  24309. else {
  24310. BABYLON.Tools.Error("Vertex shader:" + this.name);
  24311. BABYLON.Tools.Error("Fragment shader:" + this.name);
  24312. }
  24313. };
  24314. Effect.prototype._processIncludes = function (sourceCode, callback) {
  24315. var _this = this;
  24316. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  24317. var match = regex.exec(sourceCode);
  24318. var returnValue = new String(sourceCode);
  24319. while (match != null) {
  24320. var includeFile = match[1];
  24321. if (Effect.IncludesShadersStore[includeFile]) {
  24322. // Substitution
  24323. var includeContent = Effect.IncludesShadersStore[includeFile];
  24324. if (match[2]) {
  24325. var splits = match[3].split(",");
  24326. for (var index = 0; index < splits.length; index += 2) {
  24327. var source = new RegExp(splits[index], "g");
  24328. var dest = splits[index + 1];
  24329. includeContent = includeContent.replace(source, dest);
  24330. }
  24331. }
  24332. if (match[4]) {
  24333. var indexString = match[5];
  24334. if (indexString.indexOf("..") !== -1) {
  24335. var indexSplits = indexString.split("..");
  24336. var minIndex = parseInt(indexSplits[0]);
  24337. var maxIndex = parseInt(indexSplits[1]);
  24338. var sourceIncludeContent = includeContent.slice(0);
  24339. includeContent = "";
  24340. if (isNaN(maxIndex)) {
  24341. maxIndex = this._indexParameters[indexSplits[1]];
  24342. }
  24343. for (var i = minIndex; i <= maxIndex; i++) {
  24344. includeContent += sourceIncludeContent.replace(/\{X\}/g, i) + "\n";
  24345. }
  24346. }
  24347. else {
  24348. includeContent = includeContent.replace(/\{X\}/g, indexString);
  24349. }
  24350. }
  24351. // Replace
  24352. returnValue = returnValue.replace(match[0], includeContent);
  24353. }
  24354. else {
  24355. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  24356. BABYLON.Tools.LoadFile(includeShaderUrl, function (fileContent) {
  24357. Effect.IncludesShadersStore[includeFile] = fileContent;
  24358. _this._processIncludes(returnValue, callback);
  24359. });
  24360. return;
  24361. }
  24362. match = regex.exec(sourceCode);
  24363. }
  24364. callback(returnValue);
  24365. };
  24366. Effect.prototype._processPrecision = function (source) {
  24367. if (source.indexOf("precision highp float") === -1) {
  24368. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  24369. source = "precision mediump float;\n" + source;
  24370. }
  24371. else {
  24372. source = "precision highp float;\n" + source;
  24373. }
  24374. }
  24375. else {
  24376. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  24377. source = source.replace("precision highp float", "precision mediump float");
  24378. }
  24379. }
  24380. return source;
  24381. };
  24382. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  24383. try {
  24384. var engine = this._engine;
  24385. // Precision
  24386. vertexSourceCode = this._processPrecision(vertexSourceCode);
  24387. fragmentSourceCode = this._processPrecision(fragmentSourceCode);
  24388. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  24389. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  24390. this._attributes = engine.getAttributes(this._program, attributesNames);
  24391. var index;
  24392. for (index = 0; index < this._samplers.length; index++) {
  24393. var sampler = this.getUniform(this._samplers[index]);
  24394. if (sampler == null) {
  24395. this._samplers.splice(index, 1);
  24396. index--;
  24397. }
  24398. }
  24399. engine.bindSamplers(this);
  24400. this._isReady = true;
  24401. if (this.onCompiled) {
  24402. this.onCompiled(this);
  24403. }
  24404. }
  24405. catch (e) {
  24406. // Let's go through fallbacks then
  24407. if (fallbacks && fallbacks.isMoreFallbacks) {
  24408. BABYLON.Tools.Error("Unable to compile effect with current defines. Trying next fallback.");
  24409. this._dumpShadersName();
  24410. defines = fallbacks.reduce(defines);
  24411. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  24412. }
  24413. else {
  24414. BABYLON.Tools.Error("Unable to compile effect: ");
  24415. this._dumpShadersName();
  24416. BABYLON.Tools.Error("Defines: " + defines);
  24417. BABYLON.Tools.Error("Error: " + e.message);
  24418. this._compilationError = e.message;
  24419. if (this.onError) {
  24420. this.onError(this, this._compilationError);
  24421. }
  24422. }
  24423. }
  24424. };
  24425. Object.defineProperty(Effect.prototype, "isSupported", {
  24426. get: function () {
  24427. return this._compilationError === "";
  24428. },
  24429. enumerable: true,
  24430. configurable: true
  24431. });
  24432. Effect.prototype._bindTexture = function (channel, texture) {
  24433. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  24434. };
  24435. Effect.prototype.setTexture = function (channel, texture) {
  24436. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  24437. };
  24438. Effect.prototype.setTextureArray = function (channel, textures) {
  24439. if (this._samplers.indexOf(channel + "Ex") === -1) {
  24440. var initialPos = this._samplers.indexOf(channel);
  24441. for (var index = 1; index < textures.length; index++) {
  24442. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  24443. }
  24444. }
  24445. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  24446. };
  24447. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  24448. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  24449. };
  24450. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  24451. var changed = false;
  24452. var cache = this._valueCache[uniformName];
  24453. if (!cache || !(cache instanceof BABYLON.Matrix)) {
  24454. changed = true;
  24455. cache = new BABYLON.Matrix();
  24456. }
  24457. var tm = cache.m;
  24458. var om = matrix.m;
  24459. for (var index = 0; index < 16; index++) {
  24460. if (tm[index] !== om[index]) {
  24461. tm[index] = om[index];
  24462. changed = true;
  24463. }
  24464. }
  24465. this._valueCache[uniformName] = cache;
  24466. return changed;
  24467. };
  24468. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  24469. var cache = this._valueCache[uniformName];
  24470. if (!cache) {
  24471. cache = [x, y];
  24472. this._valueCache[uniformName] = cache;
  24473. return true;
  24474. }
  24475. var changed = false;
  24476. if (cache[0] !== x) {
  24477. cache[0] = x;
  24478. changed = true;
  24479. }
  24480. if (cache[1] !== y) {
  24481. cache[1] = y;
  24482. changed = true;
  24483. }
  24484. return changed;
  24485. };
  24486. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  24487. var cache = this._valueCache[uniformName];
  24488. if (!cache) {
  24489. cache = [x, y, z];
  24490. this._valueCache[uniformName] = cache;
  24491. return true;
  24492. }
  24493. var changed = false;
  24494. if (cache[0] !== x) {
  24495. cache[0] = x;
  24496. changed = true;
  24497. }
  24498. if (cache[1] !== y) {
  24499. cache[1] = y;
  24500. changed = true;
  24501. }
  24502. if (cache[2] !== z) {
  24503. cache[2] = z;
  24504. changed = true;
  24505. }
  24506. return changed;
  24507. };
  24508. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  24509. var cache = this._valueCache[uniformName];
  24510. if (!cache) {
  24511. cache = [x, y, z, w];
  24512. this._valueCache[uniformName] = cache;
  24513. return true;
  24514. }
  24515. var changed = false;
  24516. if (cache[0] !== x) {
  24517. cache[0] = x;
  24518. changed = true;
  24519. }
  24520. if (cache[1] !== y) {
  24521. cache[1] = y;
  24522. changed = true;
  24523. }
  24524. if (cache[2] !== z) {
  24525. cache[2] = z;
  24526. changed = true;
  24527. }
  24528. if (cache[3] !== w) {
  24529. cache[3] = w;
  24530. changed = true;
  24531. }
  24532. return changed;
  24533. };
  24534. Effect.prototype.setIntArray = function (uniformName, array) {
  24535. this._valueCache[uniformName] = null;
  24536. this._engine.setIntArray(this.getUniform(uniformName), array);
  24537. return this;
  24538. };
  24539. Effect.prototype.setIntArray2 = function (uniformName, array) {
  24540. this._valueCache[uniformName] = null;
  24541. this._engine.setIntArray2(this.getUniform(uniformName), array);
  24542. return this;
  24543. };
  24544. Effect.prototype.setIntArray3 = function (uniformName, array) {
  24545. this._valueCache[uniformName] = null;
  24546. this._engine.setIntArray3(this.getUniform(uniformName), array);
  24547. return this;
  24548. };
  24549. Effect.prototype.setIntArray4 = function (uniformName, array) {
  24550. this._valueCache[uniformName] = null;
  24551. this._engine.setIntArray4(this.getUniform(uniformName), array);
  24552. return this;
  24553. };
  24554. Effect.prototype.setFloatArray = function (uniformName, array) {
  24555. this._valueCache[uniformName] = null;
  24556. this._engine.setFloatArray(this.getUniform(uniformName), array);
  24557. return this;
  24558. };
  24559. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  24560. this._valueCache[uniformName] = null;
  24561. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  24562. return this;
  24563. };
  24564. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  24565. this._valueCache[uniformName] = null;
  24566. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  24567. return this;
  24568. };
  24569. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  24570. this._valueCache[uniformName] = null;
  24571. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  24572. return this;
  24573. };
  24574. Effect.prototype.setArray = function (uniformName, array) {
  24575. this._valueCache[uniformName] = null;
  24576. this._engine.setArray(this.getUniform(uniformName), array);
  24577. return this;
  24578. };
  24579. Effect.prototype.setArray2 = function (uniformName, array) {
  24580. this._valueCache[uniformName] = null;
  24581. this._engine.setArray2(this.getUniform(uniformName), array);
  24582. return this;
  24583. };
  24584. Effect.prototype.setArray3 = function (uniformName, array) {
  24585. this._valueCache[uniformName] = null;
  24586. this._engine.setArray3(this.getUniform(uniformName), array);
  24587. return this;
  24588. };
  24589. Effect.prototype.setArray4 = function (uniformName, array) {
  24590. this._valueCache[uniformName] = null;
  24591. this._engine.setArray4(this.getUniform(uniformName), array);
  24592. return this;
  24593. };
  24594. Effect.prototype.setMatrices = function (uniformName, matrices) {
  24595. this._valueCache[uniformName] = null;
  24596. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  24597. return this;
  24598. };
  24599. Effect.prototype.setMatrix = function (uniformName, matrix) {
  24600. if (this._cacheMatrix(uniformName, matrix)) {
  24601. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  24602. }
  24603. return this;
  24604. };
  24605. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  24606. this._valueCache[uniformName] = null;
  24607. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  24608. return this;
  24609. };
  24610. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  24611. this._valueCache[uniformName] = null;
  24612. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  24613. return this;
  24614. };
  24615. Effect.prototype.setFloat = function (uniformName, value) {
  24616. var cache = this._valueCache[uniformName];
  24617. if (cache !== undefined && cache === value)
  24618. return this;
  24619. this._valueCache[uniformName] = value;
  24620. this._engine.setFloat(this.getUniform(uniformName), value);
  24621. return this;
  24622. };
  24623. Effect.prototype.setBool = function (uniformName, bool) {
  24624. var cache = this._valueCache[uniformName];
  24625. if (cache !== undefined && cache === bool)
  24626. return this;
  24627. this._valueCache[uniformName] = bool;
  24628. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  24629. return this;
  24630. };
  24631. Effect.prototype.setVector2 = function (uniformName, vector2) {
  24632. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  24633. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  24634. }
  24635. return this;
  24636. };
  24637. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  24638. if (this._cacheFloat2(uniformName, x, y)) {
  24639. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  24640. }
  24641. return this;
  24642. };
  24643. Effect.prototype.setVector3 = function (uniformName, vector3) {
  24644. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  24645. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  24646. }
  24647. return this;
  24648. };
  24649. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  24650. if (this._cacheFloat3(uniformName, x, y, z)) {
  24651. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  24652. }
  24653. return this;
  24654. };
  24655. Effect.prototype.setVector4 = function (uniformName, vector4) {
  24656. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  24657. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  24658. }
  24659. return this;
  24660. };
  24661. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  24662. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  24663. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  24664. }
  24665. return this;
  24666. };
  24667. Effect.prototype.setColor3 = function (uniformName, color3) {
  24668. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  24669. this._engine.setColor3(this.getUniform(uniformName), color3);
  24670. }
  24671. return this;
  24672. };
  24673. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  24674. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  24675. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  24676. }
  24677. return this;
  24678. };
  24679. // Statics
  24680. Effect.ShadersStore = {};
  24681. Effect.IncludesShadersStore = {};
  24682. return Effect;
  24683. }());
  24684. BABYLON.Effect = Effect;
  24685. })(BABYLON || (BABYLON = {}));
  24686. var BABYLON;
  24687. (function (BABYLON) {
  24688. var MaterialHelper = (function () {
  24689. function MaterialHelper() {
  24690. }
  24691. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, maxSimultaneousLights) {
  24692. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  24693. var lightIndex = 0;
  24694. var needNormals = false;
  24695. var needRebuild = false;
  24696. var needShadows = false;
  24697. var lightmapMode = false;
  24698. for (var index = 0; index < scene.lights.length; index++) {
  24699. var light = scene.lights[index];
  24700. if (!light.isEnabled()) {
  24701. continue;
  24702. }
  24703. // Excluded check
  24704. if (light._excludedMeshesIds.length > 0) {
  24705. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  24706. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  24707. if (excludedMesh) {
  24708. light.excludedMeshes.push(excludedMesh);
  24709. }
  24710. }
  24711. light._excludedMeshesIds = [];
  24712. }
  24713. // Included check
  24714. if (light._includedOnlyMeshesIds.length > 0) {
  24715. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  24716. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  24717. if (includedOnlyMesh) {
  24718. light.includedOnlyMeshes.push(includedOnlyMesh);
  24719. }
  24720. }
  24721. light._includedOnlyMeshesIds = [];
  24722. }
  24723. if (!light.canAffectMesh(mesh)) {
  24724. continue;
  24725. }
  24726. needNormals = true;
  24727. if (defines["LIGHT" + lightIndex] === undefined) {
  24728. needRebuild = true;
  24729. }
  24730. defines["LIGHT" + lightIndex] = true;
  24731. var type;
  24732. if (light instanceof BABYLON.SpotLight) {
  24733. type = "SPOTLIGHT" + lightIndex;
  24734. }
  24735. else if (light instanceof BABYLON.HemisphericLight) {
  24736. type = "HEMILIGHT" + lightIndex;
  24737. }
  24738. else if (light instanceof BABYLON.PointLight) {
  24739. type = "POINTLIGHT" + lightIndex;
  24740. }
  24741. else {
  24742. type = "DIRLIGHT" + lightIndex;
  24743. }
  24744. if (defines[type] === undefined) {
  24745. needRebuild = true;
  24746. }
  24747. defines[type] = true;
  24748. // Specular
  24749. if (!light.specular.equalsFloats(0, 0, 0) && defines["SPECULARTERM"] !== undefined) {
  24750. defines["SPECULARTERM"] = true;
  24751. }
  24752. // Shadows
  24753. if (scene.shadowsEnabled) {
  24754. var shadowGenerator = light.getShadowGenerator();
  24755. if (mesh && mesh.receiveShadows && shadowGenerator) {
  24756. if (defines["SHADOW" + lightIndex] === undefined) {
  24757. needRebuild = true;
  24758. }
  24759. defines["SHADOW" + lightIndex] = true;
  24760. defines["SHADOWS"] = true;
  24761. if (shadowGenerator.useVarianceShadowMap || shadowGenerator.useBlurVarianceShadowMap) {
  24762. if (defines["SHADOWVSM" + lightIndex] === undefined) {
  24763. needRebuild = true;
  24764. }
  24765. defines["SHADOWVSM" + lightIndex] = true;
  24766. }
  24767. if (shadowGenerator.usePoissonSampling) {
  24768. if (defines["SHADOWPCF" + lightIndex] === undefined) {
  24769. needRebuild = true;
  24770. }
  24771. defines["SHADOWPCF" + lightIndex] = true;
  24772. }
  24773. needShadows = true;
  24774. }
  24775. }
  24776. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  24777. lightmapMode = true;
  24778. if (defines["LIGHTMAPEXCLUDED" + lightIndex] === undefined) {
  24779. needRebuild = true;
  24780. }
  24781. if (defines["LIGHTMAPNOSPECULAR" + lightIndex] === undefined) {
  24782. needRebuild = true;
  24783. }
  24784. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  24785. if (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY) {
  24786. defines["LIGHTMAPNOSPECULAR" + lightIndex] = true;
  24787. }
  24788. }
  24789. lightIndex++;
  24790. if (lightIndex === maxSimultaneousLights)
  24791. break;
  24792. }
  24793. var caps = scene.getEngine().getCaps();
  24794. if (needShadows && caps.textureFloat && caps.textureFloatLinearFiltering && caps.textureFloatRender) {
  24795. if (defines["SHADOWFULLFLOAT"] === undefined) {
  24796. needRebuild = true;
  24797. }
  24798. defines["SHADOWFULLFLOAT"] = true;
  24799. }
  24800. if (defines["LIGHTMAPEXCLUDED"] === undefined) {
  24801. needRebuild = true;
  24802. }
  24803. if (lightmapMode) {
  24804. defines["LIGHTMAPEXCLUDED"] = true;
  24805. }
  24806. if (needRebuild) {
  24807. defines.rebuild();
  24808. }
  24809. return needNormals;
  24810. };
  24811. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsList, samplersList, defines, maxSimultaneousLights) {
  24812. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  24813. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  24814. if (!defines["LIGHT" + lightIndex]) {
  24815. break;
  24816. }
  24817. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex);
  24818. samplersList.push("shadowSampler" + lightIndex);
  24819. }
  24820. };
  24821. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights) {
  24822. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  24823. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  24824. if (!defines["LIGHT" + lightIndex]) {
  24825. break;
  24826. }
  24827. if (lightIndex > 0) {
  24828. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  24829. }
  24830. if (defines["SHADOW" + lightIndex]) {
  24831. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  24832. }
  24833. if (defines["SHADOWPCF" + lightIndex]) {
  24834. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  24835. }
  24836. if (defines["SHADOWVSM" + lightIndex]) {
  24837. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  24838. }
  24839. }
  24840. };
  24841. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  24842. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  24843. fallbacks.addCPUSkinningFallback(0, mesh);
  24844. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  24845. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  24846. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  24847. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  24848. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  24849. }
  24850. }
  24851. };
  24852. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  24853. if (defines["INSTANCES"]) {
  24854. attribs.push("world0");
  24855. attribs.push("world1");
  24856. attribs.push("world2");
  24857. attribs.push("world3");
  24858. }
  24859. };
  24860. // Bindings
  24861. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect, depthValuesAlreadySet) {
  24862. var shadowGenerator = light.getShadowGenerator();
  24863. if (mesh.receiveShadows && shadowGenerator) {
  24864. if (!light.needCube()) {
  24865. effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  24866. }
  24867. else {
  24868. if (!depthValuesAlreadySet) {
  24869. depthValuesAlreadySet = true;
  24870. effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  24871. }
  24872. }
  24873. effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMapForRendering());
  24874. effect.setFloat3("shadowsInfo" + lightIndex, shadowGenerator.getDarkness(), shadowGenerator.blurScale / shadowGenerator.getShadowMap().getSize().width, shadowGenerator.bias);
  24875. }
  24876. return depthValuesAlreadySet;
  24877. };
  24878. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  24879. if (light instanceof BABYLON.PointLight) {
  24880. // Point Light
  24881. light.transferToEffect(effect, "vLightData" + lightIndex);
  24882. }
  24883. else if (light instanceof BABYLON.DirectionalLight) {
  24884. // Directional Light
  24885. light.transferToEffect(effect, "vLightData" + lightIndex);
  24886. }
  24887. else if (light instanceof BABYLON.SpotLight) {
  24888. // Spot Light
  24889. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  24890. }
  24891. else if (light instanceof BABYLON.HemisphericLight) {
  24892. // Hemispheric Light
  24893. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  24894. }
  24895. };
  24896. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights) {
  24897. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  24898. var lightIndex = 0;
  24899. var depthValuesAlreadySet = false;
  24900. for (var index = 0; index < scene.lights.length; index++) {
  24901. var light = scene.lights[index];
  24902. if (!light.isEnabled()) {
  24903. continue;
  24904. }
  24905. if (!light.canAffectMesh(mesh)) {
  24906. continue;
  24907. }
  24908. MaterialHelper.BindLightProperties(light, effect, lightIndex);
  24909. light.diffuse.scaleToRef(light.intensity, BABYLON.Tmp.Color3[0]);
  24910. effect.setColor4("vLightDiffuse" + lightIndex, BABYLON.Tmp.Color3[0], light.range);
  24911. if (defines["SPECULARTERM"]) {
  24912. light.specular.scaleToRef(light.intensity, BABYLON.Tmp.Color3[1]);
  24913. effect.setColor3("vLightSpecular" + lightIndex, BABYLON.Tmp.Color3[1]);
  24914. }
  24915. // Shadows
  24916. if (scene.shadowsEnabled) {
  24917. depthValuesAlreadySet = this.BindLightShadow(light, scene, mesh, lightIndex, effect, depthValuesAlreadySet);
  24918. }
  24919. lightIndex++;
  24920. if (lightIndex === maxSimultaneousLights)
  24921. break;
  24922. }
  24923. };
  24924. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  24925. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  24926. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  24927. effect.setColor3("vFogColor", scene.fogColor);
  24928. }
  24929. };
  24930. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  24931. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  24932. effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  24933. }
  24934. };
  24935. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  24936. if (defines["LOGARITHMICDEPTH"]) {
  24937. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  24938. }
  24939. };
  24940. MaterialHelper.BindClipPlane = function (effect, scene) {
  24941. if (scene.clipPlane) {
  24942. var clipPlane = scene.clipPlane;
  24943. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  24944. }
  24945. };
  24946. return MaterialHelper;
  24947. }());
  24948. BABYLON.MaterialHelper = MaterialHelper;
  24949. })(BABYLON || (BABYLON = {}));
  24950. var BABYLON;
  24951. (function (BABYLON) {
  24952. var FresnelParameters = (function () {
  24953. function FresnelParameters() {
  24954. this.isEnabled = true;
  24955. this.leftColor = BABYLON.Color3.White();
  24956. this.rightColor = BABYLON.Color3.Black();
  24957. this.bias = 0;
  24958. this.power = 1;
  24959. }
  24960. FresnelParameters.prototype.clone = function () {
  24961. var newFresnelParameters = new FresnelParameters();
  24962. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  24963. return new FresnelParameters;
  24964. };
  24965. FresnelParameters.prototype.serialize = function () {
  24966. var serializationObject = {};
  24967. serializationObject.isEnabled = this.isEnabled;
  24968. serializationObject.leftColor = this.leftColor;
  24969. serializationObject.rightColor = this.rightColor;
  24970. serializationObject.bias = this.bias;
  24971. serializationObject.power = this.power;
  24972. return serializationObject;
  24973. };
  24974. FresnelParameters.Parse = function (parsedFresnelParameters) {
  24975. var fresnelParameters = new FresnelParameters();
  24976. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  24977. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  24978. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  24979. fresnelParameters.bias = parsedFresnelParameters.bias;
  24980. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  24981. return fresnelParameters;
  24982. };
  24983. return FresnelParameters;
  24984. }());
  24985. BABYLON.FresnelParameters = FresnelParameters;
  24986. })(BABYLON || (BABYLON = {}));
  24987. var BABYLON;
  24988. (function (BABYLON) {
  24989. var MaterialDefines = (function () {
  24990. function MaterialDefines() {
  24991. }
  24992. MaterialDefines.prototype.rebuild = function () {
  24993. if (this._keys) {
  24994. delete this._keys;
  24995. }
  24996. this._keys = Object.keys(this);
  24997. };
  24998. MaterialDefines.prototype.isEqual = function (other) {
  24999. if (this._keys.length !== other._keys.length) {
  25000. return false;
  25001. }
  25002. for (var index = 0; index < this._keys.length; index++) {
  25003. var prop = this._keys[index];
  25004. if (this[prop] !== other[prop]) {
  25005. return false;
  25006. }
  25007. }
  25008. return true;
  25009. };
  25010. MaterialDefines.prototype.cloneTo = function (other) {
  25011. if (this._keys.length !== other._keys.length) {
  25012. other._keys = this._keys.slice(0);
  25013. }
  25014. for (var index = 0; index < this._keys.length; index++) {
  25015. var prop = this._keys[index];
  25016. other[prop] = this[prop];
  25017. }
  25018. };
  25019. MaterialDefines.prototype.reset = function () {
  25020. for (var index = 0; index < this._keys.length; index++) {
  25021. var prop = this._keys[index];
  25022. if (typeof (this[prop]) === "number") {
  25023. this[prop] = 0;
  25024. }
  25025. else {
  25026. this[prop] = false;
  25027. }
  25028. }
  25029. };
  25030. MaterialDefines.prototype.toString = function () {
  25031. var result = "";
  25032. for (var index = 0; index < this._keys.length; index++) {
  25033. var prop = this._keys[index];
  25034. if (typeof (this[prop]) === "number") {
  25035. result += "#define " + prop + " " + this[prop] + "\n";
  25036. }
  25037. else if (this[prop]) {
  25038. result += "#define " + prop + "\n";
  25039. }
  25040. }
  25041. return result;
  25042. };
  25043. return MaterialDefines;
  25044. }());
  25045. BABYLON.MaterialDefines = MaterialDefines;
  25046. var Material = (function () {
  25047. function Material(name, scene, doNotAdd) {
  25048. this.name = name;
  25049. this.checkReadyOnEveryCall = false;
  25050. this.checkReadyOnlyOnce = false;
  25051. this.state = "";
  25052. this.alpha = 1.0;
  25053. this.backFaceCulling = true;
  25054. /**
  25055. * An event triggered when the material is disposed.
  25056. * @type {BABYLON.Observable}
  25057. */
  25058. this.onDisposeObservable = new BABYLON.Observable();
  25059. /**
  25060. * An event triggered when the material is bound.
  25061. * @type {BABYLON.Observable}
  25062. */
  25063. this.onBindObservable = new BABYLON.Observable();
  25064. /**
  25065. * An event triggered when the material is unbound.
  25066. * @type {BABYLON.Observable}
  25067. */
  25068. this.onUnBindObservable = new BABYLON.Observable();
  25069. this.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  25070. this.disableDepthWrite = false;
  25071. this.fogEnabled = true;
  25072. this.pointSize = 1.0;
  25073. this.zOffset = 0;
  25074. this._wasPreviouslyReady = false;
  25075. this._fillMode = Material.TriangleFillMode;
  25076. this.id = name;
  25077. this._scene = scene;
  25078. if (scene.useRightHandedSystem) {
  25079. this.sideOrientation = Material.ClockWiseSideOrientation;
  25080. }
  25081. else {
  25082. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  25083. }
  25084. if (!doNotAdd) {
  25085. scene.materials.push(this);
  25086. }
  25087. }
  25088. Object.defineProperty(Material, "TriangleFillMode", {
  25089. get: function () {
  25090. return Material._TriangleFillMode;
  25091. },
  25092. enumerable: true,
  25093. configurable: true
  25094. });
  25095. Object.defineProperty(Material, "WireFrameFillMode", {
  25096. get: function () {
  25097. return Material._WireFrameFillMode;
  25098. },
  25099. enumerable: true,
  25100. configurable: true
  25101. });
  25102. Object.defineProperty(Material, "PointFillMode", {
  25103. get: function () {
  25104. return Material._PointFillMode;
  25105. },
  25106. enumerable: true,
  25107. configurable: true
  25108. });
  25109. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  25110. get: function () {
  25111. return Material._ClockWiseSideOrientation;
  25112. },
  25113. enumerable: true,
  25114. configurable: true
  25115. });
  25116. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  25117. get: function () {
  25118. return Material._CounterClockWiseSideOrientation;
  25119. },
  25120. enumerable: true,
  25121. configurable: true
  25122. });
  25123. Object.defineProperty(Material.prototype, "onDispose", {
  25124. set: function (callback) {
  25125. if (this._onDisposeObserver) {
  25126. this.onDisposeObservable.remove(this._onDisposeObserver);
  25127. }
  25128. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  25129. },
  25130. enumerable: true,
  25131. configurable: true
  25132. });
  25133. Object.defineProperty(Material.prototype, "onBind", {
  25134. set: function (callback) {
  25135. if (this._onBindObserver) {
  25136. this.onBindObservable.remove(this._onBindObserver);
  25137. }
  25138. this._onBindObserver = this.onBindObservable.add(callback);
  25139. },
  25140. enumerable: true,
  25141. configurable: true
  25142. });
  25143. Object.defineProperty(Material.prototype, "wireframe", {
  25144. get: function () {
  25145. return this._fillMode === Material.WireFrameFillMode;
  25146. },
  25147. set: function (value) {
  25148. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  25149. },
  25150. enumerable: true,
  25151. configurable: true
  25152. });
  25153. Object.defineProperty(Material.prototype, "pointsCloud", {
  25154. get: function () {
  25155. return this._fillMode === Material.PointFillMode;
  25156. },
  25157. set: function (value) {
  25158. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  25159. },
  25160. enumerable: true,
  25161. configurable: true
  25162. });
  25163. Object.defineProperty(Material.prototype, "fillMode", {
  25164. get: function () {
  25165. return this._fillMode;
  25166. },
  25167. set: function (value) {
  25168. this._fillMode = value;
  25169. },
  25170. enumerable: true,
  25171. configurable: true
  25172. });
  25173. /**
  25174. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  25175. * subclasses should override adding information pertainent to themselves
  25176. */
  25177. Material.prototype.toString = function (fullDetails) {
  25178. var ret = "Name: " + this.name;
  25179. if (fullDetails) {
  25180. }
  25181. return ret;
  25182. };
  25183. Object.defineProperty(Material.prototype, "isFrozen", {
  25184. get: function () {
  25185. return this.checkReadyOnlyOnce;
  25186. },
  25187. enumerable: true,
  25188. configurable: true
  25189. });
  25190. Material.prototype.freeze = function () {
  25191. this.checkReadyOnlyOnce = true;
  25192. };
  25193. Material.prototype.unfreeze = function () {
  25194. this.checkReadyOnlyOnce = false;
  25195. };
  25196. Material.prototype.isReady = function (mesh, useInstances) {
  25197. return true;
  25198. };
  25199. Material.prototype.getEffect = function () {
  25200. return this._effect;
  25201. };
  25202. Material.prototype.getScene = function () {
  25203. return this._scene;
  25204. };
  25205. Material.prototype.needAlphaBlending = function () {
  25206. return (this.alpha < 1.0);
  25207. };
  25208. Material.prototype.needAlphaTesting = function () {
  25209. return false;
  25210. };
  25211. Material.prototype.getAlphaTestTexture = function () {
  25212. return null;
  25213. };
  25214. Material.prototype.markDirty = function () {
  25215. this._wasPreviouslyReady = false;
  25216. };
  25217. Material.prototype._preBind = function () {
  25218. var engine = this._scene.getEngine();
  25219. var reverse = this.sideOrientation === Material.ClockWiseSideOrientation;
  25220. engine.enableEffect(this._effect);
  25221. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  25222. };
  25223. Material.prototype.bind = function (world, mesh) {
  25224. this._scene._cachedMaterial = this;
  25225. this.onBindObservable.notifyObservers(mesh);
  25226. if (this.disableDepthWrite) {
  25227. var engine = this._scene.getEngine();
  25228. this._cachedDepthWriteState = engine.getDepthWrite();
  25229. engine.setDepthWrite(false);
  25230. }
  25231. };
  25232. Material.prototype.bindOnlyWorldMatrix = function (world) {
  25233. };
  25234. Material.prototype.unbind = function () {
  25235. this.onUnBindObservable.notifyObservers(this);
  25236. if (this.disableDepthWrite) {
  25237. var engine = this._scene.getEngine();
  25238. engine.setDepthWrite(this._cachedDepthWriteState);
  25239. }
  25240. };
  25241. Material.prototype.clone = function (name) {
  25242. return null;
  25243. };
  25244. Material.prototype.getBindedMeshes = function () {
  25245. var result = new Array();
  25246. for (var index = 0; index < this._scene.meshes.length; index++) {
  25247. var mesh = this._scene.meshes[index];
  25248. if (mesh.material === this) {
  25249. result.push(mesh);
  25250. }
  25251. }
  25252. return result;
  25253. };
  25254. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  25255. // Animations
  25256. this.getScene().stopAnimation(this);
  25257. // Remove from scene
  25258. var index = this._scene.materials.indexOf(this);
  25259. if (index >= 0) {
  25260. this._scene.materials.splice(index, 1);
  25261. }
  25262. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  25263. if (forceDisposeEffect && this._effect) {
  25264. this._scene.getEngine()._releaseEffect(this._effect);
  25265. this._effect = null;
  25266. }
  25267. // Remove from meshes
  25268. for (index = 0; index < this._scene.meshes.length; index++) {
  25269. var mesh = this._scene.meshes[index];
  25270. if (mesh.material === this) {
  25271. mesh.material = null;
  25272. }
  25273. }
  25274. // Callback
  25275. this.onDisposeObservable.notifyObservers(this);
  25276. this.onDisposeObservable.clear();
  25277. this.onBindObservable.clear();
  25278. this.onUnBindObservable.clear();
  25279. };
  25280. Material.prototype.serialize = function () {
  25281. return BABYLON.SerializationHelper.Serialize(this);
  25282. };
  25283. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  25284. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  25285. multiMaterial.id = parsedMultiMaterial.id;
  25286. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  25287. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  25288. var subMatId = parsedMultiMaterial.materials[matIndex];
  25289. if (subMatId) {
  25290. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  25291. }
  25292. else {
  25293. multiMaterial.subMaterials.push(null);
  25294. }
  25295. }
  25296. return multiMaterial;
  25297. };
  25298. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  25299. if (!parsedMaterial.customType) {
  25300. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  25301. }
  25302. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  25303. return materialType.Parse(parsedMaterial, scene, rootUrl);
  25304. ;
  25305. };
  25306. Material._TriangleFillMode = 0;
  25307. Material._WireFrameFillMode = 1;
  25308. Material._PointFillMode = 2;
  25309. Material._ClockWiseSideOrientation = 0;
  25310. Material._CounterClockWiseSideOrientation = 1;
  25311. __decorate([
  25312. BABYLON.serialize()
  25313. ], Material.prototype, "id", void 0);
  25314. __decorate([
  25315. BABYLON.serialize()
  25316. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  25317. __decorate([
  25318. BABYLON.serialize()
  25319. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  25320. __decorate([
  25321. BABYLON.serialize()
  25322. ], Material.prototype, "state", void 0);
  25323. __decorate([
  25324. BABYLON.serialize()
  25325. ], Material.prototype, "alpha", void 0);
  25326. __decorate([
  25327. BABYLON.serialize()
  25328. ], Material.prototype, "backFaceCulling", void 0);
  25329. __decorate([
  25330. BABYLON.serialize()
  25331. ], Material.prototype, "sideOrientation", void 0);
  25332. __decorate([
  25333. BABYLON.serialize()
  25334. ], Material.prototype, "alphaMode", void 0);
  25335. __decorate([
  25336. BABYLON.serialize()
  25337. ], Material.prototype, "disableDepthWrite", void 0);
  25338. __decorate([
  25339. BABYLON.serialize()
  25340. ], Material.prototype, "fogEnabled", void 0);
  25341. __decorate([
  25342. BABYLON.serialize()
  25343. ], Material.prototype, "pointSize", void 0);
  25344. __decorate([
  25345. BABYLON.serialize()
  25346. ], Material.prototype, "zOffset", void 0);
  25347. __decorate([
  25348. BABYLON.serialize()
  25349. ], Material.prototype, "wireframe", null);
  25350. __decorate([
  25351. BABYLON.serialize()
  25352. ], Material.prototype, "pointsCloud", null);
  25353. __decorate([
  25354. BABYLON.serialize()
  25355. ], Material.prototype, "fillMode", null);
  25356. return Material;
  25357. }());
  25358. BABYLON.Material = Material;
  25359. })(BABYLON || (BABYLON = {}));
  25360. var BABYLON;
  25361. (function (BABYLON) {
  25362. var StandardMaterialDefines = (function (_super) {
  25363. __extends(StandardMaterialDefines, _super);
  25364. function StandardMaterialDefines() {
  25365. _super.call(this);
  25366. this.DIFFUSE = false;
  25367. this.AMBIENT = false;
  25368. this.OPACITY = false;
  25369. this.OPACITYRGB = false;
  25370. this.REFLECTION = false;
  25371. this.EMISSIVE = false;
  25372. this.SPECULAR = false;
  25373. this.BUMP = false;
  25374. this.PARALLAX = false;
  25375. this.PARALLAXOCCLUSION = false;
  25376. this.SPECULAROVERALPHA = false;
  25377. this.CLIPPLANE = false;
  25378. this.ALPHATEST = false;
  25379. this.ALPHAFROMDIFFUSE = false;
  25380. this.POINTSIZE = false;
  25381. this.FOG = false;
  25382. this.SPECULARTERM = false;
  25383. this.DIFFUSEFRESNEL = false;
  25384. this.OPACITYFRESNEL = false;
  25385. this.REFLECTIONFRESNEL = false;
  25386. this.REFRACTIONFRESNEL = false;
  25387. this.EMISSIVEFRESNEL = false;
  25388. this.FRESNEL = false;
  25389. this.NORMAL = false;
  25390. this.UV1 = false;
  25391. this.UV2 = false;
  25392. this.VERTEXCOLOR = false;
  25393. this.VERTEXALPHA = false;
  25394. this.NUM_BONE_INFLUENCERS = 0;
  25395. this.BonesPerMesh = 0;
  25396. this.INSTANCES = false;
  25397. this.GLOSSINESS = false;
  25398. this.ROUGHNESS = false;
  25399. this.EMISSIVEASILLUMINATION = false;
  25400. this.LINKEMISSIVEWITHDIFFUSE = false;
  25401. this.REFLECTIONFRESNELFROMSPECULAR = false;
  25402. this.LIGHTMAP = false;
  25403. this.USELIGHTMAPASSHADOWMAP = false;
  25404. this.REFLECTIONMAP_3D = false;
  25405. this.REFLECTIONMAP_SPHERICAL = false;
  25406. this.REFLECTIONMAP_PLANAR = false;
  25407. this.REFLECTIONMAP_CUBIC = false;
  25408. this.REFLECTIONMAP_PROJECTION = false;
  25409. this.REFLECTIONMAP_SKYBOX = false;
  25410. this.REFLECTIONMAP_EXPLICIT = false;
  25411. this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  25412. this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  25413. this.INVERTCUBICMAP = false;
  25414. this.LOGARITHMICDEPTH = false;
  25415. this.REFRACTION = false;
  25416. this.REFRACTIONMAP_3D = false;
  25417. this.REFLECTIONOVERALPHA = false;
  25418. this.INVERTNORMALMAPX = false;
  25419. this.INVERTNORMALMAPY = false;
  25420. this.SHADOWFULLFLOAT = false;
  25421. this.CAMERACOLORGRADING = false;
  25422. this.CAMERACOLORCURVES = false;
  25423. this.rebuild();
  25424. }
  25425. return StandardMaterialDefines;
  25426. }(BABYLON.MaterialDefines));
  25427. var StandardMaterial = (function (_super) {
  25428. __extends(StandardMaterial, _super);
  25429. function StandardMaterial(name, scene) {
  25430. var _this = this;
  25431. _super.call(this, name, scene);
  25432. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  25433. this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  25434. this.specularColor = new BABYLON.Color3(1, 1, 1);
  25435. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  25436. this.specularPower = 64;
  25437. this.useAlphaFromDiffuseTexture = false;
  25438. this.useEmissiveAsIllumination = false;
  25439. this.linkEmissiveWithDiffuse = false;
  25440. this.useReflectionFresnelFromSpecular = false;
  25441. this.useSpecularOverAlpha = false;
  25442. this.useReflectionOverAlpha = false;
  25443. this.disableLighting = false;
  25444. this.useParallax = false;
  25445. this.useParallaxOcclusion = false;
  25446. this.parallaxScaleBias = 0.05;
  25447. this.roughness = 0;
  25448. this.indexOfRefraction = 0.98;
  25449. this.invertRefractionY = true;
  25450. this.useLightmapAsShadowmap = false;
  25451. this.useGlossinessFromSpecularMapAlpha = false;
  25452. this.maxSimultaneousLights = 4;
  25453. /**
  25454. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  25455. */
  25456. this.invertNormalMapX = false;
  25457. /**
  25458. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  25459. */
  25460. this.invertNormalMapY = false;
  25461. /**
  25462. * Color Grading 2D Lookup Texture.
  25463. * This allows special effects like sepia, black and white to sixties rendering style.
  25464. */
  25465. this.cameraColorGradingTexture = null;
  25466. /**
  25467. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  25468. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  25469. * 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;
  25470. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  25471. */
  25472. this.cameraColorCurves = null;
  25473. this._renderTargets = new BABYLON.SmartArray(16);
  25474. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  25475. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  25476. this._defines = new StandardMaterialDefines();
  25477. this._cachedDefines = new StandardMaterialDefines();
  25478. this._cachedDefines.BonesPerMesh = -1;
  25479. this.getRenderTargetTextures = function () {
  25480. _this._renderTargets.reset();
  25481. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  25482. _this._renderTargets.push(_this.reflectionTexture);
  25483. }
  25484. if (_this.refractionTexture && _this.refractionTexture.isRenderTarget) {
  25485. _this._renderTargets.push(_this.refractionTexture);
  25486. }
  25487. return _this._renderTargets;
  25488. };
  25489. }
  25490. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  25491. get: function () {
  25492. return this._useLogarithmicDepth;
  25493. },
  25494. set: function (value) {
  25495. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  25496. },
  25497. enumerable: true,
  25498. configurable: true
  25499. });
  25500. StandardMaterial.prototype.needAlphaBlending = function () {
  25501. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  25502. };
  25503. StandardMaterial.prototype.needAlphaTesting = function () {
  25504. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha;
  25505. };
  25506. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  25507. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  25508. };
  25509. StandardMaterial.prototype.getAlphaTestTexture = function () {
  25510. return this.diffuseTexture;
  25511. };
  25512. // Methods
  25513. StandardMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  25514. if (!mesh) {
  25515. return true;
  25516. }
  25517. if (this._defines.INSTANCES !== useInstances) {
  25518. return false;
  25519. }
  25520. if (mesh._materialDefines && mesh._materialDefines.isEqual(this._defines)) {
  25521. return true;
  25522. }
  25523. return false;
  25524. };
  25525. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  25526. if (this.isFrozen) {
  25527. if (this._wasPreviouslyReady) {
  25528. return true;
  25529. }
  25530. }
  25531. var scene = this.getScene();
  25532. if (!this.checkReadyOnEveryCall) {
  25533. if (this._renderId === scene.getRenderId()) {
  25534. if (this._checkCache(scene, mesh, useInstances)) {
  25535. return true;
  25536. }
  25537. }
  25538. }
  25539. var engine = scene.getEngine();
  25540. var needNormals = false;
  25541. var needUVs = false;
  25542. this._defines.reset();
  25543. // Textures
  25544. if (scene.texturesEnabled) {
  25545. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  25546. if (!this.diffuseTexture.isReady()) {
  25547. return false;
  25548. }
  25549. else {
  25550. needUVs = true;
  25551. this._defines.DIFFUSE = true;
  25552. }
  25553. }
  25554. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  25555. if (!this.ambientTexture.isReady()) {
  25556. return false;
  25557. }
  25558. else {
  25559. needUVs = true;
  25560. this._defines.AMBIENT = true;
  25561. }
  25562. }
  25563. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  25564. if (!this.opacityTexture.isReady()) {
  25565. return false;
  25566. }
  25567. else {
  25568. needUVs = true;
  25569. this._defines.OPACITY = true;
  25570. if (this.opacityTexture.getAlphaFromRGB) {
  25571. this._defines.OPACITYRGB = true;
  25572. }
  25573. }
  25574. }
  25575. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  25576. if (!this.reflectionTexture.isReady()) {
  25577. return false;
  25578. }
  25579. else {
  25580. needNormals = true;
  25581. this._defines.REFLECTION = true;
  25582. if (this.roughness > 0) {
  25583. this._defines.ROUGHNESS = true;
  25584. }
  25585. if (this.useReflectionOverAlpha) {
  25586. this._defines.REFLECTIONOVERALPHA = true;
  25587. }
  25588. if (this.reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  25589. this._defines.INVERTCUBICMAP = true;
  25590. }
  25591. this._defines.REFLECTIONMAP_3D = this.reflectionTexture.isCube;
  25592. switch (this.reflectionTexture.coordinatesMode) {
  25593. case BABYLON.Texture.CUBIC_MODE:
  25594. case BABYLON.Texture.INVCUBIC_MODE:
  25595. this._defines.REFLECTIONMAP_CUBIC = true;
  25596. break;
  25597. case BABYLON.Texture.EXPLICIT_MODE:
  25598. this._defines.REFLECTIONMAP_EXPLICIT = true;
  25599. break;
  25600. case BABYLON.Texture.PLANAR_MODE:
  25601. this._defines.REFLECTIONMAP_PLANAR = true;
  25602. break;
  25603. case BABYLON.Texture.PROJECTION_MODE:
  25604. this._defines.REFLECTIONMAP_PROJECTION = true;
  25605. break;
  25606. case BABYLON.Texture.SKYBOX_MODE:
  25607. this._defines.REFLECTIONMAP_SKYBOX = true;
  25608. break;
  25609. case BABYLON.Texture.SPHERICAL_MODE:
  25610. this._defines.REFLECTIONMAP_SPHERICAL = true;
  25611. break;
  25612. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  25613. this._defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  25614. break;
  25615. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  25616. this._defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  25617. break;
  25618. }
  25619. }
  25620. }
  25621. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  25622. if (!this.emissiveTexture.isReady()) {
  25623. return false;
  25624. }
  25625. else {
  25626. needUVs = true;
  25627. this._defines.EMISSIVE = true;
  25628. }
  25629. }
  25630. if (this.lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  25631. if (!this.lightmapTexture.isReady()) {
  25632. return false;
  25633. }
  25634. else {
  25635. needUVs = true;
  25636. this._defines.LIGHTMAP = true;
  25637. this._defines.USELIGHTMAPASSHADOWMAP = this.useLightmapAsShadowmap;
  25638. }
  25639. }
  25640. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  25641. if (!this.specularTexture.isReady()) {
  25642. return false;
  25643. }
  25644. else {
  25645. needUVs = true;
  25646. this._defines.SPECULAR = true;
  25647. this._defines.GLOSSINESS = this.useGlossinessFromSpecularMapAlpha;
  25648. }
  25649. }
  25650. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && StandardMaterial.BumpTextureEnabled) {
  25651. if (!this.bumpTexture.isReady()) {
  25652. return false;
  25653. }
  25654. else {
  25655. needUVs = true;
  25656. this._defines.BUMP = true;
  25657. if (this.useParallax) {
  25658. this._defines.PARALLAX = true;
  25659. if (this.useParallaxOcclusion) {
  25660. this._defines.PARALLAXOCCLUSION = true;
  25661. }
  25662. }
  25663. if (this.invertNormalMapX) {
  25664. this._defines.INVERTNORMALMAPX = true;
  25665. }
  25666. if (this.invertNormalMapY) {
  25667. this._defines.INVERTNORMALMAPY = true;
  25668. }
  25669. }
  25670. }
  25671. if (this.refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  25672. if (!this.refractionTexture.isReady()) {
  25673. return false;
  25674. }
  25675. else {
  25676. needUVs = true;
  25677. this._defines.REFRACTION = true;
  25678. this._defines.REFRACTIONMAP_3D = this.refractionTexture.isCube;
  25679. }
  25680. }
  25681. if (this.cameraColorGradingTexture && StandardMaterial.ColorGradingTextureEnabled) {
  25682. if (!this.cameraColorGradingTexture.isReady()) {
  25683. return false;
  25684. }
  25685. else {
  25686. this._defines.CAMERACOLORGRADING = true;
  25687. }
  25688. }
  25689. }
  25690. // Effect
  25691. if (scene.clipPlane) {
  25692. this._defines.CLIPPLANE = true;
  25693. }
  25694. if (engine.getAlphaTesting()) {
  25695. this._defines.ALPHATEST = true;
  25696. }
  25697. if (this._shouldUseAlphaFromDiffuseTexture()) {
  25698. this._defines.ALPHAFROMDIFFUSE = true;
  25699. }
  25700. if (this.useEmissiveAsIllumination) {
  25701. this._defines.EMISSIVEASILLUMINATION = true;
  25702. }
  25703. if (this.linkEmissiveWithDiffuse) {
  25704. this._defines.LINKEMISSIVEWITHDIFFUSE = true;
  25705. }
  25706. if (this.useLogarithmicDepth) {
  25707. this._defines.LOGARITHMICDEPTH = true;
  25708. }
  25709. if (this.cameraColorCurves) {
  25710. this._defines.CAMERACOLORCURVES = true;
  25711. }
  25712. // Point size
  25713. if (this.pointsCloud || scene.forcePointsCloud) {
  25714. this._defines.POINTSIZE = true;
  25715. }
  25716. // Fog
  25717. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  25718. this._defines.FOG = true;
  25719. }
  25720. if (scene.lightsEnabled && !this.disableLighting) {
  25721. needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, this._defines, this.maxSimultaneousLights);
  25722. }
  25723. if (StandardMaterial.FresnelEnabled) {
  25724. // Fresnel
  25725. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled ||
  25726. this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  25727. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled ||
  25728. this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled ||
  25729. this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  25730. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  25731. this._defines.DIFFUSEFRESNEL = true;
  25732. }
  25733. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  25734. this._defines.OPACITYFRESNEL = true;
  25735. }
  25736. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  25737. this._defines.REFLECTIONFRESNEL = true;
  25738. if (this.useReflectionFresnelFromSpecular) {
  25739. this._defines.REFLECTIONFRESNELFROMSPECULAR = true;
  25740. }
  25741. }
  25742. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  25743. this._defines.REFRACTIONFRESNEL = true;
  25744. }
  25745. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  25746. this._defines.EMISSIVEFRESNEL = true;
  25747. }
  25748. needNormals = true;
  25749. this._defines.FRESNEL = true;
  25750. }
  25751. }
  25752. if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
  25753. this._defines.SPECULAROVERALPHA = true;
  25754. }
  25755. // Attribs
  25756. if (mesh) {
  25757. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  25758. this._defines.NORMAL = true;
  25759. }
  25760. if (needUVs) {
  25761. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  25762. this._defines.UV1 = true;
  25763. }
  25764. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  25765. this._defines.UV2 = true;
  25766. }
  25767. }
  25768. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  25769. this._defines.VERTEXCOLOR = true;
  25770. if (mesh.hasVertexAlpha) {
  25771. this._defines.VERTEXALPHA = true;
  25772. }
  25773. }
  25774. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  25775. this._defines.NUM_BONE_INFLUENCERS = mesh.numBoneInfluencers;
  25776. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  25777. }
  25778. // Instances
  25779. if (useInstances) {
  25780. this._defines.INSTANCES = true;
  25781. }
  25782. }
  25783. // Get correct effect
  25784. if (!this._defines.isEqual(this._cachedDefines)) {
  25785. this._defines.cloneTo(this._cachedDefines);
  25786. scene.resetCachedMaterial();
  25787. // Fallbacks
  25788. var fallbacks = new BABYLON.EffectFallbacks();
  25789. if (this._defines.REFLECTION) {
  25790. fallbacks.addFallback(0, "REFLECTION");
  25791. }
  25792. if (this._defines.SPECULAR) {
  25793. fallbacks.addFallback(0, "SPECULAR");
  25794. }
  25795. if (this._defines.BUMP) {
  25796. fallbacks.addFallback(0, "BUMP");
  25797. }
  25798. if (this._defines.PARALLAX) {
  25799. fallbacks.addFallback(1, "PARALLAX");
  25800. }
  25801. if (this._defines.PARALLAXOCCLUSION) {
  25802. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  25803. }
  25804. if (this._defines.SPECULAROVERALPHA) {
  25805. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  25806. }
  25807. if (this._defines.FOG) {
  25808. fallbacks.addFallback(1, "FOG");
  25809. }
  25810. if (this._defines.POINTSIZE) {
  25811. fallbacks.addFallback(0, "POINTSIZE");
  25812. }
  25813. if (this._defines.LOGARITHMICDEPTH) {
  25814. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  25815. }
  25816. BABYLON.MaterialHelper.HandleFallbacksForShadows(this._defines, fallbacks, this.maxSimultaneousLights);
  25817. if (this._defines.SPECULARTERM) {
  25818. fallbacks.addFallback(0, "SPECULARTERM");
  25819. }
  25820. if (this._defines.DIFFUSEFRESNEL) {
  25821. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  25822. }
  25823. if (this._defines.OPACITYFRESNEL) {
  25824. fallbacks.addFallback(2, "OPACITYFRESNEL");
  25825. }
  25826. if (this._defines.REFLECTIONFRESNEL) {
  25827. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  25828. }
  25829. if (this._defines.EMISSIVEFRESNEL) {
  25830. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  25831. }
  25832. if (this._defines.FRESNEL) {
  25833. fallbacks.addFallback(4, "FRESNEL");
  25834. }
  25835. //Attributes
  25836. var attribs = [BABYLON.VertexBuffer.PositionKind];
  25837. if (this._defines.NORMAL) {
  25838. attribs.push(BABYLON.VertexBuffer.NormalKind);
  25839. }
  25840. if (this._defines.UV1) {
  25841. attribs.push(BABYLON.VertexBuffer.UVKind);
  25842. }
  25843. if (this._defines.UV2) {
  25844. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  25845. }
  25846. if (this._defines.VERTEXCOLOR) {
  25847. attribs.push(BABYLON.VertexBuffer.ColorKind);
  25848. }
  25849. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, this._defines, fallbacks);
  25850. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, this._defines);
  25851. var shaderName = "default";
  25852. var join = this._defines.toString();
  25853. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  25854. "vFogInfos", "vFogColor", "pointSize",
  25855. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  25856. "mBones",
  25857. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  25858. "depthValues",
  25859. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  25860. "logarithmicDepthConstant"
  25861. ];
  25862. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  25863. if (this._defines.CAMERACOLORCURVES) {
  25864. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  25865. }
  25866. if (this._defines.CAMERACOLORGRADING) {
  25867. BABYLON.ColorGradingTexture.PrepareUniformsAndSamplers(uniforms, samplers);
  25868. }
  25869. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList(uniforms, samplers, this._defines, this.maxSimultaneousLights);
  25870. this._effect = scene.getEngine().createEffect(shaderName, attribs, uniforms, samplers, join, fallbacks, this.onCompiled, this.onError, { maxSimultaneousLights: this.maxSimultaneousLights - 1 });
  25871. }
  25872. if (!this._effect.isReady()) {
  25873. return false;
  25874. }
  25875. this._renderId = scene.getRenderId();
  25876. this._wasPreviouslyReady = true;
  25877. if (mesh) {
  25878. if (!mesh._materialDefines) {
  25879. mesh._materialDefines = new StandardMaterialDefines();
  25880. }
  25881. this._defines.cloneTo(mesh._materialDefines);
  25882. }
  25883. return true;
  25884. };
  25885. StandardMaterial.prototype.unbind = function () {
  25886. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  25887. this._effect.setTexture("reflection2DSampler", null);
  25888. }
  25889. if (this.refractionTexture && this.refractionTexture.isRenderTarget) {
  25890. this._effect.setTexture("refraction2DSampler", null);
  25891. }
  25892. _super.prototype.unbind.call(this);
  25893. };
  25894. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  25895. this._effect.setMatrix("world", world);
  25896. };
  25897. StandardMaterial.prototype.bind = function (world, mesh) {
  25898. var scene = this.getScene();
  25899. // Matrices
  25900. this.bindOnlyWorldMatrix(world);
  25901. // Bones
  25902. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  25903. if (scene.getCachedMaterial() !== this) {
  25904. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  25905. if (StandardMaterial.FresnelEnabled) {
  25906. // Fresnel
  25907. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  25908. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  25909. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  25910. }
  25911. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  25912. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  25913. }
  25914. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  25915. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  25916. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  25917. }
  25918. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  25919. this._effect.setColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  25920. this._effect.setColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  25921. }
  25922. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  25923. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  25924. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  25925. }
  25926. }
  25927. // Textures
  25928. if (scene.texturesEnabled) {
  25929. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  25930. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  25931. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  25932. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  25933. }
  25934. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  25935. this._effect.setTexture("ambientSampler", this.ambientTexture);
  25936. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  25937. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  25938. }
  25939. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  25940. this._effect.setTexture("opacitySampler", this.opacityTexture);
  25941. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  25942. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  25943. }
  25944. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  25945. if (this.reflectionTexture.isCube) {
  25946. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  25947. }
  25948. else {
  25949. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  25950. }
  25951. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  25952. this._effect.setFloat2("vReflectionInfos", this.reflectionTexture.level, this.roughness);
  25953. }
  25954. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  25955. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  25956. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  25957. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  25958. }
  25959. if (this.lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  25960. this._effect.setTexture("lightmapSampler", this.lightmapTexture);
  25961. this._effect.setFloat2("vLightmapInfos", this.lightmapTexture.coordinatesIndex, this.lightmapTexture.level);
  25962. this._effect.setMatrix("lightmapMatrix", this.lightmapTexture.getTextureMatrix());
  25963. }
  25964. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  25965. this._effect.setTexture("specularSampler", this.specularTexture);
  25966. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  25967. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  25968. }
  25969. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  25970. this._effect.setTexture("bumpSampler", this.bumpTexture);
  25971. this._effect.setFloat3("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level, this.parallaxScaleBias);
  25972. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  25973. }
  25974. if (this.refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  25975. var depth = 1.0;
  25976. if (this.refractionTexture.isCube) {
  25977. this._effect.setTexture("refractionCubeSampler", this.refractionTexture);
  25978. }
  25979. else {
  25980. this._effect.setTexture("refraction2DSampler", this.refractionTexture);
  25981. this._effect.setMatrix("refractionMatrix", this.refractionTexture.getReflectionTextureMatrix());
  25982. if (this.refractionTexture.depth) {
  25983. depth = this.refractionTexture.depth;
  25984. }
  25985. }
  25986. this._effect.setFloat4("vRefractionInfos", this.refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  25987. }
  25988. if (this.cameraColorGradingTexture && StandardMaterial.ColorGradingTextureEnabled) {
  25989. BABYLON.ColorGradingTexture.Bind(this.cameraColorGradingTexture, this._effect);
  25990. }
  25991. }
  25992. // Clip plane
  25993. BABYLON.MaterialHelper.BindClipPlane(this._effect, scene);
  25994. // Point size
  25995. if (this.pointsCloud) {
  25996. this._effect.setFloat("pointSize", this.pointSize);
  25997. }
  25998. // Colors
  25999. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  26000. this._effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.position);
  26001. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  26002. if (this._defines.SPECULARTERM) {
  26003. this._effect.setColor4("vSpecularColor", this.specularColor, this.specularPower);
  26004. }
  26005. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  26006. }
  26007. if (scene.getCachedMaterial() !== this || !this.isFrozen) {
  26008. // Diffuse
  26009. this._effect.setColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  26010. // Lights
  26011. if (scene.lightsEnabled && !this.disableLighting) {
  26012. BABYLON.MaterialHelper.BindLights(scene, mesh, this._effect, this._defines, this.maxSimultaneousLights);
  26013. }
  26014. // View
  26015. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture || this.refractionTexture) {
  26016. this._effect.setMatrix("view", scene.getViewMatrix());
  26017. }
  26018. // Fog
  26019. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._effect);
  26020. // Log. depth
  26021. BABYLON.MaterialHelper.BindLogDepth(this._defines, this._effect, scene);
  26022. // Color Curves
  26023. if (this.cameraColorCurves) {
  26024. BABYLON.ColorCurves.Bind(this.cameraColorCurves, this._effect);
  26025. }
  26026. }
  26027. _super.prototype.bind.call(this, world, mesh);
  26028. };
  26029. StandardMaterial.prototype.getAnimatables = function () {
  26030. var results = [];
  26031. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  26032. results.push(this.diffuseTexture);
  26033. }
  26034. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  26035. results.push(this.ambientTexture);
  26036. }
  26037. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  26038. results.push(this.opacityTexture);
  26039. }
  26040. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  26041. results.push(this.reflectionTexture);
  26042. }
  26043. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  26044. results.push(this.emissiveTexture);
  26045. }
  26046. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  26047. results.push(this.specularTexture);
  26048. }
  26049. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  26050. results.push(this.bumpTexture);
  26051. }
  26052. if (this.lightmapTexture && this.lightmapTexture.animations && this.lightmapTexture.animations.length > 0) {
  26053. results.push(this.lightmapTexture);
  26054. }
  26055. if (this.refractionTexture && this.refractionTexture.animations && this.refractionTexture.animations.length > 0) {
  26056. results.push(this.refractionTexture);
  26057. }
  26058. if (this.cameraColorGradingTexture && this.cameraColorGradingTexture.animations && this.cameraColorGradingTexture.animations.length > 0) {
  26059. results.push(this.cameraColorGradingTexture);
  26060. }
  26061. return results;
  26062. };
  26063. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  26064. if (forceDisposeTextures) {
  26065. if (this.diffuseTexture) {
  26066. this.diffuseTexture.dispose();
  26067. }
  26068. if (this.ambientTexture) {
  26069. this.ambientTexture.dispose();
  26070. }
  26071. if (this.opacityTexture) {
  26072. this.opacityTexture.dispose();
  26073. }
  26074. if (this.reflectionTexture) {
  26075. this.reflectionTexture.dispose();
  26076. }
  26077. if (this.emissiveTexture) {
  26078. this.emissiveTexture.dispose();
  26079. }
  26080. if (this.specularTexture) {
  26081. this.specularTexture.dispose();
  26082. }
  26083. if (this.bumpTexture) {
  26084. this.bumpTexture.dispose();
  26085. }
  26086. if (this.lightmapTexture) {
  26087. this.lightmapTexture.dispose();
  26088. }
  26089. if (this.refractionTexture) {
  26090. this.refractionTexture.dispose();
  26091. }
  26092. if (this.cameraColorGradingTexture) {
  26093. this.cameraColorGradingTexture.dispose();
  26094. }
  26095. }
  26096. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  26097. };
  26098. StandardMaterial.prototype.clone = function (name) {
  26099. var _this = this;
  26100. return BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  26101. };
  26102. StandardMaterial.prototype.serialize = function () {
  26103. return BABYLON.SerializationHelper.Serialize(this);
  26104. };
  26105. // Statics
  26106. StandardMaterial.Parse = function (source, scene, rootUrl) {
  26107. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  26108. };
  26109. // Flags used to enable or disable a type of texture for all Standard Materials
  26110. StandardMaterial.DiffuseTextureEnabled = true;
  26111. StandardMaterial.AmbientTextureEnabled = true;
  26112. StandardMaterial.OpacityTextureEnabled = true;
  26113. StandardMaterial.ReflectionTextureEnabled = true;
  26114. StandardMaterial.EmissiveTextureEnabled = true;
  26115. StandardMaterial.SpecularTextureEnabled = true;
  26116. StandardMaterial.BumpTextureEnabled = true;
  26117. StandardMaterial.FresnelEnabled = true;
  26118. StandardMaterial.LightmapTextureEnabled = true;
  26119. StandardMaterial.RefractionTextureEnabled = true;
  26120. StandardMaterial.ColorGradingTextureEnabled = true;
  26121. __decorate([
  26122. BABYLON.serializeAsTexture()
  26123. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  26124. __decorate([
  26125. BABYLON.serializeAsTexture()
  26126. ], StandardMaterial.prototype, "ambientTexture", void 0);
  26127. __decorate([
  26128. BABYLON.serializeAsTexture()
  26129. ], StandardMaterial.prototype, "opacityTexture", void 0);
  26130. __decorate([
  26131. BABYLON.serializeAsTexture()
  26132. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  26133. __decorate([
  26134. BABYLON.serializeAsTexture()
  26135. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  26136. __decorate([
  26137. BABYLON.serializeAsTexture()
  26138. ], StandardMaterial.prototype, "specularTexture", void 0);
  26139. __decorate([
  26140. BABYLON.serializeAsTexture()
  26141. ], StandardMaterial.prototype, "bumpTexture", void 0);
  26142. __decorate([
  26143. BABYLON.serializeAsTexture()
  26144. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  26145. __decorate([
  26146. BABYLON.serializeAsTexture()
  26147. ], StandardMaterial.prototype, "refractionTexture", void 0);
  26148. __decorate([
  26149. BABYLON.serializeAsColor3("ambient")
  26150. ], StandardMaterial.prototype, "ambientColor", void 0);
  26151. __decorate([
  26152. BABYLON.serializeAsColor3("diffuse")
  26153. ], StandardMaterial.prototype, "diffuseColor", void 0);
  26154. __decorate([
  26155. BABYLON.serializeAsColor3("specular")
  26156. ], StandardMaterial.prototype, "specularColor", void 0);
  26157. __decorate([
  26158. BABYLON.serializeAsColor3("emissive")
  26159. ], StandardMaterial.prototype, "emissiveColor", void 0);
  26160. __decorate([
  26161. BABYLON.serialize()
  26162. ], StandardMaterial.prototype, "specularPower", void 0);
  26163. __decorate([
  26164. BABYLON.serialize()
  26165. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  26166. __decorate([
  26167. BABYLON.serialize()
  26168. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  26169. __decorate([
  26170. BABYLON.serialize()
  26171. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  26172. __decorate([
  26173. BABYLON.serialize()
  26174. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  26175. __decorate([
  26176. BABYLON.serialize()
  26177. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  26178. __decorate([
  26179. BABYLON.serialize()
  26180. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  26181. __decorate([
  26182. BABYLON.serialize()
  26183. ], StandardMaterial.prototype, "disableLighting", void 0);
  26184. __decorate([
  26185. BABYLON.serialize()
  26186. ], StandardMaterial.prototype, "useParallax", void 0);
  26187. __decorate([
  26188. BABYLON.serialize()
  26189. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  26190. __decorate([
  26191. BABYLON.serialize()
  26192. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  26193. __decorate([
  26194. BABYLON.serialize()
  26195. ], StandardMaterial.prototype, "roughness", void 0);
  26196. __decorate([
  26197. BABYLON.serialize()
  26198. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  26199. __decorate([
  26200. BABYLON.serialize()
  26201. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  26202. __decorate([
  26203. BABYLON.serialize()
  26204. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  26205. __decorate([
  26206. BABYLON.serializeAsFresnelParameters()
  26207. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  26208. __decorate([
  26209. BABYLON.serializeAsFresnelParameters()
  26210. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  26211. __decorate([
  26212. BABYLON.serializeAsFresnelParameters()
  26213. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  26214. __decorate([
  26215. BABYLON.serializeAsFresnelParameters()
  26216. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  26217. __decorate([
  26218. BABYLON.serializeAsFresnelParameters()
  26219. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  26220. __decorate([
  26221. BABYLON.serialize()
  26222. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  26223. __decorate([
  26224. BABYLON.serialize()
  26225. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  26226. __decorate([
  26227. BABYLON.serialize()
  26228. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  26229. __decorate([
  26230. BABYLON.serialize()
  26231. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  26232. __decorate([
  26233. BABYLON.serializeAsTexture()
  26234. ], StandardMaterial.prototype, "cameraColorGradingTexture", void 0);
  26235. __decorate([
  26236. BABYLON.serializeAsColorCurves()
  26237. ], StandardMaterial.prototype, "cameraColorCurves", void 0);
  26238. __decorate([
  26239. BABYLON.serialize()
  26240. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  26241. return StandardMaterial;
  26242. }(BABYLON.Material));
  26243. BABYLON.StandardMaterial = StandardMaterial;
  26244. })(BABYLON || (BABYLON = {}));
  26245. var BABYLON;
  26246. (function (BABYLON) {
  26247. var MultiMaterial = (function (_super) {
  26248. __extends(MultiMaterial, _super);
  26249. function MultiMaterial(name, scene) {
  26250. _super.call(this, name, scene, true);
  26251. this.subMaterials = new Array();
  26252. scene.multiMaterials.push(this);
  26253. }
  26254. // Properties
  26255. MultiMaterial.prototype.getSubMaterial = function (index) {
  26256. if (index < 0 || index >= this.subMaterials.length) {
  26257. return this.getScene().defaultMaterial;
  26258. }
  26259. return this.subMaterials[index];
  26260. };
  26261. // Methods
  26262. MultiMaterial.prototype.isReady = function (mesh) {
  26263. for (var index = 0; index < this.subMaterials.length; index++) {
  26264. var subMaterial = this.subMaterials[index];
  26265. if (subMaterial) {
  26266. if (!this.subMaterials[index].isReady(mesh)) {
  26267. return false;
  26268. }
  26269. }
  26270. }
  26271. return true;
  26272. };
  26273. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  26274. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  26275. for (var index = 0; index < this.subMaterials.length; index++) {
  26276. var subMaterial = null;
  26277. if (cloneChildren) {
  26278. subMaterial = this.subMaterials[index].clone(name + "-" + this.subMaterials[index].name);
  26279. }
  26280. else {
  26281. subMaterial = this.subMaterials[index];
  26282. }
  26283. newMultiMaterial.subMaterials.push(subMaterial);
  26284. }
  26285. return newMultiMaterial;
  26286. };
  26287. MultiMaterial.prototype.serialize = function () {
  26288. var serializationObject = {};
  26289. serializationObject.name = this.name;
  26290. serializationObject.id = this.id;
  26291. serializationObject.tags = BABYLON.Tags.GetTags(this);
  26292. serializationObject.materials = [];
  26293. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  26294. var subMat = this.subMaterials[matIndex];
  26295. if (subMat) {
  26296. serializationObject.materials.push(subMat.id);
  26297. }
  26298. else {
  26299. serializationObject.materials.push(null);
  26300. }
  26301. }
  26302. return serializationObject;
  26303. };
  26304. return MultiMaterial;
  26305. }(BABYLON.Material));
  26306. BABYLON.MultiMaterial = MultiMaterial;
  26307. })(BABYLON || (BABYLON = {}));
  26308. var BABYLON;
  26309. (function (BABYLON) {
  26310. var SceneLoader = (function () {
  26311. function SceneLoader() {
  26312. }
  26313. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  26314. get: function () {
  26315. return 0;
  26316. },
  26317. enumerable: true,
  26318. configurable: true
  26319. });
  26320. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  26321. get: function () {
  26322. return 1;
  26323. },
  26324. enumerable: true,
  26325. configurable: true
  26326. });
  26327. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  26328. get: function () {
  26329. return 2;
  26330. },
  26331. enumerable: true,
  26332. configurable: true
  26333. });
  26334. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  26335. get: function () {
  26336. return 3;
  26337. },
  26338. enumerable: true,
  26339. configurable: true
  26340. });
  26341. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  26342. get: function () {
  26343. return SceneLoader._ForceFullSceneLoadingForIncremental;
  26344. },
  26345. set: function (value) {
  26346. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  26347. },
  26348. enumerable: true,
  26349. configurable: true
  26350. });
  26351. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  26352. get: function () {
  26353. return SceneLoader._ShowLoadingScreen;
  26354. },
  26355. set: function (value) {
  26356. SceneLoader._ShowLoadingScreen = value;
  26357. },
  26358. enumerable: true,
  26359. configurable: true
  26360. });
  26361. Object.defineProperty(SceneLoader, "loggingLevel", {
  26362. get: function () {
  26363. return SceneLoader._loggingLevel;
  26364. },
  26365. set: function (value) {
  26366. SceneLoader._loggingLevel = value;
  26367. },
  26368. enumerable: true,
  26369. configurable: true
  26370. });
  26371. SceneLoader._getDefaultPlugin = function () {
  26372. return SceneLoader._registeredPlugins[".babylon"];
  26373. };
  26374. SceneLoader._getPluginForExtension = function (extension) {
  26375. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  26376. if (registeredPlugin) {
  26377. return registeredPlugin;
  26378. }
  26379. return SceneLoader._getDefaultPlugin();
  26380. };
  26381. SceneLoader._getPluginForFilename = function (sceneFilename) {
  26382. if (sceneFilename.name) {
  26383. sceneFilename = sceneFilename.name;
  26384. }
  26385. var dotPosition = sceneFilename.lastIndexOf(".");
  26386. var queryStringPosition = sceneFilename.indexOf("?");
  26387. if (queryStringPosition === -1) {
  26388. queryStringPosition = sceneFilename.length;
  26389. }
  26390. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  26391. return SceneLoader._getPluginForExtension(extension);
  26392. };
  26393. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  26394. SceneLoader._getDirectLoad = function (sceneFilename) {
  26395. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  26396. return sceneFilename.substr(5);
  26397. }
  26398. return null;
  26399. };
  26400. // Public functions
  26401. SceneLoader.GetPluginForExtension = function (extension) {
  26402. return SceneLoader._getPluginForExtension(extension).plugin;
  26403. };
  26404. SceneLoader.RegisterPlugin = function (plugin) {
  26405. if (typeof plugin.extensions === "string") {
  26406. var extension = plugin.extensions;
  26407. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  26408. plugin: plugin,
  26409. isBinary: false
  26410. };
  26411. }
  26412. else {
  26413. var extensions = plugin.extensions;
  26414. Object.keys(extensions).forEach(function (extension) {
  26415. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  26416. plugin: plugin,
  26417. isBinary: extensions[extension].isBinary
  26418. };
  26419. });
  26420. }
  26421. };
  26422. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  26423. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  26424. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  26425. return;
  26426. }
  26427. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  26428. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  26429. return;
  26430. }
  26431. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  26432. var loadingToken = {};
  26433. scene._addPendingData(loadingToken);
  26434. var manifestChecked = function (success) {
  26435. scene.database = database;
  26436. var registeredPlugin = directLoad ? SceneLoader._getDefaultPlugin() : SceneLoader._getPluginForFilename(sceneFilename);
  26437. var plugin = registeredPlugin.plugin;
  26438. var useArrayBuffer = registeredPlugin.isBinary;
  26439. var importMeshFromData = function (data) {
  26440. var meshes = [];
  26441. var particleSystems = [];
  26442. var skeletons = [];
  26443. try {
  26444. if (plugin.importMesh) {
  26445. var syncedPlugin = plugin;
  26446. if (!syncedPlugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  26447. if (onerror) {
  26448. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  26449. }
  26450. scene._removePendingData(loadingToken);
  26451. return;
  26452. }
  26453. if (onsuccess) {
  26454. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  26455. onsuccess(meshes, particleSystems, skeletons);
  26456. scene._removePendingData(loadingToken);
  26457. }
  26458. }
  26459. else {
  26460. var asyncedPlugin = plugin;
  26461. asyncedPlugin.importMeshAsync(meshesNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  26462. if (onsuccess) {
  26463. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  26464. onsuccess(meshes, particleSystems, skeletons);
  26465. scene._removePendingData(loadingToken);
  26466. }
  26467. }, function () {
  26468. if (onerror) {
  26469. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  26470. }
  26471. scene._removePendingData(loadingToken);
  26472. });
  26473. }
  26474. }
  26475. catch (e) {
  26476. if (onerror) {
  26477. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename, e);
  26478. }
  26479. scene._removePendingData(loadingToken);
  26480. }
  26481. };
  26482. if (directLoad) {
  26483. importMeshFromData(directLoad);
  26484. return;
  26485. }
  26486. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  26487. importMeshFromData(data);
  26488. }, progressCallBack, database, useArrayBuffer);
  26489. };
  26490. if (scene.getEngine().enableOfflineSupport && !directLoad) {
  26491. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  26492. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  26493. }
  26494. else {
  26495. // If the scene is a data stream or offline support is not enabled, it's a direct load
  26496. manifestChecked(true);
  26497. }
  26498. };
  26499. /**
  26500. * Load a scene
  26501. * @param rootUrl a string that defines the root url for scene and resources
  26502. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  26503. * @param engine is the instance of BABYLON.Engine to use to create the scene
  26504. */
  26505. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  26506. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  26507. };
  26508. /**
  26509. * Append a scene
  26510. * @param rootUrl a string that defines the root url for scene and resources
  26511. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  26512. * @param scene is the instance of BABYLON.Scene to append to
  26513. */
  26514. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  26515. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  26516. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  26517. return;
  26518. }
  26519. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  26520. var registeredPlugin = directLoad ? SceneLoader._getDefaultPlugin() : SceneLoader._getPluginForFilename(sceneFilename);
  26521. var plugin = registeredPlugin.plugin;
  26522. var useArrayBuffer = registeredPlugin.isBinary;
  26523. var database;
  26524. var loadingToken = {};
  26525. scene._addPendingData(loadingToken);
  26526. if (SceneLoader.ShowLoadingScreen) {
  26527. scene.getEngine().displayLoadingUI();
  26528. }
  26529. var loadSceneFromData = function (data) {
  26530. scene.database = database;
  26531. if (plugin.load) {
  26532. var syncedPlugin = plugin;
  26533. if (!syncedPlugin.load(scene, data, rootUrl)) {
  26534. if (onerror) {
  26535. onerror(scene);
  26536. }
  26537. scene._removePendingData(loadingToken);
  26538. scene.getEngine().hideLoadingUI();
  26539. return;
  26540. }
  26541. if (onsuccess) {
  26542. onsuccess(scene);
  26543. }
  26544. scene._removePendingData(loadingToken);
  26545. }
  26546. else {
  26547. var asyncedPlugin = plugin;
  26548. asyncedPlugin.loadAsync(scene, data, rootUrl, function () {
  26549. if (onsuccess) {
  26550. onsuccess(scene);
  26551. }
  26552. }, function () {
  26553. if (onerror) {
  26554. onerror(scene);
  26555. }
  26556. scene._removePendingData(loadingToken);
  26557. scene.getEngine().hideLoadingUI();
  26558. });
  26559. }
  26560. if (SceneLoader.ShowLoadingScreen) {
  26561. scene.executeWhenReady(function () {
  26562. scene.getEngine().hideLoadingUI();
  26563. });
  26564. }
  26565. };
  26566. var manifestChecked = function (success) {
  26567. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database, useArrayBuffer);
  26568. };
  26569. if (directLoad) {
  26570. loadSceneFromData(directLoad);
  26571. return;
  26572. }
  26573. if (rootUrl.indexOf("file:") === -1) {
  26574. if (scene.getEngine().enableOfflineSupport) {
  26575. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  26576. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  26577. }
  26578. else {
  26579. manifestChecked(true);
  26580. }
  26581. }
  26582. else {
  26583. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack, useArrayBuffer);
  26584. }
  26585. };
  26586. // Flags
  26587. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  26588. SceneLoader._ShowLoadingScreen = true;
  26589. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  26590. // Members
  26591. SceneLoader._registeredPlugins = {};
  26592. return SceneLoader;
  26593. }());
  26594. BABYLON.SceneLoader = SceneLoader;
  26595. ;
  26596. })(BABYLON || (BABYLON = {}));
  26597. var BABYLON;
  26598. (function (BABYLON) {
  26599. var Internals;
  26600. (function (Internals) {
  26601. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  26602. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  26603. var parsedMaterial = parsedData.materials[index];
  26604. if (parsedMaterial.id === id) {
  26605. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  26606. }
  26607. }
  26608. return null;
  26609. };
  26610. var isDescendantOf = function (mesh, names, hierarchyIds) {
  26611. names = (names instanceof Array) ? names : [names];
  26612. for (var i in names) {
  26613. if (mesh.name === names[i]) {
  26614. hierarchyIds.push(mesh.id);
  26615. return true;
  26616. }
  26617. }
  26618. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  26619. hierarchyIds.push(mesh.id);
  26620. return true;
  26621. }
  26622. return false;
  26623. };
  26624. var logOperation = function (operation, producer) {
  26625. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  26626. };
  26627. BABYLON.SceneLoader.RegisterPlugin({
  26628. extensions: ".babylon",
  26629. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  26630. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  26631. // when SceneLoader.debugLogging = true (default), or exception encountered.
  26632. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  26633. // and avoid problems with multiple concurrent .babylon loads.
  26634. var log = "importMesh has failed JSON parse";
  26635. try {
  26636. var parsedData = JSON.parse(data);
  26637. log = "";
  26638. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  26639. var loadedSkeletonsIds = [];
  26640. var loadedMaterialsIds = [];
  26641. var hierarchyIds = [];
  26642. var index;
  26643. var cache;
  26644. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  26645. var parsedMesh = parsedData.meshes[index];
  26646. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  26647. if (meshesNames instanceof Array) {
  26648. // Remove found mesh name from list.
  26649. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  26650. }
  26651. //Geometry?
  26652. if (parsedMesh.geometryId) {
  26653. //does the file contain geometries?
  26654. if (parsedData.geometries) {
  26655. //find the correct geometry and add it to the scene
  26656. var found = false;
  26657. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  26658. if (found || !parsedData.geometries[geometryType] || !(parsedData.geometries[geometryType] instanceof Array)) {
  26659. return;
  26660. }
  26661. else {
  26662. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  26663. if (parsedGeometryData.id === parsedMesh.geometryId) {
  26664. switch (geometryType) {
  26665. case "boxes":
  26666. BABYLON.Geometry.Primitives.Box.Parse(parsedGeometryData, scene);
  26667. break;
  26668. case "spheres":
  26669. BABYLON.Geometry.Primitives.Sphere.Parse(parsedGeometryData, scene);
  26670. break;
  26671. case "cylinders":
  26672. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedGeometryData, scene);
  26673. break;
  26674. case "toruses":
  26675. BABYLON.Geometry.Primitives.Torus.Parse(parsedGeometryData, scene);
  26676. break;
  26677. case "grounds":
  26678. BABYLON.Geometry.Primitives.Ground.Parse(parsedGeometryData, scene);
  26679. break;
  26680. case "planes":
  26681. BABYLON.Geometry.Primitives.Plane.Parse(parsedGeometryData, scene);
  26682. break;
  26683. case "torusKnots":
  26684. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedGeometryData, scene);
  26685. break;
  26686. case "vertexData":
  26687. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  26688. break;
  26689. }
  26690. found = true;
  26691. }
  26692. });
  26693. }
  26694. });
  26695. if (!found) {
  26696. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  26697. }
  26698. }
  26699. }
  26700. // Material ?
  26701. if (parsedMesh.materialId) {
  26702. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  26703. if (!materialFound && parsedData.multiMaterials) {
  26704. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  26705. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  26706. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  26707. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  26708. var subMatId = parsedMultiMaterial.materials[matIndex];
  26709. loadedMaterialsIds.push(subMatId);
  26710. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  26711. log += "\n\tMaterial " + mat.toString(fullDetails);
  26712. }
  26713. loadedMaterialsIds.push(parsedMultiMaterial.id);
  26714. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  26715. materialFound = true;
  26716. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  26717. break;
  26718. }
  26719. }
  26720. }
  26721. if (!materialFound) {
  26722. loadedMaterialsIds.push(parsedMesh.materialId);
  26723. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  26724. if (!mat) {
  26725. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  26726. }
  26727. else {
  26728. log += "\n\tMaterial " + mat.toString(fullDetails);
  26729. }
  26730. }
  26731. }
  26732. // Skeleton ?
  26733. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  26734. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  26735. if (!skeletonAlreadyLoaded) {
  26736. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  26737. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  26738. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  26739. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  26740. skeletons.push(skeleton);
  26741. loadedSkeletonsIds.push(parsedSkeleton.id);
  26742. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  26743. }
  26744. }
  26745. }
  26746. }
  26747. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  26748. meshes.push(mesh);
  26749. log += "\n\tMesh " + mesh.toString(fullDetails);
  26750. }
  26751. }
  26752. // Connecting parents
  26753. var currentMesh;
  26754. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  26755. currentMesh = scene.meshes[index];
  26756. if (currentMesh._waitingParentId) {
  26757. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  26758. currentMesh._waitingParentId = undefined;
  26759. }
  26760. }
  26761. // freeze and compute world matrix application
  26762. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  26763. currentMesh = scene.meshes[index];
  26764. if (currentMesh._waitingFreezeWorldMatrix) {
  26765. currentMesh.freezeWorldMatrix();
  26766. currentMesh._waitingFreezeWorldMatrix = undefined;
  26767. }
  26768. else {
  26769. currentMesh.computeWorldMatrix(true);
  26770. }
  26771. }
  26772. // Particles
  26773. if (parsedData.particleSystems) {
  26774. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  26775. var parsedParticleSystem = parsedData.particleSystems[index];
  26776. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  26777. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  26778. }
  26779. }
  26780. }
  26781. return true;
  26782. }
  26783. catch (err) {
  26784. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log);
  26785. log = null;
  26786. throw err;
  26787. }
  26788. finally {
  26789. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  26790. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  26791. }
  26792. }
  26793. },
  26794. load: function (scene, data, rootUrl) {
  26795. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  26796. // when SceneLoader.debugLogging = true (default), or exception encountered.
  26797. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  26798. // and avoid problems with multiple concurrent .babylon loads.
  26799. var log = "importScene has failed JSON parse";
  26800. try {
  26801. var parsedData = JSON.parse(data);
  26802. log = "";
  26803. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  26804. // Scene
  26805. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  26806. scene.autoClear = parsedData.autoClear;
  26807. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  26808. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  26809. if (parsedData.gravity) {
  26810. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  26811. }
  26812. // Fog
  26813. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  26814. scene.fogMode = parsedData.fogMode;
  26815. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  26816. scene.fogStart = parsedData.fogStart;
  26817. scene.fogEnd = parsedData.fogEnd;
  26818. scene.fogDensity = parsedData.fogDensity;
  26819. log += "\tFog mode for scene: ";
  26820. switch (scene.fogMode) {
  26821. // getters not compiling, so using hardcoded
  26822. case 1:
  26823. log += "exp\n";
  26824. break;
  26825. case 2:
  26826. log += "exp2\n";
  26827. break;
  26828. case 3:
  26829. log += "linear\n";
  26830. break;
  26831. }
  26832. }
  26833. //Physics
  26834. if (parsedData.physicsEnabled) {
  26835. var physicsPlugin;
  26836. if (parsedData.physicsEngine === "cannon") {
  26837. physicsPlugin = new BABYLON.CannonJSPlugin();
  26838. }
  26839. else if (parsedData.physicsEngine === "oimo") {
  26840. physicsPlugin = new BABYLON.OimoJSPlugin();
  26841. }
  26842. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  26843. //else - default engine, which is currently oimo
  26844. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  26845. scene.enablePhysics(physicsGravity, physicsPlugin);
  26846. }
  26847. //collisions, if defined. otherwise, default is true
  26848. if (parsedData.collisionsEnabled != undefined) {
  26849. scene.collisionsEnabled = parsedData.collisionsEnabled;
  26850. }
  26851. scene.workerCollisions = !!parsedData.workerCollisions;
  26852. var index;
  26853. var cache;
  26854. // Lights
  26855. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  26856. var parsedLight = parsedData.lights[index];
  26857. var light = BABYLON.Light.Parse(parsedLight, scene);
  26858. log += (index === 0 ? "\n\tLights:" : "");
  26859. log += "\n\t\t" + light.toString(fullDetails);
  26860. }
  26861. // Animations
  26862. if (parsedData.animations) {
  26863. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  26864. var parsedAnimation = parsedData.animations[index];
  26865. var animation = BABYLON.Animation.Parse(parsedAnimation);
  26866. scene.animations.push(animation);
  26867. log += (index === 0 ? "\n\tAnimations:" : "");
  26868. log += "\n\t\t" + animation.toString(fullDetails);
  26869. }
  26870. }
  26871. if (parsedData.autoAnimate) {
  26872. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  26873. }
  26874. // Materials
  26875. if (parsedData.materials) {
  26876. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  26877. var parsedMaterial = parsedData.materials[index];
  26878. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  26879. log += (index === 0 ? "\n\tMaterials:" : "");
  26880. log += "\n\t\t" + mat.toString(fullDetails);
  26881. }
  26882. }
  26883. if (parsedData.multiMaterials) {
  26884. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  26885. var parsedMultiMaterial = parsedData.multiMaterials[index];
  26886. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  26887. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  26888. log += "\n\t\t" + mmat.toString(fullDetails);
  26889. }
  26890. }
  26891. // Skeletons
  26892. if (parsedData.skeletons) {
  26893. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  26894. var parsedSkeleton = parsedData.skeletons[index];
  26895. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  26896. log += (index === 0 ? "\n\tSkeletons:" : "");
  26897. log += "\n\t\t" + skeleton.toString(fullDetails);
  26898. }
  26899. }
  26900. // Geometries
  26901. var geometries = parsedData.geometries;
  26902. if (geometries) {
  26903. // Boxes
  26904. var boxes = geometries.boxes;
  26905. if (boxes) {
  26906. for (index = 0, cache = boxes.length; index < cache; index++) {
  26907. var parsedBox = boxes[index];
  26908. BABYLON.Geometry.Primitives.Box.Parse(parsedBox, scene);
  26909. }
  26910. }
  26911. // Spheres
  26912. var spheres = geometries.spheres;
  26913. if (spheres) {
  26914. for (index = 0, cache = spheres.length; index < cache; index++) {
  26915. var parsedSphere = spheres[index];
  26916. BABYLON.Geometry.Primitives.Sphere.Parse(parsedSphere, scene);
  26917. }
  26918. }
  26919. // Cylinders
  26920. var cylinders = geometries.cylinders;
  26921. if (cylinders) {
  26922. for (index = 0, cache = cylinders.length; index < cache; index++) {
  26923. var parsedCylinder = cylinders[index];
  26924. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedCylinder, scene);
  26925. }
  26926. }
  26927. // Toruses
  26928. var toruses = geometries.toruses;
  26929. if (toruses) {
  26930. for (index = 0, cache = toruses.length; index < cache; index++) {
  26931. var parsedTorus = toruses[index];
  26932. BABYLON.Geometry.Primitives.Torus.Parse(parsedTorus, scene);
  26933. }
  26934. }
  26935. // Grounds
  26936. var grounds = geometries.grounds;
  26937. if (grounds) {
  26938. for (index = 0, cache = grounds.length; index < cache; index++) {
  26939. var parsedGround = grounds[index];
  26940. BABYLON.Geometry.Primitives.Ground.Parse(parsedGround, scene);
  26941. }
  26942. }
  26943. // Planes
  26944. var planes = geometries.planes;
  26945. if (planes) {
  26946. for (index = 0, cache = planes.length; index < cache; index++) {
  26947. var parsedPlane = planes[index];
  26948. BABYLON.Geometry.Primitives.Plane.Parse(parsedPlane, scene);
  26949. }
  26950. }
  26951. // TorusKnots
  26952. var torusKnots = geometries.torusKnots;
  26953. if (torusKnots) {
  26954. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  26955. var parsedTorusKnot = torusKnots[index];
  26956. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedTorusKnot, scene);
  26957. }
  26958. }
  26959. // VertexData
  26960. var vertexData = geometries.vertexData;
  26961. if (vertexData) {
  26962. for (index = 0, cache = vertexData.length; index < cache; index++) {
  26963. var parsedVertexData = vertexData[index];
  26964. BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl);
  26965. }
  26966. }
  26967. }
  26968. // Meshes
  26969. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  26970. var parsedMesh = parsedData.meshes[index];
  26971. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  26972. log += (index === 0 ? "\n\tMeshes:" : "");
  26973. log += "\n\t\t" + mesh.toString(fullDetails);
  26974. }
  26975. // Cameras
  26976. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  26977. var parsedCamera = parsedData.cameras[index];
  26978. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  26979. log += (index === 0 ? "\n\tCameras:" : "");
  26980. log += "\n\t\t" + camera.toString(fullDetails);
  26981. }
  26982. if (parsedData.activeCameraID) {
  26983. scene.setActiveCameraByID(parsedData.activeCameraID);
  26984. }
  26985. // Browsing all the graph to connect the dots
  26986. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  26987. var camera = scene.cameras[index];
  26988. if (camera._waitingParentId) {
  26989. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  26990. camera._waitingParentId = undefined;
  26991. }
  26992. }
  26993. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  26994. var light = scene.lights[index];
  26995. if (light._waitingParentId) {
  26996. light.parent = scene.getLastEntryByID(light._waitingParentId);
  26997. light._waitingParentId = undefined;
  26998. }
  26999. }
  27000. // Sounds
  27001. var loadedSounds = [];
  27002. var loadedSound;
  27003. if (BABYLON.AudioEngine && parsedData.sounds) {
  27004. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  27005. var parsedSound = parsedData.sounds[index];
  27006. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  27007. if (!parsedSound.url)
  27008. parsedSound.url = parsedSound.name;
  27009. if (!loadedSounds[parsedSound.url]) {
  27010. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  27011. loadedSounds[parsedSound.url] = loadedSound;
  27012. }
  27013. else {
  27014. BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]);
  27015. }
  27016. }
  27017. else {
  27018. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  27019. }
  27020. }
  27021. }
  27022. loadedSounds = [];
  27023. // Connect parents & children and parse actions
  27024. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  27025. var mesh = scene.meshes[index];
  27026. if (mesh._waitingParentId) {
  27027. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  27028. mesh._waitingParentId = undefined;
  27029. }
  27030. if (mesh._waitingActions) {
  27031. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  27032. mesh._waitingActions = undefined;
  27033. }
  27034. }
  27035. // freeze world matrix application
  27036. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  27037. var currentMesh = scene.meshes[index];
  27038. if (currentMesh._waitingFreezeWorldMatrix) {
  27039. currentMesh.freezeWorldMatrix();
  27040. currentMesh._waitingFreezeWorldMatrix = undefined;
  27041. }
  27042. else {
  27043. currentMesh.computeWorldMatrix(true);
  27044. }
  27045. }
  27046. // Particles Systems
  27047. if (parsedData.particleSystems) {
  27048. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  27049. var parsedParticleSystem = parsedData.particleSystems[index];
  27050. BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  27051. }
  27052. }
  27053. // Lens flares
  27054. if (parsedData.lensFlareSystems) {
  27055. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  27056. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  27057. BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  27058. }
  27059. }
  27060. // Shadows
  27061. if (parsedData.shadowGenerators) {
  27062. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  27063. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  27064. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  27065. }
  27066. }
  27067. // Actions (scene)
  27068. if (parsedData.actions) {
  27069. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  27070. }
  27071. // Finish
  27072. return true;
  27073. }
  27074. catch (err) {
  27075. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log);
  27076. log = null;
  27077. throw err;
  27078. }
  27079. finally {
  27080. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  27081. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  27082. }
  27083. }
  27084. }
  27085. });
  27086. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  27087. })(BABYLON || (BABYLON = {}));
  27088. var BABYLON;
  27089. (function (BABYLON) {
  27090. var SpriteManager = (function () {
  27091. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  27092. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  27093. this.name = name;
  27094. this.sprites = new Array();
  27095. this.renderingGroupId = 0;
  27096. this.layerMask = 0x0FFFFFFF;
  27097. this.fogEnabled = true;
  27098. this.isPickable = false;
  27099. /**
  27100. * An event triggered when the manager is disposed.
  27101. * @type {BABYLON.Observable}
  27102. */
  27103. this.onDisposeObservable = new BABYLON.Observable();
  27104. this._vertexBuffers = {};
  27105. this._capacity = capacity;
  27106. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  27107. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  27108. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  27109. this._epsilon = epsilon === undefined ? 0.01 : epsilon;
  27110. if (cellSize.width) {
  27111. this.cellWidth = cellSize.width;
  27112. this.cellHeight = cellSize.height;
  27113. }
  27114. else {
  27115. this.cellWidth = cellSize;
  27116. this.cellHeight = cellSize;
  27117. }
  27118. this._scene = scene;
  27119. this._scene.spriteManagers.push(this);
  27120. var indices = [];
  27121. var index = 0;
  27122. for (var count = 0; count < capacity; count++) {
  27123. indices.push(index);
  27124. indices.push(index + 1);
  27125. indices.push(index + 2);
  27126. indices.push(index);
  27127. indices.push(index + 2);
  27128. indices.push(index + 3);
  27129. index += 4;
  27130. }
  27131. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  27132. // VBO
  27133. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  27134. this._vertexData = new Float32Array(capacity * 16 * 4);
  27135. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  27136. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  27137. var options = this._buffer.createVertexBuffer("options", 4, 4);
  27138. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  27139. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  27140. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  27141. this._vertexBuffers["options"] = options;
  27142. this._vertexBuffers["cellInfo"] = cellInfo;
  27143. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  27144. // Effects
  27145. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  27146. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  27147. }
  27148. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  27149. set: function (callback) {
  27150. if (this._onDisposeObserver) {
  27151. this.onDisposeObservable.remove(this._onDisposeObserver);
  27152. }
  27153. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  27154. },
  27155. enumerable: true,
  27156. configurable: true
  27157. });
  27158. Object.defineProperty(SpriteManager.prototype, "texture", {
  27159. get: function () {
  27160. return this._spriteTexture;
  27161. },
  27162. set: function (value) {
  27163. this._spriteTexture = value;
  27164. },
  27165. enumerable: true,
  27166. configurable: true
  27167. });
  27168. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  27169. var arrayOffset = index * 16;
  27170. if (offsetX === 0)
  27171. offsetX = this._epsilon;
  27172. else if (offsetX === 1)
  27173. offsetX = 1 - this._epsilon;
  27174. if (offsetY === 0)
  27175. offsetY = this._epsilon;
  27176. else if (offsetY === 1)
  27177. offsetY = 1 - this._epsilon;
  27178. this._vertexData[arrayOffset] = sprite.position.x;
  27179. this._vertexData[arrayOffset + 1] = sprite.position.y;
  27180. this._vertexData[arrayOffset + 2] = sprite.position.z;
  27181. this._vertexData[arrayOffset + 3] = sprite.angle;
  27182. this._vertexData[arrayOffset + 4] = sprite.width;
  27183. this._vertexData[arrayOffset + 5] = sprite.height;
  27184. this._vertexData[arrayOffset + 6] = offsetX;
  27185. this._vertexData[arrayOffset + 7] = offsetY;
  27186. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  27187. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  27188. var offset = (sprite.cellIndex / rowSize) >> 0;
  27189. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  27190. this._vertexData[arrayOffset + 11] = offset;
  27191. // Color
  27192. this._vertexData[arrayOffset + 12] = sprite.color.r;
  27193. this._vertexData[arrayOffset + 13] = sprite.color.g;
  27194. this._vertexData[arrayOffset + 14] = sprite.color.b;
  27195. this._vertexData[arrayOffset + 15] = sprite.color.a;
  27196. };
  27197. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  27198. var count = Math.min(this._capacity, this.sprites.length);
  27199. var min = BABYLON.Vector3.Zero();
  27200. var max = BABYLON.Vector3.Zero();
  27201. var distance = Number.MAX_VALUE;
  27202. var currentSprite;
  27203. var cameraSpacePosition = BABYLON.Vector3.Zero();
  27204. var cameraView = camera.getViewMatrix();
  27205. for (var index = 0; index < count; index++) {
  27206. var sprite = this.sprites[index];
  27207. if (!sprite) {
  27208. continue;
  27209. }
  27210. if (predicate) {
  27211. if (!predicate(sprite)) {
  27212. continue;
  27213. }
  27214. }
  27215. else if (!sprite.isPickable) {
  27216. continue;
  27217. }
  27218. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  27219. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  27220. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  27221. if (ray.intersectsBoxMinMax(min, max)) {
  27222. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  27223. if (distance > currentDistance) {
  27224. distance = currentDistance;
  27225. currentSprite = sprite;
  27226. if (fastCheck) {
  27227. break;
  27228. }
  27229. }
  27230. }
  27231. }
  27232. if (currentSprite) {
  27233. var result = new BABYLON.PickingInfo();
  27234. result.hit = true;
  27235. result.pickedSprite = currentSprite;
  27236. result.distance = distance;
  27237. return result;
  27238. }
  27239. return null;
  27240. };
  27241. SpriteManager.prototype.render = function () {
  27242. // Check
  27243. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  27244. return;
  27245. var engine = this._scene.getEngine();
  27246. var baseSize = this._spriteTexture.getBaseSize();
  27247. // Sprites
  27248. var deltaTime = engine.getDeltaTime();
  27249. var max = Math.min(this._capacity, this.sprites.length);
  27250. var rowSize = baseSize.width / this.cellWidth;
  27251. var offset = 0;
  27252. for (var index = 0; index < max; index++) {
  27253. var sprite = this.sprites[index];
  27254. if (!sprite) {
  27255. continue;
  27256. }
  27257. sprite._animate(deltaTime);
  27258. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  27259. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  27260. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  27261. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  27262. }
  27263. this._buffer.update(this._vertexData);
  27264. // Render
  27265. var effect = this._effectBase;
  27266. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  27267. effect = this._effectFog;
  27268. }
  27269. engine.enableEffect(effect);
  27270. var viewMatrix = this._scene.getViewMatrix();
  27271. effect.setTexture("diffuseSampler", this._spriteTexture);
  27272. effect.setMatrix("view", viewMatrix);
  27273. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  27274. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  27275. // Fog
  27276. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  27277. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  27278. effect.setColor3("vFogColor", this._scene.fogColor);
  27279. }
  27280. // VBOs
  27281. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  27282. // Draw order
  27283. engine.setDepthFunctionToLessOrEqual();
  27284. effect.setBool("alphaTest", true);
  27285. engine.setColorWrite(false);
  27286. engine.draw(true, 0, max * 6);
  27287. engine.setColorWrite(true);
  27288. effect.setBool("alphaTest", false);
  27289. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  27290. engine.draw(true, 0, max * 6);
  27291. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  27292. };
  27293. SpriteManager.prototype.dispose = function () {
  27294. if (this._buffer) {
  27295. this._buffer.dispose();
  27296. this._buffer = null;
  27297. }
  27298. if (this._indexBuffer) {
  27299. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  27300. this._indexBuffer = null;
  27301. }
  27302. if (this._spriteTexture) {
  27303. this._spriteTexture.dispose();
  27304. this._spriteTexture = null;
  27305. }
  27306. // Remove from scene
  27307. var index = this._scene.spriteManagers.indexOf(this);
  27308. this._scene.spriteManagers.splice(index, 1);
  27309. // Callback
  27310. this.onDisposeObservable.notifyObservers(this);
  27311. this.onDisposeObservable.clear();
  27312. };
  27313. return SpriteManager;
  27314. }());
  27315. BABYLON.SpriteManager = SpriteManager;
  27316. })(BABYLON || (BABYLON = {}));
  27317. var BABYLON;
  27318. (function (BABYLON) {
  27319. var Sprite = (function () {
  27320. function Sprite(name, manager) {
  27321. this.name = name;
  27322. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  27323. this.width = 1.0;
  27324. this.height = 1.0;
  27325. this.angle = 0;
  27326. this.cellIndex = 0;
  27327. this.invertU = 0;
  27328. this.invertV = 0;
  27329. this.animations = new Array();
  27330. this.isPickable = false;
  27331. this._animationStarted = false;
  27332. this._loopAnimation = false;
  27333. this._fromIndex = 0;
  27334. this._toIndex = 0;
  27335. this._delay = 0;
  27336. this._direction = 1;
  27337. this._frameCount = 0;
  27338. this._time = 0;
  27339. this._manager = manager;
  27340. this._manager.sprites.push(this);
  27341. this.position = BABYLON.Vector3.Zero();
  27342. }
  27343. Object.defineProperty(Sprite.prototype, "size", {
  27344. get: function () {
  27345. return this.width;
  27346. },
  27347. set: function (value) {
  27348. this.width = value;
  27349. this.height = value;
  27350. },
  27351. enumerable: true,
  27352. configurable: true
  27353. });
  27354. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  27355. this._fromIndex = from;
  27356. this._toIndex = to;
  27357. this._loopAnimation = loop;
  27358. this._delay = delay;
  27359. this._animationStarted = true;
  27360. this._direction = from < to ? 1 : -1;
  27361. this.cellIndex = from;
  27362. this._time = 0;
  27363. this._onAnimationEnd = onAnimationEnd;
  27364. };
  27365. Sprite.prototype.stopAnimation = function () {
  27366. this._animationStarted = false;
  27367. };
  27368. Sprite.prototype._animate = function (deltaTime) {
  27369. if (!this._animationStarted)
  27370. return;
  27371. this._time += deltaTime;
  27372. if (this._time > this._delay) {
  27373. this._time = this._time % this._delay;
  27374. this.cellIndex += this._direction;
  27375. if (this.cellIndex === this._toIndex) {
  27376. if (this._loopAnimation) {
  27377. this.cellIndex = this._fromIndex;
  27378. }
  27379. else {
  27380. this._animationStarted = false;
  27381. if (this._onAnimationEnd) {
  27382. this._onAnimationEnd();
  27383. }
  27384. if (this.disposeWhenFinishedAnimating) {
  27385. this.dispose();
  27386. }
  27387. }
  27388. }
  27389. }
  27390. };
  27391. Sprite.prototype.dispose = function () {
  27392. for (var i = 0; i < this._manager.sprites.length; i++) {
  27393. if (this._manager.sprites[i] == this) {
  27394. this._manager.sprites.splice(i, 1);
  27395. }
  27396. }
  27397. };
  27398. return Sprite;
  27399. }());
  27400. BABYLON.Sprite = Sprite;
  27401. })(BABYLON || (BABYLON = {}));
  27402. var BABYLON;
  27403. (function (BABYLON) {
  27404. var Layer = (function () {
  27405. function Layer(name, imgUrl, scene, isBackground, color) {
  27406. this.name = name;
  27407. this.scale = new BABYLON.Vector2(1, 1);
  27408. this.offset = new BABYLON.Vector2(0, 0);
  27409. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  27410. this._vertexBuffers = {};
  27411. // Events
  27412. /**
  27413. * An event triggered when the layer is disposed.
  27414. * @type {BABYLON.Observable}
  27415. */
  27416. this.onDisposeObservable = new BABYLON.Observable();
  27417. /**
  27418. * An event triggered before rendering the scene
  27419. * @type {BABYLON.Observable}
  27420. */
  27421. this.onBeforeRenderObservable = new BABYLON.Observable();
  27422. /**
  27423. * An event triggered after rendering the scene
  27424. * @type {BABYLON.Observable}
  27425. */
  27426. this.onAfterRenderObservable = new BABYLON.Observable();
  27427. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  27428. this.isBackground = isBackground === undefined ? true : isBackground;
  27429. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  27430. this._scene = scene;
  27431. this._scene.layers.push(this);
  27432. var engine = scene.getEngine();
  27433. // VBO
  27434. var vertices = [];
  27435. vertices.push(1, 1);
  27436. vertices.push(-1, 1);
  27437. vertices.push(-1, -1);
  27438. vertices.push(1, -1);
  27439. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  27440. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  27441. // Indices
  27442. var indices = [];
  27443. indices.push(0);
  27444. indices.push(1);
  27445. indices.push(2);
  27446. indices.push(0);
  27447. indices.push(2);
  27448. indices.push(3);
  27449. this._indexBuffer = engine.createIndexBuffer(indices);
  27450. // Effects
  27451. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  27452. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  27453. }
  27454. Object.defineProperty(Layer.prototype, "onDispose", {
  27455. set: function (callback) {
  27456. if (this._onDisposeObserver) {
  27457. this.onDisposeObservable.remove(this._onDisposeObserver);
  27458. }
  27459. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  27460. },
  27461. enumerable: true,
  27462. configurable: true
  27463. });
  27464. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  27465. set: function (callback) {
  27466. if (this._onBeforeRenderObserver) {
  27467. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  27468. }
  27469. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  27470. },
  27471. enumerable: true,
  27472. configurable: true
  27473. });
  27474. Object.defineProperty(Layer.prototype, "onAfterRender", {
  27475. set: function (callback) {
  27476. if (this._onAfterRenderObserver) {
  27477. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  27478. }
  27479. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  27480. },
  27481. enumerable: true,
  27482. configurable: true
  27483. });
  27484. Layer.prototype.render = function () {
  27485. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  27486. // Check
  27487. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  27488. return;
  27489. var engine = this._scene.getEngine();
  27490. this.onBeforeRenderObservable.notifyObservers(this);
  27491. // Render
  27492. engine.enableEffect(currentEffect);
  27493. engine.setState(false);
  27494. // Texture
  27495. currentEffect.setTexture("textureSampler", this.texture);
  27496. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  27497. // Color
  27498. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  27499. // Scale / offset
  27500. currentEffect.setVector2("offset", this.offset);
  27501. currentEffect.setVector2("scale", this.scale);
  27502. // VBOs
  27503. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  27504. // Draw order
  27505. if (!this.alphaTest) {
  27506. engine.setAlphaMode(this.alphaBlendingMode);
  27507. engine.draw(true, 0, 6);
  27508. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  27509. }
  27510. else {
  27511. engine.draw(true, 0, 6);
  27512. }
  27513. this.onAfterRenderObservable.notifyObservers(this);
  27514. };
  27515. Layer.prototype.dispose = function () {
  27516. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  27517. if (vertexBuffer) {
  27518. vertexBuffer.dispose();
  27519. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  27520. }
  27521. if (this._indexBuffer) {
  27522. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  27523. this._indexBuffer = null;
  27524. }
  27525. if (this.texture) {
  27526. this.texture.dispose();
  27527. this.texture = null;
  27528. }
  27529. // Remove from scene
  27530. var index = this._scene.layers.indexOf(this);
  27531. this._scene.layers.splice(index, 1);
  27532. // Callback
  27533. this.onDisposeObservable.notifyObservers(this);
  27534. this.onDisposeObservable.clear();
  27535. this.onAfterRenderObservable.clear();
  27536. this.onBeforeRenderObservable.clear();
  27537. };
  27538. return Layer;
  27539. }());
  27540. BABYLON.Layer = Layer;
  27541. })(BABYLON || (BABYLON = {}));
  27542. var BABYLON;
  27543. (function (BABYLON) {
  27544. var Particle = (function () {
  27545. function Particle() {
  27546. this.position = BABYLON.Vector3.Zero();
  27547. this.direction = BABYLON.Vector3.Zero();
  27548. this.color = new BABYLON.Color4(0, 0, 0, 0);
  27549. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  27550. this.lifeTime = 1.0;
  27551. this.age = 0;
  27552. this.size = 0;
  27553. this.angle = 0;
  27554. this.angularSpeed = 0;
  27555. }
  27556. Particle.prototype.copyTo = function (other) {
  27557. other.position.copyFrom(this.position);
  27558. other.direction.copyFrom(this.direction);
  27559. other.color.copyFrom(this.color);
  27560. other.colorStep.copyFrom(this.colorStep);
  27561. other.lifeTime = this.lifeTime;
  27562. other.age = this.age;
  27563. other.size = this.size;
  27564. other.angle = this.angle;
  27565. other.angularSpeed = this.angularSpeed;
  27566. };
  27567. return Particle;
  27568. }());
  27569. BABYLON.Particle = Particle;
  27570. })(BABYLON || (BABYLON = {}));
  27571. var BABYLON;
  27572. (function (BABYLON) {
  27573. var randomNumber = function (min, max) {
  27574. if (min === max) {
  27575. return (min);
  27576. }
  27577. var random = Math.random();
  27578. return ((random * (max - min)) + min);
  27579. };
  27580. var ParticleSystem = (function () {
  27581. function ParticleSystem(name, capacity, scene, customEffect) {
  27582. var _this = this;
  27583. this.name = name;
  27584. // Members
  27585. this.animations = [];
  27586. this.renderingGroupId = 0;
  27587. this.emitter = null;
  27588. this.emitRate = 10;
  27589. this.manualEmitCount = -1;
  27590. this.updateSpeed = 0.01;
  27591. this.targetStopDuration = 0;
  27592. this.disposeOnStop = false;
  27593. this.minEmitPower = 1;
  27594. this.maxEmitPower = 1;
  27595. this.minLifeTime = 1;
  27596. this.maxLifeTime = 1;
  27597. this.minSize = 1;
  27598. this.maxSize = 1;
  27599. this.minAngularSpeed = 0;
  27600. this.maxAngularSpeed = 0;
  27601. this.layerMask = 0x0FFFFFFF;
  27602. /**
  27603. * An event triggered when the system is disposed.
  27604. * @type {BABYLON.Observable}
  27605. */
  27606. this.onDisposeObservable = new BABYLON.Observable();
  27607. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  27608. this.forceDepthWrite = false;
  27609. this.gravity = BABYLON.Vector3.Zero();
  27610. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  27611. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  27612. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  27613. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  27614. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  27615. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  27616. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  27617. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  27618. this.particles = new Array();
  27619. this._stockParticles = new Array();
  27620. this._newPartsExcess = 0;
  27621. this._vertexBuffers = {};
  27622. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  27623. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  27624. this._scaledDirection = BABYLON.Vector3.Zero();
  27625. this._scaledGravity = BABYLON.Vector3.Zero();
  27626. this._currentRenderId = -1;
  27627. this._started = false;
  27628. this._stopped = false;
  27629. this._actualFrame = 0;
  27630. this.id = name;
  27631. this._capacity = capacity;
  27632. this._scene = scene;
  27633. this._customEffect = customEffect;
  27634. scene.particleSystems.push(this);
  27635. var indices = [];
  27636. var index = 0;
  27637. for (var count = 0; count < capacity; count++) {
  27638. indices.push(index);
  27639. indices.push(index + 1);
  27640. indices.push(index + 2);
  27641. indices.push(index);
  27642. indices.push(index + 2);
  27643. indices.push(index + 3);
  27644. index += 4;
  27645. }
  27646. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  27647. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  27648. this._vertexData = new Float32Array(capacity * 11 * 4);
  27649. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 11);
  27650. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  27651. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  27652. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  27653. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  27654. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  27655. this._vertexBuffers["options"] = options;
  27656. // Default behaviors
  27657. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  27658. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  27659. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  27660. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  27661. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  27662. };
  27663. this.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  27664. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  27665. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  27666. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  27667. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  27668. };
  27669. this.updateFunction = function (particles) {
  27670. for (var index = 0; index < particles.length; index++) {
  27671. var particle = particles[index];
  27672. particle.age += _this._scaledUpdateSpeed;
  27673. if (particle.age >= particle.lifeTime) {
  27674. _this.recycleParticle(particle);
  27675. index--;
  27676. continue;
  27677. }
  27678. else {
  27679. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  27680. particle.color.addInPlace(_this._scaledColorStep);
  27681. if (particle.color.a < 0)
  27682. particle.color.a = 0;
  27683. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  27684. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  27685. particle.position.addInPlace(_this._scaledDirection);
  27686. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  27687. particle.direction.addInPlace(_this._scaledGravity);
  27688. }
  27689. }
  27690. };
  27691. }
  27692. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  27693. set: function (callback) {
  27694. if (this._onDisposeObserver) {
  27695. this.onDisposeObservable.remove(this._onDisposeObserver);
  27696. }
  27697. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  27698. },
  27699. enumerable: true,
  27700. configurable: true
  27701. });
  27702. ParticleSystem.prototype.recycleParticle = function (particle) {
  27703. var lastParticle = this.particles.pop();
  27704. if (lastParticle !== particle) {
  27705. lastParticle.copyTo(particle);
  27706. this._stockParticles.push(lastParticle);
  27707. }
  27708. };
  27709. ParticleSystem.prototype.getCapacity = function () {
  27710. return this._capacity;
  27711. };
  27712. ParticleSystem.prototype.isAlive = function () {
  27713. return this._alive;
  27714. };
  27715. ParticleSystem.prototype.isStarted = function () {
  27716. return this._started;
  27717. };
  27718. ParticleSystem.prototype.start = function () {
  27719. this._started = true;
  27720. this._stopped = false;
  27721. this._actualFrame = 0;
  27722. };
  27723. ParticleSystem.prototype.stop = function () {
  27724. this._stopped = true;
  27725. };
  27726. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  27727. var offset = index * 11;
  27728. this._vertexData[offset] = particle.position.x;
  27729. this._vertexData[offset + 1] = particle.position.y;
  27730. this._vertexData[offset + 2] = particle.position.z;
  27731. this._vertexData[offset + 3] = particle.color.r;
  27732. this._vertexData[offset + 4] = particle.color.g;
  27733. this._vertexData[offset + 5] = particle.color.b;
  27734. this._vertexData[offset + 6] = particle.color.a;
  27735. this._vertexData[offset + 7] = particle.angle;
  27736. this._vertexData[offset + 8] = particle.size;
  27737. this._vertexData[offset + 9] = offsetX;
  27738. this._vertexData[offset + 10] = offsetY;
  27739. };
  27740. ParticleSystem.prototype._update = function (newParticles) {
  27741. // Update current
  27742. this._alive = this.particles.length > 0;
  27743. this.updateFunction(this.particles);
  27744. // Add new ones
  27745. var worldMatrix;
  27746. if (this.emitter.position) {
  27747. worldMatrix = this.emitter.getWorldMatrix();
  27748. }
  27749. else {
  27750. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  27751. }
  27752. var particle;
  27753. for (var index = 0; index < newParticles; index++) {
  27754. if (this.particles.length === this._capacity) {
  27755. break;
  27756. }
  27757. if (this._stockParticles.length !== 0) {
  27758. particle = this._stockParticles.pop();
  27759. particle.age = 0;
  27760. }
  27761. else {
  27762. particle = new BABYLON.Particle();
  27763. }
  27764. this.particles.push(particle);
  27765. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  27766. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  27767. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  27768. particle.size = randomNumber(this.minSize, this.maxSize);
  27769. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  27770. this.startPositionFunction(worldMatrix, particle.position, particle);
  27771. var step = randomNumber(0, 1.0);
  27772. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  27773. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  27774. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  27775. }
  27776. };
  27777. ParticleSystem.prototype._getEffect = function () {
  27778. if (this._customEffect) {
  27779. return this._customEffect;
  27780. }
  27781. ;
  27782. var defines = [];
  27783. if (this._scene.clipPlane) {
  27784. defines.push("#define CLIPPLANE");
  27785. }
  27786. // Effect
  27787. var join = defines.join("\n");
  27788. if (this._cachedDefines !== join) {
  27789. this._cachedDefines = join;
  27790. this._effect = this._scene.getEngine().createEffect("particles", [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  27791. }
  27792. return this._effect;
  27793. };
  27794. ParticleSystem.prototype.animate = function () {
  27795. if (!this._started)
  27796. return;
  27797. var effect = this._getEffect();
  27798. // Check
  27799. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  27800. return;
  27801. if (this._currentRenderId === this._scene.getRenderId()) {
  27802. return;
  27803. }
  27804. this._currentRenderId = this._scene.getRenderId();
  27805. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  27806. // determine the number of particles we need to create
  27807. var newParticles;
  27808. if (this.manualEmitCount > -1) {
  27809. newParticles = this.manualEmitCount;
  27810. this._newPartsExcess = 0;
  27811. this.manualEmitCount = 0;
  27812. }
  27813. else {
  27814. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  27815. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  27816. }
  27817. if (this._newPartsExcess > 1.0) {
  27818. newParticles += this._newPartsExcess >> 0;
  27819. this._newPartsExcess -= this._newPartsExcess >> 0;
  27820. }
  27821. this._alive = false;
  27822. if (!this._stopped) {
  27823. this._actualFrame += this._scaledUpdateSpeed;
  27824. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  27825. this.stop();
  27826. }
  27827. else {
  27828. newParticles = 0;
  27829. }
  27830. this._update(newParticles);
  27831. // Stopped?
  27832. if (this._stopped) {
  27833. if (!this._alive) {
  27834. this._started = false;
  27835. if (this.disposeOnStop) {
  27836. this._scene._toBeDisposed.push(this);
  27837. }
  27838. }
  27839. }
  27840. // Update VBO
  27841. var offset = 0;
  27842. for (var index = 0; index < this.particles.length; index++) {
  27843. var particle = this.particles[index];
  27844. this._appendParticleVertex(offset++, particle, 0, 0);
  27845. this._appendParticleVertex(offset++, particle, 1, 0);
  27846. this._appendParticleVertex(offset++, particle, 1, 1);
  27847. this._appendParticleVertex(offset++, particle, 0, 1);
  27848. }
  27849. this._vertexBuffer.update(this._vertexData);
  27850. };
  27851. ParticleSystem.prototype.render = function () {
  27852. var effect = this._getEffect();
  27853. // Check
  27854. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  27855. return 0;
  27856. var engine = this._scene.getEngine();
  27857. // Render
  27858. engine.enableEffect(effect);
  27859. engine.setState(false);
  27860. var viewMatrix = this._scene.getViewMatrix();
  27861. effect.setTexture("diffuseSampler", this.particleTexture);
  27862. effect.setMatrix("view", viewMatrix);
  27863. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  27864. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  27865. if (this._scene.clipPlane) {
  27866. var clipPlane = this._scene.clipPlane;
  27867. var invView = viewMatrix.clone();
  27868. invView.invert();
  27869. effect.setMatrix("invView", invView);
  27870. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  27871. }
  27872. // VBOs
  27873. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  27874. // Draw order
  27875. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  27876. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  27877. }
  27878. else {
  27879. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  27880. }
  27881. if (this.forceDepthWrite) {
  27882. engine.setDepthWrite(true);
  27883. }
  27884. engine.draw(true, 0, this.particles.length * 6);
  27885. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  27886. return this.particles.length;
  27887. };
  27888. ParticleSystem.prototype.dispose = function () {
  27889. if (this._vertexBuffer) {
  27890. this._vertexBuffer.dispose();
  27891. this._vertexBuffer = null;
  27892. }
  27893. if (this._indexBuffer) {
  27894. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  27895. this._indexBuffer = null;
  27896. }
  27897. if (this.particleTexture) {
  27898. this.particleTexture.dispose();
  27899. this.particleTexture = null;
  27900. }
  27901. // Remove from scene
  27902. var index = this._scene.particleSystems.indexOf(this);
  27903. this._scene.particleSystems.splice(index, 1);
  27904. // Callback
  27905. this.onDisposeObservable.notifyObservers(this);
  27906. this.onDisposeObservable.clear();
  27907. };
  27908. // Clone
  27909. ParticleSystem.prototype.clone = function (name, newEmitter) {
  27910. var result = new ParticleSystem(name, this._capacity, this._scene);
  27911. BABYLON.Tools.DeepCopy(this, result, ["particles"]);
  27912. if (newEmitter === undefined) {
  27913. newEmitter = this.emitter;
  27914. }
  27915. result.emitter = newEmitter;
  27916. if (this.particleTexture) {
  27917. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  27918. }
  27919. result.start();
  27920. return result;
  27921. };
  27922. ParticleSystem.prototype.serialize = function () {
  27923. var serializationObject = {};
  27924. serializationObject.name = this.name;
  27925. serializationObject.id = this.id;
  27926. // Emitter
  27927. if (this.emitter.position) {
  27928. serializationObject.emitterId = this.emitter.id;
  27929. }
  27930. else {
  27931. serializationObject.emitter = this.emitter.asArray();
  27932. }
  27933. serializationObject.capacity = this.getCapacity();
  27934. if (this.particleTexture) {
  27935. serializationObject.textureName = this.particleTexture.name;
  27936. }
  27937. // Animations
  27938. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  27939. // Particle system
  27940. serializationObject.minAngularSpeed = this.minAngularSpeed;
  27941. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  27942. serializationObject.minSize = this.minSize;
  27943. serializationObject.maxSize = this.maxSize;
  27944. serializationObject.minEmitPower = this.minEmitPower;
  27945. serializationObject.maxEmitPower = this.maxEmitPower;
  27946. serializationObject.minLifeTime = this.minLifeTime;
  27947. serializationObject.maxLifeTime = this.maxLifeTime;
  27948. serializationObject.emitRate = this.emitRate;
  27949. serializationObject.minEmitBox = this.minEmitBox.asArray();
  27950. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  27951. serializationObject.gravity = this.gravity.asArray();
  27952. serializationObject.direction1 = this.direction1.asArray();
  27953. serializationObject.direction2 = this.direction2.asArray();
  27954. serializationObject.color1 = this.color1.asArray();
  27955. serializationObject.color2 = this.color2.asArray();
  27956. serializationObject.colorDead = this.colorDead.asArray();
  27957. serializationObject.updateSpeed = this.updateSpeed;
  27958. serializationObject.targetStopDuration = this.targetStopDuration;
  27959. serializationObject.textureMask = this.textureMask.asArray();
  27960. serializationObject.blendMode = this.blendMode;
  27961. return serializationObject;
  27962. };
  27963. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  27964. var name = parsedParticleSystem.name;
  27965. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene);
  27966. if (parsedParticleSystem.id) {
  27967. particleSystem.id = parsedParticleSystem.id;
  27968. }
  27969. // Texture
  27970. if (parsedParticleSystem.textureName) {
  27971. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  27972. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  27973. }
  27974. // Emitter
  27975. if (parsedParticleSystem.emitterId) {
  27976. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  27977. }
  27978. else {
  27979. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  27980. }
  27981. // Animations
  27982. if (parsedParticleSystem.animations) {
  27983. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  27984. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  27985. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  27986. }
  27987. }
  27988. if (parsedParticleSystem.autoAnimate) {
  27989. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  27990. }
  27991. // Particle system
  27992. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  27993. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  27994. particleSystem.minSize = parsedParticleSystem.minSize;
  27995. particleSystem.maxSize = parsedParticleSystem.maxSize;
  27996. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  27997. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  27998. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  27999. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  28000. particleSystem.emitRate = parsedParticleSystem.emitRate;
  28001. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  28002. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  28003. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  28004. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  28005. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  28006. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  28007. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  28008. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  28009. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  28010. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  28011. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  28012. particleSystem.blendMode = parsedParticleSystem.blendMode;
  28013. if (!parsedParticleSystem.preventAutoStart) {
  28014. particleSystem.start();
  28015. }
  28016. return particleSystem;
  28017. };
  28018. // Statics
  28019. ParticleSystem.BLENDMODE_ONEONE = 0;
  28020. ParticleSystem.BLENDMODE_STANDARD = 1;
  28021. return ParticleSystem;
  28022. }());
  28023. BABYLON.ParticleSystem = ParticleSystem;
  28024. })(BABYLON || (BABYLON = {}));
  28025. var BABYLON;
  28026. (function (BABYLON) {
  28027. var AnimationRange = (function () {
  28028. function AnimationRange(name, from, to) {
  28029. this.name = name;
  28030. this.from = from;
  28031. this.to = to;
  28032. }
  28033. AnimationRange.prototype.clone = function () {
  28034. return new AnimationRange(this.name, this.from, this.to);
  28035. };
  28036. return AnimationRange;
  28037. }());
  28038. BABYLON.AnimationRange = AnimationRange;
  28039. /**
  28040. * Composed of a frame, and an action function
  28041. */
  28042. var AnimationEvent = (function () {
  28043. function AnimationEvent(frame, action, onlyOnce) {
  28044. this.frame = frame;
  28045. this.action = action;
  28046. this.onlyOnce = onlyOnce;
  28047. this.isDone = false;
  28048. }
  28049. return AnimationEvent;
  28050. }());
  28051. BABYLON.AnimationEvent = AnimationEvent;
  28052. var PathCursor = (function () {
  28053. function PathCursor(path) {
  28054. this.path = path;
  28055. this._onchange = new Array();
  28056. this.value = 0;
  28057. this.animations = new Array();
  28058. }
  28059. PathCursor.prototype.getPoint = function () {
  28060. var point = this.path.getPointAtLengthPosition(this.value);
  28061. return new BABYLON.Vector3(point.x, 0, point.y);
  28062. };
  28063. PathCursor.prototype.moveAhead = function (step) {
  28064. if (step === void 0) { step = 0.002; }
  28065. this.move(step);
  28066. return this;
  28067. };
  28068. PathCursor.prototype.moveBack = function (step) {
  28069. if (step === void 0) { step = 0.002; }
  28070. this.move(-step);
  28071. return this;
  28072. };
  28073. PathCursor.prototype.move = function (step) {
  28074. if (Math.abs(step) > 1) {
  28075. throw "step size should be less than 1.";
  28076. }
  28077. this.value += step;
  28078. this.ensureLimits();
  28079. this.raiseOnChange();
  28080. return this;
  28081. };
  28082. PathCursor.prototype.ensureLimits = function () {
  28083. while (this.value > 1) {
  28084. this.value -= 1;
  28085. }
  28086. while (this.value < 0) {
  28087. this.value += 1;
  28088. }
  28089. return this;
  28090. };
  28091. // used by animation engine
  28092. PathCursor.prototype.markAsDirty = function (propertyName) {
  28093. this.ensureLimits();
  28094. this.raiseOnChange();
  28095. return this;
  28096. };
  28097. PathCursor.prototype.raiseOnChange = function () {
  28098. var _this = this;
  28099. this._onchange.forEach(function (f) { return f(_this); });
  28100. return this;
  28101. };
  28102. PathCursor.prototype.onchange = function (f) {
  28103. this._onchange.push(f);
  28104. return this;
  28105. };
  28106. return PathCursor;
  28107. }());
  28108. BABYLON.PathCursor = PathCursor;
  28109. var Animation = (function () {
  28110. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  28111. this.name = name;
  28112. this.targetProperty = targetProperty;
  28113. this.framePerSecond = framePerSecond;
  28114. this.dataType = dataType;
  28115. this.loopMode = loopMode;
  28116. this.enableBlending = enableBlending;
  28117. this._offsetsCache = {};
  28118. this._highLimitsCache = {};
  28119. this._stopped = false;
  28120. this._blendingFactor = 0;
  28121. // The set of event that will be linked to this animation
  28122. this._events = new Array();
  28123. this.allowMatricesInterpolation = false;
  28124. this.blendingSpeed = 0.01;
  28125. this._ranges = {};
  28126. this.targetPropertyPath = targetProperty.split(".");
  28127. this.dataType = dataType;
  28128. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  28129. }
  28130. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  28131. var dataType = undefined;
  28132. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  28133. dataType = Animation.ANIMATIONTYPE_FLOAT;
  28134. }
  28135. else if (from instanceof BABYLON.Quaternion) {
  28136. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  28137. }
  28138. else if (from instanceof BABYLON.Vector3) {
  28139. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  28140. }
  28141. else if (from instanceof BABYLON.Vector2) {
  28142. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  28143. }
  28144. else if (from instanceof BABYLON.Color3) {
  28145. dataType = Animation.ANIMATIONTYPE_COLOR3;
  28146. }
  28147. else if (from instanceof BABYLON.Size) {
  28148. dataType = Animation.ANIMATIONTYPE_SIZE;
  28149. }
  28150. if (dataType == undefined) {
  28151. return null;
  28152. }
  28153. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  28154. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  28155. animation.setKeys(keys);
  28156. if (easingFunction !== undefined) {
  28157. animation.setEasingFunction(easingFunction);
  28158. }
  28159. return animation;
  28160. };
  28161. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  28162. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  28163. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  28164. };
  28165. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  28166. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  28167. node.animations.push(animation);
  28168. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  28169. };
  28170. // Methods
  28171. /**
  28172. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  28173. */
  28174. Animation.prototype.toString = function (fullDetails) {
  28175. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  28176. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  28177. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  28178. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  28179. if (fullDetails) {
  28180. ret += ", Ranges: {";
  28181. var first = true;
  28182. for (var name in this._ranges) {
  28183. if (first) {
  28184. ret += ", ";
  28185. first = false;
  28186. }
  28187. ret += name;
  28188. }
  28189. ret += "}";
  28190. }
  28191. return ret;
  28192. };
  28193. /**
  28194. * Add an event to this animation.
  28195. */
  28196. Animation.prototype.addEvent = function (event) {
  28197. this._events.push(event);
  28198. };
  28199. /**
  28200. * Remove all events found at the given frame
  28201. * @param frame
  28202. */
  28203. Animation.prototype.removeEvents = function (frame) {
  28204. for (var index = 0; index < this._events.length; index++) {
  28205. if (this._events[index].frame === frame) {
  28206. this._events.splice(index, 1);
  28207. index--;
  28208. }
  28209. }
  28210. };
  28211. Animation.prototype.createRange = function (name, from, to) {
  28212. // check name not already in use; could happen for bones after serialized
  28213. if (!this._ranges[name]) {
  28214. this._ranges[name] = new AnimationRange(name, from, to);
  28215. }
  28216. };
  28217. Animation.prototype.deleteRange = function (name, deleteFrames) {
  28218. if (deleteFrames === void 0) { deleteFrames = true; }
  28219. if (this._ranges[name]) {
  28220. if (deleteFrames) {
  28221. var from = this._ranges[name].from;
  28222. var to = this._ranges[name].to;
  28223. // this loop MUST go high to low for multiple splices to work
  28224. for (var key = this._keys.length - 1; key >= 0; key--) {
  28225. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  28226. this._keys.splice(key, 1);
  28227. }
  28228. }
  28229. }
  28230. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  28231. }
  28232. };
  28233. Animation.prototype.getRange = function (name) {
  28234. return this._ranges[name];
  28235. };
  28236. Animation.prototype.reset = function () {
  28237. this._offsetsCache = {};
  28238. this._highLimitsCache = {};
  28239. this.currentFrame = 0;
  28240. this._blendingFactor = 0;
  28241. this._originalBlendValue = null;
  28242. };
  28243. Animation.prototype.isStopped = function () {
  28244. return this._stopped;
  28245. };
  28246. Animation.prototype.getKeys = function () {
  28247. return this._keys;
  28248. };
  28249. Animation.prototype.getHighestFrame = function () {
  28250. var ret = 0;
  28251. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  28252. if (ret < this._keys[key].frame) {
  28253. ret = this._keys[key].frame;
  28254. }
  28255. }
  28256. return ret;
  28257. };
  28258. Animation.prototype.getEasingFunction = function () {
  28259. return this._easingFunction;
  28260. };
  28261. Animation.prototype.setEasingFunction = function (easingFunction) {
  28262. this._easingFunction = easingFunction;
  28263. };
  28264. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  28265. return startValue + (endValue - startValue) * gradient;
  28266. };
  28267. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  28268. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  28269. };
  28270. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  28271. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  28272. };
  28273. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  28274. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  28275. };
  28276. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  28277. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  28278. };
  28279. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  28280. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  28281. };
  28282. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  28283. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  28284. };
  28285. Animation.prototype.clone = function () {
  28286. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  28287. if (this._keys) {
  28288. clone.setKeys(this._keys);
  28289. }
  28290. if (this._ranges) {
  28291. clone._ranges = {};
  28292. for (var name in this._ranges) {
  28293. clone._ranges[name] = this._ranges[name].clone();
  28294. }
  28295. }
  28296. return clone;
  28297. };
  28298. Animation.prototype.setKeys = function (values) {
  28299. this._keys = values.slice(0);
  28300. this._offsetsCache = {};
  28301. this._highLimitsCache = {};
  28302. };
  28303. Animation.prototype._getKeyValue = function (value) {
  28304. if (typeof value === "function") {
  28305. return value();
  28306. }
  28307. return value;
  28308. };
  28309. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  28310. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  28311. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  28312. }
  28313. this.currentFrame = currentFrame;
  28314. // Try to get a hash to find the right key
  28315. 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));
  28316. if (this._keys[startKey].frame >= currentFrame) {
  28317. while (startKey - 1 >= 0 && this._keys[startKey].frame >= currentFrame) {
  28318. startKey--;
  28319. }
  28320. }
  28321. for (var key = startKey; key < this._keys.length; key++) {
  28322. if (this._keys[key + 1].frame >= currentFrame) {
  28323. var startValue = this._getKeyValue(this._keys[key].value);
  28324. var endValue = this._getKeyValue(this._keys[key + 1].value);
  28325. // gradient : percent of currentFrame between the frame inf and the frame sup
  28326. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  28327. // check for easingFunction and correction of gradient
  28328. if (this._easingFunction != null) {
  28329. gradient = this._easingFunction.ease(gradient);
  28330. }
  28331. switch (this.dataType) {
  28332. // Float
  28333. case Animation.ANIMATIONTYPE_FLOAT:
  28334. switch (loopMode) {
  28335. case Animation.ANIMATIONLOOPMODE_CYCLE:
  28336. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  28337. return this.floatInterpolateFunction(startValue, endValue, gradient);
  28338. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  28339. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  28340. }
  28341. break;
  28342. // Quaternion
  28343. case Animation.ANIMATIONTYPE_QUATERNION:
  28344. var quaternion = null;
  28345. switch (loopMode) {
  28346. case Animation.ANIMATIONLOOPMODE_CYCLE:
  28347. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  28348. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  28349. break;
  28350. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  28351. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  28352. break;
  28353. }
  28354. return quaternion;
  28355. // Vector3
  28356. case Animation.ANIMATIONTYPE_VECTOR3:
  28357. switch (loopMode) {
  28358. case Animation.ANIMATIONLOOPMODE_CYCLE:
  28359. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  28360. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  28361. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  28362. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  28363. }
  28364. // Vector2
  28365. case Animation.ANIMATIONTYPE_VECTOR2:
  28366. switch (loopMode) {
  28367. case Animation.ANIMATIONLOOPMODE_CYCLE:
  28368. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  28369. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  28370. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  28371. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  28372. }
  28373. // Size
  28374. case Animation.ANIMATIONTYPE_SIZE:
  28375. switch (loopMode) {
  28376. case Animation.ANIMATIONLOOPMODE_CYCLE:
  28377. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  28378. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  28379. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  28380. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  28381. }
  28382. // Color3
  28383. case Animation.ANIMATIONTYPE_COLOR3:
  28384. switch (loopMode) {
  28385. case Animation.ANIMATIONLOOPMODE_CYCLE:
  28386. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  28387. return this.color3InterpolateFunction(startValue, endValue, gradient);
  28388. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  28389. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  28390. }
  28391. // Matrix
  28392. case Animation.ANIMATIONTYPE_MATRIX:
  28393. switch (loopMode) {
  28394. case Animation.ANIMATIONLOOPMODE_CYCLE:
  28395. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  28396. if (this.allowMatricesInterpolation) {
  28397. return this.matrixInterpolateFunction(startValue, endValue, gradient);
  28398. }
  28399. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  28400. return startValue;
  28401. }
  28402. default:
  28403. break;
  28404. }
  28405. break;
  28406. }
  28407. }
  28408. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  28409. };
  28410. Animation.prototype.setValue = function (currentValue, blend) {
  28411. if (blend === void 0) { blend = false; }
  28412. // Set value
  28413. var path;
  28414. var destination;
  28415. if (this.targetPropertyPath.length > 1) {
  28416. var property = this._target[this.targetPropertyPath[0]];
  28417. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  28418. property = property[this.targetPropertyPath[index]];
  28419. }
  28420. path = this.targetPropertyPath[this.targetPropertyPath.length - 1];
  28421. destination = property;
  28422. }
  28423. else {
  28424. path = this.targetPropertyPath[0];
  28425. destination = this._target;
  28426. }
  28427. // Blending
  28428. if (this.enableBlending && this._blendingFactor <= 1.0) {
  28429. if (!this._originalBlendValue) {
  28430. if (destination[path].clone) {
  28431. this._originalBlendValue = destination[path].clone();
  28432. }
  28433. else {
  28434. this._originalBlendValue = destination[path];
  28435. }
  28436. }
  28437. if (this._originalBlendValue.prototype) {
  28438. if (this._originalBlendValue.prototype.Lerp) {
  28439. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  28440. }
  28441. else {
  28442. destination[path] = currentValue;
  28443. }
  28444. }
  28445. else if (this._originalBlendValue.m) {
  28446. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  28447. }
  28448. else {
  28449. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  28450. }
  28451. this._blendingFactor += this.blendingSpeed;
  28452. }
  28453. else {
  28454. destination[path] = currentValue;
  28455. }
  28456. if (this._target.markAsDirty) {
  28457. this._target.markAsDirty(this.targetProperty);
  28458. }
  28459. };
  28460. Animation.prototype.goToFrame = function (frame) {
  28461. if (frame < this._keys[0].frame) {
  28462. frame = this._keys[0].frame;
  28463. }
  28464. else if (frame > this._keys[this._keys.length - 1].frame) {
  28465. frame = this._keys[this._keys.length - 1].frame;
  28466. }
  28467. var currentValue = this._interpolate(frame, 0, this.loopMode);
  28468. this.setValue(currentValue);
  28469. };
  28470. Animation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  28471. if (blend === void 0) { blend = false; }
  28472. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  28473. this._stopped = true;
  28474. return false;
  28475. }
  28476. var returnValue = true;
  28477. // Adding a start key at frame 0 if missing
  28478. if (this._keys[0].frame !== 0) {
  28479. var newKey = { frame: 0, value: this._keys[0].value };
  28480. this._keys.splice(0, 0, newKey);
  28481. }
  28482. // Check limits
  28483. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  28484. from = this._keys[0].frame;
  28485. }
  28486. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  28487. to = this._keys[this._keys.length - 1].frame;
  28488. }
  28489. // Compute ratio
  28490. var range = to - from;
  28491. var offsetValue;
  28492. // ratio represents the frame delta between from and to
  28493. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  28494. var highLimitValue = 0;
  28495. if (ratio > range && !loop) {
  28496. returnValue = false;
  28497. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  28498. }
  28499. else {
  28500. // Get max value if required
  28501. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  28502. var keyOffset = to.toString() + from.toString();
  28503. if (!this._offsetsCache[keyOffset]) {
  28504. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  28505. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  28506. switch (this.dataType) {
  28507. // Float
  28508. case Animation.ANIMATIONTYPE_FLOAT:
  28509. this._offsetsCache[keyOffset] = toValue - fromValue;
  28510. break;
  28511. // Quaternion
  28512. case Animation.ANIMATIONTYPE_QUATERNION:
  28513. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  28514. break;
  28515. // Vector3
  28516. case Animation.ANIMATIONTYPE_VECTOR3:
  28517. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  28518. // Vector2
  28519. case Animation.ANIMATIONTYPE_VECTOR2:
  28520. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  28521. // Size
  28522. case Animation.ANIMATIONTYPE_SIZE:
  28523. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  28524. // Color3
  28525. case Animation.ANIMATIONTYPE_COLOR3:
  28526. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  28527. default:
  28528. break;
  28529. }
  28530. this._highLimitsCache[keyOffset] = toValue;
  28531. }
  28532. highLimitValue = this._highLimitsCache[keyOffset];
  28533. offsetValue = this._offsetsCache[keyOffset];
  28534. }
  28535. }
  28536. if (offsetValue === undefined) {
  28537. switch (this.dataType) {
  28538. // Float
  28539. case Animation.ANIMATIONTYPE_FLOAT:
  28540. offsetValue = 0;
  28541. break;
  28542. // Quaternion
  28543. case Animation.ANIMATIONTYPE_QUATERNION:
  28544. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  28545. break;
  28546. // Vector3
  28547. case Animation.ANIMATIONTYPE_VECTOR3:
  28548. offsetValue = BABYLON.Vector3.Zero();
  28549. break;
  28550. // Vector2
  28551. case Animation.ANIMATIONTYPE_VECTOR2:
  28552. offsetValue = BABYLON.Vector2.Zero();
  28553. break;
  28554. // Size
  28555. case Animation.ANIMATIONTYPE_SIZE:
  28556. offsetValue = BABYLON.Size.Zero();
  28557. break;
  28558. // Color3
  28559. case Animation.ANIMATIONTYPE_COLOR3:
  28560. offsetValue = BABYLON.Color3.Black();
  28561. }
  28562. }
  28563. // Compute value
  28564. var repeatCount = (ratio / range) >> 0;
  28565. var currentFrame = returnValue ? from + ratio % range : to;
  28566. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  28567. // Set value
  28568. this.setValue(currentValue);
  28569. // Check events
  28570. for (var index = 0; index < this._events.length; index++) {
  28571. if (currentFrame >= this._events[index].frame) {
  28572. var event = this._events[index];
  28573. if (!event.isDone) {
  28574. // If event should be done only once, remove it.
  28575. if (event.onlyOnce) {
  28576. this._events.splice(index, 1);
  28577. index--;
  28578. }
  28579. event.isDone = true;
  28580. event.action();
  28581. } // Don't do anything if the event has already be done.
  28582. }
  28583. else if (this._events[index].isDone && !this._events[index].onlyOnce) {
  28584. // reset event, the animation is looping
  28585. this._events[index].isDone = false;
  28586. }
  28587. }
  28588. if (!returnValue) {
  28589. this._stopped = true;
  28590. }
  28591. return returnValue;
  28592. };
  28593. Animation.prototype.serialize = function () {
  28594. var serializationObject = {};
  28595. serializationObject.name = this.name;
  28596. serializationObject.property = this.targetProperty;
  28597. serializationObject.framePerSecond = this.framePerSecond;
  28598. serializationObject.dataType = this.dataType;
  28599. serializationObject.loopBehavior = this.loopMode;
  28600. var dataType = this.dataType;
  28601. serializationObject.keys = [];
  28602. var keys = this.getKeys();
  28603. for (var index = 0; index < keys.length; index++) {
  28604. var animationKey = keys[index];
  28605. var key = {};
  28606. key.frame = animationKey.frame;
  28607. switch (dataType) {
  28608. case Animation.ANIMATIONTYPE_FLOAT:
  28609. key.values = [animationKey.value];
  28610. break;
  28611. case Animation.ANIMATIONTYPE_QUATERNION:
  28612. case Animation.ANIMATIONTYPE_MATRIX:
  28613. case Animation.ANIMATIONTYPE_VECTOR3:
  28614. case Animation.ANIMATIONTYPE_COLOR3:
  28615. key.values = animationKey.value.asArray();
  28616. break;
  28617. }
  28618. serializationObject.keys.push(key);
  28619. }
  28620. serializationObject.ranges = [];
  28621. for (var name in this._ranges) {
  28622. var range = {};
  28623. range.name = name;
  28624. range.from = this._ranges[name].from;
  28625. range.to = this._ranges[name].to;
  28626. serializationObject.ranges.push(range);
  28627. }
  28628. return serializationObject;
  28629. };
  28630. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  28631. get: function () {
  28632. return Animation._ANIMATIONTYPE_FLOAT;
  28633. },
  28634. enumerable: true,
  28635. configurable: true
  28636. });
  28637. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  28638. get: function () {
  28639. return Animation._ANIMATIONTYPE_VECTOR3;
  28640. },
  28641. enumerable: true,
  28642. configurable: true
  28643. });
  28644. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  28645. get: function () {
  28646. return Animation._ANIMATIONTYPE_VECTOR2;
  28647. },
  28648. enumerable: true,
  28649. configurable: true
  28650. });
  28651. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  28652. get: function () {
  28653. return Animation._ANIMATIONTYPE_SIZE;
  28654. },
  28655. enumerable: true,
  28656. configurable: true
  28657. });
  28658. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  28659. get: function () {
  28660. return Animation._ANIMATIONTYPE_QUATERNION;
  28661. },
  28662. enumerable: true,
  28663. configurable: true
  28664. });
  28665. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  28666. get: function () {
  28667. return Animation._ANIMATIONTYPE_MATRIX;
  28668. },
  28669. enumerable: true,
  28670. configurable: true
  28671. });
  28672. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  28673. get: function () {
  28674. return Animation._ANIMATIONTYPE_COLOR3;
  28675. },
  28676. enumerable: true,
  28677. configurable: true
  28678. });
  28679. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  28680. get: function () {
  28681. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  28682. },
  28683. enumerable: true,
  28684. configurable: true
  28685. });
  28686. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  28687. get: function () {
  28688. return Animation._ANIMATIONLOOPMODE_CYCLE;
  28689. },
  28690. enumerable: true,
  28691. configurable: true
  28692. });
  28693. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  28694. get: function () {
  28695. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  28696. },
  28697. enumerable: true,
  28698. configurable: true
  28699. });
  28700. Animation.Parse = function (parsedAnimation) {
  28701. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  28702. var dataType = parsedAnimation.dataType;
  28703. var keys = [];
  28704. var data;
  28705. var index;
  28706. for (index = 0; index < parsedAnimation.keys.length; index++) {
  28707. var key = parsedAnimation.keys[index];
  28708. switch (dataType) {
  28709. case Animation.ANIMATIONTYPE_FLOAT:
  28710. data = key.values[0];
  28711. break;
  28712. case Animation.ANIMATIONTYPE_QUATERNION:
  28713. data = BABYLON.Quaternion.FromArray(key.values);
  28714. break;
  28715. case Animation.ANIMATIONTYPE_MATRIX:
  28716. data = BABYLON.Matrix.FromArray(key.values);
  28717. break;
  28718. case Animation.ANIMATIONTYPE_COLOR3:
  28719. data = BABYLON.Color3.FromArray(key.values);
  28720. break;
  28721. case Animation.ANIMATIONTYPE_VECTOR3:
  28722. default:
  28723. data = BABYLON.Vector3.FromArray(key.values);
  28724. break;
  28725. }
  28726. keys.push({
  28727. frame: key.frame,
  28728. value: data
  28729. });
  28730. }
  28731. animation.setKeys(keys);
  28732. if (parsedAnimation.ranges) {
  28733. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  28734. data = parsedAnimation.ranges[index];
  28735. animation.createRange(data.name, data.from, data.to);
  28736. }
  28737. }
  28738. return animation;
  28739. };
  28740. Animation.AppendSerializedAnimations = function (source, destination) {
  28741. if (source.animations) {
  28742. destination.animations = [];
  28743. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  28744. var animation = source.animations[animationIndex];
  28745. destination.animations.push(animation.serialize());
  28746. }
  28747. }
  28748. };
  28749. // Statics
  28750. Animation._ANIMATIONTYPE_FLOAT = 0;
  28751. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  28752. Animation._ANIMATIONTYPE_QUATERNION = 2;
  28753. Animation._ANIMATIONTYPE_MATRIX = 3;
  28754. Animation._ANIMATIONTYPE_COLOR3 = 4;
  28755. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  28756. Animation._ANIMATIONTYPE_SIZE = 6;
  28757. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  28758. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  28759. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  28760. return Animation;
  28761. }());
  28762. BABYLON.Animation = Animation;
  28763. })(BABYLON || (BABYLON = {}));
  28764. var BABYLON;
  28765. (function (BABYLON) {
  28766. var Animatable = (function () {
  28767. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  28768. if (fromFrame === void 0) { fromFrame = 0; }
  28769. if (toFrame === void 0) { toFrame = 100; }
  28770. if (loopAnimation === void 0) { loopAnimation = false; }
  28771. if (speedRatio === void 0) { speedRatio = 1.0; }
  28772. this.target = target;
  28773. this.fromFrame = fromFrame;
  28774. this.toFrame = toFrame;
  28775. this.loopAnimation = loopAnimation;
  28776. this.speedRatio = speedRatio;
  28777. this.onAnimationEnd = onAnimationEnd;
  28778. this._animations = new Array();
  28779. this._paused = false;
  28780. this.animationStarted = false;
  28781. if (animations) {
  28782. this.appendAnimations(target, animations);
  28783. }
  28784. this._scene = scene;
  28785. scene._activeAnimatables.push(this);
  28786. }
  28787. // Methods
  28788. Animatable.prototype.getAnimations = function () {
  28789. return this._animations;
  28790. };
  28791. Animatable.prototype.appendAnimations = function (target, animations) {
  28792. for (var index = 0; index < animations.length; index++) {
  28793. var animation = animations[index];
  28794. animation._target = target;
  28795. this._animations.push(animation);
  28796. }
  28797. };
  28798. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  28799. var animations = this._animations;
  28800. for (var index = 0; index < animations.length; index++) {
  28801. if (animations[index].targetProperty === property) {
  28802. return animations[index];
  28803. }
  28804. }
  28805. return null;
  28806. };
  28807. Animatable.prototype.reset = function () {
  28808. var animations = this._animations;
  28809. for (var index = 0; index < animations.length; index++) {
  28810. animations[index].reset();
  28811. }
  28812. this._localDelayOffset = null;
  28813. this._pausedDelay = null;
  28814. };
  28815. Animatable.prototype.enableBlending = function (blendingSpeed) {
  28816. var animations = this._animations;
  28817. for (var index = 0; index < animations.length; index++) {
  28818. animations[index].enableBlending = true;
  28819. animations[index].blendingSpeed = blendingSpeed;
  28820. }
  28821. };
  28822. Animatable.prototype.disableBlending = function () {
  28823. var animations = this._animations;
  28824. for (var index = 0; index < animations.length; index++) {
  28825. animations[index].enableBlending = false;
  28826. }
  28827. };
  28828. Animatable.prototype.goToFrame = function (frame) {
  28829. var animations = this._animations;
  28830. for (var index = 0; index < animations.length; index++) {
  28831. animations[index].goToFrame(frame);
  28832. }
  28833. };
  28834. Animatable.prototype.pause = function () {
  28835. if (this._paused) {
  28836. return;
  28837. }
  28838. this._paused = true;
  28839. };
  28840. Animatable.prototype.restart = function () {
  28841. this._paused = false;
  28842. };
  28843. Animatable.prototype.stop = function () {
  28844. var index = this._scene._activeAnimatables.indexOf(this);
  28845. if (index > -1) {
  28846. this._scene._activeAnimatables.splice(index, 1);
  28847. var animations = this._animations;
  28848. for (var index = 0; index < animations.length; index++) {
  28849. animations[index].reset();
  28850. }
  28851. if (this.onAnimationEnd) {
  28852. this.onAnimationEnd();
  28853. }
  28854. }
  28855. };
  28856. Animatable.prototype._animate = function (delay) {
  28857. if (this._paused) {
  28858. this.animationStarted = false;
  28859. if (!this._pausedDelay) {
  28860. this._pausedDelay = delay;
  28861. }
  28862. return true;
  28863. }
  28864. if (!this._localDelayOffset) {
  28865. this._localDelayOffset = delay;
  28866. }
  28867. else if (this._pausedDelay) {
  28868. this._localDelayOffset += delay - this._pausedDelay;
  28869. this._pausedDelay = null;
  28870. }
  28871. // Animating
  28872. var running = false;
  28873. var animations = this._animations;
  28874. var index;
  28875. for (index = 0; index < animations.length; index++) {
  28876. var animation = animations[index];
  28877. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  28878. running = running || isRunning;
  28879. }
  28880. this.animationStarted = running;
  28881. if (!running) {
  28882. // Remove from active animatables
  28883. index = this._scene._activeAnimatables.indexOf(this);
  28884. this._scene._activeAnimatables.splice(index, 1);
  28885. }
  28886. if (!running && this.onAnimationEnd) {
  28887. this.onAnimationEnd();
  28888. this.onAnimationEnd = null;
  28889. }
  28890. return running;
  28891. };
  28892. return Animatable;
  28893. }());
  28894. BABYLON.Animatable = Animatable;
  28895. })(BABYLON || (BABYLON = {}));
  28896. var BABYLON;
  28897. (function (BABYLON) {
  28898. var EasingFunction = (function () {
  28899. function EasingFunction() {
  28900. // Properties
  28901. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  28902. }
  28903. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  28904. get: function () {
  28905. return EasingFunction._EASINGMODE_EASEIN;
  28906. },
  28907. enumerable: true,
  28908. configurable: true
  28909. });
  28910. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  28911. get: function () {
  28912. return EasingFunction._EASINGMODE_EASEOUT;
  28913. },
  28914. enumerable: true,
  28915. configurable: true
  28916. });
  28917. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  28918. get: function () {
  28919. return EasingFunction._EASINGMODE_EASEINOUT;
  28920. },
  28921. enumerable: true,
  28922. configurable: true
  28923. });
  28924. EasingFunction.prototype.setEasingMode = function (easingMode) {
  28925. var n = Math.min(Math.max(easingMode, 0), 2);
  28926. this._easingMode = n;
  28927. };
  28928. EasingFunction.prototype.getEasingMode = function () {
  28929. return this._easingMode;
  28930. };
  28931. EasingFunction.prototype.easeInCore = function (gradient) {
  28932. throw new Error('You must implement this method');
  28933. };
  28934. EasingFunction.prototype.ease = function (gradient) {
  28935. switch (this._easingMode) {
  28936. case EasingFunction.EASINGMODE_EASEIN:
  28937. return this.easeInCore(gradient);
  28938. case EasingFunction.EASINGMODE_EASEOUT:
  28939. return (1 - this.easeInCore(1 - gradient));
  28940. }
  28941. if (gradient >= 0.5) {
  28942. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  28943. }
  28944. return (this.easeInCore(gradient * 2) * 0.5);
  28945. };
  28946. //Statics
  28947. EasingFunction._EASINGMODE_EASEIN = 0;
  28948. EasingFunction._EASINGMODE_EASEOUT = 1;
  28949. EasingFunction._EASINGMODE_EASEINOUT = 2;
  28950. return EasingFunction;
  28951. }());
  28952. BABYLON.EasingFunction = EasingFunction;
  28953. var CircleEase = (function (_super) {
  28954. __extends(CircleEase, _super);
  28955. function CircleEase() {
  28956. _super.apply(this, arguments);
  28957. }
  28958. CircleEase.prototype.easeInCore = function (gradient) {
  28959. gradient = Math.max(0, Math.min(1, gradient));
  28960. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  28961. };
  28962. return CircleEase;
  28963. }(EasingFunction));
  28964. BABYLON.CircleEase = CircleEase;
  28965. var BackEase = (function (_super) {
  28966. __extends(BackEase, _super);
  28967. function BackEase(amplitude) {
  28968. if (amplitude === void 0) { amplitude = 1; }
  28969. _super.call(this);
  28970. this.amplitude = amplitude;
  28971. }
  28972. BackEase.prototype.easeInCore = function (gradient) {
  28973. var num = Math.max(0, this.amplitude);
  28974. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  28975. };
  28976. return BackEase;
  28977. }(EasingFunction));
  28978. BABYLON.BackEase = BackEase;
  28979. var BounceEase = (function (_super) {
  28980. __extends(BounceEase, _super);
  28981. function BounceEase(bounces, bounciness) {
  28982. if (bounces === void 0) { bounces = 3; }
  28983. if (bounciness === void 0) { bounciness = 2; }
  28984. _super.call(this);
  28985. this.bounces = bounces;
  28986. this.bounciness = bounciness;
  28987. }
  28988. BounceEase.prototype.easeInCore = function (gradient) {
  28989. var y = Math.max(0.0, this.bounces);
  28990. var bounciness = this.bounciness;
  28991. if (bounciness <= 1.0) {
  28992. bounciness = 1.001;
  28993. }
  28994. var num9 = Math.pow(bounciness, y);
  28995. var num5 = 1.0 - bounciness;
  28996. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  28997. var num15 = gradient * num4;
  28998. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  28999. var num3 = Math.floor(num65);
  29000. var num13 = num3 + 1.0;
  29001. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  29002. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  29003. var num7 = (num8 + num12) * 0.5;
  29004. var num6 = gradient - num7;
  29005. var num2 = num7 - num8;
  29006. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  29007. };
  29008. return BounceEase;
  29009. }(EasingFunction));
  29010. BABYLON.BounceEase = BounceEase;
  29011. var CubicEase = (function (_super) {
  29012. __extends(CubicEase, _super);
  29013. function CubicEase() {
  29014. _super.apply(this, arguments);
  29015. }
  29016. CubicEase.prototype.easeInCore = function (gradient) {
  29017. return (gradient * gradient * gradient);
  29018. };
  29019. return CubicEase;
  29020. }(EasingFunction));
  29021. BABYLON.CubicEase = CubicEase;
  29022. var ElasticEase = (function (_super) {
  29023. __extends(ElasticEase, _super);
  29024. function ElasticEase(oscillations, springiness) {
  29025. if (oscillations === void 0) { oscillations = 3; }
  29026. if (springiness === void 0) { springiness = 3; }
  29027. _super.call(this);
  29028. this.oscillations = oscillations;
  29029. this.springiness = springiness;
  29030. }
  29031. ElasticEase.prototype.easeInCore = function (gradient) {
  29032. var num2;
  29033. var num3 = Math.max(0.0, this.oscillations);
  29034. var num = Math.max(0.0, this.springiness);
  29035. if (num == 0) {
  29036. num2 = gradient;
  29037. }
  29038. else {
  29039. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  29040. }
  29041. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  29042. };
  29043. return ElasticEase;
  29044. }(EasingFunction));
  29045. BABYLON.ElasticEase = ElasticEase;
  29046. var ExponentialEase = (function (_super) {
  29047. __extends(ExponentialEase, _super);
  29048. function ExponentialEase(exponent) {
  29049. if (exponent === void 0) { exponent = 2; }
  29050. _super.call(this);
  29051. this.exponent = exponent;
  29052. }
  29053. ExponentialEase.prototype.easeInCore = function (gradient) {
  29054. if (this.exponent <= 0) {
  29055. return gradient;
  29056. }
  29057. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  29058. };
  29059. return ExponentialEase;
  29060. }(EasingFunction));
  29061. BABYLON.ExponentialEase = ExponentialEase;
  29062. var PowerEase = (function (_super) {
  29063. __extends(PowerEase, _super);
  29064. function PowerEase(power) {
  29065. if (power === void 0) { power = 2; }
  29066. _super.call(this);
  29067. this.power = power;
  29068. }
  29069. PowerEase.prototype.easeInCore = function (gradient) {
  29070. var y = Math.max(0.0, this.power);
  29071. return Math.pow(gradient, y);
  29072. };
  29073. return PowerEase;
  29074. }(EasingFunction));
  29075. BABYLON.PowerEase = PowerEase;
  29076. var QuadraticEase = (function (_super) {
  29077. __extends(QuadraticEase, _super);
  29078. function QuadraticEase() {
  29079. _super.apply(this, arguments);
  29080. }
  29081. QuadraticEase.prototype.easeInCore = function (gradient) {
  29082. return (gradient * gradient);
  29083. };
  29084. return QuadraticEase;
  29085. }(EasingFunction));
  29086. BABYLON.QuadraticEase = QuadraticEase;
  29087. var QuarticEase = (function (_super) {
  29088. __extends(QuarticEase, _super);
  29089. function QuarticEase() {
  29090. _super.apply(this, arguments);
  29091. }
  29092. QuarticEase.prototype.easeInCore = function (gradient) {
  29093. return (gradient * gradient * gradient * gradient);
  29094. };
  29095. return QuarticEase;
  29096. }(EasingFunction));
  29097. BABYLON.QuarticEase = QuarticEase;
  29098. var QuinticEase = (function (_super) {
  29099. __extends(QuinticEase, _super);
  29100. function QuinticEase() {
  29101. _super.apply(this, arguments);
  29102. }
  29103. QuinticEase.prototype.easeInCore = function (gradient) {
  29104. return (gradient * gradient * gradient * gradient * gradient);
  29105. };
  29106. return QuinticEase;
  29107. }(EasingFunction));
  29108. BABYLON.QuinticEase = QuinticEase;
  29109. var SineEase = (function (_super) {
  29110. __extends(SineEase, _super);
  29111. function SineEase() {
  29112. _super.apply(this, arguments);
  29113. }
  29114. SineEase.prototype.easeInCore = function (gradient) {
  29115. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  29116. };
  29117. return SineEase;
  29118. }(EasingFunction));
  29119. BABYLON.SineEase = SineEase;
  29120. var BezierCurveEase = (function (_super) {
  29121. __extends(BezierCurveEase, _super);
  29122. function BezierCurveEase(x1, y1, x2, y2) {
  29123. if (x1 === void 0) { x1 = 0; }
  29124. if (y1 === void 0) { y1 = 0; }
  29125. if (x2 === void 0) { x2 = 1; }
  29126. if (y2 === void 0) { y2 = 1; }
  29127. _super.call(this);
  29128. this.x1 = x1;
  29129. this.y1 = y1;
  29130. this.x2 = x2;
  29131. this.y2 = y2;
  29132. }
  29133. BezierCurveEase.prototype.easeInCore = function (gradient) {
  29134. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  29135. };
  29136. return BezierCurveEase;
  29137. }(EasingFunction));
  29138. BABYLON.BezierCurveEase = BezierCurveEase;
  29139. })(BABYLON || (BABYLON = {}));
  29140. var BABYLON;
  29141. (function (BABYLON) {
  29142. var Bone = (function (_super) {
  29143. __extends(Bone, _super);
  29144. function Bone(name, skeleton, parentBone, matrix, restPose) {
  29145. _super.call(this, name, skeleton.getScene());
  29146. this.name = name;
  29147. this.children = new Array();
  29148. this.animations = new Array();
  29149. this._worldTransform = new BABYLON.Matrix();
  29150. this._absoluteTransform = new BABYLON.Matrix();
  29151. this._invertedAbsoluteTransform = new BABYLON.Matrix();
  29152. this._skeleton = skeleton;
  29153. this._matrix = matrix;
  29154. this._baseMatrix = matrix;
  29155. this._restPose = restPose ? restPose : matrix.clone();
  29156. skeleton.bones.push(this);
  29157. if (parentBone) {
  29158. this._parent = parentBone;
  29159. parentBone.children.push(this);
  29160. }
  29161. else {
  29162. this._parent = null;
  29163. }
  29164. this._updateDifferenceMatrix();
  29165. }
  29166. // Members
  29167. Bone.prototype.getParent = function () {
  29168. return this._parent;
  29169. };
  29170. Bone.prototype.getLocalMatrix = function () {
  29171. return this._matrix;
  29172. };
  29173. Bone.prototype.getBaseMatrix = function () {
  29174. return this._baseMatrix;
  29175. };
  29176. Bone.prototype.getRestPose = function () {
  29177. return this._restPose;
  29178. };
  29179. Bone.prototype.returnToRest = function () {
  29180. this.updateMatrix(this._restPose.clone());
  29181. };
  29182. Bone.prototype.getWorldMatrix = function () {
  29183. return this._worldTransform;
  29184. };
  29185. Bone.prototype.getInvertedAbsoluteTransform = function () {
  29186. return this._invertedAbsoluteTransform;
  29187. };
  29188. Bone.prototype.getAbsoluteTransform = function () {
  29189. return this._absoluteTransform;
  29190. };
  29191. // Methods
  29192. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  29193. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  29194. this._baseMatrix = matrix.clone();
  29195. this._matrix = matrix.clone();
  29196. this._skeleton._markAsDirty();
  29197. if (updateDifferenceMatrix) {
  29198. this._updateDifferenceMatrix();
  29199. }
  29200. };
  29201. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  29202. if (!rootMatrix) {
  29203. rootMatrix = this._baseMatrix;
  29204. }
  29205. if (this._parent) {
  29206. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  29207. }
  29208. else {
  29209. this._absoluteTransform.copyFrom(rootMatrix);
  29210. }
  29211. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  29212. for (var index = 0; index < this.children.length; index++) {
  29213. this.children[index]._updateDifferenceMatrix();
  29214. }
  29215. };
  29216. Bone.prototype.markAsDirty = function () {
  29217. this._currentRenderId++;
  29218. this._skeleton._markAsDirty();
  29219. };
  29220. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  29221. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  29222. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  29223. // all animation may be coming from a library skeleton, so may need to create animation
  29224. if (this.animations.length === 0) {
  29225. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  29226. this.animations[0].setKeys([]);
  29227. }
  29228. // get animation info / verify there is such a range from the source bone
  29229. var sourceRange = source.animations[0].getRange(rangeName);
  29230. if (!sourceRange) {
  29231. return false;
  29232. }
  29233. var from = sourceRange.from;
  29234. var to = sourceRange.to;
  29235. var sourceKeys = source.animations[0].getKeys();
  29236. // rescaling prep
  29237. var sourceBoneLength = source.length;
  29238. var sourceParent = source.getParent();
  29239. var parent = this.getParent();
  29240. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  29241. var parentRatio = parentScalingReqd ? parent.length / sourceParent.length : null;
  29242. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  29243. var destKeys = this.animations[0].getKeys();
  29244. // loop vars declaration
  29245. var orig;
  29246. var origTranslation;
  29247. var mat;
  29248. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  29249. orig = sourceKeys[key];
  29250. if (orig.frame >= from && orig.frame <= to) {
  29251. if (rescaleAsRequired) {
  29252. mat = orig.value.clone();
  29253. // scale based on parent ratio, when bone has parent
  29254. if (parentScalingReqd) {
  29255. origTranslation = mat.getTranslation();
  29256. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  29257. }
  29258. else if (dimensionsScalingReqd) {
  29259. origTranslation = mat.getTranslation();
  29260. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  29261. }
  29262. else {
  29263. mat = orig.value;
  29264. }
  29265. }
  29266. else {
  29267. mat = orig.value;
  29268. }
  29269. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  29270. }
  29271. }
  29272. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  29273. return true;
  29274. };
  29275. return Bone;
  29276. }(BABYLON.Node));
  29277. BABYLON.Bone = Bone;
  29278. })(BABYLON || (BABYLON = {}));
  29279. var BABYLON;
  29280. (function (BABYLON) {
  29281. var Skeleton = (function () {
  29282. function Skeleton(name, id, scene) {
  29283. this.name = name;
  29284. this.id = id;
  29285. this.bones = new Array();
  29286. this.needInitialSkinMatrix = false;
  29287. this._isDirty = true;
  29288. this._meshesWithPoseMatrix = new Array();
  29289. this._identity = BABYLON.Matrix.Identity();
  29290. this._ranges = {};
  29291. this.bones = [];
  29292. this._scene = scene;
  29293. scene.skeletons.push(this);
  29294. //make sure it will recalculate the matrix next time prepare is called.
  29295. this._isDirty = true;
  29296. }
  29297. // Members
  29298. Skeleton.prototype.getTransformMatrices = function (mesh) {
  29299. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  29300. return mesh._bonesTransformMatrices;
  29301. }
  29302. return this._transformMatrices;
  29303. };
  29304. Skeleton.prototype.getScene = function () {
  29305. return this._scene;
  29306. };
  29307. // Methods
  29308. /**
  29309. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  29310. */
  29311. Skeleton.prototype.toString = function (fullDetails) {
  29312. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  29313. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  29314. if (fullDetails) {
  29315. ret += ", Ranges: {";
  29316. var first = true;
  29317. for (var name_1 in this._ranges) {
  29318. if (first) {
  29319. ret += ", ";
  29320. first = false;
  29321. }
  29322. ret += name_1;
  29323. }
  29324. ret += "}";
  29325. }
  29326. return ret;
  29327. };
  29328. /**
  29329. * Get bone's index searching by name
  29330. * @param {string} name is bone's name to search for
  29331. * @return {number} Indice of the bone. Returns -1 if not found
  29332. */
  29333. Skeleton.prototype.getBoneIndexByName = function (name) {
  29334. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  29335. if (this.bones[boneIndex].name === name) {
  29336. return boneIndex;
  29337. }
  29338. }
  29339. return -1;
  29340. };
  29341. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  29342. // check name not already in use
  29343. if (!this._ranges[name]) {
  29344. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  29345. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  29346. if (this.bones[i].animations[0]) {
  29347. this.bones[i].animations[0].createRange(name, from, to);
  29348. }
  29349. }
  29350. }
  29351. };
  29352. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  29353. if (deleteFrames === void 0) { deleteFrames = true; }
  29354. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  29355. if (this.bones[i].animations[0]) {
  29356. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  29357. }
  29358. }
  29359. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  29360. };
  29361. Skeleton.prototype.getAnimationRange = function (name) {
  29362. return this._ranges[name];
  29363. };
  29364. /**
  29365. * Returns as an Array, all AnimationRanges defined on this skeleton
  29366. */
  29367. Skeleton.prototype.getAnimationRanges = function () {
  29368. var animationRanges = [];
  29369. var name;
  29370. var i = 0;
  29371. for (name in this._ranges) {
  29372. animationRanges[i] = this._ranges[name];
  29373. i++;
  29374. }
  29375. return animationRanges;
  29376. };
  29377. /**
  29378. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  29379. */
  29380. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  29381. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  29382. if (this._ranges[name] || !source.getAnimationRange(name)) {
  29383. return false;
  29384. }
  29385. var ret = true;
  29386. var frameOffset = this._getHighestAnimationFrame() + 1;
  29387. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  29388. var boneDict = {};
  29389. var sourceBones = source.bones;
  29390. var nBones;
  29391. var i;
  29392. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  29393. boneDict[sourceBones[i].name] = sourceBones[i];
  29394. }
  29395. if (this.bones.length !== sourceBones.length) {
  29396. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  29397. ret = false;
  29398. }
  29399. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  29400. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  29401. var boneName = this.bones[i].name;
  29402. var sourceBone = boneDict[boneName];
  29403. if (sourceBone) {
  29404. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  29405. }
  29406. else {
  29407. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  29408. ret = false;
  29409. }
  29410. }
  29411. // do not call createAnimationRange(), since it also is done to bones, which was already done
  29412. var range = source.getAnimationRange(name);
  29413. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  29414. return ret;
  29415. };
  29416. Skeleton.prototype.returnToRest = function () {
  29417. for (var index = 0; index < this.bones.length; index++) {
  29418. this.bones[index].returnToRest();
  29419. }
  29420. };
  29421. Skeleton.prototype._getHighestAnimationFrame = function () {
  29422. var ret = 0;
  29423. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  29424. if (this.bones[i].animations[0]) {
  29425. var highest = this.bones[i].animations[0].getHighestFrame();
  29426. if (ret < highest) {
  29427. ret = highest;
  29428. }
  29429. }
  29430. }
  29431. return ret;
  29432. };
  29433. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  29434. var range = this.getAnimationRange(name);
  29435. if (!range) {
  29436. return null;
  29437. }
  29438. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  29439. };
  29440. Skeleton.prototype._markAsDirty = function () {
  29441. this._isDirty = true;
  29442. };
  29443. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  29444. this._meshesWithPoseMatrix.push(mesh);
  29445. };
  29446. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  29447. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  29448. if (index > -1) {
  29449. this._meshesWithPoseMatrix.splice(index, 1);
  29450. }
  29451. };
  29452. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  29453. for (var index = 0; index < this.bones.length; index++) {
  29454. var bone = this.bones[index];
  29455. var parentBone = bone.getParent();
  29456. if (parentBone) {
  29457. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  29458. }
  29459. else {
  29460. if (initialSkinMatrix) {
  29461. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  29462. }
  29463. else {
  29464. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  29465. }
  29466. }
  29467. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, index * 16);
  29468. }
  29469. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  29470. };
  29471. Skeleton.prototype.prepare = function () {
  29472. if (!this._isDirty) {
  29473. return;
  29474. }
  29475. if (this.needInitialSkinMatrix) {
  29476. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  29477. var mesh = this._meshesWithPoseMatrix[index];
  29478. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  29479. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  29480. }
  29481. var poseMatrix = mesh.getPoseMatrix();
  29482. // Prepare bones
  29483. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  29484. var bone = this.bones[boneIndex];
  29485. if (!bone.getParent()) {
  29486. var matrix = bone.getBaseMatrix();
  29487. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[0]);
  29488. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[0]);
  29489. }
  29490. }
  29491. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  29492. }
  29493. }
  29494. else {
  29495. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  29496. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  29497. }
  29498. this._computeTransformMatrices(this._transformMatrices, null);
  29499. }
  29500. this._isDirty = false;
  29501. this._scene._activeBones.addCount(this.bones.length, false);
  29502. };
  29503. Skeleton.prototype.getAnimatables = function () {
  29504. if (!this._animatables || this._animatables.length !== this.bones.length) {
  29505. this._animatables = [];
  29506. for (var index = 0; index < this.bones.length; index++) {
  29507. this._animatables.push(this.bones[index]);
  29508. }
  29509. }
  29510. return this._animatables;
  29511. };
  29512. Skeleton.prototype.clone = function (name, id) {
  29513. var result = new Skeleton(name, id || name, this._scene);
  29514. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  29515. for (var index = 0; index < this.bones.length; index++) {
  29516. var source = this.bones[index];
  29517. var parentBone = null;
  29518. if (source.getParent()) {
  29519. var parentIndex = this.bones.indexOf(source.getParent());
  29520. parentBone = result.bones[parentIndex];
  29521. }
  29522. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  29523. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  29524. }
  29525. if (this._ranges) {
  29526. result._ranges = {};
  29527. for (var rangeName in this._ranges) {
  29528. result._ranges[rangeName] = this._ranges[rangeName].clone();
  29529. }
  29530. }
  29531. this._isDirty = true;
  29532. return result;
  29533. };
  29534. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  29535. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  29536. this.bones.forEach(function (bone) {
  29537. bone.animations.forEach(function (animation) {
  29538. animation.enableBlending = true;
  29539. animation.blendingSpeed = blendingSpeed;
  29540. });
  29541. });
  29542. };
  29543. Skeleton.prototype.dispose = function () {
  29544. this._meshesWithPoseMatrix = [];
  29545. // Animations
  29546. this.getScene().stopAnimation(this);
  29547. // Remove from scene
  29548. this.getScene().removeSkeleton(this);
  29549. };
  29550. Skeleton.prototype.serialize = function () {
  29551. var serializationObject = {};
  29552. serializationObject.name = this.name;
  29553. serializationObject.id = this.id;
  29554. serializationObject.dimensionsAtRest = this.dimensionsAtRest;
  29555. serializationObject.bones = [];
  29556. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  29557. for (var index = 0; index < this.bones.length; index++) {
  29558. var bone = this.bones[index];
  29559. var serializedBone = {
  29560. parentBoneIndex: bone.getParent() ? this.bones.indexOf(bone.getParent()) : -1,
  29561. name: bone.name,
  29562. matrix: bone.getLocalMatrix().toArray(),
  29563. rest: bone.getRestPose().toArray()
  29564. };
  29565. serializationObject.bones.push(serializedBone);
  29566. if (bone.length) {
  29567. serializedBone.length = bone.length;
  29568. }
  29569. if (bone.animations && bone.animations.length > 0) {
  29570. serializedBone.animation = bone.animations[0].serialize();
  29571. }
  29572. serializationObject.ranges = [];
  29573. for (var name in this._ranges) {
  29574. var range = {};
  29575. range.name = name;
  29576. range.from = this._ranges[name].from;
  29577. range.to = this._ranges[name].to;
  29578. serializationObject.ranges.push(range);
  29579. }
  29580. }
  29581. return serializationObject;
  29582. };
  29583. Skeleton.Parse = function (parsedSkeleton, scene) {
  29584. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  29585. if (parsedSkeleton.dimensionsAtRest) {
  29586. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  29587. }
  29588. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  29589. var index;
  29590. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  29591. var parsedBone = parsedSkeleton.bones[index];
  29592. var parentBone = null;
  29593. if (parsedBone.parentBoneIndex > -1) {
  29594. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  29595. }
  29596. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  29597. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  29598. if (parsedBone.length) {
  29599. bone.length = parsedBone.length;
  29600. }
  29601. if (parsedBone.animation) {
  29602. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  29603. }
  29604. }
  29605. // placed after bones, so createAnimationRange can cascade down
  29606. if (parsedSkeleton.ranges) {
  29607. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  29608. var data = parsedSkeleton.ranges[index];
  29609. skeleton.createAnimationRange(data.name, data.from, data.to);
  29610. }
  29611. }
  29612. return skeleton;
  29613. };
  29614. return Skeleton;
  29615. }());
  29616. BABYLON.Skeleton = Skeleton;
  29617. })(BABYLON || (BABYLON = {}));
  29618. var BABYLON;
  29619. (function (BABYLON) {
  29620. var PostProcess = (function () {
  29621. function PostProcess(name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType) {
  29622. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  29623. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  29624. this.name = name;
  29625. this.width = -1;
  29626. this.height = -1;
  29627. /*
  29628. Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  29629. Can only be used on a single postprocess or on the last one of a chain.
  29630. */
  29631. this.enablePixelPerfectMode = false;
  29632. this._reusable = false;
  29633. this._textures = new BABYLON.SmartArray(2);
  29634. this._currentRenderTextureInd = 0;
  29635. this._scaleRatio = new BABYLON.Vector2(1, 1);
  29636. // Events
  29637. /**
  29638. * An event triggered when the postprocess is activated.
  29639. * @type {BABYLON.Observable}
  29640. */
  29641. this.onActivateObservable = new BABYLON.Observable();
  29642. /**
  29643. * An event triggered when the postprocess changes its size.
  29644. * @type {BABYLON.Observable}
  29645. */
  29646. this.onSizeChangedObservable = new BABYLON.Observable();
  29647. /**
  29648. * An event triggered when the postprocess applies its effect.
  29649. * @type {BABYLON.Observable}
  29650. */
  29651. this.onApplyObservable = new BABYLON.Observable();
  29652. /**
  29653. * An event triggered before rendering the postprocess
  29654. * @type {BABYLON.Observable}
  29655. */
  29656. this.onBeforeRenderObservable = new BABYLON.Observable();
  29657. /**
  29658. * An event triggered after rendering the postprocess
  29659. * @type {BABYLON.Observable}
  29660. */
  29661. this.onAfterRenderObservable = new BABYLON.Observable();
  29662. if (camera != null) {
  29663. this._camera = camera;
  29664. this._scene = camera.getScene();
  29665. camera.attachPostProcess(this);
  29666. this._engine = this._scene.getEngine();
  29667. }
  29668. else {
  29669. this._engine = engine;
  29670. }
  29671. this._options = options;
  29672. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  29673. this._reusable = reusable || false;
  29674. this._textureType = textureType;
  29675. this._samplers = samplers || [];
  29676. this._samplers.push("textureSampler");
  29677. this._fragmentUrl = fragmentUrl;
  29678. this._parameters = parameters || [];
  29679. this._parameters.push("scale");
  29680. this.updateEffect(defines);
  29681. }
  29682. Object.defineProperty(PostProcess.prototype, "onActivate", {
  29683. set: function (callback) {
  29684. if (this._onActivateObserver) {
  29685. this.onActivateObservable.remove(this._onActivateObserver);
  29686. }
  29687. this._onActivateObserver = this.onActivateObservable.add(callback);
  29688. },
  29689. enumerable: true,
  29690. configurable: true
  29691. });
  29692. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  29693. set: function (callback) {
  29694. if (this._onSizeChangedObserver) {
  29695. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  29696. }
  29697. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  29698. },
  29699. enumerable: true,
  29700. configurable: true
  29701. });
  29702. Object.defineProperty(PostProcess.prototype, "onApply", {
  29703. set: function (callback) {
  29704. if (this._onApplyObserver) {
  29705. this.onApplyObservable.remove(this._onApplyObserver);
  29706. }
  29707. this._onApplyObserver = this.onApplyObservable.add(callback);
  29708. },
  29709. enumerable: true,
  29710. configurable: true
  29711. });
  29712. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  29713. set: function (callback) {
  29714. if (this._onBeforeRenderObserver) {
  29715. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  29716. }
  29717. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  29718. },
  29719. enumerable: true,
  29720. configurable: true
  29721. });
  29722. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  29723. set: function (callback) {
  29724. if (this._onAfterRenderObserver) {
  29725. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  29726. }
  29727. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  29728. },
  29729. enumerable: true,
  29730. configurable: true
  29731. });
  29732. PostProcess.prototype.updateEffect = function (defines) {
  29733. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: this._fragmentUrl }, ["position"], this._parameters, this._samplers, defines !== undefined ? defines : "");
  29734. };
  29735. PostProcess.prototype.isReusable = function () {
  29736. return this._reusable;
  29737. };
  29738. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  29739. PostProcess.prototype.markTextureDirty = function () {
  29740. this.width = -1;
  29741. };
  29742. PostProcess.prototype.activate = function (camera, sourceTexture) {
  29743. camera = camera || this._camera;
  29744. var scene = camera.getScene();
  29745. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  29746. var requiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._options) | 0;
  29747. var requiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._options) | 0;
  29748. var desiredWidth = this._options.width || requiredWidth;
  29749. var desiredHeight = this._options.height || requiredHeight;
  29750. if (this.renderTargetSamplingMode !== BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  29751. if (!this._options.width) {
  29752. desiredWidth = BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize);
  29753. }
  29754. if (!this._options.height) {
  29755. desiredHeight = BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize);
  29756. }
  29757. }
  29758. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  29759. if (this._textures.length > 0) {
  29760. for (var i = 0; i < this._textures.length; i++) {
  29761. this._engine._releaseTexture(this._textures.data[i]);
  29762. }
  29763. this._textures.reset();
  29764. }
  29765. this.width = desiredWidth;
  29766. this.height = desiredHeight;
  29767. var textureSize = { width: this.width, height: this.height };
  29768. var textureOptions = {
  29769. generateMipMaps: false,
  29770. generateDepthBuffer: camera._postProcesses.indexOf(this) === 0,
  29771. generateStencilBuffer: camera._postProcesses.indexOf(this) === 0 && this._engine.isStencilEnable,
  29772. samplingMode: this.renderTargetSamplingMode,
  29773. type: this._textureType
  29774. };
  29775. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  29776. if (this._reusable) {
  29777. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  29778. }
  29779. this.onSizeChangedObservable.notifyObservers(this);
  29780. }
  29781. if (this.enablePixelPerfectMode) {
  29782. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  29783. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd], 0, requiredWidth, requiredHeight);
  29784. }
  29785. else {
  29786. this._scaleRatio.copyFromFloats(1, 1);
  29787. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  29788. }
  29789. this.onActivateObservable.notifyObservers(camera);
  29790. // Clear
  29791. if (this.clearColor) {
  29792. this._engine.clear(this.clearColor, true, true, true);
  29793. }
  29794. else {
  29795. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true, true);
  29796. }
  29797. if (this._reusable) {
  29798. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  29799. }
  29800. };
  29801. Object.defineProperty(PostProcess.prototype, "isSupported", {
  29802. get: function () {
  29803. return this._effect.isSupported;
  29804. },
  29805. enumerable: true,
  29806. configurable: true
  29807. });
  29808. PostProcess.prototype.apply = function () {
  29809. // Check
  29810. if (!this._effect.isReady())
  29811. return null;
  29812. // States
  29813. this._engine.enableEffect(this._effect);
  29814. this._engine.setState(false);
  29815. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  29816. this._engine.setDepthBuffer(false);
  29817. this._engine.setDepthWrite(false);
  29818. // Texture
  29819. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  29820. // Parameters
  29821. this._effect.setVector2("scale", this._scaleRatio);
  29822. this.onApplyObservable.notifyObservers(this._effect);
  29823. return this._effect;
  29824. };
  29825. PostProcess.prototype.dispose = function (camera) {
  29826. camera = camera || this._camera;
  29827. if (this._textures.length > 0) {
  29828. for (var i = 0; i < this._textures.length; i++) {
  29829. this._engine._releaseTexture(this._textures.data[i]);
  29830. }
  29831. this._textures.reset();
  29832. }
  29833. if (!camera) {
  29834. return;
  29835. }
  29836. camera.detachPostProcess(this);
  29837. var index = camera._postProcesses.indexOf(this);
  29838. if (index === 0 && camera._postProcesses.length > 0) {
  29839. this._camera._postProcesses[0].markTextureDirty();
  29840. }
  29841. this.onActivateObservable.clear();
  29842. this.onAfterRenderObservable.clear();
  29843. this.onApplyObservable.clear();
  29844. this.onBeforeRenderObservable.clear();
  29845. this.onSizeChangedObservable.clear();
  29846. };
  29847. return PostProcess;
  29848. }());
  29849. BABYLON.PostProcess = PostProcess;
  29850. })(BABYLON || (BABYLON = {}));
  29851. var BABYLON;
  29852. (function (BABYLON) {
  29853. var PostProcessManager = (function () {
  29854. function PostProcessManager(scene) {
  29855. this._vertexBuffers = {};
  29856. this._scene = scene;
  29857. }
  29858. PostProcessManager.prototype._prepareBuffers = function () {
  29859. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  29860. return;
  29861. }
  29862. // VBO
  29863. var vertices = [];
  29864. vertices.push(1, 1);
  29865. vertices.push(-1, 1);
  29866. vertices.push(-1, -1);
  29867. vertices.push(1, -1);
  29868. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  29869. // Indices
  29870. var indices = [];
  29871. indices.push(0);
  29872. indices.push(1);
  29873. indices.push(2);
  29874. indices.push(0);
  29875. indices.push(2);
  29876. indices.push(3);
  29877. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  29878. };
  29879. // Methods
  29880. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  29881. var postProcesses = this._scene.activeCamera._postProcesses;
  29882. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  29883. return false;
  29884. }
  29885. postProcesses[0].activate(this._scene.activeCamera, sourceTexture);
  29886. return true;
  29887. };
  29888. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
  29889. var engine = this._scene.getEngine();
  29890. for (var index = 0; index < postProcesses.length; index++) {
  29891. if (index < postProcesses.length - 1) {
  29892. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  29893. }
  29894. else {
  29895. if (targetTexture) {
  29896. engine.bindFramebuffer(targetTexture);
  29897. }
  29898. else {
  29899. engine.restoreDefaultFramebuffer();
  29900. }
  29901. }
  29902. var pp = postProcesses[index];
  29903. var effect = pp.apply();
  29904. if (effect) {
  29905. pp.onBeforeRenderObservable.notifyObservers(effect);
  29906. // VBOs
  29907. this._prepareBuffers();
  29908. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  29909. // Draw order
  29910. engine.draw(true, 0, 6);
  29911. pp.onAfterRenderObservable.notifyObservers(effect);
  29912. }
  29913. }
  29914. // Restore depth buffer
  29915. engine.setDepthBuffer(true);
  29916. engine.setDepthWrite(true);
  29917. };
  29918. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses) {
  29919. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  29920. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  29921. return;
  29922. }
  29923. var engine = this._scene.getEngine();
  29924. for (var index = 0, len = postProcesses.length; index < len; index++) {
  29925. if (index < len - 1) {
  29926. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  29927. }
  29928. else {
  29929. if (targetTexture) {
  29930. engine.bindFramebuffer(targetTexture, faceIndex);
  29931. }
  29932. else {
  29933. engine.restoreDefaultFramebuffer();
  29934. }
  29935. }
  29936. if (doNotPresent) {
  29937. break;
  29938. }
  29939. var pp = postProcesses[index];
  29940. var effect = pp.apply();
  29941. if (effect) {
  29942. pp.onBeforeRenderObservable.notifyObservers(effect);
  29943. // VBOs
  29944. this._prepareBuffers();
  29945. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  29946. // Draw order
  29947. engine.draw(true, 0, 6);
  29948. pp.onAfterRenderObservable.notifyObservers(effect);
  29949. }
  29950. }
  29951. // Restore depth buffer
  29952. engine.setDepthBuffer(true);
  29953. engine.setDepthWrite(true);
  29954. };
  29955. PostProcessManager.prototype.dispose = function () {
  29956. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  29957. if (buffer) {
  29958. buffer.dispose();
  29959. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  29960. }
  29961. if (this._indexBuffer) {
  29962. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  29963. this._indexBuffer = null;
  29964. }
  29965. };
  29966. return PostProcessManager;
  29967. }());
  29968. BABYLON.PostProcessManager = PostProcessManager;
  29969. })(BABYLON || (BABYLON = {}));
  29970. var BABYLON;
  29971. (function (BABYLON) {
  29972. var PassPostProcess = (function (_super) {
  29973. __extends(PassPostProcess, _super);
  29974. function PassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  29975. _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable);
  29976. }
  29977. return PassPostProcess;
  29978. }(BABYLON.PostProcess));
  29979. BABYLON.PassPostProcess = PassPostProcess;
  29980. })(BABYLON || (BABYLON = {}));
  29981. var BABYLON;
  29982. (function (BABYLON) {
  29983. /**
  29984. * This is a holder class for the physics joint created by the physics plugin.
  29985. * It holds a set of functions to control the underlying joint.
  29986. */
  29987. var PhysicsJoint = (function () {
  29988. function PhysicsJoint(type, jointData) {
  29989. this.type = type;
  29990. this.jointData = jointData;
  29991. jointData.nativeParams = jointData.nativeParams || {};
  29992. }
  29993. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  29994. get: function () {
  29995. return this._physicsJoint;
  29996. },
  29997. set: function (newJoint) {
  29998. if (this._physicsJoint) {
  29999. }
  30000. this._physicsJoint = newJoint;
  30001. },
  30002. enumerable: true,
  30003. configurable: true
  30004. });
  30005. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  30006. set: function (physicsPlugin) {
  30007. this._physicsPlugin = physicsPlugin;
  30008. },
  30009. enumerable: true,
  30010. configurable: true
  30011. });
  30012. /**
  30013. * Execute a function that is physics-plugin specific.
  30014. * @param {Function} func the function that will be executed.
  30015. * It accepts two parameters: the physics world and the physics joint.
  30016. */
  30017. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  30018. func(this._physicsPlugin.world, this._physicsJoint);
  30019. };
  30020. //TODO check if the native joints are the same
  30021. //Joint Types
  30022. PhysicsJoint.DistanceJoint = 0;
  30023. PhysicsJoint.HingeJoint = 1;
  30024. PhysicsJoint.BallAndSocketJoint = 2;
  30025. PhysicsJoint.WheelJoint = 3;
  30026. PhysicsJoint.SliderJoint = 4;
  30027. //OIMO
  30028. PhysicsJoint.PrismaticJoint = 5;
  30029. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  30030. PhysicsJoint.UniversalJoint = 6;
  30031. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  30032. //Cannon
  30033. //Similar to a Ball-Joint. Different in params
  30034. PhysicsJoint.PointToPointJoint = 8;
  30035. //Cannon only at the moment
  30036. PhysicsJoint.SpringJoint = 9;
  30037. PhysicsJoint.LockJoint = 10;
  30038. return PhysicsJoint;
  30039. }());
  30040. BABYLON.PhysicsJoint = PhysicsJoint;
  30041. /**
  30042. * A class representing a physics distance joint.
  30043. */
  30044. var DistanceJoint = (function (_super) {
  30045. __extends(DistanceJoint, _super);
  30046. function DistanceJoint(jointData) {
  30047. _super.call(this, PhysicsJoint.DistanceJoint, jointData);
  30048. }
  30049. /**
  30050. * Update the predefined distance.
  30051. */
  30052. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  30053. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  30054. };
  30055. return DistanceJoint;
  30056. }(PhysicsJoint));
  30057. BABYLON.DistanceJoint = DistanceJoint;
  30058. var MotorEnabledJoint = (function (_super) {
  30059. __extends(MotorEnabledJoint, _super);
  30060. function MotorEnabledJoint(type, jointData) {
  30061. _super.call(this, type, jointData);
  30062. }
  30063. /**
  30064. * Set the motor values.
  30065. * Attention, this function is plugin specific. Engines won't react 100% the same.
  30066. * @param {number} force the force to apply
  30067. * @param {number} maxForce max force for this motor.
  30068. */
  30069. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  30070. this._physicsPlugin.setMotor(this, force, maxForce);
  30071. };
  30072. /**
  30073. * Set the motor's limits.
  30074. * Attention, this function is plugin specific. Engines won't react 100% the same.
  30075. */
  30076. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  30077. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  30078. };
  30079. return MotorEnabledJoint;
  30080. }(PhysicsJoint));
  30081. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  30082. /**
  30083. * This class represents a single hinge physics joint
  30084. */
  30085. var HingeJoint = (function (_super) {
  30086. __extends(HingeJoint, _super);
  30087. function HingeJoint(jointData) {
  30088. _super.call(this, PhysicsJoint.HingeJoint, jointData);
  30089. }
  30090. /**
  30091. * Set the motor values.
  30092. * Attention, this function is plugin specific. Engines won't react 100% the same.
  30093. * @param {number} force the force to apply
  30094. * @param {number} maxForce max force for this motor.
  30095. */
  30096. HingeJoint.prototype.setMotor = function (force, maxForce) {
  30097. this._physicsPlugin.setMotor(this, force, maxForce);
  30098. };
  30099. /**
  30100. * Set the motor's limits.
  30101. * Attention, this function is plugin specific. Engines won't react 100% the same.
  30102. */
  30103. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  30104. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  30105. };
  30106. return HingeJoint;
  30107. }(MotorEnabledJoint));
  30108. BABYLON.HingeJoint = HingeJoint;
  30109. /**
  30110. * This class represents a dual hinge physics joint (same as wheel joint)
  30111. */
  30112. var Hinge2Joint = (function (_super) {
  30113. __extends(Hinge2Joint, _super);
  30114. function Hinge2Joint(jointData) {
  30115. _super.call(this, PhysicsJoint.Hinge2Joint, jointData);
  30116. }
  30117. /**
  30118. * Set the motor values.
  30119. * Attention, this function is plugin specific. Engines won't react 100% the same.
  30120. * @param {number} force the force to apply
  30121. * @param {number} maxForce max force for this motor.
  30122. * @param {motorIndex} the motor's index, 0 or 1.
  30123. */
  30124. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  30125. if (motorIndex === void 0) { motorIndex = 0; }
  30126. this._physicsPlugin.setMotor(this, force, maxForce, motorIndex);
  30127. };
  30128. /**
  30129. * Set the motor limits.
  30130. * Attention, this function is plugin specific. Engines won't react 100% the same.
  30131. * @param {number} upperLimit the upper limit
  30132. * @param {number} lowerLimit lower limit
  30133. * @param {motorIndex} the motor's index, 0 or 1.
  30134. */
  30135. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  30136. if (motorIndex === void 0) { motorIndex = 0; }
  30137. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  30138. };
  30139. return Hinge2Joint;
  30140. }(MotorEnabledJoint));
  30141. BABYLON.Hinge2Joint = Hinge2Joint;
  30142. })(BABYLON || (BABYLON = {}));
  30143. var BABYLON;
  30144. (function (BABYLON) {
  30145. var PhysicsImpostor = (function () {
  30146. function PhysicsImpostor(object, type, _options, _scene) {
  30147. var _this = this;
  30148. if (_options === void 0) { _options = { mass: 0 }; }
  30149. this.object = object;
  30150. this.type = type;
  30151. this._options = _options;
  30152. this._scene = _scene;
  30153. this._bodyUpdateRequired = false;
  30154. this._onBeforePhysicsStepCallbacks = new Array();
  30155. this._onAfterPhysicsStepCallbacks = new Array();
  30156. this._onPhysicsCollideCallbacks = [];
  30157. this._deltaPosition = BABYLON.Vector3.Zero();
  30158. this._tmpPositionWithDelta = BABYLON.Vector3.Zero();
  30159. this._tmpRotationWithDelta = new BABYLON.Quaternion();
  30160. /**
  30161. * this function is executed by the physics engine.
  30162. */
  30163. this.beforeStep = function () {
  30164. _this.object.position.subtractToRef(_this._deltaPosition, _this._tmpPositionWithDelta);
  30165. //conjugate deltaRotation
  30166. if (_this._deltaRotationConjugated) {
  30167. _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this._tmpRotationWithDelta);
  30168. }
  30169. else {
  30170. _this._tmpRotationWithDelta.copyFrom(_this.object.rotationQuaternion);
  30171. }
  30172. _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, _this._tmpPositionWithDelta, _this._tmpRotationWithDelta);
  30173. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  30174. func(_this);
  30175. });
  30176. };
  30177. /**
  30178. * this function is executed by the physics engine.
  30179. */
  30180. this.afterStep = function () {
  30181. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  30182. func(_this);
  30183. });
  30184. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  30185. _this.object.position.addInPlace(_this._deltaPosition);
  30186. if (_this._deltaRotation) {
  30187. _this.object.rotationQuaternion.multiplyInPlace(_this._deltaRotation);
  30188. }
  30189. };
  30190. //event and body object due to cannon's event-based architecture.
  30191. this.onCollide = function (e) {
  30192. if (!_this._onPhysicsCollideCallbacks.length)
  30193. return;
  30194. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  30195. if (otherImpostor) {
  30196. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  30197. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  30198. }).forEach(function (obj) {
  30199. obj.callback(_this, otherImpostor);
  30200. });
  30201. }
  30202. };
  30203. //sanity check!
  30204. if (!this.object) {
  30205. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  30206. return;
  30207. }
  30208. //legacy support for old syntax.
  30209. if (!this._scene && object.getScene) {
  30210. this._scene = object.getScene();
  30211. }
  30212. this._physicsEngine = this._scene.getPhysicsEngine();
  30213. if (!this._physicsEngine) {
  30214. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  30215. }
  30216. else {
  30217. //set the object's quaternion, if not set
  30218. if (!this.object.rotationQuaternion) {
  30219. if (this.object.rotation) {
  30220. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  30221. }
  30222. else {
  30223. this.object.rotationQuaternion = new BABYLON.Quaternion();
  30224. }
  30225. }
  30226. //default options params
  30227. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  30228. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  30229. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  30230. this._joints = [];
  30231. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  30232. if (!this.object.parent) {
  30233. this._init();
  30234. }
  30235. }
  30236. }
  30237. /**
  30238. * This function will completly initialize this impostor.
  30239. * It will create a new body - but only if this mesh has no parent.
  30240. * If it has, this impostor will not be used other than to define the impostor
  30241. * of the child mesh.
  30242. */
  30243. PhysicsImpostor.prototype._init = function () {
  30244. this._physicsEngine.removeImpostor(this);
  30245. this.physicsBody = null;
  30246. this._parent = this._parent || this._getPhysicsParent();
  30247. if (!this.parent) {
  30248. this._physicsEngine.addImpostor(this);
  30249. }
  30250. };
  30251. PhysicsImpostor.prototype._getPhysicsParent = function () {
  30252. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  30253. var parentMesh = this.object.parent;
  30254. return parentMesh.physicsImpostor;
  30255. }
  30256. return;
  30257. };
  30258. /**
  30259. * Should a new body be generated.
  30260. */
  30261. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  30262. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  30263. };
  30264. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  30265. this.forceUpdate();
  30266. };
  30267. /**
  30268. * Force a regeneration of this or the parent's impostor's body.
  30269. * Use under cautious - This will remove all joints already implemented.
  30270. */
  30271. PhysicsImpostor.prototype.forceUpdate = function () {
  30272. this._init();
  30273. if (this.parent) {
  30274. this.parent.forceUpdate();
  30275. }
  30276. };
  30277. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  30278. /*public get mesh(): AbstractMesh {
  30279. return this._mesh;
  30280. }*/
  30281. /**
  30282. * Gets the body that holds this impostor. Either its own, or its parent.
  30283. */
  30284. get: function () {
  30285. return this._parent ? this._parent.physicsBody : this._physicsBody;
  30286. },
  30287. /**
  30288. * Set the physics body. Used mainly by the physics engine/plugin
  30289. */
  30290. set: function (physicsBody) {
  30291. if (this._physicsBody) {
  30292. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  30293. }
  30294. this._physicsBody = physicsBody;
  30295. this.resetUpdateFlags();
  30296. },
  30297. enumerable: true,
  30298. configurable: true
  30299. });
  30300. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  30301. get: function () {
  30302. return this._parent;
  30303. },
  30304. enumerable: true,
  30305. configurable: true
  30306. });
  30307. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  30308. this._bodyUpdateRequired = false;
  30309. };
  30310. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  30311. if (this.object.getBoundingInfo) {
  30312. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  30313. return this.object.getBoundingInfo().boundingBox.extendSize.scale(2).multiply(this.object.scaling);
  30314. }
  30315. else {
  30316. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  30317. }
  30318. };
  30319. PhysicsImpostor.prototype.getObjectCenter = function () {
  30320. if (this.object.getBoundingInfo) {
  30321. return this.object.getBoundingInfo().boundingBox.center;
  30322. }
  30323. else {
  30324. return this.object.position;
  30325. }
  30326. };
  30327. /**
  30328. * Get a specific parametes from the options parameter.
  30329. */
  30330. PhysicsImpostor.prototype.getParam = function (paramName) {
  30331. return this._options[paramName];
  30332. };
  30333. /**
  30334. * Sets a specific parameter in the options given to the physics plugin
  30335. */
  30336. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  30337. this._options[paramName] = value;
  30338. this._bodyUpdateRequired = true;
  30339. };
  30340. /**
  30341. * Specifically change the body's mass option. Won't recreate the physics body object
  30342. */
  30343. PhysicsImpostor.prototype.setMass = function (mass) {
  30344. if (this.getParam("mass") !== mass) {
  30345. this.setParam("mass", mass);
  30346. }
  30347. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  30348. };
  30349. PhysicsImpostor.prototype.getLinearVelocity = function () {
  30350. return this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this);
  30351. };
  30352. /**
  30353. * Set the body's linear velocity.
  30354. */
  30355. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  30356. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  30357. };
  30358. PhysicsImpostor.prototype.getAngularVelocity = function () {
  30359. return this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this);
  30360. };
  30361. /**
  30362. * Set the body's linear velocity.
  30363. */
  30364. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  30365. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  30366. };
  30367. /**
  30368. * Execute a function with the physics plugin native code.
  30369. * Provide a function the will have two variables - the world object and the physics body object.
  30370. */
  30371. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  30372. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  30373. };
  30374. /**
  30375. * Register a function that will be executed before the physics world is stepping forward.
  30376. */
  30377. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  30378. this._onBeforePhysicsStepCallbacks.push(func);
  30379. };
  30380. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  30381. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  30382. if (index > -1) {
  30383. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  30384. }
  30385. else {
  30386. BABYLON.Tools.Warn("Function to remove was not found");
  30387. }
  30388. };
  30389. /**
  30390. * Register a function that will be executed after the physics step
  30391. */
  30392. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  30393. this._onAfterPhysicsStepCallbacks.push(func);
  30394. };
  30395. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  30396. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  30397. if (index > -1) {
  30398. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  30399. }
  30400. else {
  30401. BABYLON.Tools.Warn("Function to remove was not found");
  30402. }
  30403. };
  30404. /**
  30405. * register a function that will be executed when this impostor collides against a different body.
  30406. */
  30407. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  30408. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  30409. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  30410. };
  30411. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  30412. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  30413. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  30414. if (index > -1) {
  30415. this._onPhysicsCollideCallbacks.splice(index, 1);
  30416. }
  30417. else {
  30418. BABYLON.Tools.Warn("Function to remove was not found");
  30419. }
  30420. };
  30421. /**
  30422. * Apply a force
  30423. */
  30424. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  30425. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  30426. };
  30427. /**
  30428. * Apply an impulse
  30429. */
  30430. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  30431. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  30432. };
  30433. /**
  30434. * A help function to create a joint.
  30435. */
  30436. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  30437. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  30438. this.addJoint(otherImpostor, joint);
  30439. };
  30440. /**
  30441. * Add a joint to this impostor with a different impostor.
  30442. */
  30443. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  30444. this._joints.push({
  30445. otherImpostor: otherImpostor,
  30446. joint: joint
  30447. });
  30448. this._physicsEngine.addJoint(this, otherImpostor, joint);
  30449. };
  30450. /**
  30451. * Will keep this body still, in a sleep mode.
  30452. */
  30453. PhysicsImpostor.prototype.sleep = function () {
  30454. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  30455. };
  30456. /**
  30457. * Wake the body up.
  30458. */
  30459. PhysicsImpostor.prototype.wakeUp = function () {
  30460. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  30461. };
  30462. PhysicsImpostor.prototype.clone = function (newObject) {
  30463. if (!newObject)
  30464. return null;
  30465. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  30466. };
  30467. PhysicsImpostor.prototype.dispose = function () {
  30468. var _this = this;
  30469. //no dispose if no physics engine is available.
  30470. if (!this._physicsEngine) {
  30471. return;
  30472. }
  30473. this._joints.forEach(function (j) {
  30474. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  30475. });
  30476. //dispose the physics body
  30477. this._physicsEngine.removeImpostor(this);
  30478. if (this.parent) {
  30479. this.parent.forceUpdate();
  30480. }
  30481. else {
  30482. }
  30483. };
  30484. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  30485. this._deltaPosition.copyFrom(position);
  30486. };
  30487. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  30488. if (!this._deltaRotation) {
  30489. this._deltaRotation = new BABYLON.Quaternion();
  30490. }
  30491. this._deltaRotation.copyFrom(rotation);
  30492. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  30493. };
  30494. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  30495. //Impostor types
  30496. PhysicsImpostor.NoImpostor = 0;
  30497. PhysicsImpostor.SphereImpostor = 1;
  30498. PhysicsImpostor.BoxImpostor = 2;
  30499. PhysicsImpostor.PlaneImpostor = 3;
  30500. PhysicsImpostor.MeshImpostor = 4;
  30501. PhysicsImpostor.CylinderImpostor = 7;
  30502. PhysicsImpostor.ParticleImpostor = 8;
  30503. PhysicsImpostor.HeightmapImpostor = 9;
  30504. return PhysicsImpostor;
  30505. }());
  30506. BABYLON.PhysicsImpostor = PhysicsImpostor;
  30507. })(BABYLON || (BABYLON = {}));
  30508. var BABYLON;
  30509. (function (BABYLON) {
  30510. var PhysicsEngine = (function () {
  30511. function PhysicsEngine(gravity, _physicsPlugin) {
  30512. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  30513. this._physicsPlugin = _physicsPlugin;
  30514. //new methods and parameters
  30515. this._impostors = [];
  30516. this._joints = [];
  30517. if (!this._physicsPlugin.isSupported()) {
  30518. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  30519. + "Please make sure it is included.");
  30520. }
  30521. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  30522. this.setGravity(gravity);
  30523. this.setTimeStep();
  30524. }
  30525. PhysicsEngine.prototype.setGravity = function (gravity) {
  30526. this.gravity = gravity;
  30527. this._physicsPlugin.setGravity(this.gravity);
  30528. };
  30529. /**
  30530. * Set the time step of the physics engine.
  30531. * default is 1/60.
  30532. * To slow it down, enter 1/600 for example.
  30533. * To speed it up, 1/30
  30534. * @param {number} newTimeStep the new timestep to apply to this world.
  30535. */
  30536. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  30537. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  30538. this._physicsPlugin.setTimeStep(newTimeStep);
  30539. };
  30540. PhysicsEngine.prototype.dispose = function () {
  30541. this._impostors.forEach(function (impostor) {
  30542. impostor.dispose();
  30543. });
  30544. this._physicsPlugin.dispose();
  30545. };
  30546. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  30547. return this._physicsPlugin.name;
  30548. };
  30549. /**
  30550. * Adding a new impostor for the impostor tracking.
  30551. * This will be done by the impostor itself.
  30552. * @param {PhysicsImpostor} impostor the impostor to add
  30553. */
  30554. PhysicsEngine.prototype.addImpostor = function (impostor) {
  30555. impostor.uniqueId = this._impostors.push(impostor);
  30556. //if no parent, generate the body
  30557. if (!impostor.parent) {
  30558. this._physicsPlugin.generatePhysicsBody(impostor);
  30559. }
  30560. };
  30561. /**
  30562. * Remove an impostor from the engine.
  30563. * This impostor and its mesh will not longer be updated by the physics engine.
  30564. * @param {PhysicsImpostor} impostor the impostor to remove
  30565. */
  30566. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  30567. var index = this._impostors.indexOf(impostor);
  30568. if (index > -1) {
  30569. var removed = this._impostors.splice(index, 1);
  30570. //Is it needed?
  30571. if (removed.length) {
  30572. //this will also remove it from the world.
  30573. removed[0].physicsBody = null;
  30574. }
  30575. }
  30576. };
  30577. /**
  30578. * Add a joint to the physics engine
  30579. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  30580. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  30581. * @param {PhysicsJoint} the joint that will connect both impostors.
  30582. */
  30583. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  30584. var impostorJoint = {
  30585. mainImpostor: mainImpostor,
  30586. connectedImpostor: connectedImpostor,
  30587. joint: joint
  30588. };
  30589. joint.physicsPlugin = this._physicsPlugin;
  30590. this._joints.push(impostorJoint);
  30591. this._physicsPlugin.generateJoint(impostorJoint);
  30592. };
  30593. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  30594. var matchingJoints = this._joints.filter(function (impostorJoint) {
  30595. return (impostorJoint.connectedImpostor === connectedImpostor
  30596. && impostorJoint.joint === joint
  30597. && impostorJoint.mainImpostor === mainImpostor);
  30598. });
  30599. if (matchingJoints.length) {
  30600. this._physicsPlugin.removeJoint(matchingJoints[0]);
  30601. }
  30602. };
  30603. /**
  30604. * Called by the scene. no need to call it.
  30605. */
  30606. PhysicsEngine.prototype._step = function (delta) {
  30607. var _this = this;
  30608. //check if any mesh has no body / requires an update
  30609. this._impostors.forEach(function (impostor) {
  30610. if (impostor.isBodyInitRequired()) {
  30611. _this._physicsPlugin.generatePhysicsBody(impostor);
  30612. }
  30613. });
  30614. if (delta > 0.1) {
  30615. delta = 0.1;
  30616. }
  30617. else if (delta <= 0) {
  30618. delta = 1.0 / 60.0;
  30619. }
  30620. this._physicsPlugin.executeStep(delta, this._impostors);
  30621. };
  30622. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  30623. return this._physicsPlugin;
  30624. };
  30625. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  30626. for (var i = 0; i < this._impostors.length; ++i) {
  30627. if (this._impostors[i].object === object) {
  30628. return this._impostors[i];
  30629. }
  30630. }
  30631. };
  30632. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  30633. for (var i = 0; i < this._impostors.length; ++i) {
  30634. if (this._impostors[i].physicsBody === body) {
  30635. return this._impostors[i];
  30636. }
  30637. }
  30638. };
  30639. // Statics, Legacy support.
  30640. /**
  30641. * @Deprecated
  30642. *
  30643. */
  30644. PhysicsEngine.NoImpostor = BABYLON.PhysicsImpostor.NoImpostor;
  30645. PhysicsEngine.SphereImpostor = BABYLON.PhysicsImpostor.SphereImpostor;
  30646. PhysicsEngine.BoxImpostor = BABYLON.PhysicsImpostor.BoxImpostor;
  30647. PhysicsEngine.PlaneImpostor = BABYLON.PhysicsImpostor.PlaneImpostor;
  30648. PhysicsEngine.MeshImpostor = BABYLON.PhysicsImpostor.MeshImpostor;
  30649. PhysicsEngine.CylinderImpostor = BABYLON.PhysicsImpostor.CylinderImpostor;
  30650. PhysicsEngine.HeightmapImpostor = BABYLON.PhysicsImpostor.HeightmapImpostor;
  30651. PhysicsEngine.CapsuleImpostor = -1;
  30652. PhysicsEngine.ConeImpostor = -1;
  30653. PhysicsEngine.ConvexHullImpostor = -1;
  30654. PhysicsEngine.Epsilon = 0.001;
  30655. return PhysicsEngine;
  30656. }());
  30657. BABYLON.PhysicsEngine = PhysicsEngine;
  30658. })(BABYLON || (BABYLON = {}));
  30659. var BABYLON;
  30660. (function (BABYLON) {
  30661. var VertexData = (function () {
  30662. function VertexData() {
  30663. }
  30664. VertexData.prototype.set = function (data, kind) {
  30665. switch (kind) {
  30666. case BABYLON.VertexBuffer.PositionKind:
  30667. this.positions = data;
  30668. break;
  30669. case BABYLON.VertexBuffer.NormalKind:
  30670. this.normals = data;
  30671. break;
  30672. case BABYLON.VertexBuffer.UVKind:
  30673. this.uvs = data;
  30674. break;
  30675. case BABYLON.VertexBuffer.UV2Kind:
  30676. this.uvs2 = data;
  30677. break;
  30678. case BABYLON.VertexBuffer.UV3Kind:
  30679. this.uvs3 = data;
  30680. break;
  30681. case BABYLON.VertexBuffer.UV4Kind:
  30682. this.uvs4 = data;
  30683. break;
  30684. case BABYLON.VertexBuffer.UV5Kind:
  30685. this.uvs5 = data;
  30686. break;
  30687. case BABYLON.VertexBuffer.UV6Kind:
  30688. this.uvs6 = data;
  30689. break;
  30690. case BABYLON.VertexBuffer.ColorKind:
  30691. this.colors = data;
  30692. break;
  30693. case BABYLON.VertexBuffer.MatricesIndicesKind:
  30694. this.matricesIndices = data;
  30695. break;
  30696. case BABYLON.VertexBuffer.MatricesWeightsKind:
  30697. this.matricesWeights = data;
  30698. break;
  30699. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  30700. this.matricesIndicesExtra = data;
  30701. break;
  30702. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  30703. this.matricesWeightsExtra = data;
  30704. break;
  30705. }
  30706. };
  30707. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  30708. this._applyTo(mesh, updatable);
  30709. };
  30710. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  30711. this._applyTo(geometry, updatable);
  30712. };
  30713. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  30714. this._update(mesh);
  30715. };
  30716. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  30717. this._update(geometry);
  30718. };
  30719. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  30720. if (this.positions) {
  30721. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  30722. }
  30723. if (this.normals) {
  30724. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  30725. }
  30726. if (this.uvs) {
  30727. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  30728. }
  30729. if (this.uvs2) {
  30730. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  30731. }
  30732. if (this.uvs3) {
  30733. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  30734. }
  30735. if (this.uvs4) {
  30736. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  30737. }
  30738. if (this.uvs5) {
  30739. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  30740. }
  30741. if (this.uvs6) {
  30742. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  30743. }
  30744. if (this.colors) {
  30745. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  30746. }
  30747. if (this.matricesIndices) {
  30748. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  30749. }
  30750. if (this.matricesWeights) {
  30751. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  30752. }
  30753. if (this.matricesIndicesExtra) {
  30754. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  30755. }
  30756. if (this.matricesWeightsExtra) {
  30757. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  30758. }
  30759. if (this.indices) {
  30760. meshOrGeometry.setIndices(this.indices);
  30761. }
  30762. };
  30763. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  30764. if (this.positions) {
  30765. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  30766. }
  30767. if (this.normals) {
  30768. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  30769. }
  30770. if (this.uvs) {
  30771. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  30772. }
  30773. if (this.uvs2) {
  30774. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  30775. }
  30776. if (this.uvs3) {
  30777. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  30778. }
  30779. if (this.uvs4) {
  30780. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  30781. }
  30782. if (this.uvs5) {
  30783. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  30784. }
  30785. if (this.uvs6) {
  30786. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  30787. }
  30788. if (this.colors) {
  30789. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  30790. }
  30791. if (this.matricesIndices) {
  30792. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  30793. }
  30794. if (this.matricesWeights) {
  30795. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  30796. }
  30797. if (this.matricesIndicesExtra) {
  30798. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  30799. }
  30800. if (this.matricesWeightsExtra) {
  30801. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  30802. }
  30803. if (this.indices) {
  30804. meshOrGeometry.setIndices(this.indices);
  30805. }
  30806. };
  30807. VertexData.prototype.transform = function (matrix) {
  30808. var transformed = BABYLON.Vector3.Zero();
  30809. var index;
  30810. if (this.positions) {
  30811. var position = BABYLON.Vector3.Zero();
  30812. for (index = 0; index < this.positions.length; index += 3) {
  30813. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  30814. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  30815. this.positions[index] = transformed.x;
  30816. this.positions[index + 1] = transformed.y;
  30817. this.positions[index + 2] = transformed.z;
  30818. }
  30819. }
  30820. if (this.normals) {
  30821. var normal = BABYLON.Vector3.Zero();
  30822. for (index = 0; index < this.normals.length; index += 3) {
  30823. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  30824. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  30825. this.normals[index] = transformed.x;
  30826. this.normals[index + 1] = transformed.y;
  30827. this.normals[index + 2] = transformed.z;
  30828. }
  30829. }
  30830. };
  30831. VertexData.prototype.merge = function (other) {
  30832. if (other.indices) {
  30833. if (!this.indices) {
  30834. this.indices = [];
  30835. }
  30836. var offset = this.positions ? this.positions.length / 3 : 0;
  30837. for (var index = 0; index < other.indices.length; index++) {
  30838. //TODO check type - if Int32Array!
  30839. this.indices.push(other.indices[index] + offset);
  30840. }
  30841. }
  30842. this.positions = this._mergeElement(this.positions, other.positions);
  30843. this.normals = this._mergeElement(this.normals, other.normals);
  30844. this.uvs = this._mergeElement(this.uvs, other.uvs);
  30845. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  30846. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  30847. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  30848. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  30849. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  30850. this.colors = this._mergeElement(this.colors, other.colors);
  30851. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  30852. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  30853. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  30854. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  30855. };
  30856. VertexData.prototype._mergeElement = function (source, other) {
  30857. if (!other)
  30858. return source;
  30859. if (!source)
  30860. return other;
  30861. var len = other.length + source.length;
  30862. var isSrcTypedArray = source instanceof Float32Array;
  30863. var isOthTypedArray = other instanceof Float32Array;
  30864. // use non-loop method when the source is Float32Array
  30865. if (isSrcTypedArray) {
  30866. var ret32 = new Float32Array(len);
  30867. ret32.set(source);
  30868. ret32.set(other, source.length);
  30869. return ret32;
  30870. }
  30871. else if (!isOthTypedArray) {
  30872. return source.concat(other);
  30873. }
  30874. else {
  30875. var ret = source.slice(0); // copy source to a separate array
  30876. for (var i = 0, len = other.length; i < len; i++) {
  30877. ret.push(other[i]);
  30878. }
  30879. return ret;
  30880. }
  30881. };
  30882. VertexData.prototype.serialize = function () {
  30883. var serializationObject = this.serialize();
  30884. if (this.positions) {
  30885. serializationObject.positions = this.positions;
  30886. }
  30887. if (this.normals) {
  30888. serializationObject.normals = this.normals;
  30889. }
  30890. if (this.uvs) {
  30891. serializationObject.uvs = this.uvs;
  30892. }
  30893. if (this.uvs2) {
  30894. serializationObject.uvs2 = this.uvs2;
  30895. }
  30896. if (this.uvs3) {
  30897. serializationObject.uvs3 = this.uvs3;
  30898. }
  30899. if (this.uvs4) {
  30900. serializationObject.uvs4 = this.uvs4;
  30901. }
  30902. if (this.uvs5) {
  30903. serializationObject.uvs5 = this.uvs5;
  30904. }
  30905. if (this.uvs6) {
  30906. serializationObject.uvs6 = this.uvs6;
  30907. }
  30908. if (this.colors) {
  30909. serializationObject.colors = this.colors;
  30910. }
  30911. if (this.matricesIndices) {
  30912. serializationObject.matricesIndices = this.matricesIndices;
  30913. serializationObject.matricesIndices._isExpanded = true;
  30914. }
  30915. if (this.matricesWeights) {
  30916. serializationObject.matricesWeights = this.matricesWeights;
  30917. }
  30918. if (this.matricesIndicesExtra) {
  30919. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  30920. serializationObject.matricesIndicesExtra._isExpanded = true;
  30921. }
  30922. if (this.matricesWeightsExtra) {
  30923. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  30924. }
  30925. serializationObject.indices = this.indices;
  30926. return serializationObject;
  30927. };
  30928. // Statics
  30929. VertexData.ExtractFromMesh = function (mesh, copyWhenShared) {
  30930. return VertexData._ExtractFrom(mesh, copyWhenShared);
  30931. };
  30932. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared) {
  30933. return VertexData._ExtractFrom(geometry, copyWhenShared);
  30934. };
  30935. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared) {
  30936. var result = new VertexData();
  30937. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  30938. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared);
  30939. }
  30940. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  30941. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared);
  30942. }
  30943. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  30944. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared);
  30945. }
  30946. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  30947. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared);
  30948. }
  30949. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  30950. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared);
  30951. }
  30952. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  30953. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared);
  30954. }
  30955. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  30956. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared);
  30957. }
  30958. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  30959. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared);
  30960. }
  30961. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  30962. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared);
  30963. }
  30964. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  30965. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared);
  30966. }
  30967. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  30968. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared);
  30969. }
  30970. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  30971. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared);
  30972. }
  30973. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  30974. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared);
  30975. }
  30976. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  30977. return result;
  30978. };
  30979. VertexData.CreateRibbon = function (options) {
  30980. var pathArray = options.pathArray;
  30981. var closeArray = options.closeArray || false;
  30982. var closePath = options.closePath || false;
  30983. var invertUV = options.invertUV || false;
  30984. var defaultOffset = Math.floor(pathArray[0].length / 2);
  30985. var offset = options.offset || defaultOffset;
  30986. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  30987. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30988. var positions = [];
  30989. var indices = [];
  30990. var normals = [];
  30991. var uvs = [];
  30992. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  30993. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  30994. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  30995. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  30996. var minlg; // minimal length among all paths from pathArray
  30997. var lg = []; // array of path lengths : nb of vertex per path
  30998. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  30999. var p; // path iterator
  31000. var i; // point iterator
  31001. var j; // point iterator
  31002. // if single path in pathArray
  31003. if (pathArray.length < 2) {
  31004. var ar1 = [];
  31005. var ar2 = [];
  31006. for (i = 0; i < pathArray[0].length - offset; i++) {
  31007. ar1.push(pathArray[0][i]);
  31008. ar2.push(pathArray[0][i + offset]);
  31009. }
  31010. pathArray = [ar1, ar2];
  31011. }
  31012. // positions and horizontal distances (u)
  31013. var idc = 0;
  31014. var closePathCorr = (closePath) ? 1 : 0;
  31015. var path;
  31016. var l;
  31017. minlg = pathArray[0].length;
  31018. var vectlg;
  31019. var dist;
  31020. for (p = 0; p < pathArray.length; p++) {
  31021. uTotalDistance[p] = 0;
  31022. us[p] = [0];
  31023. path = pathArray[p];
  31024. l = path.length;
  31025. minlg = (minlg < l) ? minlg : l;
  31026. j = 0;
  31027. while (j < l) {
  31028. positions.push(path[j].x, path[j].y, path[j].z);
  31029. if (j > 0) {
  31030. vectlg = path[j].subtract(path[j - 1]).length();
  31031. dist = vectlg + uTotalDistance[p];
  31032. us[p].push(dist);
  31033. uTotalDistance[p] = dist;
  31034. }
  31035. j++;
  31036. }
  31037. if (closePath) {
  31038. j--;
  31039. positions.push(path[0].x, path[0].y, path[0].z);
  31040. vectlg = path[j].subtract(path[0]).length();
  31041. dist = vectlg + uTotalDistance[p];
  31042. us[p].push(dist);
  31043. uTotalDistance[p] = dist;
  31044. }
  31045. lg[p] = l + closePathCorr;
  31046. idx[p] = idc;
  31047. idc += (l + closePathCorr);
  31048. }
  31049. // vertical distances (v)
  31050. var path1;
  31051. var path2;
  31052. var vertex1;
  31053. var vertex2;
  31054. for (i = 0; i < minlg + closePathCorr; i++) {
  31055. vTotalDistance[i] = 0;
  31056. vs[i] = [0];
  31057. for (p = 0; p < pathArray.length - 1; p++) {
  31058. path1 = pathArray[p];
  31059. path2 = pathArray[p + 1];
  31060. if (i === minlg) {
  31061. vertex1 = path1[0];
  31062. vertex2 = path2[0];
  31063. }
  31064. else {
  31065. vertex1 = path1[i];
  31066. vertex2 = path2[i];
  31067. }
  31068. vectlg = vertex2.subtract(vertex1).length();
  31069. dist = vectlg + vTotalDistance[i];
  31070. vs[i].push(dist);
  31071. vTotalDistance[i] = dist;
  31072. }
  31073. if (closeArray) {
  31074. path1 = pathArray[p];
  31075. path2 = pathArray[0];
  31076. if (i === minlg) {
  31077. vertex2 = path2[0];
  31078. }
  31079. vectlg = vertex2.subtract(vertex1).length();
  31080. dist = vectlg + vTotalDistance[i];
  31081. vTotalDistance[i] = dist;
  31082. }
  31083. }
  31084. // uvs
  31085. var u;
  31086. var v;
  31087. for (p = 0; p < pathArray.length; p++) {
  31088. for (i = 0; i < minlg + closePathCorr; i++) {
  31089. u = us[p][i] / uTotalDistance[p];
  31090. v = vs[i][p] / vTotalDistance[i];
  31091. if (invertUV) {
  31092. uvs.push(v, u);
  31093. }
  31094. else {
  31095. uvs.push(u, v);
  31096. }
  31097. }
  31098. }
  31099. // indices
  31100. p = 0; // path index
  31101. var pi = 0; // positions array index
  31102. var l1 = lg[p] - 1; // path1 length
  31103. var l2 = lg[p + 1] - 1; // path2 length
  31104. var min = (l1 < l2) ? l1 : l2; // current path stop index
  31105. var shft = idx[1] - idx[0]; // shift
  31106. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  31107. while (pi <= min && p < path1nb) {
  31108. // 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
  31109. indices.push(pi, pi + shft, pi + 1);
  31110. indices.push(pi + shft + 1, pi + 1, pi + shft);
  31111. pi += 1;
  31112. if (pi === min) {
  31113. p++;
  31114. if (p === lg.length - 1) {
  31115. shft = idx[0] - idx[p];
  31116. l1 = lg[p] - 1;
  31117. l2 = lg[0] - 1;
  31118. }
  31119. else {
  31120. shft = idx[p + 1] - idx[p];
  31121. l1 = lg[p] - 1;
  31122. l2 = lg[p + 1] - 1;
  31123. }
  31124. pi = idx[p];
  31125. min = (l1 < l2) ? l1 + pi : l2 + pi;
  31126. }
  31127. }
  31128. // normals
  31129. VertexData.ComputeNormals(positions, indices, normals);
  31130. if (closePath) {
  31131. var indexFirst = 0;
  31132. var indexLast = 0;
  31133. for (p = 0; p < pathArray.length; p++) {
  31134. indexFirst = idx[p] * 3;
  31135. if (p + 1 < pathArray.length) {
  31136. indexLast = (idx[p + 1] - 1) * 3;
  31137. }
  31138. else {
  31139. indexLast = normals.length - 3;
  31140. }
  31141. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  31142. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  31143. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  31144. normals[indexLast] = normals[indexFirst];
  31145. normals[indexLast + 1] = normals[indexFirst + 1];
  31146. normals[indexLast + 2] = normals[indexFirst + 2];
  31147. }
  31148. }
  31149. // sides
  31150. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  31151. // Result
  31152. var vertexData = new VertexData();
  31153. vertexData.indices = indices;
  31154. vertexData.positions = positions;
  31155. vertexData.normals = normals;
  31156. vertexData.uvs = uvs;
  31157. if (closePath) {
  31158. vertexData._idx = idx;
  31159. }
  31160. return vertexData;
  31161. };
  31162. VertexData.CreateBox = function (options) {
  31163. var normalsSource = [
  31164. new BABYLON.Vector3(0, 0, 1),
  31165. new BABYLON.Vector3(0, 0, -1),
  31166. new BABYLON.Vector3(1, 0, 0),
  31167. new BABYLON.Vector3(-1, 0, 0),
  31168. new BABYLON.Vector3(0, 1, 0),
  31169. new BABYLON.Vector3(0, -1, 0)
  31170. ];
  31171. var indices = [];
  31172. var positions = [];
  31173. var normals = [];
  31174. var uvs = [];
  31175. var width = options.width || options.size || 1;
  31176. var height = options.height || options.size || 1;
  31177. var depth = options.depth || options.size || 1;
  31178. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31179. var faceUV = options.faceUV || new Array(6);
  31180. var faceColors = options.faceColors;
  31181. var colors = [];
  31182. // default face colors and UV if undefined
  31183. for (var f = 0; f < 6; f++) {
  31184. if (faceUV[f] === undefined) {
  31185. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  31186. }
  31187. if (faceColors && faceColors[f] === undefined) {
  31188. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  31189. }
  31190. }
  31191. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  31192. // Create each face in turn.
  31193. for (var index = 0; index < normalsSource.length; index++) {
  31194. var normal = normalsSource[index];
  31195. // Get two vectors perpendicular to the face normal and to each other.
  31196. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  31197. var side2 = BABYLON.Vector3.Cross(normal, side1);
  31198. // Six indices (two triangles) per face.
  31199. var verticesLength = positions.length / 3;
  31200. indices.push(verticesLength);
  31201. indices.push(verticesLength + 1);
  31202. indices.push(verticesLength + 2);
  31203. indices.push(verticesLength);
  31204. indices.push(verticesLength + 2);
  31205. indices.push(verticesLength + 3);
  31206. // Four vertices per face.
  31207. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  31208. positions.push(vertex.x, vertex.y, vertex.z);
  31209. normals.push(normal.x, normal.y, normal.z);
  31210. uvs.push(faceUV[index].z, faceUV[index].w);
  31211. if (faceColors) {
  31212. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  31213. }
  31214. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  31215. positions.push(vertex.x, vertex.y, vertex.z);
  31216. normals.push(normal.x, normal.y, normal.z);
  31217. uvs.push(faceUV[index].x, faceUV[index].w);
  31218. if (faceColors) {
  31219. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  31220. }
  31221. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  31222. positions.push(vertex.x, vertex.y, vertex.z);
  31223. normals.push(normal.x, normal.y, normal.z);
  31224. uvs.push(faceUV[index].x, faceUV[index].y);
  31225. if (faceColors) {
  31226. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  31227. }
  31228. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  31229. positions.push(vertex.x, vertex.y, vertex.z);
  31230. normals.push(normal.x, normal.y, normal.z);
  31231. uvs.push(faceUV[index].z, faceUV[index].y);
  31232. if (faceColors) {
  31233. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  31234. }
  31235. }
  31236. // sides
  31237. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  31238. // Result
  31239. var vertexData = new VertexData();
  31240. vertexData.indices = indices;
  31241. vertexData.positions = positions;
  31242. vertexData.normals = normals;
  31243. vertexData.uvs = uvs;
  31244. if (faceColors) {
  31245. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  31246. vertexData.colors = totalColors;
  31247. }
  31248. return vertexData;
  31249. };
  31250. VertexData.CreateSphere = function (options) {
  31251. var segments = options.segments || 32;
  31252. var diameterX = options.diameterX || options.diameter || 1;
  31253. var diameterY = options.diameterY || options.diameter || 1;
  31254. var diameterZ = options.diameterZ || options.diameter || 1;
  31255. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  31256. var slice = (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  31257. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31258. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  31259. var totalZRotationSteps = 2 + segments;
  31260. var totalYRotationSteps = 2 * totalZRotationSteps;
  31261. var indices = [];
  31262. var positions = [];
  31263. var normals = [];
  31264. var uvs = [];
  31265. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  31266. var normalizedZ = zRotationStep / totalZRotationSteps;
  31267. var angleZ = normalizedZ * Math.PI * slice;
  31268. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  31269. var normalizedY = yRotationStep / totalYRotationSteps;
  31270. var angleY = normalizedY * Math.PI * 2 * arc;
  31271. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  31272. var rotationY = BABYLON.Matrix.RotationY(angleY);
  31273. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  31274. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  31275. var vertex = complete.multiply(radius);
  31276. var normal = complete.divide(radius).normalize();
  31277. positions.push(vertex.x, vertex.y, vertex.z);
  31278. normals.push(normal.x, normal.y, normal.z);
  31279. uvs.push(normalizedY, normalizedZ);
  31280. }
  31281. if (zRotationStep > 0) {
  31282. var verticesCount = positions.length / 3;
  31283. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  31284. indices.push((firstIndex));
  31285. indices.push((firstIndex + 1));
  31286. indices.push(firstIndex + totalYRotationSteps + 1);
  31287. indices.push((firstIndex + totalYRotationSteps + 1));
  31288. indices.push((firstIndex + 1));
  31289. indices.push((firstIndex + totalYRotationSteps + 2));
  31290. }
  31291. }
  31292. }
  31293. // Sides
  31294. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  31295. // Result
  31296. var vertexData = new VertexData();
  31297. vertexData.indices = indices;
  31298. vertexData.positions = positions;
  31299. vertexData.normals = normals;
  31300. vertexData.uvs = uvs;
  31301. return vertexData;
  31302. };
  31303. // Cylinder and cone
  31304. VertexData.CreateCylinder = function (options) {
  31305. var height = options.height || 2;
  31306. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  31307. var diameterBottom = options.diameterBottom || options.diameter || 1;
  31308. var tessellation = options.tessellation || 24;
  31309. var subdivisions = options.subdivisions || 1;
  31310. var hasRings = options.hasRings;
  31311. var enclose = options.enclose;
  31312. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  31313. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31314. var faceUV = options.faceUV || new Array(3);
  31315. var faceColors = options.faceColors;
  31316. // default face colors and UV if undefined
  31317. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  31318. var ringNb = (hasRings) ? subdivisions : 1;
  31319. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  31320. var f;
  31321. for (f = 0; f < surfaceNb; f++) {
  31322. if (faceColors && faceColors[f] === undefined) {
  31323. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  31324. }
  31325. }
  31326. for (f = 0; f < surfaceNb; f++) {
  31327. if (faceUV && faceUV[f] === undefined) {
  31328. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  31329. }
  31330. }
  31331. var indices = [];
  31332. var positions = [];
  31333. var normals = [];
  31334. var uvs = [];
  31335. var colors = [];
  31336. var angle_step = Math.PI * 2 * arc / tessellation;
  31337. var angle;
  31338. var h;
  31339. var radius;
  31340. var tan = (diameterBottom - diameterTop) / 2 / height;
  31341. var ringVertex = BABYLON.Vector3.Zero();
  31342. var ringNormal = BABYLON.Vector3.Zero();
  31343. var ringFirstVertex = BABYLON.Vector3.Zero();
  31344. var ringFirstNormal = BABYLON.Vector3.Zero();
  31345. var quadNormal = BABYLON.Vector3.Zero();
  31346. var Y = BABYLON.Axis.Y;
  31347. // positions, normals, uvs
  31348. var i;
  31349. var j;
  31350. var r;
  31351. var ringIdx = 1;
  31352. var s = 1; // surface index
  31353. var cs = 0;
  31354. var v = 0;
  31355. for (i = 0; i <= subdivisions; i++) {
  31356. h = i / subdivisions;
  31357. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  31358. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  31359. for (r = 0; r < ringIdx; r++) {
  31360. if (hasRings) {
  31361. s += r;
  31362. }
  31363. if (enclose) {
  31364. s += 2 * r;
  31365. }
  31366. for (j = 0; j <= tessellation; j++) {
  31367. angle = j * angle_step;
  31368. // position
  31369. ringVertex.x = Math.cos(-angle) * radius;
  31370. ringVertex.y = -height / 2 + h * height;
  31371. ringVertex.z = Math.sin(-angle) * radius;
  31372. // normal
  31373. if (diameterTop === 0 && i === subdivisions) {
  31374. // if no top cap, reuse former normals
  31375. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  31376. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  31377. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  31378. }
  31379. else {
  31380. ringNormal.x = ringVertex.x;
  31381. ringNormal.z = ringVertex.z;
  31382. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  31383. ringNormal.normalize();
  31384. }
  31385. // keep first ring vertex values for enclose
  31386. if (j === 0) {
  31387. ringFirstVertex.copyFrom(ringVertex);
  31388. ringFirstNormal.copyFrom(ringNormal);
  31389. }
  31390. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  31391. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  31392. if (hasRings) {
  31393. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  31394. }
  31395. else {
  31396. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  31397. }
  31398. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  31399. if (faceColors) {
  31400. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  31401. }
  31402. }
  31403. // if enclose, add four vertices and their dedicated normals
  31404. if (arc !== 1 && enclose) {
  31405. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  31406. positions.push(0, ringVertex.y, 0);
  31407. positions.push(0, ringVertex.y, 0);
  31408. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  31409. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  31410. quadNormal.normalize();
  31411. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  31412. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  31413. quadNormal.normalize();
  31414. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  31415. if (hasRings) {
  31416. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  31417. }
  31418. else {
  31419. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  31420. }
  31421. uvs.push(faceUV[s + 1].x, v);
  31422. uvs.push(faceUV[s + 1].z, v);
  31423. if (hasRings) {
  31424. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  31425. }
  31426. else {
  31427. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  31428. }
  31429. uvs.push(faceUV[s + 2].x, v);
  31430. uvs.push(faceUV[s + 2].z, v);
  31431. if (faceColors) {
  31432. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  31433. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  31434. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  31435. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  31436. }
  31437. }
  31438. if (cs !== s) {
  31439. cs = s;
  31440. }
  31441. }
  31442. }
  31443. // indices
  31444. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  31445. var s;
  31446. i = 0;
  31447. for (s = 0; s < subdivisions; s++) {
  31448. for (j = 0; j < tessellation; j++) {
  31449. var i0 = i * (e + 1) + j;
  31450. var i1 = (i + 1) * (e + 1) + j;
  31451. var i2 = i * (e + 1) + (j + 1);
  31452. var i3 = (i + 1) * (e + 1) + (j + 1);
  31453. indices.push(i0, i1, i2);
  31454. indices.push(i3, i2, i1);
  31455. }
  31456. if (arc !== 1 && enclose) {
  31457. indices.push(i0 + 2, i1 + 2, i2 + 2);
  31458. indices.push(i3 + 2, i2 + 2, i1 + 2);
  31459. indices.push(i0 + 4, i1 + 4, i2 + 4);
  31460. indices.push(i3 + 4, i2 + 4, i1 + 4);
  31461. }
  31462. i = (hasRings) ? (i + 2) : (i + 1);
  31463. }
  31464. // Caps
  31465. var createCylinderCap = function (isTop) {
  31466. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  31467. if (radius === 0) {
  31468. return;
  31469. }
  31470. // Cap positions, normals & uvs
  31471. var angle;
  31472. var circleVector;
  31473. var i;
  31474. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  31475. var c;
  31476. if (faceColors) {
  31477. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  31478. }
  31479. // cap center
  31480. var vbase = positions.length / 3;
  31481. var offset = isTop ? height / 2 : -height / 2;
  31482. var center = new BABYLON.Vector3(0, offset, 0);
  31483. positions.push(center.x, center.y, center.z);
  31484. normals.push(0, isTop ? 1 : -1, 0);
  31485. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  31486. if (faceColors) {
  31487. colors.push(c.r, c.g, c.b, c.a);
  31488. }
  31489. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  31490. for (i = 0; i <= tessellation; i++) {
  31491. angle = Math.PI * 2 * i * arc / tessellation;
  31492. var cos = Math.cos(-angle);
  31493. var sin = Math.sin(-angle);
  31494. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  31495. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  31496. positions.push(circleVector.x, circleVector.y, circleVector.z);
  31497. normals.push(0, isTop ? 1 : -1, 0);
  31498. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  31499. if (faceColors) {
  31500. colors.push(c.r, c.g, c.b, c.a);
  31501. }
  31502. }
  31503. // Cap indices
  31504. for (i = 0; i < tessellation; i++) {
  31505. if (!isTop) {
  31506. indices.push(vbase);
  31507. indices.push(vbase + (i + 1));
  31508. indices.push(vbase + (i + 2));
  31509. }
  31510. else {
  31511. indices.push(vbase);
  31512. indices.push(vbase + (i + 2));
  31513. indices.push(vbase + (i + 1));
  31514. }
  31515. }
  31516. };
  31517. // add caps to geometry
  31518. createCylinderCap(false);
  31519. createCylinderCap(true);
  31520. // Sides
  31521. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  31522. var vertexData = new VertexData();
  31523. vertexData.indices = indices;
  31524. vertexData.positions = positions;
  31525. vertexData.normals = normals;
  31526. vertexData.uvs = uvs;
  31527. if (faceColors) {
  31528. vertexData.colors = colors;
  31529. }
  31530. return vertexData;
  31531. };
  31532. VertexData.CreateTorus = function (options) {
  31533. var indices = [];
  31534. var positions = [];
  31535. var normals = [];
  31536. var uvs = [];
  31537. var diameter = options.diameter || 1;
  31538. var thickness = options.thickness || 0.5;
  31539. var tessellation = options.tessellation || 16;
  31540. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31541. var stride = tessellation + 1;
  31542. for (var i = 0; i <= tessellation; i++) {
  31543. var u = i / tessellation;
  31544. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  31545. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  31546. for (var j = 0; j <= tessellation; j++) {
  31547. var v = 1 - j / tessellation;
  31548. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  31549. var dx = Math.cos(innerAngle);
  31550. var dy = Math.sin(innerAngle);
  31551. // Create a vertex.
  31552. var normal = new BABYLON.Vector3(dx, dy, 0);
  31553. var position = normal.scale(thickness / 2);
  31554. var textureCoordinate = new BABYLON.Vector2(u, v);
  31555. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  31556. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  31557. positions.push(position.x, position.y, position.z);
  31558. normals.push(normal.x, normal.y, normal.z);
  31559. uvs.push(textureCoordinate.x, textureCoordinate.y);
  31560. // And create indices for two triangles.
  31561. var nextI = (i + 1) % stride;
  31562. var nextJ = (j + 1) % stride;
  31563. indices.push(i * stride + j);
  31564. indices.push(i * stride + nextJ);
  31565. indices.push(nextI * stride + j);
  31566. indices.push(i * stride + nextJ);
  31567. indices.push(nextI * stride + nextJ);
  31568. indices.push(nextI * stride + j);
  31569. }
  31570. }
  31571. // Sides
  31572. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  31573. // Result
  31574. var vertexData = new VertexData();
  31575. vertexData.indices = indices;
  31576. vertexData.positions = positions;
  31577. vertexData.normals = normals;
  31578. vertexData.uvs = uvs;
  31579. return vertexData;
  31580. };
  31581. VertexData.CreateLineSystem = function (options) {
  31582. var indices = [];
  31583. var positions = [];
  31584. var lines = options.lines;
  31585. var idx = 0;
  31586. for (var l = 0; l < lines.length; l++) {
  31587. var points = lines[l];
  31588. for (var index = 0; index < points.length; index++) {
  31589. positions.push(points[index].x, points[index].y, points[index].z);
  31590. if (index > 0) {
  31591. indices.push(idx - 1);
  31592. indices.push(idx);
  31593. }
  31594. idx++;
  31595. }
  31596. }
  31597. var vertexData = new VertexData();
  31598. vertexData.indices = indices;
  31599. vertexData.positions = positions;
  31600. return vertexData;
  31601. };
  31602. VertexData.CreateDashedLines = function (options) {
  31603. var dashSize = options.dashSize || 3;
  31604. var gapSize = options.gapSize || 1;
  31605. var dashNb = options.dashNb || 200;
  31606. var points = options.points;
  31607. var positions = new Array();
  31608. var indices = new Array();
  31609. var curvect = BABYLON.Vector3.Zero();
  31610. var lg = 0;
  31611. var nb = 0;
  31612. var shft = 0;
  31613. var dashshft = 0;
  31614. var curshft = 0;
  31615. var idx = 0;
  31616. var i = 0;
  31617. for (i = 0; i < points.length - 1; i++) {
  31618. points[i + 1].subtractToRef(points[i], curvect);
  31619. lg += curvect.length();
  31620. }
  31621. shft = lg / dashNb;
  31622. dashshft = dashSize * shft / (dashSize + gapSize);
  31623. for (i = 0; i < points.length - 1; i++) {
  31624. points[i + 1].subtractToRef(points[i], curvect);
  31625. nb = Math.floor(curvect.length() / shft);
  31626. curvect.normalize();
  31627. for (var j = 0; j < nb; j++) {
  31628. curshft = shft * j;
  31629. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  31630. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  31631. indices.push(idx, idx + 1);
  31632. idx += 2;
  31633. }
  31634. }
  31635. // Result
  31636. var vertexData = new VertexData();
  31637. vertexData.positions = positions;
  31638. vertexData.indices = indices;
  31639. return vertexData;
  31640. };
  31641. VertexData.CreateGround = function (options) {
  31642. var indices = [];
  31643. var positions = [];
  31644. var normals = [];
  31645. var uvs = [];
  31646. var row, col;
  31647. var width = options.width || 1;
  31648. var height = options.height || 1;
  31649. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  31650. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  31651. for (row = 0; row <= subdivisionsY; row++) {
  31652. for (col = 0; col <= subdivisionsX; col++) {
  31653. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  31654. var normal = new BABYLON.Vector3(0, 1.0, 0);
  31655. positions.push(position.x, position.y, position.z);
  31656. normals.push(normal.x, normal.y, normal.z);
  31657. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsX);
  31658. }
  31659. }
  31660. for (row = 0; row < subdivisionsY; row++) {
  31661. for (col = 0; col < subdivisionsX; col++) {
  31662. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  31663. indices.push(col + 1 + row * (subdivisionsX + 1));
  31664. indices.push(col + row * (subdivisionsX + 1));
  31665. indices.push(col + (row + 1) * (subdivisionsX + 1));
  31666. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  31667. indices.push(col + row * (subdivisionsX + 1));
  31668. }
  31669. }
  31670. // Result
  31671. var vertexData = new VertexData();
  31672. vertexData.indices = indices;
  31673. vertexData.positions = positions;
  31674. vertexData.normals = normals;
  31675. vertexData.uvs = uvs;
  31676. return vertexData;
  31677. };
  31678. VertexData.CreateTiledGround = function (options) {
  31679. var xmin = options.xmin || -1.0;
  31680. var zmin = options.zmin || -1.0;
  31681. var xmax = options.xmax || 1.0;
  31682. var zmax = options.zmax || 1.0;
  31683. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  31684. var precision = options.precision || { w: 1, h: 1 };
  31685. var indices = [];
  31686. var positions = [];
  31687. var normals = [];
  31688. var uvs = [];
  31689. var row, col, tileRow, tileCol;
  31690. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  31691. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  31692. precision.w = (precision.w < 1) ? 1 : precision.w;
  31693. precision.h = (precision.h < 1) ? 1 : precision.h;
  31694. var tileSize = {
  31695. 'w': (xmax - xmin) / subdivisions.w,
  31696. 'h': (zmax - zmin) / subdivisions.h
  31697. };
  31698. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  31699. // Indices
  31700. var base = positions.length / 3;
  31701. var rowLength = precision.w + 1;
  31702. for (row = 0; row < precision.h; row++) {
  31703. for (col = 0; col < precision.w; col++) {
  31704. var square = [
  31705. base + col + row * rowLength,
  31706. base + (col + 1) + row * rowLength,
  31707. base + (col + 1) + (row + 1) * rowLength,
  31708. base + col + (row + 1) * rowLength
  31709. ];
  31710. indices.push(square[1]);
  31711. indices.push(square[2]);
  31712. indices.push(square[3]);
  31713. indices.push(square[0]);
  31714. indices.push(square[1]);
  31715. indices.push(square[3]);
  31716. }
  31717. }
  31718. // Position, normals and uvs
  31719. var position = BABYLON.Vector3.Zero();
  31720. var normal = new BABYLON.Vector3(0, 1.0, 0);
  31721. for (row = 0; row <= precision.h; row++) {
  31722. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  31723. for (col = 0; col <= precision.w; col++) {
  31724. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  31725. position.y = 0;
  31726. positions.push(position.x, position.y, position.z);
  31727. normals.push(normal.x, normal.y, normal.z);
  31728. uvs.push(col / precision.w, row / precision.h);
  31729. }
  31730. }
  31731. }
  31732. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  31733. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  31734. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  31735. }
  31736. }
  31737. // Result
  31738. var vertexData = new VertexData();
  31739. vertexData.indices = indices;
  31740. vertexData.positions = positions;
  31741. vertexData.normals = normals;
  31742. vertexData.uvs = uvs;
  31743. return vertexData;
  31744. };
  31745. VertexData.CreateGroundFromHeightMap = function (options) {
  31746. var indices = [];
  31747. var positions = [];
  31748. var normals = [];
  31749. var uvs = [];
  31750. var row, col;
  31751. // Vertices
  31752. for (row = 0; row <= options.subdivisions; row++) {
  31753. for (col = 0; col <= options.subdivisions; col++) {
  31754. 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));
  31755. // Compute height
  31756. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  31757. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  31758. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  31759. var r = options.buffer[pos] / 255.0;
  31760. var g = options.buffer[pos + 1] / 255.0;
  31761. var b = options.buffer[pos + 2] / 255.0;
  31762. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  31763. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  31764. // Add vertex
  31765. positions.push(position.x, position.y, position.z);
  31766. normals.push(0, 0, 0);
  31767. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  31768. }
  31769. }
  31770. // Indices
  31771. for (row = 0; row < options.subdivisions; row++) {
  31772. for (col = 0; col < options.subdivisions; col++) {
  31773. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  31774. indices.push(col + 1 + row * (options.subdivisions + 1));
  31775. indices.push(col + row * (options.subdivisions + 1));
  31776. indices.push(col + (row + 1) * (options.subdivisions + 1));
  31777. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  31778. indices.push(col + row * (options.subdivisions + 1));
  31779. }
  31780. }
  31781. // Normals
  31782. VertexData.ComputeNormals(positions, indices, normals);
  31783. // Result
  31784. var vertexData = new VertexData();
  31785. vertexData.indices = indices;
  31786. vertexData.positions = positions;
  31787. vertexData.normals = normals;
  31788. vertexData.uvs = uvs;
  31789. return vertexData;
  31790. };
  31791. VertexData.CreatePlane = function (options) {
  31792. var indices = [];
  31793. var positions = [];
  31794. var normals = [];
  31795. var uvs = [];
  31796. var width = options.width || options.size || 1;
  31797. var height = options.height || options.size || 1;
  31798. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31799. // Vertices
  31800. var halfWidth = width / 2.0;
  31801. var halfHeight = height / 2.0;
  31802. positions.push(-halfWidth, -halfHeight, 0);
  31803. normals.push(0, 0, -1.0);
  31804. uvs.push(0.0, 0.0);
  31805. positions.push(halfWidth, -halfHeight, 0);
  31806. normals.push(0, 0, -1.0);
  31807. uvs.push(1.0, 0.0);
  31808. positions.push(halfWidth, halfHeight, 0);
  31809. normals.push(0, 0, -1.0);
  31810. uvs.push(1.0, 1.0);
  31811. positions.push(-halfWidth, halfHeight, 0);
  31812. normals.push(0, 0, -1.0);
  31813. uvs.push(0.0, 1.0);
  31814. // Indices
  31815. indices.push(0);
  31816. indices.push(1);
  31817. indices.push(2);
  31818. indices.push(0);
  31819. indices.push(2);
  31820. indices.push(3);
  31821. // Sides
  31822. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  31823. // Result
  31824. var vertexData = new VertexData();
  31825. vertexData.indices = indices;
  31826. vertexData.positions = positions;
  31827. vertexData.normals = normals;
  31828. vertexData.uvs = uvs;
  31829. return vertexData;
  31830. };
  31831. VertexData.CreateDisc = function (options) {
  31832. var positions = [];
  31833. var indices = [];
  31834. var normals = [];
  31835. var uvs = [];
  31836. var radius = options.radius || 0.5;
  31837. var tessellation = options.tessellation || 64;
  31838. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  31839. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31840. // positions and uvs
  31841. positions.push(0, 0, 0); // disc center first
  31842. uvs.push(0.5, 0.5);
  31843. var theta = Math.PI * 2 * arc;
  31844. var step = theta / tessellation;
  31845. for (var a = 0; a < theta; a += step) {
  31846. var x = Math.cos(a);
  31847. var y = Math.sin(a);
  31848. var u = (x + 1) / 2;
  31849. var v = (1 - y) / 2;
  31850. positions.push(radius * x, radius * y, 0);
  31851. uvs.push(u, v);
  31852. }
  31853. if (arc === 1) {
  31854. positions.push(positions[3], positions[4], positions[5]); // close the circle
  31855. uvs.push(uvs[2], uvs[3]);
  31856. }
  31857. //indices
  31858. var vertexNb = positions.length / 3;
  31859. for (var i = 1; i < vertexNb - 1; i++) {
  31860. indices.push(i + 1, 0, i);
  31861. }
  31862. // result
  31863. VertexData.ComputeNormals(positions, indices, normals);
  31864. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  31865. var vertexData = new VertexData();
  31866. vertexData.indices = indices;
  31867. vertexData.positions = positions;
  31868. vertexData.normals = normals;
  31869. vertexData.uvs = uvs;
  31870. return vertexData;
  31871. };
  31872. VertexData.CreateIcoSphere = function (options) {
  31873. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31874. var radius = options.radius || 1;
  31875. var flat = (options.flat === undefined) ? true : options.flat;
  31876. var subdivisions = options.subdivisions || 4;
  31877. var radiusX = options.radiusX || radius;
  31878. var radiusY = options.radiusY || radius;
  31879. var radiusZ = options.radiusZ || radius;
  31880. var t = (1 + Math.sqrt(5)) / 2;
  31881. // 12 vertex x,y,z
  31882. var ico_vertices = [
  31883. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  31884. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  31885. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  31886. ];
  31887. // index of 3 vertex makes a face of icopshere
  31888. var ico_indices = [
  31889. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  31890. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  31891. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  31892. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  31893. ];
  31894. // vertex for uv have aliased position, not for UV
  31895. var vertices_unalias_id = [
  31896. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  31897. // vertex alias
  31898. 0,
  31899. 2,
  31900. 3,
  31901. 3,
  31902. 3,
  31903. 4,
  31904. 7,
  31905. 8,
  31906. 9,
  31907. 9,
  31908. 10,
  31909. 11 // 23: B + 12
  31910. ];
  31911. // uv as integer step (not pixels !)
  31912. var ico_vertexuv = [
  31913. 5, 1, 3, 1, 6, 4, 0, 0,
  31914. 5, 3, 4, 2, 2, 2, 4, 0,
  31915. 2, 0, 1, 1, 6, 0, 6, 2,
  31916. // vertex alias (for same vertex on different faces)
  31917. 0, 4,
  31918. 3, 3,
  31919. 4, 4,
  31920. 3, 1,
  31921. 4, 2,
  31922. 4, 4,
  31923. 0, 2,
  31924. 1, 1,
  31925. 2, 2,
  31926. 3, 3,
  31927. 1, 3,
  31928. 2, 4 // 23: B + 12
  31929. ];
  31930. // Vertices[0, 1, ...9, A, B] : position on UV plane
  31931. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  31932. // First island of uv mapping
  31933. // v = 4h 3+ 2
  31934. // v = 3h 9+ 4
  31935. // v = 2h 9+ 5 B
  31936. // v = 1h 9 1 0
  31937. // v = 0h 3 8 7 A
  31938. // u = 0 1 2 3 4 5 6 *a
  31939. // Second island of uv mapping
  31940. // v = 4h 0+ B+ 4+
  31941. // v = 3h A+ 2+
  31942. // v = 2h 7+ 6 3+
  31943. // v = 1h 8+ 3+
  31944. // v = 0h
  31945. // u = 0 1 2 3 4 5 6 *a
  31946. // Face layout on texture UV mapping
  31947. // ============
  31948. // \ 4 /\ 16 / ======
  31949. // \ / \ / /\ 11 /
  31950. // \/ 7 \/ / \ /
  31951. // ======= / 10 \/
  31952. // /\ 17 /\ =======
  31953. // / \ / \ \ 15 /\
  31954. // / 8 \/ 12 \ \ / \
  31955. // ============ \/ 6 \
  31956. // \ 18 /\ ============
  31957. // \ / \ \ 5 /\ 0 /
  31958. // \/ 13 \ \ / \ /
  31959. // ======= \/ 1 \/
  31960. // =============
  31961. // /\ 19 /\ 2 /\
  31962. // / \ / \ / \
  31963. // / 14 \/ 9 \/ 3 \
  31964. // ===================
  31965. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  31966. var ustep = 138 / 1024;
  31967. var vstep = 239 / 1024;
  31968. var uoffset = 60 / 1024;
  31969. var voffset = 26 / 1024;
  31970. // Second island should have margin, not to touch the first island
  31971. // avoid any borderline artefact in pixel rounding
  31972. var island_u_offset = -40 / 1024;
  31973. var island_v_offset = +20 / 1024;
  31974. // face is either island 0 or 1 :
  31975. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  31976. var island = [
  31977. 0, 0, 0, 0, 1,
  31978. 0, 0, 1, 1, 0,
  31979. 0, 0, 1, 1, 0,
  31980. 0, 1, 1, 1, 0 // 15 - 19
  31981. ];
  31982. var indices = [];
  31983. var positions = [];
  31984. var normals = [];
  31985. var uvs = [];
  31986. var current_indice = 0;
  31987. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  31988. var face_vertex_pos = new Array(3);
  31989. var face_vertex_uv = new Array(3);
  31990. var v012;
  31991. for (v012 = 0; v012 < 3; v012++) {
  31992. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  31993. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  31994. }
  31995. // create all with normals
  31996. for (var face = 0; face < 20; face++) {
  31997. // 3 vertex per face
  31998. for (v012 = 0; v012 < 3; v012++) {
  31999. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  32000. var v_id = ico_indices[3 * face + v012];
  32001. // vertex have 3D position (x,y,z)
  32002. 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]);
  32003. // Normalize to get normal, then scale to radius
  32004. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  32005. // uv Coordinates from vertex ID
  32006. 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);
  32007. }
  32008. // Subdivide the face (interpolate pos, norm, uv)
  32009. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  32010. // - norm is linear interpolation of vertex corner normal
  32011. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  32012. // - uv is linear interpolation
  32013. //
  32014. // Topology is as below for sub-divide by 2
  32015. // vertex shown as v0,v1,v2
  32016. // interp index is i1 to progress in range [v0,v1[
  32017. // interp index is i2 to progress in range [v0,v2[
  32018. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  32019. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  32020. //
  32021. //
  32022. // i2 v2
  32023. // ^ ^
  32024. // / / \
  32025. // / / \
  32026. // / / \
  32027. // / / (0,1) \
  32028. // / #---------\
  32029. // / / \ (0,0)'/ \
  32030. // / / \ / \
  32031. // / / \ / \
  32032. // / / (0,0) \ / (1,0) \
  32033. // / #---------#---------\
  32034. // v0 v1
  32035. //
  32036. // --------------------> i1
  32037. //
  32038. // interp of (i1,i2):
  32039. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  32040. // along i1 : lerp(x0,x1, i1/(S-i2))
  32041. //
  32042. // centroid of triangle is needed to get help normal computation
  32043. // (c1,c2) are used for centroid location
  32044. var interp_vertex = function (i1, i2, c1, c2) {
  32045. // vertex is interpolated from
  32046. // - face_vertex_pos[0..2]
  32047. // - face_vertex_uv[0..2]
  32048. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  32049. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  32050. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  32051. pos_interp.normalize();
  32052. var vertex_normal;
  32053. if (flat) {
  32054. // in flat mode, recalculate normal as face centroid normal
  32055. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  32056. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  32057. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  32058. }
  32059. else {
  32060. // in smooth mode, recalculate normal from each single vertex position
  32061. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  32062. }
  32063. // Vertex normal need correction due to X,Y,Z radius scaling
  32064. vertex_normal.x /= radiusX;
  32065. vertex_normal.y /= radiusY;
  32066. vertex_normal.z /= radiusZ;
  32067. vertex_normal.normalize();
  32068. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  32069. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  32070. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  32071. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  32072. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  32073. uvs.push(uv_interp.x, uv_interp.y);
  32074. // push each vertex has member of a face
  32075. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  32076. indices.push(current_indice);
  32077. current_indice++;
  32078. };
  32079. for (var i2 = 0; i2 < subdivisions; i2++) {
  32080. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  32081. // face : (i1,i2) for /\ :
  32082. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  32083. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  32084. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  32085. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  32086. if (i1 + i2 + 1 < subdivisions) {
  32087. // face : (i1,i2)' for \/ :
  32088. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  32089. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  32090. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  32091. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  32092. }
  32093. }
  32094. }
  32095. }
  32096. // Sides
  32097. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  32098. // Result
  32099. var vertexData = new VertexData();
  32100. vertexData.indices = indices;
  32101. vertexData.positions = positions;
  32102. vertexData.normals = normals;
  32103. vertexData.uvs = uvs;
  32104. return vertexData;
  32105. };
  32106. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  32107. VertexData.CreatePolyhedron = function (options) {
  32108. // provided polyhedron types :
  32109. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  32110. // 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)
  32111. var polyhedra = [];
  32112. 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]] };
  32113. 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]] };
  32114. polyhedra[2] = {
  32115. 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]],
  32116. 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]]
  32117. };
  32118. polyhedra[3] = {
  32119. 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]],
  32120. 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]]
  32121. };
  32122. polyhedra[4] = {
  32123. 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]],
  32124. 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]]
  32125. };
  32126. 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]] };
  32127. 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]] };
  32128. 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]] };
  32129. 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]] };
  32130. 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]] };
  32131. 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]] };
  32132. 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]] };
  32133. 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]] };
  32134. 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]] };
  32135. polyhedra[14] = {
  32136. 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]],
  32137. 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]]
  32138. };
  32139. var type = (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  32140. var size = options.size;
  32141. var sizeX = options.sizeX || size || 1;
  32142. var sizeY = options.sizeY || size || 1;
  32143. var sizeZ = options.sizeZ || size || 1;
  32144. var data = options.custom || polyhedra[type];
  32145. var nbfaces = data.face.length;
  32146. var faceUV = options.faceUV || new Array(nbfaces);
  32147. var faceColors = options.faceColors;
  32148. var flat = (options.flat === undefined) ? true : options.flat;
  32149. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32150. var positions = [];
  32151. var indices = [];
  32152. var normals = [];
  32153. var uvs = [];
  32154. var colors = [];
  32155. var index = 0;
  32156. var faceIdx = 0; // face cursor in the array "indexes"
  32157. var indexes = [];
  32158. var i = 0;
  32159. var f = 0;
  32160. var u, v, ang, x, y, tmp;
  32161. // default face colors and UV if undefined
  32162. if (flat) {
  32163. for (f = 0; f < nbfaces; f++) {
  32164. if (faceColors && faceColors[f] === undefined) {
  32165. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  32166. }
  32167. if (faceUV && faceUV[f] === undefined) {
  32168. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  32169. }
  32170. }
  32171. }
  32172. if (!flat) {
  32173. for (i = 0; i < data.vertex.length; i++) {
  32174. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  32175. uvs.push(0, 0);
  32176. }
  32177. for (f = 0; f < nbfaces; f++) {
  32178. for (i = 0; i < data.face[f].length - 2; i++) {
  32179. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  32180. }
  32181. }
  32182. }
  32183. else {
  32184. for (f = 0; f < nbfaces; f++) {
  32185. var fl = data.face[f].length; // number of vertices of the current face
  32186. ang = 2 * Math.PI / fl;
  32187. x = 0.5 * Math.tan(ang / 2);
  32188. y = 0.5;
  32189. // positions, uvs, colors
  32190. for (i = 0; i < fl; i++) {
  32191. // positions
  32192. 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);
  32193. indexes.push(index);
  32194. index++;
  32195. // uvs
  32196. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  32197. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  32198. uvs.push(u, v);
  32199. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  32200. y = x * Math.sin(ang) + y * Math.cos(ang);
  32201. x = tmp;
  32202. // colors
  32203. if (faceColors) {
  32204. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  32205. }
  32206. }
  32207. // indices from indexes
  32208. for (i = 0; i < fl - 2; i++) {
  32209. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  32210. }
  32211. faceIdx += fl;
  32212. }
  32213. }
  32214. VertexData.ComputeNormals(positions, indices, normals);
  32215. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  32216. var vertexData = new VertexData();
  32217. vertexData.positions = positions;
  32218. vertexData.indices = indices;
  32219. vertexData.normals = normals;
  32220. vertexData.uvs = uvs;
  32221. if (faceColors && flat) {
  32222. vertexData.colors = colors;
  32223. }
  32224. return vertexData;
  32225. };
  32226. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  32227. VertexData.CreateTorusKnot = function (options) {
  32228. var indices = [];
  32229. var positions = [];
  32230. var normals = [];
  32231. var uvs = [];
  32232. var radius = options.radius || 2;
  32233. var tube = options.tube || 0.5;
  32234. var radialSegments = options.radialSegments || 32;
  32235. var tubularSegments = options.tubularSegments || 32;
  32236. var p = options.p || 2;
  32237. var q = options.q || 3;
  32238. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32239. // Helper
  32240. var getPos = function (angle) {
  32241. var cu = Math.cos(angle);
  32242. var su = Math.sin(angle);
  32243. var quOverP = q / p * angle;
  32244. var cs = Math.cos(quOverP);
  32245. var tx = radius * (2 + cs) * 0.5 * cu;
  32246. var ty = radius * (2 + cs) * su * 0.5;
  32247. var tz = radius * Math.sin(quOverP) * 0.5;
  32248. return new BABYLON.Vector3(tx, ty, tz);
  32249. };
  32250. // Vertices
  32251. var i;
  32252. var j;
  32253. for (i = 0; i <= radialSegments; i++) {
  32254. var modI = i % radialSegments;
  32255. var u = modI / radialSegments * 2 * p * Math.PI;
  32256. var p1 = getPos(u);
  32257. var p2 = getPos(u + 0.01);
  32258. var tang = p2.subtract(p1);
  32259. var n = p2.add(p1);
  32260. var bitan = BABYLON.Vector3.Cross(tang, n);
  32261. n = BABYLON.Vector3.Cross(bitan, tang);
  32262. bitan.normalize();
  32263. n.normalize();
  32264. for (j = 0; j < tubularSegments; j++) {
  32265. var modJ = j % tubularSegments;
  32266. var v = modJ / tubularSegments * 2 * Math.PI;
  32267. var cx = -tube * Math.cos(v);
  32268. var cy = tube * Math.sin(v);
  32269. positions.push(p1.x + cx * n.x + cy * bitan.x);
  32270. positions.push(p1.y + cx * n.y + cy * bitan.y);
  32271. positions.push(p1.z + cx * n.z + cy * bitan.z);
  32272. uvs.push(i / radialSegments);
  32273. uvs.push(j / tubularSegments);
  32274. }
  32275. }
  32276. for (i = 0; i < radialSegments; i++) {
  32277. for (j = 0; j < tubularSegments; j++) {
  32278. var jNext = (j + 1) % tubularSegments;
  32279. var a = i * tubularSegments + j;
  32280. var b = (i + 1) * tubularSegments + j;
  32281. var c = (i + 1) * tubularSegments + jNext;
  32282. var d = i * tubularSegments + jNext;
  32283. indices.push(d);
  32284. indices.push(b);
  32285. indices.push(a);
  32286. indices.push(d);
  32287. indices.push(c);
  32288. indices.push(b);
  32289. }
  32290. }
  32291. // Normals
  32292. VertexData.ComputeNormals(positions, indices, normals);
  32293. // Sides
  32294. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  32295. // Result
  32296. var vertexData = new VertexData();
  32297. vertexData.indices = indices;
  32298. vertexData.positions = positions;
  32299. vertexData.normals = normals;
  32300. vertexData.uvs = uvs;
  32301. return vertexData;
  32302. };
  32303. // Tools
  32304. /**
  32305. * @param {any} - positions (number[] or Float32Array)
  32306. * @param {any} - indices (number[] or Uint16Array)
  32307. * @param {any} - normals (number[] or Float32Array)
  32308. */
  32309. VertexData.ComputeNormals = function (positions, indices, normals) {
  32310. var index = 0;
  32311. var p1p2x = 0.0;
  32312. var p1p2y = 0.0;
  32313. var p1p2z = 0.0;
  32314. var p3p2x = 0.0;
  32315. var p3p2y = 0.0;
  32316. var p3p2z = 0.0;
  32317. var faceNormalx = 0.0;
  32318. var faceNormaly = 0.0;
  32319. var faceNormalz = 0.0;
  32320. var length = 0.0;
  32321. var i1 = 0;
  32322. var i2 = 0;
  32323. var i3 = 0;
  32324. for (index = 0; index < positions.length; index++) {
  32325. normals[index] = 0.0;
  32326. }
  32327. // indice triplet = 1 face
  32328. var nbFaces = indices.length / 3;
  32329. for (index = 0; index < nbFaces; index++) {
  32330. i1 = indices[index * 3]; // get the indexes of each vertex of the face
  32331. i2 = indices[index * 3 + 1];
  32332. i3 = indices[index * 3 + 2];
  32333. p1p2x = positions[i1 * 3] - positions[i2 * 3]; // compute two vectors per face
  32334. p1p2y = positions[i1 * 3 + 1] - positions[i2 * 3 + 1];
  32335. p1p2z = positions[i1 * 3 + 2] - positions[i2 * 3 + 2];
  32336. p3p2x = positions[i3 * 3] - positions[i2 * 3];
  32337. p3p2y = positions[i3 * 3 + 1] - positions[i2 * 3 + 1];
  32338. p3p2z = positions[i3 * 3 + 2] - positions[i2 * 3 + 2];
  32339. faceNormalx = p1p2y * p3p2z - p1p2z * p3p2y; // compute the face normal with cross product
  32340. faceNormaly = p1p2z * p3p2x - p1p2x * p3p2z;
  32341. faceNormalz = p1p2x * p3p2y - p1p2y * p3p2x;
  32342. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  32343. length = (length === 0) ? 1.0 : length;
  32344. faceNormalx /= length; // normalize this normal
  32345. faceNormaly /= length;
  32346. faceNormalz /= length;
  32347. normals[i1 * 3] += faceNormalx; // accumulate all the normals per face
  32348. normals[i1 * 3 + 1] += faceNormaly;
  32349. normals[i1 * 3 + 2] += faceNormalz;
  32350. normals[i2 * 3] += faceNormalx;
  32351. normals[i2 * 3 + 1] += faceNormaly;
  32352. normals[i2 * 3 + 2] += faceNormalz;
  32353. normals[i3 * 3] += faceNormalx;
  32354. normals[i3 * 3 + 1] += faceNormaly;
  32355. normals[i3 * 3 + 2] += faceNormalz;
  32356. }
  32357. // last normalization of each normal
  32358. for (index = 0; index < normals.length / 3; index++) {
  32359. faceNormalx = normals[index * 3];
  32360. faceNormaly = normals[index * 3 + 1];
  32361. faceNormalz = normals[index * 3 + 2];
  32362. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  32363. length = (length === 0) ? 1.0 : length;
  32364. faceNormalx /= length;
  32365. faceNormaly /= length;
  32366. faceNormalz /= length;
  32367. normals[index * 3] = faceNormalx;
  32368. normals[index * 3 + 1] = faceNormaly;
  32369. normals[index * 3 + 2] = faceNormalz;
  32370. }
  32371. };
  32372. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs) {
  32373. var li = indices.length;
  32374. var ln = normals.length;
  32375. var i;
  32376. var n;
  32377. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32378. switch (sideOrientation) {
  32379. case BABYLON.Mesh.FRONTSIDE:
  32380. // nothing changed
  32381. break;
  32382. case BABYLON.Mesh.BACKSIDE:
  32383. var tmp;
  32384. // indices
  32385. for (i = 0; i < li; i += 3) {
  32386. tmp = indices[i];
  32387. indices[i] = indices[i + 2];
  32388. indices[i + 2] = tmp;
  32389. }
  32390. // normals
  32391. for (n = 0; n < ln; n++) {
  32392. normals[n] = -normals[n];
  32393. }
  32394. break;
  32395. case BABYLON.Mesh.DOUBLESIDE:
  32396. // positions
  32397. var lp = positions.length;
  32398. var l = lp / 3;
  32399. for (var p = 0; p < lp; p++) {
  32400. positions[lp + p] = positions[p];
  32401. }
  32402. // indices
  32403. for (i = 0; i < li; i += 3) {
  32404. indices[i + li] = indices[i + 2] + l;
  32405. indices[i + 1 + li] = indices[i + 1] + l;
  32406. indices[i + 2 + li] = indices[i] + l;
  32407. }
  32408. // normals
  32409. for (n = 0; n < ln; n++) {
  32410. normals[ln + n] = -normals[n];
  32411. }
  32412. // uvs
  32413. var lu = uvs.length;
  32414. for (var u = 0; u < lu; u++) {
  32415. uvs[u + lu] = uvs[u];
  32416. }
  32417. break;
  32418. }
  32419. };
  32420. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  32421. var vertexData = new VertexData();
  32422. // positions
  32423. var positions = parsedVertexData.positions;
  32424. if (positions) {
  32425. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  32426. }
  32427. // normals
  32428. var normals = parsedVertexData.normals;
  32429. if (normals) {
  32430. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  32431. }
  32432. // uvs
  32433. var uvs = parsedVertexData.uvs;
  32434. if (uvs) {
  32435. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  32436. }
  32437. // uv2s
  32438. var uv2s = parsedVertexData.uv2s;
  32439. if (uv2s) {
  32440. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  32441. }
  32442. // uv3s
  32443. var uv3s = parsedVertexData.uv3s;
  32444. if (uv3s) {
  32445. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  32446. }
  32447. // uv4s
  32448. var uv4s = parsedVertexData.uv4s;
  32449. if (uv4s) {
  32450. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  32451. }
  32452. // uv5s
  32453. var uv5s = parsedVertexData.uv5s;
  32454. if (uv5s) {
  32455. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  32456. }
  32457. // uv6s
  32458. var uv6s = parsedVertexData.uv6s;
  32459. if (uv6s) {
  32460. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  32461. }
  32462. // colors
  32463. var colors = parsedVertexData.colors;
  32464. if (colors) {
  32465. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  32466. }
  32467. // matricesIndices
  32468. var matricesIndices = parsedVertexData.matricesIndices;
  32469. if (matricesIndices) {
  32470. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  32471. }
  32472. // matricesWeights
  32473. var matricesWeights = parsedVertexData.matricesWeights;
  32474. if (matricesWeights) {
  32475. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  32476. }
  32477. // indices
  32478. var indices = parsedVertexData.indices;
  32479. if (indices) {
  32480. vertexData.indices = indices;
  32481. }
  32482. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  32483. };
  32484. return VertexData;
  32485. }());
  32486. BABYLON.VertexData = VertexData;
  32487. })(BABYLON || (BABYLON = {}));
  32488. var BABYLON;
  32489. (function (BABYLON) {
  32490. var Tags = (function () {
  32491. function Tags() {
  32492. }
  32493. Tags.EnableFor = function (obj) {
  32494. obj._tags = obj._tags || {};
  32495. obj.hasTags = function () {
  32496. return Tags.HasTags(obj);
  32497. };
  32498. obj.addTags = function (tagsString) {
  32499. return Tags.AddTagsTo(obj, tagsString);
  32500. };
  32501. obj.removeTags = function (tagsString) {
  32502. return Tags.RemoveTagsFrom(obj, tagsString);
  32503. };
  32504. obj.matchesTagsQuery = function (tagsQuery) {
  32505. return Tags.MatchesQuery(obj, tagsQuery);
  32506. };
  32507. };
  32508. Tags.DisableFor = function (obj) {
  32509. delete obj._tags;
  32510. delete obj.hasTags;
  32511. delete obj.addTags;
  32512. delete obj.removeTags;
  32513. delete obj.matchesTagsQuery;
  32514. };
  32515. Tags.HasTags = function (obj) {
  32516. if (!obj._tags) {
  32517. return false;
  32518. }
  32519. return !BABYLON.Tools.IsEmpty(obj._tags);
  32520. };
  32521. Tags.GetTags = function (obj, asString) {
  32522. if (asString === void 0) { asString = true; }
  32523. if (!obj._tags) {
  32524. return null;
  32525. }
  32526. if (asString) {
  32527. var tagsArray = [];
  32528. for (var tag in obj._tags) {
  32529. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  32530. tagsArray.push(tag);
  32531. }
  32532. }
  32533. return tagsArray.join(" ");
  32534. }
  32535. else {
  32536. return obj._tags;
  32537. }
  32538. };
  32539. // the tags 'true' and 'false' are reserved and cannot be used as tags
  32540. // a tag cannot start with '||', '&&', and '!'
  32541. // it cannot contain whitespaces
  32542. Tags.AddTagsTo = function (obj, tagsString) {
  32543. if (!tagsString) {
  32544. return;
  32545. }
  32546. if (typeof tagsString !== "string") {
  32547. return;
  32548. }
  32549. var tags = tagsString.split(" ");
  32550. for (var t in tags) {
  32551. Tags._AddTagTo(obj, tags[t]);
  32552. }
  32553. };
  32554. Tags._AddTagTo = function (obj, tag) {
  32555. tag = tag.trim();
  32556. if (tag === "" || tag === "true" || tag === "false") {
  32557. return;
  32558. }
  32559. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  32560. return;
  32561. }
  32562. Tags.EnableFor(obj);
  32563. obj._tags[tag] = true;
  32564. };
  32565. Tags.RemoveTagsFrom = function (obj, tagsString) {
  32566. if (!Tags.HasTags(obj)) {
  32567. return;
  32568. }
  32569. var tags = tagsString.split(" ");
  32570. for (var t in tags) {
  32571. Tags._RemoveTagFrom(obj, tags[t]);
  32572. }
  32573. };
  32574. Tags._RemoveTagFrom = function (obj, tag) {
  32575. delete obj._tags[tag];
  32576. };
  32577. Tags.MatchesQuery = function (obj, tagsQuery) {
  32578. if (tagsQuery === undefined) {
  32579. return true;
  32580. }
  32581. if (tagsQuery === "") {
  32582. return Tags.HasTags(obj);
  32583. }
  32584. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  32585. };
  32586. return Tags;
  32587. }());
  32588. BABYLON.Tags = Tags;
  32589. })(BABYLON || (BABYLON = {}));
  32590. var BABYLON;
  32591. (function (BABYLON) {
  32592. var Internals;
  32593. (function (Internals) {
  32594. var AndOrNotEvaluator = (function () {
  32595. function AndOrNotEvaluator() {
  32596. }
  32597. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  32598. if (!query.match(/\([^\(\)]*\)/g)) {
  32599. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  32600. }
  32601. else {
  32602. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  32603. // remove parenthesis
  32604. r = r.slice(1, r.length - 1);
  32605. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  32606. });
  32607. }
  32608. if (query === "true") {
  32609. return true;
  32610. }
  32611. if (query === "false") {
  32612. return false;
  32613. }
  32614. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  32615. };
  32616. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  32617. evaluateCallback = evaluateCallback || (function (r) {
  32618. return r === "true" ? true : false;
  32619. });
  32620. var result;
  32621. var or = parenthesisContent.split("||");
  32622. for (var i in or) {
  32623. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  32624. var and = ori.split("&&");
  32625. if (and.length > 1) {
  32626. for (var j = 0; j < and.length; ++j) {
  32627. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  32628. if (andj !== "true" && andj !== "false") {
  32629. if (andj[0] === "!") {
  32630. result = !evaluateCallback(andj.substring(1));
  32631. }
  32632. else {
  32633. result = evaluateCallback(andj);
  32634. }
  32635. }
  32636. else {
  32637. result = andj === "true" ? true : false;
  32638. }
  32639. if (!result) {
  32640. ori = "false";
  32641. break;
  32642. }
  32643. }
  32644. }
  32645. if (result || ori === "true") {
  32646. result = true;
  32647. break;
  32648. }
  32649. // result equals false (or undefined)
  32650. if (ori !== "true" && ori !== "false") {
  32651. if (ori[0] === "!") {
  32652. result = !evaluateCallback(ori.substring(1));
  32653. }
  32654. else {
  32655. result = evaluateCallback(ori);
  32656. }
  32657. }
  32658. else {
  32659. result = ori === "true" ? true : false;
  32660. }
  32661. }
  32662. // the whole parenthesis scope is replaced by 'true' or 'false'
  32663. return result ? "true" : "false";
  32664. };
  32665. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  32666. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  32667. // remove whitespaces
  32668. r = r.replace(/[\s]/g, function () { return ""; });
  32669. return r.length % 2 ? "!" : "";
  32670. });
  32671. booleanString = booleanString.trim();
  32672. if (booleanString === "!true") {
  32673. booleanString = "false";
  32674. }
  32675. else if (booleanString === "!false") {
  32676. booleanString = "true";
  32677. }
  32678. return booleanString;
  32679. };
  32680. return AndOrNotEvaluator;
  32681. }());
  32682. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  32683. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  32684. })(BABYLON || (BABYLON = {}));
  32685. var BABYLON;
  32686. (function (BABYLON) {
  32687. var PostProcessRenderPass = (function () {
  32688. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  32689. this._enabled = true;
  32690. this._refCount = 0;
  32691. this._name = name;
  32692. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  32693. this.setRenderList(renderList);
  32694. this._renderTexture.onBeforeRenderObservable.add(beforeRender);
  32695. this._renderTexture.onAfterRenderObservable.add(afterRender);
  32696. this._scene = scene;
  32697. this._renderList = renderList;
  32698. }
  32699. // private
  32700. PostProcessRenderPass.prototype._incRefCount = function () {
  32701. if (this._refCount === 0) {
  32702. this._scene.customRenderTargets.push(this._renderTexture);
  32703. }
  32704. return ++this._refCount;
  32705. };
  32706. PostProcessRenderPass.prototype._decRefCount = function () {
  32707. this._refCount--;
  32708. if (this._refCount <= 0) {
  32709. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  32710. }
  32711. return this._refCount;
  32712. };
  32713. PostProcessRenderPass.prototype._update = function () {
  32714. this.setRenderList(this._renderList);
  32715. };
  32716. // public
  32717. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  32718. this._renderTexture.renderList = renderList;
  32719. };
  32720. PostProcessRenderPass.prototype.getRenderTexture = function () {
  32721. return this._renderTexture;
  32722. };
  32723. return PostProcessRenderPass;
  32724. }());
  32725. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  32726. })(BABYLON || (BABYLON = {}));
  32727. var BABYLON;
  32728. (function (BABYLON) {
  32729. var PostProcessRenderEffect = (function () {
  32730. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  32731. this._engine = engine;
  32732. this._name = name;
  32733. this._singleInstance = singleInstance || true;
  32734. this._getPostProcess = getPostProcess;
  32735. this._cameras = [];
  32736. this._indicesForCamera = [];
  32737. this._postProcesses = {};
  32738. this._renderPasses = {};
  32739. this._renderEffectAsPasses = {};
  32740. }
  32741. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  32742. get: function () {
  32743. for (var index in this._postProcesses) {
  32744. if (!this._postProcesses[index].isSupported) {
  32745. return false;
  32746. }
  32747. }
  32748. return true;
  32749. },
  32750. enumerable: true,
  32751. configurable: true
  32752. });
  32753. PostProcessRenderEffect.prototype._update = function () {
  32754. for (var renderPassName in this._renderPasses) {
  32755. this._renderPasses[renderPassName]._update();
  32756. }
  32757. };
  32758. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  32759. this._renderPasses[renderPass._name] = renderPass;
  32760. this._linkParameters();
  32761. };
  32762. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  32763. delete this._renderPasses[renderPass._name];
  32764. this._linkParameters();
  32765. };
  32766. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  32767. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  32768. this._linkParameters();
  32769. };
  32770. PostProcessRenderEffect.prototype.getPass = function (passName) {
  32771. for (var renderPassName in this._renderPasses) {
  32772. if (renderPassName === passName) {
  32773. return this._renderPasses[passName];
  32774. }
  32775. }
  32776. };
  32777. PostProcessRenderEffect.prototype.emptyPasses = function () {
  32778. this._renderPasses = {};
  32779. this._linkParameters();
  32780. };
  32781. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  32782. var cameraKey;
  32783. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  32784. for (var i = 0; i < _cam.length; i++) {
  32785. var camera = _cam[i];
  32786. var cameraName = camera.name;
  32787. if (this._singleInstance) {
  32788. cameraKey = 0;
  32789. }
  32790. else {
  32791. cameraKey = cameraName;
  32792. }
  32793. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  32794. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  32795. if (!this._indicesForCamera[cameraName]) {
  32796. this._indicesForCamera[cameraName] = [];
  32797. }
  32798. this._indicesForCamera[cameraName].push(index);
  32799. if (this._cameras.indexOf(camera) === -1) {
  32800. this._cameras[cameraName] = camera;
  32801. }
  32802. for (var passName in this._renderPasses) {
  32803. this._renderPasses[passName]._incRefCount();
  32804. }
  32805. }
  32806. this._linkParameters();
  32807. };
  32808. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  32809. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  32810. for (var i = 0; i < _cam.length; i++) {
  32811. var camera = _cam[i];
  32812. var cameraName = camera.name;
  32813. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  32814. var index = this._cameras.indexOf(cameraName);
  32815. this._indicesForCamera.splice(index, 1);
  32816. this._cameras.splice(index, 1);
  32817. for (var passName in this._renderPasses) {
  32818. this._renderPasses[passName]._decRefCount();
  32819. }
  32820. }
  32821. };
  32822. PostProcessRenderEffect.prototype._enable = function (cameras) {
  32823. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  32824. for (var i = 0; i < _cam.length; i++) {
  32825. var camera = _cam[i];
  32826. var cameraName = camera.name;
  32827. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  32828. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  32829. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  32830. }
  32831. }
  32832. for (var passName in this._renderPasses) {
  32833. this._renderPasses[passName]._incRefCount();
  32834. }
  32835. }
  32836. };
  32837. PostProcessRenderEffect.prototype._disable = function (cameras) {
  32838. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  32839. for (var i = 0; i < _cam.length; i++) {
  32840. var camera = _cam[i];
  32841. var cameraName = camera.Name;
  32842. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  32843. for (var passName in this._renderPasses) {
  32844. this._renderPasses[passName]._decRefCount();
  32845. }
  32846. }
  32847. };
  32848. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  32849. if (this._singleInstance) {
  32850. return this._postProcesses[0];
  32851. }
  32852. else {
  32853. return this._postProcesses[camera.name];
  32854. }
  32855. };
  32856. PostProcessRenderEffect.prototype._linkParameters = function () {
  32857. var _this = this;
  32858. for (var index in this._postProcesses) {
  32859. if (this.applyParameters) {
  32860. this.applyParameters(this._postProcesses[index]);
  32861. }
  32862. this._postProcesses[index].onBeforeRenderObservable.add(function (effect) {
  32863. _this._linkTextures(effect);
  32864. });
  32865. }
  32866. };
  32867. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  32868. for (var renderPassName in this._renderPasses) {
  32869. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  32870. }
  32871. for (var renderEffectName in this._renderEffectAsPasses) {
  32872. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  32873. }
  32874. };
  32875. return PostProcessRenderEffect;
  32876. }());
  32877. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  32878. })(BABYLON || (BABYLON = {}));
  32879. var BABYLON;
  32880. (function (BABYLON) {
  32881. var PostProcessRenderPipeline = (function () {
  32882. function PostProcessRenderPipeline(engine, name) {
  32883. this._engine = engine;
  32884. this._name = name;
  32885. this._renderEffects = {};
  32886. this._renderEffectsForIsolatedPass = {};
  32887. this._cameras = [];
  32888. }
  32889. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  32890. get: function () {
  32891. for (var renderEffectName in this._renderEffects) {
  32892. if (!this._renderEffects[renderEffectName].isSupported) {
  32893. return false;
  32894. }
  32895. }
  32896. return true;
  32897. },
  32898. enumerable: true,
  32899. configurable: true
  32900. });
  32901. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  32902. this._renderEffects[renderEffect._name] = renderEffect;
  32903. };
  32904. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  32905. var renderEffects = this._renderEffects[renderEffectName];
  32906. if (!renderEffects) {
  32907. return;
  32908. }
  32909. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  32910. };
  32911. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  32912. var renderEffects = this._renderEffects[renderEffectName];
  32913. if (!renderEffects) {
  32914. return;
  32915. }
  32916. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  32917. };
  32918. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  32919. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  32920. var indicesToDelete = [];
  32921. var i;
  32922. for (i = 0; i < _cam.length; i++) {
  32923. var camera = _cam[i];
  32924. var cameraName = camera.name;
  32925. if (this._cameras.indexOf(camera) === -1) {
  32926. this._cameras[cameraName] = camera;
  32927. }
  32928. else if (unique) {
  32929. indicesToDelete.push(i);
  32930. }
  32931. }
  32932. for (i = 0; i < indicesToDelete.length; i++) {
  32933. cameras.splice(indicesToDelete[i], 1);
  32934. }
  32935. for (var renderEffectName in this._renderEffects) {
  32936. this._renderEffects[renderEffectName]._attachCameras(_cam);
  32937. }
  32938. };
  32939. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  32940. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  32941. for (var renderEffectName in this._renderEffects) {
  32942. this._renderEffects[renderEffectName]._detachCameras(_cam);
  32943. }
  32944. for (var i = 0; i < _cam.length; i++) {
  32945. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  32946. }
  32947. };
  32948. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  32949. var _this = this;
  32950. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  32951. var pass = null;
  32952. var renderEffectName;
  32953. for (renderEffectName in this._renderEffects) {
  32954. pass = this._renderEffects[renderEffectName].getPass(passName);
  32955. if (pass != null) {
  32956. break;
  32957. }
  32958. }
  32959. if (pass === null) {
  32960. return;
  32961. }
  32962. for (renderEffectName in this._renderEffects) {
  32963. this._renderEffects[renderEffectName]._disable(_cam);
  32964. }
  32965. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  32966. for (var i = 0; i < _cam.length; i++) {
  32967. var camera = _cam[i];
  32968. var cameraName = camera.name;
  32969. 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); });
  32970. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  32971. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  32972. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  32973. }
  32974. };
  32975. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  32976. var _this = this;
  32977. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  32978. for (var i = 0; i < _cam.length; i++) {
  32979. var camera = _cam[i];
  32980. var cameraName = camera.name;
  32981. 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); });
  32982. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  32983. }
  32984. for (var renderEffectName in this._renderEffects) {
  32985. this._renderEffects[renderEffectName]._enable(_cam);
  32986. }
  32987. };
  32988. PostProcessRenderPipeline.prototype._update = function () {
  32989. for (var renderEffectName in this._renderEffects) {
  32990. this._renderEffects[renderEffectName]._update();
  32991. }
  32992. for (var i = 0; i < this._cameras.length; i++) {
  32993. var cameraName = this._cameras[i].name;
  32994. if (this._renderEffectsForIsolatedPass[cameraName]) {
  32995. this._renderEffectsForIsolatedPass[cameraName]._update();
  32996. }
  32997. }
  32998. };
  32999. PostProcessRenderPipeline.prototype.dispose = function () {
  33000. // Must be implemented by children
  33001. };
  33002. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  33003. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  33004. return PostProcessRenderPipeline;
  33005. }());
  33006. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  33007. })(BABYLON || (BABYLON = {}));
  33008. var BABYLON;
  33009. (function (BABYLON) {
  33010. var PostProcessRenderPipelineManager = (function () {
  33011. function PostProcessRenderPipelineManager() {
  33012. this._renderPipelines = {};
  33013. }
  33014. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  33015. this._renderPipelines[renderPipeline._name] = renderPipeline;
  33016. };
  33017. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  33018. var renderPipeline = this._renderPipelines[renderPipelineName];
  33019. if (!renderPipeline) {
  33020. return;
  33021. }
  33022. renderPipeline._attachCameras(cameras, unique);
  33023. };
  33024. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  33025. var renderPipeline = this._renderPipelines[renderPipelineName];
  33026. if (!renderPipeline) {
  33027. return;
  33028. }
  33029. renderPipeline._detachCameras(cameras);
  33030. };
  33031. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  33032. var renderPipeline = this._renderPipelines[renderPipelineName];
  33033. if (!renderPipeline) {
  33034. return;
  33035. }
  33036. renderPipeline._enableEffect(renderEffectName, cameras);
  33037. };
  33038. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  33039. var renderPipeline = this._renderPipelines[renderPipelineName];
  33040. if (!renderPipeline) {
  33041. return;
  33042. }
  33043. renderPipeline._disableEffect(renderEffectName, cameras);
  33044. };
  33045. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  33046. var renderPipeline = this._renderPipelines[renderPipelineName];
  33047. if (!renderPipeline) {
  33048. return;
  33049. }
  33050. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  33051. };
  33052. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  33053. var renderPipeline = this._renderPipelines[renderPipelineName];
  33054. if (!renderPipeline) {
  33055. return;
  33056. }
  33057. renderPipeline._disableDisplayOnlyPass(cameras);
  33058. };
  33059. PostProcessRenderPipelineManager.prototype.update = function () {
  33060. for (var renderPipelineName in this._renderPipelines) {
  33061. var pipeline = this._renderPipelines[renderPipelineName];
  33062. if (!pipeline.isSupported) {
  33063. pipeline.dispose();
  33064. delete this._renderPipelines[renderPipelineName];
  33065. }
  33066. else {
  33067. pipeline._update();
  33068. }
  33069. }
  33070. };
  33071. return PostProcessRenderPipelineManager;
  33072. }());
  33073. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  33074. })(BABYLON || (BABYLON = {}));
  33075. var BABYLON;
  33076. (function (BABYLON) {
  33077. var BoundingBoxRenderer = (function () {
  33078. function BoundingBoxRenderer(scene) {
  33079. this.frontColor = new BABYLON.Color3(1, 1, 1);
  33080. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  33081. this.showBackLines = true;
  33082. this.renderList = new BABYLON.SmartArray(32);
  33083. this._vertexBuffers = {};
  33084. this._scene = scene;
  33085. }
  33086. BoundingBoxRenderer.prototype._prepareRessources = function () {
  33087. if (this._colorShader) {
  33088. return;
  33089. }
  33090. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  33091. attributes: [BABYLON.VertexBuffer.PositionKind],
  33092. uniforms: ["worldViewProjection", "color"]
  33093. });
  33094. var engine = this._scene.getEngine();
  33095. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  33096. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  33097. 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]);
  33098. };
  33099. BoundingBoxRenderer.prototype.reset = function () {
  33100. this.renderList.reset();
  33101. };
  33102. BoundingBoxRenderer.prototype.render = function () {
  33103. if (this.renderList.length === 0) {
  33104. return;
  33105. }
  33106. this._prepareRessources();
  33107. if (!this._colorShader.isReady()) {
  33108. return;
  33109. }
  33110. var engine = this._scene.getEngine();
  33111. engine.setDepthWrite(false);
  33112. this._colorShader._preBind();
  33113. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  33114. var boundingBox = this.renderList.data[boundingBoxIndex];
  33115. var min = boundingBox.minimum;
  33116. var max = boundingBox.maximum;
  33117. var diff = max.subtract(min);
  33118. var median = min.add(diff.scale(0.5));
  33119. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  33120. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  33121. .multiply(boundingBox.getWorldMatrix());
  33122. // VBOs
  33123. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  33124. if (this.showBackLines) {
  33125. // Back
  33126. engine.setDepthFunctionToGreaterOrEqual();
  33127. this._scene.resetCachedMaterial();
  33128. this._colorShader.setColor4("color", this.backColor.toColor4());
  33129. this._colorShader.bind(worldMatrix);
  33130. // Draw order
  33131. engine.draw(false, 0, 24);
  33132. }
  33133. // Front
  33134. engine.setDepthFunctionToLess();
  33135. this._scene.resetCachedMaterial();
  33136. this._colorShader.setColor4("color", this.frontColor.toColor4());
  33137. this._colorShader.bind(worldMatrix);
  33138. // Draw order
  33139. engine.draw(false, 0, 24);
  33140. }
  33141. this._colorShader.unbind();
  33142. engine.setDepthFunctionToLessOrEqual();
  33143. engine.setDepthWrite(true);
  33144. };
  33145. BoundingBoxRenderer.prototype.dispose = function () {
  33146. if (!this._colorShader) {
  33147. return;
  33148. }
  33149. this._colorShader.dispose();
  33150. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  33151. if (buffer) {
  33152. buffer.dispose();
  33153. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  33154. }
  33155. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  33156. };
  33157. return BoundingBoxRenderer;
  33158. }());
  33159. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  33160. })(BABYLON || (BABYLON = {}));
  33161. var BABYLON;
  33162. (function (BABYLON) {
  33163. var Condition = (function () {
  33164. function Condition(actionManager) {
  33165. this._actionManager = actionManager;
  33166. }
  33167. Condition.prototype.isValid = function () {
  33168. return true;
  33169. };
  33170. Condition.prototype._getProperty = function (propertyPath) {
  33171. return this._actionManager._getProperty(propertyPath);
  33172. };
  33173. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  33174. return this._actionManager._getEffectiveTarget(target, propertyPath);
  33175. };
  33176. Condition.prototype.serialize = function () {
  33177. };
  33178. Condition.prototype._serialize = function (serializedCondition) {
  33179. return {
  33180. type: 2,
  33181. children: [],
  33182. name: serializedCondition.name,
  33183. properties: serializedCondition.properties
  33184. };
  33185. };
  33186. return Condition;
  33187. }());
  33188. BABYLON.Condition = Condition;
  33189. var ValueCondition = (function (_super) {
  33190. __extends(ValueCondition, _super);
  33191. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  33192. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  33193. _super.call(this, actionManager);
  33194. this.propertyPath = propertyPath;
  33195. this.value = value;
  33196. this.operator = operator;
  33197. this._target = target;
  33198. this._effectiveTarget = this._getEffectiveTarget(target, this.propertyPath);
  33199. this._property = this._getProperty(this.propertyPath);
  33200. }
  33201. Object.defineProperty(ValueCondition, "IsEqual", {
  33202. get: function () {
  33203. return ValueCondition._IsEqual;
  33204. },
  33205. enumerable: true,
  33206. configurable: true
  33207. });
  33208. Object.defineProperty(ValueCondition, "IsDifferent", {
  33209. get: function () {
  33210. return ValueCondition._IsDifferent;
  33211. },
  33212. enumerable: true,
  33213. configurable: true
  33214. });
  33215. Object.defineProperty(ValueCondition, "IsGreater", {
  33216. get: function () {
  33217. return ValueCondition._IsGreater;
  33218. },
  33219. enumerable: true,
  33220. configurable: true
  33221. });
  33222. Object.defineProperty(ValueCondition, "IsLesser", {
  33223. get: function () {
  33224. return ValueCondition._IsLesser;
  33225. },
  33226. enumerable: true,
  33227. configurable: true
  33228. });
  33229. // Methods
  33230. ValueCondition.prototype.isValid = function () {
  33231. switch (this.operator) {
  33232. case ValueCondition.IsGreater:
  33233. return this._effectiveTarget[this._property] > this.value;
  33234. case ValueCondition.IsLesser:
  33235. return this._effectiveTarget[this._property] < this.value;
  33236. case ValueCondition.IsEqual:
  33237. case ValueCondition.IsDifferent:
  33238. var check;
  33239. if (this.value.equals) {
  33240. check = this.value.equals(this._effectiveTarget[this._property]);
  33241. }
  33242. else {
  33243. check = this.value === this._effectiveTarget[this._property];
  33244. }
  33245. return this.operator === ValueCondition.IsEqual ? check : !check;
  33246. }
  33247. return false;
  33248. };
  33249. ValueCondition.prototype.serialize = function () {
  33250. return this._serialize({
  33251. name: "ValueCondition",
  33252. properties: [
  33253. BABYLON.Action._GetTargetProperty(this._target),
  33254. { name: "propertyPath", value: this.propertyPath },
  33255. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  33256. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  33257. ]
  33258. });
  33259. };
  33260. ValueCondition.GetOperatorName = function (operator) {
  33261. switch (operator) {
  33262. case ValueCondition._IsEqual: return "IsEqual";
  33263. case ValueCondition._IsDifferent: return "IsDifferent";
  33264. case ValueCondition._IsGreater: return "IsGreater";
  33265. case ValueCondition._IsLesser: return "IsLesser";
  33266. default: return "";
  33267. }
  33268. };
  33269. // Statics
  33270. ValueCondition._IsEqual = 0;
  33271. ValueCondition._IsDifferent = 1;
  33272. ValueCondition._IsGreater = 2;
  33273. ValueCondition._IsLesser = 3;
  33274. return ValueCondition;
  33275. }(Condition));
  33276. BABYLON.ValueCondition = ValueCondition;
  33277. var PredicateCondition = (function (_super) {
  33278. __extends(PredicateCondition, _super);
  33279. function PredicateCondition(actionManager, predicate) {
  33280. _super.call(this, actionManager);
  33281. this.predicate = predicate;
  33282. }
  33283. PredicateCondition.prototype.isValid = function () {
  33284. return this.predicate();
  33285. };
  33286. return PredicateCondition;
  33287. }(Condition));
  33288. BABYLON.PredicateCondition = PredicateCondition;
  33289. var StateCondition = (function (_super) {
  33290. __extends(StateCondition, _super);
  33291. function StateCondition(actionManager, target, value) {
  33292. _super.call(this, actionManager);
  33293. this.value = value;
  33294. this._target = target;
  33295. }
  33296. // Methods
  33297. StateCondition.prototype.isValid = function () {
  33298. return this._target.state === this.value;
  33299. };
  33300. StateCondition.prototype.serialize = function () {
  33301. return this._serialize({
  33302. name: "StateCondition",
  33303. properties: [
  33304. BABYLON.Action._GetTargetProperty(this._target),
  33305. { name: "value", value: this.value }
  33306. ]
  33307. });
  33308. };
  33309. return StateCondition;
  33310. }(Condition));
  33311. BABYLON.StateCondition = StateCondition;
  33312. })(BABYLON || (BABYLON = {}));
  33313. var BABYLON;
  33314. (function (BABYLON) {
  33315. var Action = (function () {
  33316. function Action(triggerOptions, condition) {
  33317. this.triggerOptions = triggerOptions;
  33318. if (triggerOptions.parameter) {
  33319. this.trigger = triggerOptions.trigger;
  33320. this._triggerParameter = triggerOptions.parameter;
  33321. }
  33322. else {
  33323. this.trigger = triggerOptions;
  33324. }
  33325. this._nextActiveAction = this;
  33326. this._condition = condition;
  33327. }
  33328. // Methods
  33329. Action.prototype._prepare = function () {
  33330. };
  33331. Action.prototype.getTriggerParameter = function () {
  33332. return this._triggerParameter;
  33333. };
  33334. Action.prototype._executeCurrent = function (evt) {
  33335. if (this._nextActiveAction._condition) {
  33336. var condition = this._nextActiveAction._condition;
  33337. var currentRenderId = this._actionManager.getScene().getRenderId();
  33338. // We cache the current evaluation for the current frame
  33339. if (condition._evaluationId === currentRenderId) {
  33340. if (!condition._currentResult) {
  33341. return;
  33342. }
  33343. }
  33344. else {
  33345. condition._evaluationId = currentRenderId;
  33346. if (!condition.isValid()) {
  33347. condition._currentResult = false;
  33348. return;
  33349. }
  33350. condition._currentResult = true;
  33351. }
  33352. }
  33353. this._nextActiveAction.execute(evt);
  33354. this.skipToNextActiveAction();
  33355. };
  33356. Action.prototype.execute = function (evt) {
  33357. };
  33358. Action.prototype.skipToNextActiveAction = function () {
  33359. if (this._nextActiveAction._child) {
  33360. if (!this._nextActiveAction._child._actionManager) {
  33361. this._nextActiveAction._child._actionManager = this._actionManager;
  33362. }
  33363. this._nextActiveAction = this._nextActiveAction._child;
  33364. }
  33365. else {
  33366. this._nextActiveAction = this;
  33367. }
  33368. };
  33369. Action.prototype.then = function (action) {
  33370. this._child = action;
  33371. action._actionManager = this._actionManager;
  33372. action._prepare();
  33373. return action;
  33374. };
  33375. Action.prototype._getProperty = function (propertyPath) {
  33376. return this._actionManager._getProperty(propertyPath);
  33377. };
  33378. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  33379. return this._actionManager._getEffectiveTarget(target, propertyPath);
  33380. };
  33381. Action.prototype.serialize = function (parent) {
  33382. };
  33383. // Called by BABYLON.Action objects in serialize(...). Internal use
  33384. Action.prototype._serialize = function (serializedAction, parent) {
  33385. var serializationObject = {
  33386. type: 1,
  33387. children: [],
  33388. name: serializedAction.name,
  33389. properties: serializedAction.properties || []
  33390. };
  33391. // Serialize child
  33392. if (this._child) {
  33393. this._child.serialize(serializationObject);
  33394. }
  33395. // Check if "this" has a condition
  33396. if (this._condition) {
  33397. var serializedCondition = this._condition.serialize();
  33398. serializedCondition.children.push(serializationObject);
  33399. if (parent) {
  33400. parent.children.push(serializedCondition);
  33401. }
  33402. return serializedCondition;
  33403. }
  33404. if (parent) {
  33405. parent.children.push(serializationObject);
  33406. }
  33407. return serializationObject;
  33408. };
  33409. Action._SerializeValueAsString = function (value) {
  33410. if (typeof value === "number") {
  33411. return value.toString();
  33412. }
  33413. if (typeof value === "boolean") {
  33414. return value ? "true" : "false";
  33415. }
  33416. if (value instanceof BABYLON.Vector2) {
  33417. return value.x + ", " + value.y;
  33418. }
  33419. if (value instanceof BABYLON.Vector3) {
  33420. return value.x + ", " + value.y + ", " + value.z;
  33421. }
  33422. if (value instanceof BABYLON.Color3) {
  33423. return value.r + ", " + value.g + ", " + value.b;
  33424. }
  33425. if (value instanceof BABYLON.Color4) {
  33426. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  33427. }
  33428. return value; // string
  33429. };
  33430. Action._GetTargetProperty = function (target) {
  33431. return {
  33432. name: "target",
  33433. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  33434. : target instanceof BABYLON.Light ? "LightProperties"
  33435. : target instanceof BABYLON.Camera ? "CameraProperties"
  33436. : "SceneProperties",
  33437. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  33438. };
  33439. };
  33440. return Action;
  33441. }());
  33442. BABYLON.Action = Action;
  33443. })(BABYLON || (BABYLON = {}));
  33444. var BABYLON;
  33445. (function (BABYLON) {
  33446. /**
  33447. * ActionEvent is the event beint sent when an action is triggered.
  33448. */
  33449. var ActionEvent = (function () {
  33450. /**
  33451. * @constructor
  33452. * @param source The mesh or sprite that triggered the action.
  33453. * @param pointerX The X mouse cursor position at the time of the event
  33454. * @param pointerY The Y mouse cursor position at the time of the event
  33455. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  33456. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  33457. */
  33458. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  33459. this.source = source;
  33460. this.pointerX = pointerX;
  33461. this.pointerY = pointerY;
  33462. this.meshUnderPointer = meshUnderPointer;
  33463. this.sourceEvent = sourceEvent;
  33464. this.additionalData = additionalData;
  33465. }
  33466. /**
  33467. * Helper function to auto-create an ActionEvent from a source mesh.
  33468. * @param source The source mesh that triggered the event
  33469. * @param evt {Event} The original (browser) event
  33470. */
  33471. ActionEvent.CreateNew = function (source, evt, additionalData) {
  33472. var scene = source.getScene();
  33473. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  33474. };
  33475. /**
  33476. * Helper function to auto-create an ActionEvent from a source mesh.
  33477. * @param source The source sprite that triggered the event
  33478. * @param scene Scene associated with the sprite
  33479. * @param evt {Event} The original (browser) event
  33480. */
  33481. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  33482. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  33483. };
  33484. /**
  33485. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  33486. * @param scene the scene where the event occurred
  33487. * @param evt {Event} The original (browser) event
  33488. */
  33489. ActionEvent.CreateNewFromScene = function (scene, evt) {
  33490. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  33491. };
  33492. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  33493. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  33494. };
  33495. return ActionEvent;
  33496. }());
  33497. BABYLON.ActionEvent = ActionEvent;
  33498. /**
  33499. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  33500. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  33501. */
  33502. var ActionManager = (function () {
  33503. function ActionManager(scene) {
  33504. // Members
  33505. this.actions = new Array();
  33506. this._scene = scene;
  33507. scene._actionManagers.push(this);
  33508. }
  33509. Object.defineProperty(ActionManager, "NothingTrigger", {
  33510. get: function () {
  33511. return ActionManager._NothingTrigger;
  33512. },
  33513. enumerable: true,
  33514. configurable: true
  33515. });
  33516. Object.defineProperty(ActionManager, "OnPickTrigger", {
  33517. get: function () {
  33518. return ActionManager._OnPickTrigger;
  33519. },
  33520. enumerable: true,
  33521. configurable: true
  33522. });
  33523. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  33524. get: function () {
  33525. return ActionManager._OnLeftPickTrigger;
  33526. },
  33527. enumerable: true,
  33528. configurable: true
  33529. });
  33530. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  33531. get: function () {
  33532. return ActionManager._OnRightPickTrigger;
  33533. },
  33534. enumerable: true,
  33535. configurable: true
  33536. });
  33537. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  33538. get: function () {
  33539. return ActionManager._OnCenterPickTrigger;
  33540. },
  33541. enumerable: true,
  33542. configurable: true
  33543. });
  33544. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  33545. get: function () {
  33546. return ActionManager._OnPickDownTrigger;
  33547. },
  33548. enumerable: true,
  33549. configurable: true
  33550. });
  33551. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  33552. get: function () {
  33553. return ActionManager._OnPickUpTrigger;
  33554. },
  33555. enumerable: true,
  33556. configurable: true
  33557. });
  33558. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  33559. /// This trigger will only be raised if you also declared a OnPickDown
  33560. get: function () {
  33561. return ActionManager._OnPickOutTrigger;
  33562. },
  33563. enumerable: true,
  33564. configurable: true
  33565. });
  33566. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  33567. get: function () {
  33568. return ActionManager._OnLongPressTrigger;
  33569. },
  33570. enumerable: true,
  33571. configurable: true
  33572. });
  33573. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  33574. get: function () {
  33575. return ActionManager._OnPointerOverTrigger;
  33576. },
  33577. enumerable: true,
  33578. configurable: true
  33579. });
  33580. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  33581. get: function () {
  33582. return ActionManager._OnPointerOutTrigger;
  33583. },
  33584. enumerable: true,
  33585. configurable: true
  33586. });
  33587. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  33588. get: function () {
  33589. return ActionManager._OnEveryFrameTrigger;
  33590. },
  33591. enumerable: true,
  33592. configurable: true
  33593. });
  33594. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  33595. get: function () {
  33596. return ActionManager._OnIntersectionEnterTrigger;
  33597. },
  33598. enumerable: true,
  33599. configurable: true
  33600. });
  33601. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  33602. get: function () {
  33603. return ActionManager._OnIntersectionExitTrigger;
  33604. },
  33605. enumerable: true,
  33606. configurable: true
  33607. });
  33608. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  33609. get: function () {
  33610. return ActionManager._OnKeyDownTrigger;
  33611. },
  33612. enumerable: true,
  33613. configurable: true
  33614. });
  33615. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  33616. get: function () {
  33617. return ActionManager._OnKeyUpTrigger;
  33618. },
  33619. enumerable: true,
  33620. configurable: true
  33621. });
  33622. // Methods
  33623. ActionManager.prototype.dispose = function () {
  33624. var index = this._scene._actionManagers.indexOf(this);
  33625. if (index > -1) {
  33626. this._scene._actionManagers.splice(index, 1);
  33627. }
  33628. };
  33629. ActionManager.prototype.getScene = function () {
  33630. return this._scene;
  33631. };
  33632. /**
  33633. * Does this action manager handles actions of any of the given triggers
  33634. * @param {number[]} triggers - the triggers to be tested
  33635. * @return {boolean} whether one (or more) of the triggers is handeled
  33636. */
  33637. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  33638. for (var index = 0; index < this.actions.length; index++) {
  33639. var action = this.actions[index];
  33640. if (triggers.indexOf(action.trigger) > -1) {
  33641. return true;
  33642. }
  33643. }
  33644. return false;
  33645. };
  33646. /**
  33647. * Does this action manager handles actions of a given trigger
  33648. * @param {number} trigger - the trigger to be tested
  33649. * @return {boolean} whether the trigger is handeled
  33650. */
  33651. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  33652. for (var index = 0; index < this.actions.length; index++) {
  33653. var action = this.actions[index];
  33654. if (action.trigger === trigger) {
  33655. return true;
  33656. }
  33657. }
  33658. return false;
  33659. };
  33660. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  33661. /**
  33662. * Does this action manager has pointer triggers
  33663. * @return {boolean} whether or not it has pointer triggers
  33664. */
  33665. get: function () {
  33666. for (var index = 0; index < this.actions.length; index++) {
  33667. var action = this.actions[index];
  33668. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  33669. return true;
  33670. }
  33671. }
  33672. return false;
  33673. },
  33674. enumerable: true,
  33675. configurable: true
  33676. });
  33677. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  33678. /**
  33679. * Does this action manager has pick triggers
  33680. * @return {boolean} whether or not it has pick triggers
  33681. */
  33682. get: function () {
  33683. for (var index = 0; index < this.actions.length; index++) {
  33684. var action = this.actions[index];
  33685. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  33686. return true;
  33687. }
  33688. }
  33689. return false;
  33690. },
  33691. enumerable: true,
  33692. configurable: true
  33693. });
  33694. /**
  33695. * Registers an action to this action manager
  33696. * @param {BABYLON.Action} action - the action to be registered
  33697. * @return {BABYLON.Action} the action amended (prepared) after registration
  33698. */
  33699. ActionManager.prototype.registerAction = function (action) {
  33700. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  33701. if (this.getScene().actionManager !== this) {
  33702. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  33703. return null;
  33704. }
  33705. }
  33706. this.actions.push(action);
  33707. action._actionManager = this;
  33708. action._prepare();
  33709. return action;
  33710. };
  33711. /**
  33712. * Process a specific trigger
  33713. * @param {number} trigger - the trigger to process
  33714. * @param evt {BABYLON.ActionEvent} the event details to be processed
  33715. */
  33716. ActionManager.prototype.processTrigger = function (trigger, evt) {
  33717. for (var index = 0; index < this.actions.length; index++) {
  33718. var action = this.actions[index];
  33719. if (action.trigger === trigger) {
  33720. if (trigger === ActionManager.OnKeyUpTrigger
  33721. || trigger === ActionManager.OnKeyDownTrigger) {
  33722. var parameter = action.getTriggerParameter();
  33723. if (parameter) {
  33724. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  33725. var actualkey = String.fromCharCode(unicode).toLowerCase();
  33726. if (actualkey !== parameter.toLowerCase()) {
  33727. continue;
  33728. }
  33729. }
  33730. }
  33731. action._executeCurrent(evt);
  33732. }
  33733. }
  33734. };
  33735. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  33736. var properties = propertyPath.split(".");
  33737. for (var index = 0; index < properties.length - 1; index++) {
  33738. target = target[properties[index]];
  33739. }
  33740. return target;
  33741. };
  33742. ActionManager.prototype._getProperty = function (propertyPath) {
  33743. var properties = propertyPath.split(".");
  33744. return properties[properties.length - 1];
  33745. };
  33746. ActionManager.prototype.serialize = function (name) {
  33747. var root = {
  33748. children: [],
  33749. name: name,
  33750. type: 3,
  33751. properties: [] // Empty for root but required
  33752. };
  33753. for (var i = 0; i < this.actions.length; i++) {
  33754. var triggerObject = {
  33755. type: 0,
  33756. children: [],
  33757. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  33758. properties: []
  33759. };
  33760. var triggerOptions = this.actions[i].triggerOptions;
  33761. if (triggerOptions && typeof triggerOptions !== "number") {
  33762. if (triggerOptions.parameter instanceof BABYLON.Node) {
  33763. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  33764. }
  33765. else {
  33766. triggerObject.properties.push({ name: "parameter", targetType: null, value: triggerOptions.parameter });
  33767. }
  33768. }
  33769. // Serialize child action, recursively
  33770. this.actions[i].serialize(triggerObject);
  33771. // Add serialized trigger
  33772. root.children.push(triggerObject);
  33773. }
  33774. return root;
  33775. };
  33776. ActionManager.Parse = function (parsedActions, object, scene) {
  33777. var actionManager = new BABYLON.ActionManager(scene);
  33778. if (object === null)
  33779. scene.actionManager = actionManager;
  33780. else
  33781. object.actionManager = actionManager;
  33782. // instanciate a new object
  33783. var instanciate = function (name, params) {
  33784. var newInstance = Object.create(BABYLON[name].prototype);
  33785. newInstance.constructor.apply(newInstance, params);
  33786. return newInstance;
  33787. };
  33788. var parseParameter = function (name, value, target, propertyPath) {
  33789. if (propertyPath === null) {
  33790. // String, boolean or float
  33791. var floatValue = parseFloat(value);
  33792. if (value === "true" || value === "false")
  33793. return value === "true";
  33794. else
  33795. return isNaN(floatValue) ? value : floatValue;
  33796. }
  33797. var effectiveTarget = propertyPath.split(".");
  33798. var values = value.split(",");
  33799. // Get effective Target
  33800. for (var i = 0; i < effectiveTarget.length; i++) {
  33801. target = target[effectiveTarget[i]];
  33802. }
  33803. // Return appropriate value with its type
  33804. if (typeof (target) === "boolean")
  33805. return values[0] === "true";
  33806. if (typeof (target) === "string")
  33807. return values[0];
  33808. // Parameters with multiple values such as Vector3 etc.
  33809. var split = new Array();
  33810. for (var i = 0; i < values.length; i++)
  33811. split.push(parseFloat(values[i]));
  33812. if (target instanceof BABYLON.Vector3)
  33813. return BABYLON.Vector3.FromArray(split);
  33814. if (target instanceof BABYLON.Vector4)
  33815. return BABYLON.Vector4.FromArray(split);
  33816. if (target instanceof BABYLON.Color3)
  33817. return BABYLON.Color3.FromArray(split);
  33818. if (target instanceof BABYLON.Color4)
  33819. return BABYLON.Color4.FromArray(split);
  33820. return parseFloat(values[0]);
  33821. };
  33822. // traverse graph per trigger
  33823. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  33824. if (combineArray === void 0) { combineArray = null; }
  33825. if (parsedAction.detached)
  33826. return;
  33827. var parameters = new Array();
  33828. var target = null;
  33829. var propertyPath = null;
  33830. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  33831. // Parameters
  33832. if (parsedAction.type === 2)
  33833. parameters.push(actionManager);
  33834. else
  33835. parameters.push(trigger);
  33836. if (combine) {
  33837. var actions = new Array();
  33838. for (var j = 0; j < parsedAction.combine.length; j++) {
  33839. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  33840. }
  33841. parameters.push(actions);
  33842. }
  33843. else {
  33844. for (var i = 0; i < parsedAction.properties.length; i++) {
  33845. var value = parsedAction.properties[i].value;
  33846. var name = parsedAction.properties[i].name;
  33847. var targetType = parsedAction.properties[i].targetType;
  33848. if (name === "target")
  33849. if (targetType !== null && targetType === "SceneProperties")
  33850. value = target = scene;
  33851. else
  33852. value = target = scene.getNodeByName(value);
  33853. else if (name === "parent")
  33854. value = scene.getNodeByName(value);
  33855. else if (name === "sound")
  33856. value = scene.getSoundByName(value);
  33857. else if (name !== "propertyPath") {
  33858. if (parsedAction.type === 2 && name === "operator")
  33859. value = BABYLON.ValueCondition[value];
  33860. else
  33861. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  33862. }
  33863. else {
  33864. propertyPath = value;
  33865. }
  33866. parameters.push(value);
  33867. }
  33868. }
  33869. if (combineArray === null) {
  33870. parameters.push(condition);
  33871. }
  33872. else {
  33873. parameters.push(null);
  33874. }
  33875. // If interpolate value action
  33876. if (parsedAction.name === "InterpolateValueAction") {
  33877. var param = parameters[parameters.length - 2];
  33878. parameters[parameters.length - 1] = param;
  33879. parameters[parameters.length - 2] = condition;
  33880. }
  33881. // Action or condition(s) and not CombineAction
  33882. var newAction = instanciate(parsedAction.name, parameters);
  33883. if (newAction instanceof BABYLON.Condition && condition !== null) {
  33884. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  33885. if (action)
  33886. action.then(nothing);
  33887. else
  33888. actionManager.registerAction(nothing);
  33889. action = nothing;
  33890. }
  33891. if (combineArray === null) {
  33892. if (newAction instanceof BABYLON.Condition) {
  33893. condition = newAction;
  33894. newAction = action;
  33895. }
  33896. else {
  33897. condition = null;
  33898. if (action)
  33899. action.then(newAction);
  33900. else
  33901. actionManager.registerAction(newAction);
  33902. }
  33903. }
  33904. else {
  33905. combineArray.push(newAction);
  33906. }
  33907. for (var i = 0; i < parsedAction.children.length; i++)
  33908. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  33909. };
  33910. // triggers
  33911. for (var i = 0; i < parsedActions.children.length; i++) {
  33912. var triggerParams;
  33913. var trigger = parsedActions.children[i];
  33914. if (trigger.properties.length > 0) {
  33915. var param = trigger.properties[0].value;
  33916. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  33917. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  33918. }
  33919. else
  33920. triggerParams = BABYLON.ActionManager[trigger.name];
  33921. for (var j = 0; j < trigger.children.length; j++) {
  33922. if (!trigger.detached)
  33923. traverse(trigger.children[j], triggerParams, null, null);
  33924. }
  33925. }
  33926. };
  33927. ActionManager.GetTriggerName = function (trigger) {
  33928. switch (trigger) {
  33929. case 0: return "NothingTrigger";
  33930. case 1: return "OnPickTrigger";
  33931. case 2: return "OnLeftPickTrigger";
  33932. case 3: return "OnRightPickTrigger";
  33933. case 4: return "OnCenterPickTrigger";
  33934. case 5: return "OnPickDownTrigger";
  33935. case 6: return "OnPickUpTrigger";
  33936. case 7: return "OnLongPressTrigger";
  33937. case 8: return "OnPointerOverTrigger";
  33938. case 9: return "OnPointerOutTrigger";
  33939. case 10: return "OnEveryFrameTrigger";
  33940. case 11: return "OnIntersectionEnterTrigger";
  33941. case 12: return "OnIntersectionExitTrigger";
  33942. case 13: return "OnKeyDownTrigger";
  33943. case 14: return "OnKeyUpTrigger";
  33944. case 15: return "OnPickOutTrigger";
  33945. default: return "";
  33946. }
  33947. };
  33948. // Statics
  33949. ActionManager._NothingTrigger = 0;
  33950. ActionManager._OnPickTrigger = 1;
  33951. ActionManager._OnLeftPickTrigger = 2;
  33952. ActionManager._OnRightPickTrigger = 3;
  33953. ActionManager._OnCenterPickTrigger = 4;
  33954. ActionManager._OnPickDownTrigger = 5;
  33955. ActionManager._OnPickUpTrigger = 6;
  33956. ActionManager._OnLongPressTrigger = 7;
  33957. ActionManager._OnPointerOverTrigger = 8;
  33958. ActionManager._OnPointerOutTrigger = 9;
  33959. ActionManager._OnEveryFrameTrigger = 10;
  33960. ActionManager._OnIntersectionEnterTrigger = 11;
  33961. ActionManager._OnIntersectionExitTrigger = 12;
  33962. ActionManager._OnKeyDownTrigger = 13;
  33963. ActionManager._OnKeyUpTrigger = 14;
  33964. ActionManager._OnPickOutTrigger = 15;
  33965. ActionManager.DragMovementThreshold = 10; // in pixels
  33966. ActionManager.LongPressDelay = 500; // in milliseconds
  33967. return ActionManager;
  33968. }());
  33969. BABYLON.ActionManager = ActionManager;
  33970. })(BABYLON || (BABYLON = {}));
  33971. var BABYLON;
  33972. (function (BABYLON) {
  33973. var InterpolateValueAction = (function (_super) {
  33974. __extends(InterpolateValueAction, _super);
  33975. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  33976. if (duration === void 0) { duration = 1000; }
  33977. _super.call(this, triggerOptions, condition);
  33978. this.propertyPath = propertyPath;
  33979. this.value = value;
  33980. this.duration = duration;
  33981. this.stopOtherAnimations = stopOtherAnimations;
  33982. this.onInterpolationDone = onInterpolationDone;
  33983. this._target = this._effectiveTarget = target;
  33984. }
  33985. InterpolateValueAction.prototype._prepare = function () {
  33986. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  33987. this._property = this._getProperty(this.propertyPath);
  33988. };
  33989. InterpolateValueAction.prototype.execute = function () {
  33990. var scene = this._actionManager.getScene();
  33991. var keys = [
  33992. {
  33993. frame: 0,
  33994. value: this._effectiveTarget[this._property]
  33995. }, {
  33996. frame: 100,
  33997. value: this.value
  33998. }
  33999. ];
  34000. var dataType;
  34001. if (typeof this.value === "number") {
  34002. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  34003. }
  34004. else if (this.value instanceof BABYLON.Color3) {
  34005. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  34006. }
  34007. else if (this.value instanceof BABYLON.Vector3) {
  34008. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  34009. }
  34010. else if (this.value instanceof BABYLON.Matrix) {
  34011. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  34012. }
  34013. else if (this.value instanceof BABYLON.Quaternion) {
  34014. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  34015. }
  34016. else {
  34017. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  34018. return;
  34019. }
  34020. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  34021. animation.setKeys(keys);
  34022. if (this.stopOtherAnimations) {
  34023. scene.stopAnimation(this._effectiveTarget);
  34024. }
  34025. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, this.onInterpolationDone);
  34026. };
  34027. InterpolateValueAction.prototype.serialize = function (parent) {
  34028. return _super.prototype._serialize.call(this, {
  34029. name: "InterpolateValueAction",
  34030. properties: [
  34031. BABYLON.Action._GetTargetProperty(this._target),
  34032. { name: "propertyPath", value: this.propertyPath },
  34033. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  34034. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  34035. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  34036. ]
  34037. }, parent);
  34038. };
  34039. return InterpolateValueAction;
  34040. }(BABYLON.Action));
  34041. BABYLON.InterpolateValueAction = InterpolateValueAction;
  34042. })(BABYLON || (BABYLON = {}));
  34043. var BABYLON;
  34044. (function (BABYLON) {
  34045. var SwitchBooleanAction = (function (_super) {
  34046. __extends(SwitchBooleanAction, _super);
  34047. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  34048. _super.call(this, triggerOptions, condition);
  34049. this.propertyPath = propertyPath;
  34050. this._target = this._effectiveTarget = target;
  34051. }
  34052. SwitchBooleanAction.prototype._prepare = function () {
  34053. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  34054. this._property = this._getProperty(this.propertyPath);
  34055. };
  34056. SwitchBooleanAction.prototype.execute = function () {
  34057. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  34058. };
  34059. SwitchBooleanAction.prototype.serialize = function (parent) {
  34060. return _super.prototype._serialize.call(this, {
  34061. name: "SwitchBooleanAction",
  34062. properties: [
  34063. BABYLON.Action._GetTargetProperty(this._target),
  34064. { name: "propertyPath", value: this.propertyPath }
  34065. ]
  34066. }, parent);
  34067. };
  34068. return SwitchBooleanAction;
  34069. }(BABYLON.Action));
  34070. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  34071. var SetStateAction = (function (_super) {
  34072. __extends(SetStateAction, _super);
  34073. function SetStateAction(triggerOptions, target, value, condition) {
  34074. _super.call(this, triggerOptions, condition);
  34075. this.value = value;
  34076. this._target = target;
  34077. }
  34078. SetStateAction.prototype.execute = function () {
  34079. this._target.state = this.value;
  34080. };
  34081. SetStateAction.prototype.serialize = function (parent) {
  34082. return _super.prototype._serialize.call(this, {
  34083. name: "SetStateAction",
  34084. properties: [
  34085. BABYLON.Action._GetTargetProperty(this._target),
  34086. { name: "value", value: this.value }
  34087. ]
  34088. }, parent);
  34089. };
  34090. return SetStateAction;
  34091. }(BABYLON.Action));
  34092. BABYLON.SetStateAction = SetStateAction;
  34093. var SetValueAction = (function (_super) {
  34094. __extends(SetValueAction, _super);
  34095. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  34096. _super.call(this, triggerOptions, condition);
  34097. this.propertyPath = propertyPath;
  34098. this.value = value;
  34099. this._target = this._effectiveTarget = target;
  34100. }
  34101. SetValueAction.prototype._prepare = function () {
  34102. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  34103. this._property = this._getProperty(this.propertyPath);
  34104. };
  34105. SetValueAction.prototype.execute = function () {
  34106. this._effectiveTarget[this._property] = this.value;
  34107. if (this._target.markAsDirty) {
  34108. this._target.markAsDirty(this._property);
  34109. }
  34110. };
  34111. SetValueAction.prototype.serialize = function (parent) {
  34112. return _super.prototype._serialize.call(this, {
  34113. name: "SetValueAction",
  34114. properties: [
  34115. BABYLON.Action._GetTargetProperty(this._target),
  34116. { name: "propertyPath", value: this.propertyPath },
  34117. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  34118. ]
  34119. }, parent);
  34120. };
  34121. return SetValueAction;
  34122. }(BABYLON.Action));
  34123. BABYLON.SetValueAction = SetValueAction;
  34124. var IncrementValueAction = (function (_super) {
  34125. __extends(IncrementValueAction, _super);
  34126. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  34127. _super.call(this, triggerOptions, condition);
  34128. this.propertyPath = propertyPath;
  34129. this.value = value;
  34130. this._target = this._effectiveTarget = target;
  34131. }
  34132. IncrementValueAction.prototype._prepare = function () {
  34133. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  34134. this._property = this._getProperty(this.propertyPath);
  34135. if (typeof this._effectiveTarget[this._property] !== "number") {
  34136. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  34137. }
  34138. };
  34139. IncrementValueAction.prototype.execute = function () {
  34140. this._effectiveTarget[this._property] += this.value;
  34141. if (this._target.markAsDirty) {
  34142. this._target.markAsDirty(this._property);
  34143. }
  34144. };
  34145. IncrementValueAction.prototype.serialize = function (parent) {
  34146. return _super.prototype._serialize.call(this, {
  34147. name: "IncrementValueAction",
  34148. properties: [
  34149. BABYLON.Action._GetTargetProperty(this._target),
  34150. { name: "propertyPath", value: this.propertyPath },
  34151. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  34152. ]
  34153. }, parent);
  34154. };
  34155. return IncrementValueAction;
  34156. }(BABYLON.Action));
  34157. BABYLON.IncrementValueAction = IncrementValueAction;
  34158. var PlayAnimationAction = (function (_super) {
  34159. __extends(PlayAnimationAction, _super);
  34160. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  34161. _super.call(this, triggerOptions, condition);
  34162. this.from = from;
  34163. this.to = to;
  34164. this.loop = loop;
  34165. this._target = target;
  34166. }
  34167. PlayAnimationAction.prototype._prepare = function () {
  34168. };
  34169. PlayAnimationAction.prototype.execute = function () {
  34170. var scene = this._actionManager.getScene();
  34171. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  34172. };
  34173. PlayAnimationAction.prototype.serialize = function (parent) {
  34174. return _super.prototype._serialize.call(this, {
  34175. name: "PlayAnimationAction",
  34176. properties: [
  34177. BABYLON.Action._GetTargetProperty(this._target),
  34178. { name: "from", value: String(this.from) },
  34179. { name: "to", value: String(this.to) },
  34180. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  34181. ]
  34182. }, parent);
  34183. };
  34184. return PlayAnimationAction;
  34185. }(BABYLON.Action));
  34186. BABYLON.PlayAnimationAction = PlayAnimationAction;
  34187. var StopAnimationAction = (function (_super) {
  34188. __extends(StopAnimationAction, _super);
  34189. function StopAnimationAction(triggerOptions, target, condition) {
  34190. _super.call(this, triggerOptions, condition);
  34191. this._target = target;
  34192. }
  34193. StopAnimationAction.prototype._prepare = function () {
  34194. };
  34195. StopAnimationAction.prototype.execute = function () {
  34196. var scene = this._actionManager.getScene();
  34197. scene.stopAnimation(this._target);
  34198. };
  34199. StopAnimationAction.prototype.serialize = function (parent) {
  34200. return _super.prototype._serialize.call(this, {
  34201. name: "StopAnimationAction",
  34202. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  34203. }, parent);
  34204. };
  34205. return StopAnimationAction;
  34206. }(BABYLON.Action));
  34207. BABYLON.StopAnimationAction = StopAnimationAction;
  34208. var DoNothingAction = (function (_super) {
  34209. __extends(DoNothingAction, _super);
  34210. function DoNothingAction(triggerOptions, condition) {
  34211. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  34212. _super.call(this, triggerOptions, condition);
  34213. }
  34214. DoNothingAction.prototype.execute = function () {
  34215. };
  34216. DoNothingAction.prototype.serialize = function (parent) {
  34217. return _super.prototype._serialize.call(this, {
  34218. name: "DoNothingAction",
  34219. properties: []
  34220. }, parent);
  34221. };
  34222. return DoNothingAction;
  34223. }(BABYLON.Action));
  34224. BABYLON.DoNothingAction = DoNothingAction;
  34225. var CombineAction = (function (_super) {
  34226. __extends(CombineAction, _super);
  34227. function CombineAction(triggerOptions, children, condition) {
  34228. _super.call(this, triggerOptions, condition);
  34229. this.children = children;
  34230. }
  34231. CombineAction.prototype._prepare = function () {
  34232. for (var index = 0; index < this.children.length; index++) {
  34233. this.children[index]._actionManager = this._actionManager;
  34234. this.children[index]._prepare();
  34235. }
  34236. };
  34237. CombineAction.prototype.execute = function (evt) {
  34238. for (var index = 0; index < this.children.length; index++) {
  34239. this.children[index].execute(evt);
  34240. }
  34241. };
  34242. CombineAction.prototype.serialize = function (parent) {
  34243. var serializationObject = _super.prototype._serialize.call(this, {
  34244. name: "CombineAction",
  34245. properties: [],
  34246. combine: []
  34247. }, parent);
  34248. for (var i = 0; i < this.children.length; i++) {
  34249. serializationObject.combine.push(this.children[i].serialize(null));
  34250. }
  34251. return serializationObject;
  34252. };
  34253. return CombineAction;
  34254. }(BABYLON.Action));
  34255. BABYLON.CombineAction = CombineAction;
  34256. var ExecuteCodeAction = (function (_super) {
  34257. __extends(ExecuteCodeAction, _super);
  34258. function ExecuteCodeAction(triggerOptions, func, condition) {
  34259. _super.call(this, triggerOptions, condition);
  34260. this.func = func;
  34261. }
  34262. ExecuteCodeAction.prototype.execute = function (evt) {
  34263. this.func(evt);
  34264. };
  34265. return ExecuteCodeAction;
  34266. }(BABYLON.Action));
  34267. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  34268. var SetParentAction = (function (_super) {
  34269. __extends(SetParentAction, _super);
  34270. function SetParentAction(triggerOptions, target, parent, condition) {
  34271. _super.call(this, triggerOptions, condition);
  34272. this._target = target;
  34273. this._parent = parent;
  34274. }
  34275. SetParentAction.prototype._prepare = function () {
  34276. };
  34277. SetParentAction.prototype.execute = function () {
  34278. if (this._target.parent === this._parent) {
  34279. return;
  34280. }
  34281. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  34282. invertParentWorldMatrix.invert();
  34283. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  34284. this._target.parent = this._parent;
  34285. };
  34286. SetParentAction.prototype.serialize = function (parent) {
  34287. return _super.prototype._serialize.call(this, {
  34288. name: "SetParentAction",
  34289. properties: [
  34290. BABYLON.Action._GetTargetProperty(this._target),
  34291. BABYLON.Action._GetTargetProperty(this._parent),
  34292. ]
  34293. }, parent);
  34294. };
  34295. return SetParentAction;
  34296. }(BABYLON.Action));
  34297. BABYLON.SetParentAction = SetParentAction;
  34298. var PlaySoundAction = (function (_super) {
  34299. __extends(PlaySoundAction, _super);
  34300. function PlaySoundAction(triggerOptions, sound, condition) {
  34301. _super.call(this, triggerOptions, condition);
  34302. this._sound = sound;
  34303. }
  34304. PlaySoundAction.prototype._prepare = function () {
  34305. };
  34306. PlaySoundAction.prototype.execute = function () {
  34307. if (this._sound !== undefined)
  34308. this._sound.play();
  34309. };
  34310. PlaySoundAction.prototype.serialize = function (parent) {
  34311. return _super.prototype._serialize.call(this, {
  34312. name: "PlaySoundAction",
  34313. properties: [{ name: "sound", value: this._sound.name }]
  34314. }, parent);
  34315. };
  34316. return PlaySoundAction;
  34317. }(BABYLON.Action));
  34318. BABYLON.PlaySoundAction = PlaySoundAction;
  34319. var StopSoundAction = (function (_super) {
  34320. __extends(StopSoundAction, _super);
  34321. function StopSoundAction(triggerOptions, sound, condition) {
  34322. _super.call(this, triggerOptions, condition);
  34323. this._sound = sound;
  34324. }
  34325. StopSoundAction.prototype._prepare = function () {
  34326. };
  34327. StopSoundAction.prototype.execute = function () {
  34328. if (this._sound !== undefined)
  34329. this._sound.stop();
  34330. };
  34331. StopSoundAction.prototype.serialize = function (parent) {
  34332. return _super.prototype._serialize.call(this, {
  34333. name: "StopSoundAction",
  34334. properties: [{ name: "sound", value: this._sound.name }]
  34335. }, parent);
  34336. };
  34337. return StopSoundAction;
  34338. }(BABYLON.Action));
  34339. BABYLON.StopSoundAction = StopSoundAction;
  34340. })(BABYLON || (BABYLON = {}));
  34341. var BABYLON;
  34342. (function (BABYLON) {
  34343. var Geometry = (function () {
  34344. function Geometry(id, scene, vertexData, updatable, mesh) {
  34345. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  34346. this._totalVertices = 0;
  34347. this._isDisposed = false;
  34348. this.id = id;
  34349. this._engine = scene.getEngine();
  34350. this._meshes = [];
  34351. this._scene = scene;
  34352. //Init vertex buffer cache
  34353. this._vertexBuffers = {};
  34354. this._indices = [];
  34355. // vertexData
  34356. if (vertexData) {
  34357. this.setAllVerticesData(vertexData, updatable);
  34358. }
  34359. else {
  34360. this._totalVertices = 0;
  34361. this._indices = [];
  34362. }
  34363. // applyToMesh
  34364. if (mesh) {
  34365. if (mesh instanceof BABYLON.LinesMesh) {
  34366. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  34367. this.updateExtend();
  34368. }
  34369. this.applyToMesh(mesh);
  34370. mesh.computeWorldMatrix(true);
  34371. }
  34372. }
  34373. Object.defineProperty(Geometry.prototype, "boundingBias", {
  34374. /**
  34375. * 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
  34376. * @returns The Bias Vector
  34377. */
  34378. get: function () {
  34379. return this._boundingBias;
  34380. },
  34381. set: function (value) {
  34382. if (this._boundingBias && this._boundingBias.equals(value)) {
  34383. return;
  34384. }
  34385. this._boundingBias = value.clone();
  34386. this.updateBoundingInfo(true, null);
  34387. },
  34388. enumerable: true,
  34389. configurable: true
  34390. });
  34391. Object.defineProperty(Geometry.prototype, "extend", {
  34392. get: function () {
  34393. return this._extend;
  34394. },
  34395. enumerable: true,
  34396. configurable: true
  34397. });
  34398. Geometry.prototype.getScene = function () {
  34399. return this._scene;
  34400. };
  34401. Geometry.prototype.getEngine = function () {
  34402. return this._engine;
  34403. };
  34404. Geometry.prototype.isReady = function () {
  34405. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  34406. };
  34407. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  34408. vertexData.applyToGeometry(this, updatable);
  34409. this.notifyUpdate();
  34410. };
  34411. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  34412. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  34413. this.setVerticesBuffer(buffer);
  34414. };
  34415. Geometry.prototype.setVerticesBuffer = function (buffer) {
  34416. var kind = buffer.getKind();
  34417. if (this._vertexBuffers[kind]) {
  34418. this._vertexBuffers[kind].dispose();
  34419. }
  34420. this._vertexBuffers[kind] = buffer;
  34421. if (kind === BABYLON.VertexBuffer.PositionKind) {
  34422. var data = buffer.getData();
  34423. var stride = buffer.getStrideSize();
  34424. this._totalVertices = data.length / stride;
  34425. this.updateExtend(data, stride);
  34426. var meshes = this._meshes;
  34427. var numOfMeshes = meshes.length;
  34428. for (var index = 0; index < numOfMeshes; index++) {
  34429. var mesh = meshes[index];
  34430. mesh._resetPointsArrayCache();
  34431. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  34432. mesh._createGlobalSubMesh();
  34433. mesh.computeWorldMatrix(true);
  34434. }
  34435. }
  34436. this.notifyUpdate(kind);
  34437. };
  34438. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  34439. var vertexBuffer = this.getVertexBuffer(kind);
  34440. if (!vertexBuffer) {
  34441. return;
  34442. }
  34443. vertexBuffer.updateDirectly(data, offset);
  34444. this.notifyUpdate(kind);
  34445. };
  34446. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  34447. var vertexBuffer = this.getVertexBuffer(kind);
  34448. if (!vertexBuffer) {
  34449. return;
  34450. }
  34451. vertexBuffer.update(data);
  34452. if (kind === BABYLON.VertexBuffer.PositionKind) {
  34453. var stride = vertexBuffer.getStrideSize();
  34454. this._totalVertices = data.length / stride;
  34455. this.updateBoundingInfo(updateExtends, data);
  34456. }
  34457. this.notifyUpdate(kind);
  34458. };
  34459. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  34460. if (updateExtends) {
  34461. this.updateExtend(data);
  34462. }
  34463. var meshes = this._meshes;
  34464. var numOfMeshes = meshes.length;
  34465. for (var index = 0; index < numOfMeshes; index++) {
  34466. var mesh = meshes[index];
  34467. mesh._resetPointsArrayCache();
  34468. if (updateExtends) {
  34469. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  34470. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  34471. var subMesh = mesh.subMeshes[subIndex];
  34472. subMesh.refreshBoundingInfo();
  34473. }
  34474. }
  34475. }
  34476. };
  34477. Geometry.prototype.getTotalVertices = function () {
  34478. if (!this.isReady()) {
  34479. return 0;
  34480. }
  34481. return this._totalVertices;
  34482. };
  34483. Geometry.prototype.getVerticesData = function (kind, copyWhenShared) {
  34484. var vertexBuffer = this.getVertexBuffer(kind);
  34485. if (!vertexBuffer) {
  34486. return null;
  34487. }
  34488. var orig = vertexBuffer.getData();
  34489. if (!copyWhenShared || this._meshes.length === 1) {
  34490. return orig;
  34491. }
  34492. else {
  34493. var len = orig.length;
  34494. var copy = [];
  34495. for (var i = 0; i < len; i++) {
  34496. copy.push(orig[i]);
  34497. }
  34498. return copy;
  34499. }
  34500. };
  34501. Geometry.prototype.getVertexBuffer = function (kind) {
  34502. if (!this.isReady()) {
  34503. return null;
  34504. }
  34505. return this._vertexBuffers[kind];
  34506. };
  34507. Geometry.prototype.getVertexBuffers = function () {
  34508. if (!this.isReady()) {
  34509. return null;
  34510. }
  34511. return this._vertexBuffers;
  34512. };
  34513. Geometry.prototype.isVerticesDataPresent = function (kind) {
  34514. if (!this._vertexBuffers) {
  34515. if (this._delayInfo) {
  34516. return this._delayInfo.indexOf(kind) !== -1;
  34517. }
  34518. return false;
  34519. }
  34520. return this._vertexBuffers[kind] !== undefined;
  34521. };
  34522. Geometry.prototype.getVerticesDataKinds = function () {
  34523. var result = [];
  34524. var kind;
  34525. if (!this._vertexBuffers && this._delayInfo) {
  34526. for (kind in this._delayInfo) {
  34527. result.push(kind);
  34528. }
  34529. }
  34530. else {
  34531. for (kind in this._vertexBuffers) {
  34532. result.push(kind);
  34533. }
  34534. }
  34535. return result;
  34536. };
  34537. Geometry.prototype.setIndices = function (indices, totalVertices) {
  34538. if (this._indexBuffer) {
  34539. this._engine._releaseBuffer(this._indexBuffer);
  34540. }
  34541. this._indices = indices;
  34542. if (this._meshes.length !== 0 && this._indices) {
  34543. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  34544. }
  34545. if (totalVertices !== undefined) {
  34546. this._totalVertices = totalVertices;
  34547. }
  34548. var meshes = this._meshes;
  34549. var numOfMeshes = meshes.length;
  34550. for (var index = 0; index < numOfMeshes; index++) {
  34551. meshes[index]._createGlobalSubMesh();
  34552. }
  34553. this.notifyUpdate();
  34554. };
  34555. Geometry.prototype.getTotalIndices = function () {
  34556. if (!this.isReady()) {
  34557. return 0;
  34558. }
  34559. return this._indices.length;
  34560. };
  34561. Geometry.prototype.getIndices = function (copyWhenShared) {
  34562. if (!this.isReady()) {
  34563. return null;
  34564. }
  34565. var orig = this._indices;
  34566. if (!copyWhenShared || this._meshes.length === 1) {
  34567. return orig;
  34568. }
  34569. else {
  34570. var len = orig.length;
  34571. var copy = [];
  34572. for (var i = 0; i < len; i++) {
  34573. copy.push(orig[i]);
  34574. }
  34575. return copy;
  34576. }
  34577. };
  34578. Geometry.prototype.getIndexBuffer = function () {
  34579. if (!this.isReady()) {
  34580. return null;
  34581. }
  34582. return this._indexBuffer;
  34583. };
  34584. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  34585. var meshes = this._meshes;
  34586. var index = meshes.indexOf(mesh);
  34587. if (index === -1) {
  34588. return;
  34589. }
  34590. for (var kind in this._vertexBuffers) {
  34591. this._vertexBuffers[kind].dispose();
  34592. }
  34593. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  34594. this._indexBuffer = null;
  34595. }
  34596. meshes.splice(index, 1);
  34597. mesh._geometry = null;
  34598. if (meshes.length === 0 && shouldDispose) {
  34599. this.dispose();
  34600. }
  34601. };
  34602. Geometry.prototype.applyToMesh = function (mesh) {
  34603. if (mesh._geometry === this) {
  34604. return;
  34605. }
  34606. var previousGeometry = mesh._geometry;
  34607. if (previousGeometry) {
  34608. previousGeometry.releaseForMesh(mesh);
  34609. }
  34610. var meshes = this._meshes;
  34611. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  34612. mesh._geometry = this;
  34613. this._scene.pushGeometry(this);
  34614. meshes.push(mesh);
  34615. if (this.isReady()) {
  34616. this._applyToMesh(mesh);
  34617. }
  34618. else {
  34619. mesh._boundingInfo = this._boundingInfo;
  34620. }
  34621. };
  34622. Geometry.prototype.updateExtend = function (data, stride) {
  34623. if (data === void 0) { data = null; }
  34624. if (!data) {
  34625. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  34626. }
  34627. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  34628. };
  34629. Geometry.prototype._applyToMesh = function (mesh) {
  34630. var numOfMeshes = this._meshes.length;
  34631. // vertexBuffers
  34632. for (var kind in this._vertexBuffers) {
  34633. if (numOfMeshes === 1) {
  34634. this._vertexBuffers[kind].create();
  34635. }
  34636. this._vertexBuffers[kind].getBuffer().references = numOfMeshes;
  34637. if (kind === BABYLON.VertexBuffer.PositionKind) {
  34638. mesh._resetPointsArrayCache();
  34639. if (!this._extend) {
  34640. this.updateExtend(this._vertexBuffers[kind].getData());
  34641. }
  34642. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  34643. mesh._createGlobalSubMesh();
  34644. //bounding info was just created again, world matrix should be applied again.
  34645. mesh._updateBoundingInfo();
  34646. }
  34647. }
  34648. // indexBuffer
  34649. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  34650. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  34651. }
  34652. if (this._indexBuffer) {
  34653. this._indexBuffer.references = numOfMeshes;
  34654. }
  34655. };
  34656. Geometry.prototype.notifyUpdate = function (kind) {
  34657. if (this.onGeometryUpdated) {
  34658. this.onGeometryUpdated(this, kind);
  34659. }
  34660. };
  34661. Geometry.prototype.load = function (scene, onLoaded) {
  34662. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  34663. return;
  34664. }
  34665. if (this.isReady()) {
  34666. if (onLoaded) {
  34667. onLoaded();
  34668. }
  34669. return;
  34670. }
  34671. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  34672. this._queueLoad(scene, onLoaded);
  34673. };
  34674. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  34675. var _this = this;
  34676. scene._addPendingData(this);
  34677. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  34678. _this._delayLoadingFunction(JSON.parse(data), _this);
  34679. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  34680. _this._delayInfo = [];
  34681. scene._removePendingData(_this);
  34682. var meshes = _this._meshes;
  34683. var numOfMeshes = meshes.length;
  34684. for (var index = 0; index < numOfMeshes; index++) {
  34685. _this._applyToMesh(meshes[index]);
  34686. }
  34687. if (onLoaded) {
  34688. onLoaded();
  34689. }
  34690. }, function () { }, scene.database);
  34691. };
  34692. /**
  34693. * Invert the geometry to move from a right handed system to a left handed one.
  34694. */
  34695. Geometry.prototype.toLeftHanded = function () {
  34696. // Flip faces
  34697. var tIndices = this.getIndices(false);
  34698. if (tIndices != null && tIndices.length > 0) {
  34699. for (var i = 0; i < tIndices.length; i += 3) {
  34700. var tTemp = tIndices[i + 0];
  34701. tIndices[i + 0] = tIndices[i + 2];
  34702. tIndices[i + 2] = tTemp;
  34703. }
  34704. this.setIndices(tIndices);
  34705. }
  34706. // Negate position.z
  34707. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  34708. if (tPositions != null && tPositions.length > 0) {
  34709. for (var i = 0; i < tPositions.length; i += 3) {
  34710. tPositions[i + 2] = -tPositions[i + 2];
  34711. }
  34712. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  34713. }
  34714. // Negate normal.z
  34715. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  34716. if (tNormals != null && tNormals.length > 0) {
  34717. for (var i = 0; i < tNormals.length; i += 3) {
  34718. tNormals[i + 2] = -tNormals[i + 2];
  34719. }
  34720. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  34721. }
  34722. };
  34723. Geometry.prototype.isDisposed = function () {
  34724. return this._isDisposed;
  34725. };
  34726. Geometry.prototype.dispose = function () {
  34727. var meshes = this._meshes;
  34728. var numOfMeshes = meshes.length;
  34729. var index;
  34730. for (index = 0; index < numOfMeshes; index++) {
  34731. this.releaseForMesh(meshes[index]);
  34732. }
  34733. this._meshes = [];
  34734. for (var kind in this._vertexBuffers) {
  34735. this._vertexBuffers[kind].dispose();
  34736. }
  34737. this._vertexBuffers = {};
  34738. this._totalVertices = 0;
  34739. if (this._indexBuffer) {
  34740. this._engine._releaseBuffer(this._indexBuffer);
  34741. }
  34742. this._indexBuffer = null;
  34743. this._indices = [];
  34744. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  34745. this.delayLoadingFile = null;
  34746. this._delayLoadingFunction = null;
  34747. this._delayInfo = [];
  34748. this._boundingInfo = null;
  34749. this._scene.removeGeometry(this);
  34750. this._isDisposed = true;
  34751. };
  34752. Geometry.prototype.copy = function (id) {
  34753. var vertexData = new BABYLON.VertexData();
  34754. vertexData.indices = [];
  34755. var indices = this.getIndices();
  34756. for (var index = 0; index < indices.length; index++) {
  34757. vertexData.indices.push(indices[index]);
  34758. }
  34759. var updatable = false;
  34760. var stopChecking = false;
  34761. var kind;
  34762. for (kind in this._vertexBuffers) {
  34763. // using slice() to make a copy of the array and not just reference it
  34764. var data = this.getVerticesData(kind);
  34765. if (data instanceof Float32Array) {
  34766. vertexData.set(new Float32Array(data), kind);
  34767. }
  34768. else {
  34769. vertexData.set(data.slice(0), kind);
  34770. }
  34771. if (!stopChecking) {
  34772. updatable = this.getVertexBuffer(kind).isUpdatable();
  34773. stopChecking = !updatable;
  34774. }
  34775. }
  34776. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  34777. geometry.delayLoadState = this.delayLoadState;
  34778. geometry.delayLoadingFile = this.delayLoadingFile;
  34779. geometry._delayLoadingFunction = this._delayLoadingFunction;
  34780. for (kind in this._delayInfo) {
  34781. geometry._delayInfo = geometry._delayInfo || [];
  34782. geometry._delayInfo.push(kind);
  34783. }
  34784. // Bounding info
  34785. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  34786. return geometry;
  34787. };
  34788. Geometry.prototype.serialize = function () {
  34789. var serializationObject = {};
  34790. serializationObject.id = this.id;
  34791. if (BABYLON.Tags.HasTags(this)) {
  34792. serializationObject.tags = BABYLON.Tags.GetTags(this);
  34793. }
  34794. return serializationObject;
  34795. };
  34796. Geometry.prototype.serializeVerticeData = function () {
  34797. var serializationObject = this.serialize();
  34798. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  34799. serializationObject.positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34800. }
  34801. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  34802. serializationObject.normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  34803. }
  34804. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  34805. serializationObject.uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  34806. }
  34807. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  34808. serializationObject.uvs2 = this.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  34809. }
  34810. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  34811. serializationObject.uvs3 = this.getVerticesData(BABYLON.VertexBuffer.UV3Kind);
  34812. }
  34813. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  34814. serializationObject.uvs4 = this.getVerticesData(BABYLON.VertexBuffer.UV4Kind);
  34815. }
  34816. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  34817. serializationObject.uvs5 = this.getVerticesData(BABYLON.VertexBuffer.UV5Kind);
  34818. }
  34819. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  34820. serializationObject.uvs6 = this.getVerticesData(BABYLON.VertexBuffer.UV6Kind);
  34821. }
  34822. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  34823. serializationObject.colors = this.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  34824. }
  34825. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  34826. serializationObject.matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  34827. serializationObject.matricesIndices._isExpanded = true;
  34828. }
  34829. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  34830. serializationObject.matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  34831. }
  34832. serializationObject.indices = this.getIndices();
  34833. return serializationObject;
  34834. };
  34835. // Statics
  34836. Geometry.ExtractFromMesh = function (mesh, id) {
  34837. var geometry = mesh._geometry;
  34838. if (!geometry) {
  34839. return null;
  34840. }
  34841. return geometry.copy(id);
  34842. };
  34843. /**
  34844. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  34845. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  34846. * Be aware Math.random() could cause collisions, but:
  34847. * "All but 6 of the 128 bits of the ID are randomly generated, which means that for any two ids, there's a 1 in 2^^122 (or 5.3x10^^36) chance they'll collide"
  34848. */
  34849. Geometry.RandomId = function () {
  34850. return BABYLON.Tools.RandomId();
  34851. };
  34852. Geometry.ImportGeometry = function (parsedGeometry, mesh) {
  34853. var scene = mesh.getScene();
  34854. // Geometry
  34855. var geometryId = parsedGeometry.geometryId;
  34856. if (geometryId) {
  34857. var geometry = scene.getGeometryByID(geometryId);
  34858. if (geometry) {
  34859. geometry.applyToMesh(mesh);
  34860. }
  34861. }
  34862. else if (parsedGeometry instanceof ArrayBuffer) {
  34863. var binaryInfo = mesh._binaryInfo;
  34864. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  34865. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  34866. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  34867. }
  34868. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  34869. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  34870. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  34871. }
  34872. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  34873. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  34874. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  34875. }
  34876. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  34877. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  34878. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  34879. }
  34880. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  34881. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  34882. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  34883. }
  34884. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  34885. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  34886. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  34887. }
  34888. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  34889. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  34890. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  34891. }
  34892. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  34893. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  34894. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  34895. }
  34896. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  34897. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  34898. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  34899. }
  34900. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  34901. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  34902. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  34903. }
  34904. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  34905. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  34906. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  34907. }
  34908. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  34909. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  34910. mesh.setIndices(indicesData);
  34911. }
  34912. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  34913. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  34914. mesh.subMeshes = [];
  34915. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  34916. var materialIndex = subMeshesData[(i * 5) + 0];
  34917. var verticesStart = subMeshesData[(i * 5) + 1];
  34918. var verticesCount = subMeshesData[(i * 5) + 2];
  34919. var indexStart = subMeshesData[(i * 5) + 3];
  34920. var indexCount = subMeshesData[(i * 5) + 4];
  34921. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  34922. }
  34923. }
  34924. }
  34925. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  34926. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  34927. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  34928. if (parsedGeometry.uvs) {
  34929. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  34930. }
  34931. if (parsedGeometry.uvs2) {
  34932. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  34933. }
  34934. if (parsedGeometry.uvs3) {
  34935. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, false);
  34936. }
  34937. if (parsedGeometry.uvs4) {
  34938. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, false);
  34939. }
  34940. if (parsedGeometry.uvs5) {
  34941. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, false);
  34942. }
  34943. if (parsedGeometry.uvs6) {
  34944. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, false);
  34945. }
  34946. if (parsedGeometry.colors) {
  34947. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), false);
  34948. }
  34949. if (parsedGeometry.matricesIndices) {
  34950. if (!parsedGeometry.matricesIndices._isExpanded) {
  34951. var floatIndices = [];
  34952. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  34953. var matricesIndex = parsedGeometry.matricesIndices[i];
  34954. floatIndices.push(matricesIndex & 0x000000FF);
  34955. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  34956. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  34957. floatIndices.push(matricesIndex >> 24);
  34958. }
  34959. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  34960. }
  34961. else {
  34962. delete parsedGeometry.matricesIndices._isExpanded;
  34963. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  34964. }
  34965. }
  34966. if (parsedGeometry.matricesIndicesExtra) {
  34967. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  34968. var floatIndices = [];
  34969. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  34970. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  34971. floatIndices.push(matricesIndex & 0x000000FF);
  34972. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  34973. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  34974. floatIndices.push(matricesIndex >> 24);
  34975. }
  34976. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, false);
  34977. }
  34978. else {
  34979. delete parsedGeometry.matricesIndices._isExpanded;
  34980. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, false);
  34981. }
  34982. }
  34983. if (parsedGeometry.matricesWeights) {
  34984. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  34985. }
  34986. if (parsedGeometry.matricesWeightsExtra) {
  34987. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, false);
  34988. }
  34989. mesh.setIndices(parsedGeometry.indices);
  34990. }
  34991. // SubMeshes
  34992. if (parsedGeometry.subMeshes) {
  34993. mesh.subMeshes = [];
  34994. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  34995. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  34996. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  34997. }
  34998. }
  34999. // Flat shading
  35000. if (mesh._shouldGenerateFlatShading) {
  35001. mesh.convertToFlatShadedMesh();
  35002. delete mesh._shouldGenerateFlatShading;
  35003. }
  35004. // Update
  35005. mesh.computeWorldMatrix(true);
  35006. // Octree
  35007. if (scene['_selectionOctree']) {
  35008. scene['_selectionOctree'].addMesh(mesh);
  35009. }
  35010. };
  35011. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  35012. if (scene.getGeometryByID(parsedVertexData.id)) {
  35013. return null; // null since geometry could be something else than a box...
  35014. }
  35015. var geometry = new Geometry(parsedVertexData.id, scene);
  35016. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  35017. if (parsedVertexData.delayLoadingFile) {
  35018. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  35019. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  35020. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  35021. geometry._delayInfo = [];
  35022. if (parsedVertexData.hasUVs) {
  35023. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  35024. }
  35025. if (parsedVertexData.hasUVs2) {
  35026. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  35027. }
  35028. if (parsedVertexData.hasUVs3) {
  35029. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  35030. }
  35031. if (parsedVertexData.hasUVs4) {
  35032. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  35033. }
  35034. if (parsedVertexData.hasUVs5) {
  35035. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  35036. }
  35037. if (parsedVertexData.hasUVs6) {
  35038. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  35039. }
  35040. if (parsedVertexData.hasColors) {
  35041. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  35042. }
  35043. if (parsedVertexData.hasMatricesIndices) {
  35044. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  35045. }
  35046. if (parsedVertexData.hasMatricesWeights) {
  35047. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  35048. }
  35049. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  35050. }
  35051. else {
  35052. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  35053. }
  35054. scene.pushGeometry(geometry, true);
  35055. return geometry;
  35056. };
  35057. return Geometry;
  35058. }());
  35059. BABYLON.Geometry = Geometry;
  35060. /////// Primitives //////////////////////////////////////////////
  35061. var Geometry;
  35062. (function (Geometry) {
  35063. var Primitives;
  35064. (function (Primitives) {
  35065. /// Abstract class
  35066. var _Primitive = (function (_super) {
  35067. __extends(_Primitive, _super);
  35068. function _Primitive(id, scene, _canBeRegenerated, mesh) {
  35069. _super.call(this, id, scene, null, false, mesh); // updatable = false to be sure not to update vertices
  35070. this._canBeRegenerated = _canBeRegenerated;
  35071. this._beingRegenerated = true;
  35072. this.regenerate();
  35073. this._beingRegenerated = false;
  35074. }
  35075. _Primitive.prototype.canBeRegenerated = function () {
  35076. return this._canBeRegenerated;
  35077. };
  35078. _Primitive.prototype.regenerate = function () {
  35079. if (!this._canBeRegenerated) {
  35080. return;
  35081. }
  35082. this._beingRegenerated = true;
  35083. this.setAllVerticesData(this._regenerateVertexData(), false);
  35084. this._beingRegenerated = false;
  35085. };
  35086. _Primitive.prototype.asNewGeometry = function (id) {
  35087. return _super.prototype.copy.call(this, id);
  35088. };
  35089. // overrides
  35090. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  35091. if (!this._beingRegenerated) {
  35092. return;
  35093. }
  35094. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  35095. };
  35096. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  35097. if (!this._beingRegenerated) {
  35098. return;
  35099. }
  35100. _super.prototype.setVerticesData.call(this, kind, data, false);
  35101. };
  35102. // to override
  35103. // protected
  35104. _Primitive.prototype._regenerateVertexData = function () {
  35105. throw new Error("Abstract method");
  35106. };
  35107. _Primitive.prototype.copy = function (id) {
  35108. throw new Error("Must be overriden in sub-classes.");
  35109. };
  35110. _Primitive.prototype.serialize = function () {
  35111. var serializationObject = _super.prototype.serialize.call(this);
  35112. serializationObject.canBeRegenerated = this.canBeRegenerated();
  35113. return serializationObject;
  35114. };
  35115. return _Primitive;
  35116. }(Geometry));
  35117. Primitives._Primitive = _Primitive;
  35118. var Ribbon = (function (_super) {
  35119. __extends(Ribbon, _super);
  35120. // Members
  35121. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  35122. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35123. _super.call(this, id, scene, canBeRegenerated, mesh);
  35124. this.pathArray = pathArray;
  35125. this.closeArray = closeArray;
  35126. this.closePath = closePath;
  35127. this.offset = offset;
  35128. this.side = side;
  35129. }
  35130. Ribbon.prototype._regenerateVertexData = function () {
  35131. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  35132. };
  35133. Ribbon.prototype.copy = function (id) {
  35134. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  35135. };
  35136. return Ribbon;
  35137. }(_Primitive));
  35138. Primitives.Ribbon = Ribbon;
  35139. var Box = (function (_super) {
  35140. __extends(Box, _super);
  35141. // Members
  35142. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  35143. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35144. _super.call(this, id, scene, canBeRegenerated, mesh);
  35145. this.size = size;
  35146. this.side = side;
  35147. }
  35148. Box.prototype._regenerateVertexData = function () {
  35149. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  35150. };
  35151. Box.prototype.copy = function (id) {
  35152. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  35153. };
  35154. Box.prototype.serialize = function () {
  35155. var serializationObject = _super.prototype.serialize.call(this);
  35156. serializationObject.size = this.size;
  35157. return serializationObject;
  35158. };
  35159. Box.Parse = function (parsedBox, scene) {
  35160. if (scene.getGeometryByID(parsedBox.id)) {
  35161. return null; // null since geometry could be something else than a box...
  35162. }
  35163. var box = new Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  35164. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  35165. scene.pushGeometry(box, true);
  35166. return box;
  35167. };
  35168. return Box;
  35169. }(_Primitive));
  35170. Primitives.Box = Box;
  35171. var Sphere = (function (_super) {
  35172. __extends(Sphere, _super);
  35173. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  35174. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35175. _super.call(this, id, scene, canBeRegenerated, mesh);
  35176. this.segments = segments;
  35177. this.diameter = diameter;
  35178. this.side = side;
  35179. }
  35180. Sphere.prototype._regenerateVertexData = function () {
  35181. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  35182. };
  35183. Sphere.prototype.copy = function (id) {
  35184. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  35185. };
  35186. Sphere.prototype.serialize = function () {
  35187. var serializationObject = _super.prototype.serialize.call(this);
  35188. serializationObject.segments = this.segments;
  35189. serializationObject.diameter = this.diameter;
  35190. return serializationObject;
  35191. };
  35192. Sphere.Parse = function (parsedSphere, scene) {
  35193. if (scene.getGeometryByID(parsedSphere.id)) {
  35194. return null; // null since geometry could be something else than a sphere...
  35195. }
  35196. var sphere = new Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  35197. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  35198. scene.pushGeometry(sphere, true);
  35199. return sphere;
  35200. };
  35201. return Sphere;
  35202. }(_Primitive));
  35203. Primitives.Sphere = Sphere;
  35204. var Disc = (function (_super) {
  35205. __extends(Disc, _super);
  35206. // Members
  35207. function Disc(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  35208. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35209. _super.call(this, id, scene, canBeRegenerated, mesh);
  35210. this.radius = radius;
  35211. this.tessellation = tessellation;
  35212. this.side = side;
  35213. }
  35214. Disc.prototype._regenerateVertexData = function () {
  35215. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  35216. };
  35217. Disc.prototype.copy = function (id) {
  35218. return new Disc(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  35219. };
  35220. return Disc;
  35221. }(_Primitive));
  35222. Primitives.Disc = Disc;
  35223. var Cylinder = (function (_super) {
  35224. __extends(Cylinder, _super);
  35225. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  35226. if (subdivisions === void 0) { subdivisions = 1; }
  35227. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35228. _super.call(this, id, scene, canBeRegenerated, mesh);
  35229. this.height = height;
  35230. this.diameterTop = diameterTop;
  35231. this.diameterBottom = diameterBottom;
  35232. this.tessellation = tessellation;
  35233. this.subdivisions = subdivisions;
  35234. this.side = side;
  35235. }
  35236. Cylinder.prototype._regenerateVertexData = function () {
  35237. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  35238. };
  35239. Cylinder.prototype.copy = function (id) {
  35240. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  35241. };
  35242. Cylinder.prototype.serialize = function () {
  35243. var serializationObject = _super.prototype.serialize.call(this);
  35244. serializationObject.height = this.height;
  35245. serializationObject.diameterTop = this.diameterTop;
  35246. serializationObject.diameterBottom = this.diameterBottom;
  35247. serializationObject.tessellation = this.tessellation;
  35248. return serializationObject;
  35249. };
  35250. Cylinder.Parse = function (parsedCylinder, scene) {
  35251. if (scene.getGeometryByID(parsedCylinder.id)) {
  35252. return null; // null since geometry could be something else than a cylinder...
  35253. }
  35254. var cylinder = new Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  35255. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  35256. scene.pushGeometry(cylinder, true);
  35257. return cylinder;
  35258. };
  35259. return Cylinder;
  35260. }(_Primitive));
  35261. Primitives.Cylinder = Cylinder;
  35262. var Torus = (function (_super) {
  35263. __extends(Torus, _super);
  35264. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  35265. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35266. _super.call(this, id, scene, canBeRegenerated, mesh);
  35267. this.diameter = diameter;
  35268. this.thickness = thickness;
  35269. this.tessellation = tessellation;
  35270. this.side = side;
  35271. }
  35272. Torus.prototype._regenerateVertexData = function () {
  35273. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  35274. };
  35275. Torus.prototype.copy = function (id) {
  35276. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  35277. };
  35278. Torus.prototype.serialize = function () {
  35279. var serializationObject = _super.prototype.serialize.call(this);
  35280. serializationObject.diameter = this.diameter;
  35281. serializationObject.thickness = this.thickness;
  35282. serializationObject.tessellation = this.tessellation;
  35283. return serializationObject;
  35284. };
  35285. Torus.Parse = function (parsedTorus, scene) {
  35286. if (scene.getGeometryByID(parsedTorus.id)) {
  35287. return null; // null since geometry could be something else than a torus...
  35288. }
  35289. var torus = new Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  35290. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  35291. scene.pushGeometry(torus, true);
  35292. return torus;
  35293. };
  35294. return Torus;
  35295. }(_Primitive));
  35296. Primitives.Torus = Torus;
  35297. var Ground = (function (_super) {
  35298. __extends(Ground, _super);
  35299. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  35300. _super.call(this, id, scene, canBeRegenerated, mesh);
  35301. this.width = width;
  35302. this.height = height;
  35303. this.subdivisions = subdivisions;
  35304. }
  35305. Ground.prototype._regenerateVertexData = function () {
  35306. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  35307. };
  35308. Ground.prototype.copy = function (id) {
  35309. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  35310. };
  35311. Ground.prototype.serialize = function () {
  35312. var serializationObject = _super.prototype.serialize.call(this);
  35313. serializationObject.width = this.width;
  35314. serializationObject.height = this.height;
  35315. serializationObject.subdivisions = this.subdivisions;
  35316. return serializationObject;
  35317. };
  35318. Ground.Parse = function (parsedGround, scene) {
  35319. if (scene.getGeometryByID(parsedGround.id)) {
  35320. return null; // null since geometry could be something else than a ground...
  35321. }
  35322. var ground = new Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  35323. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  35324. scene.pushGeometry(ground, true);
  35325. return ground;
  35326. };
  35327. return Ground;
  35328. }(_Primitive));
  35329. Primitives.Ground = Ground;
  35330. var TiledGround = (function (_super) {
  35331. __extends(TiledGround, _super);
  35332. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  35333. _super.call(this, id, scene, canBeRegenerated, mesh);
  35334. this.xmin = xmin;
  35335. this.zmin = zmin;
  35336. this.xmax = xmax;
  35337. this.zmax = zmax;
  35338. this.subdivisions = subdivisions;
  35339. this.precision = precision;
  35340. }
  35341. TiledGround.prototype._regenerateVertexData = function () {
  35342. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  35343. };
  35344. TiledGround.prototype.copy = function (id) {
  35345. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  35346. };
  35347. return TiledGround;
  35348. }(_Primitive));
  35349. Primitives.TiledGround = TiledGround;
  35350. var Plane = (function (_super) {
  35351. __extends(Plane, _super);
  35352. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  35353. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35354. _super.call(this, id, scene, canBeRegenerated, mesh);
  35355. this.size = size;
  35356. this.side = side;
  35357. }
  35358. Plane.prototype._regenerateVertexData = function () {
  35359. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  35360. };
  35361. Plane.prototype.copy = function (id) {
  35362. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  35363. };
  35364. Plane.prototype.serialize = function () {
  35365. var serializationObject = _super.prototype.serialize.call(this);
  35366. serializationObject.size = this.size;
  35367. return serializationObject;
  35368. };
  35369. Plane.Parse = function (parsedPlane, scene) {
  35370. if (scene.getGeometryByID(parsedPlane.id)) {
  35371. return null; // null since geometry could be something else than a ground...
  35372. }
  35373. var plane = new Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  35374. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  35375. scene.pushGeometry(plane, true);
  35376. return plane;
  35377. };
  35378. return Plane;
  35379. }(_Primitive));
  35380. Primitives.Plane = Plane;
  35381. var TorusKnot = (function (_super) {
  35382. __extends(TorusKnot, _super);
  35383. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  35384. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35385. _super.call(this, id, scene, canBeRegenerated, mesh);
  35386. this.radius = radius;
  35387. this.tube = tube;
  35388. this.radialSegments = radialSegments;
  35389. this.tubularSegments = tubularSegments;
  35390. this.p = p;
  35391. this.q = q;
  35392. this.side = side;
  35393. }
  35394. TorusKnot.prototype._regenerateVertexData = function () {
  35395. 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 });
  35396. };
  35397. TorusKnot.prototype.copy = function (id) {
  35398. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  35399. };
  35400. TorusKnot.prototype.serialize = function () {
  35401. var serializationObject = _super.prototype.serialize.call(this);
  35402. serializationObject.radius = this.radius;
  35403. serializationObject.tube = this.tube;
  35404. serializationObject.radialSegments = this.radialSegments;
  35405. serializationObject.tubularSegments = this.tubularSegments;
  35406. serializationObject.p = this.p;
  35407. serializationObject.q = this.q;
  35408. return serializationObject;
  35409. };
  35410. ;
  35411. TorusKnot.Parse = function (parsedTorusKnot, scene) {
  35412. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  35413. return null; // null since geometry could be something else than a ground...
  35414. }
  35415. var torusKnot = new Geometry.Primitives.TorusKnot(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  35416. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  35417. scene.pushGeometry(torusKnot, true);
  35418. return torusKnot;
  35419. };
  35420. return TorusKnot;
  35421. }(_Primitive));
  35422. Primitives.TorusKnot = TorusKnot;
  35423. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  35424. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  35425. })(BABYLON || (BABYLON = {}));
  35426. var BABYLON;
  35427. (function (BABYLON) {
  35428. var GroundMesh = (function (_super) {
  35429. __extends(GroundMesh, _super);
  35430. function GroundMesh(name, scene) {
  35431. _super.call(this, name, scene);
  35432. this.generateOctree = false;
  35433. this._worldInverse = new BABYLON.Matrix();
  35434. }
  35435. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  35436. get: function () {
  35437. return Math.min(this._subdivisionsX, this._subdivisionsY);
  35438. },
  35439. enumerable: true,
  35440. configurable: true
  35441. });
  35442. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  35443. get: function () {
  35444. return this._subdivisionsX;
  35445. },
  35446. enumerable: true,
  35447. configurable: true
  35448. });
  35449. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  35450. get: function () {
  35451. return this._subdivisionsY;
  35452. },
  35453. enumerable: true,
  35454. configurable: true
  35455. });
  35456. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  35457. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  35458. this._subdivisionsX = chunksCount;
  35459. this._subdivisionsY = chunksCount;
  35460. this.subdivide(chunksCount);
  35461. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  35462. };
  35463. /**
  35464. * Returns a height (y) value in the Worl system :
  35465. * the ground altitude at the coordinates (x, z) expressed in the World system.
  35466. * Returns the ground y position if (x, z) are outside the ground surface.
  35467. * Not pertinent if the ground is rotated.
  35468. */
  35469. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  35470. // express x and y in the ground local system
  35471. x -= this.position.x;
  35472. z -= this.position.z;
  35473. x /= this.scaling.x;
  35474. z /= this.scaling.z;
  35475. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  35476. return this.position.y;
  35477. }
  35478. if (!this._heightQuads || this._heightQuads.length == 0) {
  35479. this._initHeightQuads();
  35480. this._computeHeightQuads();
  35481. }
  35482. var facet = this._getFacetAt(x, z);
  35483. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  35484. // return y in the World system
  35485. return y * this.scaling.y + this.position.y;
  35486. };
  35487. /**
  35488. * Returns a normalized vector (Vector3) orthogonal to the ground
  35489. * at the ground coordinates (x, z) expressed in the World system.
  35490. * Returns Vector3(0, 1, 0) if (x, z) are outside the ground surface.
  35491. * Not pertinent if the ground is rotated.
  35492. */
  35493. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  35494. var normal = new BABYLON.Vector3(0, 1, 0);
  35495. this.getNormalAtCoordinatesToRef(x, z, normal);
  35496. return normal;
  35497. };
  35498. /**
  35499. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  35500. * at the ground coordinates (x, z) expressed in the World system.
  35501. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  35502. * Not pertinent if the ground is rotated.
  35503. */
  35504. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  35505. // express x and y in the ground local system
  35506. x -= this.position.x;
  35507. z -= this.position.z;
  35508. x /= this.scaling.x;
  35509. z /= this.scaling.z;
  35510. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  35511. return;
  35512. }
  35513. if (!this._heightQuads || this._heightQuads.length == 0) {
  35514. this._initHeightQuads();
  35515. this._computeHeightQuads();
  35516. }
  35517. var facet = this._getFacetAt(x, z);
  35518. ref.x = facet.x;
  35519. ref.y = facet.y;
  35520. ref.z = facet.z;
  35521. };
  35522. /**
  35523. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  35524. * if the ground has been updated.
  35525. * This can be used in the render loop
  35526. */
  35527. GroundMesh.prototype.updateCoordinateHeights = function () {
  35528. if (!this._heightQuads || this._heightQuads.length == 0) {
  35529. this._initHeightQuads();
  35530. }
  35531. this._computeHeightQuads();
  35532. };
  35533. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  35534. GroundMesh.prototype._getFacetAt = function (x, z) {
  35535. // retrieve col and row from x, z coordinates in the ground local system
  35536. var subdivisionsX = this._subdivisionsX;
  35537. var subdivisionsY = this._subdivisionsY;
  35538. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  35539. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  35540. var quad = this._heightQuads[row * this._subdivisionsX + col];
  35541. var facet;
  35542. if (z < quad.slope.x * x + quad.slope.y) {
  35543. facet = quad.facet1;
  35544. }
  35545. else {
  35546. facet = quad.facet2;
  35547. }
  35548. return facet;
  35549. };
  35550. // Creates and populates the heightMap array with "facet" elements :
  35551. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  35552. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  35553. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  35554. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  35555. GroundMesh.prototype._initHeightQuads = function () {
  35556. var subdivisionsX = this._subdivisionsX;
  35557. var subdivisionsY = this._subdivisionsY;
  35558. this._heightQuads = new Array();
  35559. for (var row = 0; row < subdivisionsY; row++) {
  35560. for (var col = 0; col < subdivisionsX; col++) {
  35561. var quad = { slope: BABYLON.Vector2.Zero(), facet1: new BABYLON.Vector4(0, 0, 0, 0), facet2: new BABYLON.Vector4(0, 0, 0, 0) };
  35562. this._heightQuads[row * subdivisionsX + col] = quad;
  35563. }
  35564. }
  35565. };
  35566. // Compute each quad element values and update the the heightMap array :
  35567. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  35568. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  35569. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  35570. GroundMesh.prototype._computeHeightQuads = function () {
  35571. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  35572. var v1 = BABYLON.Tmp.Vector3[3];
  35573. var v2 = BABYLON.Tmp.Vector3[2];
  35574. var v3 = BABYLON.Tmp.Vector3[1];
  35575. var v4 = BABYLON.Tmp.Vector3[0];
  35576. var v1v2 = BABYLON.Tmp.Vector3[4];
  35577. var v1v3 = BABYLON.Tmp.Vector3[5];
  35578. var v1v4 = BABYLON.Tmp.Vector3[6];
  35579. var norm1 = BABYLON.Tmp.Vector3[7];
  35580. var norm2 = BABYLON.Tmp.Vector3[8];
  35581. var i = 0;
  35582. var j = 0;
  35583. var k = 0;
  35584. var cd = 0; // 2D slope coefficient : z = cd * x + h
  35585. var h = 0;
  35586. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  35587. var d2 = 0;
  35588. var subdivisionsX = this._subdivisionsX;
  35589. var subdivisionsY = this._subdivisionsY;
  35590. for (var row = 0; row < subdivisionsY; row++) {
  35591. for (var col = 0; col < subdivisionsX; col++) {
  35592. i = col * 3;
  35593. j = row * (subdivisionsX + 1) * 3;
  35594. k = (row + 1) * (subdivisionsX + 1) * 3;
  35595. v1.x = positions[j + i];
  35596. v1.y = positions[j + i + 1];
  35597. v1.z = positions[j + i + 2];
  35598. v2.x = positions[j + i + 3];
  35599. v2.y = positions[j + i + 4];
  35600. v2.z = positions[j + i + 5];
  35601. v3.x = positions[k + i];
  35602. v3.y = positions[k + i + 1];
  35603. v3.z = positions[k + i + 2];
  35604. v4.x = positions[k + i + 3];
  35605. v4.y = positions[k + i + 4];
  35606. v4.z = positions[k + i + 5];
  35607. // 2D slope V1V4
  35608. cd = (v4.z - v1.z) / (v4.x - v1.x);
  35609. h = v1.z - cd * v1.x; // v1 belongs to the slope
  35610. // facet equations :
  35611. // we compute each facet normal vector
  35612. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  35613. // we compute the value d by applying the equation to v1 which belongs to the plane
  35614. // then we store the facet equation in a Vector4
  35615. v2.subtractToRef(v1, v1v2);
  35616. v3.subtractToRef(v1, v1v3);
  35617. v4.subtractToRef(v1, v1v4);
  35618. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  35619. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  35620. norm1.normalize();
  35621. norm2.normalize();
  35622. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  35623. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  35624. var quad = this._heightQuads[row * subdivisionsX + col];
  35625. quad.slope.copyFromFloats(cd, h);
  35626. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  35627. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  35628. }
  35629. }
  35630. };
  35631. return GroundMesh;
  35632. }(BABYLON.Mesh));
  35633. BABYLON.GroundMesh = GroundMesh;
  35634. })(BABYLON || (BABYLON = {}));
  35635. var BABYLON;
  35636. (function (BABYLON) {
  35637. var LinesMesh = (function (_super) {
  35638. __extends(LinesMesh, _super);
  35639. function LinesMesh(name, scene, parent, source, doNotCloneChildren) {
  35640. if (parent === void 0) { parent = null; }
  35641. _super.call(this, name, scene, parent, source, doNotCloneChildren);
  35642. this.color = new BABYLON.Color3(1, 1, 1);
  35643. this.alpha = 1;
  35644. this._positionBuffer = {};
  35645. if (source) {
  35646. this.color = source.color.clone();
  35647. this.alpha = source.alpha;
  35648. }
  35649. this._intersectionThreshold = 0.1;
  35650. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  35651. attributes: [BABYLON.VertexBuffer.PositionKind],
  35652. uniforms: ["worldViewProjection", "color"],
  35653. needAlphaBlending: true
  35654. });
  35655. this._positionBuffer[BABYLON.VertexBuffer.PositionKind] = null;
  35656. }
  35657. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  35658. /**
  35659. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  35660. * This margin is expressed in world space coordinates, so its value may vary.
  35661. * Default value is 0.1
  35662. * @returns the intersection Threshold value.
  35663. */
  35664. get: function () {
  35665. return this._intersectionThreshold;
  35666. },
  35667. /**
  35668. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  35669. * This margin is expressed in world space coordinates, so its value may vary.
  35670. * @param value the new threshold to apply
  35671. */
  35672. set: function (value) {
  35673. if (this._intersectionThreshold === value) {
  35674. return;
  35675. }
  35676. this._intersectionThreshold = value;
  35677. if (this.geometry) {
  35678. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  35679. }
  35680. },
  35681. enumerable: true,
  35682. configurable: true
  35683. });
  35684. Object.defineProperty(LinesMesh.prototype, "material", {
  35685. get: function () {
  35686. return this._colorShader;
  35687. },
  35688. enumerable: true,
  35689. configurable: true
  35690. });
  35691. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  35692. get: function () {
  35693. return false;
  35694. },
  35695. enumerable: true,
  35696. configurable: true
  35697. });
  35698. LinesMesh.prototype.createInstance = function (name) {
  35699. BABYLON.Tools.Log("LinesMeshes do not support createInstance.");
  35700. return null;
  35701. };
  35702. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  35703. var engine = this.getScene().getEngine();
  35704. this._positionBuffer[BABYLON.VertexBuffer.PositionKind] = this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind);
  35705. // VBOs
  35706. engine.bindBuffers(this._positionBuffer, this._geometry.getIndexBuffer(), this._colorShader.getEffect());
  35707. // Color
  35708. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  35709. };
  35710. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  35711. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  35712. return;
  35713. }
  35714. var engine = this.getScene().getEngine();
  35715. // Draw order
  35716. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  35717. };
  35718. LinesMesh.prototype.dispose = function (doNotRecurse) {
  35719. this._colorShader.dispose();
  35720. _super.prototype.dispose.call(this, doNotRecurse);
  35721. };
  35722. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  35723. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  35724. };
  35725. return LinesMesh;
  35726. }(BABYLON.Mesh));
  35727. BABYLON.LinesMesh = LinesMesh;
  35728. })(BABYLON || (BABYLON = {}));
  35729. var BABYLON;
  35730. (function (BABYLON) {
  35731. var DefaultLoadingScreen = (function () {
  35732. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  35733. var _this = this;
  35734. if (_loadingText === void 0) { _loadingText = ""; }
  35735. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  35736. this._renderingCanvas = _renderingCanvas;
  35737. this._loadingText = _loadingText;
  35738. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  35739. // Resize
  35740. this._resizeLoadingUI = function () {
  35741. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  35742. _this._loadingDiv.style.position = "absolute";
  35743. _this._loadingDiv.style.left = canvasRect.left + "px";
  35744. _this._loadingDiv.style.top = canvasRect.top + "px";
  35745. _this._loadingDiv.style.width = canvasRect.width + "px";
  35746. _this._loadingDiv.style.height = canvasRect.height + "px";
  35747. };
  35748. }
  35749. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  35750. var _this = this;
  35751. if (this._loadingDiv) {
  35752. // Do not add a loading screen if there is already one
  35753. return;
  35754. }
  35755. this._loadingDiv = document.createElement("div");
  35756. this._loadingDiv.id = "babylonjsLoadingDiv";
  35757. this._loadingDiv.style.opacity = "0";
  35758. this._loadingDiv.style.transition = "opacity 1.5s ease";
  35759. // Loading text
  35760. this._loadingTextDiv = document.createElement("div");
  35761. this._loadingTextDiv.style.position = "absolute";
  35762. this._loadingTextDiv.style.left = "0";
  35763. this._loadingTextDiv.style.top = "50%";
  35764. this._loadingTextDiv.style.marginTop = "80px";
  35765. this._loadingTextDiv.style.width = "100%";
  35766. this._loadingTextDiv.style.height = "20px";
  35767. this._loadingTextDiv.style.fontFamily = "Arial";
  35768. this._loadingTextDiv.style.fontSize = "14px";
  35769. this._loadingTextDiv.style.color = "white";
  35770. this._loadingTextDiv.style.textAlign = "center";
  35771. this._loadingTextDiv.innerHTML = "Loading";
  35772. this._loadingDiv.appendChild(this._loadingTextDiv);
  35773. //set the predefined text
  35774. this._loadingTextDiv.innerHTML = this._loadingText;
  35775. // Loading img
  35776. var imgBack = new Image();
  35777. 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==";
  35778. imgBack.style.position = "absolute";
  35779. imgBack.style.left = "50%";
  35780. imgBack.style.top = "50%";
  35781. imgBack.style.marginLeft = "-50px";
  35782. imgBack.style.marginTop = "-50px";
  35783. imgBack.style.transition = "transform 1.0s ease";
  35784. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  35785. var deg = 360;
  35786. var onTransitionEnd = function () {
  35787. deg += 360;
  35788. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  35789. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  35790. };
  35791. imgBack.addEventListener("transitionend", onTransitionEnd);
  35792. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  35793. this._loadingDiv.appendChild(imgBack);
  35794. // front image
  35795. var imgFront = new Image();
  35796. 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=";
  35797. imgFront.style.position = "absolute";
  35798. imgFront.style.left = "50%";
  35799. imgFront.style.top = "50%";
  35800. imgFront.style.marginLeft = "-50px";
  35801. imgFront.style.marginTop = "-50px";
  35802. this._loadingDiv.appendChild(imgFront);
  35803. this._resizeLoadingUI();
  35804. window.addEventListener("resize", this._resizeLoadingUI);
  35805. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  35806. document.body.appendChild(this._loadingDiv);
  35807. setTimeout(function () {
  35808. _this._loadingDiv.style.opacity = "1";
  35809. imgBack.style.transform = "rotateZ(360deg)";
  35810. imgBack.style.webkitTransform = "rotateZ(360deg)";
  35811. }, 0);
  35812. };
  35813. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  35814. var _this = this;
  35815. if (!this._loadingDiv) {
  35816. return;
  35817. }
  35818. var onTransitionEnd = function () {
  35819. if (!_this._loadingDiv) {
  35820. return;
  35821. }
  35822. document.body.removeChild(_this._loadingDiv);
  35823. window.removeEventListener("resize", _this._resizeLoadingUI);
  35824. _this._loadingDiv = null;
  35825. };
  35826. this._loadingDiv.style.opacity = "0";
  35827. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  35828. };
  35829. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  35830. set: function (text) {
  35831. this._loadingText = text;
  35832. if (this._loadingTextDiv) {
  35833. this._loadingTextDiv.innerHTML = this._loadingText;
  35834. }
  35835. },
  35836. enumerable: true,
  35837. configurable: true
  35838. });
  35839. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  35840. get: function () {
  35841. return this._loadingDivBackgroundColor;
  35842. },
  35843. set: function (color) {
  35844. this._loadingDivBackgroundColor = color;
  35845. if (!this._loadingDiv) {
  35846. return;
  35847. }
  35848. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  35849. },
  35850. enumerable: true,
  35851. configurable: true
  35852. });
  35853. return DefaultLoadingScreen;
  35854. }());
  35855. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  35856. })(BABYLON || (BABYLON = {}));
  35857. var BABYLON;
  35858. (function (BABYLON) {
  35859. var AudioEngine = (function () {
  35860. function AudioEngine() {
  35861. this._audioContext = null;
  35862. this._audioContextInitialized = false;
  35863. this.canUseWebAudio = false;
  35864. this.WarnedWebAudioUnsupported = false;
  35865. this.unlocked = false;
  35866. this.isMP3supported = false;
  35867. this.isOGGsupported = false;
  35868. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  35869. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  35870. this.canUseWebAudio = true;
  35871. }
  35872. var audioElem = document.createElement('audio');
  35873. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  35874. this.isMP3supported = true;
  35875. }
  35876. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  35877. this.isOGGsupported = true;
  35878. }
  35879. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  35880. this._unlockiOSaudio();
  35881. }
  35882. else {
  35883. this.unlocked = true;
  35884. }
  35885. }
  35886. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  35887. get: function () {
  35888. if (!this._audioContextInitialized) {
  35889. this._initializeAudioContext();
  35890. }
  35891. return this._audioContext;
  35892. },
  35893. enumerable: true,
  35894. configurable: true
  35895. });
  35896. AudioEngine.prototype._unlockiOSaudio = function () {
  35897. var _this = this;
  35898. var unlockaudio = function () {
  35899. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  35900. var source = _this.audioContext.createBufferSource();
  35901. source.buffer = buffer;
  35902. source.connect(_this.audioContext.destination);
  35903. source.start(0);
  35904. setTimeout(function () {
  35905. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  35906. _this.unlocked = true;
  35907. window.removeEventListener('touchend', unlockaudio, false);
  35908. if (_this.onAudioUnlocked) {
  35909. _this.onAudioUnlocked();
  35910. }
  35911. }
  35912. }, 0);
  35913. };
  35914. window.addEventListener('touchend', unlockaudio, false);
  35915. };
  35916. AudioEngine.prototype._initializeAudioContext = function () {
  35917. try {
  35918. if (this.canUseWebAudio) {
  35919. this._audioContext = new AudioContext();
  35920. // create a global volume gain node
  35921. this.masterGain = this._audioContext.createGain();
  35922. this.masterGain.gain.value = 1;
  35923. this.masterGain.connect(this._audioContext.destination);
  35924. this._audioContextInitialized = true;
  35925. }
  35926. }
  35927. catch (e) {
  35928. this.canUseWebAudio = false;
  35929. BABYLON.Tools.Error("Web Audio: " + e.message);
  35930. }
  35931. };
  35932. AudioEngine.prototype.dispose = function () {
  35933. if (this.canUseWebAudio && this._audioContextInitialized) {
  35934. if (this._connectedAnalyser) {
  35935. this._connectedAnalyser.stopDebugCanvas();
  35936. this._connectedAnalyser.dispose();
  35937. this.masterGain.disconnect();
  35938. this.masterGain.connect(this._audioContext.destination);
  35939. this._connectedAnalyser = null;
  35940. }
  35941. this.masterGain.gain.value = 1;
  35942. }
  35943. this.WarnedWebAudioUnsupported = false;
  35944. };
  35945. AudioEngine.prototype.getGlobalVolume = function () {
  35946. if (this.canUseWebAudio && this._audioContextInitialized) {
  35947. return this.masterGain.gain.value;
  35948. }
  35949. else {
  35950. return -1;
  35951. }
  35952. };
  35953. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  35954. if (this.canUseWebAudio && this._audioContextInitialized) {
  35955. this.masterGain.gain.value = newVolume;
  35956. }
  35957. };
  35958. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  35959. if (this._connectedAnalyser) {
  35960. this._connectedAnalyser.stopDebugCanvas();
  35961. }
  35962. if (this.canUseWebAudio && this._audioContextInitialized) {
  35963. this._connectedAnalyser = analyser;
  35964. this.masterGain.disconnect();
  35965. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  35966. }
  35967. };
  35968. return AudioEngine;
  35969. }());
  35970. BABYLON.AudioEngine = AudioEngine;
  35971. })(BABYLON || (BABYLON = {}));
  35972. var BABYLON;
  35973. (function (BABYLON) {
  35974. var Sound = (function () {
  35975. /**
  35976. * Create a sound and attach it to a scene
  35977. * @param name Name of your sound
  35978. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  35979. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  35980. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  35981. */
  35982. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  35983. var _this = this;
  35984. this.autoplay = false;
  35985. this.loop = false;
  35986. this.useCustomAttenuation = false;
  35987. this.spatialSound = false;
  35988. this.refDistance = 1;
  35989. this.rolloffFactor = 1;
  35990. this.maxDistance = 100;
  35991. this.distanceModel = "linear";
  35992. this._panningModel = "equalpower";
  35993. this._playbackRate = 1;
  35994. this._streaming = false;
  35995. this._startTime = 0;
  35996. this._startOffset = 0;
  35997. this._position = BABYLON.Vector3.Zero();
  35998. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  35999. this._volume = 1;
  36000. this._isLoaded = false;
  36001. this._isReadyToPlay = false;
  36002. this.isPlaying = false;
  36003. this.isPaused = false;
  36004. this._isDirectional = false;
  36005. // Used if you'd like to create a directional sound.
  36006. // If not set, the sound will be omnidirectional
  36007. this._coneInnerAngle = 360;
  36008. this._coneOuterAngle = 360;
  36009. this._coneOuterGain = 0;
  36010. this._isOutputConnected = false;
  36011. this._urlType = "Unknown";
  36012. this.name = name;
  36013. this._scene = scene;
  36014. this._readyToPlayCallback = readyToPlayCallback;
  36015. // Default custom attenuation function is a linear attenuation
  36016. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  36017. if (currentDistance < maxDistance) {
  36018. return currentVolume * (1 - currentDistance / maxDistance);
  36019. }
  36020. else {
  36021. return 0;
  36022. }
  36023. };
  36024. if (options) {
  36025. this.autoplay = options.autoplay || false;
  36026. this.loop = options.loop || false;
  36027. // if volume === 0, we need another way to check this option
  36028. if (options.volume !== undefined) {
  36029. this._volume = options.volume;
  36030. }
  36031. this.spatialSound = options.spatialSound || false;
  36032. this.maxDistance = options.maxDistance || 100;
  36033. this.useCustomAttenuation = options.useCustomAttenuation || false;
  36034. this.rolloffFactor = options.rolloffFactor || 1;
  36035. this.refDistance = options.refDistance || 1;
  36036. this.distanceModel = options.distanceModel || "linear";
  36037. this._playbackRate = options.playbackRate || 1;
  36038. this._streaming = options.streaming || false;
  36039. }
  36040. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  36041. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  36042. this._soundGain.gain.value = this._volume;
  36043. this._inputAudioNode = this._soundGain;
  36044. this._ouputAudioNode = this._soundGain;
  36045. if (this.spatialSound) {
  36046. this._createSpatialParameters();
  36047. }
  36048. this._scene.mainSoundTrack.AddSound(this);
  36049. var validParameter = true;
  36050. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  36051. if (urlOrArrayBuffer) {
  36052. if (typeof (urlOrArrayBuffer) === "string")
  36053. this._urlType = "String";
  36054. if (Array.isArray(urlOrArrayBuffer))
  36055. this._urlType = "Array";
  36056. if (urlOrArrayBuffer instanceof ArrayBuffer)
  36057. this._urlType = "ArrayBuffer";
  36058. var urls = [];
  36059. var codecSupportedFound = false;
  36060. switch (this._urlType) {
  36061. case "ArrayBuffer":
  36062. if (urlOrArrayBuffer.byteLength > 0) {
  36063. codecSupportedFound = true;
  36064. this._soundLoaded(urlOrArrayBuffer);
  36065. }
  36066. break;
  36067. case "String":
  36068. urls.push(urlOrArrayBuffer);
  36069. case "Array":
  36070. if (urls.length === 0)
  36071. urls = urlOrArrayBuffer;
  36072. // If we found a supported format, we load it immediately and stop the loop
  36073. for (var i = 0; i < urls.length; i++) {
  36074. var url = urls[i];
  36075. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  36076. codecSupportedFound = true;
  36077. }
  36078. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  36079. codecSupportedFound = true;
  36080. }
  36081. if (url.indexOf(".wav", url.length - 4) !== -1) {
  36082. codecSupportedFound = true;
  36083. }
  36084. if (codecSupportedFound) {
  36085. // Loading sound using XHR2
  36086. if (!this._streaming) {
  36087. BABYLON.Tools.LoadFile(url, function (data) { _this._soundLoaded(data); }, null, this._scene.database, true);
  36088. }
  36089. else {
  36090. this._htmlAudioElement = new Audio(url);
  36091. this._htmlAudioElement.controls = false;
  36092. this._htmlAudioElement.loop = this.loop;
  36093. this._htmlAudioElement.crossOrigin = "anonymous";
  36094. this._htmlAudioElement.preload = "auto";
  36095. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  36096. _this._isReadyToPlay = true;
  36097. if (_this.autoplay) {
  36098. _this.play();
  36099. }
  36100. if (_this._readyToPlayCallback) {
  36101. _this._readyToPlayCallback();
  36102. }
  36103. });
  36104. document.body.appendChild(this._htmlAudioElement);
  36105. }
  36106. break;
  36107. }
  36108. }
  36109. break;
  36110. default:
  36111. validParameter = false;
  36112. break;
  36113. }
  36114. if (!validParameter) {
  36115. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  36116. }
  36117. else {
  36118. if (!codecSupportedFound) {
  36119. // Simulating a ready to play event to avoid breaking code path
  36120. if (this._readyToPlayCallback) {
  36121. window.setTimeout(function () {
  36122. _this._readyToPlayCallback();
  36123. }, 1000);
  36124. }
  36125. }
  36126. }
  36127. }
  36128. }
  36129. else {
  36130. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  36131. this._scene.mainSoundTrack.AddSound(this);
  36132. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  36133. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  36134. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  36135. }
  36136. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  36137. if (this._readyToPlayCallback) {
  36138. window.setTimeout(function () {
  36139. _this._readyToPlayCallback();
  36140. }, 1000);
  36141. }
  36142. }
  36143. }
  36144. Sound.prototype.dispose = function () {
  36145. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  36146. if (this.isPlaying) {
  36147. this.stop();
  36148. }
  36149. this._isReadyToPlay = false;
  36150. if (this.soundTrackId === -1) {
  36151. this._scene.mainSoundTrack.RemoveSound(this);
  36152. }
  36153. else {
  36154. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  36155. }
  36156. if (this._soundGain) {
  36157. this._soundGain.disconnect();
  36158. this._soundGain = null;
  36159. }
  36160. if (this._soundPanner) {
  36161. this._soundPanner.disconnect();
  36162. this._soundPanner = null;
  36163. }
  36164. if (this._soundSource) {
  36165. this._soundSource.disconnect();
  36166. this._soundSource = null;
  36167. }
  36168. this._audioBuffer = null;
  36169. if (this._htmlAudioElement) {
  36170. this._htmlAudioElement.pause();
  36171. this._htmlAudioElement.src = "";
  36172. document.body.removeChild(this._htmlAudioElement);
  36173. }
  36174. if (this._connectedMesh) {
  36175. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  36176. this._connectedMesh = null;
  36177. }
  36178. }
  36179. };
  36180. Sound.prototype._soundLoaded = function (audioData) {
  36181. var _this = this;
  36182. this._isLoaded = true;
  36183. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  36184. _this._audioBuffer = buffer;
  36185. _this._isReadyToPlay = true;
  36186. if (_this.autoplay) {
  36187. _this.play();
  36188. }
  36189. if (_this._readyToPlayCallback) {
  36190. _this._readyToPlayCallback();
  36191. }
  36192. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  36193. };
  36194. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  36195. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  36196. this._audioBuffer = audioBuffer;
  36197. this._isReadyToPlay = true;
  36198. }
  36199. };
  36200. Sound.prototype.updateOptions = function (options) {
  36201. if (options) {
  36202. this.loop = options.loop || this.loop;
  36203. this.maxDistance = options.maxDistance || this.maxDistance;
  36204. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  36205. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  36206. this.refDistance = options.refDistance || this.refDistance;
  36207. this.distanceModel = options.distanceModel || this.distanceModel;
  36208. this._playbackRate = options.playbackRate || this._playbackRate;
  36209. this._updateSpatialParameters();
  36210. if (this.isPlaying) {
  36211. if (this._streaming) {
  36212. this._htmlAudioElement.playbackRate = this._playbackRate;
  36213. }
  36214. else {
  36215. this._soundSource.playbackRate.value = this._playbackRate;
  36216. }
  36217. }
  36218. }
  36219. };
  36220. Sound.prototype._createSpatialParameters = function () {
  36221. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  36222. if (this._scene.headphone) {
  36223. this._panningModel = "HRTF";
  36224. }
  36225. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  36226. this._updateSpatialParameters();
  36227. this._soundPanner.connect(this._ouputAudioNode);
  36228. this._inputAudioNode = this._soundPanner;
  36229. }
  36230. };
  36231. Sound.prototype._updateSpatialParameters = function () {
  36232. if (this.spatialSound) {
  36233. if (this.useCustomAttenuation) {
  36234. // Tricks to disable in a way embedded Web Audio attenuation
  36235. this._soundPanner.distanceModel = "linear";
  36236. this._soundPanner.maxDistance = Number.MAX_VALUE;
  36237. this._soundPanner.refDistance = 1;
  36238. this._soundPanner.rolloffFactor = 1;
  36239. this._soundPanner.panningModel = this._panningModel;
  36240. }
  36241. else {
  36242. this._soundPanner.distanceModel = this.distanceModel;
  36243. this._soundPanner.maxDistance = this.maxDistance;
  36244. this._soundPanner.refDistance = this.refDistance;
  36245. this._soundPanner.rolloffFactor = this.rolloffFactor;
  36246. this._soundPanner.panningModel = this._panningModel;
  36247. }
  36248. }
  36249. };
  36250. Sound.prototype.switchPanningModelToHRTF = function () {
  36251. this._panningModel = "HRTF";
  36252. this._switchPanningModel();
  36253. };
  36254. Sound.prototype.switchPanningModelToEqualPower = function () {
  36255. this._panningModel = "equalpower";
  36256. this._switchPanningModel();
  36257. };
  36258. Sound.prototype._switchPanningModel = function () {
  36259. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  36260. this._soundPanner.panningModel = this._panningModel;
  36261. }
  36262. };
  36263. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  36264. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  36265. if (this._isOutputConnected) {
  36266. this._ouputAudioNode.disconnect();
  36267. }
  36268. this._ouputAudioNode.connect(soundTrackAudioNode);
  36269. this._isOutputConnected = true;
  36270. }
  36271. };
  36272. /**
  36273. * Transform this sound into a directional source
  36274. * @param coneInnerAngle Size of the inner cone in degree
  36275. * @param coneOuterAngle Size of the outer cone in degree
  36276. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  36277. */
  36278. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  36279. if (coneOuterAngle < coneInnerAngle) {
  36280. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  36281. return;
  36282. }
  36283. this._coneInnerAngle = coneInnerAngle;
  36284. this._coneOuterAngle = coneOuterAngle;
  36285. this._coneOuterGain = coneOuterGain;
  36286. this._isDirectional = true;
  36287. if (this.isPlaying && this.loop) {
  36288. this.stop();
  36289. this.play();
  36290. }
  36291. };
  36292. Sound.prototype.setPosition = function (newPosition) {
  36293. this._position = newPosition;
  36294. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  36295. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  36296. }
  36297. };
  36298. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  36299. this._localDirection = newLocalDirection;
  36300. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  36301. this._updateDirection();
  36302. }
  36303. };
  36304. Sound.prototype._updateDirection = function () {
  36305. var mat = this._connectedMesh.getWorldMatrix();
  36306. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  36307. direction.normalize();
  36308. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  36309. };
  36310. Sound.prototype.updateDistanceFromListener = function () {
  36311. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation) {
  36312. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  36313. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  36314. }
  36315. };
  36316. Sound.prototype.setAttenuationFunction = function (callback) {
  36317. this._customAttenuationFunction = callback;
  36318. };
  36319. /**
  36320. * Play the sound
  36321. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  36322. * @param offset (optional) Start the sound setting it at a specific time
  36323. */
  36324. Sound.prototype.play = function (time, offset) {
  36325. var _this = this;
  36326. if (this._isReadyToPlay && this._scene.audioEnabled) {
  36327. try {
  36328. if (this._startOffset < 0) {
  36329. time = -this._startOffset;
  36330. this._startOffset = 0;
  36331. }
  36332. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  36333. if (!this._soundSource || !this._streamingSource) {
  36334. if (this.spatialSound) {
  36335. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  36336. if (this._isDirectional) {
  36337. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  36338. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  36339. this._soundPanner.coneOuterGain = this._coneOuterGain;
  36340. if (this._connectedMesh) {
  36341. this._updateDirection();
  36342. }
  36343. else {
  36344. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  36345. }
  36346. }
  36347. }
  36348. }
  36349. if (this._streaming) {
  36350. if (!this._streamingSource) {
  36351. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  36352. this._htmlAudioElement.onended = function () { _this._onended(); };
  36353. this._htmlAudioElement.playbackRate = this._playbackRate;
  36354. }
  36355. this._streamingSource.disconnect();
  36356. this._streamingSource.connect(this._inputAudioNode);
  36357. this._htmlAudioElement.play();
  36358. }
  36359. else {
  36360. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  36361. this._soundSource.buffer = this._audioBuffer;
  36362. this._soundSource.connect(this._inputAudioNode);
  36363. this._soundSource.loop = this.loop;
  36364. this._soundSource.playbackRate.value = this._playbackRate;
  36365. this._soundSource.onended = function () { _this._onended(); };
  36366. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  36367. }
  36368. this._startTime = startTime;
  36369. this.isPlaying = true;
  36370. this.isPaused = false;
  36371. }
  36372. catch (ex) {
  36373. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  36374. }
  36375. }
  36376. };
  36377. Sound.prototype._onended = function () {
  36378. this.isPlaying = false;
  36379. if (this.onended) {
  36380. this.onended();
  36381. }
  36382. };
  36383. /**
  36384. * Stop the sound
  36385. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  36386. */
  36387. Sound.prototype.stop = function (time) {
  36388. if (this.isPlaying) {
  36389. if (this._streaming) {
  36390. this._htmlAudioElement.pause();
  36391. // Test needed for Firefox or it will generate an Invalid State Error
  36392. if (this._htmlAudioElement.currentTime > 0) {
  36393. this._htmlAudioElement.currentTime = 0;
  36394. }
  36395. }
  36396. else {
  36397. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  36398. this._soundSource.stop(stopTime);
  36399. this._soundSource.onended = null;
  36400. if (!this.isPaused) {
  36401. this._startOffset = 0;
  36402. }
  36403. }
  36404. this.isPlaying = false;
  36405. }
  36406. };
  36407. Sound.prototype.pause = function () {
  36408. if (this.isPlaying) {
  36409. this.isPaused = true;
  36410. if (this._streaming) {
  36411. this._htmlAudioElement.pause();
  36412. }
  36413. else {
  36414. this.stop(0);
  36415. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  36416. }
  36417. }
  36418. };
  36419. Sound.prototype.setVolume = function (newVolume, time) {
  36420. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  36421. if (time) {
  36422. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  36423. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  36424. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  36425. }
  36426. else {
  36427. this._soundGain.gain.value = newVolume;
  36428. }
  36429. }
  36430. this._volume = newVolume;
  36431. };
  36432. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  36433. this._playbackRate = newPlaybackRate;
  36434. if (this.isPlaying) {
  36435. if (this._streaming) {
  36436. this._htmlAudioElement.playbackRate = this._playbackRate;
  36437. }
  36438. else {
  36439. this._soundSource.playbackRate.value = this._playbackRate;
  36440. }
  36441. }
  36442. };
  36443. Sound.prototype.getVolume = function () {
  36444. return this._volume;
  36445. };
  36446. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  36447. var _this = this;
  36448. if (this._connectedMesh) {
  36449. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  36450. this._registerFunc = null;
  36451. }
  36452. this._connectedMesh = meshToConnectTo;
  36453. if (!this.spatialSound) {
  36454. this.spatialSound = true;
  36455. this._createSpatialParameters();
  36456. if (this.isPlaying && this.loop) {
  36457. this.stop();
  36458. this.play();
  36459. }
  36460. }
  36461. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  36462. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  36463. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  36464. };
  36465. Sound.prototype.detachFromMesh = function () {
  36466. if (this._connectedMesh) {
  36467. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  36468. this._registerFunc = null;
  36469. this._connectedMesh = null;
  36470. }
  36471. };
  36472. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  36473. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  36474. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  36475. this._updateDirection();
  36476. }
  36477. };
  36478. Sound.prototype.clone = function () {
  36479. var _this = this;
  36480. if (!this._streaming) {
  36481. var setBufferAndRun = function () {
  36482. if (_this._isReadyToPlay) {
  36483. clonedSound._audioBuffer = _this.getAudioBuffer();
  36484. clonedSound._isReadyToPlay = true;
  36485. if (clonedSound.autoplay) {
  36486. clonedSound.play();
  36487. }
  36488. }
  36489. else {
  36490. window.setTimeout(setBufferAndRun, 300);
  36491. }
  36492. };
  36493. var currentOptions = {
  36494. autoplay: this.autoplay, loop: this.loop,
  36495. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  36496. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  36497. refDistance: this.refDistance, distanceModel: this.distanceModel
  36498. };
  36499. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  36500. if (this.useCustomAttenuation) {
  36501. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  36502. }
  36503. clonedSound.setPosition(this._position);
  36504. clonedSound.setPlaybackRate(this._playbackRate);
  36505. setBufferAndRun();
  36506. return clonedSound;
  36507. }
  36508. else {
  36509. return null;
  36510. }
  36511. };
  36512. Sound.prototype.getAudioBuffer = function () {
  36513. return this._audioBuffer;
  36514. };
  36515. Sound.prototype.serialize = function () {
  36516. var serializationObject = {
  36517. name: this.name,
  36518. url: this.name,
  36519. autoplay: this.autoplay,
  36520. loop: this.loop,
  36521. volume: this._volume,
  36522. spatialSound: this.spatialSound,
  36523. maxDistance: this.maxDistance,
  36524. rolloffFactor: this.rolloffFactor,
  36525. refDistance: this.refDistance,
  36526. distanceModel: this.distanceModel,
  36527. playbackRate: this._playbackRate,
  36528. panningModel: this._panningModel,
  36529. soundTrackId: this.soundTrackId
  36530. };
  36531. if (this.spatialSound) {
  36532. if (this._connectedMesh)
  36533. serializationObject.connectedMeshId = this._connectedMesh.id;
  36534. serializationObject.position = this._position.asArray();
  36535. serializationObject.refDistance = this.refDistance;
  36536. serializationObject.distanceModel = this.distanceModel;
  36537. serializationObject.isDirectional = this._isDirectional;
  36538. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  36539. serializationObject.coneInnerAngle = this._coneInnerAngle;
  36540. serializationObject.coneOuterAngle = this._coneOuterAngle;
  36541. serializationObject.coneOuterGain = this._coneOuterGain;
  36542. }
  36543. return serializationObject;
  36544. };
  36545. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  36546. var soundName = parsedSound.name;
  36547. var soundUrl;
  36548. if (parsedSound.url) {
  36549. soundUrl = rootUrl + parsedSound.url;
  36550. }
  36551. else {
  36552. soundUrl = rootUrl + soundName;
  36553. }
  36554. var options = {
  36555. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  36556. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  36557. rolloffFactor: parsedSound.rolloffFactor,
  36558. refDistance: parsedSound.refDistance,
  36559. distanceModel: parsedSound.distanceModel,
  36560. playbackRate: parsedSound.playbackRate
  36561. };
  36562. var newSound;
  36563. if (!sourceSound) {
  36564. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  36565. scene._addPendingData(newSound);
  36566. }
  36567. else {
  36568. var setBufferAndRun = function () {
  36569. if (sourceSound._isReadyToPlay) {
  36570. newSound._audioBuffer = sourceSound.getAudioBuffer();
  36571. newSound._isReadyToPlay = true;
  36572. if (newSound.autoplay) {
  36573. newSound.play();
  36574. }
  36575. }
  36576. else {
  36577. window.setTimeout(setBufferAndRun, 300);
  36578. }
  36579. };
  36580. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  36581. setBufferAndRun();
  36582. }
  36583. if (parsedSound.position) {
  36584. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  36585. newSound.setPosition(soundPosition);
  36586. }
  36587. if (parsedSound.isDirectional) {
  36588. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  36589. if (parsedSound.localDirectionToMesh) {
  36590. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  36591. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  36592. }
  36593. }
  36594. if (parsedSound.connectedMeshId) {
  36595. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  36596. if (connectedMesh) {
  36597. newSound.attachToMesh(connectedMesh);
  36598. }
  36599. }
  36600. return newSound;
  36601. };
  36602. return Sound;
  36603. }());
  36604. BABYLON.Sound = Sound;
  36605. })(BABYLON || (BABYLON = {}));
  36606. var BABYLON;
  36607. (function (BABYLON) {
  36608. var SoundTrack = (function () {
  36609. function SoundTrack(scene, options) {
  36610. this.id = -1;
  36611. this._isMainTrack = false;
  36612. this._isInitialized = false;
  36613. this._scene = scene;
  36614. this.soundCollection = new Array();
  36615. this._options = options;
  36616. if (!this._isMainTrack) {
  36617. this._scene.soundTracks.push(this);
  36618. this.id = this._scene.soundTracks.length - 1;
  36619. }
  36620. }
  36621. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  36622. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  36623. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  36624. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  36625. if (this._options) {
  36626. if (this._options.volume) {
  36627. this._outputAudioNode.gain.value = this._options.volume;
  36628. }
  36629. if (this._options.mainTrack) {
  36630. this._isMainTrack = this._options.mainTrack;
  36631. }
  36632. }
  36633. this._isInitialized = true;
  36634. }
  36635. };
  36636. SoundTrack.prototype.dispose = function () {
  36637. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  36638. if (this._connectedAnalyser) {
  36639. this._connectedAnalyser.stopDebugCanvas();
  36640. }
  36641. while (this.soundCollection.length) {
  36642. this.soundCollection[0].dispose();
  36643. }
  36644. if (this._outputAudioNode) {
  36645. this._outputAudioNode.disconnect();
  36646. }
  36647. this._outputAudioNode = null;
  36648. }
  36649. };
  36650. SoundTrack.prototype.AddSound = function (sound) {
  36651. if (!this._isInitialized) {
  36652. this._initializeSoundTrackAudioGraph();
  36653. }
  36654. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  36655. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  36656. }
  36657. if (sound.soundTrackId) {
  36658. if (sound.soundTrackId === -1) {
  36659. this._scene.mainSoundTrack.RemoveSound(sound);
  36660. }
  36661. else {
  36662. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  36663. }
  36664. }
  36665. this.soundCollection.push(sound);
  36666. sound.soundTrackId = this.id;
  36667. };
  36668. SoundTrack.prototype.RemoveSound = function (sound) {
  36669. var index = this.soundCollection.indexOf(sound);
  36670. if (index !== -1) {
  36671. this.soundCollection.splice(index, 1);
  36672. }
  36673. };
  36674. SoundTrack.prototype.setVolume = function (newVolume) {
  36675. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  36676. this._outputAudioNode.gain.value = newVolume;
  36677. }
  36678. };
  36679. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  36680. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  36681. for (var i = 0; i < this.soundCollection.length; i++) {
  36682. this.soundCollection[i].switchPanningModelToHRTF();
  36683. }
  36684. }
  36685. };
  36686. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  36687. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  36688. for (var i = 0; i < this.soundCollection.length; i++) {
  36689. this.soundCollection[i].switchPanningModelToEqualPower();
  36690. }
  36691. }
  36692. };
  36693. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  36694. if (this._connectedAnalyser) {
  36695. this._connectedAnalyser.stopDebugCanvas();
  36696. }
  36697. this._connectedAnalyser = analyser;
  36698. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  36699. this._outputAudioNode.disconnect();
  36700. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  36701. }
  36702. };
  36703. return SoundTrack;
  36704. }());
  36705. BABYLON.SoundTrack = SoundTrack;
  36706. })(BABYLON || (BABYLON = {}));
  36707. var BABYLON;
  36708. (function (BABYLON) {
  36709. /**
  36710. * Special Glow Blur post process only blurring the alpha channel
  36711. * It enforces keeping the most luminous color in the color channel.
  36712. */
  36713. var GlowBlurPostProcess = (function (_super) {
  36714. __extends(GlowBlurPostProcess, _super);
  36715. function GlowBlurPostProcess(name, direction, blurWidth, options, camera, samplingMode, engine, reusable) {
  36716. var _this = this;
  36717. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  36718. _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable);
  36719. this.direction = direction;
  36720. this.blurWidth = blurWidth;
  36721. this.onApplyObservable.add(function (effect) {
  36722. effect.setFloat2("screenSize", _this.width, _this.height);
  36723. effect.setVector2("direction", _this.direction);
  36724. effect.setFloat("blurWidth", _this.blurWidth);
  36725. });
  36726. }
  36727. return GlowBlurPostProcess;
  36728. }(BABYLON.PostProcess));
  36729. /**
  36730. * The highlight layer Helps adding a glow effect around a mesh.
  36731. *
  36732. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  36733. * glowy meshes to your scene.
  36734. *
  36735. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  36736. */
  36737. var HighlightLayer = (function () {
  36738. /**
  36739. * Instantiates a new highlight Layer and references it to the scene..
  36740. * @param name The name of the layer
  36741. * @param scene The scene to use the layer in
  36742. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  36743. */
  36744. function HighlightLayer(name, scene, options) {
  36745. this._vertexBuffers = {};
  36746. this._mainTextureDesiredSize = { width: 0, height: 0 };
  36747. this._meshes = {};
  36748. this._maxSize = 0;
  36749. this._shouldRender = false;
  36750. this._instanceGlowingMeshStencilReference = HighlightLayer.glowingMeshStencilReference++;
  36751. /**
  36752. * Specifies whether or not the inner glow is ACTIVE in the layer.
  36753. */
  36754. this.innerGlow = true;
  36755. /**
  36756. * Specifies whether or not the outer glow is ACTIVE in the layer.
  36757. */
  36758. this.outerGlow = true;
  36759. /**
  36760. * An event triggered when the highlight layer has been disposed.
  36761. * @type {BABYLON.Observable}
  36762. */
  36763. this.onDisposeObservable = new BABYLON.Observable();
  36764. /**
  36765. * An event triggered when the highlight layer is about rendering the main texture with the glowy parts.
  36766. * @type {BABYLON.Observable}
  36767. */
  36768. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  36769. /**
  36770. * An event triggered when the highlight layer is being blurred.
  36771. * @type {BABYLON.Observable}
  36772. */
  36773. this.onBeforeBlurObservable = new BABYLON.Observable();
  36774. /**
  36775. * An event triggered when the highlight layer has been blurred.
  36776. * @type {BABYLON.Observable}
  36777. */
  36778. this.onAfterBlurObservable = new BABYLON.Observable();
  36779. /**
  36780. * An event triggered when the glowing blurred texture is being merged in the scene.
  36781. * @type {BABYLON.Observable}
  36782. */
  36783. this.onBeforeComposeObservable = new BABYLON.Observable();
  36784. /**
  36785. * An event triggered when the glowing blurred texture has been merged in the scene.
  36786. * @type {BABYLON.Observable}
  36787. */
  36788. this.onAfterComposeObservable = new BABYLON.Observable();
  36789. /**
  36790. * An event triggered when the highlight layer changes its size.
  36791. * @type {BABYLON.Observable}
  36792. */
  36793. this.onSizeChangedObservable = new BABYLON.Observable();
  36794. this._scene = scene;
  36795. var engine = scene.getEngine();
  36796. this._engine = engine;
  36797. this._maxSize = this._engine.getCaps().maxTextureSize;
  36798. this._scene.highlightLayers.push(this);
  36799. // Warn on stencil.
  36800. if (!this._engine.isStencilEnable) {
  36801. BABYLON.Tools.Warn("Rendering the Highlight Layer requires the stencil to be active on the canvas. var engine = new BABYLON.Engine(canvas, antialias, { stencil: true }");
  36802. }
  36803. // Adapt options
  36804. this._options = options || {
  36805. mainTextureRatio: 0.25,
  36806. blurTextureSizeRatio: 0.5,
  36807. blurHorizontalSize: 1,
  36808. blurVerticalSize: 1,
  36809. alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE
  36810. };
  36811. this._options.mainTextureRatio = this._options.mainTextureRatio || 0.25;
  36812. this._options.blurTextureSizeRatio = this._options.blurTextureSizeRatio || 0.5;
  36813. this._options.blurHorizontalSize = this._options.blurHorizontalSize || 1;
  36814. this._options.blurVerticalSize = this._options.blurVerticalSize || 1;
  36815. this._options.alphaBlendingMode = this._options.alphaBlendingMode || BABYLON.Engine.ALPHA_COMBINE;
  36816. // VBO
  36817. var vertices = [];
  36818. vertices.push(1, 1);
  36819. vertices.push(-1, 1);
  36820. vertices.push(-1, -1);
  36821. vertices.push(1, -1);
  36822. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  36823. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  36824. // Indices
  36825. var indices = [];
  36826. indices.push(0);
  36827. indices.push(1);
  36828. indices.push(2);
  36829. indices.push(0);
  36830. indices.push(2);
  36831. indices.push(3);
  36832. this._indexBuffer = engine.createIndexBuffer(indices);
  36833. // Effect
  36834. this._glowMapMergeEffect = engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], "");
  36835. // Render target
  36836. this.setMainTextureSize();
  36837. // Create Textures and post processes
  36838. this.createTextureAndPostProcesses();
  36839. }
  36840. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  36841. /**
  36842. * Gets the horizontal size of the blur.
  36843. */
  36844. get: function () {
  36845. return this._horizontalBlurPostprocess.blurWidth;
  36846. },
  36847. /**
  36848. * Specifies the horizontal size of the blur.
  36849. */
  36850. set: function (value) {
  36851. this._horizontalBlurPostprocess.blurWidth = value;
  36852. },
  36853. enumerable: true,
  36854. configurable: true
  36855. });
  36856. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  36857. /**
  36858. * Gets the vertical size of the blur.
  36859. */
  36860. get: function () {
  36861. return this._verticalBlurPostprocess.blurWidth;
  36862. },
  36863. /**
  36864. * Specifies the vertical size of the blur.
  36865. */
  36866. set: function (value) {
  36867. this._verticalBlurPostprocess.blurWidth = value;
  36868. },
  36869. enumerable: true,
  36870. configurable: true
  36871. });
  36872. /**
  36873. * Creates the render target textures and post processes used in the highlight layer.
  36874. */
  36875. HighlightLayer.prototype.createTextureAndPostProcesses = function () {
  36876. var _this = this;
  36877. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  36878. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  36879. blurTextureWidth = BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize);
  36880. blurTextureHeight = BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize);
  36881. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  36882. width: this._mainTextureDesiredSize.width,
  36883. height: this._mainTextureDesiredSize.height
  36884. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  36885. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  36886. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  36887. this._mainTexture.anisotropicFilteringLevel = 1;
  36888. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  36889. this._mainTexture.renderParticles = false;
  36890. this._mainTexture.renderList = null;
  36891. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  36892. width: blurTextureWidth,
  36893. height: blurTextureHeight
  36894. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  36895. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  36896. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  36897. this._blurTexture.anisotropicFilteringLevel = 16;
  36898. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  36899. this._blurTexture.renderParticles = false;
  36900. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  36901. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  36902. effect.setTexture("textureSampler", _this._mainTexture);
  36903. });
  36904. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  36905. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  36906. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  36907. });
  36908. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  36909. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  36910. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  36911. });
  36912. this._mainTexture.onAfterUnbindObservable.add(function () {
  36913. _this.onBeforeBlurObservable.notifyObservers(_this);
  36914. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._horizontalBlurPostprocess, _this._verticalBlurPostprocess], _this._blurTexture.getInternalTexture());
  36915. _this.onAfterBlurObservable.notifyObservers(_this);
  36916. });
  36917. // Custom render function
  36918. var renderSubMesh = function (subMesh) {
  36919. var mesh = subMesh.getRenderingMesh();
  36920. var scene = _this._scene;
  36921. var engine = scene.getEngine();
  36922. // Culling
  36923. engine.setState(subMesh.getMaterial().backFaceCulling);
  36924. // Managing instances
  36925. var batch = mesh._getInstancesRenderList(subMesh._id);
  36926. if (batch.mustReturn) {
  36927. return;
  36928. }
  36929. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  36930. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  36931. engine.enableEffect(_this._glowMapGenerationEffect);
  36932. mesh._bind(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  36933. var material = subMesh.getMaterial();
  36934. _this._glowMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  36935. var highlightLayerMesh = _this._meshes[mesh.id];
  36936. if (highlightLayerMesh) {
  36937. _this._glowMapGenerationEffect.setFloat4("color", highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  36938. }
  36939. else {
  36940. _this._glowMapGenerationEffect.setFloat4("color", HighlightLayer.neutralColor.r, HighlightLayer.neutralColor.g, HighlightLayer.neutralColor.b, HighlightLayer.neutralColor.a);
  36941. }
  36942. // Alpha test
  36943. if (material && material.needAlphaTesting()) {
  36944. var alphaTexture = material.getAlphaTestTexture();
  36945. _this._glowMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  36946. _this._glowMapGenerationEffect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  36947. }
  36948. // Bones
  36949. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  36950. _this._glowMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  36951. }
  36952. // Draw
  36953. mesh._processRendering(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._glowMapGenerationEffect.setMatrix("world", world); });
  36954. }
  36955. else {
  36956. // Need to reset refresh rate of the shadowMap
  36957. _this._mainTexture.resetRefreshCounter();
  36958. }
  36959. };
  36960. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  36961. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  36962. var index;
  36963. for (index = 0; index < opaqueSubMeshes.length; index++) {
  36964. renderSubMesh(opaqueSubMeshes.data[index]);
  36965. }
  36966. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  36967. renderSubMesh(alphaTestSubMeshes.data[index]);
  36968. }
  36969. for (index = 0; index < transparentSubMeshes.length; index++) {
  36970. renderSubMesh(transparentSubMeshes.data[index]);
  36971. }
  36972. };
  36973. this._mainTexture.onClearObservable.add(function (engine) {
  36974. engine.clear(HighlightLayer.neutralColor, true, true, true);
  36975. });
  36976. };
  36977. /**
  36978. * Checks for the readiness of the element composing the layer.
  36979. * @param subMesh the mesh to check for
  36980. * @param useInstances specify wether or not to use instances to render the mesh
  36981. * @return true if ready otherwise, false
  36982. */
  36983. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  36984. if (!subMesh.getMaterial().isReady()) {
  36985. return false;
  36986. }
  36987. var defines = [];
  36988. var attribs = [BABYLON.VertexBuffer.PositionKind];
  36989. var mesh = subMesh.getMesh();
  36990. var material = subMesh.getMaterial();
  36991. // Alpha test
  36992. if (material && material.needAlphaTesting()) {
  36993. defines.push("#define ALPHATEST");
  36994. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  36995. attribs.push(BABYLON.VertexBuffer.UVKind);
  36996. defines.push("#define UV1");
  36997. }
  36998. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  36999. var alphaTexture = material.getAlphaTestTexture();
  37000. if (alphaTexture.coordinatesIndex === 1) {
  37001. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  37002. defines.push("#define UV2");
  37003. }
  37004. }
  37005. }
  37006. // Bones
  37007. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  37008. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  37009. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  37010. if (mesh.numBoneInfluencers > 4) {
  37011. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  37012. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  37013. }
  37014. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  37015. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  37016. }
  37017. else {
  37018. defines.push("#define NUM_BONE_INFLUENCERS 0");
  37019. }
  37020. // Instances
  37021. if (useInstances) {
  37022. defines.push("#define INSTANCES");
  37023. attribs.push("world0");
  37024. attribs.push("world1");
  37025. attribs.push("world2");
  37026. attribs.push("world3");
  37027. }
  37028. // Get correct effect
  37029. var join = defines.join("\n");
  37030. if (this._cachedDefines !== join) {
  37031. this._cachedDefines = join;
  37032. this._glowMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color"], ["diffuseSampler"], join);
  37033. }
  37034. return this._glowMapGenerationEffect.isReady();
  37035. };
  37036. /**
  37037. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  37038. */
  37039. HighlightLayer.prototype.render = function () {
  37040. var currentEffect = this._glowMapMergeEffect;
  37041. // Check
  37042. if (!currentEffect.isReady() || !this._blurTexture.isReady())
  37043. return;
  37044. var engine = this._scene.getEngine();
  37045. this.onBeforeComposeObservable.notifyObservers(this);
  37046. // Render
  37047. engine.enableEffect(currentEffect);
  37048. engine.setState(false);
  37049. // Cache
  37050. var previousStencilBuffer = engine.getStencilBuffer();
  37051. var previousStencilFunction = engine.getStencilFunction();
  37052. var previousStencilMask = engine.getStencilMask();
  37053. var previousAlphaMode = engine.getAlphaMode();
  37054. // Texture
  37055. currentEffect.setTexture("textureSampler", this._blurTexture);
  37056. // VBOs
  37057. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  37058. // Draw order
  37059. engine.setAlphaMode(this._options.alphaBlendingMode);
  37060. engine.setStencilMask(0x00);
  37061. engine.setStencilBuffer(true);
  37062. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  37063. if (this.outerGlow) {
  37064. currentEffect.setFloat("offset", 0);
  37065. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  37066. engine.draw(true, 0, 6);
  37067. }
  37068. if (this.innerGlow) {
  37069. currentEffect.setFloat("offset", 1);
  37070. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  37071. engine.draw(true, 0, 6);
  37072. }
  37073. // Restore Cache
  37074. engine.setStencilFunction(previousStencilFunction);
  37075. engine.setStencilMask(previousStencilMask);
  37076. engine.setAlphaMode(previousAlphaMode);
  37077. engine.setStencilBuffer(previousStencilBuffer);
  37078. this.onAfterComposeObservable.notifyObservers(this);
  37079. // Handle size changes.
  37080. var size = this._mainTexture.getSize();
  37081. this.setMainTextureSize();
  37082. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  37083. // Recreate RTT and post processes on size change.
  37084. this.onSizeChangedObservable.notifyObservers(this);
  37085. this.disposeTextureAndPostProcesses();
  37086. this.createTextureAndPostProcesses();
  37087. }
  37088. };
  37089. /**
  37090. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  37091. * @param mesh The mesh to highlight
  37092. * @param color The color of the highlight
  37093. */
  37094. HighlightLayer.prototype.pushMesh = function (mesh, color) {
  37095. var _this = this;
  37096. var meshHighlight = this._meshes[mesh.id];
  37097. if (meshHighlight) {
  37098. meshHighlight.color = color;
  37099. }
  37100. else {
  37101. this._meshes[mesh.id] = {
  37102. mesh: mesh,
  37103. color: color,
  37104. // Lambda required for capture due to Observable this context
  37105. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  37106. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  37107. }),
  37108. observerDefault: mesh.onAfterRenderObservable.add(this.defaultStencilReference)
  37109. };
  37110. }
  37111. this._shouldRender = true;
  37112. };
  37113. /**
  37114. * Remove a mesh from the highlight layer in order to make it stop glowing.
  37115. * @param mesh The mesh to highlight
  37116. */
  37117. HighlightLayer.prototype.removeMesh = function (mesh) {
  37118. var meshHighlight = this._meshes[mesh.id];
  37119. if (meshHighlight) {
  37120. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  37121. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  37122. }
  37123. this._meshes[mesh.id] = undefined;
  37124. this._shouldRender = false;
  37125. for (var meshHighlightToCheck in this._meshes) {
  37126. if (meshHighlightToCheck) {
  37127. this._shouldRender = true;
  37128. break;
  37129. }
  37130. }
  37131. };
  37132. /**
  37133. * Returns true if the layer contains information to display, otherwise false.
  37134. */
  37135. HighlightLayer.prototype.shouldRender = function () {
  37136. return this._shouldRender;
  37137. };
  37138. /**
  37139. * Sets the main texture desired size which is the closest power of two
  37140. * of the engine canvas size.
  37141. */
  37142. HighlightLayer.prototype.setMainTextureSize = function () {
  37143. this._mainTextureDesiredSize.width = this._engine.getRenderingCanvas().width * this._options.mainTextureRatio;
  37144. this._mainTextureDesiredSize.height = this._engine.getRenderingCanvas().height * this._options.mainTextureRatio;
  37145. this._mainTextureDesiredSize.width = BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize);
  37146. this._mainTextureDesiredSize.height = BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize);
  37147. };
  37148. /**
  37149. * Force the stencil to the normal expected value for none glowing parts
  37150. */
  37151. HighlightLayer.prototype.defaultStencilReference = function (mesh) {
  37152. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.normalMeshStencilReference);
  37153. };
  37154. /**
  37155. * Dispose only the render target textures and post process.
  37156. */
  37157. HighlightLayer.prototype.disposeTextureAndPostProcesses = function () {
  37158. this._blurTexture.dispose();
  37159. this._mainTexture.dispose();
  37160. this._downSamplePostprocess.dispose();
  37161. this._horizontalBlurPostprocess.dispose();
  37162. this._verticalBlurPostprocess.dispose();
  37163. };
  37164. /**
  37165. * Dispose the highlight layer and free resources.
  37166. */
  37167. HighlightLayer.prototype.dispose = function () {
  37168. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  37169. if (vertexBuffer) {
  37170. vertexBuffer.dispose();
  37171. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  37172. }
  37173. if (this._indexBuffer) {
  37174. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  37175. this._indexBuffer = null;
  37176. }
  37177. // Clean textures and post processes
  37178. this.disposeTextureAndPostProcesses();
  37179. // Clean mesh references
  37180. for (var id in this._meshes) {
  37181. var meshHighlight = this._meshes[id];
  37182. if (meshHighlight && meshHighlight.mesh) {
  37183. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  37184. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  37185. }
  37186. }
  37187. this._meshes = null;
  37188. // Remove from scene
  37189. var index = this._scene.highlightLayers.indexOf(this, 0);
  37190. if (index > -1) {
  37191. this._scene.highlightLayers.splice(index, 1);
  37192. }
  37193. // Callback
  37194. this.onDisposeObservable.notifyObservers(this);
  37195. this.onDisposeObservable.clear();
  37196. this.onBeforeRenderMainTextureObservable.clear();
  37197. this.onBeforeBlurObservable.clear();
  37198. this.onBeforeComposeObservable.clear();
  37199. this.onAfterComposeObservable.clear();
  37200. this.onSizeChangedObservable.clear();
  37201. };
  37202. /**
  37203. * The neutral color used during the preparation of the glow effect.
  37204. * This is black by default as the blend operation is a blend operation.
  37205. */
  37206. HighlightLayer.neutralColor = new BABYLON.Color4(0, 0, 0, 0);
  37207. /**
  37208. * Stencil value used for glowing meshes.
  37209. */
  37210. HighlightLayer.glowingMeshStencilReference = 0x02;
  37211. /**
  37212. * Stencil value used for the other meshes in the scene.
  37213. */
  37214. HighlightLayer.normalMeshStencilReference = 0x01;
  37215. return HighlightLayer;
  37216. }());
  37217. BABYLON.HighlightLayer = HighlightLayer;
  37218. })(BABYLON || (BABYLON = {}));
  37219. var BABYLON;
  37220. (function (BABYLON) {
  37221. var SIMDVector3 = (function () {
  37222. function SIMDVector3() {
  37223. }
  37224. SIMDVector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  37225. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD(vector.x, vector.y, vector.z, transformation, result);
  37226. };
  37227. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  37228. var m = transformation.m;
  37229. var m0 = SIMD.Float32x4.load(m, 0);
  37230. var m1 = SIMD.Float32x4.load(m, 4);
  37231. var m2 = SIMD.Float32x4.load(m, 8);
  37232. var m3 = SIMD.Float32x4.load(m, 12);
  37233. var r = SIMD.Float32x4.add(SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.splat(x), m0), SIMD.Float32x4.mul(SIMD.Float32x4.splat(y), m1)), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.splat(z), m2), m3));
  37234. r = SIMD.Float32x4.div(r, SIMD.Float32x4.swizzle(r, 3, 3, 3, 3));
  37235. result.x = SIMD.Float32x4.extractLane(r, 0);
  37236. result.y = SIMD.Float32x4.extractLane(r, 1);
  37237. result.z = SIMD.Float32x4.extractLane(r, 2);
  37238. };
  37239. return SIMDVector3;
  37240. }());
  37241. var SIMDMatrix = (function () {
  37242. function SIMDMatrix() {
  37243. }
  37244. SIMDMatrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  37245. var tm = this.m;
  37246. var om = other.m;
  37247. var m0 = SIMD.Float32x4.load(om, 0);
  37248. var m1 = SIMD.Float32x4.load(om, 4);
  37249. var m2 = SIMD.Float32x4.load(om, 8);
  37250. var m3 = SIMD.Float32x4.load(om, 12);
  37251. for (var i = 0; i < 16; i += 4) {
  37252. SIMD.Float32x4.store(result, i + offset, SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.splat(tm[i]), m0), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.splat(tm[i + 1]), m1), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.splat(tm[i + 2]), m2), SIMD.Float32x4.mul(SIMD.Float32x4.splat(tm[i + 3]), m3)))));
  37253. }
  37254. return this;
  37255. };
  37256. SIMDMatrix.prototype.invertToRefSIMD = function (other) {
  37257. var src = this.m;
  37258. var dest = other.m;
  37259. // Load the 4 rows
  37260. var src0 = SIMD.Float32x4.load(src, 0);
  37261. var src1 = SIMD.Float32x4.load(src, 4);
  37262. var src2 = SIMD.Float32x4.load(src, 8);
  37263. var src3 = SIMD.Float32x4.load(src, 12);
  37264. // Transpose the source matrix. Sort of. Not a true transpose operation
  37265. var tmp1 = SIMD.Float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  37266. var row1 = SIMD.Float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  37267. var row0 = SIMD.Float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  37268. row1 = SIMD.Float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  37269. tmp1 = SIMD.Float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  37270. var row3 = SIMD.Float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  37271. var row2 = SIMD.Float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  37272. row3 = SIMD.Float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  37273. // This is a true transposition, but it will lead to an incorrect result
  37274. //tmp1 = shuffle(src0, src1, 0, 1, 4, 5);
  37275. //tmp2 = shuffle(src2, src3, 0, 1, 4, 5);
  37276. //row0 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  37277. //row1 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  37278. //tmp1 = shuffle(src0, src1, 2, 3, 6, 7);
  37279. //tmp2 = shuffle(src2, src3, 2, 3, 6, 7);
  37280. //row2 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  37281. //row3 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  37282. // ----
  37283. tmp1 = SIMD.Float32x4.mul(row2, row3);
  37284. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  37285. var minor0 = SIMD.Float32x4.mul(row1, tmp1);
  37286. var minor1 = SIMD.Float32x4.mul(row0, tmp1);
  37287. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  37288. minor0 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row1, tmp1), minor0);
  37289. minor1 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor1);
  37290. minor1 = SIMD.Float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  37291. // ----
  37292. tmp1 = SIMD.Float32x4.mul(row1, row2);
  37293. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  37294. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor0);
  37295. var minor3 = SIMD.Float32x4.mul(row0, tmp1);
  37296. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  37297. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row3, tmp1));
  37298. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor3);
  37299. minor3 = SIMD.Float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  37300. // ----
  37301. tmp1 = SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  37302. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  37303. row2 = SIMD.Float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  37304. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor0);
  37305. var minor2 = SIMD.Float32x4.mul(row0, tmp1);
  37306. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  37307. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row2, tmp1));
  37308. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor2);
  37309. minor2 = SIMD.Float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  37310. // ----
  37311. tmp1 = SIMD.Float32x4.mul(row0, row1);
  37312. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  37313. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor2);
  37314. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row2, tmp1), minor3);
  37315. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  37316. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row3, tmp1), minor2);
  37317. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row2, tmp1));
  37318. // ----
  37319. tmp1 = SIMD.Float32x4.mul(row0, row3);
  37320. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  37321. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row2, tmp1));
  37322. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor2);
  37323. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  37324. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor1);
  37325. minor2 = SIMD.Float32x4.sub(minor2, SIMD.Float32x4.mul(row1, tmp1));
  37326. // ----
  37327. tmp1 = SIMD.Float32x4.mul(row0, row2);
  37328. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  37329. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor1);
  37330. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row1, tmp1));
  37331. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  37332. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row3, tmp1));
  37333. minor3 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor3);
  37334. // Compute determinant
  37335. var det = SIMD.Float32x4.mul(row0, minor0);
  37336. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  37337. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  37338. tmp1 = SIMD.Float32x4.reciprocalApproximation(det);
  37339. det = SIMD.Float32x4.sub(SIMD.Float32x4.add(tmp1, tmp1), SIMD.Float32x4.mul(det, SIMD.Float32x4.mul(tmp1, tmp1)));
  37340. det = SIMD.Float32x4.swizzle(det, 0, 0, 0, 0);
  37341. // These shuffles aren't necessary if the faulty transposition is done
  37342. // up at the top of this function.
  37343. //minor0 =SIMD.Float32x4.swizzle(minor0, 2, 1, 0, 3);
  37344. //minor1 =SIMD.Float32x4.swizzle(minor1, 2, 1, 0, 3);
  37345. //minor2 =SIMD.Float32x4.swizzle(minor2, 2, 1, 0, 3);
  37346. //minor3 =SIMD.Float32x4.swizzle(minor3, 2, 1, 0, 3);
  37347. // Compute final values by multiplying with 1/det
  37348. SIMD.Float32x4.store(dest, 0, SIMD.Float32x4.mul(det, minor0));
  37349. SIMD.Float32x4.store(dest, 4, SIMD.Float32x4.mul(det, minor1));
  37350. SIMD.Float32x4.store(dest, 8, minor2 = SIMD.Float32x4.mul(det, minor2));
  37351. SIMD.Float32x4.store(dest, 12, SIMD.Float32x4.mul(det, minor3));
  37352. return this;
  37353. };
  37354. SIMDMatrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  37355. var out = result.m;
  37356. var center = SIMD.Float32x4(targetRef.x, targetRef.y, targetRef.z, 0.0);
  37357. var eye = SIMD.Float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0.0);
  37358. var up = SIMD.Float32x4(upRef.x, upRef.y, upRef.z, 0.0);
  37359. // cc.kmVec3Subtract(f, pCenter, pEye);
  37360. var f = SIMD.Float32x4.sub(center, eye);
  37361. // cc.kmVec3Normalize(f, f);
  37362. var tmp = SIMD.Float32x4.mul(f, f);
  37363. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  37364. f = SIMD.Float32x4.mul(f, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  37365. // cc.kmVec3Assign(up, pUp);
  37366. // cc.kmVec3Normalize(up, up);
  37367. tmp = SIMD.Float32x4.mul(up, up);
  37368. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  37369. up = SIMD.Float32x4.mul(up, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  37370. // cc.kmVec3Cross(s, f, up);
  37371. 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)));
  37372. // cc.kmVec3Normalize(s, s);
  37373. tmp = SIMD.Float32x4.mul(s, s);
  37374. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  37375. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  37376. // cc.kmVec3Cross(u, s, f);
  37377. 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)));
  37378. // cc.kmVec3Normalize(s, s);
  37379. tmp = SIMD.Float32x4.mul(s, s);
  37380. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  37381. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  37382. var zero = SIMD.Float32x4.splat(0.0);
  37383. s = SIMD.Float32x4.neg(s);
  37384. var tmp01 = SIMD.Float32x4.shuffle(s, u, 0, 1, 4, 5);
  37385. var tmp23 = SIMD.Float32x4.shuffle(f, zero, 0, 1, 4, 5);
  37386. var a0 = SIMD.Float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  37387. var a1 = SIMD.Float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  37388. var a2 = SIMD.Float32x4.shuffle(SIMD.Float32x4.shuffle(s, u, 2, 3, 6, 7), SIMD.Float32x4.shuffle(f, zero, 2, 3, 6, 7), 0, 2, 4, 6);
  37389. var a3 = SIMD.Float32x4(0.0, 0.0, 0.0, 1.0);
  37390. var b = SIMD.Float32x4(1.0, 0.0, 0.0, 0.0);
  37391. SIMD.Float32x4.store(out, 0, SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 0, 0, 0, 0), a0), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 1, 1, 1, 1), a1), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 2, 2, 2, 2), a2), SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 3, 3, 3, 3), a3)))));
  37392. b = SIMD.Float32x4(0.0, 1.0, 0.0, 0.0);
  37393. SIMD.Float32x4.store(out, 4, SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 0, 0, 0, 0), a0), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 1, 1, 1, 1), a1), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 2, 2, 2, 2), a2), SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 3, 3, 3, 3), a3)))));
  37394. b = SIMD.Float32x4(0.0, 0.0, 1.0, 0.0);
  37395. SIMD.Float32x4.store(out, 8, SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 0, 0, 0, 0), a0), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 1, 1, 1, 1), a1), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 2, 2, 2, 2), a2), SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 3, 3, 3, 3), a3)))));
  37396. b = SIMD.Float32x4.replaceLane(SIMD.Float32x4.neg(eye), 3, 1.0);
  37397. SIMD.Float32x4.store(out, 12, SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 0, 0, 0, 0), a0), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 1, 1, 1, 1), a1), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 2, 2, 2, 2), a2), SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 3, 3, 3, 3), a3)))));
  37398. };
  37399. return SIMDMatrix;
  37400. }());
  37401. var previousMultiplyToArray = BABYLON.Matrix.prototype.multiplyToArray;
  37402. var previousInvertToRef = BABYLON.Matrix.prototype.invertToRef;
  37403. var previousLookAtLHToRef = BABYLON.Matrix.LookAtLHToRef;
  37404. var previousTransformCoordinatesToRef = BABYLON.Vector3.TransformCoordinatesToRef;
  37405. var previousTransformCoordinatesFromFloatsToRef = BABYLON.Vector3.TransformCoordinatesFromFloatsToRef;
  37406. var SIMDHelper = (function () {
  37407. function SIMDHelper() {
  37408. }
  37409. Object.defineProperty(SIMDHelper, "IsEnabled", {
  37410. get: function () {
  37411. return SIMDHelper._isEnabled;
  37412. },
  37413. enumerable: true,
  37414. configurable: true
  37415. });
  37416. SIMDHelper.DisableSIMD = function () {
  37417. // Replace functions
  37418. BABYLON.Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  37419. BABYLON.Matrix.prototype.invertToRef = previousInvertToRef;
  37420. BABYLON.Matrix.LookAtLHToRef = previousLookAtLHToRef;
  37421. BABYLON.Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  37422. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  37423. SIMDHelper._isEnabled = false;
  37424. };
  37425. SIMDHelper.EnableSIMD = function () {
  37426. if (self.SIMD === undefined) {
  37427. return;
  37428. }
  37429. // check if polyfills needed
  37430. if (!self.Math.fround) {
  37431. self.Math.fround = (function (array) { return function (x) {
  37432. return array[0] = x, array[0];
  37433. }; })(new Float32Array(1));
  37434. }
  37435. if (!self.Math.imul) {
  37436. self.Math.imul = function (a, b) {
  37437. var ah = (a >>> 16) & 0xffff;
  37438. var al = a & 0xffff;
  37439. var bh = (b >>> 16) & 0xffff;
  37440. var bl = b & 0xffff;
  37441. // the shift by 0 fixes the sign on the high part
  37442. // the final |0 converts the unsigned value into a signed value
  37443. return ((al * bl) + (((ah * bl + al * bh) << 16) >>> 0) | 0);
  37444. };
  37445. }
  37446. // Replace functions
  37447. BABYLON.Matrix.prototype.multiplyToArray = SIMDMatrix.prototype.multiplyToArraySIMD;
  37448. BABYLON.Matrix.prototype.invertToRef = SIMDMatrix.prototype.invertToRefSIMD;
  37449. BABYLON.Matrix.LookAtLHToRef = SIMDMatrix.LookAtLHToRefSIMD;
  37450. BABYLON.Vector3.TransformCoordinatesToRef = SIMDVector3.TransformCoordinatesToRefSIMD;
  37451. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD;
  37452. SIMDHelper._isEnabled = true;
  37453. };
  37454. SIMDHelper._isEnabled = false;
  37455. return SIMDHelper;
  37456. }());
  37457. BABYLON.SIMDHelper = SIMDHelper;
  37458. })(BABYLON || (BABYLON = {}));
  37459. var BABYLON;
  37460. (function (BABYLON) {
  37461. /**
  37462. * This class describe a rectangle that were added to the map.
  37463. * You have access to its coordinates either in pixel or normalized (UV)
  37464. */
  37465. var PackedRect = (function () {
  37466. function PackedRect(root, parent, pos, size) {
  37467. this._pos = pos;
  37468. this._size = size;
  37469. this._root = root;
  37470. this._parent = parent;
  37471. }
  37472. Object.defineProperty(PackedRect.prototype, "pos", {
  37473. /**
  37474. * @returns the position of this node into the map
  37475. */
  37476. get: function () {
  37477. return this._pos;
  37478. },
  37479. enumerable: true,
  37480. configurable: true
  37481. });
  37482. Object.defineProperty(PackedRect.prototype, "contentSize", {
  37483. /**
  37484. * @returns the size of the rectangle this node handles
  37485. */
  37486. get: function () {
  37487. return this._contentSize;
  37488. },
  37489. enumerable: true,
  37490. configurable: true
  37491. });
  37492. Object.defineProperty(PackedRect.prototype, "UVs", {
  37493. /**
  37494. * Compute the UV of the top/left, top/right, bottom/right, bottom/left points of the rectangle this node handles into the map
  37495. * @returns And array of 4 Vector2, containing UV coordinates for the four corners of the Rectangle into the map
  37496. */
  37497. get: function () {
  37498. return this.getUVsForCustomSize(this._root._size);
  37499. },
  37500. enumerable: true,
  37501. configurable: true
  37502. });
  37503. /**
  37504. * 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.
  37505. * This method will return the UVs for this part by given the custom size of what you really use
  37506. * @param customSize must be less/equal to the allocated size, UV will be compute from this
  37507. */
  37508. PackedRect.prototype.getUVsForCustomSize = function (customSize) {
  37509. var mainWidth = this._root._size.width;
  37510. var mainHeight = this._root._size.height;
  37511. var topLeft = new BABYLON.Vector2(this._pos.x / mainWidth, this._pos.y / mainHeight);
  37512. var rightBottom = new BABYLON.Vector2((this._pos.x + customSize.width - 1) / mainWidth, (this._pos.y + customSize.height - 1) / mainHeight);
  37513. var uvs = new Array();
  37514. uvs.push(topLeft);
  37515. uvs.push(new BABYLON.Vector2(rightBottom.x, topLeft.y));
  37516. uvs.push(rightBottom);
  37517. uvs.push(new BABYLON.Vector2(topLeft.x, rightBottom.y));
  37518. return uvs;
  37519. };
  37520. /**
  37521. * Free this rectangle from the map.
  37522. * Call this method when you no longer need the rectangle to be in the map.
  37523. */
  37524. PackedRect.prototype.freeContent = function () {
  37525. if (!this.contentSize) {
  37526. return;
  37527. }
  37528. this._contentSize = null;
  37529. // If everything below is also free, reset the whole node, and attempt to reset parents if they also become free
  37530. this.attemptDefrag();
  37531. };
  37532. Object.defineProperty(PackedRect.prototype, "isUsed", {
  37533. get: function () {
  37534. return this._contentSize != null || this._leftNode != null;
  37535. },
  37536. enumerable: true,
  37537. configurable: true
  37538. });
  37539. PackedRect.prototype.findAndSplitNode = function (contentSize) {
  37540. var node = this.findNode(contentSize);
  37541. // Not enough space...
  37542. if (!node) {
  37543. return null;
  37544. }
  37545. node.splitNode(contentSize);
  37546. return node;
  37547. };
  37548. PackedRect.prototype.findNode = function (size) {
  37549. var resNode = null;
  37550. // If this node is used, recurse to each of his subNodes to find an available one in its branch
  37551. if (this.isUsed) {
  37552. if (this._leftNode) {
  37553. resNode = this._leftNode.findNode(size);
  37554. }
  37555. if (!resNode && this._rightNode) {
  37556. resNode = this._rightNode.findNode(size);
  37557. }
  37558. if (!resNode && this._bottomNode) {
  37559. resNode = this._bottomNode.findNode(size);
  37560. }
  37561. }
  37562. else if (this._initialSize && (size.width <= this._initialSize.width) && (size.height <= this._initialSize.height)) {
  37563. resNode = this;
  37564. }
  37565. else if ((size.width <= this._size.width) && (size.height <= this._size.height)) {
  37566. resNode = this;
  37567. }
  37568. return resNode;
  37569. };
  37570. PackedRect.prototype.splitNode = function (contentSize) {
  37571. // 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)
  37572. if (!this._contentSize && this._initialSize) {
  37573. 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));
  37574. return this._leftNode.splitNode(contentSize);
  37575. }
  37576. else {
  37577. this._contentSize = contentSize.clone();
  37578. this._initialSize = contentSize.clone();
  37579. if (contentSize.width !== this._size.width) {
  37580. 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));
  37581. }
  37582. if (contentSize.height !== this._size.height) {
  37583. 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));
  37584. }
  37585. return this;
  37586. }
  37587. };
  37588. PackedRect.prototype.attemptDefrag = function () {
  37589. if (!this.isUsed && this.isRecursiveFree) {
  37590. this.clearNode();
  37591. if (this._parent) {
  37592. this._parent.attemptDefrag();
  37593. }
  37594. }
  37595. };
  37596. PackedRect.prototype.clearNode = function () {
  37597. this._initialSize = null;
  37598. this._rightNode = null;
  37599. this._bottomNode = null;
  37600. };
  37601. Object.defineProperty(PackedRect.prototype, "isRecursiveFree", {
  37602. get: function () {
  37603. return !this.contentSize && (!this._leftNode || this._leftNode.isRecursiveFree) && (!this._rightNode || this._rightNode.isRecursiveFree) && (!this._bottomNode || this._bottomNode.isRecursiveFree);
  37604. },
  37605. enumerable: true,
  37606. configurable: true
  37607. });
  37608. PackedRect.prototype.evalFreeSize = function (size) {
  37609. var levelSize = 0;
  37610. if (!this.isUsed) {
  37611. if (this._initialSize) {
  37612. levelSize = this._initialSize.surface;
  37613. }
  37614. else {
  37615. levelSize = this._size.surface;
  37616. }
  37617. }
  37618. if (this._rightNode) {
  37619. levelSize += this._rightNode.evalFreeSize(0);
  37620. }
  37621. if (this._bottomNode) {
  37622. levelSize += this._bottomNode.evalFreeSize(0);
  37623. }
  37624. return levelSize + size;
  37625. };
  37626. return PackedRect;
  37627. }());
  37628. BABYLON.PackedRect = PackedRect;
  37629. /**
  37630. * The purpose of this class is to pack several Rectangles into a big map, while trying to fit everything as optimally as possible.
  37631. * This class is typically used to build lightmaps, sprite map or to pack several little textures into a big one.
  37632. * 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.
  37633. */
  37634. var RectPackingMap = (function (_super) {
  37635. __extends(RectPackingMap, _super);
  37636. /**
  37637. * Create an instance of the object with a dimension using the given size
  37638. * @param size The dimension of the rectangle that will contain all the sub ones.
  37639. */
  37640. function RectPackingMap(size) {
  37641. _super.call(this, null, null, BABYLON.Vector2.Zero(), size);
  37642. this._root = this;
  37643. }
  37644. /**
  37645. * Add a rectangle, finding the best location to store it into the map
  37646. * @param size the dimension of the rectangle to store
  37647. * @return the Node containing the rectangle information, or null if we couldn't find a free spot
  37648. */
  37649. RectPackingMap.prototype.addRect = function (size) {
  37650. var node = this.findAndSplitNode(size);
  37651. return node;
  37652. };
  37653. Object.defineProperty(RectPackingMap.prototype, "freeSpace", {
  37654. /**
  37655. * Return the current space free normalized between [0;1]
  37656. * @returns {}
  37657. */
  37658. get: function () {
  37659. var freeSize = 0;
  37660. freeSize = this.evalFreeSize(freeSize);
  37661. return freeSize / (this._size.width * this._size.height);
  37662. },
  37663. enumerable: true,
  37664. configurable: true
  37665. });
  37666. return RectPackingMap;
  37667. }(PackedRect));
  37668. BABYLON.RectPackingMap = RectPackingMap;
  37669. })(BABYLON || (BABYLON = {}));
  37670. var BABYLON;
  37671. (function (BABYLON) {
  37672. var DynamicFloatArrayElementInfo = (function () {
  37673. function DynamicFloatArrayElementInfo() {
  37674. }
  37675. return DynamicFloatArrayElementInfo;
  37676. }());
  37677. BABYLON.DynamicFloatArrayElementInfo = DynamicFloatArrayElementInfo;
  37678. /**
  37679. * 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.
  37680. * The intent is to maintain through time data that will be bound to a WebGlBuffer with the ability to change add/remove elements.
  37681. * It was first built to efficiently maintain the WebGlBuffer that contain instancing based data.
  37682. * 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.
  37683. * 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.
  37684. * 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".
  37685. */
  37686. var DynamicFloatArray = (function () {
  37687. /**
  37688. * Construct an instance of the dynamic float array
  37689. * @param stride size of one element in float (i.e. not bytes!)
  37690. * @param initialElementCount the number of available entries at construction
  37691. */
  37692. function DynamicFloatArray(stride, initialElementCount) {
  37693. this.compareValueOffset = null;
  37694. this.sortingAscending = true;
  37695. this._stride = stride;
  37696. this.buffer = new Float32Array(stride * initialElementCount);
  37697. this._lastUsed = 0;
  37698. this._firstFree = 0;
  37699. this._allEntries = new Array(initialElementCount);
  37700. this._freeEntries = new Array(initialElementCount);
  37701. for (var i = 0; i < initialElementCount; i++) {
  37702. var element = new DynamicFloatArrayElementInfo();
  37703. element.offset = i * stride;
  37704. this._allEntries[i] = element;
  37705. this._freeEntries[initialElementCount - i - 1] = element;
  37706. }
  37707. }
  37708. /**
  37709. * Allocate an element in the array.
  37710. * @return the element info instance that contains the offset into the main buffer of the element's location.
  37711. * Beware, this offset may change when you call pack()
  37712. */
  37713. DynamicFloatArray.prototype.allocElement = function () {
  37714. if (this._freeEntries.length === 0) {
  37715. this._growBuffer();
  37716. }
  37717. var el = this._freeEntries.pop();
  37718. this._lastUsed = Math.max(el.offset, this._lastUsed);
  37719. if (el.offset === this._firstFree) {
  37720. if (this._freeEntries.length > 0) {
  37721. this._firstFree = this._freeEntries[this._freeEntries.length - 1].offset;
  37722. }
  37723. else {
  37724. this._firstFree += this._stride;
  37725. }
  37726. }
  37727. return el;
  37728. };
  37729. /**
  37730. * Free the element corresponding to the given element info
  37731. * @param elInfo the element that describe the allocated element
  37732. */
  37733. DynamicFloatArray.prototype.freeElement = function (elInfo) {
  37734. this._firstFree = Math.min(elInfo.offset, this._firstFree);
  37735. this._freeEntries.push(elInfo);
  37736. };
  37737. /**
  37738. * This method will pack all the used elements into a linear sequence and put all the free space at the end.
  37739. * 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().
  37740. * @return the subArray that is the view of the used elements area, you can use it as a source to update a WebGLBuffer
  37741. */
  37742. DynamicFloatArray.prototype.pack = function () {
  37743. // no free slot? no need to pack
  37744. if (this._freeEntries.length === 0) {
  37745. return this.buffer;
  37746. }
  37747. // If the buffer is already packed the last used will always be lower than the first free
  37748. // 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.
  37749. if (this._lastUsed < this._firstFree) {
  37750. var elementsBuffer_1 = this.buffer.subarray(0, this._lastUsed + this._stride);
  37751. return elementsBuffer_1;
  37752. }
  37753. var s = this._stride;
  37754. // 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
  37755. var lastFree = new DynamicFloatArrayElementInfo();
  37756. lastFree.offset = this.totalElementCount * s;
  37757. this._freeEntries.push(lastFree);
  37758. var sortedFree = this._freeEntries.sort(function (a, b) { return a.offset - b.offset; });
  37759. var sortedAll = this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  37760. var firstFreeSlotOffset = sortedFree[0].offset;
  37761. var freeZoneSize = 1;
  37762. var occupiedZoneSize = (this.usedElementCount + 1) * s;
  37763. var prevOffset = sortedFree[0].offset;
  37764. for (var i = 1; i < sortedFree.length; i++) {
  37765. // 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
  37766. if (firstFreeSlotOffset >= occupiedZoneSize) {
  37767. break;
  37768. }
  37769. var curFree = sortedFree[i];
  37770. var curOffset = curFree.offset;
  37771. // Compute the distance between this offset and the previous
  37772. var distance = curOffset - prevOffset;
  37773. // If the distance is the stride size, they are adjacent, it good, move to the next
  37774. if (distance === s) {
  37775. // Free zone is one element bigger
  37776. ++freeZoneSize;
  37777. // as we're about to iterate to the next, the cur becomes the previous...
  37778. prevOffset = curOffset;
  37779. continue;
  37780. }
  37781. // Distance is bigger, which means there's x element between the previous free and this one
  37782. var usedRange = (distance / s) - 1;
  37783. // Two cases the free zone is smaller than the data to move or bigger
  37784. // Copy what can fit in the free zone
  37785. var curMoveOffset = curOffset - s;
  37786. var copyCount = Math.min(freeZoneSize, usedRange);
  37787. for (var j = 0; j < copyCount; j++) {
  37788. var freeI = firstFreeSlotOffset / s;
  37789. var curI = curMoveOffset / s;
  37790. var moveEl = sortedAll[curI];
  37791. this._moveElement(moveEl, firstFreeSlotOffset);
  37792. var replacedEl = sortedAll[freeI];
  37793. // set the offset of the element we replaced with a value that will make it discard at the end of the method
  37794. replacedEl.offset = curMoveOffset;
  37795. // Swap the element we moved and the one it replaced in the sorted array to reflect the action we've made
  37796. sortedAll[freeI] = moveEl;
  37797. sortedAll[curI] = replacedEl;
  37798. curMoveOffset -= s;
  37799. firstFreeSlotOffset += s;
  37800. }
  37801. // Free Zone is smaller or equal so it's no longer a free zone, set the new one to the current location
  37802. if (freeZoneSize <= usedRange) {
  37803. firstFreeSlotOffset = curMoveOffset + s;
  37804. freeZoneSize = 1 + copyCount;
  37805. }
  37806. else {
  37807. freeZoneSize = ((curOffset - firstFreeSlotOffset) / s) + 1;
  37808. }
  37809. // as we're about to iterate to the next, the cur becomes the previous...
  37810. prevOffset = curOffset;
  37811. }
  37812. var elementsBuffer = this.buffer.subarray(0, firstFreeSlotOffset);
  37813. this._lastUsed = firstFreeSlotOffset - s;
  37814. this._firstFree = firstFreeSlotOffset;
  37815. sortedFree.pop(); // Remove the last free because that's the one we added at the start of the method
  37816. this._freeEntries = sortedFree.sort(function (a, b) { return b.offset - a.offset; });
  37817. this._allEntries = sortedAll;
  37818. return elementsBuffer;
  37819. };
  37820. DynamicFloatArray.prototype._moveElement = function (element, destOffset) {
  37821. for (var i = 0; i < this._stride; i++) {
  37822. this.buffer[destOffset + i] = this.buffer[element.offset + i];
  37823. }
  37824. element.offset = destOffset;
  37825. };
  37826. DynamicFloatArray.prototype._growBuffer = function () {
  37827. // Allocate the new buffer with 50% more entries, copy the content of the current one
  37828. var newElCount = Math.floor(this.totalElementCount * 1.5);
  37829. var newBuffer = new Float32Array(newElCount * this._stride);
  37830. newBuffer.set(this.buffer);
  37831. var curCount = this.totalElementCount;
  37832. var addedCount = newElCount - this.totalElementCount;
  37833. for (var i = 0; i < addedCount; i++) {
  37834. var element = new DynamicFloatArrayElementInfo();
  37835. element.offset = (curCount + i) * this.stride;
  37836. this._allEntries.push(element);
  37837. this._freeEntries[addedCount - i - 1] = element;
  37838. }
  37839. this._firstFree = curCount * this.stride;
  37840. this.buffer = newBuffer;
  37841. };
  37842. Object.defineProperty(DynamicFloatArray.prototype, "totalElementCount", {
  37843. /**
  37844. * Get the total count of entries that can fit in the current buffer
  37845. * @returns the elements count
  37846. */
  37847. get: function () {
  37848. return this._allEntries.length;
  37849. },
  37850. enumerable: true,
  37851. configurable: true
  37852. });
  37853. Object.defineProperty(DynamicFloatArray.prototype, "freeElementCount", {
  37854. /**
  37855. * Get the count of free entries that can still be allocated without resizing the buffer
  37856. * @returns the free elements count
  37857. */
  37858. get: function () {
  37859. return this._freeEntries.length;
  37860. },
  37861. enumerable: true,
  37862. configurable: true
  37863. });
  37864. Object.defineProperty(DynamicFloatArray.prototype, "usedElementCount", {
  37865. /**
  37866. * Get the count of allocated elements
  37867. * @returns the allocated elements count
  37868. */
  37869. get: function () {
  37870. return this._allEntries.length - this._freeEntries.length;
  37871. },
  37872. enumerable: true,
  37873. configurable: true
  37874. });
  37875. Object.defineProperty(DynamicFloatArray.prototype, "stride", {
  37876. /**
  37877. * Return the size of one element in float
  37878. * @returns the size in float
  37879. */
  37880. get: function () {
  37881. return this._stride;
  37882. },
  37883. enumerable: true,
  37884. configurable: true
  37885. });
  37886. DynamicFloatArray.prototype.sort = function () {
  37887. var _this = this;
  37888. if (!this.compareValueOffset) {
  37889. throw new Error("The DynamicFloatArray.sort() method needs a valid 'compareValueOffset' property");
  37890. }
  37891. var count = this.usedElementCount;
  37892. // Do we have to (re)create the sort table?
  37893. if (!this._sortTable || this._sortTable.length < count) {
  37894. // 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...
  37895. var newCount = Math.min(this.totalElementCount, count * 2);
  37896. this._sortTable = new Array(newCount);
  37897. }
  37898. if (!this._sortedTable || this._sortedTable.length !== count) {
  37899. this._sortedTable = new Array(count);
  37900. }
  37901. // Because, you know...
  37902. this.pack();
  37903. //let stride = this.stride;
  37904. //for (let i = 0; i < count; i++) {
  37905. // let si = this._sortTable[i];
  37906. // if (!si) {
  37907. // si = new SortInfo();
  37908. // this._sortTable[i] = si;
  37909. // }
  37910. // si.entry = this._allEntries[i];
  37911. // si.compareData = this.buffer[si.entry.offset + this.compareValueOffset];
  37912. // si.swapedOffset = null;
  37913. // this._sortedTable[i] = si;
  37914. //}
  37915. var curOffset = 0;
  37916. var stride = this.stride;
  37917. for (var i = 0; i < count; i++, curOffset += stride) {
  37918. var si = this._sortTable[i];
  37919. if (!si) {
  37920. si = new SortInfo();
  37921. this._sortTable[i] = si;
  37922. }
  37923. si.compareData = this.buffer[curOffset + this.compareValueOffset];
  37924. si.offset = curOffset;
  37925. si.swapedOffset = null;
  37926. this._sortedTable[i] = si;
  37927. }
  37928. // Let's sort the sorted table, we want to keep a track of the original one (that's why we have two buffers)
  37929. if (this.sortingAscending) {
  37930. this._sortedTable.sort(function (a, b) { return a.compareData - b.compareData; });
  37931. }
  37932. else {
  37933. this._sortedTable.sort(function (a, b) { return b.compareData - a.compareData; });
  37934. }
  37935. var swapElements = function (src, dst) {
  37936. for (var i = 0; i < stride; i++) {
  37937. var tps = _this.buffer[dst + i];
  37938. _this.buffer[dst + i] = _this.buffer[src + i];
  37939. _this.buffer[src + i] = tps;
  37940. }
  37941. };
  37942. // 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:
  37943. // 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),
  37944. // and I still want something with a good algorithm complexity.
  37945. // 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,
  37946. // we need sortTable for that, it contains the original layout of SortInfo object, not the sorted one.
  37947. // The best way is to use an extra field in SortInfo, because potentially every element can be replaced.
  37948. // 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
  37949. // until we find a SortInfo object without a swapedOffset which means we got the right location
  37950. // 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
  37951. // than a double allocation of the whole float32Array or a O(n²/2) typical algorithm.
  37952. for (var i = 0; i < count; i++) {
  37953. // Get the element to move
  37954. var sourceSI = this._sortedTable[i];
  37955. var destSI = this._sortTable[i];
  37956. var sourceOff = sourceSI.offset;
  37957. // If the source changed location, find the new one
  37958. if (sourceSI.swapedOffset) {
  37959. // Follow the swapedOffset until there's none, it will mean that curSI contains the new location in its offset member
  37960. var curSI = sourceSI;
  37961. while (curSI.swapedOffset) {
  37962. curSI = this._sortTable[curSI.swapedOffset / stride];
  37963. }
  37964. // Finally get the right location
  37965. sourceOff = curSI.offset;
  37966. }
  37967. // Tag the element being replaced with its new location
  37968. destSI.swapedOffset = sourceOff;
  37969. // Swap elements (only if needed)
  37970. if (sourceOff !== destSI.offset) {
  37971. swapElements(sourceOff, destSI.offset);
  37972. }
  37973. // Update the offset in the corresponding DFAE
  37974. //sourceSI.entry.offset = destSI.entry.offset;
  37975. this._allEntries[sourceSI.offset / stride].offset = destSI.offset;
  37976. }
  37977. this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  37978. return true;
  37979. };
  37980. return DynamicFloatArray;
  37981. }());
  37982. BABYLON.DynamicFloatArray = DynamicFloatArray;
  37983. var SortInfo = (function () {
  37984. function SortInfo() {
  37985. this.compareData = this.offset = this.swapedOffset = null;
  37986. }
  37987. return SortInfo;
  37988. }());
  37989. })(BABYLON || (BABYLON = {}));
  37990. var BABYLON;
  37991. (function (BABYLON) {
  37992. /**
  37993. * This class given information about a given character.
  37994. */
  37995. var CharInfo = (function () {
  37996. function CharInfo() {
  37997. }
  37998. return CharInfo;
  37999. }());
  38000. BABYLON.CharInfo = CharInfo;
  38001. var FontTexture = (function (_super) {
  38002. __extends(FontTexture, _super);
  38003. /**
  38004. * Create a new instance of the FontTexture class
  38005. * @param name the name of the texture
  38006. * @param font the font to use, use the W3C CSS notation
  38007. * @param scene the scene that owns the texture
  38008. * @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
  38009. * @param samplingMode the texture sampling mode
  38010. * @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.
  38011. */
  38012. function FontTexture(name, font, scene, maxCharCount, samplingMode, superSample) {
  38013. if (maxCharCount === void 0) { maxCharCount = 200; }
  38014. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  38015. if (superSample === void 0) { superSample = false; }
  38016. _super.call(this, null, scene, true, false, samplingMode);
  38017. this._charInfos = {};
  38018. this._curCharCount = 0;
  38019. this._lastUpdateCharCount = -1;
  38020. this._usedCounter = 1;
  38021. this.name = name;
  38022. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  38023. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  38024. this._superSample = false;
  38025. if (superSample) {
  38026. var sfont = this.getSuperSampleFont(font);
  38027. if (sfont) {
  38028. this._superSample = true;
  38029. font = sfont;
  38030. }
  38031. }
  38032. // First canvas creation to determine the size of the texture to create
  38033. this._canvas = document.createElement("canvas");
  38034. this._context = this._canvas.getContext("2d");
  38035. this._context.font = font;
  38036. this._context.fillStyle = "white";
  38037. this._cachedFontId = null;
  38038. var res = this.getFontHeight(font);
  38039. this._lineHeightSuper = res.height;
  38040. this._lineHeight = this._superSample ? (this._lineHeightSuper / 2) : this._lineHeightSuper;
  38041. this._offset = res.offset - 1;
  38042. var maxCharWidth = this._context.measureText("W").width;
  38043. this._spaceWidthSuper = this._context.measureText(" ").width;
  38044. this._spaceWidth = this._superSample ? (this._spaceWidthSuper / 2) : this._spaceWidthSuper;
  38045. // This is an approximate size, but should always be able to fit at least the maxCharCount
  38046. var totalEstSurface = this._lineHeightSuper * maxCharWidth * maxCharCount;
  38047. var edge = Math.sqrt(totalEstSurface);
  38048. var textSize = Math.pow(2, Math.ceil(Math.log(edge) / Math.log(2)));
  38049. // Create the texture that will store the font characters
  38050. this._texture = scene.getEngine().createDynamicTexture(textSize, textSize, false, samplingMode);
  38051. var textureSize = this.getSize();
  38052. this.hasAlpha = true;
  38053. // Recreate a new canvas with the final size: the one matching the texture (resizing the previous one doesn't work as one would expect...)
  38054. this._canvas = document.createElement("canvas");
  38055. this._canvas.width = textureSize.width;
  38056. this._canvas.height = textureSize.height;
  38057. this._context = this._canvas.getContext("2d");
  38058. this._context.textBaseline = "top";
  38059. this._context.font = font;
  38060. this._context.fillStyle = "white";
  38061. this._context.imageSmoothingEnabled = false;
  38062. this._currentFreePosition = BABYLON.Vector2.Zero();
  38063. // Add the basic ASCII based characters
  38064. for (var i = 0x20; i < 0x7F; i++) {
  38065. var c = String.fromCharCode(i);
  38066. this.getChar(c);
  38067. }
  38068. this.update();
  38069. }
  38070. Object.defineProperty(FontTexture.prototype, "isSuperSampled", {
  38071. get: function () {
  38072. return this._superSample;
  38073. },
  38074. enumerable: true,
  38075. configurable: true
  38076. });
  38077. Object.defineProperty(FontTexture.prototype, "spaceWidth", {
  38078. get: function () {
  38079. return this._spaceWidth;
  38080. },
  38081. enumerable: true,
  38082. configurable: true
  38083. });
  38084. Object.defineProperty(FontTexture.prototype, "lineHeight", {
  38085. get: function () {
  38086. return this._lineHeight;
  38087. },
  38088. enumerable: true,
  38089. configurable: true
  38090. });
  38091. FontTexture.GetCachedFontTexture = function (scene, fontName, supersample) {
  38092. if (supersample === void 0) { supersample = false; }
  38093. var s = scene;
  38094. if (!s.__fontTextureCache__) {
  38095. s.__fontTextureCache__ = new BABYLON.StringDictionary();
  38096. }
  38097. var dic = s.__fontTextureCache__;
  38098. var lfn = fontName.toLocaleLowerCase() + (supersample ? "_+SS" : "_-SS");
  38099. var ft = dic.get(lfn);
  38100. if (ft) {
  38101. ++ft._usedCounter;
  38102. return ft;
  38103. }
  38104. ft = new FontTexture(null, fontName, scene, supersample ? 100 : 200, BABYLON.Texture.BILINEAR_SAMPLINGMODE, supersample);
  38105. ft._cachedFontId = lfn;
  38106. dic.add(lfn, ft);
  38107. return ft;
  38108. };
  38109. FontTexture.ReleaseCachedFontTexture = function (scene, fontName, supersample) {
  38110. if (supersample === void 0) { supersample = false; }
  38111. var s = scene;
  38112. var dic = s.__fontTextureCache__;
  38113. if (!dic) {
  38114. return;
  38115. }
  38116. var lfn = fontName.toLocaleLowerCase() + (supersample ? "_+SS" : "_-SS");
  38117. var font = dic.get(lfn);
  38118. if (--font._usedCounter === 0) {
  38119. dic.remove(lfn);
  38120. font.dispose();
  38121. }
  38122. };
  38123. /**
  38124. * Make sure the given char is present in the font map.
  38125. * @param char the character to get or add
  38126. * @return the CharInfo instance corresponding to the given character
  38127. */
  38128. FontTexture.prototype.getChar = function (char) {
  38129. if (char.length !== 1) {
  38130. return null;
  38131. }
  38132. var info = this._charInfos[char];
  38133. if (info) {
  38134. return info;
  38135. }
  38136. info = new CharInfo();
  38137. var measure = this._context.measureText(char);
  38138. var textureSize = this.getSize();
  38139. // we reached the end of the current line?
  38140. var width = Math.round(measure.width);
  38141. var xMargin = 1 + Math.ceil(this._lineHeightSuper / 15); // Right now this empiric formula seems to work...
  38142. var yMargin = xMargin;
  38143. if (this._currentFreePosition.x + width + xMargin > textureSize.width) {
  38144. this._currentFreePosition.x = 0;
  38145. this._currentFreePosition.y += this._lineHeightSuper + yMargin;
  38146. // No more room?
  38147. if (this._currentFreePosition.y > textureSize.height) {
  38148. return this.getChar("!");
  38149. }
  38150. }
  38151. // Draw the character in the texture
  38152. this._context.fillText(char, this._currentFreePosition.x, this._currentFreePosition.y - this._offset);
  38153. // Fill the CharInfo object
  38154. info.topLeftUV = new BABYLON.Vector2(this._currentFreePosition.x / textureSize.width, this._currentFreePosition.y / textureSize.height);
  38155. info.bottomRightUV = new BABYLON.Vector2((this._currentFreePosition.x + width) / textureSize.width, info.topLeftUV.y + ((this._lineHeightSuper + 2) / textureSize.height));
  38156. info.charWidth = this._superSample ? (width / 2) : width;
  38157. // Add the info structure
  38158. this._charInfos[char] = info;
  38159. this._curCharCount++;
  38160. // Set the next position
  38161. this._currentFreePosition.x += width + xMargin;
  38162. return info;
  38163. };
  38164. FontTexture.prototype.measureText = function (text, tabulationSize) {
  38165. if (tabulationSize === void 0) { tabulationSize = 4; }
  38166. var maxWidth = 0;
  38167. var curWidth = 0;
  38168. var lineCount = 1;
  38169. var charxpos = 0;
  38170. // Parse each char of the string
  38171. for (var _i = 0, text_1 = text; _i < text_1.length; _i++) {
  38172. var char = text_1[_i];
  38173. // Next line feed?
  38174. if (char === "\n") {
  38175. maxWidth = Math.max(maxWidth, curWidth);
  38176. charxpos = 0;
  38177. curWidth = 0;
  38178. ++lineCount;
  38179. continue;
  38180. }
  38181. // Tabulation ?
  38182. if (char === "\t") {
  38183. var nextPos = charxpos + tabulationSize;
  38184. nextPos = nextPos - (nextPos % tabulationSize);
  38185. curWidth += (nextPos - charxpos) * this.spaceWidth;
  38186. charxpos = nextPos;
  38187. continue;
  38188. }
  38189. if (char < " ") {
  38190. continue;
  38191. }
  38192. curWidth += this.getChar(char).charWidth;
  38193. ++charxpos;
  38194. }
  38195. maxWidth = Math.max(maxWidth, curWidth);
  38196. return new BABYLON.Size(maxWidth, lineCount * this.lineHeight);
  38197. };
  38198. FontTexture.prototype.getSuperSampleFont = function (font) {
  38199. // Eternal thank to http://stackoverflow.com/a/10136041/802124
  38200. 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*$/;
  38201. var res = font.toLocaleLowerCase().match(regex);
  38202. if (res == null) {
  38203. return null;
  38204. }
  38205. var size = parseInt(res[4]);
  38206. res[4] = (size * 2).toString() + (res[4].match(/\D+/) || []).pop();
  38207. var newFont = "";
  38208. for (var j = 1; j < res.length; j++) {
  38209. if (res[j] != null) {
  38210. newFont += res[j] + " ";
  38211. }
  38212. }
  38213. return newFont;
  38214. };
  38215. // More info here: https://videlais.com/2014/03/16/the-many-and-varied-problems-with-measuring-font-height-for-html5-canvas/
  38216. FontTexture.prototype.getFontHeight = function (font) {
  38217. var fontDraw = document.createElement("canvas");
  38218. var ctx = fontDraw.getContext('2d');
  38219. ctx.fillRect(0, 0, fontDraw.width, fontDraw.height);
  38220. ctx.textBaseline = 'top';
  38221. ctx.fillStyle = 'white';
  38222. ctx.font = font;
  38223. ctx.fillText('jH|', 0, 0);
  38224. var pixels = ctx.getImageData(0, 0, fontDraw.width, fontDraw.height).data;
  38225. var start = -1;
  38226. var end = -1;
  38227. for (var row = 0; row < fontDraw.height; row++) {
  38228. for (var column = 0; column < fontDraw.width; column++) {
  38229. var index = (row * fontDraw.width + column) * 4;
  38230. if (pixels[index] === 0) {
  38231. if (column === fontDraw.width - 1 && start !== -1) {
  38232. end = row;
  38233. row = fontDraw.height;
  38234. break;
  38235. }
  38236. continue;
  38237. }
  38238. else {
  38239. if (start === -1) {
  38240. start = row;
  38241. }
  38242. break;
  38243. }
  38244. }
  38245. }
  38246. return { height: (end - start) + 1, offset: start - 1 };
  38247. };
  38248. Object.defineProperty(FontTexture.prototype, "canRescale", {
  38249. get: function () {
  38250. return false;
  38251. },
  38252. enumerable: true,
  38253. configurable: true
  38254. });
  38255. FontTexture.prototype.getContext = function () {
  38256. return this._context;
  38257. };
  38258. /**
  38259. * Call this method when you've call getChar() at least one time, this will update the texture if needed.
  38260. * Don't be afraid to call it, if no new character was added, this method simply does nothing.
  38261. */
  38262. FontTexture.prototype.update = function () {
  38263. // Update only if there's new char added since the previous update
  38264. if (this._lastUpdateCharCount < this._curCharCount) {
  38265. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, false, true);
  38266. this._lastUpdateCharCount = this._curCharCount;
  38267. }
  38268. };
  38269. // cloning should be prohibited, there's no point to duplicate this texture at all
  38270. FontTexture.prototype.clone = function () {
  38271. return null;
  38272. };
  38273. /**
  38274. * For FontTexture retrieved using GetCachedFontTexture, use this method when you transfer this object's lifetime to another party in order to share this resource.
  38275. * When the other party is done with this object, decCachedFontTextureCounter must be called.
  38276. */
  38277. FontTexture.prototype.incCachedFontTextureCounter = function () {
  38278. ++this._usedCounter;
  38279. };
  38280. /**
  38281. * Use this method only in conjunction with incCachedFontTextureCounter, call it when you no longer need to use this shared resource.
  38282. */
  38283. FontTexture.prototype.decCachedFontTextureCounter = function () {
  38284. var s = this.getScene();
  38285. var dic = s.__fontTextureCache__;
  38286. if (!dic) {
  38287. return;
  38288. }
  38289. if (--this._usedCounter === 0) {
  38290. dic.remove(this._cachedFontId);
  38291. this.dispose();
  38292. }
  38293. };
  38294. return FontTexture;
  38295. }(BABYLON.Texture));
  38296. BABYLON.FontTexture = FontTexture;
  38297. })(BABYLON || (BABYLON = {}));
  38298. var BABYLON;
  38299. (function (BABYLON) {
  38300. var MapTexture = (function (_super) {
  38301. __extends(MapTexture, _super);
  38302. function MapTexture(name, scene, size, samplingMode, useMipMap) {
  38303. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  38304. if (useMipMap === void 0) { useMipMap = false; }
  38305. _super.call(this, null, scene, !useMipMap, false, samplingMode);
  38306. this.name = name;
  38307. this._size = size;
  38308. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  38309. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  38310. // Create the rectPackMap that will allocate portion of the texture
  38311. this._rectPackingMap = new BABYLON.RectPackingMap(new BABYLON.Size(size.width, size.height));
  38312. // Create the texture that will store the content
  38313. this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: !this.noMipmap, type: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT });
  38314. }
  38315. /**
  38316. * Allocate a rectangle of a given size in the texture map
  38317. * @param size the size of the rectangle to allocation
  38318. * @return the PackedRect instance corresponding to the allocated rect or null is there was not enough space to allocate it.
  38319. */
  38320. MapTexture.prototype.allocateRect = function (size) {
  38321. return this._rectPackingMap.addRect(size);
  38322. };
  38323. /**
  38324. * Free a given rectangle from the texture map
  38325. * @param rectInfo the instance corresponding to the rect to free.
  38326. */
  38327. MapTexture.prototype.freeRect = function (rectInfo) {
  38328. if (rectInfo) {
  38329. rectInfo.freeContent();
  38330. }
  38331. };
  38332. Object.defineProperty(MapTexture.prototype, "freeSpace", {
  38333. /**
  38334. * Return the available space in the range of [O;1]. 0 being not space left at all, 1 being an empty texture map.
  38335. * This is the cumulated space, not the biggest available surface. Due to fragmentation you may not allocate a rect corresponding to this surface.
  38336. * @returns {}
  38337. */
  38338. get: function () {
  38339. return this._rectPackingMap.freeSpace;
  38340. },
  38341. enumerable: true,
  38342. configurable: true
  38343. });
  38344. /**
  38345. * Bind the texture to the rendering engine to render in the zone of a given rectangle.
  38346. * 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.
  38347. * Don't forget to call unbindTexture when you're done rendering
  38348. * @param rect the zone to render to
  38349. * @param clear true to clear the portion's color/depth data
  38350. */
  38351. MapTexture.prototype.bindTextureForRect = function (rect, clear) {
  38352. return this.bindTextureForPosSize(rect.pos, rect.contentSize, clear);
  38353. };
  38354. /**
  38355. * Bind the texture to the rendering engine to render in the zone of the given size at the given position.
  38356. * 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.
  38357. * Don't forget to call unbindTexture when you're done rendering
  38358. * @param pos the position into the texture
  38359. * @param size the portion to fit the clip space to
  38360. * @param clear true to clear the portion's color/depth data
  38361. */
  38362. MapTexture.prototype.bindTextureForPosSize = function (pos, size, clear) {
  38363. var engine = this.getScene().getEngine();
  38364. engine.bindFramebuffer(this._texture);
  38365. this._replacedViewport = engine.setDirectViewport(pos.x, pos.y, size.width, size.height);
  38366. if (clear) {
  38367. // We only want to clear the part of the texture we're binding to, only the scissor can help us to achieve that
  38368. engine.scissorClear(pos.x, pos.y, size.width, size.height, new BABYLON.Color4(0, 0, 0, 0));
  38369. }
  38370. };
  38371. /**
  38372. * Unbind the texture map from the rendering engine.
  38373. * Call this method when you're done rendering. A previous call to bindTextureForRect has to be made.
  38374. * @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.
  38375. */
  38376. MapTexture.prototype.unbindTexture = function (dumpForDebug) {
  38377. // Dump ?
  38378. if (dumpForDebug) {
  38379. BABYLON.Tools.DumpFramebuffer(this._size.width, this._size.height, this.getScene().getEngine());
  38380. }
  38381. var engine = this.getScene().getEngine();
  38382. if (this._replacedViewport) {
  38383. engine.setViewport(this._replacedViewport);
  38384. this._replacedViewport = null;
  38385. }
  38386. engine.unBindFramebuffer(this._texture);
  38387. };
  38388. Object.defineProperty(MapTexture.prototype, "canRescale", {
  38389. get: function () {
  38390. return false;
  38391. },
  38392. enumerable: true,
  38393. configurable: true
  38394. });
  38395. // Note, I don't know what behavior this method should have: clone the underlying texture/rectPackingMap or just reference them?
  38396. // Anyway, there's not much point to use this method for this kind of texture I guess
  38397. MapTexture.prototype.clone = function () {
  38398. return null;
  38399. };
  38400. return MapTexture;
  38401. }(BABYLON.Texture));
  38402. BABYLON.MapTexture = MapTexture;
  38403. })(BABYLON || (BABYLON = {}));
  38404. var BABYLON;
  38405. (function (BABYLON) {
  38406. /**
  38407. * Stores 2D Bounding Information.
  38408. * This class handles a circle area and a bounding rectangle one.
  38409. */
  38410. var BoundingInfo2D = (function () {
  38411. function BoundingInfo2D() {
  38412. this.radius = 0;
  38413. this.center = BABYLON.Vector2.Zero();
  38414. this.extent = BABYLON.Vector2.Zero();
  38415. }
  38416. /**
  38417. * Create a BoundingInfo2D object from a given size
  38418. * @param size the size that will be used to set the extend, radius will be computed from it.
  38419. */
  38420. BoundingInfo2D.CreateFromSize = function (size) {
  38421. var r = new BoundingInfo2D();
  38422. BoundingInfo2D.CreateFromSizeToRef(size, r);
  38423. return r;
  38424. };
  38425. /**
  38426. * Create a BoundingInfo2D object from a given radius
  38427. * @param radius the radius to use, the extent will be computed from it.
  38428. */
  38429. BoundingInfo2D.CreateFromRadius = function (radius) {
  38430. var r = new BoundingInfo2D();
  38431. BoundingInfo2D.CreateFromRadiusToRef(radius, r);
  38432. return r;
  38433. };
  38434. /**
  38435. * Create a BoundingInfo2D object from a list of points.
  38436. * The resulted object will be the smallest bounding area that includes all the given points.
  38437. * @param points an array of points to compute the bounding object from.
  38438. */
  38439. BoundingInfo2D.CreateFromPoints = function (points) {
  38440. var r = new BoundingInfo2D();
  38441. BoundingInfo2D.CreateFromPointsToRef(points, r);
  38442. return r;
  38443. };
  38444. /**
  38445. * Update a BoundingInfo2D object using the given Size as input
  38446. * @param size the bounding data will be computed from this size.
  38447. * @param b must be a valid/allocated object, it will contain the result of the operation
  38448. */
  38449. BoundingInfo2D.CreateFromSizeToRef = function (size, b) {
  38450. if (!size) {
  38451. size = BABYLON.Size.Zero();
  38452. }
  38453. b.center.x = +size.width / 2;
  38454. b.center.y = +size.height / 2;
  38455. b.extent.x = b.center.x;
  38456. b.extent.y = b.center.y;
  38457. b.radius = b.extent.length();
  38458. };
  38459. /**
  38460. * Update a BoundingInfo2D object using the given radius as input
  38461. * @param radius the bounding data will be computed from this radius
  38462. * @param b must be a valid/allocated object, it will contain the result of the operation
  38463. */
  38464. BoundingInfo2D.CreateFromRadiusToRef = function (radius, b) {
  38465. b.center.x = b.center.y = 0;
  38466. var r = +radius;
  38467. b.extent.x = r;
  38468. b.extent.y = r;
  38469. b.radius = r;
  38470. };
  38471. /**
  38472. * Update a BoundingInfo2D object using the given points array as input
  38473. * @param points the point array to use to update the bounding data
  38474. * @param b must be a valid/allocated object, it will contain the result of the operation
  38475. */
  38476. BoundingInfo2D.CreateFromPointsToRef = function (points, b) {
  38477. var xmin = Number.MAX_VALUE, ymin = Number.MAX_VALUE, xmax = Number.MIN_VALUE, ymax = Number.MIN_VALUE;
  38478. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  38479. var p = points_1[_i];
  38480. xmin = Math.min(p.x, xmin);
  38481. xmax = Math.max(p.x, xmax);
  38482. ymin = Math.min(p.y, ymin);
  38483. ymax = Math.max(p.y, ymax);
  38484. }
  38485. BoundingInfo2D.CreateFromMinMaxToRef(xmin, xmax, ymin, ymax, b);
  38486. };
  38487. /**
  38488. * Update a BoundingInfo2D object using the given min/max values as input
  38489. * @param xmin the smallest x coordinate
  38490. * @param xmax the biggest x coordinate
  38491. * @param ymin the smallest y coordinate
  38492. * @param ymax the buggest y coordinate
  38493. * @param b must be a valid/allocated object, it will contain the result of the operation
  38494. */
  38495. BoundingInfo2D.CreateFromMinMaxToRef = function (xmin, xmax, ymin, ymax, b) {
  38496. var w = xmax - xmin;
  38497. var h = ymax - ymin;
  38498. b.center = new BABYLON.Vector2(xmin + w / 2, ymin + h / 2);
  38499. b.extent = new BABYLON.Vector2(xmax - b.center.x, ymax - b.center.y);
  38500. b.radius = b.extent.length();
  38501. };
  38502. /**
  38503. * Duplicate this instance and return a new one
  38504. * @return the duplicated instance
  38505. */
  38506. BoundingInfo2D.prototype.clone = function () {
  38507. var r = new BoundingInfo2D();
  38508. r.center = this.center.clone();
  38509. r.radius = this.radius;
  38510. r.extent = this.extent.clone();
  38511. return r;
  38512. };
  38513. BoundingInfo2D.prototype.clear = function () {
  38514. this.center.copyFromFloats(0, 0);
  38515. this.radius = 0;
  38516. this.extent.copyFromFloats(0, 0);
  38517. };
  38518. BoundingInfo2D.prototype.copyFrom = function (src) {
  38519. this.center.copyFrom(src.center);
  38520. this.radius = src.radius;
  38521. this.extent.copyFrom(src.extent);
  38522. };
  38523. /**
  38524. * return the max extend of the bounding info
  38525. */
  38526. BoundingInfo2D.prototype.max = function () {
  38527. var r = BABYLON.Vector2.Zero();
  38528. this.maxToRef(r);
  38529. return r;
  38530. };
  38531. /**
  38532. * Update a vector2 with the max extend of the bounding info
  38533. * @param result must be a valid/allocated vector2 that will contain the result of the operation
  38534. */
  38535. BoundingInfo2D.prototype.maxToRef = function (result) {
  38536. result.x = this.center.x + this.extent.x;
  38537. result.y = this.center.y + this.extent.y;
  38538. };
  38539. /**
  38540. * Apply a transformation matrix to this BoundingInfo2D and return a new instance containing the result
  38541. * @param matrix the transformation matrix to apply
  38542. * @return the new instance containing the result of the transformation applied on this BoundingInfo2D
  38543. */
  38544. BoundingInfo2D.prototype.transform = function (matrix) {
  38545. var r = new BoundingInfo2D();
  38546. this.transformToRef(matrix, r);
  38547. return r;
  38548. };
  38549. /**
  38550. * Compute the union of this BoundingInfo2D with a given one, returns a new BoundingInfo2D as a result
  38551. * @param other the second BoundingInfo2D to compute the union with this one
  38552. * @return a new instance containing the result of the union
  38553. */
  38554. BoundingInfo2D.prototype.union = function (other) {
  38555. var r = new BoundingInfo2D();
  38556. this.unionToRef(other, r);
  38557. return r;
  38558. };
  38559. /**
  38560. * Transform this BoundingInfo2D with a given matrix and store the result in an existing BoundingInfo2D instance.
  38561. * 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.
  38562. * @param matrix The matrix to use to compute the transformation
  38563. * @param result A VALID (i.e. allocated) BoundingInfo2D object where the result will be stored
  38564. */
  38565. BoundingInfo2D.prototype.transformToRef = function (matrix, result) {
  38566. // Construct a bounding box based on the extent values
  38567. var p = BoundingInfo2D._transform;
  38568. p[0].x = this.center.x + this.extent.x;
  38569. p[0].y = this.center.y + this.extent.y;
  38570. p[1].x = this.center.x + this.extent.x;
  38571. p[1].y = this.center.y - this.extent.y;
  38572. p[2].x = this.center.x - this.extent.x;
  38573. p[2].y = this.center.y - this.extent.y;
  38574. p[3].x = this.center.x - this.extent.x;
  38575. p[3].y = this.center.y + this.extent.y;
  38576. // Transform the four points of the bounding box with the matrix
  38577. for (var i = 0; i < 4; i++) {
  38578. BABYLON.Vector2.TransformToRef(p[i], matrix, p[i]);
  38579. }
  38580. BoundingInfo2D.CreateFromPointsToRef(p, result);
  38581. };
  38582. /**
  38583. * Compute the union of this BoundingInfo2D with another one and store the result in a third valid BoundingInfo2D object
  38584. * 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.
  38585. * @param other the second object used to compute the union
  38586. * @param result a VALID BoundingInfo2D instance (i.e. allocated) where the result will be stored
  38587. */
  38588. BoundingInfo2D.prototype.unionToRef = function (other, result) {
  38589. var xmax = Math.max(this.center.x + this.extent.x, other.center.x + other.extent.x);
  38590. var ymax = Math.max(this.center.y + this.extent.y, other.center.y + other.extent.y);
  38591. var xmin = Math.min(this.center.x - this.extent.x, other.center.x - other.extent.x);
  38592. var ymin = Math.min(this.center.y - this.extent.y, other.center.y - other.extent.y);
  38593. BoundingInfo2D.CreateFromMinMaxToRef(xmin, xmax, ymin, ymax, result);
  38594. };
  38595. /**
  38596. * Check if the given point is inside the BoundingInfo.
  38597. * The test is first made on the radius, then inside the rectangle described by the extent
  38598. * @param pickPosition the position to test
  38599. * @return true if the point is inside, false otherwise
  38600. */
  38601. BoundingInfo2D.prototype.doesIntersect = function (pickPosition) {
  38602. // is it inside the radius?
  38603. var pickLocal = pickPosition.subtract(this.center);
  38604. if (pickLocal.lengthSquared() <= (this.radius * this.radius)) {
  38605. // is it inside the rectangle?
  38606. return ((Math.abs(pickLocal.x) <= this.extent.x) && (Math.abs(pickLocal.y) <= this.extent.y));
  38607. }
  38608. return false;
  38609. };
  38610. BoundingInfo2D._transform = new Array(BABYLON.Vector2.Zero(), BABYLON.Vector2.Zero(), BABYLON.Vector2.Zero(), BABYLON.Vector2.Zero());
  38611. return BoundingInfo2D;
  38612. }());
  38613. BABYLON.BoundingInfo2D = BoundingInfo2D;
  38614. })(BABYLON || (BABYLON = {}));
  38615. var BABYLON;
  38616. (function (BABYLON) {
  38617. var LayoutEngineBase = (function () {
  38618. function LayoutEngineBase() {
  38619. this.layoutDirtyOnPropertyChangedMask = 0;
  38620. }
  38621. LayoutEngineBase.prototype.updateLayout = function (prim) {
  38622. };
  38623. Object.defineProperty(LayoutEngineBase.prototype, "isChildPositionAllowed", {
  38624. get: function () {
  38625. return false;
  38626. },
  38627. enumerable: true,
  38628. configurable: true
  38629. });
  38630. LayoutEngineBase.prototype.isLocked = function () {
  38631. return this._isLocked;
  38632. };
  38633. LayoutEngineBase.prototype.lock = function () {
  38634. if (this._isLocked) {
  38635. return false;
  38636. }
  38637. this._isLocked = true;
  38638. return true;
  38639. };
  38640. LayoutEngineBase = __decorate([
  38641. BABYLON.className("LayoutEngineBase")
  38642. ], LayoutEngineBase);
  38643. return LayoutEngineBase;
  38644. }());
  38645. BABYLON.LayoutEngineBase = LayoutEngineBase;
  38646. var CanvasLayoutEngine = (function (_super) {
  38647. __extends(CanvasLayoutEngine, _super);
  38648. function CanvasLayoutEngine() {
  38649. _super.apply(this, arguments);
  38650. }
  38651. // A very simple (no) layout computing...
  38652. // The Canvas and its direct children gets the Canvas' size as Layout Area
  38653. // Indirect children have their Layout Area to the actualSize (margin area) of their parent
  38654. CanvasLayoutEngine.prototype.updateLayout = function (prim) {
  38655. // If this prim is layoutDiry we update its layoutArea and also the one of its direct children
  38656. if (prim._isFlagSet(BABYLON.SmartPropertyPrim.flagLayoutDirty)) {
  38657. for (var _i = 0, _a = prim.children; _i < _a.length; _i++) {
  38658. var child = _a[_i];
  38659. this._doUpdate(child);
  38660. }
  38661. prim._clearFlags(BABYLON.SmartPropertyPrim.flagLayoutDirty);
  38662. }
  38663. };
  38664. CanvasLayoutEngine.prototype._doUpdate = function (prim) {
  38665. // Canvas ?
  38666. if (prim instanceof BABYLON.Canvas2D) {
  38667. prim.layoutArea = prim.actualSize;
  38668. }
  38669. else if (prim.parent instanceof BABYLON.Canvas2D) {
  38670. prim.layoutArea = prim.owner.actualSize;
  38671. }
  38672. else {
  38673. prim.layoutArea = prim.parent.contentArea;
  38674. }
  38675. };
  38676. Object.defineProperty(CanvasLayoutEngine.prototype, "isChildPositionAllowed", {
  38677. get: function () {
  38678. return true;
  38679. },
  38680. enumerable: true,
  38681. configurable: true
  38682. });
  38683. CanvasLayoutEngine.Singleton = new CanvasLayoutEngine();
  38684. CanvasLayoutEngine = __decorate([
  38685. BABYLON.className("CanvasLayoutEngine")
  38686. ], CanvasLayoutEngine);
  38687. return CanvasLayoutEngine;
  38688. }(LayoutEngineBase));
  38689. BABYLON.CanvasLayoutEngine = CanvasLayoutEngine;
  38690. var StackPanelLayoutEngine = (function (_super) {
  38691. __extends(StackPanelLayoutEngine, _super);
  38692. function StackPanelLayoutEngine() {
  38693. _super.call(this);
  38694. this._isHorizontal = true;
  38695. this.layoutDirtyOnPropertyChangedMask = BABYLON.Prim2DBase.sizeProperty.flagId;
  38696. }
  38697. Object.defineProperty(StackPanelLayoutEngine, "Horizontal", {
  38698. get: function () {
  38699. if (!StackPanelLayoutEngine._horizontal) {
  38700. StackPanelLayoutEngine._horizontal = new StackPanelLayoutEngine();
  38701. StackPanelLayoutEngine._horizontal.isHorizontal = true;
  38702. StackPanelLayoutEngine._horizontal.lock();
  38703. }
  38704. return StackPanelLayoutEngine._horizontal;
  38705. },
  38706. enumerable: true,
  38707. configurable: true
  38708. });
  38709. Object.defineProperty(StackPanelLayoutEngine, "Vertical", {
  38710. get: function () {
  38711. if (!StackPanelLayoutEngine._vertical) {
  38712. StackPanelLayoutEngine._vertical = new StackPanelLayoutEngine();
  38713. StackPanelLayoutEngine._vertical.isHorizontal = false;
  38714. StackPanelLayoutEngine._vertical.lock();
  38715. }
  38716. return StackPanelLayoutEngine._vertical;
  38717. },
  38718. enumerable: true,
  38719. configurable: true
  38720. });
  38721. Object.defineProperty(StackPanelLayoutEngine.prototype, "isHorizontal", {
  38722. get: function () {
  38723. return this._isHorizontal;
  38724. },
  38725. set: function (val) {
  38726. if (this.isLocked()) {
  38727. return;
  38728. }
  38729. this._isHorizontal = val;
  38730. },
  38731. enumerable: true,
  38732. configurable: true
  38733. });
  38734. StackPanelLayoutEngine.prototype.updateLayout = function (prim) {
  38735. if (prim._isFlagSet(BABYLON.SmartPropertyPrim.flagLayoutDirty)) {
  38736. var x = 0;
  38737. var y = 0;
  38738. var h = this.isHorizontal;
  38739. var max = 0;
  38740. for (var _i = 0, _a = prim.children; _i < _a.length; _i++) {
  38741. var child = _a[_i];
  38742. var layoutArea = void 0;
  38743. if (child._hasMargin) {
  38744. child.margin.computeWithAlignment(prim.layoutArea, child.actualSize, child.marginAlignment, StackPanelLayoutEngine.dstOffset, StackPanelLayoutEngine.dstArea, true);
  38745. layoutArea = StackPanelLayoutEngine.dstArea;
  38746. child.layoutArea = layoutArea;
  38747. }
  38748. else {
  38749. layoutArea = child.layoutArea;
  38750. child.margin.computeArea(child.actualSize, layoutArea);
  38751. }
  38752. max = Math.max(max, h ? layoutArea.height : layoutArea.width);
  38753. }
  38754. for (var _b = 0, _c = prim.children; _b < _c.length; _b++) {
  38755. var child = _c[_b];
  38756. child.layoutAreaPos = new BABYLON.Vector2(x, y);
  38757. var layoutArea = child.layoutArea;
  38758. if (h) {
  38759. x += layoutArea.width;
  38760. child.layoutArea = new BABYLON.Size(layoutArea.width, max);
  38761. }
  38762. else {
  38763. y += layoutArea.height;
  38764. child.layoutArea = new BABYLON.Size(max, layoutArea.height);
  38765. }
  38766. }
  38767. prim._clearFlags(BABYLON.SmartPropertyPrim.flagLayoutDirty);
  38768. }
  38769. };
  38770. Object.defineProperty(StackPanelLayoutEngine.prototype, "isChildPositionAllowed", {
  38771. get: function () {
  38772. return false;
  38773. },
  38774. enumerable: true,
  38775. configurable: true
  38776. });
  38777. StackPanelLayoutEngine._horizontal = null;
  38778. StackPanelLayoutEngine._vertical = null;
  38779. StackPanelLayoutEngine.dstOffset = BABYLON.Vector2.Zero();
  38780. StackPanelLayoutEngine.dstArea = BABYLON.Size.Zero();
  38781. StackPanelLayoutEngine = __decorate([
  38782. BABYLON.className("StackPanelLayoutEngine")
  38783. ], StackPanelLayoutEngine);
  38784. return StackPanelLayoutEngine;
  38785. }(LayoutEngineBase));
  38786. BABYLON.StackPanelLayoutEngine = StackPanelLayoutEngine;
  38787. })(BABYLON || (BABYLON = {}));
  38788. var BABYLON;
  38789. (function (BABYLON) {
  38790. /**
  38791. * Base class implementing the ILocable interface.
  38792. * The particularity of this class is to call the protected onLock() method when the instance is about to be locked for good.
  38793. */
  38794. var LockableBase = (function () {
  38795. function LockableBase() {
  38796. }
  38797. LockableBase.prototype.isLocked = function () {
  38798. return this._isLocked;
  38799. };
  38800. LockableBase.prototype.lock = function () {
  38801. if (this._isLocked) {
  38802. return true;
  38803. }
  38804. this.onLock();
  38805. this._isLocked = true;
  38806. return false;
  38807. };
  38808. /**
  38809. * Protected handler that will be called when the instance is about to be locked.
  38810. */
  38811. LockableBase.prototype.onLock = function () {
  38812. };
  38813. return LockableBase;
  38814. }());
  38815. BABYLON.LockableBase = LockableBase;
  38816. var SolidColorBrush2D = (function (_super) {
  38817. __extends(SolidColorBrush2D, _super);
  38818. function SolidColorBrush2D(color, lock) {
  38819. if (lock === void 0) { lock = false; }
  38820. _super.call(this);
  38821. this._color = color;
  38822. if (lock) {
  38823. {
  38824. this.lock();
  38825. }
  38826. }
  38827. }
  38828. /**
  38829. * Return true if the brush is transparent, false if it's totally opaque
  38830. */
  38831. SolidColorBrush2D.prototype.isTransparent = function () {
  38832. return this._color && this._color.a < 1.0;
  38833. };
  38834. Object.defineProperty(SolidColorBrush2D.prototype, "color", {
  38835. /**
  38836. * The color used by this instance to render
  38837. * @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.
  38838. */
  38839. get: function () {
  38840. return this._color;
  38841. },
  38842. set: function (value) {
  38843. if (this.isLocked()) {
  38844. return;
  38845. }
  38846. this._color = value;
  38847. },
  38848. enumerable: true,
  38849. configurable: true
  38850. });
  38851. /**
  38852. * Return a unique identifier of the instance, which is simply the hexadecimal representation (CSS Style) of the solid color.
  38853. */
  38854. SolidColorBrush2D.prototype.toString = function () {
  38855. return this._color.toHexString();
  38856. };
  38857. SolidColorBrush2D = __decorate([
  38858. BABYLON.className("SolidColorBrush2D")
  38859. ], SolidColorBrush2D);
  38860. return SolidColorBrush2D;
  38861. }(LockableBase));
  38862. BABYLON.SolidColorBrush2D = SolidColorBrush2D;
  38863. var GradientColorBrush2D = (function (_super) {
  38864. __extends(GradientColorBrush2D, _super);
  38865. function GradientColorBrush2D(color1, color2, translation, rotation, scale, lock) {
  38866. if (translation === void 0) { translation = BABYLON.Vector2.Zero(); }
  38867. if (rotation === void 0) { rotation = 0; }
  38868. if (scale === void 0) { scale = 1; }
  38869. if (lock === void 0) { lock = false; }
  38870. _super.call(this);
  38871. this._color1 = color1;
  38872. this._color2 = color2;
  38873. this._translation = translation;
  38874. this._rotation = rotation;
  38875. this._scale = scale;
  38876. if (lock) {
  38877. this.lock();
  38878. }
  38879. }
  38880. /**
  38881. * Return true if the brush is transparent, false if it's totally opaque
  38882. */
  38883. GradientColorBrush2D.prototype.isTransparent = function () {
  38884. return (this._color1 && this._color1.a < 1.0) || (this._color2 && this._color2.a < 1.0);
  38885. };
  38886. Object.defineProperty(GradientColorBrush2D.prototype, "color1", {
  38887. /**
  38888. * First color, the blend will start from this color
  38889. */
  38890. get: function () {
  38891. return this._color1;
  38892. },
  38893. set: function (value) {
  38894. if (this.isLocked()) {
  38895. return;
  38896. }
  38897. this._color1 = value;
  38898. },
  38899. enumerable: true,
  38900. configurable: true
  38901. });
  38902. Object.defineProperty(GradientColorBrush2D.prototype, "color2", {
  38903. /**
  38904. * Second color, the blend will end to this color
  38905. */
  38906. get: function () {
  38907. return this._color2;
  38908. },
  38909. set: function (value) {
  38910. if (this.isLocked()) {
  38911. return;
  38912. }
  38913. this._color2 = value;
  38914. },
  38915. enumerable: true,
  38916. configurable: true
  38917. });
  38918. Object.defineProperty(GradientColorBrush2D.prototype, "translation", {
  38919. /**
  38920. * Translation vector to apply on the blend
  38921. * Default is [0;0]
  38922. */
  38923. get: function () {
  38924. return this._translation;
  38925. },
  38926. set: function (value) {
  38927. if (this.isLocked()) {
  38928. return;
  38929. }
  38930. this._translation = value;
  38931. },
  38932. enumerable: true,
  38933. configurable: true
  38934. });
  38935. Object.defineProperty(GradientColorBrush2D.prototype, "rotation", {
  38936. /**
  38937. * Rotation in radian to apply to the brush
  38938. * Default direction of the brush is vertical, you can change this using this property.
  38939. * Default is 0.
  38940. */
  38941. get: function () {
  38942. return this._rotation;
  38943. },
  38944. set: function (value) {
  38945. if (this.isLocked()) {
  38946. return;
  38947. }
  38948. this._rotation = value;
  38949. },
  38950. enumerable: true,
  38951. configurable: true
  38952. });
  38953. Object.defineProperty(GradientColorBrush2D.prototype, "scale", {
  38954. /**
  38955. * Scale factor to apply to the gradient.
  38956. * Default is 1: no scale.
  38957. */
  38958. get: function () {
  38959. return this._scale;
  38960. },
  38961. set: function (value) {
  38962. if (this.isLocked()) {
  38963. return;
  38964. }
  38965. this._scale = value;
  38966. },
  38967. enumerable: true,
  38968. configurable: true
  38969. });
  38970. /**
  38971. * Return a string describing the brush
  38972. */
  38973. GradientColorBrush2D.prototype.toString = function () {
  38974. return "C1:" + this._color1 + ";C2:" + this._color2 + ";T:" + this._translation.toString() + ";R:" + this._rotation + ";S:" + this._scale + ";";
  38975. };
  38976. /**
  38977. * Build a unique key string for the given parameters
  38978. */
  38979. GradientColorBrush2D.BuildKey = function (color1, color2, translation, rotation, scale) {
  38980. return "C1:" + color1 + ";C2:" + color2 + ";T:" + translation.toString() + ";R:" + rotation + ";S:" + scale + ";";
  38981. };
  38982. GradientColorBrush2D = __decorate([
  38983. BABYLON.className("GradientColorBrush2D")
  38984. ], GradientColorBrush2D);
  38985. return GradientColorBrush2D;
  38986. }(LockableBase));
  38987. BABYLON.GradientColorBrush2D = GradientColorBrush2D;
  38988. })(BABYLON || (BABYLON = {}));
  38989. var BABYLON;
  38990. (function (BABYLON) {
  38991. var Prim2DClassInfo = (function () {
  38992. function Prim2DClassInfo() {
  38993. }
  38994. return Prim2DClassInfo;
  38995. }());
  38996. BABYLON.Prim2DClassInfo = Prim2DClassInfo;
  38997. var Prim2DPropInfo = (function () {
  38998. function Prim2DPropInfo() {
  38999. }
  39000. Prim2DPropInfo.PROPKIND_MODEL = 1;
  39001. Prim2DPropInfo.PROPKIND_INSTANCE = 2;
  39002. Prim2DPropInfo.PROPKIND_DYNAMIC = 3;
  39003. return Prim2DPropInfo;
  39004. }());
  39005. BABYLON.Prim2DPropInfo = Prim2DPropInfo;
  39006. /**
  39007. * Custom type of the propertyChanged observable
  39008. */
  39009. var PropertyChangedInfo = (function () {
  39010. function PropertyChangedInfo() {
  39011. }
  39012. return PropertyChangedInfo;
  39013. }());
  39014. BABYLON.PropertyChangedInfo = PropertyChangedInfo;
  39015. var ClassTreeInfo = (function () {
  39016. function ClassTreeInfo(baseClass, type, classContentFactory) {
  39017. this._baseClass = baseClass;
  39018. this._type = type;
  39019. this._subClasses = new Array();
  39020. this._levelContent = new BABYLON.StringDictionary();
  39021. this._classContentFactory = classContentFactory;
  39022. }
  39023. Object.defineProperty(ClassTreeInfo.prototype, "classContent", {
  39024. get: function () {
  39025. if (!this._classContent) {
  39026. this._classContent = this._classContentFactory(this._baseClass ? this._baseClass.classContent : null);
  39027. }
  39028. return this._classContent;
  39029. },
  39030. enumerable: true,
  39031. configurable: true
  39032. });
  39033. Object.defineProperty(ClassTreeInfo.prototype, "type", {
  39034. get: function () {
  39035. return this._type;
  39036. },
  39037. enumerable: true,
  39038. configurable: true
  39039. });
  39040. Object.defineProperty(ClassTreeInfo.prototype, "levelContent", {
  39041. get: function () {
  39042. return this._levelContent;
  39043. },
  39044. enumerable: true,
  39045. configurable: true
  39046. });
  39047. Object.defineProperty(ClassTreeInfo.prototype, "fullContent", {
  39048. get: function () {
  39049. if (!this._fullContent) {
  39050. var dic_1 = new BABYLON.StringDictionary();
  39051. var curLevel = this;
  39052. while (curLevel) {
  39053. curLevel.levelContent.forEach(function (k, v) { return dic_1.add(k, v); });
  39054. curLevel = curLevel._baseClass;
  39055. }
  39056. this._fullContent = dic_1;
  39057. }
  39058. return this._fullContent;
  39059. },
  39060. enumerable: true,
  39061. configurable: true
  39062. });
  39063. ClassTreeInfo.prototype.getLevelOf = function (type) {
  39064. // Are we already there?
  39065. if (type === this._type) {
  39066. return this;
  39067. }
  39068. var baseProto = Object.getPrototypeOf(type);
  39069. var curProtoContent = this.getOrAddType(Object.getPrototypeOf(baseProto), baseProto);
  39070. if (!curProtoContent) {
  39071. this.getLevelOf(baseProto);
  39072. }
  39073. return this.getOrAddType(baseProto, type);
  39074. };
  39075. ClassTreeInfo.prototype.getOrAddType = function (baseType, type) {
  39076. // Are we at the level corresponding to the baseType?
  39077. // If so, get or add the level we're looking for
  39078. if (baseType === this._type) {
  39079. for (var _i = 0, _a = this._subClasses; _i < _a.length; _i++) {
  39080. var subType = _a[_i];
  39081. if (subType.type === type) {
  39082. return subType.node;
  39083. }
  39084. }
  39085. var node = new ClassTreeInfo(this, type, this._classContentFactory);
  39086. var info = { type: type, node: node };
  39087. this._subClasses.push(info);
  39088. return info.node;
  39089. }
  39090. // Recurse down to keep looking for the node corresponding to the baseTypeName
  39091. for (var _b = 0, _c = this._subClasses; _b < _c.length; _b++) {
  39092. var subType = _c[_b];
  39093. var info = subType.node.getOrAddType(baseType, type);
  39094. if (info) {
  39095. return info;
  39096. }
  39097. }
  39098. return null;
  39099. };
  39100. ClassTreeInfo.get = function (type) {
  39101. var dic = type["__classTreeInfo"];
  39102. if (!dic) {
  39103. return null;
  39104. }
  39105. return dic.getLevelOf(type);
  39106. };
  39107. ClassTreeInfo.getOrRegister = function (type, classContentFactory) {
  39108. var dic = type["__classTreeInfo"];
  39109. if (!dic) {
  39110. dic = new ClassTreeInfo(null, type, classContentFactory);
  39111. type["__classTreeInfo"] = dic;
  39112. }
  39113. return dic;
  39114. };
  39115. return ClassTreeInfo;
  39116. }());
  39117. BABYLON.ClassTreeInfo = ClassTreeInfo;
  39118. var SmartPropertyPrim = (function () {
  39119. function SmartPropertyPrim() {
  39120. this._flags = 0;
  39121. this._modelKey = null;
  39122. this._instanceDirtyFlags = 0;
  39123. this._levelBoundingInfo = new BABYLON.BoundingInfo2D();
  39124. this.animations = new Array();
  39125. }
  39126. Object.defineProperty(SmartPropertyPrim.prototype, "isDisposed", {
  39127. /**
  39128. * Check if the object is disposed or not.
  39129. * @returns true if the object is dispose, false otherwise.
  39130. */
  39131. get: function () {
  39132. return this._isFlagSet(SmartPropertyPrim.flagIsDisposed);
  39133. },
  39134. enumerable: true,
  39135. configurable: true
  39136. });
  39137. /**
  39138. * Disposable pattern, this method must be overloaded by derived types in order to clean up hardware related resources.
  39139. * @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.
  39140. */
  39141. SmartPropertyPrim.prototype.dispose = function () {
  39142. if (this.isDisposed) {
  39143. return false;
  39144. }
  39145. // Don't set to null, it may upset somebody...
  39146. this.animations.splice(0);
  39147. this._setFlags(SmartPropertyPrim.flagIsDisposed);
  39148. return true;
  39149. };
  39150. /**
  39151. * Returns as a new array populated with the Animatable used by the primitive. Must be overloaded by derived primitives.
  39152. * Look at Sprite2D for more information
  39153. */
  39154. SmartPropertyPrim.prototype.getAnimatables = function () {
  39155. return new Array();
  39156. };
  39157. Object.defineProperty(SmartPropertyPrim.prototype, "modelKey", {
  39158. /**
  39159. * Property giving the Model Key associated to the property.
  39160. * This value is constructed from the type of the primitive and all the name/value of its properties declared with the modelLevelProperty decorator
  39161. * @returns the model key string.
  39162. */
  39163. get: function () {
  39164. var _this = this;
  39165. // No need to compute it?
  39166. if (!this._isFlagSet(SmartPropertyPrim.flagModelDirty) && this._modelKey) {
  39167. return this._modelKey;
  39168. }
  39169. var modelKey = "Class:" + BABYLON.Tools.getClassName(this) + ";";
  39170. var propDic = this.propDic;
  39171. propDic.forEach(function (k, v) {
  39172. if (v.kind === Prim2DPropInfo.PROPKIND_MODEL) {
  39173. var propVal = _this[v.name];
  39174. // 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
  39175. if (propVal && propVal.constructor === Array) {
  39176. var firstVal = propVal[0];
  39177. if (!firstVal) {
  39178. propVal = 0;
  39179. }
  39180. else {
  39181. propVal = BABYLON.Tools.hashCodeFromStream(BABYLON.Tools.arrayOrStringFeeder(propVal));
  39182. }
  39183. }
  39184. modelKey += v.name + ":" + ((propVal != null) ? ((v.typeLevelCompare) ? BABYLON.Tools.getClassName(propVal) : propVal.toString()) : "[null]") + ";";
  39185. }
  39186. });
  39187. this._clearFlags(SmartPropertyPrim.flagModelDirty);
  39188. this._modelKey = modelKey;
  39189. return modelKey;
  39190. },
  39191. enumerable: true,
  39192. configurable: true
  39193. });
  39194. Object.defineProperty(SmartPropertyPrim.prototype, "isDirty", {
  39195. /**
  39196. * States if the Primitive is dirty and should be rendered again next time.
  39197. * @returns true is dirty, false otherwise
  39198. */
  39199. get: function () {
  39200. return (this._instanceDirtyFlags !== 0) || this._areSomeFlagsSet(SmartPropertyPrim.flagModelDirty | SmartPropertyPrim.flagPositioningDirty | SmartPropertyPrim.flagLayoutDirty);
  39201. },
  39202. enumerable: true,
  39203. configurable: true
  39204. });
  39205. Object.defineProperty(SmartPropertyPrim.prototype, "propDic", {
  39206. /**
  39207. * Access the dictionary of properties metadata. Only properties decorated with XXXXLevelProperty are concerned
  39208. * @returns the dictionary, the key is the property name as declared in Javascript, the value is the metadata object
  39209. */
  39210. get: function () {
  39211. if (!this._propInfo) {
  39212. var cti = ClassTreeInfo.get(Object.getPrototypeOf(this));
  39213. if (!cti) {
  39214. throw new Error("Can't access the propDic member in class definition, is this class SmartPropertyPrim based?");
  39215. }
  39216. this._propInfo = cti.fullContent;
  39217. }
  39218. return this._propInfo;
  39219. },
  39220. enumerable: true,
  39221. configurable: true
  39222. });
  39223. SmartPropertyPrim._createPropInfo = function (target, propName, propId, dirtyBoundingInfo, dirtyParentBoundingBox, typeLevelCompare, kind) {
  39224. var dic = ClassTreeInfo.getOrRegister(target, function () { return new Prim2DClassInfo(); });
  39225. var node = dic.getLevelOf(target);
  39226. var propInfo = node.levelContent.get(propId.toString());
  39227. if (propInfo) {
  39228. throw new Error("The ID " + propId + " is already taken by another property declaration named: " + propInfo.name);
  39229. }
  39230. // Create, setup and add the PropInfo object to our prop dictionary
  39231. propInfo = new Prim2DPropInfo();
  39232. propInfo.id = propId;
  39233. propInfo.flagId = Math.pow(2, propId);
  39234. propInfo.kind = kind;
  39235. propInfo.name = propName;
  39236. propInfo.dirtyBoundingInfo = dirtyBoundingInfo;
  39237. propInfo.dirtyParentBoundingInfo = dirtyParentBoundingBox;
  39238. propInfo.typeLevelCompare = typeLevelCompare;
  39239. node.levelContent.add(propName, propInfo);
  39240. return propInfo;
  39241. };
  39242. SmartPropertyPrim._checkUnchanged = function (curValue, newValue) {
  39243. // Nothing to nothing: nothing to do!
  39244. if ((curValue === null && newValue === null) || (curValue === undefined && newValue === undefined)) {
  39245. return true;
  39246. }
  39247. // Check value unchanged
  39248. if ((curValue != null) && (newValue != null)) {
  39249. if (typeof (curValue.equals) == "function") {
  39250. if (curValue.equals(newValue)) {
  39251. return true;
  39252. }
  39253. }
  39254. else {
  39255. if (curValue === newValue) {
  39256. return true;
  39257. }
  39258. }
  39259. }
  39260. return false;
  39261. };
  39262. SmartPropertyPrim.prototype._triggerPropertyChanged = function (propInfo, newValue) {
  39263. if (this.isDisposed) {
  39264. return;
  39265. }
  39266. if (!propInfo) {
  39267. return;
  39268. }
  39269. this._handlePropChanged(undefined, newValue, propInfo.name, propInfo, propInfo.typeLevelCompare);
  39270. };
  39271. SmartPropertyPrim.prototype._boundingBoxDirty = function () {
  39272. this._setFlags(SmartPropertyPrim.flagLevelBoundingInfoDirty);
  39273. // Escalate the dirty flag in the instance hierarchy, stop when a renderable group is found or at the end
  39274. if (this instanceof BABYLON.Prim2DBase) {
  39275. var curprim = this;
  39276. while (curprim) {
  39277. curprim._setFlags(SmartPropertyPrim.flagBoundingInfoDirty);
  39278. if (curprim.isSizeAuto) {
  39279. curprim.onPrimitivePropertyDirty(BABYLON.Prim2DBase.sizeProperty.flagId);
  39280. curprim._setFlags(SmartPropertyPrim.flagPositioningDirty);
  39281. }
  39282. if (curprim instanceof BABYLON.Group2D) {
  39283. if (curprim.isRenderableGroup) {
  39284. break;
  39285. }
  39286. }
  39287. curprim = curprim.parent;
  39288. }
  39289. }
  39290. };
  39291. SmartPropertyPrim.prototype._handlePropChanged = function (curValue, newValue, propName, propInfo, typeLevelCompare) {
  39292. // If the property change also dirty the boundingInfo, update the boundingInfo dirty flags
  39293. if (propInfo.dirtyBoundingInfo) {
  39294. this._boundingBoxDirty();
  39295. }
  39296. else if (propInfo.dirtyParentBoundingInfo) {
  39297. var p = this._parent;
  39298. if (p != null) {
  39299. p._boundingBoxDirty();
  39300. }
  39301. }
  39302. // Trigger property changed
  39303. var info = SmartPropertyPrim.propChangedInfo;
  39304. info.oldValue = curValue;
  39305. info.newValue = newValue;
  39306. info.propertyName = propName;
  39307. var propMask = propInfo.flagId;
  39308. this.propertyChanged.notifyObservers(info, propMask);
  39309. // If the property belong to a group, check if it's a cached one, and dirty its render sprite accordingly
  39310. if (this instanceof BABYLON.Group2D) {
  39311. this.handleGroupChanged(propInfo);
  39312. }
  39313. // Check for parent layout dirty
  39314. if (this instanceof BABYLON.Prim2DBase) {
  39315. var p = this._parent;
  39316. if (p != null && p.layoutEngine && (p.layoutEngine.layoutDirtyOnPropertyChangedMask & propInfo.flagId) !== 0) {
  39317. p._setLayoutDirty();
  39318. }
  39319. }
  39320. // For type level compare, if there's a change of type it's a change of model, otherwise we issue an instance change
  39321. var instanceDirty = false;
  39322. if (typeLevelCompare && curValue != null && newValue != null) {
  39323. var cvProto = curValue.__proto__;
  39324. var nvProto = newValue.__proto__;
  39325. instanceDirty = (cvProto === nvProto);
  39326. }
  39327. // Set the dirty flags
  39328. if (!instanceDirty && (propInfo.kind === Prim2DPropInfo.PROPKIND_MODEL)) {
  39329. if (!this.isDirty) {
  39330. this._setFlags(SmartPropertyPrim.flagModelDirty);
  39331. }
  39332. }
  39333. else if (instanceDirty || (propInfo.kind === Prim2DPropInfo.PROPKIND_INSTANCE) || (propInfo.kind === Prim2DPropInfo.PROPKIND_DYNAMIC)) {
  39334. this.onPrimitivePropertyDirty(propMask);
  39335. }
  39336. };
  39337. SmartPropertyPrim.prototype.onPrimitivePropertyDirty = function (propFlagId) {
  39338. this.onPrimBecomesDirty();
  39339. this._instanceDirtyFlags |= propFlagId;
  39340. };
  39341. SmartPropertyPrim.prototype.handleGroupChanged = function (prop) {
  39342. };
  39343. /**
  39344. * Check if a given set of properties are dirty or not.
  39345. * @param flags a ORed combination of Prim2DPropInfo.flagId values
  39346. * @return true if at least one property is dirty, false if none of them are.
  39347. */
  39348. SmartPropertyPrim.prototype.checkPropertiesDirty = function (flags) {
  39349. return (this._instanceDirtyFlags & flags) !== 0;
  39350. };
  39351. /**
  39352. * Clear a given set of properties.
  39353. * @param flags a ORed combination of Prim2DPropInfo.flagId values
  39354. * @return the new set of property still marked as dirty
  39355. */
  39356. SmartPropertyPrim.prototype.clearPropertiesDirty = function (flags) {
  39357. this._instanceDirtyFlags &= ~flags;
  39358. return this._instanceDirtyFlags;
  39359. };
  39360. SmartPropertyPrim.prototype._resetPropertiesDirty = function () {
  39361. this._instanceDirtyFlags = 0;
  39362. this._clearFlags(SmartPropertyPrim.flagPrimInDirtyList | SmartPropertyPrim.flagNeedRefresh);
  39363. };
  39364. Object.defineProperty(SmartPropertyPrim.prototype, "levelBoundingInfo", {
  39365. /**
  39366. * Retrieve the boundingInfo for this Primitive, computed based on the primitive itself and NOT its children
  39367. */
  39368. get: function () {
  39369. if (this._isFlagSet(SmartPropertyPrim.flagLevelBoundingInfoDirty)) {
  39370. this.updateLevelBoundingInfo();
  39371. this._clearFlags(SmartPropertyPrim.flagLevelBoundingInfoDirty);
  39372. }
  39373. return this._levelBoundingInfo;
  39374. },
  39375. enumerable: true,
  39376. configurable: true
  39377. });
  39378. /**
  39379. * This method must be overridden by a given Primitive implementation to compute its boundingInfo
  39380. */
  39381. SmartPropertyPrim.prototype.updateLevelBoundingInfo = function () {
  39382. };
  39383. /**
  39384. * Property method called when the Primitive becomes dirty
  39385. */
  39386. SmartPropertyPrim.prototype.onPrimBecomesDirty = function () {
  39387. };
  39388. SmartPropertyPrim._hookProperty = function (propId, piStore, typeLevelCompare, dirtyBoundingInfo, dirtyParentBoundingBox, kind) {
  39389. return function (target, propName, descriptor) {
  39390. var propInfo = SmartPropertyPrim._createPropInfo(target, propName, propId, dirtyBoundingInfo, dirtyParentBoundingBox, typeLevelCompare, kind);
  39391. if (piStore) {
  39392. piStore(propInfo);
  39393. }
  39394. var getter = descriptor.get, setter = descriptor.set;
  39395. // Overload the property setter implementation to add our own logic
  39396. descriptor.set = function (val) {
  39397. // check for disposed first, do nothing
  39398. if (this.isDisposed) {
  39399. return;
  39400. }
  39401. var curVal = getter.call(this);
  39402. if (SmartPropertyPrim._checkUnchanged(curVal, val)) {
  39403. return;
  39404. }
  39405. // Cast the object we're working one
  39406. var prim = this;
  39407. // Change the value
  39408. setter.call(this, val);
  39409. // Notify change, dirty flags update
  39410. prim._handlePropChanged(curVal, val, propName, propInfo, typeLevelCompare);
  39411. };
  39412. };
  39413. };
  39414. /**
  39415. * Add an externally attached data from its key.
  39416. * This method call will fail and return false, if such key already exists.
  39417. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  39418. * @param key the unique key that identifies the data
  39419. * @param data the data object to associate to the key for this Engine instance
  39420. * @return true if no such key were already present and the data was added successfully, false otherwise
  39421. */
  39422. SmartPropertyPrim.prototype.addExternalData = function (key, data) {
  39423. if (!this._externalData) {
  39424. this._externalData = new BABYLON.StringDictionary();
  39425. }
  39426. return this._externalData.add(key, data);
  39427. };
  39428. /**
  39429. * Get an externally attached data from its key
  39430. * @param key the unique key that identifies the data
  39431. * @return the associated data, if present (can be null), or undefined if not present
  39432. */
  39433. SmartPropertyPrim.prototype.getExternalData = function (key) {
  39434. if (!this._externalData) {
  39435. return null;
  39436. }
  39437. return this._externalData.get(key);
  39438. };
  39439. /**
  39440. * Get an externally attached data from its key, create it using a factory if it's not already present
  39441. * @param key the unique key that identifies the data
  39442. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  39443. * @return the associated data, can be null if the factory returned null.
  39444. */
  39445. SmartPropertyPrim.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  39446. if (!this._externalData) {
  39447. this._externalData = new BABYLON.StringDictionary();
  39448. }
  39449. return this._externalData.getOrAddWithFactory(key, factory);
  39450. };
  39451. /**
  39452. * Remove an externally attached data from the Engine instance
  39453. * @param key the unique key that identifies the data
  39454. * @return true if the data was successfully removed, false if it doesn't exist
  39455. */
  39456. SmartPropertyPrim.prototype.removeExternalData = function (key) {
  39457. if (!this._externalData) {
  39458. return false;
  39459. }
  39460. return this._externalData.remove(key);
  39461. };
  39462. /**
  39463. * Check if a given flag is set
  39464. * @param flag the flag value
  39465. * @return true if set, false otherwise
  39466. */
  39467. SmartPropertyPrim.prototype._isFlagSet = function (flag) {
  39468. return (this._flags & flag) !== 0;
  39469. };
  39470. /**
  39471. * Check if all given flags are set
  39472. * @param flags the flags ORed
  39473. * @return true if all the flags are set, false otherwise
  39474. */
  39475. SmartPropertyPrim.prototype._areAllFlagsSet = function (flags) {
  39476. return (this._flags & flags) === flags;
  39477. };
  39478. /**
  39479. * Check if at least one flag of the given flags is set
  39480. * @param flags the flags ORed
  39481. * @return true if at least one flag is set, false otherwise
  39482. */
  39483. SmartPropertyPrim.prototype._areSomeFlagsSet = function (flags) {
  39484. return (this._flags & flags) !== 0;
  39485. };
  39486. /**
  39487. * Clear the given flags
  39488. * @param flags the flags to clear
  39489. */
  39490. SmartPropertyPrim.prototype._clearFlags = function (flags) {
  39491. this._flags &= ~flags;
  39492. };
  39493. /**
  39494. * Set the given flags to true state
  39495. * @param flags the flags ORed to set
  39496. * @return the flags state before this call
  39497. */
  39498. SmartPropertyPrim.prototype._setFlags = function (flags) {
  39499. var cur = this._flags;
  39500. this._flags |= flags;
  39501. return cur;
  39502. };
  39503. /**
  39504. * Change the state of the given flags
  39505. * @param flags the flags ORed to change
  39506. * @param state true to set them, false to clear them
  39507. */
  39508. SmartPropertyPrim.prototype._changeFlags = function (flags, state) {
  39509. if (state) {
  39510. this._flags |= flags;
  39511. }
  39512. else {
  39513. this._flags &= ~flags;
  39514. }
  39515. };
  39516. SmartPropertyPrim.propChangedInfo = new PropertyChangedInfo();
  39517. SmartPropertyPrim.flagIsDisposed = 0x0000001; // set if the object is already disposed
  39518. SmartPropertyPrim.flagLevelBoundingInfoDirty = 0x0000002; // set if the primitive's level bounding box (not including children) is dirty
  39519. SmartPropertyPrim.flagModelDirty = 0x0000004; // set if the model must be changed
  39520. SmartPropertyPrim.flagLayoutDirty = 0x0000008; // set if the layout must be computed
  39521. SmartPropertyPrim.flagLevelVisible = 0x0000010; // set if the primitive is set as visible for its level only
  39522. SmartPropertyPrim.flagBoundingInfoDirty = 0x0000020; // set if the primitive's overall bounding box (including children) is dirty
  39523. SmartPropertyPrim.flagIsPickable = 0x0000040; // set if the primitive can be picked during interaction
  39524. SmartPropertyPrim.flagIsVisible = 0x0000080; // set if the primitive is concretely visible (use the levelVisible of parents)
  39525. SmartPropertyPrim.flagVisibilityChanged = 0x0000100; // set if there was a transition between visible/hidden status
  39526. SmartPropertyPrim.flagPositioningDirty = 0x0000200; // set if the primitive positioning must be computed
  39527. SmartPropertyPrim.flagTrackedGroup = 0x0000400; // set if the group2D is tracking a scene node
  39528. SmartPropertyPrim.flagWorldCacheChanged = 0x0000800; // set if the cached bitmap of a world space canvas changed
  39529. SmartPropertyPrim.flagChildrenFlatZOrder = 0x0001000; // set if all the children (direct and indirect) will share the same Z-Order
  39530. SmartPropertyPrim.flagZOrderDirty = 0x0002000; // set if the Z-Order for this prim and its children must be recomputed
  39531. SmartPropertyPrim.flagActualOpacityDirty = 0x0004000; // set if the actualOpactity should be recomputed
  39532. SmartPropertyPrim.flagPrimInDirtyList = 0x0008000; // set if the primitive is in the primDirtyList
  39533. SmartPropertyPrim.flagIsContainer = 0x0010000; // set if the primitive is a container
  39534. SmartPropertyPrim.flagNeedRefresh = 0x0020000; // set if the primitive wasn't successful at refresh
  39535. SmartPropertyPrim.flagActualScaleDirty = 0x0040000; // set if the actualScale property needs to be recomputed
  39536. SmartPropertyPrim.flagDontInheritParentScale = 0x0080000; // set if the actualScale must not use its parent's scale to be computed
  39537. SmartPropertyPrim.flagGlobalTransformDirty = 0x0100000; // set if the global transform must be recomputed due to a local transform change
  39538. SmartPropertyPrim.flagLayoutBoundingInfoDirty = 0x0100000; // set if the layout bounding info is dirty
  39539. SmartPropertyPrim = __decorate([
  39540. BABYLON.className("SmartPropertyPrim")
  39541. ], SmartPropertyPrim);
  39542. return SmartPropertyPrim;
  39543. }());
  39544. BABYLON.SmartPropertyPrim = SmartPropertyPrim;
  39545. function modelLevelProperty(propId, piStore, typeLevelCompare, dirtyBoundingInfo, dirtyParentBoundingBox) {
  39546. if (typeLevelCompare === void 0) { typeLevelCompare = false; }
  39547. if (dirtyBoundingInfo === void 0) { dirtyBoundingInfo = false; }
  39548. if (dirtyParentBoundingBox === void 0) { dirtyParentBoundingBox = false; }
  39549. return SmartPropertyPrim._hookProperty(propId, piStore, typeLevelCompare, dirtyBoundingInfo, dirtyParentBoundingBox, Prim2DPropInfo.PROPKIND_MODEL);
  39550. }
  39551. BABYLON.modelLevelProperty = modelLevelProperty;
  39552. function instanceLevelProperty(propId, piStore, typeLevelCompare, dirtyBoundingInfo, dirtyParentBoundingBox) {
  39553. if (typeLevelCompare === void 0) { typeLevelCompare = false; }
  39554. if (dirtyBoundingInfo === void 0) { dirtyBoundingInfo = false; }
  39555. if (dirtyParentBoundingBox === void 0) { dirtyParentBoundingBox = false; }
  39556. return SmartPropertyPrim._hookProperty(propId, piStore, typeLevelCompare, dirtyBoundingInfo, dirtyParentBoundingBox, Prim2DPropInfo.PROPKIND_INSTANCE);
  39557. }
  39558. BABYLON.instanceLevelProperty = instanceLevelProperty;
  39559. function dynamicLevelProperty(propId, piStore, typeLevelCompare, dirtyBoundingInfo, dirtyParentBoundingBox) {
  39560. if (typeLevelCompare === void 0) { typeLevelCompare = false; }
  39561. if (dirtyBoundingInfo === void 0) { dirtyBoundingInfo = false; }
  39562. if (dirtyParentBoundingBox === void 0) { dirtyParentBoundingBox = false; }
  39563. return SmartPropertyPrim._hookProperty(propId, piStore, typeLevelCompare, dirtyBoundingInfo, dirtyParentBoundingBox, Prim2DPropInfo.PROPKIND_DYNAMIC);
  39564. }
  39565. BABYLON.dynamicLevelProperty = dynamicLevelProperty;
  39566. })(BABYLON || (BABYLON = {}));
  39567. var BABYLON;
  39568. (function (BABYLON) {
  39569. var PrepareRender2DContext = (function () {
  39570. function PrepareRender2DContext() {
  39571. this.forceRefreshPrimitive = false;
  39572. }
  39573. return PrepareRender2DContext;
  39574. }());
  39575. BABYLON.PrepareRender2DContext = PrepareRender2DContext;
  39576. var Render2DContext = (function () {
  39577. function Render2DContext(renderMode) {
  39578. this._renderMode = renderMode;
  39579. this.useInstancing = false;
  39580. this.groupInfoPartData = null;
  39581. this.partDataStartIndex = this.partDataEndIndex = null;
  39582. this.instancedBuffers = null;
  39583. }
  39584. Object.defineProperty(Render2DContext.prototype, "renderMode", {
  39585. /**
  39586. * Define which render Mode should be used to render the primitive: one of Render2DContext.RenderModeXxxx property
  39587. */
  39588. get: function () {
  39589. return this._renderMode;
  39590. },
  39591. enumerable: true,
  39592. configurable: true
  39593. });
  39594. Object.defineProperty(Render2DContext, "RenderModeOpaque", {
  39595. /**
  39596. * The set of primitives to render is opaque.
  39597. * This is the first rendering pass. All Opaque primitives are rendered. Depth Compare and Write are both enabled.
  39598. */
  39599. get: function () {
  39600. return Render2DContext._renderModeOpaque;
  39601. },
  39602. enumerable: true,
  39603. configurable: true
  39604. });
  39605. Object.defineProperty(Render2DContext, "RenderModeAlphaTest", {
  39606. /**
  39607. * The set of primitives to render is using Alpha Test (aka masking).
  39608. * 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.
  39609. */
  39610. get: function () {
  39611. return Render2DContext._renderModeAlphaTest;
  39612. },
  39613. enumerable: true,
  39614. configurable: true
  39615. });
  39616. Object.defineProperty(Render2DContext, "RenderModeTransparent", {
  39617. /**
  39618. * The set of primitives to render is transparent.
  39619. * 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.
  39620. */
  39621. get: function () {
  39622. return Render2DContext._renderModeTransparent;
  39623. },
  39624. enumerable: true,
  39625. configurable: true
  39626. });
  39627. Render2DContext._renderModeOpaque = 1;
  39628. Render2DContext._renderModeAlphaTest = 2;
  39629. Render2DContext._renderModeTransparent = 3;
  39630. return Render2DContext;
  39631. }());
  39632. BABYLON.Render2DContext = Render2DContext;
  39633. /**
  39634. * This class store information for the pointerEventObservable Observable.
  39635. * 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.
  39636. */
  39637. var PrimitivePointerInfo = (function () {
  39638. function PrimitivePointerInfo() {
  39639. this.primitivePointerPos = BABYLON.Vector2.Zero();
  39640. this.tilt = BABYLON.Vector2.Zero();
  39641. this.cancelBubble = false;
  39642. }
  39643. Object.defineProperty(PrimitivePointerInfo, "PointerOver", {
  39644. // 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.
  39645. /**
  39646. * This event type is raised when a pointing device is moved into the hit test boundaries of a primitive.
  39647. * Bubbles: yes
  39648. */
  39649. get: function () {
  39650. return PrimitivePointerInfo._pointerOver;
  39651. },
  39652. enumerable: true,
  39653. configurable: true
  39654. });
  39655. Object.defineProperty(PrimitivePointerInfo, "PointerEnter", {
  39656. /**
  39657. * This event type is raised when a pointing device is moved into the hit test boundaries of a primitive or one of its descendants.
  39658. * Bubbles: no
  39659. */
  39660. get: function () {
  39661. return PrimitivePointerInfo._pointerEnter;
  39662. },
  39663. enumerable: true,
  39664. configurable: true
  39665. });
  39666. Object.defineProperty(PrimitivePointerInfo, "PointerDown", {
  39667. /**
  39668. * 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.
  39669. * Bubbles: yes
  39670. */
  39671. get: function () {
  39672. return PrimitivePointerInfo._pointerDown;
  39673. },
  39674. enumerable: true,
  39675. configurable: true
  39676. });
  39677. Object.defineProperty(PrimitivePointerInfo, "PointerMouseWheel", {
  39678. /**
  39679. * This event type is raised when the pointer is a mouse and it's wheel is rolling
  39680. * Bubbles: yes
  39681. */
  39682. get: function () {
  39683. return PrimitivePointerInfo._pointerMouseWheel;
  39684. },
  39685. enumerable: true,
  39686. configurable: true
  39687. });
  39688. Object.defineProperty(PrimitivePointerInfo, "PointerMove", {
  39689. /**
  39690. * 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.
  39691. * Bubbles: yes
  39692. */
  39693. get: function () {
  39694. return PrimitivePointerInfo._pointerMove;
  39695. },
  39696. enumerable: true,
  39697. configurable: true
  39698. });
  39699. Object.defineProperty(PrimitivePointerInfo, "PointerUp", {
  39700. /**
  39701. * 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.
  39702. * Bubbles: yes
  39703. */
  39704. get: function () {
  39705. return PrimitivePointerInfo._pointerUp;
  39706. },
  39707. enumerable: true,
  39708. configurable: true
  39709. });
  39710. Object.defineProperty(PrimitivePointerInfo, "PointerOut", {
  39711. /**
  39712. * This event type is raised when a pointing device is moved out of the hit test the boundaries of a primitive.
  39713. * Bubbles: yes
  39714. */
  39715. get: function () {
  39716. return PrimitivePointerInfo._pointerOut;
  39717. },
  39718. enumerable: true,
  39719. configurable: true
  39720. });
  39721. Object.defineProperty(PrimitivePointerInfo, "PointerLeave", {
  39722. /**
  39723. * This event type is raised when a pointing device is moved out of the hit test boundaries of a primitive and all its descendants.
  39724. * Bubbles: no
  39725. */
  39726. get: function () {
  39727. return PrimitivePointerInfo._pointerLeave;
  39728. },
  39729. enumerable: true,
  39730. configurable: true
  39731. });
  39732. Object.defineProperty(PrimitivePointerInfo, "PointerGotCapture", {
  39733. /**
  39734. * 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.
  39735. * Bubbles: yes
  39736. */
  39737. get: function () {
  39738. return PrimitivePointerInfo._pointerGotCapture;
  39739. },
  39740. enumerable: true,
  39741. configurable: true
  39742. });
  39743. Object.defineProperty(PrimitivePointerInfo, "PointerLostCapture", {
  39744. /**
  39745. * This event type is raised after pointer capture is released for a pointer.
  39746. * Bubbles: yes
  39747. */
  39748. get: function () {
  39749. return PrimitivePointerInfo._pointerLostCapture;
  39750. },
  39751. enumerable: true,
  39752. configurable: true
  39753. });
  39754. Object.defineProperty(PrimitivePointerInfo, "MouseWheelPrecision", {
  39755. get: function () {
  39756. return PrimitivePointerInfo._mouseWheelPrecision;
  39757. },
  39758. enumerable: true,
  39759. configurable: true
  39760. });
  39761. PrimitivePointerInfo.prototype.updateRelatedTarget = function (prim, primPointerPos) {
  39762. this.relatedTarget = prim;
  39763. this.relatedTargetPointerPos = primPointerPos;
  39764. };
  39765. PrimitivePointerInfo.getEventTypeName = function (mask) {
  39766. switch (mask) {
  39767. case PrimitivePointerInfo.PointerOver: return "PointerOver";
  39768. case PrimitivePointerInfo.PointerEnter: return "PointerEnter";
  39769. case PrimitivePointerInfo.PointerDown: return "PointerDown";
  39770. case PrimitivePointerInfo.PointerMouseWheel: return "PointerMouseWheel";
  39771. case PrimitivePointerInfo.PointerMove: return "PointerMove";
  39772. case PrimitivePointerInfo.PointerUp: return "PointerUp";
  39773. case PrimitivePointerInfo.PointerOut: return "PointerOut";
  39774. case PrimitivePointerInfo.PointerLeave: return "PointerLeave";
  39775. case PrimitivePointerInfo.PointerGotCapture: return "PointerGotCapture";
  39776. case PrimitivePointerInfo.PointerLostCapture: return "PointerLostCapture";
  39777. }
  39778. };
  39779. PrimitivePointerInfo._pointerOver = 0x0001;
  39780. PrimitivePointerInfo._pointerEnter = 0x0002;
  39781. PrimitivePointerInfo._pointerDown = 0x0004;
  39782. PrimitivePointerInfo._pointerMouseWheel = 0x0008;
  39783. PrimitivePointerInfo._pointerMove = 0x0010;
  39784. PrimitivePointerInfo._pointerUp = 0x0020;
  39785. PrimitivePointerInfo._pointerOut = 0x0040;
  39786. PrimitivePointerInfo._pointerLeave = 0x0080;
  39787. PrimitivePointerInfo._pointerGotCapture = 0x0100;
  39788. PrimitivePointerInfo._pointerLostCapture = 0x0200;
  39789. PrimitivePointerInfo._mouseWheelPrecision = 3.0;
  39790. return PrimitivePointerInfo;
  39791. }());
  39792. BABYLON.PrimitivePointerInfo = PrimitivePointerInfo;
  39793. /**
  39794. * Defines the horizontal and vertical alignment information for a Primitive.
  39795. */
  39796. var PrimitiveAlignment = (function () {
  39797. function PrimitiveAlignment(changeCallback) {
  39798. this._changedCallback = changeCallback;
  39799. this._horizontal = PrimitiveAlignment.AlignLeft;
  39800. this._vertical = PrimitiveAlignment.AlignBottom;
  39801. }
  39802. Object.defineProperty(PrimitiveAlignment, "AlignLeft", {
  39803. /**
  39804. * Alignment is made relative to the left edge of the Primitive. Valid for horizontal alignment only.
  39805. */
  39806. get: function () { return PrimitiveAlignment._AlignLeft; },
  39807. enumerable: true,
  39808. configurable: true
  39809. });
  39810. Object.defineProperty(PrimitiveAlignment, "AlignTop", {
  39811. /**
  39812. * Alignment is made relative to the top edge of the Primitive. Valid for vertical alignment only.
  39813. */
  39814. get: function () { return PrimitiveAlignment._AlignTop; },
  39815. enumerable: true,
  39816. configurable: true
  39817. });
  39818. Object.defineProperty(PrimitiveAlignment, "AlignRight", {
  39819. /**
  39820. * Alignment is made relative to the right edge of the Primitive. Valid for horizontal alignment only.
  39821. */
  39822. get: function () { return PrimitiveAlignment._AlignRight; },
  39823. enumerable: true,
  39824. configurable: true
  39825. });
  39826. Object.defineProperty(PrimitiveAlignment, "AlignBottom", {
  39827. /**
  39828. * Alignment is made relative to the bottom edge of the Primitive. Valid for vertical alignment only.
  39829. */
  39830. get: function () { return PrimitiveAlignment._AlignBottom; },
  39831. enumerable: true,
  39832. configurable: true
  39833. });
  39834. Object.defineProperty(PrimitiveAlignment, "AlignCenter", {
  39835. /**
  39836. * Alignment is made to center the content from equal distance to the opposite edges of the Primitive
  39837. */
  39838. get: function () { return PrimitiveAlignment._AlignCenter; },
  39839. enumerable: true,
  39840. configurable: true
  39841. });
  39842. Object.defineProperty(PrimitiveAlignment, "AlignStretch", {
  39843. /**
  39844. * The content is stretched toward the opposite edges of the Primitive
  39845. */
  39846. get: function () { return PrimitiveAlignment._AlignStretch; },
  39847. enumerable: true,
  39848. configurable: true
  39849. });
  39850. Object.defineProperty(PrimitiveAlignment.prototype, "horizontal", {
  39851. /**
  39852. * Get/set the horizontal alignment. Use one of the AlignXXX static properties of this class
  39853. */
  39854. get: function () {
  39855. return this._horizontal;
  39856. },
  39857. set: function (value) {
  39858. if (this._horizontal === value) {
  39859. return;
  39860. }
  39861. this._horizontal = value;
  39862. this._changedCallback();
  39863. },
  39864. enumerable: true,
  39865. configurable: true
  39866. });
  39867. Object.defineProperty(PrimitiveAlignment.prototype, "vertical", {
  39868. /**
  39869. * Get/set the vertical alignment. Use one of the AlignXXX static properties of this class
  39870. */
  39871. get: function () {
  39872. return this._vertical;
  39873. },
  39874. set: function (value) {
  39875. if (this._vertical === value) {
  39876. return;
  39877. }
  39878. this._vertical = value;
  39879. this._changedCallback();
  39880. },
  39881. enumerable: true,
  39882. configurable: true
  39883. });
  39884. /**
  39885. * Set the horizontal alignment from a string value.
  39886. * @param text can be either: 'left','right','center','stretch'
  39887. */
  39888. PrimitiveAlignment.prototype.setHorizontal = function (text) {
  39889. var v = text.trim().toLocaleLowerCase();
  39890. switch (v) {
  39891. case "left":
  39892. this.horizontal = PrimitiveAlignment.AlignLeft;
  39893. return;
  39894. case "right":
  39895. this.horizontal = PrimitiveAlignment.AlignRight;
  39896. return;
  39897. case "center":
  39898. this.horizontal = PrimitiveAlignment.AlignCenter;
  39899. return;
  39900. case "stretch":
  39901. this.horizontal = PrimitiveAlignment.AlignStretch;
  39902. return;
  39903. }
  39904. };
  39905. /**
  39906. * Set the vertical alignment from a string value.
  39907. * @param text can be either: 'top','bottom','center','stretch'
  39908. */
  39909. PrimitiveAlignment.prototype.setVertical = function (text) {
  39910. var v = text.trim().toLocaleLowerCase();
  39911. switch (v) {
  39912. case "top":
  39913. this.vertical = PrimitiveAlignment.AlignTop;
  39914. return;
  39915. case "bottom":
  39916. this.vertical = PrimitiveAlignment.AlignBottom;
  39917. return;
  39918. case "center":
  39919. this.vertical = PrimitiveAlignment.AlignCenter;
  39920. return;
  39921. case "stretch":
  39922. this.vertical = PrimitiveAlignment.AlignStretch;
  39923. return;
  39924. }
  39925. };
  39926. /**
  39927. * Set the horizontal and or vertical alignments from a string value.
  39928. * @param text can be: [<h:|horizontal:><left|right|center|stretch>], [<v:|vertical:><top|bottom|center|stretch>]
  39929. */
  39930. PrimitiveAlignment.prototype.fromString = function (value) {
  39931. var m = value.trim().split(",");
  39932. for (var _i = 0, m_1 = m; _i < m_1.length; _i++) {
  39933. var v = m_1[_i];
  39934. v = v.toLocaleLowerCase().trim();
  39935. // Horizontal
  39936. var i = v.indexOf("h:");
  39937. if (i === -1) {
  39938. i = v.indexOf("horizontal:");
  39939. }
  39940. if (i !== -1) {
  39941. v = v.substr(v.indexOf(":") + 1);
  39942. this.setHorizontal(v);
  39943. continue;
  39944. }
  39945. // Vertical
  39946. i = v.indexOf("v:");
  39947. if (i === -1) {
  39948. i = v.indexOf("vertical:");
  39949. }
  39950. if (i !== -1) {
  39951. v = v.substr(v.indexOf(":") + 1);
  39952. this.setVertical(v);
  39953. continue;
  39954. }
  39955. }
  39956. };
  39957. PrimitiveAlignment._AlignLeft = 1;
  39958. PrimitiveAlignment._AlignTop = 1; // Same as left
  39959. PrimitiveAlignment._AlignRight = 2;
  39960. PrimitiveAlignment._AlignBottom = 2; // Same as right
  39961. PrimitiveAlignment._AlignCenter = 3;
  39962. PrimitiveAlignment._AlignStretch = 4;
  39963. return PrimitiveAlignment;
  39964. }());
  39965. BABYLON.PrimitiveAlignment = PrimitiveAlignment;
  39966. /**
  39967. * Stores information about a Primitive that was intersected
  39968. */
  39969. var PrimitiveIntersectedInfo = (function () {
  39970. function PrimitiveIntersectedInfo(prim, intersectionLocation) {
  39971. this.prim = prim;
  39972. this.intersectionLocation = intersectionLocation;
  39973. }
  39974. return PrimitiveIntersectedInfo;
  39975. }());
  39976. BABYLON.PrimitiveIntersectedInfo = PrimitiveIntersectedInfo;
  39977. /**
  39978. * Define a thickness toward every edges of a Primitive to allow margin and padding.
  39979. * The thickness can be expressed as pixels, percentages, inherit the value of the parent primitive or be auto.
  39980. */
  39981. var PrimitiveThickness = (function () {
  39982. function PrimitiveThickness(parentAccess, changedCallback) {
  39983. this._parentAccess = parentAccess;
  39984. this._changedCallback = changedCallback;
  39985. this._pixels = new Array(4);
  39986. this._percentages = new Array(4);
  39987. this._setType(0, PrimitiveThickness.Auto);
  39988. this._setType(1, PrimitiveThickness.Auto);
  39989. this._setType(2, PrimitiveThickness.Auto);
  39990. this._setType(3, PrimitiveThickness.Auto);
  39991. this._pixels[0] = 0;
  39992. this._pixels[1] = 0;
  39993. this._pixels[2] = 0;
  39994. this._pixels[3] = 0;
  39995. }
  39996. /**
  39997. * Set the thickness from a string value
  39998. * @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.
  39999. * Values are: 'auto', 'inherit', 'XX%' for percentage, 'XXpx' or 'XX' for pixels.
  40000. */
  40001. PrimitiveThickness.prototype.fromString = function (thickness) {
  40002. this._clear();
  40003. var m = thickness.trim().split(",");
  40004. // Special case, one value to apply to all edges
  40005. if (m.length === 1 && thickness.indexOf(":") === -1) {
  40006. this._setStringValue(m[0], 0, false);
  40007. this._setStringValue(m[0], 1, false);
  40008. this._setStringValue(m[0], 2, false);
  40009. this._setStringValue(m[0], 3, false);
  40010. this._changedCallback();
  40011. return;
  40012. }
  40013. var res = false;
  40014. for (var _i = 0, m_2 = m; _i < m_2.length; _i++) {
  40015. var cm = m_2[_i];
  40016. res = this._extractString(cm, false) || res;
  40017. }
  40018. if (!res) {
  40019. throw new Error("Can't parse the string to create a PrimitiveMargin object, format must be: 'top: <value>, left:<value>, right:<value>, bottom:<value>");
  40020. }
  40021. // Check the margin that weren't set and set them in auto
  40022. if ((this._flags & 0x000F) === 0)
  40023. this._flags |= PrimitiveThickness.Pixel << 0;
  40024. if ((this._flags & 0x00F0) === 0)
  40025. this._flags |= PrimitiveThickness.Pixel << 4;
  40026. if ((this._flags & 0x0F00) === 0)
  40027. this._flags |= PrimitiveThickness.Pixel << 8;
  40028. if ((this._flags & 0xF000) === 0)
  40029. this._flags |= PrimitiveThickness.Pixel << 12;
  40030. this._changedCallback();
  40031. };
  40032. /**
  40033. * Set the thickness from multiple string
  40034. * Possible values are: 'auto', 'inherit', 'XX%' for percentage, 'XXpx' or 'XX' for pixels.
  40035. * @param top the top thickness to set
  40036. * @param left the left thickness to set
  40037. * @param right the right thickness to set
  40038. * @param bottom the bottom thickness to set
  40039. */
  40040. PrimitiveThickness.prototype.fromStrings = function (top, left, right, bottom) {
  40041. this._clear();
  40042. this._setStringValue(top, 0, false);
  40043. this._setStringValue(left, 1, false);
  40044. this._setStringValue(right, 2, false);
  40045. this._setStringValue(bottom, 3, false);
  40046. this._changedCallback();
  40047. return this;
  40048. };
  40049. /**
  40050. * Set the thickness from pixel values
  40051. * @param top the top thickness in pixels to set
  40052. * @param left the left thickness in pixels to set
  40053. * @param right the right thickness in pixels to set
  40054. * @param bottom the bottom thickness in pixels to set
  40055. */
  40056. PrimitiveThickness.prototype.fromPixels = function (top, left, right, bottom) {
  40057. this._clear();
  40058. this._pixels[0] = top;
  40059. this._pixels[1] = left;
  40060. this._pixels[2] = right;
  40061. this._pixels[3] = bottom;
  40062. this._changedCallback();
  40063. return this;
  40064. };
  40065. /**
  40066. * Apply the same pixel value to all edges
  40067. * @param margin the value to set, in pixels.
  40068. */
  40069. PrimitiveThickness.prototype.fromUniformPixels = function (margin) {
  40070. this._clear();
  40071. this._pixels[0] = margin;
  40072. this._pixels[1] = margin;
  40073. this._pixels[2] = margin;
  40074. this._pixels[3] = margin;
  40075. this._changedCallback();
  40076. return this;
  40077. };
  40078. /**
  40079. * Set all edges in auto
  40080. */
  40081. PrimitiveThickness.prototype.auto = function () {
  40082. this._clear();
  40083. this._flags = (PrimitiveThickness.Auto << 0) | (PrimitiveThickness.Auto << 4) | (PrimitiveThickness.Auto << 8) | (PrimitiveThickness.Auto << 12);
  40084. this._pixels[0] = 0;
  40085. this._pixels[1] = 0;
  40086. this._pixels[2] = 0;
  40087. this._pixels[3] = 0;
  40088. this._changedCallback();
  40089. return this;
  40090. };
  40091. PrimitiveThickness.prototype._clear = function () {
  40092. this._flags = 0;
  40093. this._pixels[0] = 0;
  40094. this._pixels[1] = 0;
  40095. this._pixels[2] = 0;
  40096. this._pixels[3] = 0;
  40097. this._percentages[0] = null;
  40098. this._percentages[1] = null;
  40099. this._percentages[2] = null;
  40100. this._percentages[3] = null;
  40101. };
  40102. PrimitiveThickness.prototype._extractString = function (value, emitChanged) {
  40103. var v = value.trim().toLocaleLowerCase();
  40104. if (v.indexOf("top:") === 0) {
  40105. v = v.substr(4).trim();
  40106. return this._setStringValue(v, 0, emitChanged);
  40107. }
  40108. if (v.indexOf("left:") === 0) {
  40109. v = v.substr(5).trim();
  40110. return this._setStringValue(v, 1, emitChanged);
  40111. }
  40112. if (v.indexOf("right:") === 0) {
  40113. v = v.substr(6).trim();
  40114. return this._setStringValue(v, 2, emitChanged);
  40115. }
  40116. if (v.indexOf("bottom:") === 0) {
  40117. v = v.substr(7).trim();
  40118. return this._setStringValue(v, 3, emitChanged);
  40119. }
  40120. return false;
  40121. };
  40122. PrimitiveThickness.prototype._setStringValue = function (value, index, emitChanged) {
  40123. // Check for auto
  40124. var v = value.trim().toLocaleLowerCase();
  40125. if (v === "auto") {
  40126. if (this._isType(index, PrimitiveThickness.Auto)) {
  40127. return true;
  40128. }
  40129. this._setType(index, PrimitiveThickness.Auto);
  40130. this._pixels[index] = 0;
  40131. if (emitChanged) {
  40132. this._changedCallback();
  40133. }
  40134. }
  40135. else if (v === "inherit") {
  40136. if (this._isType(index, PrimitiveThickness.Inherit)) {
  40137. return true;
  40138. }
  40139. this._setType(index, PrimitiveThickness.Inherit);
  40140. this._pixels[index] = null;
  40141. if (emitChanged) {
  40142. this._changedCallback();
  40143. }
  40144. }
  40145. else {
  40146. var pI = v.indexOf("%");
  40147. // Check for percentage
  40148. if (pI !== -1) {
  40149. var n_1 = v.substr(0, pI);
  40150. var number_1 = Math.round(Number(n_1)) / 100; // Normalize the percentage to [0;1] with a 0.01 precision
  40151. if (this._isType(index, PrimitiveThickness.Percentage) && (this._percentages[index] === number_1)) {
  40152. return true;
  40153. }
  40154. this._setType(index, PrimitiveThickness.Percentage);
  40155. if (isNaN(number_1)) {
  40156. return false;
  40157. }
  40158. this._percentages[index] = number_1;
  40159. if (emitChanged) {
  40160. this._changedCallback();
  40161. }
  40162. return true;
  40163. }
  40164. // Check for pixel
  40165. var n = void 0;
  40166. pI = v.indexOf("px");
  40167. if (pI !== -1) {
  40168. n = v.substr(0, pI).trim();
  40169. }
  40170. else {
  40171. n = v;
  40172. }
  40173. var number = Number(n);
  40174. if (this._isType(index, PrimitiveThickness.Pixel) && (this._pixels[index] === number)) {
  40175. return true;
  40176. }
  40177. if (isNaN(number)) {
  40178. return false;
  40179. }
  40180. this._pixels[index] = number;
  40181. this._setType(index, PrimitiveThickness.Pixel);
  40182. if (emitChanged) {
  40183. this._changedCallback();
  40184. }
  40185. return true;
  40186. }
  40187. };
  40188. PrimitiveThickness.prototype._setPixels = function (value, index, emitChanged) {
  40189. // 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
  40190. value = Math.round(value);
  40191. if (this._isType(index, PrimitiveThickness.Pixel) && this._pixels[index] === value) {
  40192. return;
  40193. }
  40194. this._setType(index, PrimitiveThickness.Pixel);
  40195. this._pixels[index] = value;
  40196. if (emitChanged) {
  40197. this._changedCallback();
  40198. }
  40199. };
  40200. PrimitiveThickness.prototype._setPercentage = function (value, index, emitChanged) {
  40201. // Clip Value to bounds
  40202. value = Math.min(1, value);
  40203. value = Math.max(0, value);
  40204. value = Math.round(value * 100) / 100; // 0.01 precision
  40205. if (this._isType(index, PrimitiveThickness.Percentage) && this._percentages[index] === value) {
  40206. return;
  40207. }
  40208. this._setType(index, PrimitiveThickness.Percentage);
  40209. this._percentages[index] = value;
  40210. if (emitChanged) {
  40211. this._changedCallback();
  40212. }
  40213. };
  40214. PrimitiveThickness.prototype._getStringValue = function (index) {
  40215. var f = (this._flags >> (index * 4)) & 0xF;
  40216. switch (f) {
  40217. case PrimitiveThickness.Auto:
  40218. return "auto";
  40219. case PrimitiveThickness.Pixel:
  40220. return this._pixels[index] + "px";
  40221. case PrimitiveThickness.Percentage:
  40222. return this._percentages[index] * 100 + "%";
  40223. case PrimitiveThickness.Inherit:
  40224. return "inherit";
  40225. }
  40226. return "";
  40227. };
  40228. PrimitiveThickness.prototype._isType = function (index, type) {
  40229. var f = (this._flags >> (index * 4)) & 0xF;
  40230. return f === type;
  40231. };
  40232. PrimitiveThickness.prototype._getType = function (index, processInherit) {
  40233. var t = (this._flags >> (index * 4)) & 0xF;
  40234. if (processInherit && (t === PrimitiveThickness.Inherit)) {
  40235. var p = this._parentAccess();
  40236. if (p) {
  40237. return p._getType(index, true);
  40238. }
  40239. return PrimitiveThickness.Auto;
  40240. }
  40241. return t;
  40242. };
  40243. PrimitiveThickness.prototype._setType = function (index, type) {
  40244. this._flags &= ~(0xF << (index * 4));
  40245. this._flags |= type << (index * 4);
  40246. };
  40247. PrimitiveThickness.prototype.setTop = function (value) {
  40248. if (typeof value === "string") {
  40249. this._setStringValue(value, 0, true);
  40250. }
  40251. else {
  40252. this.topPixels = value;
  40253. }
  40254. };
  40255. PrimitiveThickness.prototype.setLeft = function (value) {
  40256. if (typeof value === "string") {
  40257. this._setStringValue(value, 1, true);
  40258. }
  40259. else {
  40260. this.leftPixels = value;
  40261. }
  40262. };
  40263. PrimitiveThickness.prototype.setRight = function (value) {
  40264. if (typeof value === "string") {
  40265. this._setStringValue(value, 2, true);
  40266. }
  40267. else {
  40268. this.rightPixels = value;
  40269. }
  40270. };
  40271. PrimitiveThickness.prototype.setBottom = function (value) {
  40272. if (typeof value === "string") {
  40273. this._setStringValue(value, 3, true);
  40274. }
  40275. else {
  40276. this.bottomPixels = value;
  40277. }
  40278. };
  40279. Object.defineProperty(PrimitiveThickness.prototype, "top", {
  40280. /**
  40281. * Get/set the top thickness. Possible values are: 'auto', 'inherit', 'XX%' for percentage, 'XXpx' or 'XX' for pixels.
  40282. */
  40283. get: function () {
  40284. return this._getStringValue(0);
  40285. },
  40286. set: function (value) {
  40287. this._setStringValue(value, 0, true);
  40288. },
  40289. enumerable: true,
  40290. configurable: true
  40291. });
  40292. Object.defineProperty(PrimitiveThickness.prototype, "left", {
  40293. /**
  40294. * Get/set the left thickness. Possible values are: 'auto', 'inherit', 'XX%' for percentage, 'XXpx' or 'XX' for pixels.
  40295. */
  40296. get: function () {
  40297. return this._getStringValue(1);
  40298. },
  40299. set: function (value) {
  40300. this._setStringValue(value, 1, true);
  40301. },
  40302. enumerable: true,
  40303. configurable: true
  40304. });
  40305. Object.defineProperty(PrimitiveThickness.prototype, "right", {
  40306. /**
  40307. * Get/set the right thickness. Possible values are: 'auto', 'inherit', 'XX%' for percentage, 'XXpx' or 'XX' for pixels.
  40308. */
  40309. get: function () {
  40310. return this._getStringValue(2);
  40311. },
  40312. set: function (value) {
  40313. this._setStringValue(value, 2, true);
  40314. },
  40315. enumerable: true,
  40316. configurable: true
  40317. });
  40318. Object.defineProperty(PrimitiveThickness.prototype, "bottom", {
  40319. /**
  40320. * Get/set the bottom thickness. Possible values are: 'auto', 'inherit', 'XX%' for percentage, 'XXpx' or 'XX' for pixels.
  40321. */
  40322. get: function () {
  40323. return this._getStringValue(3);
  40324. },
  40325. set: function (value) {
  40326. this._setStringValue(value, 3, true);
  40327. },
  40328. enumerable: true,
  40329. configurable: true
  40330. });
  40331. Object.defineProperty(PrimitiveThickness.prototype, "topPixels", {
  40332. /**
  40333. * Get/set the top thickness in pixel.
  40334. */
  40335. get: function () {
  40336. return this._pixels[0];
  40337. },
  40338. set: function (value) {
  40339. this._setPixels(value, 0, true);
  40340. },
  40341. enumerable: true,
  40342. configurable: true
  40343. });
  40344. Object.defineProperty(PrimitiveThickness.prototype, "leftPixels", {
  40345. /**
  40346. * Get/set the left thickness in pixel.
  40347. */
  40348. get: function () {
  40349. return this._pixels[1];
  40350. },
  40351. set: function (value) {
  40352. this._setPixels(value, 1, true);
  40353. },
  40354. enumerable: true,
  40355. configurable: true
  40356. });
  40357. Object.defineProperty(PrimitiveThickness.prototype, "rightPixels", {
  40358. /**
  40359. * Get/set the right thickness in pixel.
  40360. */
  40361. get: function () {
  40362. return this._pixels[2];
  40363. },
  40364. set: function (value) {
  40365. this._setPixels(value, 2, true);
  40366. },
  40367. enumerable: true,
  40368. configurable: true
  40369. });
  40370. Object.defineProperty(PrimitiveThickness.prototype, "bottomPixels", {
  40371. /**
  40372. * Get/set the bottom thickness in pixel.
  40373. */
  40374. get: function () {
  40375. return this._pixels[3];
  40376. },
  40377. set: function (value) {
  40378. this._setPixels(value, 3, true);
  40379. },
  40380. enumerable: true,
  40381. configurable: true
  40382. });
  40383. Object.defineProperty(PrimitiveThickness.prototype, "topPercentage", {
  40384. /**
  40385. * Get/set the top thickness in percentage.
  40386. * The get will return a valid value only if the edge type is percentage.
  40387. * The Set will change the edge mode if needed
  40388. */
  40389. get: function () {
  40390. return this._percentages[0];
  40391. },
  40392. set: function (value) {
  40393. this._setPercentage(value, 0, true);
  40394. },
  40395. enumerable: true,
  40396. configurable: true
  40397. });
  40398. Object.defineProperty(PrimitiveThickness.prototype, "leftPercentage", {
  40399. /**
  40400. * Get/set the left thickness in percentage.
  40401. * The get will return a valid value only if the edge mode is percentage.
  40402. * The Set will change the edge mode if needed
  40403. */
  40404. get: function () {
  40405. return this._percentages[1];
  40406. },
  40407. set: function (value) {
  40408. this._setPercentage(value, 1, true);
  40409. },
  40410. enumerable: true,
  40411. configurable: true
  40412. });
  40413. Object.defineProperty(PrimitiveThickness.prototype, "rightPercentage", {
  40414. /**
  40415. * Get/set the right thickness in percentage.
  40416. * The get will return a valid value only if the edge mode is percentage.
  40417. * The Set will change the edge mode if needed
  40418. */
  40419. get: function () {
  40420. return this._percentages[2];
  40421. },
  40422. set: function (value) {
  40423. this._setPercentage(value, 2, true);
  40424. },
  40425. enumerable: true,
  40426. configurable: true
  40427. });
  40428. Object.defineProperty(PrimitiveThickness.prototype, "bottomPercentage", {
  40429. /**
  40430. * Get/set the bottom thickness in percentage.
  40431. * The get will return a valid value only if the edge mode is percentage.
  40432. * The Set will change the edge mode if needed
  40433. */
  40434. get: function () {
  40435. return this._percentages[3];
  40436. },
  40437. set: function (value) {
  40438. this._setPercentage(value, 3, true);
  40439. },
  40440. enumerable: true,
  40441. configurable: true
  40442. });
  40443. Object.defineProperty(PrimitiveThickness.prototype, "topMode", {
  40444. /**
  40445. * Get/set the top mode. The setter shouldn't be used, other setters with value should be preferred
  40446. */
  40447. get: function () {
  40448. return this._getType(0, false);
  40449. },
  40450. set: function (mode) {
  40451. this._setType(0, mode);
  40452. },
  40453. enumerable: true,
  40454. configurable: true
  40455. });
  40456. Object.defineProperty(PrimitiveThickness.prototype, "leftMode", {
  40457. /**
  40458. * Get/set the left mode. The setter shouldn't be used, other setters with value should be preferred
  40459. */
  40460. get: function () {
  40461. return this._getType(1, false);
  40462. },
  40463. set: function (mode) {
  40464. this._setType(1, mode);
  40465. },
  40466. enumerable: true,
  40467. configurable: true
  40468. });
  40469. Object.defineProperty(PrimitiveThickness.prototype, "rightMode", {
  40470. /**
  40471. * Get/set the right mode. The setter shouldn't be used, other setters with value should be preferred
  40472. */
  40473. get: function () {
  40474. return this._getType(2, false);
  40475. },
  40476. set: function (mode) {
  40477. this._setType(2, mode);
  40478. },
  40479. enumerable: true,
  40480. configurable: true
  40481. });
  40482. Object.defineProperty(PrimitiveThickness.prototype, "bottomMode", {
  40483. /**
  40484. * Get/set the bottom mode. The setter shouldn't be used, other setters with value should be preferred
  40485. */
  40486. get: function () {
  40487. return this._getType(3, false);
  40488. },
  40489. set: function (mode) {
  40490. this._setType(3, mode);
  40491. },
  40492. enumerable: true,
  40493. configurable: true
  40494. });
  40495. PrimitiveThickness.prototype._computePixels = function (index, sourceArea, emitChanged) {
  40496. var type = this._getType(index, false);
  40497. if (type === PrimitiveThickness.Inherit) {
  40498. this._parentAccess()._computePixels(index, sourceArea, emitChanged);
  40499. return;
  40500. }
  40501. if (type !== PrimitiveThickness.Percentage) {
  40502. return;
  40503. }
  40504. var pixels = ((index === 0 || index === 3) ? sourceArea.height : sourceArea.width) * this._percentages[index];
  40505. this._pixels[index] = pixels;
  40506. if (emitChanged) {
  40507. this._changedCallback();
  40508. }
  40509. };
  40510. /**
  40511. * Compute the positioning/size of an area considering the thickness of this object and a given alignment
  40512. * @param sourceArea the source area where the content must be sized/positioned
  40513. * @param contentSize the content size to position/resize
  40514. * @param alignment the alignment setting
  40515. * @param dstOffset the position of the content
  40516. * @param dstArea the new size of the content
  40517. */
  40518. PrimitiveThickness.prototype.computeWithAlignment = function (sourceArea, contentSize, alignment, dstOffset, dstArea, computeLayoutArea) {
  40519. if (computeLayoutArea === void 0) { computeLayoutArea = false; }
  40520. // Fetch some data
  40521. var topType = this._getType(0, true);
  40522. var leftType = this._getType(1, true);
  40523. var rightType = this._getType(2, true);
  40524. var bottomType = this._getType(3, true);
  40525. var hasWidth = contentSize && (contentSize.width != null);
  40526. var hasHeight = contentSize && (contentSize.height != null);
  40527. var width = hasWidth ? contentSize.width : 0;
  40528. var height = hasHeight ? contentSize.height : 0;
  40529. var isTopAuto = topType === PrimitiveThickness.Auto;
  40530. var isLeftAuto = leftType === PrimitiveThickness.Auto;
  40531. var isRightAuto = rightType === PrimitiveThickness.Auto;
  40532. var isBottomAuto = bottomType === PrimitiveThickness.Auto;
  40533. switch (alignment.horizontal) {
  40534. case PrimitiveAlignment.AlignLeft:
  40535. {
  40536. if (isLeftAuto) {
  40537. dstOffset.x = 0;
  40538. }
  40539. else {
  40540. this._computePixels(1, sourceArea, true);
  40541. dstOffset.x = this.leftPixels;
  40542. }
  40543. dstArea.width = width;
  40544. if (computeLayoutArea) {
  40545. dstArea.width += this.leftPixels;
  40546. }
  40547. break;
  40548. }
  40549. case PrimitiveAlignment.AlignRight:
  40550. {
  40551. if (isRightAuto) {
  40552. dstOffset.x = Math.round(sourceArea.width - width);
  40553. }
  40554. else {
  40555. this._computePixels(2, sourceArea, true);
  40556. dstOffset.x = Math.round(sourceArea.width - (width + this.rightPixels));
  40557. }
  40558. dstArea.width = width;
  40559. if (computeLayoutArea) {
  40560. dstArea.width += this.rightPixels;
  40561. }
  40562. break;
  40563. }
  40564. case PrimitiveAlignment.AlignStretch:
  40565. {
  40566. if (isLeftAuto) {
  40567. dstOffset.x = 0;
  40568. }
  40569. else {
  40570. this._computePixels(1, sourceArea, true);
  40571. dstOffset.x = this.leftPixels;
  40572. }
  40573. var right = 0;
  40574. if (!isRightAuto) {
  40575. this._computePixels(2, sourceArea, true);
  40576. right = this.rightPixels;
  40577. }
  40578. dstArea.width = sourceArea.width - (dstOffset.x + right);
  40579. break;
  40580. }
  40581. case PrimitiveAlignment.AlignCenter:
  40582. {
  40583. if (!isLeftAuto) {
  40584. this._computePixels(1, sourceArea, true);
  40585. }
  40586. if (!isRightAuto) {
  40587. this._computePixels(2, sourceArea, true);
  40588. }
  40589. var offset = (isLeftAuto ? 0 : this.leftPixels) - (isRightAuto ? 0 : this.rightPixels);
  40590. dstOffset.x = Math.round(((sourceArea.width - width) / 2) + offset);
  40591. dstArea.width = width;
  40592. break;
  40593. }
  40594. }
  40595. switch (alignment.vertical) {
  40596. case PrimitiveAlignment.AlignTop:
  40597. {
  40598. if (isTopAuto) {
  40599. dstOffset.y = sourceArea.height - height;
  40600. }
  40601. else {
  40602. this._computePixels(0, sourceArea, true);
  40603. dstOffset.y = Math.round(sourceArea.height - (height + this.topPixels));
  40604. }
  40605. dstArea.height = height;
  40606. if (computeLayoutArea) {
  40607. dstArea.height += this.topPixels;
  40608. }
  40609. break;
  40610. }
  40611. case PrimitiveAlignment.AlignBottom:
  40612. {
  40613. if (isBottomAuto) {
  40614. dstOffset.y = 0;
  40615. }
  40616. else {
  40617. this._computePixels(3, sourceArea, true);
  40618. dstOffset.y = this.bottomPixels;
  40619. }
  40620. dstArea.height = height;
  40621. if (computeLayoutArea) {
  40622. dstArea.height += this.bottomPixels;
  40623. }
  40624. break;
  40625. }
  40626. case PrimitiveAlignment.AlignStretch:
  40627. {
  40628. if (isBottomAuto) {
  40629. dstOffset.y = 0;
  40630. }
  40631. else {
  40632. this._computePixels(3, sourceArea, true);
  40633. dstOffset.y = this.bottomPixels;
  40634. }
  40635. var top_1 = 0;
  40636. if (!isTopAuto) {
  40637. this._computePixels(0, sourceArea, true);
  40638. top_1 = this.topPixels;
  40639. }
  40640. dstArea.height = sourceArea.height - (dstOffset.y + top_1);
  40641. break;
  40642. }
  40643. case PrimitiveAlignment.AlignCenter:
  40644. {
  40645. if (!isTopAuto) {
  40646. this._computePixels(0, sourceArea, true);
  40647. }
  40648. if (!isBottomAuto) {
  40649. this._computePixels(3, sourceArea, true);
  40650. }
  40651. var offset = (isBottomAuto ? 0 : this.bottomPixels) - (isTopAuto ? 0 : this.topPixels);
  40652. dstOffset.y = Math.round(((sourceArea.height - height) / 2) + offset);
  40653. dstArea.height = height;
  40654. break;
  40655. }
  40656. }
  40657. };
  40658. /**
  40659. * Compute an area and its position considering this thickness properties based on a given source area
  40660. * @param sourceArea the source area
  40661. * @param dstOffset the position of the resulting area
  40662. * @param dstArea the size of the resulting area
  40663. */
  40664. PrimitiveThickness.prototype.compute = function (sourceArea, dstOffset, dstArea) {
  40665. this._computePixels(0, sourceArea, true);
  40666. this._computePixels(1, sourceArea, true);
  40667. this._computePixels(2, sourceArea, true);
  40668. this._computePixels(3, sourceArea, true);
  40669. dstOffset.x = this.leftPixels;
  40670. dstArea.width = sourceArea.width - (dstOffset.x + this.rightPixels);
  40671. dstOffset.y = this.bottomPixels;
  40672. dstArea.height = sourceArea.height - (dstOffset.y + this.topPixels);
  40673. };
  40674. /**
  40675. * Compute an area considering this thickness properties based on a given source area
  40676. * @param sourceArea the source area
  40677. * @param result the resulting area
  40678. */
  40679. PrimitiveThickness.prototype.computeArea = function (sourceArea, result) {
  40680. this._computePixels(0, sourceArea, true);
  40681. this._computePixels(1, sourceArea, true);
  40682. this._computePixels(2, sourceArea, true);
  40683. this._computePixels(3, sourceArea, true);
  40684. result.width = this.leftPixels + sourceArea.width + this.rightPixels;
  40685. result.height = this.bottomPixels + sourceArea.height + this.topPixels;
  40686. };
  40687. PrimitiveThickness.prototype.enlarge = function (sourceArea, dstOffset, enlargedArea) {
  40688. this._computePixels(0, sourceArea, true);
  40689. this._computePixels(1, sourceArea, true);
  40690. this._computePixels(2, sourceArea, true);
  40691. this._computePixels(3, sourceArea, true);
  40692. dstOffset.x = this.leftPixels;
  40693. enlargedArea.width = sourceArea.width + (dstOffset.x + this.rightPixels);
  40694. dstOffset.y = this.bottomPixels;
  40695. enlargedArea.height = sourceArea.height + (dstOffset.y + this.topPixels);
  40696. };
  40697. PrimitiveThickness.Auto = 0x1;
  40698. PrimitiveThickness.Inherit = 0x2;
  40699. PrimitiveThickness.Percentage = 0x4;
  40700. PrimitiveThickness.Pixel = 0x8;
  40701. return PrimitiveThickness;
  40702. }());
  40703. BABYLON.PrimitiveThickness = PrimitiveThickness;
  40704. /**
  40705. * Main class used for the Primitive Intersection API
  40706. */
  40707. var IntersectInfo2D = (function () {
  40708. function IntersectInfo2D() {
  40709. this.findFirstOnly = false;
  40710. this.intersectHidden = false;
  40711. this.pickPosition = BABYLON.Vector2.Zero();
  40712. }
  40713. Object.defineProperty(IntersectInfo2D.prototype, "isIntersected", {
  40714. /**
  40715. * true if at least one primitive intersected during the test
  40716. */
  40717. get: function () {
  40718. return this.intersectedPrimitives && this.intersectedPrimitives.length > 0;
  40719. },
  40720. enumerable: true,
  40721. configurable: true
  40722. });
  40723. IntersectInfo2D.prototype.isPrimIntersected = function (prim) {
  40724. for (var _i = 0, _a = this.intersectedPrimitives; _i < _a.length; _i++) {
  40725. var cur = _a[_i];
  40726. if (cur.prim === prim) {
  40727. return cur.intersectionLocation;
  40728. }
  40729. }
  40730. return null;
  40731. };
  40732. // Internals, don't use
  40733. IntersectInfo2D.prototype._exit = function (firstLevel) {
  40734. if (firstLevel) {
  40735. this._globalPickPosition = null;
  40736. }
  40737. };
  40738. return IntersectInfo2D;
  40739. }());
  40740. BABYLON.IntersectInfo2D = IntersectInfo2D;
  40741. var Prim2DBase = (function (_super) {
  40742. __extends(Prim2DBase, _super);
  40743. function Prim2DBase(settings) {
  40744. // Avoid checking every time if the object exists
  40745. if (settings == null) {
  40746. settings = {};
  40747. }
  40748. // BASE CLASS CALL
  40749. _super.call(this);
  40750. // Fetch the owner, parent. There're many ways to do it and we can end up with nothing for both
  40751. var owner;
  40752. var parent;
  40753. if (Prim2DBase._isCanvasInit) {
  40754. owner = this;
  40755. parent = null;
  40756. this._canvasPreInit(settings);
  40757. }
  40758. else {
  40759. if (settings.parent != null) {
  40760. parent = settings.parent;
  40761. owner = settings.parent.owner;
  40762. if (!owner) {
  40763. throw new Error("Parent " + parent.id + " of " + settings.id + " doesn't have a valid owner!");
  40764. }
  40765. 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)) {
  40766. 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");
  40767. }
  40768. }
  40769. }
  40770. // Fields initialization
  40771. this._layoutEngine = BABYLON.CanvasLayoutEngine.Singleton;
  40772. this._size = null; //Size.Zero();
  40773. this._scale = new BABYLON.Vector2(1, 1);
  40774. this._actualSize = null;
  40775. this._boundingSize = BABYLON.Size.Zero();
  40776. this._layoutArea = BABYLON.Size.Zero();
  40777. this._layoutAreaPos = null;
  40778. this._layoutBoundingInfo = null;
  40779. this._marginOffset = BABYLON.Vector2.Zero();
  40780. this._paddingOffset = BABYLON.Vector2.Zero();
  40781. this._parentPaddingOffset = BABYLON.Vector2.Zero();
  40782. this._parentContentArea = BABYLON.Size.Zero();
  40783. this._lastAutoSizeArea = BABYLON.Size.Zero();
  40784. this._contentArea = new BABYLON.Size(null, null);
  40785. this._pointerEventObservable = new BABYLON.Observable();
  40786. this._boundingInfo = new BABYLON.BoundingInfo2D();
  40787. this._owner = owner;
  40788. this._parent = null;
  40789. this._margin = null;
  40790. this._padding = null;
  40791. this._marginAlignment = null;
  40792. this._id = settings.id;
  40793. this.propertyChanged = new BABYLON.Observable();
  40794. this._children = new Array();
  40795. this._localTransform = new BABYLON.Matrix();
  40796. this._globalTransform = null;
  40797. this._invGlobalTransform = null;
  40798. this._globalTransformProcessStep = 0;
  40799. this._globalTransformStep = 0;
  40800. this._renderGroup = null;
  40801. this._primLinearPosition = 0;
  40802. this._manualZOrder = null;
  40803. this._zOrder = 0;
  40804. this._zMax = 0;
  40805. this._firstZDirtyIndex = Prim2DBase._bigInt;
  40806. this._actualOpacity = 0;
  40807. this._actualScale = BABYLON.Vector2.Zero();
  40808. var isPickable = true;
  40809. var isContainer = true;
  40810. if (settings.isPickable !== undefined) {
  40811. isPickable = settings.isPickable;
  40812. }
  40813. if (settings.isContainer !== undefined) {
  40814. isContainer = settings.isContainer;
  40815. }
  40816. if (settings.dontInheritParentScale) {
  40817. this._setFlags(BABYLON.SmartPropertyPrim.flagDontInheritParentScale);
  40818. }
  40819. this._setFlags((isPickable ? BABYLON.SmartPropertyPrim.flagIsPickable : 0) | BABYLON.SmartPropertyPrim.flagBoundingInfoDirty | BABYLON.SmartPropertyPrim.flagActualOpacityDirty | (isContainer ? BABYLON.SmartPropertyPrim.flagIsContainer : 0) | BABYLON.SmartPropertyPrim.flagActualScaleDirty | BABYLON.SmartPropertyPrim.flagLayoutBoundingInfoDirty);
  40820. if (settings.opacity != null) {
  40821. this._opacity = settings.opacity;
  40822. }
  40823. else {
  40824. this._opacity = 1;
  40825. }
  40826. this._updateRenderMode();
  40827. if (settings.childrenFlatZOrder) {
  40828. this._setFlags(BABYLON.SmartPropertyPrim.flagChildrenFlatZOrder);
  40829. }
  40830. // If the parent is given, initialize the hierarchy/owner related data
  40831. if (parent != null) {
  40832. parent.addChild(this);
  40833. this._hierarchyDepth = parent._hierarchyDepth + 1;
  40834. this._patchHierarchy(parent.owner);
  40835. }
  40836. // If it's a group, detect its own states
  40837. if (this.owner && this instanceof BABYLON.Group2D) {
  40838. var group = this;
  40839. group.detectGroupStates();
  40840. }
  40841. // Time to insert children if some are specified
  40842. if (settings.children != null) {
  40843. for (var _i = 0, _a = settings.children; _i < _a.length; _i++) {
  40844. var child = _a[_i];
  40845. this.addChild(child);
  40846. // Good time to patch the hierarchy, it won't go very far if there's no need to
  40847. if (this.owner != null) {
  40848. child._patchHierarchy(this.owner);
  40849. }
  40850. }
  40851. }
  40852. if (settings.zOrder != null) {
  40853. this.zOrder = settings.zOrder;
  40854. }
  40855. // Set the model related properties
  40856. if (settings.position != null) {
  40857. this.position = settings.position;
  40858. }
  40859. else if (settings.x != null || settings.y != null) {
  40860. this.position = new BABYLON.Vector2(settings.x || 0, settings.y || 0);
  40861. }
  40862. else {
  40863. this._position = null;
  40864. }
  40865. this.rotation = (settings.rotation == null) ? 0 : settings.rotation;
  40866. if (settings.scale != null) {
  40867. this.scale = settings.scale;
  40868. }
  40869. else {
  40870. if (settings.scaleX != null) {
  40871. this.scaleX = settings.scaleX;
  40872. }
  40873. if (settings.scaleY != null) {
  40874. this.scaleY = settings.scaleY;
  40875. }
  40876. }
  40877. this.levelVisible = (settings.isVisible == null) ? true : settings.isVisible;
  40878. this.origin = settings.origin || new BABYLON.Vector2(0.5, 0.5);
  40879. // Layout Engine
  40880. if (settings.layoutEngine != null) {
  40881. if (typeof settings.layoutEngine === "string") {
  40882. var name_1 = settings.layoutEngine.toLocaleLowerCase().trim();
  40883. if (name_1 === "canvas" || name_1 === "canvaslayoutengine") {
  40884. this.layoutEngine = BABYLON.CanvasLayoutEngine.Singleton;
  40885. }
  40886. else if (name_1.indexOf("stackpanel") === 0 || name_1.indexOf("horizontalstackpanel") === 0) {
  40887. this.layoutEngine = BABYLON.StackPanelLayoutEngine.Horizontal;
  40888. }
  40889. else if (name_1.indexOf("verticalstackpanel") === 0) {
  40890. this.layoutEngine = BABYLON.StackPanelLayoutEngine.Vertical;
  40891. }
  40892. }
  40893. else if (settings.layoutEngine instanceof BABYLON.LayoutEngineBase) {
  40894. this.layoutEngine = settings.layoutEngine;
  40895. }
  40896. }
  40897. // Set the layout/margin stuffs
  40898. if (settings.marginTop) {
  40899. this.margin.setTop(settings.marginTop);
  40900. }
  40901. if (settings.marginLeft) {
  40902. this.margin.setLeft(settings.marginLeft);
  40903. }
  40904. if (settings.marginRight) {
  40905. this.margin.setRight(settings.marginRight);
  40906. }
  40907. if (settings.marginBottom) {
  40908. this.margin.setBottom(settings.marginBottom);
  40909. }
  40910. if (settings.margin) {
  40911. if (typeof settings.margin === "string") {
  40912. this.margin.fromString(settings.margin);
  40913. }
  40914. else {
  40915. this.margin.fromUniformPixels(settings.margin);
  40916. }
  40917. }
  40918. if (settings.marginHAlignment) {
  40919. this.marginAlignment.horizontal = settings.marginHAlignment;
  40920. }
  40921. if (settings.marginVAlignment) {
  40922. this.marginAlignment.vertical = settings.marginVAlignment;
  40923. }
  40924. if (settings.marginAlignment) {
  40925. this.marginAlignment.fromString(settings.marginAlignment);
  40926. }
  40927. if (settings.paddingTop) {
  40928. this.padding.setTop(settings.paddingTop);
  40929. }
  40930. if (settings.paddingLeft) {
  40931. this.padding.setLeft(settings.paddingLeft);
  40932. }
  40933. if (settings.paddingRight) {
  40934. this.padding.setRight(settings.paddingRight);
  40935. }
  40936. if (settings.paddingBottom) {
  40937. this.padding.setBottom(settings.paddingBottom);
  40938. }
  40939. if (settings.padding) {
  40940. this.padding.fromString(settings.padding);
  40941. }
  40942. // Dirty layout and positioning
  40943. this._parentLayoutDirty();
  40944. this._positioningDirty();
  40945. }
  40946. Object.defineProperty(Prim2DBase.prototype, "actionManager", {
  40947. get: function () {
  40948. if (!this._actionManager) {
  40949. this._actionManager = new BABYLON.ActionManager(this.owner.scene);
  40950. }
  40951. return this._actionManager;
  40952. },
  40953. enumerable: true,
  40954. configurable: true
  40955. });
  40956. /**
  40957. * From 'this' primitive, traverse up (from parent to parent) until the given predicate is true
  40958. * @param predicate the predicate to test on each parent
  40959. * @return the first primitive where the predicate was successful
  40960. */
  40961. Prim2DBase.prototype.traverseUp = function (predicate) {
  40962. var p = this;
  40963. while (p != null) {
  40964. if (predicate(p)) {
  40965. return p;
  40966. }
  40967. p = p._parent;
  40968. }
  40969. return null;
  40970. };
  40971. Object.defineProperty(Prim2DBase.prototype, "owner", {
  40972. /**
  40973. * Retrieve the owner Canvas2D
  40974. */
  40975. get: function () {
  40976. return this._owner;
  40977. },
  40978. enumerable: true,
  40979. configurable: true
  40980. });
  40981. Object.defineProperty(Prim2DBase.prototype, "parent", {
  40982. /**
  40983. * Get the parent primitive (can be the Canvas, only the Canvas has no parent)
  40984. */
  40985. get: function () {
  40986. return this._parent;
  40987. },
  40988. enumerable: true,
  40989. configurable: true
  40990. });
  40991. Object.defineProperty(Prim2DBase.prototype, "children", {
  40992. /**
  40993. * The array of direct children primitives
  40994. */
  40995. get: function () {
  40996. return this._children;
  40997. },
  40998. enumerable: true,
  40999. configurable: true
  41000. });
  41001. Object.defineProperty(Prim2DBase.prototype, "id", {
  41002. /**
  41003. * The identifier of this primitive, may not be unique, it's for information purpose only
  41004. */
  41005. get: function () {
  41006. return this._id;
  41007. },
  41008. enumerable: true,
  41009. configurable: true
  41010. });
  41011. Object.defineProperty(Prim2DBase.prototype, "actualPosition", {
  41012. get: function () {
  41013. if (this._actualPosition != null) {
  41014. return this._actualPosition;
  41015. }
  41016. if (this._position != null) {
  41017. return this._position;
  41018. }
  41019. // At least return 0,0, we can't return null on actualPosition
  41020. return Prim2DBase._nullPosition;
  41021. },
  41022. /**
  41023. * DO NOT INVOKE for internal purpose only
  41024. */
  41025. set: function (val) {
  41026. this._actualPosition = val;
  41027. },
  41028. enumerable: true,
  41029. configurable: true
  41030. });
  41031. Object.defineProperty(Prim2DBase.prototype, "actualX", {
  41032. /**
  41033. * Shortcut to actualPosition.x
  41034. */
  41035. get: function () {
  41036. return this.actualPosition.x;
  41037. },
  41038. enumerable: true,
  41039. configurable: true
  41040. });
  41041. Object.defineProperty(Prim2DBase.prototype, "actualY", {
  41042. /**
  41043. * Shortcut to actualPosition.y
  41044. */
  41045. get: function () {
  41046. return this.actualPosition.y;
  41047. },
  41048. enumerable: true,
  41049. configurable: true
  41050. });
  41051. Object.defineProperty(Prim2DBase.prototype, "position", {
  41052. /**
  41053. * Position of the primitive, relative to its parent.
  41054. * BEWARE: if you change only position.x or y it won't trigger a property change and you won't have the expected behavior.
  41055. * Use this property to set a new Vector2 object, otherwise to change only the x/y use Prim2DBase.x or y properties.
  41056. * Setting this property may have no effect is specific alignment are in effect.
  41057. */
  41058. get: function () {
  41059. return this._position || Prim2DBase._nullPosition;
  41060. },
  41061. set: function (value) {
  41062. if (!this._checkPositionChange()) {
  41063. return;
  41064. }
  41065. this._position = value;
  41066. this._triggerPropertyChanged(Prim2DBase.actualPositionProperty, value);
  41067. },
  41068. enumerable: true,
  41069. configurable: true
  41070. });
  41071. Object.defineProperty(Prim2DBase.prototype, "x", {
  41072. /**
  41073. * Direct access to the position.x value of the primitive
  41074. * Use this property when you only want to change one component of the position property
  41075. */
  41076. get: function () {
  41077. if (!this._position) {
  41078. return null;
  41079. }
  41080. return this._position.x;
  41081. },
  41082. set: function (value) {
  41083. if (!this._checkPositionChange()) {
  41084. return;
  41085. }
  41086. if (!this._position) {
  41087. this._position = BABYLON.Vector2.Zero();
  41088. }
  41089. if (this._position.x === value) {
  41090. return;
  41091. }
  41092. this._position.x = value;
  41093. this._triggerPropertyChanged(Prim2DBase.positionProperty, value);
  41094. this._triggerPropertyChanged(Prim2DBase.actualPositionProperty, value);
  41095. },
  41096. enumerable: true,
  41097. configurable: true
  41098. });
  41099. Object.defineProperty(Prim2DBase.prototype, "y", {
  41100. /**
  41101. * Direct access to the position.y value of the primitive
  41102. * Use this property when you only want to change one component of the position property
  41103. */
  41104. get: function () {
  41105. if (!this._position) {
  41106. return null;
  41107. }
  41108. return this._position.y;
  41109. },
  41110. set: function (value) {
  41111. if (!this._checkPositionChange()) {
  41112. return;
  41113. }
  41114. if (!this._position) {
  41115. this._position = BABYLON.Vector2.Zero();
  41116. }
  41117. if (this._position.y === value) {
  41118. return;
  41119. }
  41120. this._position.y = value;
  41121. this._triggerPropertyChanged(Prim2DBase.positionProperty, value);
  41122. this._triggerPropertyChanged(Prim2DBase.actualPositionProperty, value);
  41123. },
  41124. enumerable: true,
  41125. configurable: true
  41126. });
  41127. Object.defineProperty(Prim2DBase.prototype, "size", {
  41128. /**
  41129. * Size of the primitive or its bounding area
  41130. * BEWARE: if you change only size.width or height it won't trigger a property change and you won't have the expected behavior.
  41131. * Use this property to set a new Size object, otherwise to change only the width/height use Prim2DBase.width or height properties.
  41132. */
  41133. get: function () {
  41134. if (!this._size || this._size.width == null || this._size.height == null) {
  41135. if (Prim2DBase.boundinbBoxReentrency) {
  41136. return Prim2DBase.nullSize;
  41137. }
  41138. if (!this._isFlagSet(BABYLON.SmartPropertyPrim.flagBoundingInfoDirty)) {
  41139. return this._boundingSize;
  41140. }
  41141. Prim2DBase.boundinbBoxReentrency = true;
  41142. var b = this.boundingInfo;
  41143. Prim2DBase.boundinbBoxReentrency = false;
  41144. return this._boundingSize;
  41145. }
  41146. return this._size;
  41147. },
  41148. set: function (value) {
  41149. this._size = value;
  41150. },
  41151. enumerable: true,
  41152. configurable: true
  41153. });
  41154. Object.defineProperty(Prim2DBase.prototype, "width", {
  41155. /**
  41156. * Direct access to the size.width value of the primitive
  41157. * Use this property when you only want to change one component of the size property
  41158. */
  41159. get: function () {
  41160. if (!this.size) {
  41161. return null;
  41162. }
  41163. return this.size.width;
  41164. },
  41165. set: function (value) {
  41166. if (!this.size) {
  41167. this.size = new BABYLON.Size(value, 0);
  41168. return;
  41169. }
  41170. if (this.size.width === value) {
  41171. return;
  41172. }
  41173. this.size.width = value;
  41174. this._triggerPropertyChanged(Prim2DBase.sizeProperty, value);
  41175. this._positioningDirty();
  41176. },
  41177. enumerable: true,
  41178. configurable: true
  41179. });
  41180. Object.defineProperty(Prim2DBase.prototype, "height", {
  41181. /**
  41182. * Direct access to the size.height value of the primitive
  41183. * Use this property when you only want to change one component of the size property
  41184. */
  41185. get: function () {
  41186. if (!this.size) {
  41187. return null;
  41188. }
  41189. return this.size.height;
  41190. },
  41191. set: function (value) {
  41192. if (!this.size) {
  41193. this.size = new BABYLON.Size(0, value);
  41194. return;
  41195. }
  41196. if (this.size.height === value) {
  41197. return;
  41198. }
  41199. this.size.height = value;
  41200. this._triggerPropertyChanged(Prim2DBase.sizeProperty, value);
  41201. this._positioningDirty();
  41202. },
  41203. enumerable: true,
  41204. configurable: true
  41205. });
  41206. Object.defineProperty(Prim2DBase.prototype, "rotation", {
  41207. get: function () {
  41208. return this._rotation;
  41209. },
  41210. set: function (value) {
  41211. this._rotation = value;
  41212. },
  41213. enumerable: true,
  41214. configurable: true
  41215. });
  41216. Object.defineProperty(Prim2DBase.prototype, "scale", {
  41217. get: function () {
  41218. return this._scale.x;
  41219. },
  41220. set: function (value) {
  41221. this._scale.x = this._scale.y = value;
  41222. this._setFlags(BABYLON.SmartPropertyPrim.flagActualScaleDirty);
  41223. this._spreadActualScaleDirty();
  41224. },
  41225. enumerable: true,
  41226. configurable: true
  41227. });
  41228. Object.defineProperty(Prim2DBase.prototype, "actualSize", {
  41229. /**
  41230. * Return the size of the primitive as it's being rendered into the target.
  41231. * 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.
  41232. * BEWARE: don't use the setter, it's for internal purpose only
  41233. * Note to implementers: you have to override this property and declare if necessary a @xxxxInstanceLevel decorator
  41234. */
  41235. get: function () {
  41236. if (this._actualSize) {
  41237. return this._actualSize;
  41238. }
  41239. return this._size;
  41240. },
  41241. set: function (value) {
  41242. if (this._actualSize.equals(value)) {
  41243. return;
  41244. }
  41245. this._actualSize = value;
  41246. },
  41247. enumerable: true,
  41248. configurable: true
  41249. });
  41250. Object.defineProperty(Prim2DBase.prototype, "actualZOffset", {
  41251. get: function () {
  41252. if (this._manualZOrder != null) {
  41253. return this._manualZOrder;
  41254. }
  41255. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagZOrderDirty)) {
  41256. this._updateZOrder();
  41257. }
  41258. return (1 - this._zOrder);
  41259. },
  41260. enumerable: true,
  41261. configurable: true
  41262. });
  41263. Object.defineProperty(Prim2DBase.prototype, "minSize", {
  41264. /**
  41265. * Get or set the minimal size the Layout Engine should respect when computing the primitive's actualSize.
  41266. * The Primitive's size won't be less than specified.
  41267. * The default value depends of the Primitive type
  41268. */
  41269. get: function () {
  41270. return this._minSize;
  41271. },
  41272. set: function (value) {
  41273. if (this._minSize && value && this._minSize.equals(value)) {
  41274. return;
  41275. }
  41276. this._minSize = value;
  41277. this._parentLayoutDirty();
  41278. },
  41279. enumerable: true,
  41280. configurable: true
  41281. });
  41282. Object.defineProperty(Prim2DBase.prototype, "maxSize", {
  41283. /**
  41284. * Get or set the maximal size the Layout Engine should respect when computing the primitive's actualSize.
  41285. * The Primitive's size won't be more than specified.
  41286. * The default value depends of the Primitive type
  41287. */
  41288. get: function () {
  41289. return this._maxSize;
  41290. },
  41291. set: function (value) {
  41292. if (this._maxSize && value && this._maxSize.equals(value)) {
  41293. return;
  41294. }
  41295. this._maxSize = value;
  41296. this._parentLayoutDirty();
  41297. },
  41298. enumerable: true,
  41299. configurable: true
  41300. });
  41301. Object.defineProperty(Prim2DBase.prototype, "origin", {
  41302. /**
  41303. * The origin defines the normalized coordinate of the center of the primitive, from the bottom/left corner.
  41304. * The origin is used only to compute transformation of the primitive, it has no meaning in the primitive local frame of reference
  41305. * For instance:
  41306. * 0,0 means the center is bottom/left. Which is the default for Canvas2D instances
  41307. * 0.5,0.5 means the center is at the center of the primitive, which is default of all types of Primitives
  41308. * 0,1 means the center is top/left
  41309. * @returns The normalized center.
  41310. */
  41311. get: function () {
  41312. return this._origin;
  41313. },
  41314. set: function (value) {
  41315. this._origin = value;
  41316. },
  41317. enumerable: true,
  41318. configurable: true
  41319. });
  41320. Object.defineProperty(Prim2DBase.prototype, "levelVisible", {
  41321. get: function () {
  41322. return this._isFlagSet(BABYLON.SmartPropertyPrim.flagLevelVisible);
  41323. },
  41324. set: function (value) {
  41325. this._changeFlags(BABYLON.SmartPropertyPrim.flagLevelVisible, value);
  41326. },
  41327. enumerable: true,
  41328. configurable: true
  41329. });
  41330. Object.defineProperty(Prim2DBase.prototype, "isVisible", {
  41331. get: function () {
  41332. return this._isFlagSet(BABYLON.SmartPropertyPrim.flagIsVisible);
  41333. },
  41334. set: function (value) {
  41335. this._changeFlags(BABYLON.SmartPropertyPrim.flagIsVisible, value);
  41336. },
  41337. enumerable: true,
  41338. configurable: true
  41339. });
  41340. Object.defineProperty(Prim2DBase.prototype, "zOrder", {
  41341. get: function () {
  41342. return this._manualZOrder;
  41343. },
  41344. set: function (value) {
  41345. if (this._manualZOrder === value) {
  41346. return;
  41347. }
  41348. this._manualZOrder = value;
  41349. this.onZOrderChanged();
  41350. if (this._actualZOrderChangedObservable && this._actualZOrderChangedObservable.hasObservers()) {
  41351. this._actualZOrderChangedObservable.notifyObservers(value);
  41352. }
  41353. },
  41354. enumerable: true,
  41355. configurable: true
  41356. });
  41357. Object.defineProperty(Prim2DBase.prototype, "isManualZOrder", {
  41358. get: function () {
  41359. return this._manualZOrder != null;
  41360. },
  41361. enumerable: true,
  41362. configurable: true
  41363. });
  41364. Object.defineProperty(Prim2DBase.prototype, "margin", {
  41365. get: function () {
  41366. var _this = this;
  41367. if (!this._margin) {
  41368. this._margin = new PrimitiveThickness(function () {
  41369. if (!_this.parent) {
  41370. return null;
  41371. }
  41372. return _this.parent.margin;
  41373. }, function () { return _this._positioningDirty(); });
  41374. }
  41375. return this._margin;
  41376. },
  41377. enumerable: true,
  41378. configurable: true
  41379. });
  41380. Object.defineProperty(Prim2DBase.prototype, "_hasMargin", {
  41381. get: function () {
  41382. return (this._margin !== null) || (this._marginAlignment !== null);
  41383. },
  41384. enumerable: true,
  41385. configurable: true
  41386. });
  41387. Object.defineProperty(Prim2DBase.prototype, "padding", {
  41388. get: function () {
  41389. var _this = this;
  41390. if (!this._padding) {
  41391. this._padding = new PrimitiveThickness(function () {
  41392. if (!_this.parent) {
  41393. return null;
  41394. }
  41395. return _this.parent.padding;
  41396. }, function () { return _this._positioningDirty(); });
  41397. }
  41398. return this._padding;
  41399. },
  41400. enumerable: true,
  41401. configurable: true
  41402. });
  41403. Object.defineProperty(Prim2DBase.prototype, "_hasPadding", {
  41404. get: function () {
  41405. return this._padding !== null;
  41406. },
  41407. enumerable: true,
  41408. configurable: true
  41409. });
  41410. Object.defineProperty(Prim2DBase.prototype, "marginAlignment", {
  41411. get: function () {
  41412. var _this = this;
  41413. if (!this._marginAlignment) {
  41414. this._marginAlignment = new PrimitiveAlignment(function () { return _this._positioningDirty(); });
  41415. }
  41416. return this._marginAlignment;
  41417. },
  41418. enumerable: true,
  41419. configurable: true
  41420. });
  41421. Object.defineProperty(Prim2DBase.prototype, "opacity", {
  41422. get: function () {
  41423. return this._opacity;
  41424. },
  41425. set: function (value) {
  41426. if (value < 0) {
  41427. value = 0;
  41428. }
  41429. else if (value > 1) {
  41430. value = 1;
  41431. }
  41432. if (this._opacity === value) {
  41433. return;
  41434. }
  41435. this._opacity = value;
  41436. this._setFlags(BABYLON.SmartPropertyPrim.flagActualOpacityDirty);
  41437. this._spreadActualOpacityChanged();
  41438. this._updateRenderMode();
  41439. },
  41440. enumerable: true,
  41441. configurable: true
  41442. });
  41443. Object.defineProperty(Prim2DBase.prototype, "scaleX", {
  41444. get: function () {
  41445. return this._scale.x;
  41446. },
  41447. set: function (value) {
  41448. this._scale.x = value;
  41449. this._setFlags(BABYLON.SmartPropertyPrim.flagActualScaleDirty);
  41450. this._spreadActualScaleDirty();
  41451. },
  41452. enumerable: true,
  41453. configurable: true
  41454. });
  41455. Object.defineProperty(Prim2DBase.prototype, "scaleY", {
  41456. get: function () {
  41457. return this._scale.y;
  41458. },
  41459. set: function (value) {
  41460. this._scale.y = value;
  41461. this._setFlags(BABYLON.SmartPropertyPrim.flagActualScaleDirty);
  41462. this._spreadActualScaleDirty();
  41463. },
  41464. enumerable: true,
  41465. configurable: true
  41466. });
  41467. Prim2DBase.prototype._spreadActualScaleDirty = function () {
  41468. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  41469. var child = _a[_i];
  41470. child._setFlags(BABYLON.SmartPropertyPrim.flagActualScaleDirty);
  41471. child._spreadActualScaleDirty();
  41472. }
  41473. };
  41474. Object.defineProperty(Prim2DBase.prototype, "actualScale", {
  41475. /**
  41476. * Returns the actual scale of this Primitive, the value is computed from the scale property of this primitive, multiplied by the actualScale of its parent one (if any). The Vector2 object returned contains the scale for both X and Y axis
  41477. */
  41478. get: function () {
  41479. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagActualScaleDirty)) {
  41480. var cur = this._isFlagSet(BABYLON.SmartPropertyPrim.flagDontInheritParentScale) ? null : this.parent;
  41481. var sx = this.scaleX;
  41482. var sy = this.scaleY;
  41483. while (cur) {
  41484. sx *= cur.scaleX;
  41485. sy *= cur.scaleY;
  41486. cur = cur._isFlagSet(BABYLON.SmartPropertyPrim.flagDontInheritParentScale) ? null : cur.parent;
  41487. }
  41488. this._actualScale.copyFromFloats(sx, sy);
  41489. this._clearFlags(BABYLON.SmartPropertyPrim.flagActualScaleDirty);
  41490. }
  41491. return this._actualScale;
  41492. },
  41493. enumerable: true,
  41494. configurable: true
  41495. });
  41496. Object.defineProperty(Prim2DBase.prototype, "actualScaleX", {
  41497. /**
  41498. * Get the actual Scale of the X axis, shortcut for this.actualScale.x
  41499. */
  41500. get: function () {
  41501. return this.actualScale.x;
  41502. },
  41503. enumerable: true,
  41504. configurable: true
  41505. });
  41506. Object.defineProperty(Prim2DBase.prototype, "actualScaleY", {
  41507. /**
  41508. * Get the actual Scale of the Y axis, shortcut for this.actualScale.y
  41509. */
  41510. get: function () {
  41511. return this.actualScale.y;
  41512. },
  41513. enumerable: true,
  41514. configurable: true
  41515. });
  41516. Object.defineProperty(Prim2DBase.prototype, "actualOpacity", {
  41517. /**
  41518. * Get the actual opacity level, this property is computed from the opacity property, multiplied by the actualOpacity of its parent (if any)
  41519. */
  41520. get: function () {
  41521. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagActualOpacityDirty)) {
  41522. var cur = this.parent;
  41523. var op = this.opacity;
  41524. while (cur) {
  41525. op *= cur.opacity;
  41526. cur = cur.parent;
  41527. }
  41528. this._actualOpacity = op;
  41529. this._clearFlags(BABYLON.SmartPropertyPrim.flagActualOpacityDirty);
  41530. }
  41531. return this._actualOpacity;
  41532. },
  41533. enumerable: true,
  41534. configurable: true
  41535. });
  41536. Object.defineProperty(Prim2DBase.prototype, "layoutEngine", {
  41537. /**
  41538. * Get/set the layout engine to use for this primitive.
  41539. * The default layout engine is the CanvasLayoutEngine.
  41540. */
  41541. get: function () {
  41542. if (!this._layoutEngine) {
  41543. this._layoutEngine = BABYLON.CanvasLayoutEngine.Singleton;
  41544. }
  41545. return this._layoutEngine;
  41546. },
  41547. set: function (value) {
  41548. if (this._layoutEngine === value) {
  41549. return;
  41550. }
  41551. this._changeLayoutEngine(value);
  41552. },
  41553. enumerable: true,
  41554. configurable: true
  41555. });
  41556. Object.defineProperty(Prim2DBase.prototype, "layoutArea", {
  41557. /**
  41558. * Get/set the layout are of this primitive.
  41559. * The Layout area is the zone allocated by the Layout Engine for this particular primitive. Margins/Alignment will be computed based on this area.
  41560. * The setter should only be called by a Layout Engine class.
  41561. */
  41562. get: function () {
  41563. return this._layoutArea;
  41564. },
  41565. set: function (val) {
  41566. if (this._layoutArea.equals(val)) {
  41567. return;
  41568. }
  41569. this._positioningDirty();
  41570. if (this.parent) {
  41571. this.parent._setFlags(BABYLON.SmartPropertyPrim.flagLayoutBoundingInfoDirty);
  41572. }
  41573. this._layoutArea = val;
  41574. },
  41575. enumerable: true,
  41576. configurable: true
  41577. });
  41578. Object.defineProperty(Prim2DBase.prototype, "layoutAreaPos", {
  41579. /**
  41580. * Get/set the layout area position (relative to the parent primitive).
  41581. * The setter should only be called by a Layout Engine class.
  41582. */
  41583. get: function () {
  41584. return this._layoutAreaPos || Prim2DBase._nullPosition;
  41585. },
  41586. set: function (val) {
  41587. if (this._layoutAreaPos && this._layoutAreaPos.equals(val)) {
  41588. return;
  41589. }
  41590. if (this.parent) {
  41591. this.parent._setFlags(BABYLON.SmartPropertyPrim.flagLayoutBoundingInfoDirty);
  41592. }
  41593. this._positioningDirty();
  41594. this._layoutAreaPos = val;
  41595. },
  41596. enumerable: true,
  41597. configurable: true
  41598. });
  41599. Object.defineProperty(Prim2DBase.prototype, "isPickable", {
  41600. /**
  41601. * Define if the Primitive can be subject to intersection test or not (default is true)
  41602. */
  41603. get: function () {
  41604. return this._isFlagSet(BABYLON.SmartPropertyPrim.flagIsPickable);
  41605. },
  41606. set: function (value) {
  41607. this._changeFlags(BABYLON.SmartPropertyPrim.flagIsPickable, value);
  41608. },
  41609. enumerable: true,
  41610. configurable: true
  41611. });
  41612. Object.defineProperty(Prim2DBase.prototype, "isContainer", {
  41613. /**
  41614. * Define if the Primitive acts as a container or not
  41615. * A container will encapsulate its children for interaction event.
  41616. * If it's not a container events will be process down to children if the primitive is not pickable.
  41617. * Default value is true
  41618. */
  41619. get: function () {
  41620. return this._isFlagSet(BABYLON.SmartPropertyPrim.flagIsContainer);
  41621. },
  41622. set: function (value) {
  41623. this._changeFlags(BABYLON.SmartPropertyPrim.flagIsContainer, value);
  41624. },
  41625. enumerable: true,
  41626. configurable: true
  41627. });
  41628. Object.defineProperty(Prim2DBase.prototype, "hierarchyDepth", {
  41629. /**
  41630. * Return the depth level of the Primitive into the Canvas' Graph. A Canvas will be 0, its direct children 1, and so on.
  41631. */
  41632. get: function () {
  41633. return this._hierarchyDepth;
  41634. },
  41635. enumerable: true,
  41636. configurable: true
  41637. });
  41638. Object.defineProperty(Prim2DBase.prototype, "renderGroup", {
  41639. /**
  41640. * Retrieve the Group that is responsible to render this primitive
  41641. */
  41642. get: function () {
  41643. return this._renderGroup;
  41644. },
  41645. enumerable: true,
  41646. configurable: true
  41647. });
  41648. Object.defineProperty(Prim2DBase.prototype, "globalTransform", {
  41649. /**
  41650. * Get the global transformation matrix of the primitive
  41651. */
  41652. get: function () {
  41653. this._updateLocalTransform();
  41654. return this._globalTransform;
  41655. },
  41656. enumerable: true,
  41657. configurable: true
  41658. });
  41659. /**
  41660. * return the global position of the primitive, relative to its canvas
  41661. */
  41662. Prim2DBase.prototype.getGlobalPosition = function () {
  41663. var v = new BABYLON.Vector2(0, 0);
  41664. this.getGlobalPositionByRef(v);
  41665. return v;
  41666. };
  41667. /**
  41668. * return the global position of the primitive, relative to its canvas
  41669. * @param v the valid Vector2 object where the global position will be stored
  41670. */
  41671. Prim2DBase.prototype.getGlobalPositionByRef = function (v) {
  41672. v.x = this.globalTransform.m[12];
  41673. v.y = this.globalTransform.m[13];
  41674. };
  41675. Object.defineProperty(Prim2DBase.prototype, "invGlobalTransform", {
  41676. /**
  41677. * Get invert of the global transformation matrix of the primitive
  41678. */
  41679. get: function () {
  41680. this._updateLocalTransform();
  41681. return this._invGlobalTransform;
  41682. },
  41683. enumerable: true,
  41684. configurable: true
  41685. });
  41686. Object.defineProperty(Prim2DBase.prototype, "localTransform", {
  41687. /**
  41688. * Get the local transformation of the primitive
  41689. */
  41690. get: function () {
  41691. this._updateLocalTransform();
  41692. return this._localTransform;
  41693. },
  41694. enumerable: true,
  41695. configurable: true
  41696. });
  41697. Object.defineProperty(Prim2DBase.prototype, "boundingInfo", {
  41698. /**
  41699. * Get the boundingInfo associated to the primitive and its children.
  41700. * The value is supposed to be always up to date
  41701. */
  41702. get: function () {
  41703. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagBoundingInfoDirty)) {
  41704. if (this.owner) {
  41705. this.owner.boundingInfoRecomputeCounter.addCount(1, false);
  41706. }
  41707. if (this.isSizedByContent) {
  41708. this._boundingInfo.clear();
  41709. }
  41710. else {
  41711. this._boundingInfo.copyFrom(this.levelBoundingInfo);
  41712. }
  41713. var bi = this._boundingInfo;
  41714. var tps = new BABYLON.BoundingInfo2D();
  41715. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  41716. var curChild = _a[_i];
  41717. var bb = curChild.boundingInfo;
  41718. bb.transformToRef(curChild.localTransform, tps);
  41719. bi.unionToRef(tps, bi);
  41720. }
  41721. this._boundingInfo.maxToRef(Prim2DBase._bMax);
  41722. 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);
  41723. this._clearFlags(BABYLON.SmartPropertyPrim.flagBoundingInfoDirty);
  41724. }
  41725. return this._boundingInfo;
  41726. },
  41727. enumerable: true,
  41728. configurable: true
  41729. });
  41730. Object.defineProperty(Prim2DBase.prototype, "layoutBoundingInfo", {
  41731. /**
  41732. * Get the boundingInfo of the primitive's content arranged by a layout Engine
  41733. * If a particular child is not arranged by layout, it's boundingInfo is used instead to produce something as accurate as possible
  41734. */
  41735. get: function () {
  41736. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagLayoutBoundingInfoDirty)) {
  41737. if (!this._layoutBoundingInfo) {
  41738. this._layoutBoundingInfo = new BABYLON.BoundingInfo2D();
  41739. }
  41740. if (this.isSizedByContent) {
  41741. this._layoutBoundingInfo.clear();
  41742. }
  41743. else {
  41744. this._layoutBoundingInfo.copyFrom(this.levelBoundingInfo);
  41745. }
  41746. var bi = this._layoutBoundingInfo;
  41747. var tps = new BABYLON.BoundingInfo2D();
  41748. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  41749. var curChild = _a[_i];
  41750. var bb = void 0;
  41751. if (curChild._layoutAreaPos) {
  41752. var s = curChild._layoutArea;
  41753. BABYLON.BoundingInfo2D.CreateFromMinMaxToRef(0, s.width, 0, s.height, Prim2DBase._tpsBB);
  41754. bb = Prim2DBase._tpsBB;
  41755. }
  41756. else {
  41757. bb = curChild.boundingInfo;
  41758. }
  41759. bb.transformToRef(curChild.localTransform, tps);
  41760. bi.unionToRef(tps, bi);
  41761. }
  41762. this._clearFlags(BABYLON.SmartPropertyPrim.flagLayoutBoundingInfoDirty);
  41763. }
  41764. return this._layoutBoundingInfo;
  41765. },
  41766. enumerable: true,
  41767. configurable: true
  41768. });
  41769. Object.defineProperty(Prim2DBase.prototype, "isSizeAuto", {
  41770. /**
  41771. * Determine if the size is automatically computed or fixed because manually specified.
  41772. * Use the actualSize property to get the final/real size of the primitive
  41773. * @returns true if the size is automatically computed, false if it were manually specified.
  41774. */
  41775. get: function () {
  41776. return this._size == null;
  41777. },
  41778. enumerable: true,
  41779. configurable: true
  41780. });
  41781. Object.defineProperty(Prim2DBase.prototype, "isSizedByContent", {
  41782. /**
  41783. * Return true if this prim has an auto size which is set by the children's global bounding box
  41784. */
  41785. get: function () {
  41786. return (this._size == null) && (this._children.length > 0);
  41787. },
  41788. enumerable: true,
  41789. configurable: true
  41790. });
  41791. Object.defineProperty(Prim2DBase.prototype, "isPositionAuto", {
  41792. /**
  41793. * Determine if the position is automatically computed or fixed because manually specified.
  41794. * Use the actualPosition property to get the final/real position of the primitive
  41795. * @returns true if the position is automatically computed, false if it were manually specified.
  41796. */
  41797. get: function () {
  41798. return this._position == null;
  41799. },
  41800. enumerable: true,
  41801. configurable: true
  41802. });
  41803. Object.defineProperty(Prim2DBase.prototype, "pointerEventObservable", {
  41804. /**
  41805. * Interaction with the primitive can be create using this Observable. See the PrimitivePointerInfo class for more information
  41806. */
  41807. get: function () {
  41808. return this._pointerEventObservable;
  41809. },
  41810. enumerable: true,
  41811. configurable: true
  41812. });
  41813. Object.defineProperty(Prim2DBase.prototype, "zActualOrderChangedObservable", {
  41814. get: function () {
  41815. if (!this._actualZOrderChangedObservable) {
  41816. this._actualZOrderChangedObservable = new BABYLON.Observable();
  41817. }
  41818. return this._actualZOrderChangedObservable;
  41819. },
  41820. enumerable: true,
  41821. configurable: true
  41822. });
  41823. Prim2DBase.prototype.findById = function (id) {
  41824. if (this._id === id) {
  41825. return this;
  41826. }
  41827. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  41828. var child = _a[_i];
  41829. var r = child.findById(id);
  41830. if (r != null) {
  41831. return r;
  41832. }
  41833. }
  41834. };
  41835. Prim2DBase.prototype.onZOrderChanged = function () {
  41836. };
  41837. Prim2DBase.prototype.levelIntersect = function (intersectInfo) {
  41838. return false;
  41839. };
  41840. /**
  41841. * Capture all the Events of the given PointerId for this primitive.
  41842. * Don't forget to call releasePointerEventsCapture when done.
  41843. * @param pointerId the Id of the pointer to capture the events from.
  41844. */
  41845. Prim2DBase.prototype.setPointerEventCapture = function (pointerId) {
  41846. return this.owner._setPointerCapture(pointerId, this);
  41847. };
  41848. /**
  41849. * Release a captured pointer made with setPointerEventCapture.
  41850. * @param pointerId the Id of the pointer to release the capture from.
  41851. */
  41852. Prim2DBase.prototype.releasePointerEventsCapture = function (pointerId) {
  41853. return this.owner._releasePointerCapture(pointerId, this);
  41854. };
  41855. /**
  41856. * Make an intersection test with the primitive, all inputs/outputs are stored in the IntersectInfo2D class, see its documentation for more information.
  41857. * @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.
  41858. */
  41859. Prim2DBase.prototype.intersect = function (intersectInfo) {
  41860. if (!intersectInfo) {
  41861. return false;
  41862. }
  41863. // If this is null it means this method is call for the first level, initialize stuffs
  41864. var firstLevel = !intersectInfo._globalPickPosition;
  41865. if (firstLevel) {
  41866. // 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).
  41867. intersectInfo._globalPickPosition = BABYLON.Vector2.Zero();
  41868. BABYLON.Vector2.TransformToRef(intersectInfo.pickPosition, this.globalTransform, intersectInfo._globalPickPosition);
  41869. intersectInfo._localPickPosition = intersectInfo.pickPosition.clone();
  41870. intersectInfo.intersectedPrimitives = new Array();
  41871. intersectInfo.topMostIntersectedPrimitive = null;
  41872. }
  41873. if (!intersectInfo.intersectHidden && !this.isVisible) {
  41874. return false;
  41875. }
  41876. var id = this.id;
  41877. if (id != null && id.indexOf("__cachedSpriteOfGroup__") === 0) {
  41878. var ownerGroup = this.getExternalData("__cachedGroup__");
  41879. return ownerGroup.intersect(intersectInfo);
  41880. }
  41881. // If we're testing a cachedGroup, we must reject pointer outside its levelBoundingInfo because children primitives could be partially clipped outside so we must not accept them as intersected when it's the case (because they're not visually visible).
  41882. var isIntersectionTest = false;
  41883. if (this instanceof BABYLON.Group2D) {
  41884. var g = this;
  41885. isIntersectionTest = g.isCachedGroup;
  41886. }
  41887. if (isIntersectionTest && !this.levelBoundingInfo.doesIntersect(intersectInfo._localPickPosition)) {
  41888. // Important to call this before each return to allow a good recursion next time this intersectInfo is reused
  41889. intersectInfo._exit(firstLevel);
  41890. return false;
  41891. }
  41892. // Fast rejection test with boundingInfo
  41893. if (this.isPickable && !this.boundingInfo.doesIntersect(intersectInfo._localPickPosition)) {
  41894. // Important to call this before each return to allow a good recursion next time this intersectInfo is reused
  41895. intersectInfo._exit(firstLevel);
  41896. return false;
  41897. }
  41898. // We hit the boundingInfo that bounds this primitive and its children, now we have to test on the primitive of this level
  41899. var levelIntersectRes = false;
  41900. if (this.isPickable) {
  41901. levelIntersectRes = this.levelIntersect(intersectInfo);
  41902. if (levelIntersectRes) {
  41903. var pii = new PrimitiveIntersectedInfo(this, intersectInfo._localPickPosition.clone());
  41904. intersectInfo.intersectedPrimitives.push(pii);
  41905. if (!intersectInfo.topMostIntersectedPrimitive || (intersectInfo.topMostIntersectedPrimitive.prim.actualZOffset > pii.prim.actualZOffset)) {
  41906. intersectInfo.topMostIntersectedPrimitive = pii;
  41907. }
  41908. // If we must stop at the first intersection, we're done, quit!
  41909. if (intersectInfo.findFirstOnly) {
  41910. intersectInfo._exit(firstLevel);
  41911. return true;
  41912. }
  41913. }
  41914. }
  41915. // Recurse to children if needed
  41916. if (!levelIntersectRes || !intersectInfo.findFirstOnly) {
  41917. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  41918. var curChild = _a[_i];
  41919. // Don't test primitive not pick able or if it's hidden and we don't test hidden ones
  41920. if ((!curChild.isPickable && curChild.isContainer) || (!intersectInfo.intersectHidden && !curChild.isVisible)) {
  41921. continue;
  41922. }
  41923. // Must compute the localPickLocation for the children level
  41924. BABYLON.Vector2.TransformToRef(intersectInfo._globalPickPosition, curChild.invGlobalTransform, intersectInfo._localPickPosition);
  41925. // If we got an intersection with the child and we only need to find the first one, quit!
  41926. if (curChild.intersect(intersectInfo) && intersectInfo.findFirstOnly) {
  41927. intersectInfo._exit(firstLevel);
  41928. return true;
  41929. }
  41930. }
  41931. }
  41932. intersectInfo._exit(firstLevel);
  41933. return intersectInfo.isIntersected;
  41934. };
  41935. /**
  41936. * Move a child object into a new position regarding its siblings to change its rendering order.
  41937. * You can also use the shortcut methods to move top/bottom: moveChildToTop, moveChildToBottom, moveToTop, moveToBottom.
  41938. * @param child the object to move
  41939. * @param previous the object which will be before "child", if child has to be the first among sibling, set "previous" to null.
  41940. */
  41941. Prim2DBase.prototype.moveChild = function (child, previous) {
  41942. if (child.parent !== this) {
  41943. return false;
  41944. }
  41945. var childIndex = this._children.indexOf(child);
  41946. var prevIndex = previous ? this._children.indexOf(previous) : -1;
  41947. if (!this._isFlagSet(BABYLON.SmartPropertyPrim.flagChildrenFlatZOrder)) {
  41948. this._setFlags(BABYLON.SmartPropertyPrim.flagZOrderDirty);
  41949. this._firstZDirtyIndex = Math.min(this._firstZDirtyIndex, prevIndex + 1);
  41950. }
  41951. this._children.splice(prevIndex + 1, 0, this._children.splice(childIndex, 1)[0]);
  41952. return true;
  41953. };
  41954. /**
  41955. * Move the given child so it's displayed on the top of all its siblings
  41956. * @param child the primitive to move to the top
  41957. */
  41958. Prim2DBase.prototype.moveChildToTop = function (child) {
  41959. return this.moveChild(child, this._children[this._children.length - 1]);
  41960. };
  41961. /**
  41962. * Move the given child so it's displayed on the bottom of all its siblings
  41963. * @param child the primitive to move to the top
  41964. */
  41965. Prim2DBase.prototype.moveChildToBottom = function (child) {
  41966. return this.moveChild(child, null);
  41967. };
  41968. /**
  41969. * Move this primitive to be at the top among all its sibling
  41970. */
  41971. Prim2DBase.prototype.moveToTop = function () {
  41972. if (this.parent == null) {
  41973. return false;
  41974. }
  41975. return this.parent.moveChildToTop(this);
  41976. };
  41977. /**
  41978. * Move this primitive to be at the bottom among all its sibling
  41979. */
  41980. Prim2DBase.prototype.moveToBottom = function () {
  41981. if (this.parent == null) {
  41982. return false;
  41983. }
  41984. return this.parent.moveChildToBottom(this);
  41985. };
  41986. Prim2DBase.prototype.addChild = function (child) {
  41987. child._parent = this;
  41988. this._boundingBoxDirty();
  41989. var flat = this._isFlagSet(BABYLON.SmartPropertyPrim.flagChildrenFlatZOrder);
  41990. if (flat) {
  41991. child._setFlags(BABYLON.SmartPropertyPrim.flagChildrenFlatZOrder);
  41992. child._setZOrder(this._zOrder, true);
  41993. child._zMax = this._zOrder;
  41994. }
  41995. else {
  41996. this._setFlags(BABYLON.SmartPropertyPrim.flagZOrderDirty);
  41997. }
  41998. var length = this._children.push(child);
  41999. this._firstZDirtyIndex = Math.min(this._firstZDirtyIndex, length - 1);
  42000. };
  42001. /**
  42002. * Dispose the primitive, remove it from its parent.
  42003. */
  42004. Prim2DBase.prototype.dispose = function () {
  42005. if (!_super.prototype.dispose.call(this)) {
  42006. return false;
  42007. }
  42008. if (this._actionManager) {
  42009. this._actionManager.dispose();
  42010. this._actionManager = null;
  42011. }
  42012. // If there's a parent, remove this object from its parent list
  42013. if (this._parent) {
  42014. if (this instanceof BABYLON.Group2D) {
  42015. var g = this;
  42016. if (g.isRenderableGroup) {
  42017. var parentRenderable = this.parent.traverseUp(function (p) { return (p instanceof BABYLON.Group2D && p.isRenderableGroup); });
  42018. if (parentRenderable != null) {
  42019. var l = parentRenderable._renderableData._childrenRenderableGroups;
  42020. var i_1 = l.indexOf(g);
  42021. if (i_1 !== -1) {
  42022. l.splice(i_1, 1);
  42023. }
  42024. }
  42025. }
  42026. }
  42027. var i = this._parent._children.indexOf(this);
  42028. if (i !== undefined) {
  42029. this._parent._children.splice(i, 1);
  42030. }
  42031. this._parent = null;
  42032. }
  42033. // Recurse dispose to children
  42034. if (this._children) {
  42035. while (this._children.length > 0) {
  42036. this._children[this._children.length - 1].dispose();
  42037. }
  42038. }
  42039. return true;
  42040. };
  42041. Prim2DBase.prototype.onPrimBecomesDirty = function () {
  42042. if (this._renderGroup && !this._isFlagSet(BABYLON.SmartPropertyPrim.flagPrimInDirtyList)) {
  42043. this._renderGroup._addPrimToDirtyList(this);
  42044. this._setFlags(BABYLON.SmartPropertyPrim.flagPrimInDirtyList);
  42045. }
  42046. };
  42047. Prim2DBase.prototype._needPrepare = function () {
  42048. return this._areSomeFlagsSet(BABYLON.SmartPropertyPrim.flagVisibilityChanged | BABYLON.SmartPropertyPrim.flagModelDirty | BABYLON.SmartPropertyPrim.flagNeedRefresh) || (this._instanceDirtyFlags !== 0) || (this._globalTransformProcessStep !== this._globalTransformStep);
  42049. };
  42050. Prim2DBase.prototype._prepareRender = function (context) {
  42051. this._prepareRenderPre(context);
  42052. this._prepareRenderPost(context);
  42053. };
  42054. Prim2DBase.prototype._prepareRenderPre = function (context) {
  42055. };
  42056. Prim2DBase.prototype._prepareRenderPost = function (context) {
  42057. // Don't recurse if it's a renderable group, the content will be processed by the group itself
  42058. if (this instanceof BABYLON.Group2D) {
  42059. var self = this;
  42060. if (self.isRenderableGroup) {
  42061. return;
  42062. }
  42063. }
  42064. // Check if we need to recurse the prepare to children primitives
  42065. // - must have children
  42066. // - the global transform of this level have changed, or
  42067. // - the visible state of primitive has changed
  42068. if (this._children.length > 0 && ((this._globalTransformProcessStep !== this._globalTransformStep) ||
  42069. this.checkPropertiesDirty(Prim2DBase.isVisibleProperty.flagId))) {
  42070. this._children.forEach(function (c) {
  42071. // As usual stop the recursion if we meet a renderable group
  42072. if (!(c instanceof BABYLON.Group2D && c.isRenderableGroup)) {
  42073. c._prepareRender(context);
  42074. }
  42075. });
  42076. }
  42077. // Finally reset the dirty flags as we've processed everything
  42078. this._clearFlags(BABYLON.SmartPropertyPrim.flagModelDirty);
  42079. this._instanceDirtyFlags = 0;
  42080. };
  42081. Prim2DBase.prototype._canvasPreInit = function (settings) {
  42082. };
  42083. Prim2DBase.CheckParent = function (parent) {
  42084. //if (!Prim2DBase._isCanvasInit && !parent) {
  42085. // 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)");
  42086. //}
  42087. };
  42088. Prim2DBase.prototype.updateCachedStatesOf = function (list, recurse) {
  42089. for (var _i = 0, list_1 = list; _i < list_1.length; _i++) {
  42090. var cur = list_1[_i];
  42091. cur.updateCachedStates(recurse);
  42092. }
  42093. };
  42094. Prim2DBase.prototype._parentLayoutDirty = function () {
  42095. if (!this._parent || this._parent.isDisposed) {
  42096. return;
  42097. }
  42098. this._parent._setLayoutDirty();
  42099. };
  42100. Prim2DBase.prototype._setLayoutDirty = function () {
  42101. this.onPrimBecomesDirty();
  42102. this._setFlags(BABYLON.SmartPropertyPrim.flagLayoutDirty);
  42103. };
  42104. Prim2DBase.prototype._checkPositionChange = function () {
  42105. if (this.parent && this.parent.layoutEngine.isChildPositionAllowed === false) {
  42106. console.log("Can't manually set the position of " + this.id + ", the Layout Engine of its parent doesn't allow it");
  42107. return false;
  42108. }
  42109. return true;
  42110. };
  42111. Prim2DBase.prototype._positioningDirty = function () {
  42112. this.onPrimBecomesDirty();
  42113. this._setFlags(BABYLON.SmartPropertyPrim.flagPositioningDirty);
  42114. };
  42115. Prim2DBase.prototype._spreadActualOpacityChanged = function () {
  42116. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  42117. var child = _a[_i];
  42118. child._setFlags(BABYLON.SmartPropertyPrim.flagActualOpacityDirty);
  42119. child._updateRenderMode();
  42120. child.onPrimBecomesDirty();
  42121. child._spreadActualOpacityChanged();
  42122. }
  42123. };
  42124. Prim2DBase.prototype._changeLayoutEngine = function (engine) {
  42125. this._layoutEngine = engine;
  42126. };
  42127. Prim2DBase.prototype._updateLocalTransform = function () {
  42128. var tflags = Prim2DBase.actualPositionProperty.flagId | Prim2DBase.rotationProperty.flagId | Prim2DBase.scaleProperty.flagId | Prim2DBase.scaleXProperty.flagId | Prim2DBase.scaleYProperty.flagId | Prim2DBase.originProperty.flagId;
  42129. if (this.checkPropertiesDirty(tflags)) {
  42130. if (this.owner) {
  42131. this.owner.addupdateLocalTransformCounter(1);
  42132. }
  42133. var rot = BABYLON.Quaternion.RotationAxis(new BABYLON.Vector3(0, 0, 1), this._rotation);
  42134. var local;
  42135. var pos = this._position ? this.position : this.layoutAreaPos;
  42136. if (this._origin.x === 0 && this._origin.y === 0) {
  42137. local = BABYLON.Matrix.Compose(new BABYLON.Vector3(this._scale.x, this._scale.y, 1), rot, new BABYLON.Vector3(pos.x, pos.y, 0));
  42138. this._localTransform = local;
  42139. }
  42140. else {
  42141. // -Origin offset
  42142. var as = this.actualSize;
  42143. BABYLON.Matrix.TranslationToRef((-as.width * this._origin.x), (-as.height * this._origin.y), 0, Prim2DBase._t0);
  42144. // -Origin * rotation
  42145. rot.toRotationMatrix(Prim2DBase._t1);
  42146. Prim2DBase._t0.multiplyToRef(Prim2DBase._t1, Prim2DBase._t2);
  42147. // -Origin * rotation * scale
  42148. BABYLON.Matrix.ScalingToRef(this._scale.x, this._scale.y, 1, Prim2DBase._t0);
  42149. Prim2DBase._t2.multiplyToRef(Prim2DBase._t0, Prim2DBase._t1);
  42150. // -Origin * rotation * scale * (Origin + Position)
  42151. BABYLON.Matrix.TranslationToRef((as.width * this._origin.x) + pos.x, (as.height * this._origin.y) + pos.y, 0, Prim2DBase._t2);
  42152. Prim2DBase._t1.multiplyToRef(Prim2DBase._t2, this._localTransform);
  42153. }
  42154. this.clearPropertiesDirty(tflags);
  42155. this._setFlags(BABYLON.SmartPropertyPrim.flagGlobalTransformDirty);
  42156. return true;
  42157. }
  42158. return false;
  42159. };
  42160. Prim2DBase.prototype.updateCachedStates = function (recurse) {
  42161. if (this.isDisposed) {
  42162. return;
  42163. }
  42164. this.owner.addCachedGroupRenderCounter(1);
  42165. // Check if the parent is synced
  42166. if (this._parent && ((this._parent._globalTransformProcessStep !== this.owner._globalTransformProcessStep) || this._parent._areSomeFlagsSet(BABYLON.SmartPropertyPrim.flagLayoutDirty | BABYLON.SmartPropertyPrim.flagPositioningDirty | BABYLON.SmartPropertyPrim.flagZOrderDirty))) {
  42167. this._parent.updateCachedStates(false);
  42168. }
  42169. // Update Z-Order if needed
  42170. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagZOrderDirty)) {
  42171. this._updateZOrder();
  42172. }
  42173. // Update actualSize only if there' not positioning to recompute and the size changed
  42174. // Otherwise positioning will take care of it.
  42175. var sizeDirty = this.checkPropertiesDirty(Prim2DBase.sizeProperty.flagId);
  42176. if (!this._isFlagSet(BABYLON.SmartPropertyPrim.flagLayoutDirty) && !this._isFlagSet(BABYLON.SmartPropertyPrim.flagPositioningDirty) && sizeDirty) {
  42177. var size = this.size;
  42178. if (size) {
  42179. if (this.size.width != null) {
  42180. this.actualSize.width = this.size.width;
  42181. }
  42182. if (this.size.height != null) {
  42183. this.actualSize.height = this.size.height;
  42184. }
  42185. this.clearPropertiesDirty(Prim2DBase.sizeProperty.flagId);
  42186. }
  42187. }
  42188. var positioningDirty = this._isFlagSet(BABYLON.SmartPropertyPrim.flagPositioningDirty);
  42189. var positioningComputed = positioningDirty && !this._isFlagSet(BABYLON.SmartPropertyPrim.flagPositioningDirty);
  42190. // Check for layout update
  42191. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagLayoutDirty)) {
  42192. this.owner.addUpdateLayoutCounter(1);
  42193. this._layoutEngine.updateLayout(this);
  42194. this._clearFlags(BABYLON.SmartPropertyPrim.flagLayoutDirty);
  42195. }
  42196. var autoContentChanged = false;
  42197. if (this.isSizeAuto) {
  42198. if (!this._lastAutoSizeArea) {
  42199. autoContentChanged = this.actualSize !== null;
  42200. }
  42201. else {
  42202. autoContentChanged = (!this._lastAutoSizeArea.equals(this.actualSize));
  42203. }
  42204. }
  42205. // Check for positioning update
  42206. if (!positioningComputed && (autoContentChanged || sizeDirty || this._isFlagSet(BABYLON.SmartPropertyPrim.flagPositioningDirty) || (this._parent && !this._parent.contentArea.equals(this._parentContentArea)))) {
  42207. this._updatePositioning();
  42208. this._clearFlags(BABYLON.SmartPropertyPrim.flagPositioningDirty);
  42209. if (sizeDirty) {
  42210. this.clearPropertiesDirty(Prim2DBase.sizeProperty.flagId);
  42211. }
  42212. positioningComputed = true;
  42213. }
  42214. if (positioningComputed && this._parent) {
  42215. this._parentContentArea.copyFrom(this._parent.contentArea);
  42216. }
  42217. // Check if we must update this prim
  42218. if (this === this.owner || this._globalTransformProcessStep !== this.owner._globalTransformProcessStep) {
  42219. this.owner.addUpdateGlobalTransformCounter(1);
  42220. var curVisibleState = this.isVisible;
  42221. this.isVisible = (!this._parent || this._parent.isVisible) && this.levelVisible;
  42222. // Detect a change of visibility
  42223. this._changeFlags(BABYLON.SmartPropertyPrim.flagVisibilityChanged, curVisibleState !== this.isVisible);
  42224. // Get/compute the localTransform
  42225. var localDirty = this._updateLocalTransform();
  42226. var parentPaddingChanged = false;
  42227. var parentPaddingOffset = Prim2DBase._v0;
  42228. if (this._parent) {
  42229. parentPaddingOffset = this._parent._paddingOffset;
  42230. parentPaddingChanged = !parentPaddingOffset.equals(this._parentPaddingOffset);
  42231. }
  42232. // Check if there are changes in the parent that will force us to update the global matrix
  42233. var parentDirty = (this._parent != null) ? (this._parent._globalTransformStep !== this._parentTransformStep) : false;
  42234. // Check if we have to update the globalTransform
  42235. if (!this._globalTransform || localDirty || parentDirty || parentPaddingChanged || this._areSomeFlagsSet(BABYLON.SmartPropertyPrim.flagGlobalTransformDirty)) {
  42236. var globalTransform = this._parent ? this._parent._globalTransform : null;
  42237. var localTransform = void 0;
  42238. Prim2DBase._transMtx.copyFrom(this._localTransform);
  42239. Prim2DBase._transMtx.m[12] += this._marginOffset.x + parentPaddingOffset.x;
  42240. Prim2DBase._transMtx.m[13] += this._marginOffset.y + parentPaddingOffset.y;
  42241. localTransform = Prim2DBase._transMtx;
  42242. this._globalTransform = this._parent ? localTransform.multiply(globalTransform) : localTransform.clone();
  42243. this._invGlobalTransform = BABYLON.Matrix.Invert(this._globalTransform);
  42244. this._globalTransformStep = this.owner._globalTransformProcessStep + 1;
  42245. this._parentTransformStep = this._parent ? this._parent._globalTransformStep : 0;
  42246. this._clearFlags(BABYLON.SmartPropertyPrim.flagGlobalTransformDirty);
  42247. }
  42248. this._globalTransformProcessStep = this.owner._globalTransformProcessStep;
  42249. }
  42250. if (recurse) {
  42251. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  42252. var child = _a[_i];
  42253. // Stop the recursion if we meet a renderable group
  42254. child.updateCachedStates(!(child instanceof BABYLON.Group2D && child.isRenderableGroup));
  42255. }
  42256. }
  42257. };
  42258. Prim2DBase.prototype._updatePositioning = function () {
  42259. if (this.owner) {
  42260. this.owner.addUpdatePositioningCounter(1);
  42261. }
  42262. // From this point we assume that the primitive layoutArea is computed and up to date.
  42263. // We know have to :
  42264. // 1. Determine the PaddingArea and the ActualPosition based on the margin/marginAlignment properties, which will also set the size property of the primitive
  42265. // 2. Determine the contentArea based on the padding property.
  42266. // 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
  42267. if (!this._hasMargin && (this.actualSize.width == null || this.actualSize.height == null)) {
  42268. if (this.actualSize.width == null) {
  42269. this.marginAlignment.horizontal = PrimitiveAlignment.AlignStretch;
  42270. }
  42271. if (this.actualSize.height == null) {
  42272. this.marginAlignment.vertical = PrimitiveAlignment.AlignStretch;
  42273. }
  42274. }
  42275. // Apply margin
  42276. if (this._hasMargin) {
  42277. this.margin.computeWithAlignment(this.layoutArea, this.size || this.actualSize, this.marginAlignment, this._marginOffset, Prim2DBase._size);
  42278. this.actualSize = Prim2DBase._size.clone();
  42279. }
  42280. var isSizeAuto = this.isSizeAuto;
  42281. if (this._hasPadding) {
  42282. // Two cases from here: the size of the Primitive is Auto, its content can't be shrink, so me resize the primitive itself
  42283. if (isSizeAuto) {
  42284. var content = this.size.clone();
  42285. this._getActualSizeFromContentToRef(content, Prim2DBase._icArea);
  42286. this.padding.enlarge(Prim2DBase._icArea, this._paddingOffset, Prim2DBase._size);
  42287. this._contentArea.copyFrom(content);
  42288. this.actualSize = Prim2DBase._size.clone();
  42289. // Changing the padding has resize the prim, which forces us to recompute margin again
  42290. if (this._hasMargin) {
  42291. this.margin.computeWithAlignment(this.layoutArea, Prim2DBase._size, this.marginAlignment, this._marginOffset, Prim2DBase._size);
  42292. }
  42293. }
  42294. else {
  42295. this._getInitialContentAreaToRef(this.actualSize, Prim2DBase._icPos, Prim2DBase._icArea);
  42296. Prim2DBase._icArea.width = Math.max(0, Prim2DBase._icArea.width);
  42297. Prim2DBase._icArea.height = Math.max(0, Prim2DBase._icArea.height);
  42298. this.padding.compute(Prim2DBase._icArea, this._paddingOffset, Prim2DBase._size);
  42299. this._paddingOffset.x += Prim2DBase._icPos.x;
  42300. this._paddingOffset.y += Prim2DBase._icPos.y;
  42301. this._contentArea.copyFrom(Prim2DBase._size);
  42302. }
  42303. }
  42304. else {
  42305. this._getInitialContentAreaToRef(this.actualSize, Prim2DBase._icPos, Prim2DBase._icArea);
  42306. Prim2DBase._icArea.width = Math.max(0, Prim2DBase._icArea.width);
  42307. Prim2DBase._icArea.height = Math.max(0, Prim2DBase._icArea.height);
  42308. this._paddingOffset.copyFrom(Prim2DBase._icPos);
  42309. this._contentArea.copyFrom(Prim2DBase._icArea);
  42310. }
  42311. if (!this._position) {
  42312. var aPos = new BABYLON.Vector2(this.layoutAreaPos.x + this._marginOffset.x, this.layoutAreaPos.y + this._marginOffset.y);
  42313. this.actualPosition = aPos;
  42314. }
  42315. if (isSizeAuto) {
  42316. this._lastAutoSizeArea = this.actualSize;
  42317. }
  42318. };
  42319. Object.defineProperty(Prim2DBase.prototype, "contentArea", {
  42320. /**
  42321. * Get the content are of this primitive, this area is computed using the padding property and also possibly the primitive type itself.
  42322. * Children of this primitive will be positioned relative to the bottom/left corner of this area.
  42323. */
  42324. get: function () {
  42325. // Check for positioning update
  42326. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagPositioningDirty)) {
  42327. this._updatePositioning();
  42328. this._clearFlags(BABYLON.SmartPropertyPrim.flagPositioningDirty);
  42329. }
  42330. return this._contentArea;
  42331. },
  42332. enumerable: true,
  42333. configurable: true
  42334. });
  42335. Prim2DBase.prototype._patchHierarchy = function (owner) {
  42336. this._owner = owner;
  42337. // The only place we initialize the _renderGroup is this method, if it's set, we already been there, no need to execute more
  42338. if (this._renderGroup != null) {
  42339. return;
  42340. }
  42341. if (this instanceof BABYLON.Group2D) {
  42342. var group = this;
  42343. group.detectGroupStates();
  42344. if (group._trackedNode && !group._isFlagSet(BABYLON.SmartPropertyPrim.flagTrackedGroup)) {
  42345. group.owner._registerTrackedNode(this);
  42346. }
  42347. }
  42348. this._renderGroup = this.traverseUp(function (p) { return p instanceof BABYLON.Group2D && p.isRenderableGroup; });
  42349. if (this._parent) {
  42350. this._parentLayoutDirty();
  42351. }
  42352. // Make sure the prim is in the dirtyList if it should be
  42353. if (this._renderGroup && this.isDirty) {
  42354. var list = this._renderGroup._renderableData._primDirtyList;
  42355. var i = list.indexOf(this);
  42356. if (i === -1) {
  42357. list.push(this);
  42358. }
  42359. }
  42360. // Recurse
  42361. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  42362. var child = _a[_i];
  42363. child._hierarchyDepth = this._hierarchyDepth + 1;
  42364. child._patchHierarchy(owner);
  42365. }
  42366. };
  42367. Prim2DBase.prototype._updateZOrder = function () {
  42368. var prevLinPos = this._primLinearPosition;
  42369. var startI = 0;
  42370. var startZ = this._zOrder;
  42371. // 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
  42372. var childrenCount = this._children.length;
  42373. if (this._firstZDirtyIndex > 0) {
  42374. if ((this._firstZDirtyIndex - 1) < childrenCount) {
  42375. var prevPrim = this._children[this._firstZDirtyIndex - 1];
  42376. prevLinPos = prevPrim._primLinearPosition;
  42377. startI = this._firstZDirtyIndex - 1;
  42378. startZ = prevPrim._zOrder;
  42379. }
  42380. }
  42381. var startPos = prevLinPos;
  42382. // Update the linear position of the primitive from the first one to the last inside this primitive, compute the total number of prim traversed
  42383. Prim2DBase._totalCount = 0;
  42384. for (var i = startI; i < childrenCount; i++) {
  42385. var child = this._children[i];
  42386. prevLinPos = child._updatePrimitiveLinearPosition(prevLinPos);
  42387. }
  42388. // Compute the new Z-Order for all the primitives
  42389. // Add 20% to the current total count to reserve space for future insertions, except if we're rebuilding due to a zMinDelta reached
  42390. var zDelta = (this._zMax - startZ) / (Prim2DBase._totalCount * (Prim2DBase._zRebuildReentrency ? 1 : 1.2));
  42391. // 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.
  42392. if (zDelta < BABYLON.Canvas2D._zMinDelta) {
  42393. // 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...
  42394. if (Prim2DBase._zRebuildReentrency) {
  42395. var p = this._parent;
  42396. if (p == null) {
  42397. // 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...)
  42398. console.log("Can't compute Z-Order for " + this.id + "'s children, zDelta is too small, Z-Order is now in an unstable state");
  42399. Prim2DBase._zRebuildReentrency = false;
  42400. return;
  42401. }
  42402. p._firstZDirtyIndex = 0;
  42403. return p._updateZOrder();
  42404. }
  42405. Prim2DBase._zRebuildReentrency = true;
  42406. this._firstZDirtyIndex = 0;
  42407. this._updateZOrder();
  42408. Prim2DBase._zRebuildReentrency = false;
  42409. }
  42410. for (var i = startI; i < childrenCount; i++) {
  42411. var child = this._children[i];
  42412. child._updatePrimitiveZOrder(startPos, startZ, zDelta);
  42413. }
  42414. // Notify the Observers that we found during the Z change (we do it after to avoid any kind of re-entrance)
  42415. for (var _i = 0, _a = Prim2DBase._zOrderChangedNotifList; _i < _a.length; _i++) {
  42416. var p = _a[_i];
  42417. p._actualZOrderChangedObservable.notifyObservers(p.actualZOffset);
  42418. }
  42419. Prim2DBase._zOrderChangedNotifList.splice(0);
  42420. this._firstZDirtyIndex = Prim2DBase._bigInt;
  42421. this._clearFlags(BABYLON.SmartPropertyPrim.flagZOrderDirty);
  42422. };
  42423. Prim2DBase.prototype._updatePrimitiveLinearPosition = function (prevLinPos) {
  42424. if (this.isManualZOrder) {
  42425. return prevLinPos;
  42426. }
  42427. this._primLinearPosition = ++prevLinPos;
  42428. Prim2DBase._totalCount++;
  42429. // Check for the FlatZOrder, which means the children won't have a dedicated Z-Order but will all share the same (unique) one.
  42430. if (!this._isFlagSet(BABYLON.SmartPropertyPrim.flagChildrenFlatZOrder)) {
  42431. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  42432. var child = _a[_i];
  42433. prevLinPos = child._updatePrimitiveLinearPosition(prevLinPos);
  42434. }
  42435. }
  42436. return prevLinPos;
  42437. };
  42438. Prim2DBase.prototype._updatePrimitiveZOrder = function (startPos, startZ, deltaZ) {
  42439. if (this.isManualZOrder) {
  42440. return null;
  42441. }
  42442. var newZ = startZ + ((this._primLinearPosition - startPos) * deltaZ);
  42443. var isFlat = this._isFlagSet(BABYLON.SmartPropertyPrim.flagChildrenFlatZOrder);
  42444. this._setZOrder(newZ, false);
  42445. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagZOrderDirty)) {
  42446. this._firstZDirtyIndex = Prim2DBase._bigInt;
  42447. this._clearFlags(BABYLON.SmartPropertyPrim.flagZOrderDirty);
  42448. }
  42449. var curZ = newZ;
  42450. // Check for the FlatZOrder, which means the children won't have a dedicated Z-Order but will all share the same (unique) one.
  42451. if (isFlat) {
  42452. if (this._children.length > 0) {
  42453. //let childrenZOrder = startZ + ((this._children[0]._primLinearPosition - startPos) * deltaZ);
  42454. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  42455. var child = _a[_i];
  42456. child._updatePrimitiveFlatZOrder(this._zOrder);
  42457. }
  42458. }
  42459. }
  42460. else {
  42461. for (var _b = 0, _c = this._children; _b < _c.length; _b++) {
  42462. var child = _c[_b];
  42463. var r = child._updatePrimitiveZOrder(startPos, startZ, deltaZ);
  42464. if (r != null) {
  42465. curZ = r;
  42466. }
  42467. }
  42468. }
  42469. this._zMax = isFlat ? newZ : (curZ + deltaZ);
  42470. return curZ;
  42471. };
  42472. Prim2DBase.prototype._updatePrimitiveFlatZOrder = function (newZ) {
  42473. if (this.isManualZOrder) {
  42474. return;
  42475. }
  42476. this._setZOrder(newZ, false);
  42477. this._zMax = newZ;
  42478. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagZOrderDirty)) {
  42479. this._firstZDirtyIndex = Prim2DBase._bigInt;
  42480. this._clearFlags(BABYLON.SmartPropertyPrim.flagZOrderDirty);
  42481. }
  42482. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  42483. var child = _a[_i];
  42484. child._updatePrimitiveFlatZOrder(newZ);
  42485. }
  42486. };
  42487. Prim2DBase.prototype._setZOrder = function (newZ, directEmit) {
  42488. if (newZ !== this._zOrder) {
  42489. this._zOrder = newZ;
  42490. this.onPrimBecomesDirty();
  42491. this.onZOrderChanged();
  42492. if (this._actualZOrderChangedObservable && this._actualZOrderChangedObservable.hasObservers()) {
  42493. if (directEmit) {
  42494. this._actualZOrderChangedObservable.notifyObservers(newZ);
  42495. }
  42496. else {
  42497. Prim2DBase._zOrderChangedNotifList.push(this);
  42498. }
  42499. }
  42500. }
  42501. };
  42502. Prim2DBase.prototype._updateRenderMode = function () {
  42503. };
  42504. /**
  42505. * This method is used to alter the contentArea of the Primitive before margin is applied.
  42506. * 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.
  42507. * @param primSize the current size of the primitive
  42508. * @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!
  42509. * @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!
  42510. */
  42511. Prim2DBase.prototype._getInitialContentAreaToRef = function (primSize, initialContentPosition, initialContentArea) {
  42512. initialContentArea.copyFrom(primSize);
  42513. initialContentPosition.x = initialContentPosition.y = 0;
  42514. };
  42515. /**
  42516. * This method is used to calculate the new size of the primitive based on the content which must stay the same
  42517. * Check the Rectangle2D implementation for a concrete application.
  42518. * @param primSize the current size of the primitive
  42519. * @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!
  42520. */
  42521. Prim2DBase.prototype._getActualSizeFromContentToRef = function (primSize, newPrimSize) {
  42522. newPrimSize.copyFrom(primSize);
  42523. };
  42524. Prim2DBase.PRIM2DBASE_PROPCOUNT = 16;
  42525. Prim2DBase._bigInt = Math.pow(2, 30);
  42526. Prim2DBase._nullPosition = BABYLON.Vector2.Zero();
  42527. Prim2DBase.boundinbBoxReentrency = false;
  42528. Prim2DBase.nullSize = BABYLON.Size.Zero();
  42529. Prim2DBase._bMax = BABYLON.Vector2.Zero();
  42530. Prim2DBase._tpsBB = new BABYLON.BoundingInfo2D();
  42531. Prim2DBase._isCanvasInit = false;
  42532. Prim2DBase._t0 = new BABYLON.Matrix();
  42533. Prim2DBase._t1 = new BABYLON.Matrix();
  42534. Prim2DBase._t2 = new BABYLON.Matrix();
  42535. Prim2DBase._v0 = BABYLON.Vector2.Zero(); // Must stay with the value 0,0
  42536. Prim2DBase._transMtx = BABYLON.Matrix.Zero();
  42537. Prim2DBase._icPos = BABYLON.Vector2.Zero();
  42538. Prim2DBase._icArea = BABYLON.Size.Zero();
  42539. Prim2DBase._size = BABYLON.Size.Zero();
  42540. Prim2DBase._zOrderChangedNotifList = new Array();
  42541. Prim2DBase._zRebuildReentrency = false;
  42542. Prim2DBase._totalCount = 0;
  42543. __decorate([
  42544. BABYLON.instanceLevelProperty(1, function (pi) { return Prim2DBase.actualPositionProperty = pi; }, false, false, true)
  42545. ], Prim2DBase.prototype, "actualPosition", null);
  42546. __decorate([
  42547. BABYLON.dynamicLevelProperty(2, function (pi) { return Prim2DBase.positionProperty = pi; }, false, false, true)
  42548. ], Prim2DBase.prototype, "position", null);
  42549. __decorate([
  42550. BABYLON.dynamicLevelProperty(3, function (pi) { return Prim2DBase.sizeProperty = pi; }, false, true)
  42551. ], Prim2DBase.prototype, "size", null);
  42552. __decorate([
  42553. BABYLON.instanceLevelProperty(4, function (pi) { return Prim2DBase.rotationProperty = pi; }, false, true)
  42554. ], Prim2DBase.prototype, "rotation", null);
  42555. __decorate([
  42556. BABYLON.instanceLevelProperty(5, function (pi) { return Prim2DBase.scaleProperty = pi; }, false, true)
  42557. ], Prim2DBase.prototype, "scale", null);
  42558. __decorate([
  42559. BABYLON.dynamicLevelProperty(6, function (pi) { return Prim2DBase.originProperty = pi; }, false, true)
  42560. ], Prim2DBase.prototype, "origin", null);
  42561. __decorate([
  42562. BABYLON.dynamicLevelProperty(7, function (pi) { return Prim2DBase.levelVisibleProperty = pi; })
  42563. ], Prim2DBase.prototype, "levelVisible", null);
  42564. __decorate([
  42565. BABYLON.instanceLevelProperty(8, function (pi) { return Prim2DBase.isVisibleProperty = pi; })
  42566. ], Prim2DBase.prototype, "isVisible", null);
  42567. __decorate([
  42568. BABYLON.instanceLevelProperty(9, function (pi) { return Prim2DBase.zOrderProperty = pi; })
  42569. ], Prim2DBase.prototype, "zOrder", null);
  42570. __decorate([
  42571. BABYLON.dynamicLevelProperty(10, function (pi) { return Prim2DBase.marginProperty = pi; })
  42572. ], Prim2DBase.prototype, "margin", null);
  42573. __decorate([
  42574. BABYLON.dynamicLevelProperty(11, function (pi) { return Prim2DBase.paddingProperty = pi; })
  42575. ], Prim2DBase.prototype, "padding", null);
  42576. __decorate([
  42577. BABYLON.dynamicLevelProperty(12, function (pi) { return Prim2DBase.marginAlignmentProperty = pi; })
  42578. ], Prim2DBase.prototype, "marginAlignment", null);
  42579. __decorate([
  42580. BABYLON.instanceLevelProperty(13, function (pi) { return Prim2DBase.opacityProperty = pi; })
  42581. ], Prim2DBase.prototype, "opacity", null);
  42582. __decorate([
  42583. BABYLON.instanceLevelProperty(14, function (pi) { return Prim2DBase.scaleXProperty = pi; }, false, true)
  42584. ], Prim2DBase.prototype, "scaleX", null);
  42585. __decorate([
  42586. BABYLON.instanceLevelProperty(15, function (pi) { return Prim2DBase.scaleYProperty = pi; }, false, true)
  42587. ], Prim2DBase.prototype, "scaleY", null);
  42588. Prim2DBase = __decorate([
  42589. BABYLON.className("Prim2DBase")
  42590. ], Prim2DBase);
  42591. return Prim2DBase;
  42592. }(BABYLON.SmartPropertyPrim));
  42593. BABYLON.Prim2DBase = Prim2DBase;
  42594. })(BABYLON || (BABYLON = {}));
  42595. var BABYLON;
  42596. (function (BABYLON) {
  42597. var GroupInstanceInfo = (function () {
  42598. function GroupInstanceInfo(owner, mrc, partCount) {
  42599. this._partCount = partCount;
  42600. this.owner = owner;
  42601. this.modelRenderCache = mrc;
  42602. this.modelRenderCache.addRef();
  42603. this.partIndexFromId = new BABYLON.StringDictionary();
  42604. this._usedShaderCategories = new Array(partCount);
  42605. this._strides = new Array(partCount);
  42606. this._opaqueData = null;
  42607. this._alphaTestData = null;
  42608. this._transparentData = null;
  42609. this.opaqueDirty = this.alphaTestDirty = this.transparentDirty = this.transparentOrderDirty = false;
  42610. }
  42611. GroupInstanceInfo.prototype.dispose = function () {
  42612. if (this._isDisposed) {
  42613. return false;
  42614. }
  42615. if (this.modelRenderCache) {
  42616. this.modelRenderCache.dispose();
  42617. this.modelRenderCache = null;
  42618. }
  42619. var engine = this.owner.owner.engine;
  42620. if (this._opaqueData) {
  42621. this._opaqueData.forEach(function (d) { return d.dispose(engine); });
  42622. this._opaqueData = null;
  42623. }
  42624. if (this._alphaTestData) {
  42625. this._alphaTestData.forEach(function (d) { return d.dispose(engine); });
  42626. this._alphaTestData = null;
  42627. }
  42628. if (this._transparentData) {
  42629. this._transparentData.forEach(function (d) { return d.dispose(engine); });
  42630. this._transparentData = null;
  42631. }
  42632. this.partIndexFromId = null;
  42633. this._isDisposed = true;
  42634. return true;
  42635. };
  42636. Object.defineProperty(GroupInstanceInfo.prototype, "hasOpaqueData", {
  42637. get: function () {
  42638. return this._opaqueData != null;
  42639. },
  42640. enumerable: true,
  42641. configurable: true
  42642. });
  42643. Object.defineProperty(GroupInstanceInfo.prototype, "hasAlphaTestData", {
  42644. get: function () {
  42645. return this._alphaTestData != null;
  42646. },
  42647. enumerable: true,
  42648. configurable: true
  42649. });
  42650. Object.defineProperty(GroupInstanceInfo.prototype, "hasTransparentData", {
  42651. get: function () {
  42652. return this._transparentData != null;
  42653. },
  42654. enumerable: true,
  42655. configurable: true
  42656. });
  42657. Object.defineProperty(GroupInstanceInfo.prototype, "opaqueData", {
  42658. get: function () {
  42659. if (!this._opaqueData) {
  42660. this._opaqueData = new Array(this._partCount);
  42661. for (var i = 0; i < this._partCount; i++) {
  42662. this._opaqueData[i] = new GroupInfoPartData(this._strides[i]);
  42663. }
  42664. }
  42665. return this._opaqueData;
  42666. },
  42667. enumerable: true,
  42668. configurable: true
  42669. });
  42670. Object.defineProperty(GroupInstanceInfo.prototype, "alphaTestData", {
  42671. get: function () {
  42672. if (!this._alphaTestData) {
  42673. this._alphaTestData = new Array(this._partCount);
  42674. for (var i = 0; i < this._partCount; i++) {
  42675. this._alphaTestData[i] = new GroupInfoPartData(this._strides[i]);
  42676. }
  42677. }
  42678. return this._alphaTestData;
  42679. },
  42680. enumerable: true,
  42681. configurable: true
  42682. });
  42683. Object.defineProperty(GroupInstanceInfo.prototype, "transparentData", {
  42684. get: function () {
  42685. if (!this._transparentData) {
  42686. this._transparentData = new Array(this._partCount);
  42687. for (var i = 0; i < this._partCount; i++) {
  42688. var zoff = this.modelRenderCache._partData[i]._zBiasOffset;
  42689. this._transparentData[i] = new TransparentGroupInfoPartData(this._strides[i], zoff);
  42690. }
  42691. }
  42692. return this._transparentData;
  42693. },
  42694. enumerable: true,
  42695. configurable: true
  42696. });
  42697. GroupInstanceInfo.prototype.sortTransparentData = function () {
  42698. if (!this.transparentOrderDirty) {
  42699. return;
  42700. }
  42701. for (var i = 0; i < this._transparentData.length; i++) {
  42702. var td = this._transparentData[i];
  42703. td._partData.sort();
  42704. }
  42705. this.transparentOrderDirty = false;
  42706. };
  42707. Object.defineProperty(GroupInstanceInfo.prototype, "usedShaderCategories", {
  42708. get: function () {
  42709. return this._usedShaderCategories;
  42710. },
  42711. enumerable: true,
  42712. configurable: true
  42713. });
  42714. Object.defineProperty(GroupInstanceInfo.prototype, "strides", {
  42715. get: function () {
  42716. return this._strides;
  42717. },
  42718. enumerable: true,
  42719. configurable: true
  42720. });
  42721. return GroupInstanceInfo;
  42722. }());
  42723. BABYLON.GroupInstanceInfo = GroupInstanceInfo;
  42724. var TransparentSegment = (function () {
  42725. function TransparentSegment() {
  42726. this.groupInsanceInfo = null;
  42727. this.startZ = 0;
  42728. this.endZ = 0;
  42729. this.startDataIndex = BABYLON.Prim2DBase._bigInt;
  42730. this.endDataIndex = 0;
  42731. this.partBuffers = null;
  42732. }
  42733. TransparentSegment.prototype.dispose = function (engine) {
  42734. if (this.partBuffers) {
  42735. this.partBuffers.forEach(function (b) { return engine._releaseBuffer(b); });
  42736. this.partBuffers.splice(0);
  42737. this.partBuffers = null;
  42738. }
  42739. };
  42740. return TransparentSegment;
  42741. }());
  42742. BABYLON.TransparentSegment = TransparentSegment;
  42743. var GroupInfoPartData = (function () {
  42744. function GroupInfoPartData(stride) {
  42745. this._partData = null;
  42746. this._partBuffer = null;
  42747. this._partBufferSize = 0;
  42748. this._partData = new BABYLON.DynamicFloatArray(stride / 4, 50);
  42749. this._isDisposed = false;
  42750. }
  42751. GroupInfoPartData.prototype.dispose = function (engine) {
  42752. if (this._isDisposed) {
  42753. return false;
  42754. }
  42755. if (this._partBuffer) {
  42756. engine._releaseBuffer(this._partBuffer);
  42757. this._partBuffer = null;
  42758. }
  42759. this._partData = null;
  42760. this._isDisposed = true;
  42761. };
  42762. return GroupInfoPartData;
  42763. }());
  42764. BABYLON.GroupInfoPartData = GroupInfoPartData;
  42765. var TransparentGroupInfoPartData = (function (_super) {
  42766. __extends(TransparentGroupInfoPartData, _super);
  42767. function TransparentGroupInfoPartData(stride, zoff) {
  42768. _super.call(this, stride);
  42769. this._partData.compareValueOffset = zoff;
  42770. this._partData.sortingAscending = false;
  42771. }
  42772. return TransparentGroupInfoPartData;
  42773. }(GroupInfoPartData));
  42774. BABYLON.TransparentGroupInfoPartData = TransparentGroupInfoPartData;
  42775. var ModelRenderCache = (function () {
  42776. function ModelRenderCache(engine, modelKey) {
  42777. this._engine = engine;
  42778. this._modelKey = modelKey;
  42779. this._nextKey = 1;
  42780. this._refCounter = 1;
  42781. this._partData = null;
  42782. }
  42783. ModelRenderCache.prototype.dispose = function () {
  42784. if (--this._refCounter !== 0) {
  42785. return false;
  42786. }
  42787. // Remove the Model Render Cache from the global dictionary
  42788. var edata = this._engine.getExternalData("__BJSCANVAS2D__");
  42789. if (edata) {
  42790. edata.DisposeModelRenderCache(this);
  42791. }
  42792. return true;
  42793. };
  42794. Object.defineProperty(ModelRenderCache.prototype, "isDisposed", {
  42795. get: function () {
  42796. return this._refCounter <= 0;
  42797. },
  42798. enumerable: true,
  42799. configurable: true
  42800. });
  42801. ModelRenderCache.prototype.addRef = function () {
  42802. return ++this._refCounter;
  42803. };
  42804. Object.defineProperty(ModelRenderCache.prototype, "modelKey", {
  42805. get: function () {
  42806. return this._modelKey;
  42807. },
  42808. enumerable: true,
  42809. configurable: true
  42810. });
  42811. /**
  42812. * Render the model instances
  42813. * @param instanceInfo
  42814. * @param context
  42815. * @return must return true is the rendering succeed, false if the rendering couldn't be done (asset's not yet ready, like Effect)
  42816. */
  42817. ModelRenderCache.prototype.render = function (instanceInfo, context) {
  42818. return true;
  42819. };
  42820. ModelRenderCache.prototype.getPartIndexFromId = function (partId) {
  42821. for (var i = 0; i < this._partData.length; i++) {
  42822. if (this._partData[i]._partId === partId) {
  42823. return i;
  42824. }
  42825. }
  42826. return null;
  42827. };
  42828. ModelRenderCache.prototype.loadInstancingAttributes = function (partId, effect) {
  42829. var i = this.getPartIndexFromId(partId);
  42830. if (i === null) {
  42831. return null;
  42832. }
  42833. var ci = this._partsClassInfo[i];
  42834. var categories = this._partData[i]._partUsedCategories;
  42835. var res = ci.classContent.getInstancingAttributeInfos(effect, categories);
  42836. return res;
  42837. };
  42838. ModelRenderCache.prototype.setupUniforms = function (effect, partIndex, data, elementCount) {
  42839. var pd = this._partData[partIndex];
  42840. var offset = (pd._partDataStride / 4) * elementCount;
  42841. var pci = this._partsClassInfo[partIndex];
  42842. var self = this;
  42843. pci.fullContent.forEach(function (k, v) {
  42844. if (!v.category || pd._partUsedCategories.indexOf(v.category) !== -1) {
  42845. switch (v.dataType) {
  42846. case 4 /* float */:
  42847. {
  42848. var attribOffset = v.instanceOffset.get(pd._partJoinedUsedCategories);
  42849. effect.setFloat(v.attributeName, data.buffer[offset + attribOffset]);
  42850. break;
  42851. }
  42852. case 0 /* Vector2 */:
  42853. {
  42854. var attribOffset = v.instanceOffset.get(pd._partJoinedUsedCategories);
  42855. ModelRenderCache.v2.x = data.buffer[offset + attribOffset + 0];
  42856. ModelRenderCache.v2.y = data.buffer[offset + attribOffset + 1];
  42857. effect.setVector2(v.attributeName, ModelRenderCache.v2);
  42858. break;
  42859. }
  42860. case 5 /* Color3 */:
  42861. case 1 /* Vector3 */:
  42862. {
  42863. var attribOffset = v.instanceOffset.get(pd._partJoinedUsedCategories);
  42864. ModelRenderCache.v3.x = data.buffer[offset + attribOffset + 0];
  42865. ModelRenderCache.v3.y = data.buffer[offset + attribOffset + 1];
  42866. ModelRenderCache.v3.z = data.buffer[offset + attribOffset + 2];
  42867. effect.setVector3(v.attributeName, ModelRenderCache.v3);
  42868. break;
  42869. }
  42870. case 6 /* Color4 */:
  42871. case 2 /* Vector4 */:
  42872. {
  42873. var attribOffset = v.instanceOffset.get(pd._partJoinedUsedCategories);
  42874. ModelRenderCache.v4.x = data.buffer[offset + attribOffset + 0];
  42875. ModelRenderCache.v4.y = data.buffer[offset + attribOffset + 1];
  42876. ModelRenderCache.v4.z = data.buffer[offset + attribOffset + 2];
  42877. ModelRenderCache.v4.w = data.buffer[offset + attribOffset + 3];
  42878. effect.setVector4(v.attributeName, ModelRenderCache.v4);
  42879. break;
  42880. }
  42881. default:
  42882. }
  42883. }
  42884. });
  42885. };
  42886. //setupUniformsLocation(effect: Effect, uniforms: string[], partId: number) {
  42887. // let i = this.getPartIndexFromId(partId);
  42888. // if (i === null) {
  42889. // return null;
  42890. // }
  42891. // let pci = this._partsClassInfo[i];
  42892. // pci.fullContent.forEach((k, v) => {
  42893. // if (uniforms.indexOf(v.attributeName) !== -1) {
  42894. // v.uniformLocation = effect.getUniform(v.attributeName);
  42895. // }
  42896. // });
  42897. //}
  42898. ModelRenderCache.v2 = BABYLON.Vector2.Zero();
  42899. ModelRenderCache.v3 = BABYLON.Vector3.Zero();
  42900. ModelRenderCache.v4 = BABYLON.Vector4.Zero();
  42901. return ModelRenderCache;
  42902. }());
  42903. BABYLON.ModelRenderCache = ModelRenderCache;
  42904. var ModelRenderCachePartData = (function () {
  42905. function ModelRenderCachePartData() {
  42906. }
  42907. return ModelRenderCachePartData;
  42908. }());
  42909. BABYLON.ModelRenderCachePartData = ModelRenderCachePartData;
  42910. })(BABYLON || (BABYLON = {}));
  42911. var BABYLON;
  42912. (function (BABYLON) {
  42913. var InstanceClassInfo = (function () {
  42914. function InstanceClassInfo(base) {
  42915. this._baseInfo = base;
  42916. this._nextOffset = new BABYLON.StringDictionary();
  42917. this._attributes = new Array();
  42918. }
  42919. InstanceClassInfo.prototype.mapProperty = function (propInfo, push) {
  42920. var curOff = this._nextOffset.getOrAdd(InstanceClassInfo._CurCategories, 0);
  42921. propInfo.instanceOffset.add(InstanceClassInfo._CurCategories, this._getBaseOffset(InstanceClassInfo._CurCategories) + curOff);
  42922. //console.log(`[${InstanceClassInfo._CurCategories}] New PropInfo. Category: ${propInfo.category}, Name: ${propInfo.attributeName}, Offset: ${propInfo.instanceOffset.get(InstanceClassInfo._CurCategories)}, Size: ${propInfo.size / 4}`);
  42923. this._nextOffset.set(InstanceClassInfo._CurCategories, curOff + (propInfo.size / 4));
  42924. if (push) {
  42925. this._attributes.push(propInfo);
  42926. }
  42927. };
  42928. InstanceClassInfo.prototype.getInstancingAttributeInfos = function (effect, categories) {
  42929. var catInline = ";" + categories.join(";") + ";";
  42930. var res = new Array();
  42931. var curInfo = this;
  42932. while (curInfo) {
  42933. for (var _i = 0, _a = curInfo._attributes; _i < _a.length; _i++) {
  42934. var attrib = _a[_i];
  42935. // 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
  42936. if (!attrib.category || categories.indexOf(attrib.category) !== -1) {
  42937. var index = effect.getAttributeLocationByName(attrib.attributeName);
  42938. var iai = new BABYLON.InstancingAttributeInfo();
  42939. iai.index = index;
  42940. 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)
  42941. iai.offset = attrib.instanceOffset.get(catInline) * 4; // attrib.instanceOffset is in float, iai.offset must be in bytes
  42942. iai.attributeName = attrib.attributeName;
  42943. res.push(iai);
  42944. }
  42945. }
  42946. curInfo = curInfo._baseInfo;
  42947. }
  42948. return res;
  42949. };
  42950. InstanceClassInfo.prototype.getShaderAttributes = function (categories) {
  42951. var res = new Array();
  42952. var curInfo = this;
  42953. while (curInfo) {
  42954. for (var _i = 0, _a = curInfo._attributes; _i < _a.length; _i++) {
  42955. var attrib = _a[_i];
  42956. // 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
  42957. if (!attrib.category || categories.indexOf(attrib.category) !== -1) {
  42958. res.push(attrib.attributeName);
  42959. }
  42960. }
  42961. curInfo = curInfo._baseInfo;
  42962. }
  42963. return res;
  42964. };
  42965. InstanceClassInfo.prototype._getBaseOffset = function (categories) {
  42966. var curOffset = 0;
  42967. var curBase = this._baseInfo;
  42968. while (curBase) {
  42969. curOffset += curBase._nextOffset.getOrAdd(categories, 0);
  42970. curBase = curBase._baseInfo;
  42971. }
  42972. return curOffset;
  42973. };
  42974. return InstanceClassInfo;
  42975. }());
  42976. BABYLON.InstanceClassInfo = InstanceClassInfo;
  42977. var InstancePropInfo = (function () {
  42978. function InstancePropInfo() {
  42979. this.instanceOffset = new BABYLON.StringDictionary();
  42980. }
  42981. InstancePropInfo.prototype.setSize = function (val) {
  42982. if (val instanceof BABYLON.Vector2) {
  42983. this.size = 8;
  42984. this.dataType = 0 /* Vector2 */;
  42985. return;
  42986. }
  42987. if (val instanceof BABYLON.Vector3) {
  42988. this.size = 12;
  42989. this.dataType = 1 /* Vector3 */;
  42990. return;
  42991. }
  42992. if (val instanceof BABYLON.Vector4) {
  42993. this.size = 16;
  42994. this.dataType = 2 /* Vector4 */;
  42995. return;
  42996. }
  42997. if (val instanceof BABYLON.Matrix) {
  42998. throw new Error("Matrix type is not supported by WebGL Instance Buffer, you have to use four Vector4 properties instead");
  42999. }
  43000. if (typeof (val) === "number") {
  43001. this.size = 4;
  43002. this.dataType = 4 /* float */;
  43003. return;
  43004. }
  43005. if (val instanceof BABYLON.Color3) {
  43006. this.size = 12;
  43007. this.dataType = 5 /* Color3 */;
  43008. return;
  43009. }
  43010. if (val instanceof BABYLON.Color4) {
  43011. this.size = 16;
  43012. this.dataType = 6 /* Color4 */;
  43013. return;
  43014. }
  43015. if (val instanceof BABYLON.Size) {
  43016. this.size = 8;
  43017. this.dataType = 7 /* Size */;
  43018. return;
  43019. }
  43020. return;
  43021. };
  43022. InstancePropInfo.prototype.writeData = function (array, offset, val) {
  43023. switch (this.dataType) {
  43024. case 0 /* Vector2 */:
  43025. {
  43026. var v = val;
  43027. array[offset + 0] = v.x;
  43028. array[offset + 1] = v.y;
  43029. break;
  43030. }
  43031. case 1 /* Vector3 */:
  43032. {
  43033. var v = val;
  43034. array[offset + 0] = v.x;
  43035. array[offset + 1] = v.y;
  43036. array[offset + 2] = v.z;
  43037. break;
  43038. }
  43039. case 2 /* Vector4 */:
  43040. {
  43041. var v = val;
  43042. array[offset + 0] = v.x;
  43043. array[offset + 1] = v.y;
  43044. array[offset + 2] = v.z;
  43045. array[offset + 3] = v.w;
  43046. break;
  43047. }
  43048. case 5 /* Color3 */:
  43049. {
  43050. var v = val;
  43051. array[offset + 0] = v.r;
  43052. array[offset + 1] = v.g;
  43053. array[offset + 2] = v.b;
  43054. break;
  43055. }
  43056. case 6 /* Color4 */:
  43057. {
  43058. var v = val;
  43059. array[offset + 0] = v.r;
  43060. array[offset + 1] = v.g;
  43061. array[offset + 2] = v.b;
  43062. array[offset + 3] = v.a;
  43063. break;
  43064. }
  43065. case 4 /* float */:
  43066. {
  43067. var v = val;
  43068. array[offset] = v;
  43069. break;
  43070. }
  43071. case 3 /* Matrix */:
  43072. {
  43073. var v = val;
  43074. for (var i = 0; i < 16; i++) {
  43075. array[offset + i] = v.m[i];
  43076. }
  43077. break;
  43078. }
  43079. case 7 /* Size */:
  43080. {
  43081. var s = val;
  43082. array[offset + 0] = s.width;
  43083. array[offset + 1] = s.height;
  43084. break;
  43085. }
  43086. }
  43087. };
  43088. return InstancePropInfo;
  43089. }());
  43090. BABYLON.InstancePropInfo = InstancePropInfo;
  43091. function instanceData(category, shaderAttributeName) {
  43092. return function (target, propName, descriptor) {
  43093. var dic = BABYLON.ClassTreeInfo.getOrRegister(target, function (base) { return new InstanceClassInfo(base); });
  43094. var node = dic.getLevelOf(target);
  43095. var instanceDataName = propName;
  43096. shaderAttributeName = shaderAttributeName || instanceDataName;
  43097. var info = node.levelContent.get(instanceDataName);
  43098. if (info) {
  43099. throw new Error("The ID " + instanceDataName + " is already taken by another instance data");
  43100. }
  43101. info = new InstancePropInfo();
  43102. info.attributeName = shaderAttributeName;
  43103. info.category = category || null;
  43104. if (info.category) {
  43105. info.delimitedCategory = ";" + info.category + ";";
  43106. }
  43107. node.levelContent.add(instanceDataName, info);
  43108. descriptor.get = function () {
  43109. return null;
  43110. };
  43111. descriptor.set = function (val) {
  43112. // Check that we're not trying to set a property that belongs to a category that is not allowed (current)
  43113. // Quit if it's the case, otherwise we could overwrite data somewhere...
  43114. if (info.category && InstanceClassInfo._CurCategories.indexOf(info.delimitedCategory) === -1) {
  43115. return;
  43116. }
  43117. if (!info.size) {
  43118. info.setSize(val);
  43119. node.classContent.mapProperty(info, true);
  43120. }
  43121. else if (!info.instanceOffset.contains(InstanceClassInfo._CurCategories)) {
  43122. node.classContent.mapProperty(info, false);
  43123. }
  43124. var obj = this;
  43125. if (obj.dataBuffer && obj.dataElements) {
  43126. var offset = obj.dataElements[obj.curElement].offset + info.instanceOffset.get(InstanceClassInfo._CurCategories);
  43127. info.writeData(obj.dataBuffer.buffer, offset, val);
  43128. }
  43129. };
  43130. };
  43131. }
  43132. BABYLON.instanceData = instanceData;
  43133. var InstanceDataBase = (function () {
  43134. function InstanceDataBase(partId, dataElementCount) {
  43135. this.id = partId;
  43136. this.curElement = 0;
  43137. this._dataElementCount = dataElementCount;
  43138. this.renderMode = 0;
  43139. this.arrayLengthChanged = false;
  43140. }
  43141. Object.defineProperty(InstanceDataBase.prototype, "zBias", {
  43142. get: function () {
  43143. return null;
  43144. },
  43145. enumerable: true,
  43146. configurable: true
  43147. });
  43148. Object.defineProperty(InstanceDataBase.prototype, "transformX", {
  43149. get: function () {
  43150. return null;
  43151. },
  43152. enumerable: true,
  43153. configurable: true
  43154. });
  43155. Object.defineProperty(InstanceDataBase.prototype, "transformY", {
  43156. get: function () {
  43157. return null;
  43158. },
  43159. enumerable: true,
  43160. configurable: true
  43161. });
  43162. Object.defineProperty(InstanceDataBase.prototype, "opacity", {
  43163. get: function () {
  43164. return null;
  43165. },
  43166. enumerable: true,
  43167. configurable: true
  43168. });
  43169. InstanceDataBase.prototype.getClassTreeInfo = function () {
  43170. if (!this.typeInfo) {
  43171. this.typeInfo = BABYLON.ClassTreeInfo.get(Object.getPrototypeOf(this));
  43172. }
  43173. return this.typeInfo;
  43174. };
  43175. InstanceDataBase.prototype.allocElements = function () {
  43176. if (!this.dataBuffer || this.dataElements) {
  43177. return;
  43178. }
  43179. var res = new Array(this.dataElementCount);
  43180. for (var i = 0; i < this.dataElementCount; i++) {
  43181. res[i] = this.dataBuffer.allocElement();
  43182. }
  43183. this.dataElements = res;
  43184. };
  43185. InstanceDataBase.prototype.freeElements = function () {
  43186. if (!this.dataElements) {
  43187. return;
  43188. }
  43189. for (var _i = 0, _a = this.dataElements; _i < _a.length; _i++) {
  43190. var ei = _a[_i];
  43191. this.dataBuffer.freeElement(ei);
  43192. }
  43193. this.dataElements = null;
  43194. };
  43195. Object.defineProperty(InstanceDataBase.prototype, "dataElementCount", {
  43196. get: function () {
  43197. return this._dataElementCount;
  43198. },
  43199. set: function (value) {
  43200. if (value === this._dataElementCount) {
  43201. return;
  43202. }
  43203. this.arrayLengthChanged = true;
  43204. this.freeElements();
  43205. this._dataElementCount = value;
  43206. this.allocElements();
  43207. },
  43208. enumerable: true,
  43209. configurable: true
  43210. });
  43211. __decorate([
  43212. instanceData()
  43213. ], InstanceDataBase.prototype, "zBias", null);
  43214. __decorate([
  43215. instanceData()
  43216. ], InstanceDataBase.prototype, "transformX", null);
  43217. __decorate([
  43218. instanceData()
  43219. ], InstanceDataBase.prototype, "transformY", null);
  43220. __decorate([
  43221. instanceData()
  43222. ], InstanceDataBase.prototype, "opacity", null);
  43223. return InstanceDataBase;
  43224. }());
  43225. BABYLON.InstanceDataBase = InstanceDataBase;
  43226. var RenderablePrim2D = (function (_super) {
  43227. __extends(RenderablePrim2D, _super);
  43228. function RenderablePrim2D(settings) {
  43229. _super.call(this, settings);
  43230. this._transparentPrimitiveInfo = null;
  43231. }
  43232. Object.defineProperty(RenderablePrim2D.prototype, "isAlphaTest", {
  43233. get: function () {
  43234. return this._useTextureAlpha() || this._isPrimAlphaTest();
  43235. },
  43236. enumerable: true,
  43237. configurable: true
  43238. });
  43239. Object.defineProperty(RenderablePrim2D.prototype, "isTransparent", {
  43240. get: function () {
  43241. return (this.actualOpacity < 1) || this._shouldUseAlphaFromTexture() || this._isPrimTransparent();
  43242. },
  43243. enumerable: true,
  43244. configurable: true
  43245. });
  43246. Object.defineProperty(RenderablePrim2D.prototype, "renderMode", {
  43247. get: function () {
  43248. return this._renderMode;
  43249. },
  43250. enumerable: true,
  43251. configurable: true
  43252. });
  43253. /**
  43254. * Dispose the primitive and its resources, remove it from its parent
  43255. */
  43256. RenderablePrim2D.prototype.dispose = function () {
  43257. if (!_super.prototype.dispose.call(this)) {
  43258. return false;
  43259. }
  43260. if (this.renderGroup) {
  43261. this.renderGroup._setCacheGroupDirty();
  43262. }
  43263. if (this._transparentPrimitiveInfo) {
  43264. this.renderGroup._renderableData.removeTransparentPrimitiveInfo(this._transparentPrimitiveInfo);
  43265. this._transparentPrimitiveInfo = null;
  43266. }
  43267. if (this._instanceDataParts) {
  43268. this._cleanupInstanceDataParts();
  43269. }
  43270. if (this._modelRenderCache) {
  43271. this._modelRenderCache.dispose();
  43272. this._modelRenderCache = null;
  43273. }
  43274. if (this._instanceDataParts) {
  43275. this._instanceDataParts.forEach(function (p) {
  43276. p.freeElements();
  43277. });
  43278. this._instanceDataParts = null;
  43279. }
  43280. return true;
  43281. };
  43282. RenderablePrim2D.prototype._cleanupInstanceDataParts = function () {
  43283. var gii = null;
  43284. for (var _i = 0, _a = this._instanceDataParts; _i < _a.length; _i++) {
  43285. var part = _a[_i];
  43286. part.freeElements();
  43287. gii = part.groupInstanceInfo;
  43288. }
  43289. if (gii) {
  43290. var usedCount = 0;
  43291. if (gii.hasOpaqueData) {
  43292. var od = gii.opaqueData[0];
  43293. usedCount += od._partData.usedElementCount;
  43294. gii.opaqueDirty = true;
  43295. }
  43296. if (gii.hasAlphaTestData) {
  43297. var atd = gii.alphaTestData[0];
  43298. usedCount += atd._partData.usedElementCount;
  43299. gii.alphaTestDirty = true;
  43300. }
  43301. if (gii.hasTransparentData) {
  43302. var td = gii.transparentData[0];
  43303. usedCount += td._partData.usedElementCount;
  43304. gii.transparentDirty = true;
  43305. }
  43306. if (usedCount === 0 && gii.modelRenderCache != null) {
  43307. this.renderGroup._renderableData._renderGroupInstancesInfo.remove(gii.modelRenderCache.modelKey);
  43308. gii.dispose();
  43309. }
  43310. if (this._modelRenderCache) {
  43311. this._modelRenderCache.dispose();
  43312. this._modelRenderCache = null;
  43313. }
  43314. }
  43315. this._instanceDataParts = null;
  43316. };
  43317. RenderablePrim2D.prototype._prepareRenderPre = function (context) {
  43318. _super.prototype._prepareRenderPre.call(this, context);
  43319. // If the model changed and we have already an instance, we must remove this instance from the obsolete model
  43320. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagModelDirty) && this._instanceDataParts) {
  43321. this._cleanupInstanceDataParts();
  43322. }
  43323. // Need to create the model?
  43324. var setupModelRenderCache = false;
  43325. if (!this._modelRenderCache || this._isFlagSet(BABYLON.SmartPropertyPrim.flagModelDirty)) {
  43326. setupModelRenderCache = this._createModelRenderCache();
  43327. }
  43328. var gii = null;
  43329. var newInstance = false;
  43330. // Need to create the instance data parts?
  43331. if (!this._instanceDataParts) {
  43332. // Yes, flag it for later, more processing will have to be done
  43333. newInstance = true;
  43334. gii = this._createModelDataParts();
  43335. }
  43336. // If the ModelRenderCache is brand new, now is the time to call the implementation's specific setup method to create the rendering resources
  43337. if (setupModelRenderCache) {
  43338. this.setupModelRenderCache(this._modelRenderCache);
  43339. }
  43340. // 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.
  43341. // 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.
  43342. if (this._areSomeFlagsSet(BABYLON.SmartPropertyPrim.flagVisibilityChanged | BABYLON.SmartPropertyPrim.flagNeedRefresh) || context.forceRefreshPrimitive || newInstance || (this._instanceDirtyFlags !== 0) || (this._globalTransformProcessStep !== this._globalTransformStep) || this._mustUpdateInstance()) {
  43343. this._updateInstanceDataParts(gii);
  43344. }
  43345. };
  43346. RenderablePrim2D.prototype._createModelRenderCache = function () {
  43347. var _this = this;
  43348. var setupModelRenderCache = false;
  43349. if (this._modelRenderCache) {
  43350. this._modelRenderCache.dispose();
  43351. }
  43352. this._modelRenderCache = this.owner._engineData.GetOrAddModelCache(this.modelKey, function (key) {
  43353. var mrc = _this.createModelRenderCache(key);
  43354. setupModelRenderCache = true;
  43355. return mrc;
  43356. });
  43357. this._clearFlags(BABYLON.SmartPropertyPrim.flagModelDirty);
  43358. // if this is still false it means the MRC already exists, so we add a reference to it
  43359. if (!setupModelRenderCache) {
  43360. this._modelRenderCache.addRef();
  43361. }
  43362. return setupModelRenderCache;
  43363. };
  43364. RenderablePrim2D.prototype._createModelDataParts = function () {
  43365. var _this = this;
  43366. // Create the instance data parts of the primitive and store them
  43367. var parts = this.createInstanceDataParts();
  43368. this._instanceDataParts = parts;
  43369. // Check if the ModelRenderCache for this particular instance is also brand new, initialize it if it's the case
  43370. if (!this._modelRenderCache._partData) {
  43371. this._setupModelRenderCache(parts);
  43372. }
  43373. // The Rendering resources (Effect, VB, IB, Textures) are stored in the ModelRenderCache
  43374. // But it's the RenderGroup that will store all the Instanced related data to render all the primitive it owns.
  43375. // So for a given ModelKey we getOrAdd a GroupInstanceInfo that will store all these data
  43376. var gii = this.renderGroup._renderableData._renderGroupInstancesInfo.getOrAddWithFactory(this.modelKey, function (k) {
  43377. var res = new BABYLON.GroupInstanceInfo(_this.renderGroup, _this._modelRenderCache, _this._modelRenderCache._partData.length);
  43378. for (var j = 0; j < _this._modelRenderCache._partData.length; j++) {
  43379. var part = _this._instanceDataParts[j];
  43380. res.partIndexFromId.add(part.id.toString(), j);
  43381. res.usedShaderCategories[j] = ";" + _this.getUsedShaderCategories(part).join(";") + ";";
  43382. res.strides[j] = _this._modelRenderCache._partData[j]._partDataStride;
  43383. }
  43384. return res;
  43385. });
  43386. // Get the GroupInfoDataPart corresponding to the render category of the part
  43387. var rm = 0;
  43388. var gipd = null;
  43389. if (this.isTransparent) {
  43390. gipd = gii.transparentData;
  43391. rm = BABYLON.Render2DContext.RenderModeTransparent;
  43392. }
  43393. else if (this.isAlphaTest) {
  43394. gipd = gii.alphaTestData;
  43395. rm = BABYLON.Render2DContext.RenderModeAlphaTest;
  43396. }
  43397. else {
  43398. gipd = gii.opaqueData;
  43399. rm = BABYLON.Render2DContext.RenderModeOpaque;
  43400. }
  43401. // For each instance data part of the primitive, allocate the instanced element it needs for render
  43402. for (var i = 0; i < parts.length; i++) {
  43403. var part = parts[i];
  43404. part.dataBuffer = gipd[i]._partData;
  43405. part.allocElements();
  43406. part.renderMode = rm;
  43407. part.groupInstanceInfo = gii;
  43408. }
  43409. return gii;
  43410. };
  43411. RenderablePrim2D.prototype._setupModelRenderCache = function (parts) {
  43412. var ctiArray = new Array();
  43413. this._modelRenderCache._partData = new Array();
  43414. for (var _i = 0, parts_1 = parts; _i < parts_1.length; _i++) {
  43415. var dataPart = parts_1[_i];
  43416. var pd = new BABYLON.ModelRenderCachePartData();
  43417. this._modelRenderCache._partData.push(pd);
  43418. var cat = this.getUsedShaderCategories(dataPart);
  43419. var cti = dataPart.getClassTreeInfo();
  43420. // Make sure the instance is visible other the properties won't be set and their size/offset wont be computed
  43421. var curVisible = this.isVisible;
  43422. this.isVisible = true;
  43423. // 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.
  43424. //console.log("Build Prop Layout for " + Tools.getClassName(this._instanceDataParts[0]));
  43425. var joinCat = ";" + cat.join(";") + ";";
  43426. pd._partJoinedUsedCategories = joinCat;
  43427. InstanceClassInfo._CurCategories = joinCat;
  43428. var obj = this.beforeRefreshForLayoutConstruction(dataPart);
  43429. if (!this.refreshInstanceDataPart(dataPart)) {
  43430. console.log("Layout construction for " + BABYLON.Tools.getClassName(this._instanceDataParts[0]) + " failed because refresh returned false");
  43431. }
  43432. this.afterRefreshForLayoutConstruction(dataPart, obj);
  43433. this.isVisible = curVisible;
  43434. var size = 0;
  43435. cti.fullContent.forEach(function (k, v) {
  43436. if (!v.category || cat.indexOf(v.category) !== -1) {
  43437. if (v.attributeName === "zBias") {
  43438. pd._zBiasOffset = v.instanceOffset.get(joinCat);
  43439. }
  43440. if (!v.size) {
  43441. console.log("ERROR: Couldn't detect the size of the Property " + v.attributeName + " from type " + BABYLON.Tools.getClassName(cti.type) + ". Property is ignored.");
  43442. }
  43443. else {
  43444. size += v.size;
  43445. }
  43446. }
  43447. });
  43448. pd._partDataStride = size;
  43449. pd._partUsedCategories = cat;
  43450. pd._partId = dataPart.id;
  43451. ctiArray.push(cti);
  43452. }
  43453. this._modelRenderCache._partsClassInfo = ctiArray;
  43454. };
  43455. RenderablePrim2D.prototype.onZOrderChanged = function () {
  43456. if (this.isTransparent && this._transparentPrimitiveInfo) {
  43457. this.renderGroup._renderableData.transparentPrimitiveZChanged(this._transparentPrimitiveInfo);
  43458. var gii = this.renderGroup._renderableData._renderGroupInstancesInfo.get(this.modelKey);
  43459. // Flag the transparentData dirty has will have to sort it again
  43460. gii.transparentOrderDirty = true;
  43461. }
  43462. };
  43463. RenderablePrim2D.prototype._mustUpdateInstance = function () {
  43464. return false;
  43465. };
  43466. RenderablePrim2D.prototype._useTextureAlpha = function () {
  43467. return false;
  43468. };
  43469. RenderablePrim2D.prototype._shouldUseAlphaFromTexture = function () {
  43470. return false;
  43471. };
  43472. RenderablePrim2D.prototype._isPrimAlphaTest = function () {
  43473. return false;
  43474. };
  43475. RenderablePrim2D.prototype._isPrimTransparent = function () {
  43476. return false;
  43477. };
  43478. RenderablePrim2D.prototype._updateInstanceDataParts = function (gii) {
  43479. // Fetch the GroupInstanceInfo if we don't already have it
  43480. var rd = this.renderGroup._renderableData;
  43481. if (!gii) {
  43482. gii = rd._renderGroupInstancesInfo.get(this.modelKey);
  43483. }
  43484. var isTransparent = this.isTransparent;
  43485. var isAlphaTest = this.isAlphaTest;
  43486. var wereTransparent = false;
  43487. // Check a render mode change
  43488. var rmChanged = false;
  43489. if (this._instanceDataParts.length > 0) {
  43490. var firstPart = this._instanceDataParts[0];
  43491. var partRM = firstPart.renderMode;
  43492. var curRM = this.renderMode;
  43493. if (partRM !== curRM) {
  43494. wereTransparent = partRM === BABYLON.Render2DContext.RenderModeTransparent;
  43495. rmChanged = true;
  43496. var gipd = void 0;
  43497. switch (curRM) {
  43498. case BABYLON.Render2DContext.RenderModeTransparent:
  43499. gipd = gii.transparentData;
  43500. break;
  43501. case BABYLON.Render2DContext.RenderModeAlphaTest:
  43502. gipd = gii.alphaTestData;
  43503. break;
  43504. default:
  43505. gipd = gii.opaqueData;
  43506. }
  43507. for (var i = 0; i < this._instanceDataParts.length; i++) {
  43508. var part = this._instanceDataParts[i];
  43509. part.freeElements();
  43510. part.dataBuffer = gipd[i]._partData;
  43511. part.renderMode = curRM;
  43512. }
  43513. }
  43514. }
  43515. // Handle changes related to ZOffset
  43516. var visChanged = this._isFlagSet(BABYLON.SmartPropertyPrim.flagVisibilityChanged);
  43517. if (isTransparent || wereTransparent) {
  43518. // Handle visibility change, which is also triggered when the primitive just got created
  43519. if (visChanged || rmChanged) {
  43520. if (this.isVisible && !wereTransparent) {
  43521. if (!this._transparentPrimitiveInfo) {
  43522. // Add the primitive to the list of transparent ones in the group that render is
  43523. this._transparentPrimitiveInfo = rd.addNewTransparentPrimitiveInfo(this, gii);
  43524. }
  43525. }
  43526. else {
  43527. if (this._transparentPrimitiveInfo) {
  43528. rd.removeTransparentPrimitiveInfo(this._transparentPrimitiveInfo);
  43529. this._transparentPrimitiveInfo = null;
  43530. }
  43531. }
  43532. gii.transparentOrderDirty = true;
  43533. }
  43534. }
  43535. var rebuildTrans = false;
  43536. // For each Instance Data part, refresh it to update the data in the DynamicFloatArray
  43537. for (var _i = 0, _a = this._instanceDataParts; _i < _a.length; _i++) {
  43538. var part = _a[_i];
  43539. var justAllocated = false;
  43540. // Check if we need to allocate data elements (hidden prim which becomes visible again)
  43541. if (!part.dataElements && (visChanged || rmChanged || this.isVisible)) {
  43542. part.allocElements();
  43543. justAllocated = true;
  43544. }
  43545. InstanceClassInfo._CurCategories = gii.usedShaderCategories[gii.partIndexFromId.get(part.id.toString())];
  43546. // Will return false if the instance should not be rendered (not visible or other any reasons)
  43547. part.arrayLengthChanged = false;
  43548. if (!this.refreshInstanceDataPart(part)) {
  43549. // Free the data element
  43550. if (part.dataElements) {
  43551. part.freeElements();
  43552. }
  43553. // The refresh couldn't succeed, push the primitive to be dirty again for the next render
  43554. if (this.isVisible) {
  43555. rd._primNewDirtyList.push(this);
  43556. }
  43557. }
  43558. rebuildTrans = rebuildTrans || part.arrayLengthChanged || justAllocated;
  43559. }
  43560. this._instanceDirtyFlags = 0;
  43561. // Make the appropriate data dirty
  43562. if (isTransparent) {
  43563. gii.transparentDirty = true;
  43564. if (rebuildTrans) {
  43565. rd._transparentListChanged = true;
  43566. }
  43567. }
  43568. else if (isAlphaTest) {
  43569. gii.alphaTestDirty = true;
  43570. }
  43571. else {
  43572. gii.opaqueDirty = true;
  43573. }
  43574. this._clearFlags(BABYLON.SmartPropertyPrim.flagVisibilityChanged); // Reset the flag as we've handled the case
  43575. };
  43576. RenderablePrim2D.prototype._updateTransparentSegmentIndices = function (ts) {
  43577. var minOff = BABYLON.Prim2DBase._bigInt;
  43578. var maxOff = 0;
  43579. for (var _i = 0, _a = this._instanceDataParts; _i < _a.length; _i++) {
  43580. var part = _a[_i];
  43581. if (part && part.dataElements) {
  43582. part.dataBuffer.pack();
  43583. for (var _b = 0, _c = part.dataElements; _b < _c.length; _b++) {
  43584. var el = _c[_b];
  43585. minOff = Math.min(minOff, el.offset);
  43586. maxOff = Math.max(maxOff, el.offset);
  43587. }
  43588. ts.startDataIndex = Math.min(ts.startDataIndex, minOff / part.dataBuffer.stride);
  43589. ts.endDataIndex = Math.max(ts.endDataIndex, (maxOff / part.dataBuffer.stride) + 1); // +1 for exclusive
  43590. }
  43591. }
  43592. };
  43593. // This internal method is mainly used for transparency processing
  43594. RenderablePrim2D.prototype._getNextPrimZOrder = function () {
  43595. var length = this._instanceDataParts.length;
  43596. for (var i = 0; i < length; i++) {
  43597. var part = this._instanceDataParts[i];
  43598. if (part) {
  43599. var stride = part.dataBuffer.stride;
  43600. var lastElementOffset = part.dataElements[part.dataElements.length - 1].offset;
  43601. // check if it's the last in the DFA
  43602. if (part.dataBuffer.totalElementCount * stride <= lastElementOffset) {
  43603. return null;
  43604. }
  43605. // Return the Z of the next primitive that lies in the DFA
  43606. return part.dataBuffer[lastElementOffset + stride + this.modelRenderCache._partData[i]._zBiasOffset];
  43607. }
  43608. }
  43609. return null;
  43610. };
  43611. // This internal method is mainly used for transparency processing
  43612. RenderablePrim2D.prototype._getPrevPrimZOrder = function () {
  43613. var length = this._instanceDataParts.length;
  43614. for (var i = 0; i < length; i++) {
  43615. var part = this._instanceDataParts[i];
  43616. if (part) {
  43617. var stride = part.dataBuffer.stride;
  43618. var firstElementOffset = part.dataElements[0].offset;
  43619. // check if it's the first in the DFA
  43620. if (firstElementOffset === 0) {
  43621. return null;
  43622. }
  43623. // Return the Z of the previous primitive that lies in the DFA
  43624. return part.dataBuffer[firstElementOffset - stride + this.modelRenderCache._partData[i]._zBiasOffset];
  43625. }
  43626. }
  43627. return null;
  43628. };
  43629. /**
  43630. * Transform a given point using the Primitive's origin setting.
  43631. * This method requires the Primitive's actualSize to be accurate
  43632. * @param p the point to transform
  43633. * @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.
  43634. * @param res an allocated Vector2 that will receive the transformed content
  43635. */
  43636. RenderablePrim2D.prototype.transformPointWithOriginByRef = function (p, originOffset, res) {
  43637. var actualSize = this.actualSize;
  43638. res.x = p.x - ((this.origin.x + (originOffset ? originOffset.x : 0)) * actualSize.width);
  43639. res.y = p.y - ((this.origin.y + (originOffset ? originOffset.y : 0)) * actualSize.height);
  43640. };
  43641. RenderablePrim2D.prototype.transformPointWithOriginToRef = function (p, originOffset, res) {
  43642. this.transformPointWithOriginByRef(p, originOffset, res);
  43643. return res;
  43644. };
  43645. /**
  43646. * Get the info for a given effect based on the dataPart metadata
  43647. * @param dataPartId partId in part list to get the info
  43648. * @param vertexBufferAttributes vertex buffer attributes to manually add
  43649. * @param uniforms uniforms to manually add
  43650. * @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
  43651. */
  43652. RenderablePrim2D.prototype.getDataPartEffectInfo = function (dataPartId, vertexBufferAttributes, uniforms, useInstanced) {
  43653. if (uniforms === void 0) { uniforms = null; }
  43654. if (useInstanced === void 0) { useInstanced = null; }
  43655. var dataPart = BABYLON.Tools.first(this._instanceDataParts, function (i) { return i.id === dataPartId; });
  43656. if (!dataPart) {
  43657. return null;
  43658. }
  43659. var instancedArray = this.owner.supportInstancedArray;
  43660. if (useInstanced != null) {
  43661. // Check if the caller ask for Instanced Array and the engine does not support it, return null if it's the case
  43662. if (useInstanced && instancedArray === false) {
  43663. return null;
  43664. }
  43665. // Use the caller's setting
  43666. instancedArray = useInstanced;
  43667. }
  43668. var cti = dataPart.getClassTreeInfo();
  43669. var categories = this.getUsedShaderCategories(dataPart);
  43670. var att = cti.classContent.getShaderAttributes(categories);
  43671. var defines = "";
  43672. categories.forEach(function (c) { defines += "#define " + c + "\n"; });
  43673. if (instancedArray) {
  43674. defines += "#define Instanced\n";
  43675. }
  43676. return {
  43677. attributes: instancedArray ? vertexBufferAttributes.concat(att) : vertexBufferAttributes,
  43678. uniforms: instancedArray ? (uniforms != null ? uniforms : []) : ((uniforms != null) ? att.concat(uniforms) : (att != null ? att : [])),
  43679. defines: defines
  43680. };
  43681. };
  43682. Object.defineProperty(RenderablePrim2D.prototype, "modelRenderCache", {
  43683. get: function () {
  43684. return this._modelRenderCache;
  43685. },
  43686. enumerable: true,
  43687. configurable: true
  43688. });
  43689. RenderablePrim2D.prototype.createModelRenderCache = function (modelKey) {
  43690. return null;
  43691. };
  43692. RenderablePrim2D.prototype.setupModelRenderCache = function (modelRenderCache) {
  43693. };
  43694. RenderablePrim2D.prototype.createInstanceDataParts = function () {
  43695. return null;
  43696. };
  43697. RenderablePrim2D.prototype.getUsedShaderCategories = function (dataPart) {
  43698. return [];
  43699. };
  43700. RenderablePrim2D.prototype.beforeRefreshForLayoutConstruction = function (part) {
  43701. };
  43702. RenderablePrim2D.prototype.afterRefreshForLayoutConstruction = function (part, obj) {
  43703. };
  43704. RenderablePrim2D.prototype.applyActualScaleOnTransform = function () {
  43705. return true;
  43706. };
  43707. RenderablePrim2D.prototype.refreshInstanceDataPart = function (part) {
  43708. if (!this.isVisible) {
  43709. return false;
  43710. }
  43711. part.isVisible = this.isVisible;
  43712. // 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)
  43713. if (part.dataElementCount === 1) {
  43714. part.curElement = 0;
  43715. this.updateInstanceDataPart(part);
  43716. }
  43717. return true;
  43718. };
  43719. /**
  43720. * Update the instanceDataBase level properties of a part
  43721. * @param part the part to update
  43722. * @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).
  43723. */
  43724. RenderablePrim2D.prototype.updateInstanceDataPart = function (part, positionOffset) {
  43725. if (positionOffset === void 0) { positionOffset = null; }
  43726. var t = this._globalTransform.multiply(this.renderGroup.invGlobalTransform); // Compute the transformation into the renderGroup's space
  43727. var rgScale = this._areSomeFlagsSet(BABYLON.SmartPropertyPrim.flagDontInheritParentScale) ? RenderablePrim2D._uV : this.renderGroup.actualScale; // We still need to apply the scale of the renderGroup to our rendering, so get it.
  43728. var size = this.renderGroup.viewportSize;
  43729. var zBias = this.actualZOffset;
  43730. var offX = 0;
  43731. var offY = 0;
  43732. // If there's an offset, apply the global transformation matrix on it to get a global offset
  43733. if (positionOffset) {
  43734. offX = positionOffset.x * t.m[0] + positionOffset.y * t.m[4];
  43735. offY = positionOffset.x * t.m[1] + positionOffset.y * t.m[5];
  43736. }
  43737. // 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
  43738. // Current coordinates are expressed in renderGroup coordinates ([0, renderGroup.actualSize.width|height]) with 0,0 being at the left/top corner
  43739. // So for X:
  43740. // - tx.x = value * 2 / width: is to switch from [0, renderGroup.width] to [0, 2]
  43741. // - 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].
  43742. // At last we don't forget to apply the actualScale of the Render Group to tx[0] and ty[1] to propagate scaling correctly
  43743. var w = size.width;
  43744. var h = size.height;
  43745. var invZBias = 1 / zBias;
  43746. var tx = new BABYLON.Vector4(t.m[0] * rgScale.x * 2 / w, t.m[4] * 2 / w, 0 /*t.m[8]*/, ((t.m[12] + offX) * rgScale.x * 2 / w) - 1);
  43747. var ty = new BABYLON.Vector4(t.m[1] * 2 / h, t.m[5] * rgScale.y * 2 / h, 0 /*t.m[9]*/, ((t.m[13] + offY) * rgScale.y * 2 / h) - 1);
  43748. if (!this.applyActualScaleOnTransform()) {
  43749. var las = this.actualScale;
  43750. tx.x /= las.x;
  43751. ty.y /= las.y;
  43752. }
  43753. part.transformX = tx;
  43754. part.transformY = ty;
  43755. part.opacity = this.actualOpacity;
  43756. // 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)
  43757. part.zBias = new BABYLON.Vector2(zBias, invZBias);
  43758. };
  43759. RenderablePrim2D.prototype._updateRenderMode = function () {
  43760. if (this.isTransparent) {
  43761. this._renderMode = BABYLON.Render2DContext.RenderModeTransparent;
  43762. }
  43763. else if (this.isAlphaTest) {
  43764. this._renderMode = BABYLON.Render2DContext.RenderModeAlphaTest;
  43765. }
  43766. else {
  43767. this._renderMode = BABYLON.Render2DContext.RenderModeOpaque;
  43768. }
  43769. };
  43770. RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT = BABYLON.Prim2DBase.PRIM2DBASE_PROPCOUNT + 5;
  43771. RenderablePrim2D._uV = new BABYLON.Vector2(1, 1);
  43772. __decorate([
  43773. BABYLON.dynamicLevelProperty(BABYLON.Prim2DBase.PRIM2DBASE_PROPCOUNT + 0, function (pi) { return RenderablePrim2D.isAlphaTestProperty = pi; })
  43774. ], RenderablePrim2D.prototype, "isAlphaTest", null);
  43775. __decorate([
  43776. BABYLON.dynamicLevelProperty(BABYLON.Prim2DBase.PRIM2DBASE_PROPCOUNT + 1, function (pi) { return RenderablePrim2D.isTransparentProperty = pi; })
  43777. ], RenderablePrim2D.prototype, "isTransparent", null);
  43778. RenderablePrim2D = __decorate([
  43779. BABYLON.className("RenderablePrim2D")
  43780. ], RenderablePrim2D);
  43781. return RenderablePrim2D;
  43782. }(BABYLON.Prim2DBase));
  43783. BABYLON.RenderablePrim2D = RenderablePrim2D;
  43784. })(BABYLON || (BABYLON = {}));
  43785. var BABYLON;
  43786. (function (BABYLON) {
  43787. var Shape2D = (function (_super) {
  43788. __extends(Shape2D, _super);
  43789. function Shape2D(settings) {
  43790. _super.call(this, settings);
  43791. if (!settings) {
  43792. settings = {};
  43793. }
  43794. var borderBrush = null;
  43795. if (settings.border) {
  43796. if (typeof (settings.border) === "string") {
  43797. borderBrush = BABYLON.Canvas2D.GetBrushFromString(settings.border);
  43798. }
  43799. else {
  43800. borderBrush = settings.border;
  43801. }
  43802. }
  43803. var fillBrush = null;
  43804. if (settings.fill) {
  43805. if (typeof (settings.fill) === "string") {
  43806. fillBrush = BABYLON.Canvas2D.GetBrushFromString(settings.fill);
  43807. }
  43808. else {
  43809. fillBrush = settings.fill;
  43810. }
  43811. }
  43812. this._isTransparent = false;
  43813. this._oldTransparent = false;
  43814. this.border = borderBrush;
  43815. this.fill = fillBrush;
  43816. this._updateTransparencyStatus();
  43817. this.borderThickness = settings.borderThickness;
  43818. }
  43819. Object.defineProperty(Shape2D.prototype, "border", {
  43820. get: function () {
  43821. return this._border;
  43822. },
  43823. set: function (value) {
  43824. this._border = value;
  43825. this._updateTransparencyStatus();
  43826. },
  43827. enumerable: true,
  43828. configurable: true
  43829. });
  43830. Object.defineProperty(Shape2D.prototype, "fill", {
  43831. /**
  43832. * Get/set the brush to render the Fill part of the Primitive
  43833. */
  43834. get: function () {
  43835. return this._fill;
  43836. },
  43837. set: function (value) {
  43838. this._fill = value;
  43839. this._updateTransparencyStatus();
  43840. },
  43841. enumerable: true,
  43842. configurable: true
  43843. });
  43844. Object.defineProperty(Shape2D.prototype, "borderThickness", {
  43845. get: function () {
  43846. return this._borderThickness;
  43847. },
  43848. set: function (value) {
  43849. this._borderThickness = value;
  43850. },
  43851. enumerable: true,
  43852. configurable: true
  43853. });
  43854. Shape2D.prototype.getUsedShaderCategories = function (dataPart) {
  43855. var cat = _super.prototype.getUsedShaderCategories.call(this, dataPart);
  43856. // Fill Part
  43857. if (dataPart.id === Shape2D.SHAPE2D_FILLPARTID) {
  43858. var fill = this.fill;
  43859. if (fill instanceof BABYLON.SolidColorBrush2D) {
  43860. cat.push(Shape2D.SHAPE2D_CATEGORY_FILLSOLID);
  43861. }
  43862. if (fill instanceof BABYLON.GradientColorBrush2D) {
  43863. cat.push(Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT);
  43864. }
  43865. }
  43866. // Border Part
  43867. if (dataPart.id === Shape2D.SHAPE2D_BORDERPARTID) {
  43868. cat.push(Shape2D.SHAPE2D_CATEGORY_BORDER);
  43869. var border = this.border;
  43870. if (border instanceof BABYLON.SolidColorBrush2D) {
  43871. cat.push(Shape2D.SHAPE2D_CATEGORY_BORDERSOLID);
  43872. }
  43873. if (border instanceof BABYLON.GradientColorBrush2D) {
  43874. cat.push(Shape2D.SHAPE2D_CATEGORY_BORDERGRADIENT);
  43875. }
  43876. }
  43877. return cat;
  43878. };
  43879. Shape2D.prototype.applyActualScaleOnTransform = function () {
  43880. return false;
  43881. };
  43882. Shape2D.prototype.refreshInstanceDataPart = function (part) {
  43883. if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
  43884. return false;
  43885. }
  43886. // Fill Part
  43887. if (part.id === Shape2D.SHAPE2D_FILLPARTID) {
  43888. var d = part;
  43889. if (this.fill) {
  43890. var fill = this.fill;
  43891. if (fill instanceof BABYLON.SolidColorBrush2D) {
  43892. d.fillSolidColor = fill.color;
  43893. }
  43894. else if (fill instanceof BABYLON.GradientColorBrush2D) {
  43895. d.fillGradientColor1 = fill.color1;
  43896. d.fillGradientColor2 = fill.color2;
  43897. 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));
  43898. var ty = new BABYLON.Vector4(t.m[1], t.m[5], t.m[9], t.m[13]);
  43899. d.fillGradientTY = ty;
  43900. }
  43901. }
  43902. }
  43903. else if (part.id === Shape2D.SHAPE2D_BORDERPARTID) {
  43904. var d = part;
  43905. if (this.border) {
  43906. d.borderThickness = this.borderThickness;
  43907. var border = this.border;
  43908. if (border instanceof BABYLON.SolidColorBrush2D) {
  43909. d.borderSolidColor = border.color;
  43910. }
  43911. else if (border instanceof BABYLON.GradientColorBrush2D) {
  43912. d.borderGradientColor1 = border.color1;
  43913. d.borderGradientColor2 = border.color2;
  43914. 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));
  43915. var ty = new BABYLON.Vector4(t.m[1], t.m[5], t.m[9], t.m[13]);
  43916. d.borderGradientTY = ty;
  43917. }
  43918. }
  43919. }
  43920. return true;
  43921. };
  43922. Shape2D.prototype._updateTransparencyStatus = function () {
  43923. this._isTransparent = (this._border && this._border.isTransparent()) || (this._fill && this._fill.isTransparent()) || (this.actualOpacity < 1);
  43924. if (this._isTransparent !== this._oldTransparent) {
  43925. this._oldTransparent = this._isTransparent;
  43926. this._updateRenderMode();
  43927. }
  43928. };
  43929. Shape2D.prototype._mustUpdateInstance = function () {
  43930. var res = this._oldTransparent !== this._isTransparent;
  43931. if (res) {
  43932. this._updateRenderMode();
  43933. this._oldTransparent = this._isTransparent;
  43934. }
  43935. return res;
  43936. };
  43937. Shape2D.prototype._isPrimTransparent = function () {
  43938. return this._isTransparent;
  43939. };
  43940. Shape2D.SHAPE2D_BORDERPARTID = 1;
  43941. Shape2D.SHAPE2D_FILLPARTID = 2;
  43942. Shape2D.SHAPE2D_CATEGORY_BORDER = "Border";
  43943. Shape2D.SHAPE2D_CATEGORY_BORDERSOLID = "BorderSolid";
  43944. Shape2D.SHAPE2D_CATEGORY_BORDERGRADIENT = "BorderGradient";
  43945. Shape2D.SHAPE2D_CATEGORY_FILLSOLID = "FillSolid";
  43946. Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT = "FillGradient";
  43947. Shape2D.SHAPE2D_PROPCOUNT = BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 5;
  43948. __decorate([
  43949. BABYLON.modelLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 1, function (pi) { return Shape2D.borderProperty = pi; }, true)
  43950. ], Shape2D.prototype, "border", null);
  43951. __decorate([
  43952. BABYLON.modelLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 2, function (pi) { return Shape2D.fillProperty = pi; }, true)
  43953. ], Shape2D.prototype, "fill", null);
  43954. __decorate([
  43955. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 3, function (pi) { return Shape2D.borderThicknessProperty = pi; })
  43956. ], Shape2D.prototype, "borderThickness", null);
  43957. Shape2D = __decorate([
  43958. BABYLON.className("Shape2D")
  43959. ], Shape2D);
  43960. return Shape2D;
  43961. }(BABYLON.RenderablePrim2D));
  43962. BABYLON.Shape2D = Shape2D;
  43963. var Shape2DInstanceData = (function (_super) {
  43964. __extends(Shape2DInstanceData, _super);
  43965. function Shape2DInstanceData() {
  43966. _super.apply(this, arguments);
  43967. }
  43968. Object.defineProperty(Shape2DInstanceData.prototype, "fillSolidColor", {
  43969. // FILL ATTRIBUTES
  43970. get: function () {
  43971. return null;
  43972. },
  43973. enumerable: true,
  43974. configurable: true
  43975. });
  43976. Object.defineProperty(Shape2DInstanceData.prototype, "fillGradientColor1", {
  43977. get: function () {
  43978. return null;
  43979. },
  43980. enumerable: true,
  43981. configurable: true
  43982. });
  43983. Object.defineProperty(Shape2DInstanceData.prototype, "fillGradientColor2", {
  43984. get: function () {
  43985. return null;
  43986. },
  43987. enumerable: true,
  43988. configurable: true
  43989. });
  43990. Object.defineProperty(Shape2DInstanceData.prototype, "fillGradientTY", {
  43991. get: function () {
  43992. return null;
  43993. },
  43994. enumerable: true,
  43995. configurable: true
  43996. });
  43997. Object.defineProperty(Shape2DInstanceData.prototype, "borderThickness", {
  43998. // BORDER ATTRIBUTES
  43999. get: function () {
  44000. return null;
  44001. },
  44002. enumerable: true,
  44003. configurable: true
  44004. });
  44005. Object.defineProperty(Shape2DInstanceData.prototype, "borderSolidColor", {
  44006. get: function () {
  44007. return null;
  44008. },
  44009. enumerable: true,
  44010. configurable: true
  44011. });
  44012. Object.defineProperty(Shape2DInstanceData.prototype, "borderGradientColor1", {
  44013. get: function () {
  44014. return null;
  44015. },
  44016. enumerable: true,
  44017. configurable: true
  44018. });
  44019. Object.defineProperty(Shape2DInstanceData.prototype, "borderGradientColor2", {
  44020. get: function () {
  44021. return null;
  44022. },
  44023. enumerable: true,
  44024. configurable: true
  44025. });
  44026. Object.defineProperty(Shape2DInstanceData.prototype, "borderGradientTY", {
  44027. get: function () {
  44028. return null;
  44029. },
  44030. enumerable: true,
  44031. configurable: true
  44032. });
  44033. __decorate([
  44034. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_FILLSOLID)
  44035. ], Shape2DInstanceData.prototype, "fillSolidColor", null);
  44036. __decorate([
  44037. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT)
  44038. ], Shape2DInstanceData.prototype, "fillGradientColor1", null);
  44039. __decorate([
  44040. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT)
  44041. ], Shape2DInstanceData.prototype, "fillGradientColor2", null);
  44042. __decorate([
  44043. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT)
  44044. ], Shape2DInstanceData.prototype, "fillGradientTY", null);
  44045. __decorate([
  44046. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_BORDER)
  44047. ], Shape2DInstanceData.prototype, "borderThickness", null);
  44048. __decorate([
  44049. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_BORDERSOLID)
  44050. ], Shape2DInstanceData.prototype, "borderSolidColor", null);
  44051. __decorate([
  44052. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_BORDERGRADIENT)
  44053. ], Shape2DInstanceData.prototype, "borderGradientColor1", null);
  44054. __decorate([
  44055. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_BORDERGRADIENT)
  44056. ], Shape2DInstanceData.prototype, "borderGradientColor2", null);
  44057. __decorate([
  44058. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_BORDERGRADIENT)
  44059. ], Shape2DInstanceData.prototype, "borderGradientTY", null);
  44060. return Shape2DInstanceData;
  44061. }(BABYLON.InstanceDataBase));
  44062. BABYLON.Shape2DInstanceData = Shape2DInstanceData;
  44063. })(BABYLON || (BABYLON = {}));
  44064. var BABYLON;
  44065. (function (BABYLON) {
  44066. var Group2D = (function (_super) {
  44067. __extends(Group2D, _super);
  44068. /**
  44069. * Create an Logical or Renderable Group.
  44070. * @param settings a combination of settings, possible ones are
  44071. * - 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)
  44072. * - children: an array of direct children
  44073. * - id a text identifier, for information purpose
  44074. * - position: the X & Y positions relative to its parent. Alternatively the x and y properties can be set. Default is [0;0]
  44075. * - rotation: the initial rotation (in radian) of the primitive. default is 0
  44076. * - scale: the initial scale of the primitive. default is 1. You can alternatively use scaleX &| scaleY to apply non uniform scale
  44077. * - dontInheritParentScale: if set the parent's scale won't be taken into consideration to compute the actualScale property
  44078. * - opacity: set the overall opacity of the primitive, 1 to be opaque (default), less than 1 to be transparent.
  44079. * - zOrder: override the zOrder with the specified value
  44080. * - origin: define the normalized origin point location, default [0.5;0.5]
  44081. * - 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.
  44082. * - cacheBehavior: Define how the group should behave regarding the Canvas's cache strategy, default is Group2D.GROUPCACHEBEHAVIOR_FOLLOWCACHESTRATEGY
  44083. * - 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).
  44084. * - isVisible: true if the group must be visible, false for hidden. Default is true.
  44085. * - isPickable: if true the Primitive can be used with interaction mode and will issue Pointer Event. If false it will be ignored for interaction/intersection test. Default value is true.
  44086. * - isContainer: if true the Primitive acts as a container for interaction, if the primitive is not pickable or doesn't intersection, no further test will be perform on its children. If set to false, children will always be considered for intersection/interaction. Default value is true.
  44087. * - 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!
  44088. * - marginTop: top margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44089. * - marginLeft: left margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44090. * - marginRight: right margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44091. * - marginBottom: bottom margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44092. * - margin: top, left, right and bottom margin formatted as a single string (see PrimitiveThickness.fromString)
  44093. * - marginHAlignment: one value of the PrimitiveAlignment type's static properties
  44094. * - marginVAlignment: one value of the PrimitiveAlignment type's static properties
  44095. * - marginAlignment: a string defining the alignment, see PrimitiveAlignment.fromString
  44096. * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44097. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44098. * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44099. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44100. * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
  44101. */
  44102. function Group2D(settings) {
  44103. if (settings == null) {
  44104. settings = {};
  44105. }
  44106. if (settings.origin == null) {
  44107. settings.origin = new BABYLON.Vector2(0, 0);
  44108. }
  44109. _super.call(this, settings);
  44110. var size = (!settings.size && !settings.width && !settings.height) ? null : (settings.size || (new BABYLON.Size(settings.width || 0, settings.height || 0)));
  44111. this._trackedNode = (settings.trackNode == null) ? null : settings.trackNode;
  44112. if (this._trackedNode && this.owner) {
  44113. this.owner._registerTrackedNode(this);
  44114. }
  44115. this._cacheBehavior = (settings.cacheBehavior == null) ? Group2D.GROUPCACHEBEHAVIOR_FOLLOWCACHESTRATEGY : settings.cacheBehavior;
  44116. var rd = this._renderableData;
  44117. if (rd) {
  44118. rd._noResizeOnScale = (this.cacheBehavior & Group2D.GROUPCACHEBEHAVIOR_NORESIZEONSCALE) !== 0;
  44119. }
  44120. this.size = size;
  44121. this._viewportPosition = BABYLON.Vector2.Zero();
  44122. this._viewportSize = BABYLON.Size.Zero();
  44123. }
  44124. Group2D._createCachedCanvasGroup = function (owner) {
  44125. var g = new Group2D({ parent: owner, id: "__cachedCanvasGroup__", position: BABYLON.Vector2.Zero(), origin: BABYLON.Vector2.Zero(), size: null, isVisible: true, isPickable: false, dontInheritParentScale: true });
  44126. return g;
  44127. };
  44128. Group2D.prototype.applyCachedTexture = function (vertexData, material) {
  44129. this._bindCacheTarget();
  44130. if (vertexData) {
  44131. var uv = vertexData.uvs;
  44132. var nodeuv = this._renderableData._cacheNodeUVs;
  44133. for (var i = 0; i < 4; i++) {
  44134. uv[i * 2 + 0] = nodeuv[i].x;
  44135. uv[i * 2 + 1] = nodeuv[i].y;
  44136. }
  44137. }
  44138. if (material) {
  44139. material.diffuseTexture = this._renderableData._cacheTexture;
  44140. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  44141. }
  44142. this._renderableData._cacheTexture.hasAlpha = true;
  44143. this._unbindCacheTarget();
  44144. };
  44145. Object.defineProperty(Group2D.prototype, "cachedRect", {
  44146. /**
  44147. * Allow you to access the information regarding the cached rectangle of the Group2D into the MapTexture.
  44148. * 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.
  44149. */
  44150. get: function () {
  44151. if (!this._renderableData) {
  44152. return null;
  44153. }
  44154. return this._renderableData._cacheNode;
  44155. },
  44156. enumerable: true,
  44157. configurable: true
  44158. });
  44159. Object.defineProperty(Group2D.prototype, "cachedUVs", {
  44160. /**
  44161. * The UVs into the MapTexture that map the cached group
  44162. */
  44163. get: function () {
  44164. if (!this._renderableData) {
  44165. return null;
  44166. }
  44167. return this._renderableData._cacheNodeUVs;
  44168. },
  44169. enumerable: true,
  44170. configurable: true
  44171. });
  44172. Object.defineProperty(Group2D.prototype, "cachedUVsChanged", {
  44173. get: function () {
  44174. if (!this._renderableData) {
  44175. return null;
  44176. }
  44177. if (!this._renderableData._cacheNodeUVsChangedObservable) {
  44178. this._renderableData._cacheNodeUVsChangedObservable = new BABYLON.Observable();
  44179. }
  44180. return this._renderableData._cacheNodeUVsChangedObservable;
  44181. },
  44182. enumerable: true,
  44183. configurable: true
  44184. });
  44185. Object.defineProperty(Group2D.prototype, "cacheTexture", {
  44186. /**
  44187. * Access the texture that maintains a cached version of the Group2D.
  44188. * This is useful only if you're not using a WorldSpaceNode for your WorldSpace Canvas and therefore need to perform the rendering yourself.
  44189. */
  44190. get: function () {
  44191. if (!this._renderableData) {
  44192. return null;
  44193. }
  44194. return this._renderableData._cacheTexture;
  44195. },
  44196. enumerable: true,
  44197. configurable: true
  44198. });
  44199. /**
  44200. * Call this method to remove this Group and its children from the Canvas
  44201. */
  44202. Group2D.prototype.dispose = function () {
  44203. if (!_super.prototype.dispose.call(this)) {
  44204. return false;
  44205. }
  44206. if (this._trackedNode != null) {
  44207. this.owner._unregisterTrackedNode(this);
  44208. this._trackedNode = null;
  44209. }
  44210. if (this._renderableData) {
  44211. this._renderableData.dispose(this.owner);
  44212. this._renderableData = null;
  44213. }
  44214. return true;
  44215. };
  44216. Object.defineProperty(Group2D.prototype, "isRenderableGroup", {
  44217. /**
  44218. * @returns Returns true if the Group render content, false if it's a logical group only
  44219. */
  44220. get: function () {
  44221. return this._isRenderableGroup;
  44222. },
  44223. enumerable: true,
  44224. configurable: true
  44225. });
  44226. Object.defineProperty(Group2D.prototype, "isCachedGroup", {
  44227. /**
  44228. * @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
  44229. */
  44230. get: function () {
  44231. return this._isCachedGroup;
  44232. },
  44233. enumerable: true,
  44234. configurable: true
  44235. });
  44236. Object.defineProperty(Group2D.prototype, "size", {
  44237. get: function () {
  44238. return this._size;
  44239. },
  44240. /**
  44241. * Get/Set the size of the group. If null the size of the group will be determine from its content.
  44242. * 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.
  44243. */
  44244. set: function (val) {
  44245. this._size = val;
  44246. },
  44247. enumerable: true,
  44248. configurable: true
  44249. });
  44250. Object.defineProperty(Group2D.prototype, "viewportSize", {
  44251. get: function () {
  44252. return this._viewportSize;
  44253. },
  44254. enumerable: true,
  44255. configurable: true
  44256. });
  44257. Object.defineProperty(Group2D.prototype, "actualSize", {
  44258. get: function () {
  44259. // The computed size will be floor on both width and height
  44260. var actualSize;
  44261. // Return the actualSize if set
  44262. if (this._actualSize) {
  44263. return this._actualSize;
  44264. }
  44265. // Return the size if set by the user
  44266. if (this._size) {
  44267. actualSize = new BABYLON.Size(Math.ceil(this._size.width), Math.ceil(this._size.height));
  44268. }
  44269. else {
  44270. var m = this.layoutBoundingInfo.max();
  44271. actualSize = new BABYLON.Size(Math.ceil(m.x), Math.ceil(m.y));
  44272. }
  44273. // 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)
  44274. if (!actualSize.equals(this._actualSize)) {
  44275. this.onPrimitivePropertyDirty(Group2D.actualSizeProperty.flagId);
  44276. this._actualSize = actualSize;
  44277. this.handleGroupChanged(Group2D.actualSizeProperty);
  44278. }
  44279. return actualSize;
  44280. },
  44281. set: function (value) {
  44282. this._actualSize = value;
  44283. },
  44284. enumerable: true,
  44285. configurable: true
  44286. });
  44287. Object.defineProperty(Group2D.prototype, "cacheBehavior", {
  44288. /**
  44289. * 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.
  44290. * GROUPCACHEBEHAVIOR_NORESIZEONSCALE can also be set if you set it at creation time.
  44291. * 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.
  44292. */
  44293. get: function () {
  44294. return this._cacheBehavior;
  44295. },
  44296. enumerable: true,
  44297. configurable: true
  44298. });
  44299. Group2D.prototype._addPrimToDirtyList = function (prim) {
  44300. this._renderableData._primDirtyList.push(prim);
  44301. };
  44302. Group2D.prototype._renderCachedCanvas = function () {
  44303. this.owner._addGroupRenderCount(1);
  44304. this.updateCachedStates(true);
  44305. var context = new BABYLON.PrepareRender2DContext();
  44306. this._prepareGroupRender(context);
  44307. this._groupRender();
  44308. };
  44309. Object.defineProperty(Group2D.prototype, "trackedNode", {
  44310. /**
  44311. * Get/set the Scene's Node that should be tracked, the group's position will follow the projected position of the Node.
  44312. */
  44313. get: function () {
  44314. return this._trackedNode;
  44315. },
  44316. set: function (val) {
  44317. if (val != null) {
  44318. if (!this._isFlagSet(BABYLON.SmartPropertyPrim.flagTrackedGroup)) {
  44319. this.owner._registerTrackedNode(this);
  44320. }
  44321. this._trackedNode = val;
  44322. }
  44323. else {
  44324. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagTrackedGroup)) {
  44325. this.owner._unregisterTrackedNode(this);
  44326. }
  44327. this._trackedNode = null;
  44328. }
  44329. },
  44330. enumerable: true,
  44331. configurable: true
  44332. });
  44333. Group2D.prototype.levelIntersect = function (intersectInfo) {
  44334. // 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
  44335. return true;
  44336. };
  44337. Group2D.prototype.updateLevelBoundingInfo = function () {
  44338. var size;
  44339. // If the size is set by the user, the boundingInfo is computed from this value
  44340. if (this.size) {
  44341. size = this.size;
  44342. }
  44343. else {
  44344. size = new BABYLON.Size(0, 0);
  44345. }
  44346. BABYLON.BoundingInfo2D.CreateFromSizeToRef(size, this._levelBoundingInfo);
  44347. };
  44348. // Method called only on renderable groups to prepare the rendering
  44349. Group2D.prototype._prepareGroupRender = function (context) {
  44350. var sortedDirtyList = null;
  44351. // Update the Global Transformation and visibility status of the changed primitives
  44352. var rd = this._renderableData;
  44353. if ((rd._primDirtyList.length > 0) || context.forceRefreshPrimitive) {
  44354. sortedDirtyList = rd._primDirtyList.sort(function (a, b) { return a.hierarchyDepth - b.hierarchyDepth; });
  44355. this.updateCachedStatesOf(sortedDirtyList, true);
  44356. }
  44357. var s = this.actualSize;
  44358. var a = this.actualScale;
  44359. var sw = Math.ceil(s.width * a.x);
  44360. var sh = Math.ceil(s.height * a.y);
  44361. // The dimension must be overridden when using the designSize feature, the ratio is maintain to compute a uniform scale, which is mandatory but if the designSize's ratio is different from the rendering surface's ratio, content will be clipped in some cases.
  44362. // So we set the width/height to the rendering's one because that's what we want for the viewport!
  44363. if (this instanceof BABYLON.Canvas2D) {
  44364. var c = this;
  44365. if (c.designSize != null) {
  44366. sw = this.owner.engine.getRenderWidth();
  44367. sh = this.owner.engine.getRenderHeight();
  44368. }
  44369. }
  44370. // Setup the size of the rendering viewport
  44371. // 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
  44372. if (!this._isCachedGroup) {
  44373. // Compute the WebGL viewport's location/size
  44374. var t = this._globalTransform.getTranslation();
  44375. var rs = this.owner._renderingSize;
  44376. sh = Math.min(sh, rs.height - t.y);
  44377. sw = Math.min(sw, rs.width - t.x);
  44378. var x = t.x;
  44379. var y = t.y;
  44380. // 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
  44381. this._viewportPosition.x = x;
  44382. this._viewportPosition.y = y;
  44383. }
  44384. // For a cachedGroup we also check of the group's actualSize is changing, if it's the case then the rendering zone will be change so we also have to dirty all primitives to prepare them again.
  44385. if (this._viewportSize.width !== sw || this._viewportSize.height !== sh) {
  44386. context.forceRefreshPrimitive = true;
  44387. this._viewportSize.width = sw;
  44388. this._viewportSize.height = sh;
  44389. }
  44390. if ((rd._primDirtyList.length > 0) || context.forceRefreshPrimitive) {
  44391. // If the group is cached, set the dirty flag to true because of the incoming changes
  44392. this._cacheGroupDirty = this._isCachedGroup;
  44393. rd._primNewDirtyList.splice(0);
  44394. // If it's a force refresh, prepare all the children
  44395. if (context.forceRefreshPrimitive) {
  44396. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  44397. var p = _a[_i];
  44398. p._prepareRender(context);
  44399. }
  44400. }
  44401. else {
  44402. // Each primitive that changed at least once was added into the primDirtyList, we have to sort this level using
  44403. // the hierarchyDepth in order to prepare primitives from top to bottom
  44404. if (!sortedDirtyList) {
  44405. sortedDirtyList = rd._primDirtyList.sort(function (a, b) { return a.hierarchyDepth - b.hierarchyDepth; });
  44406. }
  44407. sortedDirtyList.forEach(function (p) {
  44408. // 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.
  44409. // 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.
  44410. if (!p.isDisposed && p._needPrepare()) {
  44411. p._prepareRender(context);
  44412. }
  44413. });
  44414. }
  44415. // Everything is updated, clear the dirty list
  44416. rd._primDirtyList.forEach(function (p) {
  44417. if (rd._primNewDirtyList.indexOf(p) === -1) {
  44418. p._resetPropertiesDirty();
  44419. }
  44420. else {
  44421. p._setFlags(BABYLON.SmartPropertyPrim.flagNeedRefresh);
  44422. }
  44423. });
  44424. rd._primDirtyList.splice(0);
  44425. rd._primDirtyList = rd._primDirtyList.concat(rd._primNewDirtyList);
  44426. }
  44427. // A renderable group has a list of direct children that are also renderable groups, we recurse on them to also prepare them
  44428. rd._childrenRenderableGroups.forEach(function (g) {
  44429. g._prepareGroupRender(context);
  44430. });
  44431. };
  44432. Group2D.prototype._groupRender = function () {
  44433. var _this = this;
  44434. var engine = this.owner.engine;
  44435. var failedCount = 0;
  44436. // First recurse to children render group to render them (in their cache or on screen)
  44437. for (var _i = 0, _a = this._renderableData._childrenRenderableGroups; _i < _a.length; _i++) {
  44438. var childGroup = _a[_i];
  44439. childGroup._groupRender();
  44440. }
  44441. // Render the primitives if needed: either if we don't cache the content or if the content is cached but has changed
  44442. if (!this.isCachedGroup || this._cacheGroupDirty) {
  44443. this.owner._addGroupRenderCount(1);
  44444. if (this.isCachedGroup) {
  44445. this._bindCacheTarget();
  44446. }
  44447. else {
  44448. var curVP = engine.setDirectViewport(this._viewportPosition.x, this._viewportPosition.y, this._viewportSize.width, this._viewportSize.height);
  44449. }
  44450. var curAlphaTest = engine.getAlphaTesting() === true;
  44451. var curDepthWrite = engine.getDepthWrite() === true;
  44452. // ===================================================================
  44453. // First pass, update the InstancedArray and render Opaque primitives
  44454. // Disable Alpha Testing, Enable Depth Write
  44455. engine.setAlphaTesting(false);
  44456. engine.setDepthWrite(true);
  44457. // For each different model of primitive to render
  44458. var context_1 = new BABYLON.Render2DContext(BABYLON.Render2DContext.RenderModeOpaque);
  44459. this._renderableData._renderGroupInstancesInfo.forEach(function (k, v) {
  44460. // Prepare the context object, update the WebGL Instanced Array buffer if needed
  44461. var renderCount = _this._prepareContext(engine, context_1, v);
  44462. // If null is returned, there's no opaque data to render
  44463. if (renderCount === null) {
  44464. return;
  44465. }
  44466. // Submit render only if we have something to render (everything may be hidden and the floatarray empty)
  44467. if (!_this.owner.supportInstancedArray || renderCount > 0) {
  44468. // render all the instances of this model, if the render method returns true then our instances are no longer dirty
  44469. var renderFailed = !v.modelRenderCache.render(v, context_1);
  44470. // Update dirty flag/related
  44471. v.opaqueDirty = renderFailed;
  44472. failedCount += renderFailed ? 1 : 0;
  44473. }
  44474. });
  44475. // =======================================================================
  44476. // Second pass, update the InstancedArray and render AlphaTest primitives
  44477. // Enable Alpha Testing, Enable Depth Write
  44478. engine.setAlphaTesting(true);
  44479. engine.setDepthWrite(true);
  44480. // For each different model of primitive to render
  44481. context_1 = new BABYLON.Render2DContext(BABYLON.Render2DContext.RenderModeAlphaTest);
  44482. this._renderableData._renderGroupInstancesInfo.forEach(function (k, v) {
  44483. // Prepare the context object, update the WebGL Instanced Array buffer if needed
  44484. var renderCount = _this._prepareContext(engine, context_1, v);
  44485. // If null is returned, there's no opaque data to render
  44486. if (renderCount === null) {
  44487. return;
  44488. }
  44489. // Submit render only if we have something to render (everything may be hidden and the floatarray empty)
  44490. if (!_this.owner.supportInstancedArray || renderCount > 0) {
  44491. // render all the instances of this model, if the render method returns true then our instances are no longer dirty
  44492. var renderFailed = !v.modelRenderCache.render(v, context_1);
  44493. // Update dirty flag/related
  44494. v.opaqueDirty = renderFailed;
  44495. failedCount += renderFailed ? 1 : 0;
  44496. }
  44497. });
  44498. // =======================================================================
  44499. // Third pass, transparent primitive rendering
  44500. // Enable Alpha Testing, Disable Depth Write
  44501. engine.setAlphaTesting(true);
  44502. engine.setDepthWrite(false);
  44503. // First Check if the transparent List change so we can update the TransparentSegment and PartData (sort if needed)
  44504. if (this._renderableData._transparentListChanged) {
  44505. this._updateTransparentData();
  44506. }
  44507. // From this point on we have up to date data to render, so let's go
  44508. failedCount += this._renderTransparentData();
  44509. // =======================================================================
  44510. // Unbind target/restore viewport setting, clear dirty flag, and quit
  44511. // The group's content is no longer dirty
  44512. this._cacheGroupDirty = failedCount !== 0;
  44513. if (this.isCachedGroup) {
  44514. this._unbindCacheTarget();
  44515. }
  44516. else {
  44517. if (curVP) {
  44518. engine.setViewport(curVP);
  44519. }
  44520. }
  44521. // Restore saved states
  44522. engine.setAlphaTesting(curAlphaTest);
  44523. engine.setDepthWrite(curDepthWrite);
  44524. }
  44525. };
  44526. Group2D.prototype._setCacheGroupDirty = function () {
  44527. this._cacheGroupDirty = true;
  44528. };
  44529. Group2D.prototype._updateTransparentData = function () {
  44530. this.owner._addUpdateTransparentDataCount(1);
  44531. var rd = this._renderableData;
  44532. // Sort all the primitive from their depth, max (bottom) to min (top)
  44533. rd._transparentPrimitives.sort(function (a, b) { return b._primitive.actualZOffset - a._primitive.actualZOffset; });
  44534. var checkAndAddPrimInSegment = function (seg, tpiI) {
  44535. var tpi = rd._transparentPrimitives[tpiI];
  44536. // Fast rejection: if gii are different
  44537. if (seg.groupInsanceInfo !== tpi._groupInstanceInfo) {
  44538. return false;
  44539. }
  44540. //let tpiZ = tpi._primitive.actualZOffset;
  44541. // We've made it so far, the tpi can be part of the segment, add it
  44542. tpi._transparentSegment = seg;
  44543. tpi._primitive._updateTransparentSegmentIndices(seg);
  44544. return true;
  44545. };
  44546. // Free the existing TransparentSegments
  44547. for (var _i = 0, _a = rd._transparentSegments; _i < _a.length; _i++) {
  44548. var ts = _a[_i];
  44549. ts.dispose(this.owner.engine);
  44550. }
  44551. rd._transparentSegments.splice(0);
  44552. var prevSeg = null;
  44553. for (var tpiI = 0; tpiI < rd._transparentPrimitives.length; tpiI++) {
  44554. var tpi = rd._transparentPrimitives[tpiI];
  44555. // Check if the Data in which the primitive is stored is not sorted properly
  44556. if (tpi._groupInstanceInfo.transparentOrderDirty) {
  44557. tpi._groupInstanceInfo.sortTransparentData();
  44558. }
  44559. // Reset the segment, we have to create/rebuild it
  44560. tpi._transparentSegment = null;
  44561. // If there's a previous valid segment, check if this prim can be part of it
  44562. if (prevSeg) {
  44563. checkAndAddPrimInSegment(prevSeg, tpiI);
  44564. }
  44565. // If we couldn't insert in the adjacent segments, he have to create one
  44566. if (!tpi._transparentSegment) {
  44567. var ts = new BABYLON.TransparentSegment();
  44568. ts.groupInsanceInfo = tpi._groupInstanceInfo;
  44569. var prim = tpi._primitive;
  44570. ts.startZ = prim.actualZOffset;
  44571. prim._updateTransparentSegmentIndices(ts);
  44572. ts.endZ = ts.startZ;
  44573. tpi._transparentSegment = ts;
  44574. rd._transparentSegments.push(ts);
  44575. }
  44576. // Update prevSeg
  44577. prevSeg = tpi._transparentSegment;
  44578. }
  44579. //rd._firstChangedPrim = null;
  44580. rd._transparentListChanged = false;
  44581. };
  44582. Group2D.prototype._renderTransparentData = function () {
  44583. var failedCount = 0;
  44584. var context = new BABYLON.Render2DContext(BABYLON.Render2DContext.RenderModeTransparent);
  44585. var rd = this._renderableData;
  44586. var useInstanced = this.owner.supportInstancedArray;
  44587. var length = rd._transparentSegments.length;
  44588. for (var i = 0; i < length; i++) {
  44589. context.instancedBuffers = null;
  44590. var ts = rd._transparentSegments[i];
  44591. var gii = ts.groupInsanceInfo;
  44592. var mrc = gii.modelRenderCache;
  44593. var engine = this.owner.engine;
  44594. var count = ts.endDataIndex - ts.startDataIndex;
  44595. // Use Instanced Array if it's supported and if there's at least 5 prims to draw.
  44596. // We don't want to create an Instanced Buffer for less that 5 prims
  44597. if (useInstanced && count >= 5) {
  44598. if (!ts.partBuffers) {
  44599. var buffers = new Array();
  44600. for (var j = 0; j < gii.transparentData.length; j++) {
  44601. var gitd = gii.transparentData[j];
  44602. var dfa = gitd._partData;
  44603. var data = dfa.pack();
  44604. var stride = dfa.stride;
  44605. var neededSize = count * stride * 4;
  44606. var buffer = engine.createInstancesBuffer(neededSize); // Create + bind
  44607. var segData = data.subarray(ts.startDataIndex * stride, ts.endDataIndex * stride);
  44608. engine.updateArrayBuffer(segData);
  44609. buffers.push(buffer);
  44610. }
  44611. ts.partBuffers = buffers;
  44612. }
  44613. else if (gii.transparentDirty) {
  44614. for (var j = 0; j < gii.transparentData.length; j++) {
  44615. var gitd = gii.transparentData[j];
  44616. var dfa = gitd._partData;
  44617. var data = dfa.pack();
  44618. var stride = dfa.stride;
  44619. var buffer = ts.partBuffers[j];
  44620. var segData = data.subarray(ts.startDataIndex * stride, ts.endDataIndex * stride);
  44621. engine.bindArrayBuffer(buffer);
  44622. engine.updateArrayBuffer(segData);
  44623. }
  44624. }
  44625. context.useInstancing = true;
  44626. context.instancesCount = count;
  44627. context.instancedBuffers = ts.partBuffers;
  44628. context.groupInfoPartData = gii.transparentData;
  44629. var renderFailed = !mrc.render(gii, context);
  44630. failedCount += renderFailed ? 1 : 0;
  44631. }
  44632. else {
  44633. context.useInstancing = false;
  44634. context.partDataStartIndex = ts.startDataIndex;
  44635. context.partDataEndIndex = ts.endDataIndex;
  44636. context.groupInfoPartData = gii.transparentData;
  44637. var renderFailed = !mrc.render(gii, context);
  44638. failedCount += renderFailed ? 1 : 0;
  44639. }
  44640. }
  44641. return failedCount;
  44642. };
  44643. Group2D.prototype._prepareContext = function (engine, context, gii) {
  44644. var gipd = null;
  44645. var setDirty;
  44646. var getDirty;
  44647. // Render Mode specifics
  44648. switch (context.renderMode) {
  44649. case BABYLON.Render2DContext.RenderModeOpaque:
  44650. {
  44651. if (!gii.hasOpaqueData) {
  44652. return null;
  44653. }
  44654. setDirty = function (dirty) { gii.opaqueDirty = dirty; };
  44655. getDirty = function () { return gii.opaqueDirty; };
  44656. context.groupInfoPartData = gii.opaqueData;
  44657. gipd = gii.opaqueData;
  44658. break;
  44659. }
  44660. case BABYLON.Render2DContext.RenderModeAlphaTest:
  44661. {
  44662. if (!gii.hasAlphaTestData) {
  44663. return null;
  44664. }
  44665. setDirty = function (dirty) { gii.alphaTestDirty = dirty; };
  44666. getDirty = function () { return gii.alphaTestDirty; };
  44667. context.groupInfoPartData = gii.alphaTestData;
  44668. gipd = gii.alphaTestData;
  44669. break;
  44670. }
  44671. default:
  44672. throw new Error("_prepareContext is only for opaque or alphaTest");
  44673. }
  44674. var renderCount = 0;
  44675. // This part will pack the dynamicfloatarray and update the instanced array WebGLBufffer
  44676. // Skip it if instanced arrays are not supported
  44677. if (this.owner.supportInstancedArray) {
  44678. // Flag for instancing
  44679. context.useInstancing = true;
  44680. // Make sure all the WebGLBuffers of the Instanced Array are created/up to date for the parts to render.
  44681. for (var i = 0; i < gipd.length; i++) {
  44682. var pid = gipd[i];
  44683. // If the instances of the model was changed, pack the data
  44684. var array = pid._partData;
  44685. var instanceData_1 = array.pack();
  44686. renderCount += array.usedElementCount;
  44687. // Compute the size the instance buffer should have
  44688. var neededSize = array.usedElementCount * array.stride * 4;
  44689. // Check if we have to (re)create the instancesBuffer because there's none or the size is too small
  44690. if (!pid._partBuffer || (pid._partBufferSize < neededSize)) {
  44691. if (pid._partBuffer) {
  44692. engine.deleteInstancesBuffer(pid._partBuffer);
  44693. }
  44694. pid._partBuffer = engine.createInstancesBuffer(neededSize); // Create + bind
  44695. pid._partBufferSize = neededSize;
  44696. setDirty(false);
  44697. // Update the WebGL buffer to match the new content of the instances data
  44698. engine.updateArrayBuffer(instanceData_1);
  44699. }
  44700. else if (getDirty()) {
  44701. // Update the WebGL buffer to match the new content of the instances data
  44702. engine.bindArrayBuffer(pid._partBuffer);
  44703. engine.updateArrayBuffer(instanceData_1);
  44704. }
  44705. }
  44706. setDirty(false);
  44707. }
  44708. else {
  44709. context.partDataStartIndex = 0;
  44710. // Find the first valid object to get the count
  44711. if (context.groupInfoPartData.length > 0) {
  44712. var i = 0;
  44713. while (!context.groupInfoPartData[i]) {
  44714. i++;
  44715. }
  44716. context.partDataEndIndex = context.groupInfoPartData[i]._partData.usedElementCount;
  44717. }
  44718. }
  44719. return renderCount;
  44720. };
  44721. Group2D.prototype._setRenderingScale = function (scale) {
  44722. if (this._renderableData._renderingScale === scale) {
  44723. return;
  44724. }
  44725. this._renderableData._renderingScale = scale;
  44726. };
  44727. Group2D.prototype._bindCacheTarget = function () {
  44728. var curWidth;
  44729. var curHeight;
  44730. var rd = this._renderableData;
  44731. var rs = rd._renderingScale;
  44732. var noResizeScale = rd._noResizeOnScale;
  44733. var isCanvas = this.parent == null;
  44734. var scale;
  44735. if (noResizeScale) {
  44736. scale = isCanvas ? Group2D._uV : this.parent.actualScale;
  44737. }
  44738. else {
  44739. scale = this.actualScale;
  44740. }
  44741. Group2D._s.width = Math.ceil(this.actualSize.width * scale.x * rs);
  44742. Group2D._s.height = Math.ceil(this.actualSize.height * scale.y * rs);
  44743. var sizeChanged = !Group2D._s.equals(rd._cacheSize);
  44744. if (rd._cacheNode) {
  44745. var size = rd._cacheNode.contentSize;
  44746. // Check if we have to deallocate because the size is too small
  44747. if ((size.width < Group2D._s.width) || (size.height < Group2D._s.height)) {
  44748. // For Screen space: over-provisioning of 7% more to avoid frequent resizing for few pixels...
  44749. // For World space: no over-provisioning
  44750. var overprovisioning = this.owner.isScreenSpace ? 1.07 : 1;
  44751. curWidth = Math.floor(Group2D._s.width * overprovisioning);
  44752. curHeight = Math.floor(Group2D._s.height * overprovisioning);
  44753. //console.log(`[${this._globalTransformProcessStep}] Resize group ${this.id}, width: ${curWidth}, height: ${curHeight}`);
  44754. rd._cacheTexture.freeRect(rd._cacheNode);
  44755. rd._cacheNode = null;
  44756. }
  44757. }
  44758. if (!rd._cacheNode) {
  44759. // Check if we have to allocate a rendering zone in the global cache texture
  44760. var res = this.owner._allocateGroupCache(this, this.parent && this.parent.renderGroup, curWidth ? new BABYLON.Size(curWidth, curHeight) : null, rd._useMipMap, rd._anisotropicLevel);
  44761. rd._cacheNode = res.node;
  44762. rd._cacheTexture = res.texture;
  44763. rd._cacheRenderSprite = res.sprite;
  44764. sizeChanged = true;
  44765. }
  44766. if (sizeChanged) {
  44767. rd._cacheSize.copyFrom(Group2D._s);
  44768. rd._cacheNodeUVs = rd._cacheNode.getUVsForCustomSize(rd._cacheSize);
  44769. if (rd._cacheNodeUVsChangedObservable && rd._cacheNodeUVsChangedObservable.hasObservers()) {
  44770. rd._cacheNodeUVsChangedObservable.notifyObservers(rd._cacheNodeUVs);
  44771. }
  44772. this._setFlags(BABYLON.SmartPropertyPrim.flagWorldCacheChanged);
  44773. }
  44774. var n = rd._cacheNode;
  44775. rd._cacheTexture.bindTextureForPosSize(n.pos, Group2D._s, true);
  44776. };
  44777. Group2D.prototype._unbindCacheTarget = function () {
  44778. if (this._renderableData._cacheTexture) {
  44779. this._renderableData._cacheTexture.unbindTexture();
  44780. }
  44781. };
  44782. Group2D.prototype.handleGroupChanged = function (prop) {
  44783. // This method is only for cachedGroup
  44784. var rd = this._renderableData;
  44785. if (!rd) {
  44786. return;
  44787. }
  44788. var cachedSprite = rd._cacheRenderSprite;
  44789. if (!this.isCachedGroup || !cachedSprite) {
  44790. return;
  44791. }
  44792. // For now we only support these property changes
  44793. // TODO: add more! :)
  44794. if (prop.id === BABYLON.Prim2DBase.actualPositionProperty.id) {
  44795. cachedSprite.actualPosition = this.actualPosition.clone();
  44796. if (cachedSprite.position != null) {
  44797. cachedSprite.position = cachedSprite.actualPosition.clone();
  44798. }
  44799. }
  44800. else if (prop.id === BABYLON.Prim2DBase.rotationProperty.id) {
  44801. cachedSprite.rotation = this.rotation;
  44802. }
  44803. else if (prop.id === BABYLON.Prim2DBase.scaleProperty.id) {
  44804. cachedSprite.scale = this.scale;
  44805. }
  44806. else if (prop.id === BABYLON.Prim2DBase.originProperty.id) {
  44807. cachedSprite.origin = this.origin.clone();
  44808. }
  44809. else if (prop.id === Group2D.actualSizeProperty.id) {
  44810. cachedSprite.size = this.actualSize.clone();
  44811. }
  44812. };
  44813. Group2D.prototype.detectGroupStates = function () {
  44814. var isCanvas = this instanceof BABYLON.Canvas2D;
  44815. var canvasStrat = this.owner.cachingStrategy;
  44816. // In Don't Cache mode, only the canvas is renderable, all the other groups are logical. There are not a single cached group.
  44817. if (canvasStrat === BABYLON.Canvas2D.CACHESTRATEGY_DONTCACHE) {
  44818. this._isRenderableGroup = isCanvas;
  44819. this._isCachedGroup = false;
  44820. }
  44821. else if (canvasStrat === BABYLON.Canvas2D.CACHESTRATEGY_CANVAS) {
  44822. if (isCanvas) {
  44823. this._isRenderableGroup = true;
  44824. this._isCachedGroup = true;
  44825. }
  44826. else {
  44827. this._isRenderableGroup = this.id === "__cachedCanvasGroup__";
  44828. this._isCachedGroup = false;
  44829. }
  44830. }
  44831. else if (canvasStrat === BABYLON.Canvas2D.CACHESTRATEGY_TOPLEVELGROUPS) {
  44832. if (isCanvas) {
  44833. this._isRenderableGroup = true;
  44834. this._isCachedGroup = false;
  44835. }
  44836. else {
  44837. if (this.hierarchyDepth === 1) {
  44838. this._isRenderableGroup = true;
  44839. this._isCachedGroup = true;
  44840. }
  44841. else {
  44842. this._isRenderableGroup = false;
  44843. this._isCachedGroup = false;
  44844. }
  44845. }
  44846. }
  44847. else if (canvasStrat === BABYLON.Canvas2D.CACHESTRATEGY_ALLGROUPS) {
  44848. var gcb = this.cacheBehavior & Group2D.GROUPCACHEBEHAVIOR_OPTIONMASK;
  44849. if ((gcb === Group2D.GROUPCACHEBEHAVIOR_DONTCACHEOVERRIDE) || (gcb === Group2D.GROUPCACHEBEHAVIOR_CACHEINPARENTGROUP)) {
  44850. this._isRenderableGroup = gcb === Group2D.GROUPCACHEBEHAVIOR_DONTCACHEOVERRIDE;
  44851. this._isCachedGroup = false;
  44852. }
  44853. if (gcb === Group2D.GROUPCACHEBEHAVIOR_FOLLOWCACHESTRATEGY) {
  44854. this._isRenderableGroup = true;
  44855. this._isCachedGroup = true;
  44856. }
  44857. }
  44858. if (this._isRenderableGroup) {
  44859. // Yes, we do need that check, trust me, unfortunately we can call _detectGroupStates many time on the same object...
  44860. if (!this._renderableData) {
  44861. this._renderableData = new RenderableGroupData();
  44862. }
  44863. }
  44864. // If the group is tagged as renderable we add it to the renderable tree
  44865. if (this._isCachedGroup) {
  44866. this._renderableData._noResizeOnScale = (this.cacheBehavior & Group2D.GROUPCACHEBEHAVIOR_NORESIZEONSCALE) !== 0;
  44867. var cur = this.parent;
  44868. while (cur) {
  44869. if (cur instanceof Group2D && cur._isRenderableGroup) {
  44870. if (cur._renderableData._childrenRenderableGroups.indexOf(this) === -1) {
  44871. cur._renderableData._childrenRenderableGroups.push(this);
  44872. }
  44873. break;
  44874. }
  44875. cur = cur.parent;
  44876. }
  44877. }
  44878. };
  44879. Group2D.GROUP2D_PROPCOUNT = BABYLON.Prim2DBase.PRIM2DBASE_PROPCOUNT + 5;
  44880. /**
  44881. * Default behavior, the group will use the caching strategy defined at the Canvas Level
  44882. */
  44883. Group2D.GROUPCACHEBEHAVIOR_FOLLOWCACHESTRATEGY = 0;
  44884. /**
  44885. * When used, this group's content won't be cached, no matter which strategy used.
  44886. * If the group is part of a WorldSpace Canvas, its content will be drawn in the Canvas cache bitmap.
  44887. */
  44888. Group2D.GROUPCACHEBEHAVIOR_DONTCACHEOVERRIDE = 1;
  44889. /**
  44890. * When used, the group's content will be cached in the nearest cached parent group/canvas
  44891. */
  44892. Group2D.GROUPCACHEBEHAVIOR_CACHEINPARENTGROUP = 2;
  44893. /**
  44894. * You can specify this behavior to any cached Group2D to indicate that you don't want the cached content to be resized when the Group's actualScale is changing. It will draw the content stretched or shrink which is faster than a resize. This setting is obviously for performance consideration, don't use it if you want the best rendering quality
  44895. */
  44896. Group2D.GROUPCACHEBEHAVIOR_NORESIZEONSCALE = 0x100;
  44897. Group2D.GROUPCACHEBEHAVIOR_OPTIONMASK = 0xFF;
  44898. Group2D._uV = new BABYLON.Vector2(1, 1);
  44899. Group2D._s = BABYLON.Size.Zero();
  44900. __decorate([
  44901. BABYLON.instanceLevelProperty(BABYLON.Prim2DBase.PRIM2DBASE_PROPCOUNT + 1, function (pi) { return Group2D.sizeProperty = pi; }, false, true)
  44902. ], Group2D.prototype, "size", null);
  44903. __decorate([
  44904. BABYLON.instanceLevelProperty(BABYLON.Prim2DBase.PRIM2DBASE_PROPCOUNT + 2, function (pi) { return Group2D.actualSizeProperty = pi; })
  44905. ], Group2D.prototype, "actualSize", null);
  44906. Group2D = __decorate([
  44907. BABYLON.className("Group2D")
  44908. ], Group2D);
  44909. return Group2D;
  44910. }(BABYLON.Prim2DBase));
  44911. BABYLON.Group2D = Group2D;
  44912. var RenderableGroupData = (function () {
  44913. function RenderableGroupData() {
  44914. this._primDirtyList = new Array();
  44915. this._primNewDirtyList = new Array();
  44916. this._childrenRenderableGroups = new Array();
  44917. this._renderGroupInstancesInfo = new BABYLON.StringDictionary();
  44918. this._transparentPrimitives = new Array();
  44919. this._transparentSegments = new Array();
  44920. this._transparentListChanged = false;
  44921. this._cacheNode = null;
  44922. this._cacheTexture = null;
  44923. this._cacheRenderSprite = null;
  44924. this._renderingScale = 1;
  44925. this._cacheNodeUVs = null;
  44926. this._cacheNodeUVsChangedObservable = null;
  44927. this._cacheSize = BABYLON.Size.Zero();
  44928. this._useMipMap = false;
  44929. this._anisotropicLevel = 1;
  44930. this._noResizeOnScale = false;
  44931. }
  44932. RenderableGroupData.prototype.dispose = function (owner) {
  44933. var engine = owner.engine;
  44934. if (this._cacheRenderSprite) {
  44935. this._cacheRenderSprite.dispose();
  44936. this._cacheRenderSprite = null;
  44937. }
  44938. if (this._cacheTexture && this._cacheNode) {
  44939. this._cacheTexture.freeRect(this._cacheNode);
  44940. this._cacheTexture = null;
  44941. this._cacheNode = null;
  44942. }
  44943. if (this._primDirtyList) {
  44944. this._primDirtyList.splice(0);
  44945. this._primDirtyList = null;
  44946. }
  44947. if (this._renderGroupInstancesInfo) {
  44948. this._renderGroupInstancesInfo.forEach(function (k, v) {
  44949. v.dispose();
  44950. });
  44951. this._renderGroupInstancesInfo = null;
  44952. }
  44953. if (this._cacheNodeUVsChangedObservable) {
  44954. this._cacheNodeUVsChangedObservable.clear();
  44955. this._cacheNodeUVsChangedObservable = null;
  44956. }
  44957. if (this._transparentSegments) {
  44958. for (var _i = 0, _a = this._transparentSegments; _i < _a.length; _i++) {
  44959. var ts = _a[_i];
  44960. ts.dispose(engine);
  44961. }
  44962. this._transparentSegments.splice(0);
  44963. this._transparentSegments = null;
  44964. }
  44965. };
  44966. RenderableGroupData.prototype.addNewTransparentPrimitiveInfo = function (prim, gii) {
  44967. var tpi = new TransparentPrimitiveInfo();
  44968. tpi._primitive = prim;
  44969. tpi._groupInstanceInfo = gii;
  44970. tpi._transparentSegment = null;
  44971. this._transparentPrimitives.push(tpi);
  44972. this._transparentListChanged = true;
  44973. return tpi;
  44974. };
  44975. RenderableGroupData.prototype.removeTransparentPrimitiveInfo = function (tpi) {
  44976. var index = this._transparentPrimitives.indexOf(tpi);
  44977. if (index !== -1) {
  44978. this._transparentPrimitives.splice(index, 1);
  44979. this._transparentListChanged = true;
  44980. }
  44981. };
  44982. RenderableGroupData.prototype.transparentPrimitiveZChanged = function (tpi) {
  44983. this._transparentListChanged = true;
  44984. //this.updateSmallestZChangedPrim(tpi);
  44985. };
  44986. return RenderableGroupData;
  44987. }());
  44988. BABYLON.RenderableGroupData = RenderableGroupData;
  44989. var TransparentPrimitiveInfo = (function () {
  44990. function TransparentPrimitiveInfo() {
  44991. }
  44992. return TransparentPrimitiveInfo;
  44993. }());
  44994. BABYLON.TransparentPrimitiveInfo = TransparentPrimitiveInfo;
  44995. })(BABYLON || (BABYLON = {}));
  44996. var BABYLON;
  44997. (function (BABYLON) {
  44998. var Rectangle2DRenderCache = (function (_super) {
  44999. __extends(Rectangle2DRenderCache, _super);
  45000. function Rectangle2DRenderCache(engine, modelKey) {
  45001. _super.call(this, engine, modelKey);
  45002. this.effectsReady = false;
  45003. this.fillVB = null;
  45004. this.fillIB = null;
  45005. this.fillIndicesCount = 0;
  45006. this.instancingFillAttributes = null;
  45007. this.effectFill = null;
  45008. this.effectFillInstanced = null;
  45009. this.borderVB = null;
  45010. this.borderIB = null;
  45011. this.borderIndicesCount = 0;
  45012. this.instancingBorderAttributes = null;
  45013. this.effectBorder = null;
  45014. this.effectBorderInstanced = null;
  45015. }
  45016. Rectangle2DRenderCache.prototype.render = function (instanceInfo, context) {
  45017. // Do nothing if the shader is still loading/preparing
  45018. if (!this.effectsReady) {
  45019. if ((this.effectFill && (!this.effectFill.isReady() || (this.effectFillInstanced && !this.effectFillInstanced.isReady()))) ||
  45020. (this.effectBorder && (!this.effectBorder.isReady() || (this.effectBorderInstanced && !this.effectBorderInstanced.isReady())))) {
  45021. return false;
  45022. }
  45023. this.effectsReady = true;
  45024. }
  45025. var canvas = instanceInfo.owner.owner;
  45026. var engine = canvas.engine;
  45027. var depthFunction = 0;
  45028. if (this.effectFill && this.effectBorder) {
  45029. depthFunction = engine.getDepthFunction();
  45030. engine.setDepthFunctionToLessOrEqual();
  45031. }
  45032. var curAlphaMode = engine.getAlphaMode();
  45033. if (this.effectFill) {
  45034. var partIndex = instanceInfo.partIndexFromId.get(BABYLON.Shape2D.SHAPE2D_FILLPARTID.toString());
  45035. var pid = context.groupInfoPartData[partIndex];
  45036. if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
  45037. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE, true);
  45038. }
  45039. var effect = context.useInstancing ? this.effectFillInstanced : this.effectFill;
  45040. engine.enableEffect(effect);
  45041. engine.bindBuffersDirectly(this.fillVB, this.fillIB, [1], 4, effect);
  45042. if (context.useInstancing) {
  45043. if (!this.instancingFillAttributes) {
  45044. this.instancingFillAttributes = this.loadInstancingAttributes(BABYLON.Shape2D.SHAPE2D_FILLPARTID, effect);
  45045. }
  45046. var glBuffer = context.instancedBuffers ? context.instancedBuffers[partIndex] : pid._partBuffer;
  45047. var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
  45048. canvas._addDrawCallCount(1, context.renderMode);
  45049. engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingFillAttributes);
  45050. engine.draw(true, 0, this.fillIndicesCount, count);
  45051. engine.unbindInstanceAttributes();
  45052. }
  45053. else {
  45054. canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
  45055. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  45056. this.setupUniforms(effect, partIndex, pid._partData, i);
  45057. engine.draw(true, 0, this.fillIndicesCount);
  45058. }
  45059. }
  45060. }
  45061. if (this.effectBorder) {
  45062. var partIndex = instanceInfo.partIndexFromId.get(BABYLON.Shape2D.SHAPE2D_BORDERPARTID.toString());
  45063. var pid = context.groupInfoPartData[partIndex];
  45064. if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
  45065. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE, true);
  45066. }
  45067. var effect = context.useInstancing ? this.effectBorderInstanced : this.effectBorder;
  45068. engine.enableEffect(effect);
  45069. engine.bindBuffersDirectly(this.borderVB, this.borderIB, [1], 4, effect);
  45070. if (context.useInstancing) {
  45071. if (!this.instancingBorderAttributes) {
  45072. this.instancingBorderAttributes = this.loadInstancingAttributes(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, effect);
  45073. }
  45074. var glBuffer = context.instancedBuffers ? context.instancedBuffers[partIndex] : pid._partBuffer;
  45075. var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
  45076. canvas._addDrawCallCount(1, context.renderMode);
  45077. engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingBorderAttributes);
  45078. engine.draw(true, 0, this.borderIndicesCount, count);
  45079. engine.unbindInstanceAttributes();
  45080. }
  45081. else {
  45082. canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
  45083. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  45084. this.setupUniforms(effect, partIndex, pid._partData, i);
  45085. engine.draw(true, 0, this.borderIndicesCount);
  45086. }
  45087. }
  45088. }
  45089. engine.setAlphaMode(curAlphaMode, true);
  45090. if (this.effectFill && this.effectBorder) {
  45091. engine.setDepthFunction(depthFunction);
  45092. }
  45093. return true;
  45094. };
  45095. Rectangle2DRenderCache.prototype.dispose = function () {
  45096. if (!_super.prototype.dispose.call(this)) {
  45097. return false;
  45098. }
  45099. if (this.fillVB) {
  45100. this._engine._releaseBuffer(this.fillVB);
  45101. this.fillVB = null;
  45102. }
  45103. if (this.fillIB) {
  45104. this._engine._releaseBuffer(this.fillIB);
  45105. this.fillIB = null;
  45106. }
  45107. this.effectFill = null;
  45108. this.effectFillInstanced = null;
  45109. this.effectBorder = null;
  45110. this.effectBorderInstanced = null;
  45111. if (this.borderVB) {
  45112. this._engine._releaseBuffer(this.borderVB);
  45113. this.borderVB = null;
  45114. }
  45115. if (this.borderIB) {
  45116. this._engine._releaseBuffer(this.borderIB);
  45117. this.borderIB = null;
  45118. }
  45119. return true;
  45120. };
  45121. return Rectangle2DRenderCache;
  45122. }(BABYLON.ModelRenderCache));
  45123. BABYLON.Rectangle2DRenderCache = Rectangle2DRenderCache;
  45124. var Rectangle2DInstanceData = (function (_super) {
  45125. __extends(Rectangle2DInstanceData, _super);
  45126. function Rectangle2DInstanceData(partId) {
  45127. _super.call(this, partId, 1);
  45128. }
  45129. Object.defineProperty(Rectangle2DInstanceData.prototype, "properties", {
  45130. get: function () {
  45131. return null;
  45132. },
  45133. enumerable: true,
  45134. configurable: true
  45135. });
  45136. __decorate([
  45137. BABYLON.instanceData()
  45138. ], Rectangle2DInstanceData.prototype, "properties", null);
  45139. return Rectangle2DInstanceData;
  45140. }(BABYLON.Shape2DInstanceData));
  45141. BABYLON.Rectangle2DInstanceData = Rectangle2DInstanceData;
  45142. var Rectangle2D = (function (_super) {
  45143. __extends(Rectangle2D, _super);
  45144. /**
  45145. * Create an Rectangle 2D Shape primitive. May be a sharp rectangle (with sharp corners), or a rounded one.
  45146. * @param settings a combination of settings, possible ones are
  45147. * - 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)
  45148. * - children: an array of direct children
  45149. * - id a text identifier, for information purpose
  45150. * - position: the X & Y positions relative to its parent. Alternatively the x and y settings can be set. Default is [0;0]
  45151. * - rotation: the initial rotation (in radian) of the primitive. default is 0
  45152. * - scale: the initial scale of the primitive. default is 1. You can alternatively use scaleX &| scaleY to apply non uniform scale
  45153. * - dontInheritParentScale: if set the parent's scale won't be taken into consideration to compute the actualScale property
  45154. * - opacity: set the overall opacity of the primitive, 1 to be opaque (default), less than 1 to be transparent.
  45155. * - zOrder: override the zOrder with the specified value
  45156. * - origin: define the normalized origin point location, default [0.5;0.5]
  45157. * - size: the size of the group. Alternatively the width and height settings can be set. Default will be [10;10].
  45158. * - roundRadius: if the rectangle has rounded corner, set their radius, default is 0 (to get a sharp edges rectangle).
  45159. * - 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)
  45160. * - 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)
  45161. * - borderThickness: the thickness of the drawn border, default is 1.
  45162. * - isVisible: true if the primitive must be visible, false for hidden. Default is true.
  45163. * - isPickable: if true the Primitive can be used with interaction mode and will issue Pointer Event. If false it will be ignored for interaction/intersection test. Default value is true.
  45164. * - isContainer: if true the Primitive acts as a container for interaction, if the primitive is not pickable or doesn't intersection, no further test will be perform on its children. If set to false, children will always be considered for intersection/interaction. Default value is true.
  45165. * - 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!
  45166. * - marginTop: top margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  45167. * - marginLeft: left margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  45168. * - marginRight: right margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  45169. * - marginBottom: bottom margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  45170. * - margin: top, left, right and bottom margin formatted as a single string (see PrimitiveThickness.fromString)
  45171. * - marginHAlignment: one value of the PrimitiveAlignment type's static properties
  45172. * - marginVAlignment: one value of the PrimitiveAlignment type's static properties
  45173. * - marginAlignment: a string defining the alignment, see PrimitiveAlignment.fromString
  45174. * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  45175. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  45176. * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  45177. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  45178. * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
  45179. */
  45180. function Rectangle2D(settings) {
  45181. // Avoid checking every time if the object exists
  45182. if (settings == null) {
  45183. settings = {};
  45184. }
  45185. _super.call(this, settings);
  45186. if (settings.size != null) {
  45187. this.size = settings.size;
  45188. }
  45189. else if (settings.width || settings.height) {
  45190. var size = new BABYLON.Size(settings.width, settings.height);
  45191. this.size = size;
  45192. }
  45193. //let size = settings.size || (new Size((settings.width === null) ? null : (settings.width || 10), (settings.height === null) ? null : (settings.height || 10)));
  45194. var roundRadius = (settings.roundRadius == null) ? 0 : settings.roundRadius;
  45195. var borderThickness = (settings.borderThickness == null) ? 1 : settings.borderThickness;
  45196. //this.size = size;
  45197. this.roundRadius = roundRadius;
  45198. this.borderThickness = borderThickness;
  45199. }
  45200. Object.defineProperty(Rectangle2D.prototype, "actualSize", {
  45201. get: function () {
  45202. if (this._actualSize) {
  45203. return this._actualSize;
  45204. }
  45205. return this.size;
  45206. },
  45207. set: function (value) {
  45208. this._actualSize = value;
  45209. },
  45210. enumerable: true,
  45211. configurable: true
  45212. });
  45213. Object.defineProperty(Rectangle2D.prototype, "notRounded", {
  45214. get: function () {
  45215. return this._notRounded;
  45216. },
  45217. set: function (value) {
  45218. this._notRounded = value;
  45219. },
  45220. enumerable: true,
  45221. configurable: true
  45222. });
  45223. Object.defineProperty(Rectangle2D.prototype, "roundRadius", {
  45224. get: function () {
  45225. return this._roundRadius;
  45226. },
  45227. set: function (value) {
  45228. this._roundRadius = value;
  45229. this.notRounded = value === 0;
  45230. this._positioningDirty();
  45231. },
  45232. enumerable: true,
  45233. configurable: true
  45234. });
  45235. Rectangle2D.prototype.levelIntersect = function (intersectInfo) {
  45236. // If we got there it mean the boundingInfo intersection succeed, if the rectangle has not roundRadius, it means it succeed!
  45237. if (this.notRounded) {
  45238. return true;
  45239. }
  45240. // 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.
  45241. // 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)
  45242. // 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.
  45243. // First let remove the origin out the equation, to have the rectangle with an origin at bottom/left
  45244. var size = this.size;
  45245. Rectangle2D._i0.x = intersectInfo._localPickPosition.x;
  45246. Rectangle2D._i0.y = intersectInfo._localPickPosition.y;
  45247. var rr = this.roundRadius;
  45248. var rrs = rr * rr;
  45249. // Check if the point is in the bottom/left quarter area
  45250. Rectangle2D._i1.x = rr;
  45251. Rectangle2D._i1.y = rr;
  45252. if (Rectangle2D._i0.x <= Rectangle2D._i1.x && Rectangle2D._i0.y <= Rectangle2D._i1.y) {
  45253. // Compute the intersection point in the quarter local space
  45254. Rectangle2D._i2.x = Rectangle2D._i0.x - Rectangle2D._i1.x;
  45255. Rectangle2D._i2.y = Rectangle2D._i0.y - Rectangle2D._i1.y;
  45256. // It's a hit if the squared distance is less/equal to the squared radius of the round circle
  45257. return Rectangle2D._i2.lengthSquared() <= rrs;
  45258. }
  45259. // Check if the point is in the top/left quarter area
  45260. Rectangle2D._i1.x = rr;
  45261. Rectangle2D._i1.y = size.height - rr;
  45262. if (Rectangle2D._i0.x <= Rectangle2D._i1.x && Rectangle2D._i0.y >= Rectangle2D._i1.y) {
  45263. // Compute the intersection point in the quarter local space
  45264. Rectangle2D._i2.x = Rectangle2D._i0.x - Rectangle2D._i1.x;
  45265. Rectangle2D._i2.y = Rectangle2D._i0.y - Rectangle2D._i1.y;
  45266. // It's a hit if the squared distance is less/equal to the squared radius of the round circle
  45267. return Rectangle2D._i2.lengthSquared() <= rrs;
  45268. }
  45269. // Check if the point is in the top/right quarter area
  45270. Rectangle2D._i1.x = size.width - rr;
  45271. Rectangle2D._i1.y = size.height - rr;
  45272. if (Rectangle2D._i0.x >= Rectangle2D._i1.x && Rectangle2D._i0.y >= Rectangle2D._i1.y) {
  45273. // Compute the intersection point in the quarter local space
  45274. Rectangle2D._i2.x = Rectangle2D._i0.x - Rectangle2D._i1.x;
  45275. Rectangle2D._i2.y = Rectangle2D._i0.y - Rectangle2D._i1.y;
  45276. // It's a hit if the squared distance is less/equal to the squared radius of the round circle
  45277. return Rectangle2D._i2.lengthSquared() <= rrs;
  45278. }
  45279. // Check if the point is in the bottom/right quarter area
  45280. Rectangle2D._i1.x = size.width - rr;
  45281. Rectangle2D._i1.y = rr;
  45282. if (Rectangle2D._i0.x >= Rectangle2D._i1.x && Rectangle2D._i0.y <= Rectangle2D._i1.y) {
  45283. // Compute the intersection point in the quarter local space
  45284. Rectangle2D._i2.x = Rectangle2D._i0.x - Rectangle2D._i1.x;
  45285. Rectangle2D._i2.y = Rectangle2D._i0.y - Rectangle2D._i1.y;
  45286. // It's a hit if the squared distance is less/equal to the squared radius of the round circle
  45287. return Rectangle2D._i2.lengthSquared() <= rrs;
  45288. }
  45289. // At any other locations the point is guarantied to be inside
  45290. return true;
  45291. };
  45292. Rectangle2D.prototype.updateLevelBoundingInfo = function () {
  45293. BABYLON.BoundingInfo2D.CreateFromSizeToRef(this.actualSize, this._levelBoundingInfo);
  45294. };
  45295. Rectangle2D.prototype.createModelRenderCache = function (modelKey) {
  45296. var renderCache = new Rectangle2DRenderCache(this.owner.engine, modelKey);
  45297. return renderCache;
  45298. };
  45299. Rectangle2D.prototype.setupModelRenderCache = function (modelRenderCache) {
  45300. var renderCache = modelRenderCache;
  45301. var engine = this.owner.engine;
  45302. // Need to create WebGL resources for fill part?
  45303. if (this.fill) {
  45304. var vbSize = ((this.notRounded ? 1 : Rectangle2D.roundSubdivisions) * 4) + 1;
  45305. var vb = new Float32Array(vbSize);
  45306. for (var i = 0; i < vbSize; i++) {
  45307. vb[i] = i;
  45308. }
  45309. renderCache.fillVB = engine.createVertexBuffer(vb);
  45310. var triCount = vbSize - 1;
  45311. var ib = new Float32Array(triCount * 3);
  45312. for (var i = 0; i < triCount; i++) {
  45313. ib[i * 3 + 0] = 0;
  45314. ib[i * 3 + 2] = i + 1;
  45315. ib[i * 3 + 1] = i + 2;
  45316. }
  45317. ib[triCount * 3 - 2] = 1;
  45318. renderCache.fillIB = engine.createIndexBuffer(ib);
  45319. renderCache.fillIndicesCount = triCount * 3;
  45320. // 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
  45321. var ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_FILLPARTID, ["index"], null, true);
  45322. if (ei) {
  45323. renderCache.effectFillInstanced = engine.createEffect("rect2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  45324. }
  45325. // Get the non instanced version
  45326. ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_FILLPARTID, ["index"], null, false);
  45327. renderCache.effectFill = engine.createEffect("rect2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  45328. }
  45329. // Need to create WebGL resource for border part?
  45330. if (this.border) {
  45331. var vbSize = (this.notRounded ? 1 : Rectangle2D.roundSubdivisions) * 4 * 2;
  45332. var vb = new Float32Array(vbSize);
  45333. for (var i = 0; i < vbSize; i++) {
  45334. vb[i] = i;
  45335. }
  45336. renderCache.borderVB = engine.createVertexBuffer(vb);
  45337. var triCount = vbSize;
  45338. var rs = triCount / 2;
  45339. var ib = new Float32Array(triCount * 3);
  45340. for (var i = 0; i < rs; i++) {
  45341. var r0 = i;
  45342. var r1 = (i + 1) % rs;
  45343. ib[i * 6 + 0] = rs + r1;
  45344. ib[i * 6 + 1] = rs + r0;
  45345. ib[i * 6 + 2] = r0;
  45346. ib[i * 6 + 3] = r1;
  45347. ib[i * 6 + 4] = rs + r1;
  45348. ib[i * 6 + 5] = r0;
  45349. }
  45350. renderCache.borderIB = engine.createIndexBuffer(ib);
  45351. renderCache.borderIndicesCount = triCount * 3;
  45352. // 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
  45353. var ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, ["index"], null, true);
  45354. if (ei) {
  45355. renderCache.effectBorderInstanced = engine.createEffect("rect2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  45356. }
  45357. // Get the non instanced version
  45358. ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, ["index"], null, false);
  45359. renderCache.effectBorder = engine.createEffect("rect2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  45360. }
  45361. return renderCache;
  45362. };
  45363. // 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
  45364. Rectangle2D.prototype._getInitialContentAreaToRef = function (primSize, initialContentPosition, initialContentArea) {
  45365. // Fall back to default implementation if there's no round Radius
  45366. if (this._notRounded) {
  45367. _super.prototype._getInitialContentAreaToRef.call(this, primSize, initialContentPosition, initialContentArea);
  45368. }
  45369. else {
  45370. var rr = Math.round((this.roundRadius - (this.roundRadius / Math.sqrt(2))) * 1.3);
  45371. initialContentPosition.x = initialContentPosition.y = rr;
  45372. initialContentArea.width = Math.max(0, primSize.width - (rr * 2));
  45373. initialContentArea.height = Math.max(0, primSize.height - (rr * 2));
  45374. }
  45375. };
  45376. Rectangle2D.prototype._getActualSizeFromContentToRef = function (primSize, newPrimSize) {
  45377. // Fall back to default implementation if there's no round Radius
  45378. if (this._notRounded) {
  45379. _super.prototype._getActualSizeFromContentToRef.call(this, primSize, newPrimSize);
  45380. }
  45381. else {
  45382. var rr = Math.round((this.roundRadius - (this.roundRadius / Math.sqrt(2))) * 1.3);
  45383. newPrimSize.copyFrom(primSize);
  45384. newPrimSize.width += rr * 2;
  45385. newPrimSize.height += rr * 2;
  45386. }
  45387. };
  45388. Rectangle2D.prototype.createInstanceDataParts = function () {
  45389. var res = new Array();
  45390. if (this.border) {
  45391. res.push(new Rectangle2DInstanceData(BABYLON.Shape2D.SHAPE2D_BORDERPARTID));
  45392. }
  45393. if (this.fill) {
  45394. res.push(new Rectangle2DInstanceData(BABYLON.Shape2D.SHAPE2D_FILLPARTID));
  45395. }
  45396. return res;
  45397. };
  45398. Rectangle2D.prototype.refreshInstanceDataPart = function (part) {
  45399. if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
  45400. return false;
  45401. }
  45402. if (part.id === BABYLON.Shape2D.SHAPE2D_BORDERPARTID) {
  45403. var d = part;
  45404. var size = this.actualSize;
  45405. var s = this.actualScale;
  45406. d.properties = new BABYLON.Vector3(size.width * s.x, size.height * s.y, this.roundRadius || 0);
  45407. }
  45408. else if (part.id === BABYLON.Shape2D.SHAPE2D_FILLPARTID) {
  45409. var d = part;
  45410. var size = this.actualSize;
  45411. var s = this.actualScale;
  45412. d.properties = new BABYLON.Vector3(size.width * s.x, size.height * s.y, this.roundRadius || 0);
  45413. }
  45414. return true;
  45415. };
  45416. Rectangle2D._i0 = BABYLON.Vector2.Zero();
  45417. Rectangle2D._i1 = BABYLON.Vector2.Zero();
  45418. Rectangle2D._i2 = BABYLON.Vector2.Zero();
  45419. Rectangle2D.roundSubdivisions = 16;
  45420. __decorate([
  45421. BABYLON.instanceLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 1, function (pi) { return Rectangle2D.actualSizeProperty = pi; }, false, true)
  45422. ], Rectangle2D.prototype, "actualSize", null);
  45423. __decorate([
  45424. BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 2, function (pi) { return Rectangle2D.notRoundedProperty = pi; })
  45425. ], Rectangle2D.prototype, "notRounded", null);
  45426. __decorate([
  45427. BABYLON.instanceLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 3, function (pi) { return Rectangle2D.roundRadiusProperty = pi; })
  45428. ], Rectangle2D.prototype, "roundRadius", null);
  45429. Rectangle2D = __decorate([
  45430. BABYLON.className("Rectangle2D")
  45431. ], Rectangle2D);
  45432. return Rectangle2D;
  45433. }(BABYLON.Shape2D));
  45434. BABYLON.Rectangle2D = Rectangle2D;
  45435. })(BABYLON || (BABYLON = {}));
  45436. var BABYLON;
  45437. (function (BABYLON) {
  45438. var Ellipse2DRenderCache = (function (_super) {
  45439. __extends(Ellipse2DRenderCache, _super);
  45440. function Ellipse2DRenderCache(engine, modelKey) {
  45441. _super.call(this, engine, modelKey);
  45442. this.effectsReady = false;
  45443. this.fillVB = null;
  45444. this.fillIB = null;
  45445. this.fillIndicesCount = 0;
  45446. this.instancingFillAttributes = null;
  45447. this.effectFillInstanced = null;
  45448. this.effectFill = null;
  45449. this.borderVB = null;
  45450. this.borderIB = null;
  45451. this.borderIndicesCount = 0;
  45452. this.instancingBorderAttributes = null;
  45453. this.effectBorderInstanced = null;
  45454. this.effectBorder = null;
  45455. }
  45456. Ellipse2DRenderCache.prototype.render = function (instanceInfo, context) {
  45457. // Do nothing if the shader is still loading/preparing
  45458. if (!this.effectsReady) {
  45459. if ((this.effectFill && (!this.effectFill.isReady() || (this.effectFillInstanced && !this.effectFillInstanced.isReady()))) ||
  45460. (this.effectBorder && (!this.effectBorder.isReady() || (this.effectBorderInstanced && !this.effectBorderInstanced.isReady())))) {
  45461. return false;
  45462. }
  45463. this.effectsReady = true;
  45464. }
  45465. var canvas = instanceInfo.owner.owner;
  45466. var engine = canvas.engine;
  45467. var depthFunction = 0;
  45468. if (this.effectFill && this.effectBorder) {
  45469. depthFunction = engine.getDepthFunction();
  45470. engine.setDepthFunctionToLessOrEqual();
  45471. }
  45472. var curAlphaMode = engine.getAlphaMode();
  45473. if (this.effectFill) {
  45474. var partIndex = instanceInfo.partIndexFromId.get(BABYLON.Shape2D.SHAPE2D_FILLPARTID.toString());
  45475. var pid = context.groupInfoPartData[partIndex];
  45476. if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
  45477. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE, true);
  45478. }
  45479. var effect = context.useInstancing ? this.effectFillInstanced : this.effectFill;
  45480. engine.enableEffect(effect);
  45481. engine.bindBuffersDirectly(this.fillVB, this.fillIB, [1], 4, effect);
  45482. if (context.useInstancing) {
  45483. if (!this.instancingFillAttributes) {
  45484. this.instancingFillAttributes = this.loadInstancingAttributes(BABYLON.Shape2D.SHAPE2D_FILLPARTID, effect);
  45485. }
  45486. var glBuffer = context.instancedBuffers ? context.instancedBuffers[partIndex] : pid._partBuffer;
  45487. var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
  45488. canvas._addDrawCallCount(1, context.renderMode);
  45489. engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingFillAttributes);
  45490. engine.draw(true, 0, this.fillIndicesCount, count);
  45491. engine.unbindInstanceAttributes();
  45492. }
  45493. else {
  45494. canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
  45495. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  45496. this.setupUniforms(effect, partIndex, pid._partData, i);
  45497. engine.draw(true, 0, this.fillIndicesCount);
  45498. }
  45499. }
  45500. }
  45501. if (this.effectBorder) {
  45502. var partIndex = instanceInfo.partIndexFromId.get(BABYLON.Shape2D.SHAPE2D_BORDERPARTID.toString());
  45503. var pid = context.groupInfoPartData[partIndex];
  45504. if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
  45505. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE, true);
  45506. }
  45507. var effect = context.useInstancing ? this.effectBorderInstanced : this.effectBorder;
  45508. engine.enableEffect(effect);
  45509. engine.bindBuffersDirectly(this.borderVB, this.borderIB, [1], 4, effect);
  45510. if (context.useInstancing) {
  45511. if (!this.instancingBorderAttributes) {
  45512. this.instancingBorderAttributes = this.loadInstancingAttributes(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, effect);
  45513. }
  45514. var glBuffer = context.instancedBuffers ? context.instancedBuffers[partIndex] : pid._partBuffer;
  45515. var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
  45516. canvas._addDrawCallCount(1, context.renderMode);
  45517. engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingBorderAttributes);
  45518. engine.draw(true, 0, this.borderIndicesCount, count);
  45519. engine.unbindInstanceAttributes();
  45520. }
  45521. else {
  45522. canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
  45523. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  45524. this.setupUniforms(effect, partIndex, pid._partData, i);
  45525. engine.draw(true, 0, this.borderIndicesCount);
  45526. }
  45527. }
  45528. }
  45529. engine.setAlphaMode(curAlphaMode, true);
  45530. if (this.effectFill && this.effectBorder) {
  45531. engine.setDepthFunction(depthFunction);
  45532. }
  45533. return true;
  45534. };
  45535. Ellipse2DRenderCache.prototype.dispose = function () {
  45536. if (!_super.prototype.dispose.call(this)) {
  45537. return false;
  45538. }
  45539. if (this.fillVB) {
  45540. this._engine._releaseBuffer(this.fillVB);
  45541. this.fillVB = null;
  45542. }
  45543. if (this.fillIB) {
  45544. this._engine._releaseBuffer(this.fillIB);
  45545. this.fillIB = null;
  45546. }
  45547. this.effectFill = null;
  45548. this.effectFillInstanced = null;
  45549. this.effectBorder = null;
  45550. this.effectBorderInstanced = null;
  45551. if (this.borderVB) {
  45552. this._engine._releaseBuffer(this.borderVB);
  45553. this.borderVB = null;
  45554. }
  45555. if (this.borderIB) {
  45556. this._engine._releaseBuffer(this.borderIB);
  45557. this.borderIB = null;
  45558. }
  45559. return true;
  45560. };
  45561. return Ellipse2DRenderCache;
  45562. }(BABYLON.ModelRenderCache));
  45563. BABYLON.Ellipse2DRenderCache = Ellipse2DRenderCache;
  45564. var Ellipse2DInstanceData = (function (_super) {
  45565. __extends(Ellipse2DInstanceData, _super);
  45566. function Ellipse2DInstanceData(partId) {
  45567. _super.call(this, partId, 1);
  45568. }
  45569. Object.defineProperty(Ellipse2DInstanceData.prototype, "properties", {
  45570. get: function () {
  45571. return null;
  45572. },
  45573. enumerable: true,
  45574. configurable: true
  45575. });
  45576. __decorate([
  45577. BABYLON.instanceData()
  45578. ], Ellipse2DInstanceData.prototype, "properties", null);
  45579. return Ellipse2DInstanceData;
  45580. }(BABYLON.Shape2DInstanceData));
  45581. BABYLON.Ellipse2DInstanceData = Ellipse2DInstanceData;
  45582. var Ellipse2D = (function (_super) {
  45583. __extends(Ellipse2D, _super);
  45584. /**
  45585. * Create an Ellipse 2D Shape primitive
  45586. * @param settings a combination of settings, possible ones are
  45587. * - 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)
  45588. * - children: an array of direct children
  45589. * - id: a text identifier, for information purpose
  45590. * - position: the X & Y positions relative to its parent. Alternatively the x and y properties can be set. Default is [0;0]
  45591. * - rotation: the initial rotation (in radian) of the primitive. default is 0
  45592. * - scale: the initial scale of the primitive. default is 1. You can alternatively use scaleX &| scaleY to apply non uniform scale
  45593. * - dontInheritParentScale: if set the parent's scale won't be taken into consideration to compute the actualScale property
  45594. * - opacity: set the overall opacity of the primitive, 1 to be opaque (default), less than 1 to be transparent.
  45595. * - zOrder: override the zOrder with the specified value
  45596. * - origin: define the normalized origin point location, default [0.5;0.5]
  45597. * - size: the size of the group. Alternatively the width and height properties can be set. Default will be [10;10].
  45598. * - subdivision: the number of subdivision to create the ellipse perimeter, default is 64.
  45599. * - 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)
  45600. * - 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)
  45601. * - borderThickness: the thickness of the drawn border, default is 1.
  45602. * - isVisible: true if the group must be visible, false for hidden. Default is true.
  45603. * - isPickable: if true the Primitive can be used with interaction mode and will issue Pointer Event. If false it will be ignored for interaction/intersection test. Default value is true.
  45604. * - isContainer: if true the Primitive acts as a container for interaction, if the primitive is not pickable or doesn't intersection, no further test will be perform on its children. If set to false, children will always be considered for intersection/interaction. Default value is true.
  45605. * - 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!
  45606. * - marginTop: top margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  45607. * - marginLeft: left margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  45608. * - marginRight: right margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  45609. * - marginBottom: bottom margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  45610. * - margin: top, left, right and bottom margin formatted as a single string (see PrimitiveThickness.fromString)
  45611. * - marginHAlignment: one value of the PrimitiveAlignment type's static properties
  45612. * - marginVAlignment: one value of the PrimitiveAlignment type's static properties
  45613. * - marginAlignment: a string defining the alignment, see PrimitiveAlignment.fromString
  45614. * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  45615. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  45616. * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  45617. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  45618. * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
  45619. */
  45620. function Ellipse2D(settings) {
  45621. // Avoid checking every time if the object exists
  45622. if (settings == null) {
  45623. settings = {};
  45624. }
  45625. _super.call(this, settings);
  45626. if (settings.size != null) {
  45627. this.size = settings.size;
  45628. }
  45629. else if (settings.width || settings.height) {
  45630. var size = new BABYLON.Size(settings.width, settings.height);
  45631. this.size = size;
  45632. }
  45633. var sub = (settings.subdivisions == null) ? 64 : settings.subdivisions;
  45634. this.subdivisions = sub;
  45635. }
  45636. Object.defineProperty(Ellipse2D.prototype, "actualSize", {
  45637. get: function () {
  45638. if (this._actualSize) {
  45639. return this._actualSize;
  45640. }
  45641. return this.size;
  45642. },
  45643. set: function (value) {
  45644. this._actualSize = value;
  45645. },
  45646. enumerable: true,
  45647. configurable: true
  45648. });
  45649. Object.defineProperty(Ellipse2D.prototype, "subdivisions", {
  45650. get: function () {
  45651. return this._subdivisions;
  45652. },
  45653. set: function (value) {
  45654. this._subdivisions = value;
  45655. },
  45656. enumerable: true,
  45657. configurable: true
  45658. });
  45659. Ellipse2D.prototype.levelIntersect = function (intersectInfo) {
  45660. var w = this.size.width / 2;
  45661. var h = this.size.height / 2;
  45662. var x = intersectInfo._localPickPosition.x - w;
  45663. var y = intersectInfo._localPickPosition.y - h;
  45664. return ((x * x) / (w * w) + (y * y) / (h * h)) <= 1;
  45665. };
  45666. Ellipse2D.prototype.updateLevelBoundingInfo = function () {
  45667. BABYLON.BoundingInfo2D.CreateFromSizeToRef(this.actualSize, this._levelBoundingInfo);
  45668. };
  45669. Ellipse2D.prototype.createModelRenderCache = function (modelKey) {
  45670. var renderCache = new Ellipse2DRenderCache(this.owner.engine, modelKey);
  45671. return renderCache;
  45672. };
  45673. Ellipse2D.prototype.setupModelRenderCache = function (modelRenderCache) {
  45674. var renderCache = modelRenderCache;
  45675. var engine = this.owner.engine;
  45676. // Need to create WebGL resources for fill part?
  45677. if (this.fill) {
  45678. var vbSize = this.subdivisions + 1;
  45679. var vb = new Float32Array(vbSize);
  45680. for (var i = 0; i < vbSize; i++) {
  45681. vb[i] = i;
  45682. }
  45683. renderCache.fillVB = engine.createVertexBuffer(vb);
  45684. var triCount = vbSize - 1;
  45685. var ib = new Float32Array(triCount * 3);
  45686. for (var i = 0; i < triCount; i++) {
  45687. ib[i * 3 + 0] = 0;
  45688. ib[i * 3 + 2] = i + 1;
  45689. ib[i * 3 + 1] = i + 2;
  45690. }
  45691. ib[triCount * 3 - 2] = 1;
  45692. renderCache.fillIB = engine.createIndexBuffer(ib);
  45693. renderCache.fillIndicesCount = triCount * 3;
  45694. // 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
  45695. var ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_FILLPARTID, ["index"], null, true);
  45696. if (ei) {
  45697. renderCache.effectFillInstanced = engine.createEffect({ vertex: "ellipse2d", fragment: "ellipse2d" }, ei.attributes, ei.uniforms, [], ei.defines, null);
  45698. }
  45699. // Get the non instanced version
  45700. ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_FILLPARTID, ["index"], null, false);
  45701. renderCache.effectFill = engine.createEffect({ vertex: "ellipse2d", fragment: "ellipse2d" }, ei.attributes, ei.uniforms, [], ei.defines, null);
  45702. }
  45703. // Need to create WebGL resource for border part?
  45704. if (this.border) {
  45705. var vbSize = this.subdivisions * 2;
  45706. var vb = new Float32Array(vbSize);
  45707. for (var i = 0; i < vbSize; i++) {
  45708. vb[i] = i;
  45709. }
  45710. renderCache.borderVB = engine.createVertexBuffer(vb);
  45711. var triCount = vbSize;
  45712. var rs = triCount / 2;
  45713. var ib = new Float32Array(triCount * 3);
  45714. for (var i = 0; i < rs; i++) {
  45715. var r0 = i;
  45716. var r1 = (i + 1) % rs;
  45717. ib[i * 6 + 0] = rs + r1;
  45718. ib[i * 6 + 1] = rs + r0;
  45719. ib[i * 6 + 2] = r0;
  45720. ib[i * 6 + 3] = r1;
  45721. ib[i * 6 + 4] = rs + r1;
  45722. ib[i * 6 + 5] = r0;
  45723. }
  45724. renderCache.borderIB = engine.createIndexBuffer(ib);
  45725. renderCache.borderIndicesCount = (triCount * 3);
  45726. // 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
  45727. var ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, ["index"], null, true);
  45728. if (ei) {
  45729. renderCache.effectBorderInstanced = engine.createEffect("ellipse2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  45730. }
  45731. // Get the non instanced version
  45732. ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, ["index"], null, false);
  45733. renderCache.effectBorder = engine.createEffect("ellipse2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  45734. }
  45735. return renderCache;
  45736. };
  45737. Ellipse2D.prototype.createInstanceDataParts = function () {
  45738. var res = new Array();
  45739. if (this.border) {
  45740. res.push(new Ellipse2DInstanceData(BABYLON.Shape2D.SHAPE2D_BORDERPARTID));
  45741. }
  45742. if (this.fill) {
  45743. res.push(new Ellipse2DInstanceData(BABYLON.Shape2D.SHAPE2D_FILLPARTID));
  45744. }
  45745. return res;
  45746. };
  45747. Ellipse2D.prototype.refreshInstanceDataPart = function (part) {
  45748. if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
  45749. return false;
  45750. }
  45751. if (part.id === BABYLON.Shape2D.SHAPE2D_BORDERPARTID) {
  45752. var d = part;
  45753. var size = this.actualSize;
  45754. var s = this.actualScale;
  45755. d.properties = new BABYLON.Vector3(size.width * s.x, size.height * s.y, this.subdivisions);
  45756. }
  45757. else if (part.id === BABYLON.Shape2D.SHAPE2D_FILLPARTID) {
  45758. var d = part;
  45759. var size = this.actualSize;
  45760. var s = this.actualScale;
  45761. d.properties = new BABYLON.Vector3(size.width * s.x, size.height * s.y, this.subdivisions);
  45762. }
  45763. return true;
  45764. };
  45765. __decorate([
  45766. BABYLON.instanceLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 1, function (pi) { return Ellipse2D.acutalSizeProperty = pi; }, false, true)
  45767. ], Ellipse2D.prototype, "actualSize", null);
  45768. __decorate([
  45769. BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 2, function (pi) { return Ellipse2D.subdivisionsProperty = pi; })
  45770. ], Ellipse2D.prototype, "subdivisions", null);
  45771. Ellipse2D = __decorate([
  45772. BABYLON.className("Ellipse2D")
  45773. ], Ellipse2D);
  45774. return Ellipse2D;
  45775. }(BABYLON.Shape2D));
  45776. BABYLON.Ellipse2D = Ellipse2D;
  45777. })(BABYLON || (BABYLON = {}));
  45778. var BABYLON;
  45779. (function (BABYLON) {
  45780. var Sprite2DRenderCache = (function (_super) {
  45781. __extends(Sprite2DRenderCache, _super);
  45782. function Sprite2DRenderCache() {
  45783. _super.apply(this, arguments);
  45784. this.effectsReady = false;
  45785. this.vb = null;
  45786. this.ib = null;
  45787. this.instancingAttributes = null;
  45788. this.texture = null;
  45789. this.effect = null;
  45790. this.effectInstanced = null;
  45791. }
  45792. Sprite2DRenderCache.prototype.render = function (instanceInfo, context) {
  45793. // Do nothing if the shader is still loading/preparing
  45794. if (!this.effectsReady) {
  45795. if ((this.effect && (!this.effect.isReady() || (this.effectInstanced && !this.effectInstanced.isReady())))) {
  45796. return false;
  45797. }
  45798. this.effectsReady = true;
  45799. }
  45800. // Compute the offset locations of the attributes in the vertex shader that will be mapped to the instance buffer data
  45801. var canvas = instanceInfo.owner.owner;
  45802. var engine = canvas.engine;
  45803. var cur = engine.getAlphaMode();
  45804. var effect = context.useInstancing ? this.effectInstanced : this.effect;
  45805. engine.enableEffect(effect);
  45806. effect.setTexture("diffuseSampler", this.texture);
  45807. engine.bindBuffersDirectly(this.vb, this.ib, [1], 4, effect);
  45808. if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
  45809. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE, true);
  45810. }
  45811. effect.setBool("alphaTest", context.renderMode === BABYLON.Render2DContext.RenderModeAlphaTest);
  45812. var pid = context.groupInfoPartData[0];
  45813. if (context.useInstancing) {
  45814. if (!this.instancingAttributes) {
  45815. this.instancingAttributes = this.loadInstancingAttributes(Sprite2D.SPRITE2D_MAINPARTID, effect);
  45816. }
  45817. var glBuffer = context.instancedBuffers ? context.instancedBuffers[0] : pid._partBuffer;
  45818. var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
  45819. canvas._addDrawCallCount(1, context.renderMode);
  45820. engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingAttributes);
  45821. engine.draw(true, 0, 6, count);
  45822. engine.unbindInstanceAttributes();
  45823. }
  45824. else {
  45825. canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
  45826. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  45827. this.setupUniforms(effect, 0, pid._partData, i);
  45828. engine.draw(true, 0, 6);
  45829. }
  45830. }
  45831. engine.setAlphaMode(cur, true);
  45832. return true;
  45833. };
  45834. Sprite2DRenderCache.prototype.dispose = function () {
  45835. if (!_super.prototype.dispose.call(this)) {
  45836. return false;
  45837. }
  45838. if (this.vb) {
  45839. this._engine._releaseBuffer(this.vb);
  45840. this.vb = null;
  45841. }
  45842. if (this.ib) {
  45843. this._engine._releaseBuffer(this.ib);
  45844. this.ib = null;
  45845. }
  45846. //if (this.texture) {
  45847. // this.texture.dispose();
  45848. // this.texture = null;
  45849. //}
  45850. this.effect = null;
  45851. this.effectInstanced = null;
  45852. return true;
  45853. };
  45854. return Sprite2DRenderCache;
  45855. }(BABYLON.ModelRenderCache));
  45856. BABYLON.Sprite2DRenderCache = Sprite2DRenderCache;
  45857. var Sprite2DInstanceData = (function (_super) {
  45858. __extends(Sprite2DInstanceData, _super);
  45859. function Sprite2DInstanceData(partId) {
  45860. _super.call(this, partId, 1);
  45861. }
  45862. Object.defineProperty(Sprite2DInstanceData.prototype, "topLeftUV", {
  45863. get: function () {
  45864. return null;
  45865. },
  45866. enumerable: true,
  45867. configurable: true
  45868. });
  45869. Object.defineProperty(Sprite2DInstanceData.prototype, "sizeUV", {
  45870. get: function () {
  45871. return null;
  45872. },
  45873. enumerable: true,
  45874. configurable: true
  45875. });
  45876. Object.defineProperty(Sprite2DInstanceData.prototype, "scaleFactor", {
  45877. get: function () {
  45878. return null;
  45879. },
  45880. enumerable: true,
  45881. configurable: true
  45882. });
  45883. Object.defineProperty(Sprite2DInstanceData.prototype, "textureSize", {
  45884. get: function () {
  45885. return null;
  45886. },
  45887. enumerable: true,
  45888. configurable: true
  45889. });
  45890. Object.defineProperty(Sprite2DInstanceData.prototype, "properties", {
  45891. // 3 floats being:
  45892. // - x: frame number to display
  45893. // - y: invertY setting
  45894. // - z: alignToPixel setting
  45895. get: function () {
  45896. return null;
  45897. },
  45898. enumerable: true,
  45899. configurable: true
  45900. });
  45901. __decorate([
  45902. BABYLON.instanceData()
  45903. ], Sprite2DInstanceData.prototype, "topLeftUV", null);
  45904. __decorate([
  45905. BABYLON.instanceData()
  45906. ], Sprite2DInstanceData.prototype, "sizeUV", null);
  45907. __decorate([
  45908. BABYLON.instanceData()
  45909. ], Sprite2DInstanceData.prototype, "scaleFactor", null);
  45910. __decorate([
  45911. BABYLON.instanceData()
  45912. ], Sprite2DInstanceData.prototype, "textureSize", null);
  45913. __decorate([
  45914. BABYLON.instanceData()
  45915. ], Sprite2DInstanceData.prototype, "properties", null);
  45916. return Sprite2DInstanceData;
  45917. }(BABYLON.InstanceDataBase));
  45918. BABYLON.Sprite2DInstanceData = Sprite2DInstanceData;
  45919. var Sprite2D = (function (_super) {
  45920. __extends(Sprite2D, _super);
  45921. /**
  45922. * Create an 2D Sprite primitive
  45923. * @param texture the texture that stores the sprite to render
  45924. * @param settings a combination of settings, possible ones are
  45925. * - 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)
  45926. * - children: an array of direct children
  45927. * - id a text identifier, for information purpose
  45928. * - position: the X & Y positions relative to its parent. Alternatively the x and y properties can be set. Default is [0;0]
  45929. * - rotation: the initial rotation (in radian) of the primitive. default is 0
  45930. * - scale: the initial scale of the primitive. default is 1. You can alternatively use scaleX &| scaleY to apply non uniform scale
  45931. * - dontInheritParentScale: if set the parent's scale won't be taken into consideration to compute the actualScale property
  45932. * - opacity: set the overall opacity of the primitive, 1 to be opaque (default), less than 1 to be transparent.
  45933. * - zOrder: override the zOrder with the specified value
  45934. * - origin: define the normalized origin point location, default [0.5;0.5]
  45935. * - spriteSize: the size of the sprite (in pixels), if null the size of the given texture will be used, default is null.
  45936. * - spriteLocation: the location (in pixels) in the texture of the top/left corner of the Sprite to display, default is null (0,0)
  45937. * - 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.
  45938. * - invertY: if true the texture Y will be inverted, default is false.
  45939. * - 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.
  45940. * - isVisible: true if the sprite must be visible, false for hidden. Default is true.
  45941. * - isPickable: if true the Primitive can be used with interaction mode and will issue Pointer Event. If false it will be ignored for interaction/intersection test. Default value is true.
  45942. * - isContainer: if true the Primitive acts as a container for interaction, if the primitive is not pickable or doesn't intersection, no further test will be perform on its children. If set to false, children will always be considered for intersection/interaction. Default value is true.
  45943. * - 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!
  45944. * - marginTop: top margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  45945. * - marginLeft: left margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  45946. * - marginRight: right margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  45947. * - marginBottom: bottom margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  45948. * - margin: top, left, right and bottom margin formatted as a single string (see PrimitiveThickness.fromString)
  45949. * - marginHAlignment: one value of the PrimitiveAlignment type's static properties
  45950. * - marginVAlignment: one value of the PrimitiveAlignment type's static properties
  45951. * - marginAlignment: a string defining the alignment, see PrimitiveAlignment.fromString
  45952. * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  45953. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  45954. * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  45955. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  45956. * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
  45957. */
  45958. function Sprite2D(texture, settings) {
  45959. var _this = this;
  45960. if (!settings) {
  45961. settings = {};
  45962. }
  45963. _super.call(this, settings);
  45964. this.texture = texture;
  45965. this.texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  45966. this.texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  45967. this.size = settings.spriteSize;
  45968. this.spriteLocation = settings.spriteLocation || new BABYLON.Vector2(0, 0);
  45969. this.spriteScaleFactor = settings.spriteScaleFactor || new BABYLON.Vector2(1, 1);
  45970. this.spriteFrame = 0;
  45971. this.invertY = (settings.invertY == null) ? false : settings.invertY;
  45972. this.alignToPixel = (settings.alignToPixel == null) ? true : settings.alignToPixel;
  45973. this.useAlphaFromTexture = true;
  45974. if (settings.spriteSize == null || !texture.isReady()) {
  45975. if (texture.isReady()) {
  45976. this.size = texture.getBaseSize();
  45977. }
  45978. else {
  45979. texture.onLoadObservable.add(function () {
  45980. if (settings.spriteSize == null) {
  45981. _this.size = texture.getBaseSize();
  45982. }
  45983. _this._positioningDirty();
  45984. _this._instanceDirtyFlags |= BABYLON.Prim2DBase.originProperty.flagId | Sprite2D.textureProperty.flagId; // To make sure the sprite is issued again for render
  45985. });
  45986. }
  45987. }
  45988. }
  45989. Object.defineProperty(Sprite2D.prototype, "texture", {
  45990. get: function () {
  45991. return this._texture;
  45992. },
  45993. set: function (value) {
  45994. this._texture = value;
  45995. this._oldTextureHasAlpha = this._texture && this.texture.hasAlpha;
  45996. },
  45997. enumerable: true,
  45998. configurable: true
  45999. });
  46000. Object.defineProperty(Sprite2D.prototype, "useAlphaFromTexture", {
  46001. get: function () {
  46002. return this._useAlphaFromTexture;
  46003. },
  46004. set: function (value) {
  46005. if (this._useAlphaFromTexture === value) {
  46006. return;
  46007. }
  46008. this._useAlphaFromTexture = value;
  46009. this._updateRenderMode();
  46010. },
  46011. enumerable: true,
  46012. configurable: true
  46013. });
  46014. Object.defineProperty(Sprite2D.prototype, "actualSize", {
  46015. get: function () {
  46016. if (this._actualSize) {
  46017. return this._actualSize;
  46018. }
  46019. return this.size;
  46020. },
  46021. set: function (value) {
  46022. this._actualSize = value;
  46023. },
  46024. enumerable: true,
  46025. configurable: true
  46026. });
  46027. Object.defineProperty(Sprite2D.prototype, "spriteLocation", {
  46028. get: function () {
  46029. return this._location;
  46030. },
  46031. set: function (value) {
  46032. this._location = value;
  46033. },
  46034. enumerable: true,
  46035. configurable: true
  46036. });
  46037. Object.defineProperty(Sprite2D.prototype, "spriteFrame", {
  46038. get: function () {
  46039. return this._spriteFrame;
  46040. },
  46041. set: function (value) {
  46042. this._spriteFrame = value;
  46043. },
  46044. enumerable: true,
  46045. configurable: true
  46046. });
  46047. Object.defineProperty(Sprite2D.prototype, "invertY", {
  46048. get: function () {
  46049. return this._invertY;
  46050. },
  46051. set: function (value) {
  46052. this._invertY = value;
  46053. },
  46054. enumerable: true,
  46055. configurable: true
  46056. });
  46057. Object.defineProperty(Sprite2D.prototype, "spriteScaleFactor", {
  46058. get: function () {
  46059. return this._spriteScaleFactor;
  46060. },
  46061. set: function (value) {
  46062. this._spriteScaleFactor = value;
  46063. },
  46064. enumerable: true,
  46065. configurable: true
  46066. });
  46067. /**
  46068. * Sets the scale of the sprite using a BABYLON.Size(w,h).
  46069. * Keeps proportion by taking the maximum of the two scale for x and y.
  46070. * @param {Size} size Size(width,height)
  46071. */
  46072. Sprite2D.prototype.scaleToSize = function (size) {
  46073. var baseSize = this.size;
  46074. if (baseSize == null || !this.texture.isReady()) {
  46075. // we're probably at initiation of the scene, size is not set
  46076. if (this.texture.isReady()) {
  46077. baseSize = this.texture.getBaseSize();
  46078. }
  46079. else {
  46080. // the texture is not ready, wait for it to load before calling scaleToSize again
  46081. var thisObject = this;
  46082. this.texture.onLoadObservable.add(function () {
  46083. thisObject.scaleToSize(size);
  46084. });
  46085. return;
  46086. }
  46087. }
  46088. this.scale = Math.max(size.height / baseSize.height, size.width / baseSize.width);
  46089. };
  46090. Object.defineProperty(Sprite2D.prototype, "alignToPixel", {
  46091. /**
  46092. * Get/set if the sprite rendering should be aligned to the target rendering device pixel or not
  46093. */
  46094. get: function () {
  46095. return this._alignToPixel;
  46096. },
  46097. set: function (value) {
  46098. this._alignToPixel = value;
  46099. },
  46100. enumerable: true,
  46101. configurable: true
  46102. });
  46103. Sprite2D.prototype.updateLevelBoundingInfo = function () {
  46104. BABYLON.BoundingInfo2D.CreateFromSizeToRef(this.size, this._levelBoundingInfo);
  46105. };
  46106. /**
  46107. * Get the animatable array (see http://doc.babylonjs.com/tutorials/Animations)
  46108. */
  46109. Sprite2D.prototype.getAnimatables = function () {
  46110. var res = new Array();
  46111. if (this.texture && this.texture.animations && this.texture.animations.length > 0) {
  46112. res.push(this.texture);
  46113. }
  46114. return res;
  46115. };
  46116. Sprite2D.prototype.levelIntersect = function (intersectInfo) {
  46117. // 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
  46118. return true;
  46119. };
  46120. Sprite2D._createCachedCanvasSprite = function (owner, texture, size, pos) {
  46121. var sprite = new Sprite2D(texture, { parent: owner, id: "__cachedCanvasSprite__", position: BABYLON.Vector2.Zero(), origin: BABYLON.Vector2.Zero(), spriteSize: size, spriteLocation: pos, alignToPixel: true });
  46122. return sprite;
  46123. };
  46124. Sprite2D.prototype.createModelRenderCache = function (modelKey) {
  46125. var renderCache = new Sprite2DRenderCache(this.owner.engine, modelKey);
  46126. return renderCache;
  46127. };
  46128. Sprite2D.prototype.setupModelRenderCache = function (modelRenderCache) {
  46129. var renderCache = modelRenderCache;
  46130. var engine = this.owner.engine;
  46131. var vb = new Float32Array(4);
  46132. for (var i = 0; i < 4; i++) {
  46133. vb[i] = i;
  46134. }
  46135. renderCache.vb = engine.createVertexBuffer(vb);
  46136. var ib = new Float32Array(6);
  46137. ib[0] = 0;
  46138. ib[1] = 2;
  46139. ib[2] = 1;
  46140. ib[3] = 0;
  46141. ib[4] = 3;
  46142. ib[5] = 2;
  46143. renderCache.ib = engine.createIndexBuffer(ib);
  46144. renderCache.texture = this.texture;
  46145. // 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
  46146. var ei = this.getDataPartEffectInfo(Sprite2D.SPRITE2D_MAINPARTID, ["index"], ["alphaTest"], true);
  46147. if (ei) {
  46148. renderCache.effectInstanced = engine.createEffect("sprite2d", ei.attributes, ei.uniforms, ["diffuseSampler"], ei.defines, null);
  46149. }
  46150. ei = this.getDataPartEffectInfo(Sprite2D.SPRITE2D_MAINPARTID, ["index"], ["alphaTest"], false);
  46151. renderCache.effect = engine.createEffect("sprite2d", ei.attributes, ei.uniforms, ["diffuseSampler"], ei.defines, null);
  46152. return renderCache;
  46153. };
  46154. Sprite2D.prototype.createInstanceDataParts = function () {
  46155. return [new Sprite2DInstanceData(Sprite2D.SPRITE2D_MAINPARTID)];
  46156. };
  46157. Sprite2D.prototype.beforeRefreshForLayoutConstruction = function (part) {
  46158. Sprite2D.layoutConstructMode = true;
  46159. };
  46160. // if obj contains something, we restore the _text property
  46161. Sprite2D.prototype.afterRefreshForLayoutConstruction = function (part, obj) {
  46162. Sprite2D.layoutConstructMode = false;
  46163. };
  46164. Sprite2D.prototype.refreshInstanceDataPart = function (part) {
  46165. if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
  46166. return false;
  46167. }
  46168. if (!this.texture.isReady() && !Sprite2D.layoutConstructMode) {
  46169. return false;
  46170. }
  46171. if (part.id === Sprite2D.SPRITE2D_MAINPARTID) {
  46172. var d = this._instanceDataParts[0];
  46173. if (Sprite2D.layoutConstructMode) {
  46174. d.topLeftUV = BABYLON.Vector2.Zero();
  46175. d.sizeUV = BABYLON.Vector2.Zero();
  46176. d.properties = BABYLON.Vector3.Zero();
  46177. d.textureSize = BABYLON.Vector2.Zero();
  46178. d.scaleFactor = BABYLON.Vector2.Zero();
  46179. }
  46180. else {
  46181. var ts = this.texture.getBaseSize();
  46182. var sl = this.spriteLocation;
  46183. var ss = this.actualSize;
  46184. var ssf = this.spriteScaleFactor;
  46185. d.topLeftUV = new BABYLON.Vector2(sl.x / ts.width, sl.y / ts.height);
  46186. var suv = new BABYLON.Vector2(ss.width / ts.width, ss.height / ts.height);
  46187. d.sizeUV = suv;
  46188. d.scaleFactor = ssf;
  46189. Sprite2D._prop.x = this.spriteFrame;
  46190. Sprite2D._prop.y = this.invertY ? 1 : 0;
  46191. Sprite2D._prop.z = this.alignToPixel ? 1 : 0;
  46192. d.properties = Sprite2D._prop;
  46193. d.textureSize = new BABYLON.Vector2(ts.width, ts.height);
  46194. }
  46195. }
  46196. return true;
  46197. };
  46198. Sprite2D.prototype._mustUpdateInstance = function () {
  46199. var res = this._oldTextureHasAlpha !== (this.texture != null && this.texture.hasAlpha);
  46200. this._oldTextureHasAlpha = this.texture != null && this.texture.hasAlpha;
  46201. if (res) {
  46202. this._updateRenderMode();
  46203. }
  46204. return res;
  46205. };
  46206. Sprite2D.prototype._useTextureAlpha = function () {
  46207. return this.texture != null && this.texture.hasAlpha;
  46208. };
  46209. Sprite2D.prototype._shouldUseAlphaFromTexture = function () {
  46210. return this.texture != null && this.texture.hasAlpha && this.useAlphaFromTexture;
  46211. };
  46212. Sprite2D.SPRITE2D_MAINPARTID = 1;
  46213. Sprite2D._prop = BABYLON.Vector3.Zero();
  46214. Sprite2D.layoutConstructMode = false;
  46215. __decorate([
  46216. BABYLON.modelLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 1, function (pi) { return Sprite2D.textureProperty = pi; })
  46217. ], Sprite2D.prototype, "texture", null);
  46218. __decorate([
  46219. BABYLON.dynamicLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 2, function (pi) { return Sprite2D.useAlphaFromTextureProperty = pi; })
  46220. ], Sprite2D.prototype, "useAlphaFromTexture", null);
  46221. __decorate([
  46222. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 3, function (pi) { return Sprite2D.actualSizeProperty = pi; }, false, true)
  46223. ], Sprite2D.prototype, "actualSize", null);
  46224. __decorate([
  46225. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 4, function (pi) { return Sprite2D.spriteLocationProperty = pi; })
  46226. ], Sprite2D.prototype, "spriteLocation", null);
  46227. __decorate([
  46228. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 5, function (pi) { return Sprite2D.spriteFrameProperty = pi; })
  46229. ], Sprite2D.prototype, "spriteFrame", null);
  46230. __decorate([
  46231. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 6, function (pi) { return Sprite2D.invertYProperty = pi; })
  46232. ], Sprite2D.prototype, "invertY", null);
  46233. __decorate([
  46234. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 7, function (pi) { return Sprite2D.spriteScaleFactorProperty = pi; })
  46235. ], Sprite2D.prototype, "spriteScaleFactor", null);
  46236. Sprite2D = __decorate([
  46237. BABYLON.className("Sprite2D")
  46238. ], Sprite2D);
  46239. return Sprite2D;
  46240. }(BABYLON.RenderablePrim2D));
  46241. BABYLON.Sprite2D = Sprite2D;
  46242. })(BABYLON || (BABYLON = {}));
  46243. var BABYLON;
  46244. (function (BABYLON) {
  46245. var Text2DRenderCache = (function (_super) {
  46246. __extends(Text2DRenderCache, _super);
  46247. function Text2DRenderCache() {
  46248. _super.apply(this, arguments);
  46249. this.effectsReady = false;
  46250. this.vb = null;
  46251. this.ib = null;
  46252. this.instancingAttributes = null;
  46253. this.fontTexture = null;
  46254. this.effect = null;
  46255. this.effectInstanced = null;
  46256. }
  46257. Text2DRenderCache.prototype.render = function (instanceInfo, context) {
  46258. // Do nothing if the shader is still loading/preparing
  46259. if (!this.effectsReady) {
  46260. if ((this.effect && (!this.effect.isReady() || (this.effectInstanced && !this.effectInstanced.isReady())))) {
  46261. return false;
  46262. }
  46263. this.effectsReady = true;
  46264. }
  46265. var canvas = instanceInfo.owner.owner;
  46266. var engine = canvas.engine;
  46267. this.fontTexture.update();
  46268. var effect = context.useInstancing ? this.effectInstanced : this.effect;
  46269. engine.enableEffect(effect);
  46270. effect.setTexture("diffuseSampler", this.fontTexture);
  46271. engine.bindBuffersDirectly(this.vb, this.ib, [1], 4, effect);
  46272. var curAlphaMode = engine.getAlphaMode();
  46273. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE, true);
  46274. var pid = context.groupInfoPartData[0];
  46275. if (context.useInstancing) {
  46276. if (!this.instancingAttributes) {
  46277. this.instancingAttributes = this.loadInstancingAttributes(Text2D.TEXT2D_MAINPARTID, effect);
  46278. }
  46279. var glBuffer = context.instancedBuffers ? context.instancedBuffers[0] : pid._partBuffer;
  46280. var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
  46281. canvas._addDrawCallCount(1, context.renderMode);
  46282. engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingAttributes);
  46283. engine.draw(true, 0, 6, count);
  46284. engine.unbindInstanceAttributes();
  46285. }
  46286. else {
  46287. canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
  46288. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  46289. this.setupUniforms(effect, 0, pid._partData, i);
  46290. engine.draw(true, 0, 6);
  46291. }
  46292. }
  46293. engine.setAlphaMode(curAlphaMode, true);
  46294. return true;
  46295. };
  46296. Text2DRenderCache.prototype.dispose = function () {
  46297. if (!_super.prototype.dispose.call(this)) {
  46298. return false;
  46299. }
  46300. if (this.vb) {
  46301. this._engine._releaseBuffer(this.vb);
  46302. this.vb = null;
  46303. }
  46304. if (this.ib) {
  46305. this._engine._releaseBuffer(this.ib);
  46306. this.ib = null;
  46307. }
  46308. if (this.fontTexture) {
  46309. this.fontTexture.decCachedFontTextureCounter();
  46310. this.fontTexture = null;
  46311. }
  46312. this.effect = null;
  46313. this.effectInstanced = null;
  46314. return true;
  46315. };
  46316. return Text2DRenderCache;
  46317. }(BABYLON.ModelRenderCache));
  46318. BABYLON.Text2DRenderCache = Text2DRenderCache;
  46319. var Text2DInstanceData = (function (_super) {
  46320. __extends(Text2DInstanceData, _super);
  46321. function Text2DInstanceData(partId, dataElementCount) {
  46322. _super.call(this, partId, dataElementCount);
  46323. }
  46324. Object.defineProperty(Text2DInstanceData.prototype, "topLeftUV", {
  46325. get: function () {
  46326. return null;
  46327. },
  46328. enumerable: true,
  46329. configurable: true
  46330. });
  46331. Object.defineProperty(Text2DInstanceData.prototype, "sizeUV", {
  46332. get: function () {
  46333. return null;
  46334. },
  46335. enumerable: true,
  46336. configurable: true
  46337. });
  46338. Object.defineProperty(Text2DInstanceData.prototype, "textureSize", {
  46339. get: function () {
  46340. return null;
  46341. },
  46342. enumerable: true,
  46343. configurable: true
  46344. });
  46345. Object.defineProperty(Text2DInstanceData.prototype, "color", {
  46346. get: function () {
  46347. return null;
  46348. },
  46349. enumerable: true,
  46350. configurable: true
  46351. });
  46352. Object.defineProperty(Text2DInstanceData.prototype, "superSampleFactor", {
  46353. get: function () {
  46354. return null;
  46355. },
  46356. enumerable: true,
  46357. configurable: true
  46358. });
  46359. __decorate([
  46360. BABYLON.instanceData()
  46361. ], Text2DInstanceData.prototype, "topLeftUV", null);
  46362. __decorate([
  46363. BABYLON.instanceData()
  46364. ], Text2DInstanceData.prototype, "sizeUV", null);
  46365. __decorate([
  46366. BABYLON.instanceData()
  46367. ], Text2DInstanceData.prototype, "textureSize", null);
  46368. __decorate([
  46369. BABYLON.instanceData()
  46370. ], Text2DInstanceData.prototype, "color", null);
  46371. __decorate([
  46372. BABYLON.instanceData()
  46373. ], Text2DInstanceData.prototype, "superSampleFactor", null);
  46374. return Text2DInstanceData;
  46375. }(BABYLON.InstanceDataBase));
  46376. BABYLON.Text2DInstanceData = Text2DInstanceData;
  46377. var Text2D = (function (_super) {
  46378. __extends(Text2D, _super);
  46379. /**
  46380. * Create a Text primitive
  46381. * @param text the text to display
  46382. * @param settings a combination of settings, possible ones are
  46383. * - 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)
  46384. * - children: an array of direct children
  46385. * - id a text identifier, for information purpose
  46386. * - position: the X & Y positions relative to its parent. Alternatively the x and y properties can be set. Default is [0;0]
  46387. * - rotation: the initial rotation (in radian) of the primitive. default is 0
  46388. * - scale: the initial scale of the primitive. default is 1. You can alternatively use scaleX &| scaleY to apply non uniform scale
  46389. * - dontInheritParentScale: if set the parent's scale won't be taken into consideration to compute the actualScale property
  46390. * - opacity: set the overall opacity of the primitive, 1 to be opaque (default), less than 1 to be transparent.
  46391. * - zOrder: override the zOrder with the specified value
  46392. * - origin: define the normalized origin point location, default [0.5;0.5]
  46393. * - fontName: the name/size/style of the font to use, following the CSS notation. Default is "12pt Arial".
  46394. * - 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.
  46395. * - defaultFontColor: the color by default to apply on each letter of the text to display, default is plain white.
  46396. * - areaSize: the size of the area in which to display the text, default is auto-fit from text content.
  46397. * - tabulationSize: number of space character to insert when a tabulation is encountered, default is 4
  46398. * - isVisible: true if the text must be visible, false for hidden. Default is true.
  46399. * - isPickable: if true the Primitive can be used with interaction mode and will issue Pointer Event. If false it will be ignored for interaction/intersection test. Default value is true.
  46400. * - isContainer: if true the Primitive acts as a container for interaction, if the primitive is not pickable or doesn't intersection, no further test will be perform on its children. If set to false, children will always be considered for intersection/interaction. Default value is true.
  46401. * - 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!
  46402. * - marginTop: top margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  46403. * - marginLeft: left margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  46404. * - marginRight: right margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  46405. * - marginBottom: bottom margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  46406. * - margin: top, left, right and bottom margin formatted as a single string (see PrimitiveThickness.fromString)
  46407. * - marginHAlignment: one value of the PrimitiveAlignment type's static properties
  46408. * - marginVAlignment: one value of the PrimitiveAlignment type's static properties
  46409. * - marginAlignment: a string defining the alignment, see PrimitiveAlignment.fromString
  46410. * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  46411. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  46412. * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  46413. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  46414. * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
  46415. */
  46416. function Text2D(text, settings) {
  46417. if (!settings) {
  46418. settings = {};
  46419. }
  46420. _super.call(this, settings);
  46421. this.fontName = (settings.fontName == null) ? "12pt Arial" : settings.fontName;
  46422. this._fontSuperSample = (settings.fontSuperSample != null && settings.fontSuperSample);
  46423. this.defaultFontColor = (settings.defaultFontColor == null) ? new BABYLON.Color4(1, 1, 1, 1) : settings.defaultFontColor;
  46424. this._tabulationSize = (settings.tabulationSize == null) ? 4 : settings.tabulationSize;
  46425. this._textSize = null;
  46426. this.text = text;
  46427. this.size = (settings.size == null) ? null : settings.size;
  46428. this._updateRenderMode();
  46429. }
  46430. Object.defineProperty(Text2D.prototype, "fontName", {
  46431. get: function () {
  46432. return this._fontName;
  46433. },
  46434. set: function (value) {
  46435. if (this._fontName) {
  46436. throw new Error("Font Name change is not supported right now.");
  46437. }
  46438. this._fontName = value;
  46439. },
  46440. enumerable: true,
  46441. configurable: true
  46442. });
  46443. Object.defineProperty(Text2D.prototype, "defaultFontColor", {
  46444. get: function () {
  46445. return this._defaultFontColor;
  46446. },
  46447. set: function (value) {
  46448. this._defaultFontColor = value;
  46449. },
  46450. enumerable: true,
  46451. configurable: true
  46452. });
  46453. Object.defineProperty(Text2D.prototype, "text", {
  46454. get: function () {
  46455. return this._text;
  46456. },
  46457. set: function (value) {
  46458. this._text = value;
  46459. this._textSize = null; // A change of text will reset the TextSize which will be recomputed next time it's used
  46460. this._size = null;
  46461. this._updateCharCount();
  46462. // Trigger a textSize to for a sizeChange if necessary, which is needed for layout to recompute
  46463. var s = this.textSize;
  46464. },
  46465. enumerable: true,
  46466. configurable: true
  46467. });
  46468. Object.defineProperty(Text2D.prototype, "size", {
  46469. get: function () {
  46470. if (this._size != null) {
  46471. return this._size;
  46472. }
  46473. return this.textSize;
  46474. },
  46475. set: function (value) {
  46476. this._size = value;
  46477. },
  46478. enumerable: true,
  46479. configurable: true
  46480. });
  46481. Object.defineProperty(Text2D.prototype, "actualSize", {
  46482. /**
  46483. * Get the actual size of the Text2D primitive
  46484. */
  46485. get: function () {
  46486. if (this._actualSize) {
  46487. return this._actualSize;
  46488. }
  46489. return this.size;
  46490. },
  46491. enumerable: true,
  46492. configurable: true
  46493. });
  46494. Object.defineProperty(Text2D.prototype, "textSize", {
  46495. /**
  46496. * Get the area that bounds the text associated to the primitive
  46497. */
  46498. get: function () {
  46499. if (!this._textSize) {
  46500. if (this.owner) {
  46501. var newSize = this.fontTexture.measureText(this._text, this._tabulationSize);
  46502. if (!newSize.equals(this._textSize)) {
  46503. this.onPrimitivePropertyDirty(BABYLON.Prim2DBase.sizeProperty.flagId);
  46504. this._positioningDirty();
  46505. }
  46506. this._textSize = newSize;
  46507. }
  46508. else {
  46509. return Text2D.nullSize;
  46510. }
  46511. }
  46512. return this._textSize;
  46513. },
  46514. enumerable: true,
  46515. configurable: true
  46516. });
  46517. Object.defineProperty(Text2D.prototype, "fontTexture", {
  46518. get: function () {
  46519. if (this._fontTexture) {
  46520. return this._fontTexture;
  46521. }
  46522. if (this.fontName == null || this.owner == null || this.owner.scene == null) {
  46523. return null;
  46524. }
  46525. this._fontTexture = BABYLON.FontTexture.GetCachedFontTexture(this.owner.scene, this.fontName, this._fontSuperSample);
  46526. return this._fontTexture;
  46527. },
  46528. enumerable: true,
  46529. configurable: true
  46530. });
  46531. /**
  46532. * Dispose the primitive, remove it from its parent
  46533. */
  46534. Text2D.prototype.dispose = function () {
  46535. if (!_super.prototype.dispose.call(this)) {
  46536. return false;
  46537. }
  46538. if (this._fontTexture) {
  46539. BABYLON.FontTexture.ReleaseCachedFontTexture(this.owner.scene, this.fontName, this._fontSuperSample);
  46540. this._fontTexture = null;
  46541. }
  46542. return true;
  46543. };
  46544. Text2D.prototype.updateLevelBoundingInfo = function () {
  46545. BABYLON.BoundingInfo2D.CreateFromSizeToRef(this.actualSize, this._levelBoundingInfo);
  46546. };
  46547. Text2D.prototype.levelIntersect = function (intersectInfo) {
  46548. // 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...
  46549. return true;
  46550. };
  46551. Text2D.prototype.createModelRenderCache = function (modelKey) {
  46552. var renderCache = new Text2DRenderCache(this.owner.engine, modelKey);
  46553. return renderCache;
  46554. };
  46555. Text2D.prototype.setupModelRenderCache = function (modelRenderCache) {
  46556. var renderCache = modelRenderCache;
  46557. var engine = this.owner.engine;
  46558. renderCache.fontTexture = this.fontTexture;
  46559. renderCache.fontTexture.incCachedFontTextureCounter();
  46560. var vb = new Float32Array(4);
  46561. for (var i = 0; i < 4; i++) {
  46562. vb[i] = i;
  46563. }
  46564. renderCache.vb = engine.createVertexBuffer(vb);
  46565. var ib = new Float32Array(6);
  46566. ib[0] = 0;
  46567. ib[1] = 2;
  46568. ib[2] = 1;
  46569. ib[3] = 0;
  46570. ib[4] = 3;
  46571. ib[5] = 2;
  46572. renderCache.ib = engine.createIndexBuffer(ib);
  46573. // 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
  46574. var ei = this.getDataPartEffectInfo(Text2D.TEXT2D_MAINPARTID, ["index"], null, true);
  46575. if (ei) {
  46576. renderCache.effectInstanced = engine.createEffect("text2d", ei.attributes, ei.uniforms, ["diffuseSampler"], ei.defines, null);
  46577. }
  46578. ei = this.getDataPartEffectInfo(Text2D.TEXT2D_MAINPARTID, ["index"], null, false);
  46579. renderCache.effect = engine.createEffect("text2d", ei.attributes, ei.uniforms, ["diffuseSampler"], ei.defines, null);
  46580. return renderCache;
  46581. };
  46582. Text2D.prototype.createInstanceDataParts = function () {
  46583. return [new Text2DInstanceData(Text2D.TEXT2D_MAINPARTID, this._charCount)];
  46584. };
  46585. // Looks like a hack!? Yes! Because that's what it is!
  46586. // 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
  46587. // 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)
  46588. Text2D.prototype.beforeRefreshForLayoutConstruction = function (part) {
  46589. if (!this._charCount) {
  46590. var curText = this._text;
  46591. this.text = "A";
  46592. return curText;
  46593. }
  46594. };
  46595. // if obj contains something, we restore the _text property
  46596. Text2D.prototype.afterRefreshForLayoutConstruction = function (part, obj) {
  46597. if (obj !== undefined) {
  46598. this.text = obj;
  46599. }
  46600. };
  46601. Text2D.prototype.refreshInstanceDataPart = function (part) {
  46602. if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
  46603. return false;
  46604. }
  46605. if (part.id === Text2D.TEXT2D_MAINPARTID) {
  46606. var d = part;
  46607. var texture = this.fontTexture;
  46608. var superSampleFactor = texture.isSuperSampled ? 0.5 : 1;
  46609. var ts = texture.getSize();
  46610. var offset = BABYLON.Vector2.Zero();
  46611. var lh = this.fontTexture.lineHeight;
  46612. 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
  46613. var charxpos = 0;
  46614. d.dataElementCount = this._charCount;
  46615. d.curElement = 0;
  46616. for (var _i = 0, _a = this.text; _i < _a.length; _i++) {
  46617. var char = _a[_i];
  46618. // Line feed
  46619. if (char === "\n") {
  46620. offset.x = 0;
  46621. offset.y -= texture.lineHeight;
  46622. }
  46623. // Tabulation ?
  46624. if (char === "\t") {
  46625. var nextPos = charxpos + this._tabulationSize;
  46626. nextPos = nextPos - (nextPos % this._tabulationSize);
  46627. offset.x += (nextPos - charxpos) * texture.spaceWidth;
  46628. charxpos = nextPos;
  46629. continue;
  46630. }
  46631. if (char < " ") {
  46632. continue;
  46633. }
  46634. this.updateInstanceDataPart(d, offset);
  46635. var ci = texture.getChar(char);
  46636. offset.x += ci.charWidth;
  46637. d.topLeftUV = ci.topLeftUV;
  46638. var suv = ci.bottomRightUV.subtract(ci.topLeftUV);
  46639. d.sizeUV = suv;
  46640. d.textureSize = new BABYLON.Vector2(ts.width, ts.height);
  46641. d.color = this.defaultFontColor;
  46642. d.superSampleFactor = superSampleFactor;
  46643. ++d.curElement;
  46644. }
  46645. }
  46646. return true;
  46647. };
  46648. Text2D.prototype._updateCharCount = function () {
  46649. var count = 0;
  46650. for (var _i = 0, _a = this._text; _i < _a.length; _i++) {
  46651. var char = _a[_i];
  46652. if (char === "\r" || char === "\n" || char === "\t" || char < " ") {
  46653. continue;
  46654. }
  46655. ++count;
  46656. }
  46657. this._charCount = count;
  46658. };
  46659. Text2D.prototype._useTextureAlpha = function () {
  46660. return this.fontTexture != null && this.fontTexture.hasAlpha;
  46661. };
  46662. Text2D.prototype._shouldUseAlphaFromTexture = function () {
  46663. return true;
  46664. };
  46665. Text2D.TEXT2D_MAINPARTID = 1;
  46666. __decorate([
  46667. BABYLON.modelLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 1, function (pi) { return Text2D.fontProperty = pi; }, false, true)
  46668. ], Text2D.prototype, "fontName", null);
  46669. __decorate([
  46670. BABYLON.dynamicLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 2, function (pi) { return Text2D.defaultFontColorProperty = pi; })
  46671. ], Text2D.prototype, "defaultFontColor", null);
  46672. __decorate([
  46673. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 3, function (pi) { return Text2D.textProperty = pi; }, false, true)
  46674. ], Text2D.prototype, "text", null);
  46675. __decorate([
  46676. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 4, function (pi) { return Text2D.sizeProperty = pi; })
  46677. ], Text2D.prototype, "size", null);
  46678. Text2D = __decorate([
  46679. BABYLON.className("Text2D")
  46680. ], Text2D);
  46681. return Text2D;
  46682. }(BABYLON.RenderablePrim2D));
  46683. BABYLON.Text2D = Text2D;
  46684. })(BABYLON || (BABYLON = {}));
  46685. var BABYLON;
  46686. (function (BABYLON) {
  46687. var Lines2DRenderCache = (function (_super) {
  46688. __extends(Lines2DRenderCache, _super);
  46689. function Lines2DRenderCache(engine, modelKey) {
  46690. _super.call(this, engine, modelKey);
  46691. this.effectsReady = false;
  46692. this.fillVB = null;
  46693. this.fillIB = null;
  46694. this.fillIndicesCount = 0;
  46695. this.instancingFillAttributes = null;
  46696. this.effectFill = null;
  46697. this.effectFillInstanced = null;
  46698. this.borderVB = null;
  46699. this.borderIB = null;
  46700. this.borderIndicesCount = 0;
  46701. this.instancingBorderAttributes = null;
  46702. this.effectBorder = null;
  46703. this.effectBorderInstanced = null;
  46704. }
  46705. Lines2DRenderCache.prototype.render = function (instanceInfo, context) {
  46706. // Do nothing if the shader is still loading/preparing
  46707. if (!this.effectsReady) {
  46708. if ((this.effectFill && (!this.effectFill.isReady() || (this.effectFillInstanced && !this.effectFillInstanced.isReady()))) ||
  46709. (this.effectBorder && (!this.effectBorder.isReady() || (this.effectBorderInstanced && !this.effectBorderInstanced.isReady())))) {
  46710. return false;
  46711. }
  46712. this.effectsReady = true;
  46713. }
  46714. var canvas = instanceInfo.owner.owner;
  46715. var engine = canvas.engine;
  46716. var depthFunction = 0;
  46717. if (this.effectFill && this.effectBorder) {
  46718. depthFunction = engine.getDepthFunction();
  46719. engine.setDepthFunctionToLessOrEqual();
  46720. }
  46721. var curAlphaMode = engine.getAlphaMode();
  46722. if (this.effectFill) {
  46723. var partIndex = instanceInfo.partIndexFromId.get(BABYLON.Shape2D.SHAPE2D_FILLPARTID.toString());
  46724. var pid = context.groupInfoPartData[partIndex];
  46725. if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
  46726. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE, true);
  46727. }
  46728. var effect = context.useInstancing ? this.effectFillInstanced : this.effectFill;
  46729. engine.enableEffect(effect);
  46730. engine.bindBuffersDirectly(this.fillVB, this.fillIB, [2], 2 * 4, effect);
  46731. if (context.useInstancing) {
  46732. if (!this.instancingFillAttributes) {
  46733. this.instancingFillAttributes = this.loadInstancingAttributes(BABYLON.Shape2D.SHAPE2D_FILLPARTID, effect);
  46734. }
  46735. var glBuffer = context.instancedBuffers ? context.instancedBuffers[partIndex] : pid._partBuffer;
  46736. var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
  46737. canvas._addDrawCallCount(1, context.renderMode);
  46738. engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingFillAttributes);
  46739. engine.draw(true, 0, this.fillIndicesCount, count);
  46740. engine.unbindInstanceAttributes();
  46741. }
  46742. else {
  46743. canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
  46744. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  46745. this.setupUniforms(effect, partIndex, pid._partData, i);
  46746. engine.draw(true, 0, this.fillIndicesCount);
  46747. }
  46748. }
  46749. }
  46750. if (this.effectBorder) {
  46751. var partIndex = instanceInfo.partIndexFromId.get(BABYLON.Shape2D.SHAPE2D_BORDERPARTID.toString());
  46752. var pid = context.groupInfoPartData[partIndex];
  46753. if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
  46754. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE, true);
  46755. }
  46756. var effect = context.useInstancing ? this.effectBorderInstanced : this.effectBorder;
  46757. engine.enableEffect(effect);
  46758. engine.bindBuffersDirectly(this.borderVB, this.borderIB, [2], 2 * 4, effect);
  46759. if (context.useInstancing) {
  46760. if (!this.instancingBorderAttributes) {
  46761. this.instancingBorderAttributes = this.loadInstancingAttributes(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, effect);
  46762. }
  46763. var glBuffer = context.instancedBuffers ? context.instancedBuffers[partIndex] : pid._partBuffer;
  46764. var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
  46765. canvas._addDrawCallCount(1, context.renderMode);
  46766. engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingBorderAttributes);
  46767. engine.draw(true, 0, this.borderIndicesCount, count);
  46768. engine.unbindInstanceAttributes();
  46769. }
  46770. else {
  46771. canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
  46772. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  46773. this.setupUniforms(effect, partIndex, pid._partData, i);
  46774. engine.draw(true, 0, this.borderIndicesCount);
  46775. }
  46776. }
  46777. }
  46778. engine.setAlphaMode(curAlphaMode, true);
  46779. if (this.effectFill && this.effectBorder) {
  46780. engine.setDepthFunction(depthFunction);
  46781. }
  46782. return true;
  46783. };
  46784. Lines2DRenderCache.prototype.dispose = function () {
  46785. if (!_super.prototype.dispose.call(this)) {
  46786. return false;
  46787. }
  46788. if (this.fillVB) {
  46789. this._engine._releaseBuffer(this.fillVB);
  46790. this.fillVB = null;
  46791. }
  46792. if (this.fillIB) {
  46793. this._engine._releaseBuffer(this.fillIB);
  46794. this.fillIB = null;
  46795. }
  46796. this.effectFill = null;
  46797. this.effectFillInstanced = null;
  46798. this.effectBorder = null;
  46799. this.effectBorderInstanced = null;
  46800. if (this.borderVB) {
  46801. this._engine._releaseBuffer(this.borderVB);
  46802. this.borderVB = null;
  46803. }
  46804. if (this.borderIB) {
  46805. this._engine._releaseBuffer(this.borderIB);
  46806. this.borderIB = null;
  46807. }
  46808. return true;
  46809. };
  46810. return Lines2DRenderCache;
  46811. }(BABYLON.ModelRenderCache));
  46812. BABYLON.Lines2DRenderCache = Lines2DRenderCache;
  46813. var Lines2DInstanceData = (function (_super) {
  46814. __extends(Lines2DInstanceData, _super);
  46815. function Lines2DInstanceData(partId) {
  46816. _super.call(this, partId, 1);
  46817. }
  46818. Object.defineProperty(Lines2DInstanceData.prototype, "boundingMin", {
  46819. get: function () {
  46820. return null;
  46821. },
  46822. enumerable: true,
  46823. configurable: true
  46824. });
  46825. Object.defineProperty(Lines2DInstanceData.prototype, "boundingMax", {
  46826. get: function () {
  46827. return null;
  46828. },
  46829. enumerable: true,
  46830. configurable: true
  46831. });
  46832. __decorate([
  46833. BABYLON.instanceData(BABYLON.Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT)
  46834. ], Lines2DInstanceData.prototype, "boundingMin", null);
  46835. __decorate([
  46836. BABYLON.instanceData(BABYLON.Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT)
  46837. ], Lines2DInstanceData.prototype, "boundingMax", null);
  46838. return Lines2DInstanceData;
  46839. }(BABYLON.Shape2DInstanceData));
  46840. BABYLON.Lines2DInstanceData = Lines2DInstanceData;
  46841. var Lines2D = (function (_super) {
  46842. __extends(Lines2D, _super);
  46843. /**
  46844. * Create an 2D Lines Shape primitive. The defined lines may be opened or closed (see below)
  46845. * @param points an array that describe the points to use to draw the line, must contain at least two entries.
  46846. * @param settings a combination of settings, possible ones are
  46847. * - 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)
  46848. * - children: an array of direct children
  46849. * - id a text identifier, for information purpose
  46850. * - position: the X & Y positions relative to its parent. Alternatively the x and y properties can be set. Default is [0;0]
  46851. * - rotation: the initial rotation (in radian) of the primitive. default is 0
  46852. * - scale: the initial scale of the primitive. default is 1. You can alternatively use scaleX &| scaleY to apply non uniform scale
  46853. * - dontInheritParentScale: if set the parent's scale won't be taken into consideration to compute the actualScale property
  46854. * - opacity: set the overall opacity of the primitive, 1 to be opaque (default), less than 1 to be transparent.
  46855. * - zOrder: override the zOrder with the specified value
  46856. * - origin: define the normalized origin point location, default [0.5;0.5]
  46857. * - 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.
  46858. * - 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.
  46859. * - 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.
  46860. * - 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.
  46861. * - 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)
  46862. * - 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)
  46863. * - borderThickness: the thickness of the drawn border, default is 1.
  46864. * - isVisible: true if the primitive must be visible, false for hidden. Default is true.
  46865. * - isPickable: if true the Primitive can be used with interaction mode and will issue Pointer Event. If false it will be ignored for interaction/intersection test. Default value is true.
  46866. * - isContainer: if true the Primitive acts as a container for interaction, if the primitive is not pickable or doesn't intersection, no further test will be perform on its children. If set to false, children will always be considered for intersection/interaction. Default value is true.
  46867. * - 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!
  46868. * - marginTop: top margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  46869. * - marginLeft: left margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  46870. * - marginRight: right margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  46871. * - marginBottom: bottom margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  46872. * - margin: top, left, right and bottom margin formatted as a single string (see PrimitiveThickness.fromString)
  46873. * - marginHAlignment: one value of the PrimitiveAlignment type's static properties
  46874. * - marginVAlignment: one value of the PrimitiveAlignment type's static properties
  46875. * - marginAlignment: a string defining the alignment, see PrimitiveAlignment.fromString
  46876. * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  46877. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  46878. * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  46879. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  46880. * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
  46881. */
  46882. function Lines2D(points, settings) {
  46883. if (!settings) {
  46884. settings = {};
  46885. }
  46886. _super.call(this, settings);
  46887. this._fillVB = null;
  46888. this._fillIB = null;
  46889. this._borderVB = null;
  46890. this._borderIB = null;
  46891. this._size = BABYLON.Size.Zero();
  46892. this._boundingMin = null;
  46893. this._boundingMax = null;
  46894. var fillThickness = (settings.fillThickness == null) ? 1 : settings.fillThickness;
  46895. var startCap = (settings.startCap == null) ? 0 : settings.startCap;
  46896. var endCap = (settings.endCap == null) ? 0 : settings.endCap;
  46897. var closed = (settings.closed == null) ? false : settings.closed;
  46898. this.points = points;
  46899. this.fillThickness = fillThickness;
  46900. this.startCap = startCap;
  46901. this.endCap = endCap;
  46902. this.closed = closed;
  46903. }
  46904. Object.defineProperty(Lines2D, "NoCap", {
  46905. /**
  46906. * No Cap to apply on the extremity
  46907. */
  46908. get: function () { return Lines2D._noCap; },
  46909. enumerable: true,
  46910. configurable: true
  46911. });
  46912. Object.defineProperty(Lines2D, "RoundCap", {
  46913. /**
  46914. * A round cap, will use the line thickness as diameter
  46915. */
  46916. get: function () { return Lines2D._roundCap; },
  46917. enumerable: true,
  46918. configurable: true
  46919. });
  46920. Object.defineProperty(Lines2D, "TriangleCap", {
  46921. /**
  46922. * Creates a triangle at the extremity.
  46923. */
  46924. get: function () { return Lines2D._triangleCap; },
  46925. enumerable: true,
  46926. configurable: true
  46927. });
  46928. Object.defineProperty(Lines2D, "SquareAnchorCap", {
  46929. /**
  46930. * Creates a Square anchor at the extremity, the square size is twice the thickness of the line
  46931. */
  46932. get: function () { return Lines2D._squareAnchorCap; },
  46933. enumerable: true,
  46934. configurable: true
  46935. });
  46936. Object.defineProperty(Lines2D, "RoundAnchorCap", {
  46937. /**
  46938. * Creates a round anchor at the extremity, the diameter is twice the thickness of the line
  46939. */
  46940. get: function () { return Lines2D._roundAnchorCap; },
  46941. enumerable: true,
  46942. configurable: true
  46943. });
  46944. Object.defineProperty(Lines2D, "DiamondAnchorCap", {
  46945. /**
  46946. * Creates a diamond anchor at the extremity.
  46947. */
  46948. get: function () { return Lines2D._diamondAnchorCap; },
  46949. enumerable: true,
  46950. configurable: true
  46951. });
  46952. Object.defineProperty(Lines2D, "ArrowCap", {
  46953. /**
  46954. * Creates an arrow anchor at the extremity. the arrow base size is twice the thickness of the line
  46955. */
  46956. get: function () { return Lines2D._arrowCap; },
  46957. enumerable: true,
  46958. configurable: true
  46959. });
  46960. Object.defineProperty(Lines2D.prototype, "points", {
  46961. get: function () {
  46962. return this._points;
  46963. },
  46964. set: function (value) {
  46965. this._points = value;
  46966. this._contour = null;
  46967. this._boundingBoxDirty();
  46968. },
  46969. enumerable: true,
  46970. configurable: true
  46971. });
  46972. Object.defineProperty(Lines2D.prototype, "fillThickness", {
  46973. get: function () {
  46974. return this._fillThickness;
  46975. },
  46976. set: function (value) {
  46977. this._fillThickness = value;
  46978. },
  46979. enumerable: true,
  46980. configurable: true
  46981. });
  46982. Object.defineProperty(Lines2D.prototype, "closed", {
  46983. get: function () {
  46984. return this._closed;
  46985. },
  46986. set: function (value) {
  46987. this._closed = value;
  46988. },
  46989. enumerable: true,
  46990. configurable: true
  46991. });
  46992. Object.defineProperty(Lines2D.prototype, "startCap", {
  46993. get: function () {
  46994. return this._startCap;
  46995. },
  46996. set: function (value) {
  46997. this._startCap = value;
  46998. },
  46999. enumerable: true,
  47000. configurable: true
  47001. });
  47002. Object.defineProperty(Lines2D.prototype, "endCap", {
  47003. get: function () {
  47004. return this._endCap;
  47005. },
  47006. set: function (value) {
  47007. this._endCap = value;
  47008. },
  47009. enumerable: true,
  47010. configurable: true
  47011. });
  47012. Lines2D.prototype.levelIntersect = function (intersectInfo) {
  47013. var _this = this;
  47014. if (this._contour == null) {
  47015. this._computeLines2D();
  47016. }
  47017. var pl = this.points.length;
  47018. var l = this.closed ? pl + 1 : pl;
  47019. var p = intersectInfo._localPickPosition;
  47020. this.transformPointWithOriginToRef(this._contour[0], null, Lines2D._prevA);
  47021. this.transformPointWithOriginToRef(this._contour[1], null, Lines2D._prevB);
  47022. for (var i = 1; i < l; i++) {
  47023. this.transformPointWithOriginToRef(this._contour[(i % pl) * 2 + 0], null, Lines2D._curA);
  47024. this.transformPointWithOriginToRef(this._contour[(i % pl) * 2 + 1], null, Lines2D._curB);
  47025. if (BABYLON.Vector2.PointInTriangle(p, Lines2D._prevA, Lines2D._prevB, Lines2D._curA)) {
  47026. return true;
  47027. }
  47028. if (BABYLON.Vector2.PointInTriangle(p, Lines2D._curA, Lines2D._prevB, Lines2D._curB)) {
  47029. return true;
  47030. }
  47031. Lines2D._prevA.x = Lines2D._curA.x;
  47032. Lines2D._prevA.y = Lines2D._curA.y;
  47033. Lines2D._prevB.x = Lines2D._curB.x;
  47034. Lines2D._prevB.y = Lines2D._curB.y;
  47035. }
  47036. var capIntersect = function (tri, points) {
  47037. var l = tri.length;
  47038. for (var i = 0; i < l; i += 3) {
  47039. Lines2D._curA.x = points[tri[i + 0] * 2 + 0];
  47040. Lines2D._curA.y = points[tri[i + 0] * 2 + 1];
  47041. _this.transformPointWithOriginToRef(Lines2D._curA, null, Lines2D._curB);
  47042. Lines2D._curA.x = points[tri[i + 1] * 2 + 0];
  47043. Lines2D._curA.y = points[tri[i + 1] * 2 + 1];
  47044. _this.transformPointWithOriginToRef(Lines2D._curA, null, Lines2D._prevA);
  47045. Lines2D._curA.x = points[tri[i + 2] * 2 + 0];
  47046. Lines2D._curA.y = points[tri[i + 2] * 2 + 1];
  47047. _this.transformPointWithOriginToRef(Lines2D._curA, null, Lines2D._prevB);
  47048. if (BABYLON.Vector2.PointInTriangle(p, Lines2D._prevA, Lines2D._prevB, Lines2D._curB)) {
  47049. return true;
  47050. }
  47051. }
  47052. return false;
  47053. };
  47054. if (this._startCapTriIndices) {
  47055. if (this._startCapTriIndices && capIntersect(this._startCapTriIndices, this._startCapContour)) {
  47056. return true;
  47057. }
  47058. if (this._endCapTriIndices && capIntersect(this._endCapTriIndices, this._endCapContour)) {
  47059. return true;
  47060. }
  47061. }
  47062. return false;
  47063. };
  47064. Object.defineProperty(Lines2D.prototype, "boundingMin", {
  47065. get: function () {
  47066. if (!this._boundingMin) {
  47067. this._computeLines2D();
  47068. }
  47069. return this._boundingMin;
  47070. },
  47071. enumerable: true,
  47072. configurable: true
  47073. });
  47074. Object.defineProperty(Lines2D.prototype, "boundingMax", {
  47075. get: function () {
  47076. if (!this._boundingMax) {
  47077. this._computeLines2D();
  47078. }
  47079. return this._boundingMax;
  47080. },
  47081. enumerable: true,
  47082. configurable: true
  47083. });
  47084. Lines2D.prototype.getUsedShaderCategories = function (dataPart) {
  47085. var res = _super.prototype.getUsedShaderCategories.call(this, dataPart);
  47086. // Remove the BORDER category, we don't use it in the VertexShader
  47087. var i = res.indexOf(BABYLON.Shape2D.SHAPE2D_CATEGORY_BORDER);
  47088. if (i !== -1) {
  47089. res.splice(i, 1);
  47090. }
  47091. return res;
  47092. };
  47093. Lines2D.prototype.updateLevelBoundingInfo = function () {
  47094. if (!this._boundingMin) {
  47095. this._computeLines2D();
  47096. }
  47097. BABYLON.BoundingInfo2D.CreateFromMinMaxToRef(this._boundingMin.x, this._boundingMax.x, this._boundingMin.y, this._boundingMax.y, this._levelBoundingInfo);
  47098. };
  47099. Lines2D.prototype.createModelRenderCache = function (modelKey) {
  47100. var renderCache = new Lines2DRenderCache(this.owner.engine, modelKey);
  47101. return renderCache;
  47102. };
  47103. ///////////////////////////////////////////////////////////////////////////////////
  47104. // Methods for Lines building
  47105. Lines2D.prototype._perp = function (v, res) {
  47106. res.x = v.y;
  47107. res.y = -v.x;
  47108. };
  47109. ;
  47110. Lines2D.prototype._direction = function (a, b, res) {
  47111. a.subtractToRef(b, res);
  47112. res.normalize();
  47113. };
  47114. Lines2D.prototype._computeMiter = function (tangent, miter, a, b) {
  47115. a.addToRef(b, tangent);
  47116. tangent.normalize();
  47117. miter.x = -tangent.y;
  47118. miter.y = tangent.x;
  47119. Lines2D._miterTps.x = -a.y;
  47120. Lines2D._miterTps.y = a.x;
  47121. return 1 / BABYLON.Vector2.Dot(miter, Lines2D._miterTps);
  47122. };
  47123. Lines2D.prototype._intersect = function (x1, y1, x2, y2, x3, y3, x4, y4) {
  47124. var d = (x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4);
  47125. if (d === 0)
  47126. return false;
  47127. var xi = ((x3 - x4) * (x1 * y2 - y1 * x2) - (x1 - x2) * (x3 * y4 - y3 * x4)) / d; // Intersection point is xi/yi, just in case...
  47128. //let yi = ((y3 - y4) * (x1 * y2 - y1 * x2) - (y1 - y2) * (x3 * y4 - y3 * x4)) / d; // That's why I left it commented
  47129. if (xi < Math.min(x1, x2) || xi > Math.max(x1, x2))
  47130. return false;
  47131. if (xi < Math.min(x3, x4) || xi > Math.max(x3, x4))
  47132. return false;
  47133. return true;
  47134. };
  47135. Lines2D.prototype._updateMinMax = function (array, offset) {
  47136. if (offset >= array.length) {
  47137. return;
  47138. }
  47139. this._boundingMin.x = Math.min(this._boundingMin.x, array[offset]);
  47140. this._boundingMax.x = Math.max(this._boundingMax.x, array[offset]);
  47141. this._boundingMin.y = Math.min(this._boundingMin.y, array[offset + 1]);
  47142. this._boundingMax.y = Math.max(this._boundingMax.y, array[offset + 1]);
  47143. };
  47144. Lines2D.prototype._store = function (array, contour, index, max, p, n, halfThickness, borderThickness, detectFlip) {
  47145. var borderMode = borderThickness != null && !isNaN(borderThickness);
  47146. var off = index * (borderMode ? 8 : 4);
  47147. // 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)
  47148. if (off >= array.length) {
  47149. return;
  47150. }
  47151. // Store start/end normal, we need it for the cap construction
  47152. if (index === 0) {
  47153. this._perp(n, Lines2D._startDir);
  47154. }
  47155. else if (index === max - 1) {
  47156. this._perp(n, Lines2D._endDir);
  47157. Lines2D._endDir.x *= -1;
  47158. Lines2D._endDir.y *= -1;
  47159. }
  47160. var swap = false;
  47161. array[off + 0] = p.x + n.x * halfThickness;
  47162. array[off + 1] = p.y + n.y * halfThickness;
  47163. array[off + 2] = p.x + n.x * -halfThickness;
  47164. array[off + 3] = p.y + n.y * -halfThickness;
  47165. this._updateMinMax(array, off);
  47166. this._updateMinMax(array, off + 2);
  47167. // If an index is given we check if the two segments formed between [index+0;detectFlip+0] and [index+2;detectFlip+2] intersect themselves.
  47168. // 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
  47169. if (detectFlip !== undefined) {
  47170. // Flip if intersect
  47171. var flipOff = detectFlip * (borderMode ? 8 : 4);
  47172. 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])) {
  47173. swap = true;
  47174. var tps = array[off + 0];
  47175. array[off + 0] = array[off + 2];
  47176. array[off + 2] = tps;
  47177. tps = array[off + 1];
  47178. array[off + 1] = array[off + 3];
  47179. array[off + 3] = tps;
  47180. }
  47181. }
  47182. if (borderMode) {
  47183. var t = halfThickness + borderThickness;
  47184. array[off + 4] = p.x + n.x * (swap ? -t : t);
  47185. array[off + 5] = p.y + n.y * (swap ? -t : t);
  47186. array[off + 6] = p.x + n.x * (swap ? t : -t);
  47187. array[off + 7] = p.y + n.y * (swap ? t : -t);
  47188. this._updateMinMax(array, off + 4);
  47189. this._updateMinMax(array, off + 6);
  47190. }
  47191. if (contour) {
  47192. off += borderMode ? 4 : 0;
  47193. contour.push(new BABYLON.Vector2(array[off + 0], array[off + 1]));
  47194. contour.push(new BABYLON.Vector2(array[off + 2], array[off + 3]));
  47195. }
  47196. };
  47197. Lines2D.prototype._getCapSize = function (type, border) {
  47198. if (border === void 0) { border = false; }
  47199. var sd = Lines2D._roundCapSubDiv;
  47200. // If no array given, we call this to get the size
  47201. var vbsize = 0, ibsize = 0;
  47202. switch (type) {
  47203. case Lines2D.NoCap:
  47204. {
  47205. // If the line is not close and we're computing border, we add the size to generate the edge border
  47206. if (!this.closed && border) {
  47207. vbsize = 4;
  47208. ibsize = 6;
  47209. }
  47210. else {
  47211. vbsize = ibsize = 0;
  47212. }
  47213. break;
  47214. }
  47215. case Lines2D.RoundCap:
  47216. {
  47217. if (border) {
  47218. vbsize = sd;
  47219. ibsize = (sd - 2) * 3;
  47220. }
  47221. else {
  47222. vbsize = (sd / 2) + 1;
  47223. ibsize = (sd / 2) * 3;
  47224. }
  47225. break;
  47226. }
  47227. case Lines2D.ArrowCap:
  47228. {
  47229. if (border) {
  47230. vbsize = 12;
  47231. ibsize = 24;
  47232. }
  47233. else {
  47234. vbsize = 3;
  47235. ibsize = 3;
  47236. }
  47237. break;
  47238. }
  47239. case Lines2D.TriangleCap:
  47240. {
  47241. if (border) {
  47242. vbsize = 6;
  47243. ibsize = 12;
  47244. }
  47245. else {
  47246. vbsize = 3;
  47247. ibsize = 3;
  47248. }
  47249. break;
  47250. }
  47251. case Lines2D.DiamondAnchorCap:
  47252. {
  47253. if (border) {
  47254. vbsize = 10;
  47255. ibsize = 24;
  47256. }
  47257. else {
  47258. vbsize = 5;
  47259. ibsize = 9;
  47260. }
  47261. break;
  47262. }
  47263. case Lines2D.SquareAnchorCap:
  47264. {
  47265. if (border) {
  47266. vbsize = 12;
  47267. ibsize = 30;
  47268. }
  47269. else {
  47270. vbsize = 4;
  47271. ibsize = 6;
  47272. }
  47273. break;
  47274. }
  47275. case Lines2D.RoundAnchorCap:
  47276. {
  47277. if (border) {
  47278. vbsize = sd * 2;
  47279. ibsize = (sd - 1) * 6;
  47280. }
  47281. else {
  47282. vbsize = sd + 1;
  47283. ibsize = (sd + 1) * 3;
  47284. }
  47285. break;
  47286. }
  47287. }
  47288. return { vbsize: vbsize * 2, ibsize: ibsize };
  47289. };
  47290. Lines2D.prototype._storeVertex = function (vb, baseOffset, index, basePos, rotation, vertex, contour) {
  47291. var c = Math.cos(rotation);
  47292. var s = Math.sin(rotation);
  47293. Lines2D._tpsV.x = (c * vertex.x) + (-s * vertex.y) + basePos.x;
  47294. Lines2D._tpsV.y = (s * vertex.x) + (c * vertex.y) + basePos.y;
  47295. var offset = baseOffset + (index * 2);
  47296. vb[offset + 0] = Lines2D._tpsV.x;
  47297. vb[offset + 1] = Lines2D._tpsV.y;
  47298. if (contour) {
  47299. contour.push(Lines2D._tpsV.x);
  47300. contour.push(Lines2D._tpsV.y);
  47301. }
  47302. this._updateMinMax(vb, offset);
  47303. return (baseOffset + index * 2) / 2;
  47304. };
  47305. Lines2D.prototype._storeIndex = function (ib, baseOffset, index, vertexIndex) {
  47306. ib[baseOffset + index] = vertexIndex;
  47307. };
  47308. Lines2D.prototype._buildCap = function (vb, vbi, ib, ibi, pos, thickness, borderThickness, type, capDir, contour) {
  47309. // 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
  47310. var sd = Lines2D._roundCapSubDiv;
  47311. var dir = new BABYLON.Vector2(1, 0);
  47312. var angle = Math.atan2(capDir.y, capDir.x) - Math.atan2(dir.y, dir.x);
  47313. var ht = thickness / 2;
  47314. var t = thickness;
  47315. var borderMode = borderThickness != null;
  47316. var bt = borderThickness;
  47317. switch (type) {
  47318. case Lines2D.NoCap:
  47319. if (borderMode && !this.closed) {
  47320. var vi = 0;
  47321. var ii = 0;
  47322. var v1 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, ht + bt), contour);
  47323. var v2 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(bt, ht + bt), contour);
  47324. var v3 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(bt, -(ht + bt)), contour);
  47325. var v4 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, -(ht + bt)), contour);
  47326. this._storeIndex(ib, ibi, ii++, v1);
  47327. this._storeIndex(ib, ibi, ii++, v2);
  47328. this._storeIndex(ib, ibi, ii++, v3);
  47329. this._storeIndex(ib, ibi, ii++, v1);
  47330. this._storeIndex(ib, ibi, ii++, v3);
  47331. this._storeIndex(ib, ibi, ii++, v4);
  47332. }
  47333. break;
  47334. case Lines2D.ArrowCap:
  47335. ht *= 2;
  47336. case Lines2D.TriangleCap:
  47337. {
  47338. if (borderMode) {
  47339. var f = type === Lines2D.TriangleCap ? bt : Math.sqrt(bt * bt * 2);
  47340. var v1 = this._storeVertex(vb, vbi, 0, pos, angle, new BABYLON.Vector2(0, ht), null);
  47341. var v2 = this._storeVertex(vb, vbi, 1, pos, angle, new BABYLON.Vector2(ht, 0), null);
  47342. var v3 = this._storeVertex(vb, vbi, 2, pos, angle, new BABYLON.Vector2(0, -ht), null);
  47343. var v4 = this._storeVertex(vb, vbi, 3, pos, angle, new BABYLON.Vector2(0, ht + f), contour);
  47344. var v5 = this._storeVertex(vb, vbi, 4, pos, angle, new BABYLON.Vector2(ht + f, 0), contour);
  47345. var v6 = this._storeVertex(vb, vbi, 5, pos, angle, new BABYLON.Vector2(0, -(ht + f)), contour);
  47346. var ii = 0;
  47347. this._storeIndex(ib, ibi, ii++, v1);
  47348. this._storeIndex(ib, ibi, ii++, v4);
  47349. this._storeIndex(ib, ibi, ii++, v5);
  47350. this._storeIndex(ib, ibi, ii++, v1);
  47351. this._storeIndex(ib, ibi, ii++, v5);
  47352. this._storeIndex(ib, ibi, ii++, v2);
  47353. this._storeIndex(ib, ibi, ii++, v6);
  47354. this._storeIndex(ib, ibi, ii++, v3);
  47355. this._storeIndex(ib, ibi, ii++, v2);
  47356. this._storeIndex(ib, ibi, ii++, v6);
  47357. this._storeIndex(ib, ibi, ii++, v2);
  47358. this._storeIndex(ib, ibi, ii++, v5);
  47359. if (type === Lines2D.ArrowCap) {
  47360. var rht = thickness / 2;
  47361. var v10 = this._storeVertex(vb, vbi, 9, pos, angle, new BABYLON.Vector2(0, -(rht + bt)), null);
  47362. var v12 = this._storeVertex(vb, vbi, 11, pos, angle, new BABYLON.Vector2(-bt, -(ht + f)), contour);
  47363. var v11 = this._storeVertex(vb, vbi, 10, pos, angle, new BABYLON.Vector2(-bt, -(rht + bt)), contour);
  47364. var v7 = this._storeVertex(vb, vbi, 6, pos, angle, new BABYLON.Vector2(0, rht + bt), null);
  47365. var v8 = this._storeVertex(vb, vbi, 7, pos, angle, new BABYLON.Vector2(-bt, rht + bt), contour);
  47366. var v9 = this._storeVertex(vb, vbi, 8, pos, angle, new BABYLON.Vector2(-bt, ht + f), contour);
  47367. this._storeIndex(ib, ibi, ii++, v7);
  47368. this._storeIndex(ib, ibi, ii++, v8);
  47369. this._storeIndex(ib, ibi, ii++, v9);
  47370. this._storeIndex(ib, ibi, ii++, v7);
  47371. this._storeIndex(ib, ibi, ii++, v9);
  47372. this._storeIndex(ib, ibi, ii++, v4);
  47373. this._storeIndex(ib, ibi, ii++, v10);
  47374. this._storeIndex(ib, ibi, ii++, v12);
  47375. this._storeIndex(ib, ibi, ii++, v11);
  47376. this._storeIndex(ib, ibi, ii++, v10);
  47377. this._storeIndex(ib, ibi, ii++, v6);
  47378. this._storeIndex(ib, ibi, ii++, v12);
  47379. }
  47380. }
  47381. else {
  47382. var v1 = this._storeVertex(vb, vbi, 0, pos, angle, new BABYLON.Vector2(0, ht), contour);
  47383. var v2 = this._storeVertex(vb, vbi, 1, pos, angle, new BABYLON.Vector2(ht, 0), contour);
  47384. var v3 = this._storeVertex(vb, vbi, 2, pos, angle, new BABYLON.Vector2(0, -ht), contour);
  47385. this._storeIndex(ib, ibi, 0, v1);
  47386. this._storeIndex(ib, ibi, 1, v2);
  47387. this._storeIndex(ib, ibi, 2, v3);
  47388. }
  47389. break;
  47390. }
  47391. case Lines2D.RoundCap:
  47392. {
  47393. if (borderMode) {
  47394. var curA = -Math.PI / 2;
  47395. var incA = Math.PI / (sd / 2 - 1);
  47396. var ii = 0;
  47397. for (var i = 0; i < (sd / 2); i++) {
  47398. var v1 = this._storeVertex(vb, vbi, i * 2 + 0, pos, angle, new BABYLON.Vector2(Math.cos(curA) * ht, Math.sin(curA) * ht), null);
  47399. 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);
  47400. if (i > 0) {
  47401. this._storeIndex(ib, ibi, ii++, v1 - 2);
  47402. this._storeIndex(ib, ibi, ii++, v2 - 2);
  47403. this._storeIndex(ib, ibi, ii++, v2);
  47404. this._storeIndex(ib, ibi, ii++, v1 - 2);
  47405. this._storeIndex(ib, ibi, ii++, v2);
  47406. this._storeIndex(ib, ibi, ii++, v1);
  47407. }
  47408. curA += incA;
  47409. }
  47410. }
  47411. else {
  47412. var c = this._storeVertex(vb, vbi, 0, pos, angle, new BABYLON.Vector2(0, 0), null);
  47413. var curA = -Math.PI / 2;
  47414. var incA = Math.PI / (sd / 2 - 1);
  47415. this._storeVertex(vb, vbi, 1, pos, angle, new BABYLON.Vector2(Math.cos(curA) * ht, Math.sin(curA) * ht), null);
  47416. curA += incA;
  47417. for (var i = 1; i < (sd / 2); i++) {
  47418. var v2 = this._storeVertex(vb, vbi, i + 1, pos, angle, new BABYLON.Vector2(Math.cos(curA) * ht, Math.sin(curA) * ht), contour);
  47419. this._storeIndex(ib, ibi, i * 3 + 0, c);
  47420. this._storeIndex(ib, ibi, i * 3 + 1, v2 - 1);
  47421. this._storeIndex(ib, ibi, i * 3 + 2, v2);
  47422. curA += incA;
  47423. }
  47424. }
  47425. break;
  47426. }
  47427. case Lines2D.SquareAnchorCap:
  47428. {
  47429. var vi = 0;
  47430. var c = borderMode ? null : contour;
  47431. var v1 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, t), c);
  47432. var v2 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(t * 2, t), c);
  47433. var v3 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(t * 2, -t), c);
  47434. var v4 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, -t), c);
  47435. if (borderMode) {
  47436. var v5 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, ht + bt), null);
  47437. var v6 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(-bt, ht + bt), contour);
  47438. var v7 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(-bt, t + bt), contour);
  47439. var v8 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(t * 2 + bt, t + bt), contour);
  47440. var v9 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(t * 2 + bt, -(t + bt)), contour);
  47441. var v10 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(-bt, -(t + bt)), contour);
  47442. var v11 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(-bt, -(ht + bt)), contour);
  47443. var v12 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, -(ht + bt)), null);
  47444. var ii = 0;
  47445. this._storeIndex(ib, ibi, ii++, v6);
  47446. this._storeIndex(ib, ibi, ii++, v1);
  47447. this._storeIndex(ib, ibi, ii++, v5);
  47448. this._storeIndex(ib, ibi, ii++, v6);
  47449. this._storeIndex(ib, ibi, ii++, v7);
  47450. this._storeIndex(ib, ibi, ii++, v1);
  47451. this._storeIndex(ib, ibi, ii++, v1);
  47452. this._storeIndex(ib, ibi, ii++, v7);
  47453. this._storeIndex(ib, ibi, ii++, v8);
  47454. this._storeIndex(ib, ibi, ii++, v1);
  47455. this._storeIndex(ib, ibi, ii++, v8);
  47456. this._storeIndex(ib, ibi, ii++, v2);
  47457. this._storeIndex(ib, ibi, ii++, v2);
  47458. this._storeIndex(ib, ibi, ii++, v8);
  47459. this._storeIndex(ib, ibi, ii++, v9);
  47460. this._storeIndex(ib, ibi, ii++, v2);
  47461. this._storeIndex(ib, ibi, ii++, v9);
  47462. this._storeIndex(ib, ibi, ii++, v3);
  47463. this._storeIndex(ib, ibi, ii++, v3);
  47464. this._storeIndex(ib, ibi, ii++, v9);
  47465. this._storeIndex(ib, ibi, ii++, v10);
  47466. this._storeIndex(ib, ibi, ii++, v3);
  47467. this._storeIndex(ib, ibi, ii++, v10);
  47468. this._storeIndex(ib, ibi, ii++, v4);
  47469. this._storeIndex(ib, ibi, ii++, v10);
  47470. this._storeIndex(ib, ibi, ii++, v11);
  47471. this._storeIndex(ib, ibi, ii++, v4);
  47472. this._storeIndex(ib, ibi, ii++, v11);
  47473. this._storeIndex(ib, ibi, ii++, v12);
  47474. this._storeIndex(ib, ibi, ii++, v4);
  47475. }
  47476. else {
  47477. this._storeIndex(ib, ibi, 0, v1);
  47478. this._storeIndex(ib, ibi, 1, v2);
  47479. this._storeIndex(ib, ibi, 2, v3);
  47480. this._storeIndex(ib, ibi, 3, v1);
  47481. this._storeIndex(ib, ibi, 4, v3);
  47482. this._storeIndex(ib, ibi, 5, v4);
  47483. }
  47484. break;
  47485. }
  47486. case Lines2D.RoundAnchorCap:
  47487. {
  47488. var cpos = Math.sqrt(t * t - ht * ht);
  47489. var center = new BABYLON.Vector2(cpos, 0);
  47490. var curA = BABYLON.Tools.ToRadians(-150);
  47491. var incA = BABYLON.Tools.ToRadians(300) / (sd - 1);
  47492. if (borderMode) {
  47493. var ii = 0;
  47494. for (var i = 0; i < sd; i++) {
  47495. var v1 = this._storeVertex(vb, vbi, i * 2 + 0, pos, angle, new BABYLON.Vector2(cpos + Math.cos(curA) * t, Math.sin(curA) * t), null);
  47496. 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);
  47497. if (i > 0) {
  47498. this._storeIndex(ib, ibi, ii++, v1 - 2);
  47499. this._storeIndex(ib, ibi, ii++, v2 - 2);
  47500. this._storeIndex(ib, ibi, ii++, v2);
  47501. this._storeIndex(ib, ibi, ii++, v1 - 2);
  47502. this._storeIndex(ib, ibi, ii++, v2);
  47503. this._storeIndex(ib, ibi, ii++, v1);
  47504. }
  47505. curA += incA;
  47506. }
  47507. }
  47508. else {
  47509. var c = this._storeVertex(vb, vbi, 0, pos, angle, center, null);
  47510. this._storeVertex(vb, vbi, 1, pos, angle, new BABYLON.Vector2(cpos + Math.cos(curA) * t, Math.sin(curA) * t), null);
  47511. curA += incA;
  47512. for (var i = 1; i < sd; i++) {
  47513. var v2 = this._storeVertex(vb, vbi, i + 1, pos, angle, new BABYLON.Vector2(cpos + Math.cos(curA) * t, Math.sin(curA) * t), contour);
  47514. this._storeIndex(ib, ibi, i * 3 + 0, c);
  47515. this._storeIndex(ib, ibi, i * 3 + 1, v2 - 1);
  47516. this._storeIndex(ib, ibi, i * 3 + 2, v2);
  47517. curA += incA;
  47518. }
  47519. this._storeIndex(ib, ibi, sd * 3 + 0, c);
  47520. this._storeIndex(ib, ibi, sd * 3 + 1, c + 1);
  47521. this._storeIndex(ib, ibi, sd * 3 + 2, c + sd);
  47522. }
  47523. break;
  47524. }
  47525. case Lines2D.DiamondAnchorCap:
  47526. {
  47527. var vi = 0;
  47528. var c = borderMode ? null : contour;
  47529. var v1 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, ht), c);
  47530. var v2 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(ht, t), c);
  47531. var v3 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(ht * 3, 0), c);
  47532. var v4 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(ht, -t), c);
  47533. var v5 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, -ht), c);
  47534. if (borderMode) {
  47535. var f = Math.sqrt(bt * bt * 2);
  47536. var v6 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(-f, ht), contour);
  47537. var v7 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(ht, t + f), contour);
  47538. var v8 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(ht * 3 + f, 0), contour);
  47539. var v9 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(ht, -(t + f)), contour);
  47540. var v10 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(-f, -ht), contour);
  47541. var ii = 0;
  47542. this._storeIndex(ib, ibi, ii++, v6);
  47543. this._storeIndex(ib, ibi, ii++, v7);
  47544. this._storeIndex(ib, ibi, ii++, v1);
  47545. this._storeIndex(ib, ibi, ii++, v1);
  47546. this._storeIndex(ib, ibi, ii++, v7);
  47547. this._storeIndex(ib, ibi, ii++, v2);
  47548. this._storeIndex(ib, ibi, ii++, v2);
  47549. this._storeIndex(ib, ibi, ii++, v7);
  47550. this._storeIndex(ib, ibi, ii++, v8);
  47551. this._storeIndex(ib, ibi, ii++, v2);
  47552. this._storeIndex(ib, ibi, ii++, v8);
  47553. this._storeIndex(ib, ibi, ii++, v3);
  47554. this._storeIndex(ib, ibi, ii++, v3);
  47555. this._storeIndex(ib, ibi, ii++, v8);
  47556. this._storeIndex(ib, ibi, ii++, v9);
  47557. this._storeIndex(ib, ibi, ii++, v3);
  47558. this._storeIndex(ib, ibi, ii++, v9);
  47559. this._storeIndex(ib, ibi, ii++, v4);
  47560. this._storeIndex(ib, ibi, ii++, v4);
  47561. this._storeIndex(ib, ibi, ii++, v9);
  47562. this._storeIndex(ib, ibi, ii++, v10);
  47563. this._storeIndex(ib, ibi, ii++, v4);
  47564. this._storeIndex(ib, ibi, ii++, v10);
  47565. this._storeIndex(ib, ibi, ii++, v5);
  47566. }
  47567. else {
  47568. this._storeIndex(ib, ibi, 0, v1);
  47569. this._storeIndex(ib, ibi, 1, v2);
  47570. this._storeIndex(ib, ibi, 2, v3);
  47571. this._storeIndex(ib, ibi, 3, v1);
  47572. this._storeIndex(ib, ibi, 4, v3);
  47573. this._storeIndex(ib, ibi, 5, v5);
  47574. this._storeIndex(ib, ibi, 6, v5);
  47575. this._storeIndex(ib, ibi, 7, v3);
  47576. this._storeIndex(ib, ibi, 8, v4);
  47577. }
  47578. break;
  47579. }
  47580. }
  47581. return null;
  47582. };
  47583. Lines2D.prototype._buildLine = function (vb, contour, ht, bt) {
  47584. var lineA = BABYLON.Vector2.Zero();
  47585. var lineB = BABYLON.Vector2.Zero();
  47586. var tangent = BABYLON.Vector2.Zero();
  47587. var miter = BABYLON.Vector2.Zero();
  47588. var curNormal = null;
  47589. if (this.closed) {
  47590. this.points.push(this.points[0]);
  47591. }
  47592. var total = this.points.length;
  47593. for (var i = 1; i < total; i++) {
  47594. var last = this.points[i - 1];
  47595. var cur = this.points[i];
  47596. var next = (i < (this.points.length - 1)) ? this.points[i + 1] : null;
  47597. this._direction(cur, last, lineA);
  47598. if (!curNormal) {
  47599. curNormal = BABYLON.Vector2.Zero();
  47600. this._perp(lineA, curNormal);
  47601. }
  47602. if (i === 1) {
  47603. this._store(vb, contour, 0, total, this.points[0], curNormal, ht, bt);
  47604. }
  47605. if (!next) {
  47606. this._perp(lineA, curNormal);
  47607. this._store(vb, contour, i, total, this.points[i], curNormal, ht, bt, i - 1);
  47608. }
  47609. else {
  47610. this._direction(next, cur, lineB);
  47611. var miterLen = this._computeMiter(tangent, miter, lineA, lineB);
  47612. this._store(vb, contour, i, total, this.points[i], miter, miterLen * ht, miterLen * bt, i - 1);
  47613. }
  47614. }
  47615. if (this.points.length > 2 && this.closed) {
  47616. var last2 = this.points[total - 2];
  47617. var cur2 = this.points[0];
  47618. var next2 = this.points[1];
  47619. this._direction(cur2, last2, lineA);
  47620. this._direction(next2, cur2, lineB);
  47621. this._perp(lineA, curNormal);
  47622. var miterLen2 = this._computeMiter(tangent, miter, lineA, lineB);
  47623. this._store(vb, null, 0, total, this.points[0], miter, miterLen2 * ht, miterLen2 * bt, 1);
  47624. // Patch contour
  47625. if (contour) {
  47626. var off = (bt == null) ? 0 : 4;
  47627. contour[0].x = vb[off + 0];
  47628. contour[0].y = vb[off + 1];
  47629. contour[1].x = vb[off + 2];
  47630. contour[1].y = vb[off + 3];
  47631. }
  47632. }
  47633. // Remove the point we added at the beginning
  47634. if (this.closed) {
  47635. this.points.splice(total - 1);
  47636. }
  47637. };
  47638. // Methods for Lines building
  47639. ///////////////////////////////////////////////////////////////////////////////////
  47640. Lines2D.prototype.setupModelRenderCache = function (modelRenderCache) {
  47641. var renderCache = modelRenderCache;
  47642. var engine = this.owner.engine;
  47643. if (this._fillVB === null) {
  47644. this._computeLines2D();
  47645. }
  47646. // Need to create WebGL resources for fill part?
  47647. if (this.fill) {
  47648. renderCache.fillVB = engine.createVertexBuffer(this._fillVB);
  47649. renderCache.fillIB = engine.createIndexBuffer(this._fillIB);
  47650. renderCache.fillIndicesCount = this._fillIB.length;
  47651. // 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
  47652. var ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_FILLPARTID, ["position"], null, true);
  47653. if (ei) {
  47654. renderCache.effectFillInstanced = engine.createEffect("lines2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  47655. }
  47656. // Get the non instanced version
  47657. ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_FILLPARTID, ["position"], null, false);
  47658. renderCache.effectFill = engine.createEffect("lines2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  47659. }
  47660. // Need to create WebGL resources for border part?
  47661. if (this.border) {
  47662. renderCache.borderVB = engine.createVertexBuffer(this._borderVB);
  47663. renderCache.borderIB = engine.createIndexBuffer(this._borderIB);
  47664. renderCache.borderIndicesCount = this._borderIB.length;
  47665. // 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
  47666. var ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, ["position"], null, true);
  47667. if (ei) {
  47668. renderCache.effectBorderInstanced = engine.createEffect({ vertex: "lines2d", fragment: "lines2d" }, ei.attributes, ei.uniforms, [], ei.defines, null);
  47669. }
  47670. // Get the non instanced version
  47671. ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, ["position"], null, false);
  47672. renderCache.effectBorder = engine.createEffect({ vertex: "lines2d", fragment: "lines2d" }, ei.attributes, ei.uniforms, [], ei.defines, null);
  47673. }
  47674. this._fillVB = null;
  47675. this._fillIB = null;
  47676. this._borderVB = null;
  47677. this._borderIB = null;
  47678. return renderCache;
  47679. };
  47680. Lines2D.prototype._computeLines2D = function () {
  47681. // Init min/max because their being computed here
  47682. this._boundingMin = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  47683. this._boundingMax = new BABYLON.Vector2(Number.MIN_VALUE, Number.MIN_VALUE);
  47684. var contour = new Array();
  47685. var startCapContour = new Array();
  47686. var endCapContour = new Array();
  47687. // Need to create WebGL resources for fill part?
  47688. if (this.fill) {
  47689. var startCapInfo = this._getCapSize(this.startCap);
  47690. var endCapInfo = this._getCapSize(this.endCap);
  47691. var count = this.points.length;
  47692. var vbSize = (count * 2 * 2) + startCapInfo.vbsize + endCapInfo.vbsize;
  47693. this._fillVB = new Float32Array(vbSize);
  47694. var vb = this._fillVB;
  47695. var ht = this.fillThickness / 2;
  47696. var total = this.points.length;
  47697. this._buildLine(vb, this.border ? null : contour, ht);
  47698. var max = total * 2;
  47699. var triCount = (count - (this.closed ? 0 : 1)) * 2;
  47700. this._fillIB = new Float32Array(triCount * 3 + startCapInfo.ibsize + endCapInfo.ibsize);
  47701. var ib = this._fillIB;
  47702. for (var i = 0; i < triCount; i += 2) {
  47703. ib[i * 3 + 0] = i + 0;
  47704. ib[i * 3 + 1] = i + 1;
  47705. ib[i * 3 + 2] = (i + 2) % max;
  47706. ib[i * 3 + 3] = i + 1;
  47707. ib[i * 3 + 4] = (i + 3) % max;
  47708. ib[i * 3 + 5] = (i + 2) % max;
  47709. }
  47710. this._buildCap(vb, count * 2 * 2, ib, triCount * 3, this.points[0], this.fillThickness, null, this.startCap, Lines2D._startDir, this.border ? null : startCapContour);
  47711. 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);
  47712. }
  47713. // Need to create WebGL resources for border part?
  47714. if (this.border) {
  47715. var startCapInfo = this._getCapSize(this.startCap, true);
  47716. var endCapInfo = this._getCapSize(this.endCap, true);
  47717. var count = this.points.length;
  47718. var vbSize = (count * 2 * 2 * 2) + startCapInfo.vbsize + endCapInfo.vbsize;
  47719. this._borderVB = new Float32Array(vbSize);
  47720. var vb = this._borderVB;
  47721. var ht = this.fillThickness / 2;
  47722. var bt = this.borderThickness;
  47723. var total = this.points.length;
  47724. this._buildLine(vb, contour, ht, bt);
  47725. var max = total * 2 * 2;
  47726. var triCount = (count - (this.closed ? 0 : 1)) * 2 * 2;
  47727. this._borderIB = new Float32Array(triCount * 3 + startCapInfo.ibsize + endCapInfo.ibsize);
  47728. var ib = this._borderIB;
  47729. for (var i = 0; i < triCount; i += 4) {
  47730. ib[i * 3 + 0] = i + 0;
  47731. ib[i * 3 + 1] = i + 2;
  47732. ib[i * 3 + 2] = (i + 6) % max;
  47733. ib[i * 3 + 3] = i + 0;
  47734. ib[i * 3 + 4] = (i + 6) % max;
  47735. ib[i * 3 + 5] = (i + 4) % max;
  47736. ib[i * 3 + 6] = i + 3;
  47737. ib[i * 3 + 7] = i + 1;
  47738. ib[i * 3 + 8] = (i + 5) % max;
  47739. ib[i * 3 + 9] = i + 3;
  47740. ib[i * 3 + 10] = (i + 5) % max;
  47741. ib[i * 3 + 11] = (i + 7) % max;
  47742. }
  47743. this._buildCap(vb, count * 2 * 2 * 2, ib, triCount * 3, this.points[0], this.fillThickness, this.borderThickness, this.startCap, Lines2D._startDir, startCapContour);
  47744. 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);
  47745. }
  47746. this._contour = contour;
  47747. if (startCapContour.length > 0) {
  47748. var startCapTri = Earcut.earcut(startCapContour, null, 2);
  47749. this._startCapTriIndices = startCapTri;
  47750. this._startCapContour = startCapContour;
  47751. }
  47752. else {
  47753. this._startCapTriIndices = null;
  47754. this._startCapContour = null;
  47755. }
  47756. if (endCapContour.length > 0) {
  47757. var endCapTri = Earcut.earcut(endCapContour, null, 2);
  47758. this._endCapContour = endCapContour;
  47759. this._endCapTriIndices = endCapTri;
  47760. }
  47761. else {
  47762. this._endCapContour = null;
  47763. this._endCapTriIndices = null;
  47764. }
  47765. var bs = this._boundingMax.subtract(this._boundingMin);
  47766. this._size.width = bs.x;
  47767. this._size.height = bs.y;
  47768. };
  47769. Object.defineProperty(Lines2D.prototype, "size", {
  47770. get: function () {
  47771. if (this._size == null) {
  47772. this._computeLines2D();
  47773. }
  47774. return this._size;
  47775. },
  47776. enumerable: true,
  47777. configurable: true
  47778. });
  47779. Lines2D.prototype.createInstanceDataParts = function () {
  47780. var res = new Array();
  47781. if (this.border) {
  47782. res.push(new Lines2DInstanceData(BABYLON.Shape2D.SHAPE2D_BORDERPARTID));
  47783. }
  47784. if (this.fill) {
  47785. res.push(new Lines2DInstanceData(BABYLON.Shape2D.SHAPE2D_FILLPARTID));
  47786. }
  47787. return res;
  47788. };
  47789. Lines2D.prototype.applyActualScaleOnTransform = function () {
  47790. return true;
  47791. };
  47792. Lines2D.prototype.refreshInstanceDataPart = function (part) {
  47793. if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
  47794. return false;
  47795. }
  47796. if (part.id === BABYLON.Shape2D.SHAPE2D_BORDERPARTID) {
  47797. var d = part;
  47798. if (this.border instanceof BABYLON.GradientColorBrush2D) {
  47799. d.boundingMin = this.boundingMin;
  47800. d.boundingMax = this.boundingMax;
  47801. }
  47802. }
  47803. else if (part.id === BABYLON.Shape2D.SHAPE2D_FILLPARTID) {
  47804. var d = part;
  47805. if (this.fill instanceof BABYLON.GradientColorBrush2D) {
  47806. d.boundingMin = this.boundingMin;
  47807. d.boundingMax = this.boundingMax;
  47808. }
  47809. }
  47810. return true;
  47811. };
  47812. Lines2D._prevA = BABYLON.Vector2.Zero();
  47813. Lines2D._prevB = BABYLON.Vector2.Zero();
  47814. Lines2D._curA = BABYLON.Vector2.Zero();
  47815. Lines2D._curB = BABYLON.Vector2.Zero();
  47816. Lines2D._miterTps = BABYLON.Vector2.Zero();
  47817. Lines2D._startDir = BABYLON.Vector2.Zero();
  47818. Lines2D._endDir = BABYLON.Vector2.Zero();
  47819. Lines2D._tpsV = BABYLON.Vector2.Zero();
  47820. Lines2D._noCap = 0;
  47821. Lines2D._roundCap = 1;
  47822. Lines2D._triangleCap = 2;
  47823. Lines2D._squareAnchorCap = 3;
  47824. Lines2D._roundAnchorCap = 4;
  47825. Lines2D._diamondAnchorCap = 5;
  47826. Lines2D._arrowCap = 6;
  47827. Lines2D._roundCapSubDiv = 36;
  47828. __decorate([
  47829. BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 1, function (pi) { return Lines2D.pointsProperty = pi; })
  47830. ], Lines2D.prototype, "points", null);
  47831. __decorate([
  47832. BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 2, function (pi) { return Lines2D.fillThicknessProperty = pi; })
  47833. ], Lines2D.prototype, "fillThickness", null);
  47834. __decorate([
  47835. BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 3, function (pi) { return Lines2D.closedProperty = pi; })
  47836. ], Lines2D.prototype, "closed", null);
  47837. __decorate([
  47838. BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 4, function (pi) { return Lines2D.startCapProperty = pi; })
  47839. ], Lines2D.prototype, "startCap", null);
  47840. __decorate([
  47841. BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 5, function (pi) { return Lines2D.endCapProperty = pi; })
  47842. ], Lines2D.prototype, "endCap", null);
  47843. Lines2D = __decorate([
  47844. BABYLON.className("Lines2D")
  47845. ], Lines2D);
  47846. return Lines2D;
  47847. }(BABYLON.Shape2D));
  47848. BABYLON.Lines2D = Lines2D;
  47849. })(BABYLON || (BABYLON = {}));
  47850. var BABYLON;
  47851. (function (BABYLON) {
  47852. // This class contains data that lifetime is bounding to the Babylon Engine object
  47853. var Canvas2DEngineBoundData = (function () {
  47854. function Canvas2DEngineBoundData() {
  47855. this._modelCache = new BABYLON.StringDictionary();
  47856. }
  47857. Canvas2DEngineBoundData.prototype.GetOrAddModelCache = function (key, factory) {
  47858. return this._modelCache.getOrAddWithFactory(key, factory);
  47859. };
  47860. Canvas2DEngineBoundData.prototype.DisposeModelRenderCache = function (modelRenderCache) {
  47861. if (!modelRenderCache.isDisposed) {
  47862. return false;
  47863. }
  47864. this._modelCache.remove(modelRenderCache.modelKey);
  47865. return true;
  47866. };
  47867. return Canvas2DEngineBoundData;
  47868. }());
  47869. BABYLON.Canvas2DEngineBoundData = Canvas2DEngineBoundData;
  47870. var Canvas2D = (function (_super) {
  47871. __extends(Canvas2D, _super);
  47872. function Canvas2D(scene, settings) {
  47873. var _this = this;
  47874. _super.call(this, settings);
  47875. /**
  47876. * 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.
  47877. * Beware that you have to take under consideration the origin in your calculations! Good luck!
  47878. */
  47879. this.worldSpaceToNodeLocal = function (worldPos) {
  47880. var node = _this._worldSpaceNode;
  47881. if (!node) {
  47882. return;
  47883. }
  47884. var mtx = node.getWorldMatrix().clone();
  47885. mtx.invert();
  47886. var v = BABYLON.Vector3.TransformCoordinates(worldPos, mtx);
  47887. var res = new BABYLON.Vector2(v.x, v.y);
  47888. var size = _this.actualSize;
  47889. res.x += size.width * 0.5; // res is centered, make it relative to bottom/left
  47890. res.y += size.height * 0.5;
  47891. return res;
  47892. };
  47893. /**
  47894. * 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
  47895. */
  47896. this.worldSpaceCacheChanged = function () {
  47897. var plane = _this.worldSpaceCanvasNode;
  47898. var vd = BABYLON.VertexData.ExtractFromMesh(plane); //new VertexData();
  47899. vd.uvs = new Float32Array(8);
  47900. var material = plane.material;
  47901. var tex = _this._renderableData._cacheTexture;
  47902. if (material.diffuseTexture !== tex) {
  47903. material.diffuseTexture = tex;
  47904. tex.hasAlpha = true;
  47905. }
  47906. var nodeuv = _this._renderableData._cacheNodeUVs;
  47907. for (var i = 0; i < 4; i++) {
  47908. vd.uvs[i * 2 + 0] = nodeuv[i].x;
  47909. vd.uvs[i * 2 + 1] = nodeuv[i].y;
  47910. }
  47911. vd.applyToMesh(plane);
  47912. };
  47913. this._notifDebugMode = false;
  47914. this._mapCounter = 0;
  47915. this._drawCallsOpaqueCounter = new BABYLON.PerfCounter();
  47916. this._drawCallsAlphaTestCounter = new BABYLON.PerfCounter();
  47917. this._drawCallsTransparentCounter = new BABYLON.PerfCounter();
  47918. this._groupRenderCounter = new BABYLON.PerfCounter();
  47919. this._updateTransparentDataCounter = new BABYLON.PerfCounter();
  47920. this._cachedGroupRenderCounter = new BABYLON.PerfCounter();
  47921. this._updateCachedStateCounter = new BABYLON.PerfCounter();
  47922. this._updateLayoutCounter = new BABYLON.PerfCounter();
  47923. this._updatePositioningCounter = new BABYLON.PerfCounter();
  47924. this._updateLocalTransformCounter = new BABYLON.PerfCounter();
  47925. this._updateGlobalTransformCounter = new BABYLON.PerfCounter();
  47926. this._boundingInfoRecomputeCounter = new BABYLON.PerfCounter();
  47927. this._cachedCanvasGroup = null;
  47928. this._profileInfoText = null;
  47929. BABYLON.Prim2DBase._isCanvasInit = false;
  47930. if (!settings) {
  47931. settings = {};
  47932. }
  47933. if (this._cachingStrategy !== Canvas2D.CACHESTRATEGY_TOPLEVELGROUPS) {
  47934. this._background = new BABYLON.Rectangle2D({ parent: this, id: "###CANVAS BACKGROUND###", size: settings.size }); //TODO CHECK when size is null
  47935. this._background.zOrder = 1.0;
  47936. this._background.isPickable = false;
  47937. this._background.origin = BABYLON.Vector2.Zero();
  47938. this._background.levelVisible = false;
  47939. if (settings.backgroundRoundRadius != null) {
  47940. this.backgroundRoundRadius = settings.backgroundRoundRadius;
  47941. }
  47942. if (settings.backgroundBorder != null) {
  47943. if (typeof (settings.backgroundBorder) === "string") {
  47944. this.backgroundBorder = Canvas2D.GetBrushFromString(settings.backgroundBorder);
  47945. }
  47946. else {
  47947. this.backgroundBorder = settings.backgroundBorder;
  47948. }
  47949. }
  47950. if (settings.backgroundBorderThickNess != null) {
  47951. this.backgroundBorderThickness = settings.backgroundBorderThickNess;
  47952. }
  47953. if (settings.backgroundFill != null) {
  47954. if (typeof (settings.backgroundFill) === "string") {
  47955. this.backgroundFill = Canvas2D.GetBrushFromString(settings.backgroundFill);
  47956. }
  47957. else {
  47958. this.backgroundFill = settings.backgroundFill;
  47959. }
  47960. }
  47961. // Put a handler to resize the background whenever the canvas is resizing
  47962. this.propertyChanged.add(function (e, s) {
  47963. if (e.propertyName === "size") {
  47964. _this._background.size = _this.size;
  47965. }
  47966. }, BABYLON.Group2D.sizeProperty.flagId);
  47967. this._background._patchHierarchy(this);
  47968. }
  47969. var engine = scene.getEngine();
  47970. this.__engineData = engine.getOrAddExternalDataWithFactory("__BJSCANVAS2D__", function (k) { return new Canvas2DEngineBoundData(); });
  47971. this._primPointerInfo = new BABYLON.PrimitivePointerInfo();
  47972. this._capturedPointers = new BABYLON.StringDictionary();
  47973. this._pickStartingPosition = BABYLON.Vector2.Zero();
  47974. this._hierarchyLevelMaxSiblingCount = 50;
  47975. this._hierarchyDepth = 0;
  47976. this._zOrder = 0;
  47977. this._zMax = 1;
  47978. this._scene = scene;
  47979. this._engine = engine;
  47980. this._renderingSize = new BABYLON.Size(0, 0);
  47981. this._designSize = settings.designSize || null;
  47982. this._designUseHorizAxis = settings.designUseHorizAxis === true;
  47983. this._trackedGroups = new Array();
  47984. this._maxAdaptiveWorldSpaceCanvasSize = null;
  47985. this._groupCacheMaps = new BABYLON.StringDictionary();
  47986. this._patchHierarchy(this);
  47987. var enableInteraction = (settings.enableInteraction == null) ? true : settings.enableInteraction;
  47988. this._fitRenderingDevice = !settings.size;
  47989. if (!settings.size) {
  47990. settings.size = new BABYLON.Size(engine.getRenderWidth(), engine.getRenderHeight());
  47991. }
  47992. // Register scene dispose to also dispose the canvas when it'll happens
  47993. scene.onDisposeObservable.add(function (d, s) {
  47994. _this.dispose();
  47995. });
  47996. if (this._isScreenSpace) {
  47997. this._afterRenderObserver = this._scene.onAfterRenderObservable.add(function (d, s) {
  47998. _this._engine.clear(null, false, true, true);
  47999. _this._render();
  48000. });
  48001. }
  48002. else {
  48003. this._beforeRenderObserver = this._scene.onBeforeRenderObservable.add(function (d, s) {
  48004. _this._render();
  48005. });
  48006. }
  48007. this._supprtInstancedArray = this._engine.getCaps().instancedArrays !== null;
  48008. //this._supprtInstancedArray = false; // TODO REMOVE!!!
  48009. this._setupInteraction(enableInteraction);
  48010. }
  48011. Object.defineProperty(Canvas2D.prototype, "drawCallsOpaqueCounter", {
  48012. get: function () {
  48013. return this._drawCallsOpaqueCounter;
  48014. },
  48015. enumerable: true,
  48016. configurable: true
  48017. });
  48018. Object.defineProperty(Canvas2D.prototype, "drawCallsAlphaTestCounter", {
  48019. get: function () {
  48020. return this._drawCallsAlphaTestCounter;
  48021. },
  48022. enumerable: true,
  48023. configurable: true
  48024. });
  48025. Object.defineProperty(Canvas2D.prototype, "drawCallsTransparentCounter", {
  48026. get: function () {
  48027. return this._drawCallsTransparentCounter;
  48028. },
  48029. enumerable: true,
  48030. configurable: true
  48031. });
  48032. Object.defineProperty(Canvas2D.prototype, "groupRenderCounter", {
  48033. get: function () {
  48034. return this._groupRenderCounter;
  48035. },
  48036. enumerable: true,
  48037. configurable: true
  48038. });
  48039. Object.defineProperty(Canvas2D.prototype, "updateTransparentDataCounter", {
  48040. get: function () {
  48041. return this._updateTransparentDataCounter;
  48042. },
  48043. enumerable: true,
  48044. configurable: true
  48045. });
  48046. Object.defineProperty(Canvas2D.prototype, "cachedGroupRenderCounter", {
  48047. get: function () {
  48048. return this._cachedGroupRenderCounter;
  48049. },
  48050. enumerable: true,
  48051. configurable: true
  48052. });
  48053. Object.defineProperty(Canvas2D.prototype, "updateCachedStateCounter", {
  48054. get: function () {
  48055. return this._updateCachedStateCounter;
  48056. },
  48057. enumerable: true,
  48058. configurable: true
  48059. });
  48060. Object.defineProperty(Canvas2D.prototype, "updateLayoutCounter", {
  48061. get: function () {
  48062. return this._updateLayoutCounter;
  48063. },
  48064. enumerable: true,
  48065. configurable: true
  48066. });
  48067. Object.defineProperty(Canvas2D.prototype, "updatePositioningCounter", {
  48068. get: function () {
  48069. return this._updatePositioningCounter;
  48070. },
  48071. enumerable: true,
  48072. configurable: true
  48073. });
  48074. Object.defineProperty(Canvas2D.prototype, "updateLocalTransformCounter", {
  48075. get: function () {
  48076. return this._updateLocalTransformCounter;
  48077. },
  48078. enumerable: true,
  48079. configurable: true
  48080. });
  48081. Object.defineProperty(Canvas2D.prototype, "updateGlobalTransformCounter", {
  48082. get: function () {
  48083. return this._updateGlobalTransformCounter;
  48084. },
  48085. enumerable: true,
  48086. configurable: true
  48087. });
  48088. Object.defineProperty(Canvas2D.prototype, "boundingInfoRecomputeCounter", {
  48089. get: function () {
  48090. return this._boundingInfoRecomputeCounter;
  48091. },
  48092. enumerable: true,
  48093. configurable: true
  48094. });
  48095. Canvas2D.prototype._canvasPreInit = function (settings) {
  48096. var cachingStrategy = (settings.cachingStrategy == null) ? Canvas2D.CACHESTRATEGY_DONTCACHE : settings.cachingStrategy;
  48097. this._cachingStrategy = cachingStrategy;
  48098. this._isScreenSpace = (settings.isScreenSpace == null) ? true : settings.isScreenSpace;
  48099. };
  48100. Canvas2D.prototype._setupInteraction = function (enable) {
  48101. var _this = this;
  48102. // No change detection
  48103. if (enable === this._interactionEnabled) {
  48104. return;
  48105. }
  48106. // Set the new state
  48107. this._interactionEnabled = enable;
  48108. // ScreenSpace mode
  48109. if (this._isScreenSpace) {
  48110. // Disable interaction
  48111. if (!enable) {
  48112. if (this._scenePrePointerObserver) {
  48113. this.scene.onPrePointerObservable.remove(this._scenePrePointerObserver);
  48114. this._scenePrePointerObserver = null;
  48115. }
  48116. return;
  48117. }
  48118. // Enable Interaction
  48119. // Register the observable
  48120. this._scenePrePointerObserver = this.scene.onPrePointerObservable.add(function (e, s) {
  48121. if (_this.isVisible === false) {
  48122. return;
  48123. }
  48124. var hs = 1 / _this.engine.getHardwareScalingLevel();
  48125. var localPos = e.localPosition.multiplyByFloats(hs, hs);
  48126. _this._handlePointerEventForInteraction(e, localPos, s);
  48127. });
  48128. }
  48129. else {
  48130. var scene = this.scene;
  48131. if (enable) {
  48132. scene.constantlyUpdateMeshUnderPointer = true;
  48133. this._scenePointerObserver = scene.onPointerObservable.add(function (e, s) {
  48134. if (_this.isVisible === false) {
  48135. return;
  48136. }
  48137. if (e.pickInfo.hit && e.pickInfo.pickedMesh === _this._worldSpaceNode && _this.worldSpaceToNodeLocal) {
  48138. var localPos = _this.worldSpaceToNodeLocal(e.pickInfo.pickedPoint);
  48139. _this._handlePointerEventForInteraction(e, localPos, s);
  48140. }
  48141. });
  48142. }
  48143. else {
  48144. if (this._scenePointerObserver) {
  48145. this.scene.onPointerObservable.remove(this._scenePointerObserver);
  48146. this._scenePointerObserver = null;
  48147. }
  48148. }
  48149. }
  48150. };
  48151. /**
  48152. * Internal method, you should use the Prim2DBase version instead
  48153. */
  48154. Canvas2D.prototype._setPointerCapture = function (pointerId, primitive) {
  48155. if (this.isPointerCaptured(pointerId)) {
  48156. return false;
  48157. }
  48158. // Try to capture the pointer on the HTML side
  48159. try {
  48160. this.engine.getRenderingCanvas().setPointerCapture(pointerId);
  48161. }
  48162. catch (e) {
  48163. }
  48164. this._primPointerInfo.updateRelatedTarget(primitive, BABYLON.Vector2.Zero());
  48165. this._bubbleNotifyPrimPointerObserver(primitive, BABYLON.PrimitivePointerInfo.PointerGotCapture, null);
  48166. this._capturedPointers.add(pointerId.toString(), primitive);
  48167. return true;
  48168. };
  48169. /**
  48170. * Internal method, you should use the Prim2DBase version instead
  48171. */
  48172. Canvas2D.prototype._releasePointerCapture = function (pointerId, primitive) {
  48173. if (this._capturedPointers.get(pointerId.toString()) !== primitive) {
  48174. return false;
  48175. }
  48176. // Try to release the pointer on the HTML side
  48177. try {
  48178. this.engine.getRenderingCanvas().releasePointerCapture(pointerId);
  48179. }
  48180. catch (e) {
  48181. }
  48182. this._primPointerInfo.updateRelatedTarget(primitive, BABYLON.Vector2.Zero());
  48183. this._bubbleNotifyPrimPointerObserver(primitive, BABYLON.PrimitivePointerInfo.PointerLostCapture, null);
  48184. this._capturedPointers.remove(pointerId.toString());
  48185. return true;
  48186. };
  48187. /**
  48188. * Determine if the given pointer is captured or not
  48189. * @param pointerId the Id of the pointer
  48190. * @return true if it's captured, false otherwise
  48191. */
  48192. Canvas2D.prototype.isPointerCaptured = function (pointerId) {
  48193. return this._capturedPointers.contains(pointerId.toString());
  48194. };
  48195. Canvas2D.prototype.getCapturedPrimitive = function (pointerId) {
  48196. // Avoid unnecessary lookup
  48197. if (this._capturedPointers.count === 0) {
  48198. return null;
  48199. }
  48200. return this._capturedPointers.get(pointerId.toString());
  48201. };
  48202. Canvas2D.prototype._handlePointerEventForInteraction = function (eventData, localPosition, eventState) {
  48203. // Dispose check
  48204. if (this.isDisposed) {
  48205. return;
  48206. }
  48207. // Update the this._primPointerInfo structure we'll send to observers using the PointerEvent data
  48208. if (!this._updatePointerInfo(eventData, localPosition)) {
  48209. return;
  48210. }
  48211. var capturedPrim = this.getCapturedPrimitive(this._primPointerInfo.pointerId);
  48212. // 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.
  48213. // 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.
  48214. this._updateIntersectionList(this._primPointerInfo.canvasPointerPos, capturedPrim !== null, true);
  48215. // 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
  48216. this._updateOverStatus();
  48217. // Check if we have nothing to raise
  48218. if (!this._actualOverPrimitive && !capturedPrim) {
  48219. return;
  48220. }
  48221. // Update the relatedTarget info with the over primitive or the captured one (if any)
  48222. var targetPrim = capturedPrim || this._actualOverPrimitive.prim;
  48223. var targetPointerPos = capturedPrim ? this._primPointerInfo.canvasPointerPos.subtract(new BABYLON.Vector2(targetPrim.globalTransform.m[12], targetPrim.globalTransform.m[13])) : this._actualOverPrimitive.intersectionLocation;
  48224. this._primPointerInfo.updateRelatedTarget(targetPrim, targetPointerPos);
  48225. // Analyze the pointer event type and fire proper events on the primitive
  48226. var skip = false;
  48227. if (eventData.type === BABYLON.PointerEventTypes.POINTERWHEEL) {
  48228. skip = !this._bubbleNotifyPrimPointerObserver(targetPrim, BABYLON.PrimitivePointerInfo.PointerMouseWheel, eventData);
  48229. }
  48230. else if (eventData.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  48231. skip = !this._bubbleNotifyPrimPointerObserver(targetPrim, BABYLON.PrimitivePointerInfo.PointerMove, eventData);
  48232. }
  48233. else if (eventData.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  48234. skip = !this._bubbleNotifyPrimPointerObserver(targetPrim, BABYLON.PrimitivePointerInfo.PointerDown, eventData);
  48235. }
  48236. else if (eventData.type === BABYLON.PointerEventTypes.POINTERUP) {
  48237. skip = !this._bubbleNotifyPrimPointerObserver(targetPrim, BABYLON.PrimitivePointerInfo.PointerUp, eventData);
  48238. }
  48239. eventState.skipNextObservers = skip;
  48240. };
  48241. Canvas2D.prototype._updatePointerInfo = function (eventData, localPosition) {
  48242. var s = this.scale;
  48243. var pii = this._primPointerInfo;
  48244. if (!pii.canvasPointerPos) {
  48245. pii.canvasPointerPos = BABYLON.Vector2.Zero();
  48246. }
  48247. var camera = this._scene.cameraToUseForPointers || this._scene.activeCamera;
  48248. if (!camera || !camera.viewport) {
  48249. return false;
  48250. }
  48251. var engine = this._scene.getEngine();
  48252. if (this._isScreenSpace) {
  48253. var cameraViewport = camera.viewport;
  48254. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  48255. // Moving coordinates to local viewport world
  48256. var x = localPosition.x - viewport.x;
  48257. var y = localPosition.y - viewport.y;
  48258. pii.canvasPointerPos.x = (x - this.actualPosition.x) / s;
  48259. pii.canvasPointerPos.y = (engine.getRenderHeight() - y - this.actualPosition.y) / s;
  48260. }
  48261. else {
  48262. pii.canvasPointerPos.x = localPosition.x / s;
  48263. pii.canvasPointerPos.y = localPosition.y / s;
  48264. }
  48265. //console.log(`UpdatePointerInfo for ${this.id}, X:${pii.canvasPointerPos.x}, Y:${pii.canvasPointerPos.y}`);
  48266. pii.mouseWheelDelta = 0;
  48267. if (eventData.type === BABYLON.PointerEventTypes.POINTERWHEEL) {
  48268. var event = eventData.event;
  48269. if (event.wheelDelta) {
  48270. pii.mouseWheelDelta = event.wheelDelta / (BABYLON.PrimitivePointerInfo.MouseWheelPrecision * 40);
  48271. }
  48272. else if (event.detail) {
  48273. pii.mouseWheelDelta = -event.detail / BABYLON.PrimitivePointerInfo.MouseWheelPrecision;
  48274. }
  48275. }
  48276. else {
  48277. var pe = eventData.event;
  48278. pii.ctrlKey = pe.ctrlKey;
  48279. pii.altKey = pe.altKey;
  48280. pii.shiftKey = pe.shiftKey;
  48281. pii.metaKey = pe.metaKey;
  48282. pii.button = pe.button;
  48283. pii.buttons = pe.buttons;
  48284. pii.pointerId = pe.pointerId;
  48285. pii.width = pe.width;
  48286. pii.height = pe.height;
  48287. pii.presssure = pe.pressure;
  48288. pii.tilt.x = pe.tiltX;
  48289. pii.tilt.y = pe.tiltY;
  48290. pii.isCaptured = this.getCapturedPrimitive(pe.pointerId) !== null;
  48291. }
  48292. return true;
  48293. };
  48294. Canvas2D.prototype._updateIntersectionList = function (mouseLocalPos, isCapture, force) {
  48295. if (!force && (this.scene.getRenderId() === this._intersectionRenderId)) {
  48296. return;
  48297. }
  48298. // 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
  48299. if (!this._globalTransform) {
  48300. this.updateCachedStates(true);
  48301. }
  48302. var ii = Canvas2D._interInfo;
  48303. ii.pickPosition.x = mouseLocalPos.x;
  48304. ii.pickPosition.y = mouseLocalPos.y;
  48305. ii.findFirstOnly = false;
  48306. // Fast rejection: test if the mouse pointer is outside the canvas's bounding Info
  48307. if (!isCapture && !this.levelBoundingInfo.doesIntersect(ii.pickPosition)) {
  48308. this._previousIntersectionList = this._actualIntersectionList;
  48309. this._actualIntersectionList = null;
  48310. this._previousOverPrimitive = this._actualOverPrimitive;
  48311. this._actualOverPrimitive = null;
  48312. return;
  48313. }
  48314. this.intersect(ii);
  48315. this._previousIntersectionList = this._actualIntersectionList;
  48316. this._actualIntersectionList = ii.intersectedPrimitives;
  48317. this._previousOverPrimitive = this._actualOverPrimitive;
  48318. this._actualOverPrimitive = ii.topMostIntersectedPrimitive;
  48319. this._intersectionRenderId = this.scene.getRenderId();
  48320. };
  48321. // Based on the previousIntersectionList and the actualInstersectionList we can determined which primitives are being hover state or loosing it
  48322. Canvas2D.prototype._updateOverStatus = function () {
  48323. if ((this.scene.getRenderId() === this._hoverStatusRenderId) || !this._previousIntersectionList || !this._actualIntersectionList) {
  48324. return;
  48325. }
  48326. // Detect a change of over
  48327. var prevPrim = this._previousOverPrimitive ? this._previousOverPrimitive.prim : null;
  48328. var actualPrim = this._actualOverPrimitive ? this._actualOverPrimitive.prim : null;
  48329. if (prevPrim !== actualPrim) {
  48330. // Detect if the current pointer is captured, only fire event if they belong to the capture primitive
  48331. var capturedPrim = this.getCapturedPrimitive(this._primPointerInfo.pointerId);
  48332. // Notify the previous "over" prim that the pointer is no longer over it
  48333. if ((capturedPrim && capturedPrim === prevPrim) || (!capturedPrim && prevPrim)) {
  48334. this._primPointerInfo.updateRelatedTarget(prevPrim, this._previousOverPrimitive.intersectionLocation);
  48335. this._bubbleNotifyPrimPointerObserver(prevPrim, BABYLON.PrimitivePointerInfo.PointerOut, null);
  48336. }
  48337. // Notify the new "over" prim that the pointer is over it
  48338. if ((capturedPrim && capturedPrim === actualPrim) || (!capturedPrim && actualPrim)) {
  48339. this._primPointerInfo.updateRelatedTarget(actualPrim, this._actualOverPrimitive.intersectionLocation);
  48340. this._bubbleNotifyPrimPointerObserver(actualPrim, BABYLON.PrimitivePointerInfo.PointerOver, null);
  48341. }
  48342. }
  48343. this._hoverStatusRenderId = this.scene.getRenderId();
  48344. };
  48345. Canvas2D.prototype._updatePrimPointerPos = function (prim) {
  48346. if (this._primPointerInfo.isCaptured) {
  48347. this._primPointerInfo.primitivePointerPos = this._primPointerInfo.relatedTargetPointerPos;
  48348. }
  48349. else {
  48350. for (var _i = 0, _a = this._actualIntersectionList; _i < _a.length; _i++) {
  48351. var pii = _a[_i];
  48352. if (pii.prim === prim) {
  48353. this._primPointerInfo.primitivePointerPos = pii.intersectionLocation;
  48354. return;
  48355. }
  48356. }
  48357. }
  48358. };
  48359. Canvas2D.prototype._debugExecObserver = function (prim, mask) {
  48360. if (!this._notifDebugMode) {
  48361. return;
  48362. }
  48363. var debug = "";
  48364. for (var i = 0; i < prim.hierarchyDepth; i++) {
  48365. debug += " ";
  48366. }
  48367. var pii = this._primPointerInfo;
  48368. 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();
  48369. console.log(debug);
  48370. };
  48371. Canvas2D.prototype._bubbleNotifyPrimPointerObserver = function (prim, mask, eventData) {
  48372. var ppi = this._primPointerInfo;
  48373. var event = eventData ? eventData.event : null;
  48374. // In case of PointerOver/Out we will first notify the parent with PointerEnter/Leave
  48375. if ((mask & (BABYLON.PrimitivePointerInfo.PointerOver | BABYLON.PrimitivePointerInfo.PointerOut)) !== 0) {
  48376. this._notifParents(prim, mask);
  48377. }
  48378. var bubbleCancelled = false;
  48379. var cur = prim;
  48380. while (cur) {
  48381. // Only trigger the observers if the primitive is intersected (except for out)
  48382. if (!bubbleCancelled) {
  48383. this._updatePrimPointerPos(cur);
  48384. // Exec the observers
  48385. this._debugExecObserver(cur, mask);
  48386. if (!cur._pointerEventObservable.notifyObservers(ppi, mask) && eventData instanceof BABYLON.PointerInfoPre) {
  48387. eventData.skipOnPointerObservable = true;
  48388. return false;
  48389. }
  48390. this._triggerActionManager(cur, ppi, mask, event);
  48391. // Bubble canceled? If we're not executing PointerOver or PointerOut, quit immediately
  48392. // If it's PointerOver/Out we have to trigger PointerEnter/Leave no matter what
  48393. if (ppi.cancelBubble) {
  48394. if ((mask & (BABYLON.PrimitivePointerInfo.PointerOver | BABYLON.PrimitivePointerInfo.PointerOut)) === 0) {
  48395. return false;
  48396. }
  48397. // We're dealing with PointerOver/Out, let's keep looping to fire PointerEnter/Leave, but not Over/Out anymore
  48398. bubbleCancelled = true;
  48399. }
  48400. }
  48401. // If bubble is cancel we didn't update the Primitive Pointer Pos yet, let's do it
  48402. if (bubbleCancelled) {
  48403. this._updatePrimPointerPos(cur);
  48404. }
  48405. // Trigger a PointerEnter corresponding to the PointerOver
  48406. if (mask === BABYLON.PrimitivePointerInfo.PointerOver) {
  48407. this._debugExecObserver(cur, BABYLON.PrimitivePointerInfo.PointerEnter);
  48408. cur._pointerEventObservable.notifyObservers(ppi, BABYLON.PrimitivePointerInfo.PointerEnter);
  48409. }
  48410. else if (mask === BABYLON.PrimitivePointerInfo.PointerOut) {
  48411. this._debugExecObserver(cur, BABYLON.PrimitivePointerInfo.PointerLeave);
  48412. cur._pointerEventObservable.notifyObservers(ppi, BABYLON.PrimitivePointerInfo.PointerLeave);
  48413. }
  48414. // Loop to the parent
  48415. cur = cur.parent;
  48416. }
  48417. return true;
  48418. };
  48419. Canvas2D.prototype._triggerActionManager = function (prim, ppi, mask, eventData) {
  48420. var _this = this;
  48421. // 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
  48422. if (!this._globalTransform) {
  48423. this.updateCachedStates(true);
  48424. }
  48425. // Process Trigger related to PointerDown
  48426. if ((mask & BABYLON.PrimitivePointerInfo.PointerDown) !== 0) {
  48427. // On pointer down, record the current position and time to be able to trick PickTrigger and LongPressTrigger
  48428. this._pickStartingPosition = ppi.primitivePointerPos.clone();
  48429. this._pickStartingTime = new Date().getTime();
  48430. this._pickedDownPrim = null;
  48431. if (prim.actionManager) {
  48432. this._pickedDownPrim = prim;
  48433. if (prim.actionManager.hasPickTriggers) {
  48434. var actionEvent = BABYLON.ActionEvent.CreateNewFromPrimitive(prim, ppi.primitivePointerPos, eventData);
  48435. switch (eventData.button) {
  48436. case 0:
  48437. prim.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, actionEvent);
  48438. break;
  48439. case 1:
  48440. prim.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, actionEvent);
  48441. break;
  48442. case 2:
  48443. prim.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, actionEvent);
  48444. break;
  48445. }
  48446. prim.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, actionEvent);
  48447. }
  48448. if (prim.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  48449. window.setTimeout(function () {
  48450. var ppi = _this._primPointerInfo;
  48451. var capturedPrim = _this.getCapturedPrimitive(ppi.pointerId);
  48452. _this._updateIntersectionList(ppi.canvasPointerPos, capturedPrim !== null, true);
  48453. var ii = new BABYLON.IntersectInfo2D();
  48454. ii.pickPosition = ppi.canvasPointerPos.clone();
  48455. ii.findFirstOnly = false;
  48456. _this.intersect(ii);
  48457. if (ii.isPrimIntersected(prim) !== null) {
  48458. if (prim.actionManager) {
  48459. 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)) {
  48460. _this._pickStartingTime = 0;
  48461. prim.actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNewFromPrimitive(prim, ppi.primitivePointerPos, eventData));
  48462. }
  48463. }
  48464. }
  48465. }, BABYLON.ActionManager.LongPressDelay);
  48466. }
  48467. }
  48468. }
  48469. else if ((mask & BABYLON.PrimitivePointerInfo.PointerUp) !== 0) {
  48470. this._pickStartingTime = 0;
  48471. var actionEvent = BABYLON.ActionEvent.CreateNewFromPrimitive(prim, ppi.primitivePointerPos, eventData);
  48472. if (prim.actionManager) {
  48473. // OnPickUpTrigger
  48474. prim.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, actionEvent);
  48475. // OnPickTrigger
  48476. if (Math.abs(this._pickStartingPosition.x - ppi.canvasPointerPos.x) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(this._pickStartingPosition.y - ppi.canvasPointerPos.y) < BABYLON.ActionManager.DragMovementThreshold) {
  48477. prim.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, actionEvent);
  48478. }
  48479. }
  48480. // OnPickOutTrigger
  48481. if (this._pickedDownPrim && this._pickedDownPrim.actionManager && (this._pickedDownPrim !== prim)) {
  48482. this._pickedDownPrim.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, actionEvent);
  48483. }
  48484. }
  48485. else if ((mask & BABYLON.PrimitivePointerInfo.PointerOver) !== 0) {
  48486. if (prim.actionManager) {
  48487. var actionEvent = BABYLON.ActionEvent.CreateNewFromPrimitive(prim, ppi.primitivePointerPos, eventData);
  48488. prim.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, actionEvent);
  48489. }
  48490. }
  48491. else if ((mask & BABYLON.PrimitivePointerInfo.PointerOut) !== 0) {
  48492. if (prim.actionManager) {
  48493. var actionEvent = BABYLON.ActionEvent.CreateNewFromPrimitive(prim, ppi.primitivePointerPos, eventData);
  48494. prim.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, actionEvent);
  48495. }
  48496. }
  48497. };
  48498. Canvas2D.prototype._notifParents = function (prim, mask) {
  48499. var pii = this._primPointerInfo;
  48500. var curPrim = this;
  48501. while (curPrim) {
  48502. this._updatePrimPointerPos(curPrim);
  48503. // Fire the proper notification
  48504. if (mask === BABYLON.PrimitivePointerInfo.PointerOver) {
  48505. this._debugExecObserver(curPrim, BABYLON.PrimitivePointerInfo.PointerEnter);
  48506. curPrim._pointerEventObservable.notifyObservers(pii, BABYLON.PrimitivePointerInfo.PointerEnter);
  48507. }
  48508. else if (mask === BABYLON.PrimitivePointerInfo.PointerOut) {
  48509. this._debugExecObserver(curPrim, BABYLON.PrimitivePointerInfo.PointerLeave);
  48510. curPrim._pointerEventObservable.notifyObservers(pii, BABYLON.PrimitivePointerInfo.PointerLeave);
  48511. }
  48512. curPrim = curPrim.parent;
  48513. }
  48514. };
  48515. /**
  48516. * Don't forget to call the dispose method when you're done with the Canvas instance.
  48517. * But don't worry, if you dispose its scene, the canvas will be automatically disposed too.
  48518. */
  48519. Canvas2D.prototype.dispose = function () {
  48520. if (!_super.prototype.dispose.call(this)) {
  48521. return false;
  48522. }
  48523. if (this._profilingCanvas) {
  48524. this._profilingCanvas.dispose();
  48525. this._profilingCanvas = null;
  48526. }
  48527. if (this.interactionEnabled) {
  48528. this._setupInteraction(false);
  48529. }
  48530. if (this._beforeRenderObserver) {
  48531. this._scene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  48532. this._beforeRenderObserver = null;
  48533. }
  48534. if (this._afterRenderObserver) {
  48535. this._scene.onAfterRenderObservable.remove(this._afterRenderObserver);
  48536. this._afterRenderObserver = null;
  48537. }
  48538. if (this._groupCacheMaps) {
  48539. this._groupCacheMaps.forEach(function (k, m) { return m.forEach(function (e) { return e.dispose(); }); });
  48540. this._groupCacheMaps = null;
  48541. }
  48542. };
  48543. Object.defineProperty(Canvas2D.prototype, "scene", {
  48544. /**
  48545. * Accessor to the Scene that owns the Canvas
  48546. * @returns The instance of the Scene object
  48547. */
  48548. get: function () {
  48549. return this._scene;
  48550. },
  48551. enumerable: true,
  48552. configurable: true
  48553. });
  48554. Object.defineProperty(Canvas2D.prototype, "engine", {
  48555. /**
  48556. * Accessor to the Engine that drives the Scene used by this Canvas
  48557. * @returns The instance of the Engine object
  48558. */
  48559. get: function () {
  48560. return this._engine;
  48561. },
  48562. enumerable: true,
  48563. configurable: true
  48564. });
  48565. Object.defineProperty(Canvas2D.prototype, "cachingStrategy", {
  48566. /**
  48567. * Accessor of the Caching Strategy used by this Canvas.
  48568. * See Canvas2D.CACHESTRATEGY_xxxx static members for more information
  48569. * @returns the value corresponding to the used strategy.
  48570. */
  48571. get: function () {
  48572. return this._cachingStrategy;
  48573. },
  48574. enumerable: true,
  48575. configurable: true
  48576. });
  48577. Object.defineProperty(Canvas2D.prototype, "isScreenSpace", {
  48578. /**
  48579. * Return true if the Canvas is a Screen Space one, false if it's a World Space one.
  48580. * @returns {}
  48581. */
  48582. get: function () {
  48583. return this._isScreenSpace;
  48584. },
  48585. enumerable: true,
  48586. configurable: true
  48587. });
  48588. Object.defineProperty(Canvas2D.prototype, "worldSpaceCanvasNode", {
  48589. /**
  48590. * Only valid for World Space Canvas, returns the scene node that displays the canvas
  48591. */
  48592. get: function () {
  48593. return this._worldSpaceNode;
  48594. },
  48595. set: function (val) {
  48596. this._worldSpaceNode = val;
  48597. },
  48598. enumerable: true,
  48599. configurable: true
  48600. });
  48601. Object.defineProperty(Canvas2D.prototype, "supportInstancedArray", {
  48602. /**
  48603. * Check if the WebGL Instanced Array extension is supported or not
  48604. */
  48605. get: function () {
  48606. return this._supprtInstancedArray;
  48607. },
  48608. enumerable: true,
  48609. configurable: true
  48610. });
  48611. Object.defineProperty(Canvas2D.prototype, "backgroundFill", {
  48612. /**
  48613. * Property that defines the fill object used to draw the background of the Canvas.
  48614. * Note that Canvas with a Caching Strategy of
  48615. * @returns If the background is not set, null will be returned, otherwise a valid fill object is returned.
  48616. */
  48617. get: function () {
  48618. if (!this._background || !this._background.isVisible) {
  48619. return null;
  48620. }
  48621. return this._background.fill;
  48622. },
  48623. set: function (value) {
  48624. this.checkBackgroundAvailability();
  48625. if (value === this._background.fill) {
  48626. return;
  48627. }
  48628. this._background.fill = value;
  48629. this._background.levelVisible = true;
  48630. },
  48631. enumerable: true,
  48632. configurable: true
  48633. });
  48634. Object.defineProperty(Canvas2D.prototype, "backgroundBorder", {
  48635. /**
  48636. * Property that defines the border object used to draw the background of the Canvas.
  48637. * @returns If the background is not set, null will be returned, otherwise a valid border object is returned.
  48638. */
  48639. get: function () {
  48640. if (!this._background || !this._background.isVisible) {
  48641. return null;
  48642. }
  48643. return this._background.border;
  48644. },
  48645. set: function (value) {
  48646. this.checkBackgroundAvailability();
  48647. if (value === this._background.border) {
  48648. return;
  48649. }
  48650. this._background.border = value;
  48651. this._background.levelVisible = true;
  48652. },
  48653. enumerable: true,
  48654. configurable: true
  48655. });
  48656. Object.defineProperty(Canvas2D.prototype, "backgroundBorderThickness", {
  48657. /**
  48658. * Property that defines the thickness of the border object used to draw the background of the Canvas.
  48659. * @returns If the background is not set, null will be returned, otherwise a valid number matching the thickness is returned.
  48660. */
  48661. get: function () {
  48662. if (!this._background || !this._background.isVisible) {
  48663. return null;
  48664. }
  48665. return this._background.borderThickness;
  48666. },
  48667. set: function (value) {
  48668. this.checkBackgroundAvailability();
  48669. if (value === this._background.borderThickness) {
  48670. return;
  48671. }
  48672. this._background.borderThickness = value;
  48673. },
  48674. enumerable: true,
  48675. configurable: true
  48676. });
  48677. Object.defineProperty(Canvas2D.prototype, "backgroundRoundRadius", {
  48678. /**
  48679. * You can set the roundRadius of the background
  48680. * @returns The current roundRadius
  48681. */
  48682. get: function () {
  48683. if (!this._background || !this._background.isVisible) {
  48684. return null;
  48685. }
  48686. return this._background.roundRadius;
  48687. },
  48688. set: function (value) {
  48689. this.checkBackgroundAvailability();
  48690. if (value === this._background.roundRadius) {
  48691. return;
  48692. }
  48693. this._background.roundRadius = value;
  48694. this._background.levelVisible = true;
  48695. },
  48696. enumerable: true,
  48697. configurable: true
  48698. });
  48699. Object.defineProperty(Canvas2D.prototype, "interactionEnabled", {
  48700. /**
  48701. * Enable/Disable interaction for this Canvas
  48702. * When enabled the Prim2DBase.pointerEventObservable property will notified when appropriate events occur
  48703. */
  48704. get: function () {
  48705. return this._interactionEnabled;
  48706. },
  48707. set: function (enable) {
  48708. this._setupInteraction(enable);
  48709. },
  48710. enumerable: true,
  48711. configurable: true
  48712. });
  48713. Object.defineProperty(Canvas2D.prototype, "designSize", {
  48714. get: function () {
  48715. return this._designSize;
  48716. },
  48717. enumerable: true,
  48718. configurable: true
  48719. });
  48720. Object.defineProperty(Canvas2D.prototype, "designSizeUseHorizAxis", {
  48721. get: function () {
  48722. return this._designUseHorizAxis;
  48723. },
  48724. enumerable: true,
  48725. configurable: true
  48726. });
  48727. Object.defineProperty(Canvas2D.prototype, "_engineData", {
  48728. /**
  48729. * Access the babylon.js' engine bound data, do not invoke this method, it's for internal purpose only
  48730. * @returns {}
  48731. */
  48732. get: function () {
  48733. return this.__engineData;
  48734. },
  48735. enumerable: true,
  48736. configurable: true
  48737. });
  48738. Canvas2D.prototype.createCanvasProfileInfoCanvas = function () {
  48739. if (this._profilingCanvas) {
  48740. return this._profilingCanvas;
  48741. }
  48742. var canvas = new ScreenSpaceCanvas2D(this.scene, {
  48743. id: "ProfileInfoCanvas", cachingStrategy: Canvas2D.CACHESTRATEGY_DONTCACHE, children: [
  48744. new BABYLON.Rectangle2D({
  48745. id: "ProfileBorder", border: "#FFFFFFFF", borderThickness: 2, roundRadius: 5, fill: "#C04040C0", marginAlignment: "h: left, v: top", margin: "10", padding: "10", children: [
  48746. new BABYLON.Text2D("Stats", { id: "ProfileInfoText", marginAlignment: "h: left, v: top", fontName: "10pt Lucida Console" })
  48747. ]
  48748. })
  48749. ]
  48750. });
  48751. this._profileInfoText = canvas.findById("ProfileInfoText");
  48752. this._profilingCanvas = canvas;
  48753. return canvas;
  48754. };
  48755. Canvas2D.prototype.checkBackgroundAvailability = function () {
  48756. if (this._cachingStrategy === Canvas2D.CACHESTRATEGY_TOPLEVELGROUPS) {
  48757. throw Error("Can't use Canvas Background with the caching strategy TOPLEVELGROUPS");
  48758. }
  48759. };
  48760. Canvas2D.prototype._initPerfMetrics = function () {
  48761. this._drawCallsOpaqueCounter.fetchNewFrame();
  48762. this._drawCallsAlphaTestCounter.fetchNewFrame();
  48763. this._drawCallsTransparentCounter.fetchNewFrame();
  48764. this._groupRenderCounter.fetchNewFrame();
  48765. this._updateTransparentDataCounter.fetchNewFrame();
  48766. this._cachedGroupRenderCounter.fetchNewFrame();
  48767. this._updateCachedStateCounter.fetchNewFrame();
  48768. this._updateLayoutCounter.fetchNewFrame();
  48769. this._updatePositioningCounter.fetchNewFrame();
  48770. this._updateLocalTransformCounter.fetchNewFrame();
  48771. this._updateGlobalTransformCounter.fetchNewFrame();
  48772. this._boundingInfoRecomputeCounter.fetchNewFrame();
  48773. };
  48774. Canvas2D.prototype._fetchPerfMetrics = function () {
  48775. this._drawCallsOpaqueCounter.addCount(0, true);
  48776. this._drawCallsAlphaTestCounter.addCount(0, true);
  48777. this._drawCallsTransparentCounter.addCount(0, true);
  48778. this._groupRenderCounter.addCount(0, true);
  48779. this._updateTransparentDataCounter.addCount(0, true);
  48780. this._cachedGroupRenderCounter.addCount(0, true);
  48781. this._updateCachedStateCounter.addCount(0, true);
  48782. this._updateLayoutCounter.addCount(0, true);
  48783. this._updatePositioningCounter.addCount(0, true);
  48784. this._updateLocalTransformCounter.addCount(0, true);
  48785. this._updateGlobalTransformCounter.addCount(0, true);
  48786. this._boundingInfoRecomputeCounter.addCount(0, true);
  48787. };
  48788. Canvas2D.prototype._updateProfileCanvas = function () {
  48789. if (this._profileInfoText == null) {
  48790. return;
  48791. }
  48792. var format = function (v) { return (Math.round(v * 100) / 100).toString(); };
  48793. var p = "Draw Calls:\n" +
  48794. (" - Opaque: " + format(this.drawCallsOpaqueCounter.current) + ", (avg:" + format(this.drawCallsOpaqueCounter.lastSecAverage) + ", t:" + format(this.drawCallsOpaqueCounter.total) + ")\n") +
  48795. (" - AlphaTest: " + format(this.drawCallsAlphaTestCounter.current) + ", (avg:" + format(this.drawCallsAlphaTestCounter.lastSecAverage) + ", t:" + format(this.drawCallsAlphaTestCounter.total) + ")\n") +
  48796. (" - Transparent: " + format(this.drawCallsTransparentCounter.current) + ", (avg:" + format(this.drawCallsTransparentCounter.lastSecAverage) + ", t:" + format(this.drawCallsTransparentCounter.total) + ")\n") +
  48797. ("Group Render: " + this.groupRenderCounter.current + ", (avg:" + format(this.groupRenderCounter.lastSecAverage) + ", t:" + format(this.groupRenderCounter.total) + ")\n") +
  48798. ("Update Transparent Data: " + this.updateTransparentDataCounter.current + ", (avg:" + format(this.updateTransparentDataCounter.lastSecAverage) + ", t:" + format(this.updateTransparentDataCounter.total) + ")\n") +
  48799. ("Cached Group Render: " + this.cachedGroupRenderCounter.current + ", (avg:" + format(this.cachedGroupRenderCounter.lastSecAverage) + ", t:" + format(this.cachedGroupRenderCounter.total) + ")\n") +
  48800. ("Update Cached States: " + this.updateCachedStateCounter.current + ", (avg:" + format(this.updateCachedStateCounter.lastSecAverage) + ", t:" + format(this.updateCachedStateCounter.total) + ")\n") +
  48801. (" - Update Layout: " + this.updateLayoutCounter.current + ", (avg:" + format(this.updateLayoutCounter.lastSecAverage) + ", t:" + format(this.updateLayoutCounter.total) + ")\n") +
  48802. (" - Update Positioning: " + this.updatePositioningCounter.current + ", (avg:" + format(this.updatePositioningCounter.lastSecAverage) + ", t:" + format(this.updatePositioningCounter.total) + ")\n") +
  48803. (" - Update Local Trans: " + this.updateLocalTransformCounter.current + ", (avg:" + format(this.updateLocalTransformCounter.lastSecAverage) + ", t:" + format(this.updateLocalTransformCounter.total) + ")\n") +
  48804. (" - Update Global Trans: " + this.updateGlobalTransformCounter.current + ", (avg:" + format(this.updateGlobalTransformCounter.lastSecAverage) + ", t:" + format(this.updateGlobalTransformCounter.total) + ")\n") +
  48805. (" - BoundingInfo Recompute: " + this.boundingInfoRecomputeCounter.current + ", (avg:" + format(this.boundingInfoRecomputeCounter.lastSecAverage) + ", t:" + format(this.boundingInfoRecomputeCounter.total) + ")\n");
  48806. this._profileInfoText.text = p;
  48807. };
  48808. Canvas2D.prototype._addDrawCallCount = function (count, renderMode) {
  48809. switch (renderMode) {
  48810. case BABYLON.Render2DContext.RenderModeOpaque:
  48811. this._drawCallsOpaqueCounter.addCount(count, false);
  48812. return;
  48813. case BABYLON.Render2DContext.RenderModeAlphaTest:
  48814. this._drawCallsAlphaTestCounter.addCount(count, false);
  48815. return;
  48816. case BABYLON.Render2DContext.RenderModeTransparent:
  48817. this._drawCallsTransparentCounter.addCount(count, false);
  48818. return;
  48819. }
  48820. };
  48821. Canvas2D.prototype._addGroupRenderCount = function (count) {
  48822. this._groupRenderCounter.addCount(count, false);
  48823. };
  48824. Canvas2D.prototype._addUpdateTransparentDataCount = function (count) {
  48825. this._updateTransparentDataCounter.addCount(count, false);
  48826. };
  48827. Canvas2D.prototype.addCachedGroupRenderCounter = function (count) {
  48828. this._cachedGroupRenderCounter.addCount(count, false);
  48829. };
  48830. Canvas2D.prototype.addUpdateCachedStateCounter = function (count) {
  48831. this._updateCachedStateCounter.addCount(count, false);
  48832. };
  48833. Canvas2D.prototype.addUpdateLayoutCounter = function (count) {
  48834. this._updateLayoutCounter.addCount(count, false);
  48835. };
  48836. Canvas2D.prototype.addUpdatePositioningCounter = function (count) {
  48837. this._updatePositioningCounter.addCount(count, false);
  48838. };
  48839. Canvas2D.prototype.addupdateLocalTransformCounter = function (count) {
  48840. this._updateLocalTransformCounter.addCount(count, false);
  48841. };
  48842. Canvas2D.prototype.addUpdateGlobalTransformCounter = function (count) {
  48843. this._updateGlobalTransformCounter.addCount(count, false);
  48844. };
  48845. Canvas2D.prototype._updateTrackedNodes = function () {
  48846. var cam = this.scene.cameraToUseForPointers || this.scene.activeCamera;
  48847. cam.getViewMatrix().multiplyToRef(cam.getProjectionMatrix(), Canvas2D._m);
  48848. var rh = this.engine.getRenderHeight();
  48849. var v = cam.viewport.toGlobal(this.engine.getRenderWidth(), rh);
  48850. for (var _i = 0, _a = this._trackedGroups; _i < _a.length; _i++) {
  48851. var group = _a[_i];
  48852. if (group.isDisposed || !group.isVisible) {
  48853. continue;
  48854. }
  48855. var node = group.trackedNode;
  48856. var worldMtx = node.getWorldMatrix();
  48857. var proj = BABYLON.Vector3.Project(Canvas2D._v, worldMtx, Canvas2D._m, v);
  48858. var s = this.scale;
  48859. group.x = Math.round(proj.x / s);
  48860. group.y = Math.round((rh - proj.y) / s);
  48861. }
  48862. };
  48863. /**
  48864. * Call this method change you want to have layout related data computed and up to date (layout area, primitive area, local/global transformation matrices)
  48865. */
  48866. Canvas2D.prototype.updateCanvasLayout = function (forceRecompute) {
  48867. this._updateCanvasState(forceRecompute);
  48868. };
  48869. Canvas2D.prototype._updateAdaptiveSizeWorldCanvas = function () {
  48870. if (this._globalTransformStep < 2) {
  48871. return;
  48872. }
  48873. var n = this.worldSpaceCanvasNode;
  48874. var bi = n.getBoundingInfo().boundingBox;
  48875. var v = bi.vectorsWorld;
  48876. var cam = this.scene.cameraToUseForPointers || this.scene.activeCamera;
  48877. cam.getViewMatrix().multiplyToRef(cam.getProjectionMatrix(), Canvas2D._m);
  48878. var vp = cam.viewport.toGlobal(this.engine.getRenderWidth(), this.engine.getRenderHeight());
  48879. var projPoints = new Array(4);
  48880. for (var i = 0; i < 4; i++) {
  48881. projPoints[i] = BABYLON.Vector3.Project(v[i], Canvas2D._mI, Canvas2D._m, vp);
  48882. }
  48883. var left = projPoints[3].subtract(projPoints[0]).length();
  48884. var top = projPoints[3].subtract(projPoints[1]).length();
  48885. var right = projPoints[1].subtract(projPoints[2]).length();
  48886. var bottom = projPoints[2].subtract(projPoints[0]).length();
  48887. var w = Math.round(Math.max(top, bottom));
  48888. var h = Math.round(Math.max(right, left));
  48889. var isW = w > h;
  48890. // Basically if it's under 256 we use 256, otherwise we take the biggest power of 2
  48891. var edge = Math.max(w, h);
  48892. if (edge < 256) {
  48893. edge = 256;
  48894. }
  48895. else {
  48896. edge = Math.pow(2, Math.ceil(Math.log(edge) / Math.log(2)));
  48897. }
  48898. // Clip values if needed
  48899. edge = Math.min(edge, this._maxAdaptiveWorldSpaceCanvasSize);
  48900. var newScale = edge / ((isW) ? this.size.width : this.size.height);
  48901. if (newScale !== this.scale) {
  48902. var scale = newScale;
  48903. // console.log(`New adaptive scale for Canvas ${this.id}, w: ${w}, h: ${h}, scale: ${scale}, edge: ${edge}, isW: ${isW}`);
  48904. this._setRenderingScale(scale);
  48905. }
  48906. };
  48907. Canvas2D.prototype._updateCanvasState = function (forceRecompute) {
  48908. // Check if the update has already been made for this render Frame
  48909. if (!forceRecompute && this.scene.getRenderId() === this._updateRenderId) {
  48910. return;
  48911. }
  48912. // Detect a change of rendering size
  48913. var renderingSizeChanged = false;
  48914. var newWidth = this.engine.getRenderWidth();
  48915. if (newWidth !== this._renderingSize.width) {
  48916. renderingSizeChanged = true;
  48917. }
  48918. this._renderingSize.width = newWidth;
  48919. var newHeight = this.engine.getRenderHeight();
  48920. if (newHeight !== this._renderingSize.height) {
  48921. renderingSizeChanged = true;
  48922. }
  48923. this._renderingSize.height = newHeight;
  48924. // If the canvas fit the rendering size and it changed, update
  48925. if (renderingSizeChanged && this._fitRenderingDevice) {
  48926. this._actualSize = this._renderingSize.clone();
  48927. this._size = this._renderingSize.clone();
  48928. if (this._background) {
  48929. this._background.size = this.size;
  48930. }
  48931. // Dirty the Layout at the Canvas level to recompute as the size changed
  48932. this._setLayoutDirty();
  48933. }
  48934. // If there's a design size, update the scale according to the renderingSize
  48935. if (this._designSize) {
  48936. var scale = void 0;
  48937. if (this._designUseHorizAxis) {
  48938. scale = this._renderingSize.width / this._designSize.width;
  48939. }
  48940. else {
  48941. scale = this._renderingSize.height / this._designSize.height;
  48942. }
  48943. this.size = this._designSize.clone();
  48944. this.scale = scale;
  48945. }
  48946. var context = new BABYLON.PrepareRender2DContext();
  48947. ++this._globalTransformProcessStep;
  48948. this.updateCachedStates(false);
  48949. this._prepareGroupRender(context);
  48950. this._updateRenderId = this.scene.getRenderId();
  48951. };
  48952. /**
  48953. * Method that renders the Canvas, you should not invoke
  48954. */
  48955. Canvas2D.prototype._render = function () {
  48956. this._initPerfMetrics();
  48957. this._updateCanvasState(false);
  48958. this._updateTrackedNodes();
  48959. // Nothing to do is the Canvas is not visible
  48960. if (this.isVisible === false) {
  48961. return;
  48962. }
  48963. if (!this._isScreenSpace) {
  48964. this._updateAdaptiveSizeWorldCanvas();
  48965. }
  48966. this._updateCanvasState(false);
  48967. if (this._primPointerInfo.canvasPointerPos) {
  48968. this._updateIntersectionList(this._primPointerInfo.canvasPointerPos, false, false);
  48969. this._updateOverStatus(); // TODO this._primPointerInfo may not be up to date!
  48970. }
  48971. this.engine.setState(false);
  48972. this._groupRender();
  48973. if (!this._isScreenSpace) {
  48974. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagWorldCacheChanged)) {
  48975. this.worldSpaceCacheChanged();
  48976. this._clearFlags(BABYLON.SmartPropertyPrim.flagWorldCacheChanged);
  48977. }
  48978. }
  48979. // If the canvas is cached at canvas level, we must manually render the sprite that will display its content
  48980. if (this._cachingStrategy === Canvas2D.CACHESTRATEGY_CANVAS && this._cachedCanvasGroup) {
  48981. this._cachedCanvasGroup._renderCachedCanvas();
  48982. }
  48983. this._fetchPerfMetrics();
  48984. this._updateProfileCanvas();
  48985. };
  48986. /**
  48987. * Internal method that allocate a cache for the given group.
  48988. * Caching is made using a collection of MapTexture where many groups have their bitmap cache stored inside.
  48989. * @param group The group to allocate the cache of.
  48990. * @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.
  48991. */
  48992. Canvas2D.prototype._allocateGroupCache = function (group, parent, minSize, useMipMap, anisotropicLevel) {
  48993. if (useMipMap === void 0) { useMipMap = false; }
  48994. if (anisotropicLevel === void 0) { anisotropicLevel = 1; }
  48995. var key = (useMipMap ? "MipMap" : "NoMipMap") + "_" + anisotropicLevel;
  48996. var rd = group._renderableData;
  48997. var noResizeScale = rd._noResizeOnScale;
  48998. var isCanvas = parent == null;
  48999. var scale;
  49000. if (noResizeScale) {
  49001. scale = isCanvas ? Canvas2D._unS : group.parent.actualScale;
  49002. }
  49003. else {
  49004. scale = group.actualScale;
  49005. }
  49006. // Determine size
  49007. var size = group.actualSize;
  49008. size = new BABYLON.Size(Math.ceil(size.width * scale.x), Math.ceil(size.height * scale.y));
  49009. if (minSize) {
  49010. size.width = Math.max(minSize.width, size.width);
  49011. size.height = Math.max(minSize.height, size.height);
  49012. }
  49013. var mapArray = this._groupCacheMaps.getOrAddWithFactory(key, function () { return new Array(); });
  49014. // Try to find a spot in one of the cached texture
  49015. var res = null;
  49016. var map;
  49017. for (var _i = 0, mapArray_1 = mapArray; _i < mapArray_1.length; _i++) {
  49018. var _map = mapArray_1[_i];
  49019. map = _map;
  49020. var node = map.allocateRect(size);
  49021. if (node) {
  49022. res = { node: node, texture: map };
  49023. break;
  49024. }
  49025. }
  49026. // Couldn't find a map that could fit the rect, create a new map for it
  49027. if (!res) {
  49028. var mapSize = new BABYLON.Size(Canvas2D._groupTextureCacheSize, Canvas2D._groupTextureCacheSize);
  49029. // Check if the predefined size would fit, other create a custom size using the nearest bigger power of 2
  49030. if (size.width > mapSize.width || size.height > mapSize.height) {
  49031. mapSize.width = Math.pow(2, Math.ceil(Math.log(size.width) / Math.log(2)));
  49032. mapSize.height = Math.pow(2, Math.ceil(Math.log(size.height) / Math.log(2)));
  49033. }
  49034. var id = "groupsMapChache" + this._mapCounter++ + "forCanvas" + this.id;
  49035. map = new BABYLON.MapTexture(id, this._scene, mapSize, useMipMap ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : BABYLON.Texture.BILINEAR_SAMPLINGMODE, useMipMap);
  49036. map.hasAlpha = true;
  49037. map.anisotropicFilteringLevel = 4;
  49038. mapArray.splice(0, 0, map);
  49039. var node = map.allocateRect(size);
  49040. res = { node: node, texture: map };
  49041. }
  49042. // Check if we have to create a Sprite that will display the content of the Canvas which is cached.
  49043. // Don't do it in case of the group being a worldspace canvas (because its texture is bound to a WorldSpaceCanvas node)
  49044. if (group !== this || this._isScreenSpace) {
  49045. var node = res.node;
  49046. // 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
  49047. var sprite = void 0;
  49048. if (this._cachingStrategy === Canvas2D.CACHESTRATEGY_CANVAS) {
  49049. this._cachedCanvasGroup = BABYLON.Group2D._createCachedCanvasGroup(this);
  49050. sprite = new BABYLON.Sprite2D(map, { parent: this._cachedCanvasGroup, id: "__cachedCanvasSprite__", spriteSize: node.contentSize, spriteLocation: node.pos });
  49051. sprite.zOrder = 1;
  49052. sprite.origin = BABYLON.Vector2.Zero();
  49053. }
  49054. else {
  49055. sprite = new BABYLON.Sprite2D(map, { parent: parent, id: "__cachedSpriteOfGroup__" + group.id, x: group.actualPosition.x, y: group.actualPosition.y, spriteSize: node.contentSize, spriteLocation: node.pos, dontInheritParentScale: true });
  49056. sprite.origin = group.origin.clone();
  49057. sprite.addExternalData("__cachedGroup__", group);
  49058. sprite.pointerEventObservable.add(function (e, s) {
  49059. if (group.pointerEventObservable !== null) {
  49060. group.pointerEventObservable.notifyObservers(e, s.mask);
  49061. }
  49062. });
  49063. res.sprite = sprite;
  49064. }
  49065. if (sprite && noResizeScale) {
  49066. var relScale = isCanvas ? group.actualScale : group.actualScale.divide(group.parent.actualScale);
  49067. sprite.scaleX = relScale.x;
  49068. sprite.scaleY = relScale.y;
  49069. }
  49070. }
  49071. return res;
  49072. };
  49073. /**
  49074. * Internal method used to register a Scene Node to track position for the given group
  49075. * Do not invoke this method, for internal purpose only.
  49076. * @param group the group to track its associated Scene Node
  49077. */
  49078. Canvas2D.prototype._registerTrackedNode = function (group) {
  49079. if (group._isFlagSet(BABYLON.SmartPropertyPrim.flagTrackedGroup)) {
  49080. return;
  49081. }
  49082. this._trackedGroups.push(group);
  49083. group._setFlags(BABYLON.SmartPropertyPrim.flagTrackedGroup);
  49084. };
  49085. /**
  49086. * Internal method used to unregister a tracked Scene Node
  49087. * Do not invoke this method, it's for internal purpose only.
  49088. * @param group the group to unregister its tracked Scene Node from.
  49089. */
  49090. Canvas2D.prototype._unregisterTrackedNode = function (group) {
  49091. if (!group._isFlagSet(BABYLON.SmartPropertyPrim.flagTrackedGroup)) {
  49092. return;
  49093. }
  49094. var i = this._trackedGroups.indexOf(group);
  49095. if (i !== -1) {
  49096. this._trackedGroups.splice(i, 1);
  49097. }
  49098. group._clearFlags(BABYLON.SmartPropertyPrim.flagTrackedGroup);
  49099. };
  49100. /**
  49101. * Get a Solid Color Brush instance matching the given color.
  49102. * @param color The color to retrieve
  49103. * @return A shared instance of the SolidColorBrush2D class that use the given color
  49104. */
  49105. Canvas2D.GetSolidColorBrush = function (color) {
  49106. return Canvas2D._solidColorBrushes.getOrAddWithFactory(color.toHexString(), function () { return new BABYLON.SolidColorBrush2D(color.clone(), true); });
  49107. };
  49108. /**
  49109. * Get a Solid Color Brush instance matching the given color expressed as a CSS formatted hexadecimal value.
  49110. * @param color The color to retrieve
  49111. * @return A shared instance of the SolidColorBrush2D class that uses the given color
  49112. */
  49113. Canvas2D.GetSolidColorBrushFromHex = function (hexValue) {
  49114. return Canvas2D._solidColorBrushes.getOrAddWithFactory(hexValue, function () { return new BABYLON.SolidColorBrush2D(BABYLON.Color4.FromHexString(hexValue), true); });
  49115. };
  49116. /**
  49117. * Get a Gradient Color Brush
  49118. * @param color1 starting color
  49119. * @param color2 engine color
  49120. * @param translation translation vector to apply. default is [0;0]
  49121. * @param rotation rotation in radian to apply to the brush, initial direction is top to bottom. rotation is counter clockwise. default is 0.
  49122. * @param scale scaling factor to apply. default is 1.
  49123. */
  49124. Canvas2D.GetGradientColorBrush = function (color1, color2, translation, rotation, scale) {
  49125. if (translation === void 0) { translation = BABYLON.Vector2.Zero(); }
  49126. if (rotation === void 0) { rotation = 0; }
  49127. if (scale === void 0) { scale = 1; }
  49128. return Canvas2D._gradientColorBrushes.getOrAddWithFactory(BABYLON.GradientColorBrush2D.BuildKey(color1, color2, translation, rotation, scale), function () { return new BABYLON.GradientColorBrush2D(color1, color2, translation, rotation, scale, true); });
  49129. };
  49130. /**
  49131. * Create a solid or gradient brush from a string value.
  49132. * @param brushString should be either
  49133. * - "solid: #RRGGBBAA" or "#RRGGBBAA"
  49134. * - "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.
  49135. */
  49136. Canvas2D.GetBrushFromString = function (brushString) {
  49137. // Note: yes, I hate/don't know RegEx.. Feel free to add your contribution to the cause!
  49138. brushString = brushString.trim();
  49139. var split = brushString.split(",");
  49140. // Solid, formatted as: "[solid:]#FF808080"
  49141. if (split.length === 1) {
  49142. var value = null;
  49143. if (brushString.indexOf("solid:") === 0) {
  49144. value = brushString.substr(6).trim();
  49145. }
  49146. else if (brushString.indexOf("#") === 0) {
  49147. value = brushString;
  49148. }
  49149. else {
  49150. return null;
  49151. }
  49152. return Canvas2D.GetSolidColorBrushFromHex(value);
  49153. }
  49154. else {
  49155. if (split[0].indexOf("gradient:") === 0) {
  49156. split[0] = split[0].substr(9).trim();
  49157. }
  49158. try {
  49159. var start = BABYLON.Color4.FromHexString(split[0].trim());
  49160. var end = BABYLON.Color4.FromHexString(split[1].trim());
  49161. var t = BABYLON.Vector2.Zero();
  49162. if (split.length > 2) {
  49163. var v = split[2].trim();
  49164. if (v.charAt(0) !== "[" || v.charAt(v.length - 1) !== "]") {
  49165. return null;
  49166. }
  49167. var sep = v.indexOf(":");
  49168. var x = parseFloat(v.substr(1, sep));
  49169. var y = parseFloat(v.substr(sep + 1, v.length - (sep + 1)));
  49170. t = new BABYLON.Vector2(x, y);
  49171. }
  49172. var r = 0;
  49173. if (split.length > 3) {
  49174. r = BABYLON.Tools.ToRadians(parseFloat(split[3].trim()));
  49175. }
  49176. var s = 1;
  49177. if (split.length > 4) {
  49178. s = parseFloat(split[4].trim());
  49179. }
  49180. return Canvas2D.GetGradientColorBrush(start, end, t, r, s);
  49181. }
  49182. catch (e) {
  49183. return null;
  49184. }
  49185. }
  49186. };
  49187. /**
  49188. * 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.
  49189. * This strategy doesn't allow primitives added directly as children of the Canvas.
  49190. * 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.
  49191. */
  49192. Canvas2D.CACHESTRATEGY_TOPLEVELGROUPS = 1;
  49193. /**
  49194. * In this strategy each group will have its own cache bitmap (except if a given group explicitly defines the DONTCACHEOVERRIDE or CACHEINPARENTGROUP behaviors).
  49195. * 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.
  49196. * When using this strategy, group instances can rely on the DONTCACHEOVERRIDE or CACHEINPARENTGROUP behaviors to minimize the amount of cached bitmaps.
  49197. * 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.
  49198. */
  49199. Canvas2D.CACHESTRATEGY_ALLGROUPS = 2;
  49200. /**
  49201. * 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).
  49202. */
  49203. Canvas2D.CACHESTRATEGY_CANVAS = 3;
  49204. /**
  49205. * This strategy is used to recompose/redraw the canvas entirely at each viewport render.
  49206. * 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).
  49207. * Note that you can't use this strategy for WorldSpace Canvas, they need at least a top level group caching.
  49208. */
  49209. Canvas2D.CACHESTRATEGY_DONTCACHE = 4;
  49210. Canvas2D._zMinDelta = 1 / (Math.pow(2, 24) - 1);
  49211. Canvas2D._interInfo = new BABYLON.IntersectInfo2D();
  49212. Canvas2D._v = BABYLON.Vector3.Zero(); // Must stay zero
  49213. Canvas2D._m = BABYLON.Matrix.Identity();
  49214. Canvas2D._mI = BABYLON.Matrix.Identity(); // Must stay identity
  49215. Canvas2D._unS = new BABYLON.Vector2(1, 1);
  49216. /**
  49217. * Define the default size used for both the width and height of a MapTexture to allocate.
  49218. * Note that some MapTexture might be bigger than this size if the first node to allocate is bigger in width or height
  49219. */
  49220. Canvas2D._groupTextureCacheSize = 1024;
  49221. Canvas2D._solidColorBrushes = new BABYLON.StringDictionary();
  49222. Canvas2D._gradientColorBrushes = new BABYLON.StringDictionary();
  49223. Canvas2D = __decorate([
  49224. BABYLON.className("Canvas2D")
  49225. ], Canvas2D);
  49226. return Canvas2D;
  49227. }(BABYLON.Group2D));
  49228. BABYLON.Canvas2D = Canvas2D;
  49229. var WorldSpaceCanvas2D = (function (_super) {
  49230. __extends(WorldSpaceCanvas2D, _super);
  49231. /**
  49232. * 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.
  49233. * 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.
  49234. * @param scene the Scene that owns the Canvas
  49235. * @param size the dimension of the Canvas in World Space
  49236. * @param settings a combination of settings, possible ones are
  49237. * - children: an array of direct children primitives
  49238. * - id: a text identifier, for information purpose only, default is null.
  49239. * - worldPosition the position of the Canvas in World Space, default is [0,0,0]
  49240. * - worldRotation the rotation of the Canvas in World Space, default is Quaternion.Identity()
  49241. * - sideOrientation: Unexpected behavior occur if the value is different from Mesh.DEFAULTSIDE right now, so please use this one, which is the default.
  49242. * - cachingStrategy Must be CACHESTRATEGY_CANVAS for now, which is the default.
  49243. * - 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).
  49244. * - isVisible: true if the canvas must be visible, false for hidden. Default is true.
  49245. * - backgroundRoundRadius: the round radius of the background, either backgroundFill or backgroundBorder must be specified.
  49246. * - 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.
  49247. * - 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.
  49248. * - backgroundBorderThickness: if a backgroundBorder is specified, its thickness can be set using this property
  49249. * - 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.
  49250. * - 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.
  49251. * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  49252. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  49253. * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  49254. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  49255. * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
  49256. */
  49257. function WorldSpaceCanvas2D(scene, size, settings) {
  49258. var _this = this;
  49259. BABYLON.Prim2DBase._isCanvasInit = true;
  49260. var s = settings;
  49261. s.isScreenSpace = false;
  49262. s.size = size.clone();
  49263. settings.cachingStrategy = (settings.cachingStrategy == null) ? Canvas2D.CACHESTRATEGY_CANVAS : settings.cachingStrategy;
  49264. if (settings.cachingStrategy !== Canvas2D.CACHESTRATEGY_CANVAS) {
  49265. throw new Error("Right now only the CACHESTRATEGY_CANVAS cache Strategy is supported for WorldSpace Canvas. More will come soon!");
  49266. }
  49267. _super.call(this, scene, settings);
  49268. BABYLON.Prim2DBase._isCanvasInit = false;
  49269. this._renderableData._useMipMap = true;
  49270. this._renderableData._anisotropicLevel = 8;
  49271. //if (cachingStrategy === Canvas2D.CACHESTRATEGY_DONTCACHE) {
  49272. // throw new Error("CACHESTRATEGY_DONTCACHE cache Strategy can't be used for WorldSpace Canvas");
  49273. //}
  49274. var createWorldSpaceNode = !settings || (settings.customWorldSpaceNode == null);
  49275. var id = settings ? settings.id || null : null;
  49276. // Set the max size of texture allowed for the adaptive render of the world space canvas cached bitmap
  49277. var capMaxTextSize = this.engine.getCaps().maxRenderTextureSize;
  49278. var defaultTextSize = (Math.min(capMaxTextSize, 1024)); // Default is 4K if allowed otherwise the max allowed
  49279. if (settings.maxAdaptiveCanvasSize == null) {
  49280. this._maxAdaptiveWorldSpaceCanvasSize = defaultTextSize;
  49281. }
  49282. else {
  49283. // We still clip the given value with the max allowed, the user may not be aware of these limitations
  49284. this._maxAdaptiveWorldSpaceCanvasSize = Math.min(settings.maxAdaptiveCanvasSize, capMaxTextSize);
  49285. }
  49286. if (createWorldSpaceNode) {
  49287. var plane = new BABYLON.WorldSpaceCanvas2DNode(id, scene, this);
  49288. var vertexData = BABYLON.VertexData.CreatePlane({
  49289. width: size.width,
  49290. height: size.height,
  49291. sideOrientation: settings && settings.sideOrientation || BABYLON.Mesh.DEFAULTSIDE
  49292. });
  49293. var mtl = new BABYLON.StandardMaterial(id + "_Material", scene);
  49294. this.applyCachedTexture(vertexData, mtl);
  49295. vertexData.applyToMesh(plane, true);
  49296. mtl.specularColor = new BABYLON.Color3(0, 0, 0);
  49297. mtl.disableLighting = true;
  49298. mtl.useAlphaFromDiffuseTexture = true;
  49299. plane.position = settings && settings.worldPosition || BABYLON.Vector3.Zero();
  49300. plane.rotationQuaternion = settings && settings.worldRotation || BABYLON.Quaternion.Identity();
  49301. plane.material = mtl;
  49302. this._worldSpaceNode = plane;
  49303. }
  49304. else {
  49305. this._worldSpaceNode = settings.customWorldSpaceNode;
  49306. this.applyCachedTexture(null, null);
  49307. }
  49308. this.propertyChanged.add(function (e, st) {
  49309. var mesh = _this._worldSpaceNode;
  49310. if (mesh) {
  49311. mesh.isVisible = _this.isVisible;
  49312. }
  49313. }, BABYLON.Prim2DBase.isVisibleProperty.flagId);
  49314. }
  49315. WorldSpaceCanvas2D = __decorate([
  49316. BABYLON.className("WorldSpaceCanvas2D")
  49317. ], WorldSpaceCanvas2D);
  49318. return WorldSpaceCanvas2D;
  49319. }(Canvas2D));
  49320. BABYLON.WorldSpaceCanvas2D = WorldSpaceCanvas2D;
  49321. var ScreenSpaceCanvas2D = (function (_super) {
  49322. __extends(ScreenSpaceCanvas2D, _super);
  49323. /**
  49324. * 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.
  49325. * 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.
  49326. * All caching strategies will be available.
  49327. * 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]
  49328. * @param scene the Scene that owns the Canvas
  49329. * @param settings a combination of settings, possible ones are
  49330. * - children: an array of direct children primitives
  49331. * - id: a text identifier, for information purpose only
  49332. * - x: the position along the x axis (horizontal), relative to the left edge of the viewport. you can alternatively use the position setting.
  49333. * - y: the position along the y axis (vertically), relative to the bottom edge of the viewport. you can alternatively use the position setting.
  49334. * - 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]
  49335. * - width: the width of the Canvas. you can alternatively use the size setting.
  49336. * - height: the height of the Canvas. you can alternatively use the size setting.
  49337. * - 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
  49338. * - designSize: if you want to set the canvas content based on fixed coordinates whatever the final canvas dimension would be, set this. For instance a designSize of 360*640 will give you the possibility to specify all the children element in this frame. The Canvas' true size will be the HTMLCanvas' size: for instance it could be 720*1280, then a uniform scale of 2 will be applied on the Canvas to keep the absolute coordinates working as expecting. If the ratios of the designSize and the true Canvas size are not the same, then the scale is computed following the designUseHorizAxis member by using either the size of the horizontal axis or the vertical axis.
  49339. * - designUseHorizAxis: you can set this member if you use designSize to specify which axis is priority to compute the scale when the ratio of the canvas' size is different from the designSize's one.
  49340. * - cachingStrategy: either CACHESTRATEGY_TOPLEVELGROUPS, CACHESTRATEGY_ALLGROUPS, CACHESTRATEGY_CANVAS, CACHESTRATEGY_DONTCACHE. Please refer to their respective documentation for more information. Default is Canvas2D.CACHESTRATEGY_DONTCACHE
  49341. * - 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.
  49342. * - isVisible: true if the canvas must be visible, false for hidden. Default is true.
  49343. * - backgroundRoundRadius: the round radius of the background, either backgroundFill or backgroundBorder must be specified.
  49344. * - 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.
  49345. * - 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.
  49346. * - backgroundBorderThickness: if a backgroundBorder is specified, its thickness can be set using this property
  49347. * - 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.
  49348. * - paddingTop: top padding, can be a number (will be pixels) or a string (see BABYLON.PrimitiveThickness.fromString)
  49349. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see BABYLON.PrimitiveThickness.fromString)
  49350. * - paddingRight: right padding, can be a number (will be pixels) or a string (see BABYLON.PrimitiveThickness.fromString)
  49351. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see BABYLON.PrimitiveThickness.fromString)
  49352. * - padding: top, left, right and bottom padding formatted as a single string (see BABYLON.PrimitiveThickness.fromString)
  49353. */
  49354. function ScreenSpaceCanvas2D(scene, settings) {
  49355. BABYLON.Prim2DBase._isCanvasInit = true;
  49356. _super.call(this, scene, settings);
  49357. }
  49358. ScreenSpaceCanvas2D = __decorate([
  49359. BABYLON.className("ScreenSpaceCanvas2D")
  49360. ], ScreenSpaceCanvas2D);
  49361. return ScreenSpaceCanvas2D;
  49362. }(Canvas2D));
  49363. BABYLON.ScreenSpaceCanvas2D = ScreenSpaceCanvas2D;
  49364. })(BABYLON || (BABYLON = {}));
  49365. var BABYLON;
  49366. (function (BABYLON) {
  49367. /**
  49368. * This is the class that is used to display a World Space Canvas into a 3D scene
  49369. */
  49370. var WorldSpaceCanvas2DNode = (function (_super) {
  49371. __extends(WorldSpaceCanvas2DNode, _super);
  49372. function WorldSpaceCanvas2DNode(name, scene, canvas) {
  49373. _super.call(this, name, scene);
  49374. this._canvas = canvas;
  49375. }
  49376. WorldSpaceCanvas2DNode.prototype.dispose = function () {
  49377. _super.prototype.dispose.call(this);
  49378. if (this._canvas) {
  49379. this._canvas.dispose();
  49380. this._canvas = null;
  49381. }
  49382. };
  49383. return WorldSpaceCanvas2DNode;
  49384. }(BABYLON.Mesh));
  49385. BABYLON.WorldSpaceCanvas2DNode = WorldSpaceCanvas2DNode;
  49386. })(BABYLON || (BABYLON = {}));
  49387. var BABYLON;
  49388. (function (BABYLON) {
  49389. var ShaderMaterial = (function (_super) {
  49390. __extends(ShaderMaterial, _super);
  49391. function ShaderMaterial(name, scene, shaderPath, options) {
  49392. _super.call(this, name, scene);
  49393. this._textures = {};
  49394. this._textureArrays = {};
  49395. this._floats = {};
  49396. this._floatsArrays = {};
  49397. this._colors3 = {};
  49398. this._colors4 = {};
  49399. this._vectors2 = {};
  49400. this._vectors3 = {};
  49401. this._vectors4 = {};
  49402. this._matrices = {};
  49403. this._matrices3x3 = {};
  49404. this._matrices2x2 = {};
  49405. this._cachedWorldViewMatrix = new BABYLON.Matrix();
  49406. this._shaderPath = shaderPath;
  49407. options.needAlphaBlending = options.needAlphaBlending || false;
  49408. options.needAlphaTesting = options.needAlphaTesting || false;
  49409. options.attributes = options.attributes || ["position", "normal", "uv"];
  49410. options.uniforms = options.uniforms || ["worldViewProjection"];
  49411. options.samplers = options.samplers || [];
  49412. options.defines = options.defines || [];
  49413. this._options = options;
  49414. }
  49415. ShaderMaterial.prototype.needAlphaBlending = function () {
  49416. return this._options.needAlphaBlending;
  49417. };
  49418. ShaderMaterial.prototype.needAlphaTesting = function () {
  49419. return this._options.needAlphaTesting;
  49420. };
  49421. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  49422. if (this._options.uniforms.indexOf(uniformName) === -1) {
  49423. this._options.uniforms.push(uniformName);
  49424. }
  49425. };
  49426. ShaderMaterial.prototype.setTexture = function (name, texture) {
  49427. if (this._options.samplers.indexOf(name) === -1) {
  49428. this._options.samplers.push(name);
  49429. }
  49430. this._textures[name] = texture;
  49431. return this;
  49432. };
  49433. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  49434. if (this._options.samplers.indexOf(name) === -1) {
  49435. this._options.samplers.push(name);
  49436. }
  49437. this._checkUniform(name);
  49438. this._textureArrays[name] = textures;
  49439. return this;
  49440. };
  49441. ShaderMaterial.prototype.setFloat = function (name, value) {
  49442. this._checkUniform(name);
  49443. this._floats[name] = value;
  49444. return this;
  49445. };
  49446. ShaderMaterial.prototype.setFloats = function (name, value) {
  49447. this._checkUniform(name);
  49448. this._floatsArrays[name] = value;
  49449. return this;
  49450. };
  49451. ShaderMaterial.prototype.setColor3 = function (name, value) {
  49452. this._checkUniform(name);
  49453. this._colors3[name] = value;
  49454. return this;
  49455. };
  49456. ShaderMaterial.prototype.setColor4 = function (name, value) {
  49457. this._checkUniform(name);
  49458. this._colors4[name] = value;
  49459. return this;
  49460. };
  49461. ShaderMaterial.prototype.setVector2 = function (name, value) {
  49462. this._checkUniform(name);
  49463. this._vectors2[name] = value;
  49464. return this;
  49465. };
  49466. ShaderMaterial.prototype.setVector3 = function (name, value) {
  49467. this._checkUniform(name);
  49468. this._vectors3[name] = value;
  49469. return this;
  49470. };
  49471. ShaderMaterial.prototype.setVector4 = function (name, value) {
  49472. this._checkUniform(name);
  49473. this._vectors4[name] = value;
  49474. return this;
  49475. };
  49476. ShaderMaterial.prototype.setMatrix = function (name, value) {
  49477. this._checkUniform(name);
  49478. this._matrices[name] = value;
  49479. return this;
  49480. };
  49481. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  49482. this._checkUniform(name);
  49483. this._matrices3x3[name] = value;
  49484. return this;
  49485. };
  49486. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  49487. this._checkUniform(name);
  49488. this._matrices2x2[name] = value;
  49489. return this;
  49490. };
  49491. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  49492. var scene = this.getScene();
  49493. var engine = scene.getEngine();
  49494. if (!this.checkReadyOnEveryCall) {
  49495. if (this._renderId === scene.getRenderId()) {
  49496. return true;
  49497. }
  49498. }
  49499. // Instances
  49500. var defines = [];
  49501. var fallbacks = new BABYLON.EffectFallbacks();
  49502. if (useInstances) {
  49503. defines.push("#define INSTANCES");
  49504. }
  49505. for (var index = 0; index < this._options.defines.length; index++) {
  49506. defines.push(this._options.defines[index]);
  49507. }
  49508. // Bones
  49509. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  49510. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  49511. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  49512. fallbacks.addCPUSkinningFallback(0, mesh);
  49513. }
  49514. // Alpha test
  49515. if (engine.getAlphaTesting()) {
  49516. defines.push("#define ALPHATEST");
  49517. }
  49518. var previousEffect = this._effect;
  49519. var join = defines.join("\n");
  49520. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, join, fallbacks, this.onCompiled, this.onError);
  49521. if (!this._effect.isReady()) {
  49522. return false;
  49523. }
  49524. if (previousEffect !== this._effect) {
  49525. scene.resetCachedMaterial();
  49526. }
  49527. this._renderId = scene.getRenderId();
  49528. return true;
  49529. };
  49530. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  49531. var scene = this.getScene();
  49532. if (this._options.uniforms.indexOf("world") !== -1) {
  49533. this._effect.setMatrix("world", world);
  49534. }
  49535. if (this._options.uniforms.indexOf("worldView") !== -1) {
  49536. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  49537. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  49538. }
  49539. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  49540. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  49541. }
  49542. };
  49543. ShaderMaterial.prototype.bind = function (world, mesh) {
  49544. // Std values
  49545. this.bindOnlyWorldMatrix(world);
  49546. if (this.getScene().getCachedMaterial() !== this) {
  49547. if (this._options.uniforms.indexOf("view") !== -1) {
  49548. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  49549. }
  49550. if (this._options.uniforms.indexOf("projection") !== -1) {
  49551. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  49552. }
  49553. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  49554. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  49555. }
  49556. // Bones
  49557. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  49558. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  49559. }
  49560. var name;
  49561. // Texture
  49562. for (name in this._textures) {
  49563. this._effect.setTexture(name, this._textures[name]);
  49564. }
  49565. // Texture arrays
  49566. for (name in this._textureArrays) {
  49567. this._effect.setTextureArray(name, this._textureArrays[name]);
  49568. }
  49569. // Float
  49570. for (name in this._floats) {
  49571. this._effect.setFloat(name, this._floats[name]);
  49572. }
  49573. // Float s
  49574. for (name in this._floatsArrays) {
  49575. this._effect.setArray(name, this._floatsArrays[name]);
  49576. }
  49577. // Color3
  49578. for (name in this._colors3) {
  49579. this._effect.setColor3(name, this._colors3[name]);
  49580. }
  49581. // Color4
  49582. for (name in this._colors4) {
  49583. var color = this._colors4[name];
  49584. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  49585. }
  49586. // Vector2
  49587. for (name in this._vectors2) {
  49588. this._effect.setVector2(name, this._vectors2[name]);
  49589. }
  49590. // Vector3
  49591. for (name in this._vectors3) {
  49592. this._effect.setVector3(name, this._vectors3[name]);
  49593. }
  49594. // Vector4
  49595. for (name in this._vectors4) {
  49596. this._effect.setVector4(name, this._vectors4[name]);
  49597. }
  49598. // Matrix
  49599. for (name in this._matrices) {
  49600. this._effect.setMatrix(name, this._matrices[name]);
  49601. }
  49602. // Matrix 3x3
  49603. for (name in this._matrices3x3) {
  49604. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  49605. }
  49606. // Matrix 2x2
  49607. for (name in this._matrices2x2) {
  49608. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  49609. }
  49610. }
  49611. _super.prototype.bind.call(this, world, mesh);
  49612. };
  49613. ShaderMaterial.prototype.clone = function (name) {
  49614. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  49615. return newShaderMaterial;
  49616. };
  49617. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  49618. if (forceDisposeTextures) {
  49619. var name;
  49620. for (name in this._textures) {
  49621. this._textures[name].dispose();
  49622. }
  49623. for (name in this._textureArrays) {
  49624. var array = this._textureArrays[name];
  49625. for (var index = 0; index < array.length; index++) {
  49626. array[index].dispose();
  49627. }
  49628. }
  49629. }
  49630. this._textures = {};
  49631. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  49632. };
  49633. ShaderMaterial.prototype.serialize = function () {
  49634. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  49635. serializationObject.customType = "BABYLON.ShaderMaterial";
  49636. serializationObject.options = this._options;
  49637. serializationObject.shaderPath = this._shaderPath;
  49638. var name;
  49639. // Texture
  49640. serializationObject.textures = {};
  49641. for (name in this._textures) {
  49642. serializationObject.textures[name] = this._textures[name].serialize();
  49643. }
  49644. // Texture arrays
  49645. serializationObject.textureArrays = {};
  49646. for (name in this._textureArrays) {
  49647. serializationObject.textureArrays[name] = [];
  49648. var array = this._textureArrays[name];
  49649. for (var index = 0; index < array.length; index++) {
  49650. serializationObject.textureArrays[name].push(array[index].serialize());
  49651. }
  49652. }
  49653. // Float
  49654. serializationObject.floats = {};
  49655. for (name in this._floats) {
  49656. serializationObject.floats[name] = this._floats[name];
  49657. }
  49658. // Float s
  49659. serializationObject.floatArrays = {};
  49660. for (name in this._floatsArrays) {
  49661. serializationObject.floatArrays[name] = this._floatsArrays[name];
  49662. }
  49663. // Color3
  49664. serializationObject.colors3 = {};
  49665. for (name in this._colors3) {
  49666. serializationObject.colors3[name] = this._colors3[name].asArray();
  49667. }
  49668. // Color4
  49669. serializationObject.colors4 = {};
  49670. for (name in this._colors4) {
  49671. serializationObject.colors4[name] = this._colors4[name].asArray();
  49672. }
  49673. // Vector2
  49674. serializationObject.vectors2 = {};
  49675. for (name in this._vectors2) {
  49676. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  49677. }
  49678. // Vector3
  49679. serializationObject.vectors3 = {};
  49680. for (name in this._vectors3) {
  49681. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  49682. }
  49683. // Vector4
  49684. serializationObject.vectors4 = {};
  49685. for (name in this._vectors4) {
  49686. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  49687. }
  49688. // Matrix
  49689. serializationObject.matrices = {};
  49690. for (name in this._matrices) {
  49691. serializationObject.matrices[name] = this._matrices[name].asArray();
  49692. }
  49693. // Matrix 3x3
  49694. serializationObject.matrices3x3 = {};
  49695. for (name in this._matrices3x3) {
  49696. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  49697. }
  49698. // Matrix 2x2
  49699. serializationObject.matrices2x2 = {};
  49700. for (name in this._matrices2x2) {
  49701. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  49702. }
  49703. return serializationObject;
  49704. };
  49705. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  49706. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  49707. var name;
  49708. // Texture
  49709. for (name in source.textures) {
  49710. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  49711. }
  49712. // Texture arrays
  49713. for (name in source.textureArrays) {
  49714. var array = source.textureArrays[name];
  49715. var textureArray = new Array();
  49716. for (var index = 0; index < array.length; index++) {
  49717. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  49718. }
  49719. material.setTextureArray(name, textureArray);
  49720. }
  49721. // Float
  49722. for (name in source.floats) {
  49723. material.setFloat(name, source.floats[name]);
  49724. }
  49725. // Float s
  49726. for (name in source.floatsArrays) {
  49727. material.setFloats(name, source.floatsArrays[name]);
  49728. }
  49729. // Color3
  49730. for (name in source.colors3) {
  49731. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  49732. }
  49733. // Color4
  49734. for (name in source.colors4) {
  49735. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  49736. }
  49737. // Vector2
  49738. for (name in source.vectors2) {
  49739. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  49740. }
  49741. // Vector3
  49742. for (name in source.vectors3) {
  49743. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  49744. }
  49745. // Vector4
  49746. for (name in source.vectors4) {
  49747. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  49748. }
  49749. // Matrix
  49750. for (name in source.matrices) {
  49751. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  49752. }
  49753. // Matrix 3x3
  49754. for (name in source.matrices3x3) {
  49755. material.setMatrix3x3(name, source.matrices3x3[name]);
  49756. }
  49757. // Matrix 2x2
  49758. for (name in source.matrices2x2) {
  49759. material.setMatrix2x2(name, source.matrices2x2[name]);
  49760. }
  49761. return material;
  49762. };
  49763. return ShaderMaterial;
  49764. }(BABYLON.Material));
  49765. BABYLON.ShaderMaterial = ShaderMaterial;
  49766. })(BABYLON || (BABYLON = {}));
  49767. var BABYLON;
  49768. (function (BABYLON) {
  49769. var Internals;
  49770. (function (Internals) {
  49771. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  49772. // All values and structures referenced from:
  49773. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  49774. var DDS_MAGIC = 0x20534444;
  49775. 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;
  49776. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  49777. 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;
  49778. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  49779. function FourCCToInt32(value) {
  49780. return value.charCodeAt(0) +
  49781. (value.charCodeAt(1) << 8) +
  49782. (value.charCodeAt(2) << 16) +
  49783. (value.charCodeAt(3) << 24);
  49784. }
  49785. function Int32ToFourCC(value) {
  49786. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  49787. }
  49788. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  49789. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  49790. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  49791. var headerLengthInt = 31; // The header length in 32 bit ints
  49792. // Offsets into the header array
  49793. var off_magic = 0;
  49794. var off_size = 1;
  49795. var off_flags = 2;
  49796. var off_height = 3;
  49797. var off_width = 4;
  49798. var off_mipmapCount = 7;
  49799. var off_pfFlags = 20;
  49800. var off_pfFourCC = 21;
  49801. var off_RGBbpp = 22;
  49802. var off_RMask = 23;
  49803. var off_GMask = 24;
  49804. var off_BMask = 25;
  49805. var off_AMask = 26;
  49806. var off_caps1 = 27;
  49807. var off_caps2 = 28;
  49808. ;
  49809. var DDSTools = (function () {
  49810. function DDSTools() {
  49811. }
  49812. DDSTools.GetDDSInfo = function (arrayBuffer) {
  49813. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  49814. var mipmapCount = 1;
  49815. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  49816. mipmapCount = Math.max(1, header[off_mipmapCount]);
  49817. }
  49818. return {
  49819. width: header[off_width],
  49820. height: header[off_height],
  49821. mipmapCount: mipmapCount,
  49822. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  49823. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  49824. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  49825. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  49826. };
  49827. };
  49828. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  49829. var byteArray = new Uint8Array(dataLength);
  49830. var srcData = new Uint8Array(arrayBuffer);
  49831. var index = 0;
  49832. for (var y = height - 1; y >= 0; y--) {
  49833. for (var x = 0; x < width; x++) {
  49834. var srcPos = dataOffset + (x + y * width) * 4;
  49835. byteArray[index + 2] = srcData[srcPos];
  49836. byteArray[index + 1] = srcData[srcPos + 1];
  49837. byteArray[index] = srcData[srcPos + 2];
  49838. byteArray[index + 3] = srcData[srcPos + 3];
  49839. index += 4;
  49840. }
  49841. }
  49842. return byteArray;
  49843. };
  49844. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  49845. var byteArray = new Uint8Array(dataLength);
  49846. var srcData = new Uint8Array(arrayBuffer);
  49847. var index = 0;
  49848. for (var y = height - 1; y >= 0; y--) {
  49849. for (var x = 0; x < width; x++) {
  49850. var srcPos = dataOffset + (x + y * width) * 3;
  49851. byteArray[index + 2] = srcData[srcPos];
  49852. byteArray[index + 1] = srcData[srcPos + 1];
  49853. byteArray[index] = srcData[srcPos + 2];
  49854. index += 3;
  49855. }
  49856. }
  49857. return byteArray;
  49858. };
  49859. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  49860. var byteArray = new Uint8Array(dataLength);
  49861. var srcData = new Uint8Array(arrayBuffer);
  49862. var index = 0;
  49863. for (var y = height - 1; y >= 0; y--) {
  49864. for (var x = 0; x < width; x++) {
  49865. var srcPos = dataOffset + (x + y * width);
  49866. byteArray[index] = srcData[srcPos];
  49867. index++;
  49868. }
  49869. }
  49870. return byteArray;
  49871. };
  49872. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  49873. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  49874. if (header[off_magic] != DDS_MAGIC) {
  49875. BABYLON.Tools.Error("Invalid magic number in DDS header");
  49876. return;
  49877. }
  49878. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  49879. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  49880. return;
  49881. }
  49882. if (info.isFourCC) {
  49883. fourCC = header[off_pfFourCC];
  49884. switch (fourCC) {
  49885. case FOURCC_DXT1:
  49886. blockBytes = 8;
  49887. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  49888. break;
  49889. case FOURCC_DXT3:
  49890. blockBytes = 16;
  49891. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  49892. break;
  49893. case FOURCC_DXT5:
  49894. blockBytes = 16;
  49895. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  49896. break;
  49897. default:
  49898. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  49899. return;
  49900. }
  49901. }
  49902. mipmapCount = 1;
  49903. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  49904. mipmapCount = Math.max(1, header[off_mipmapCount]);
  49905. }
  49906. var bpp = header[off_RGBbpp];
  49907. for (var face = 0; face < faces; face++) {
  49908. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  49909. width = header[off_width];
  49910. height = header[off_height];
  49911. dataOffset = header[off_size] + 4;
  49912. for (i = 0; i < mipmapCount; ++i) {
  49913. if (info.isRGB) {
  49914. if (bpp === 24) {
  49915. dataLength = width * height * 3;
  49916. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  49917. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  49918. }
  49919. else {
  49920. dataLength = width * height * 4;
  49921. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  49922. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  49923. }
  49924. }
  49925. else if (info.isLuminance) {
  49926. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  49927. var unpaddedRowSize = width;
  49928. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  49929. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  49930. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  49931. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  49932. }
  49933. else {
  49934. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  49935. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  49936. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  49937. }
  49938. dataOffset += dataLength;
  49939. width *= 0.5;
  49940. height *= 0.5;
  49941. width = Math.max(1.0, width);
  49942. height = Math.max(1.0, height);
  49943. }
  49944. }
  49945. };
  49946. return DDSTools;
  49947. }());
  49948. Internals.DDSTools = DDSTools;
  49949. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  49950. })(BABYLON || (BABYLON = {}));
  49951. var BABYLON;
  49952. (function (BABYLON) {
  49953. var CannonJSPlugin = (function () {
  49954. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  49955. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  49956. if (iterations === void 0) { iterations = 10; }
  49957. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  49958. this.name = "CannonJSPlugin";
  49959. this._physicsMaterials = [];
  49960. this._fixedTimeStep = 1 / 60;
  49961. //See https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  49962. this._currentCollisionGroup = 2;
  49963. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  49964. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  49965. this._tmpPosition = BABYLON.Vector3.Zero();
  49966. this._tmpQuaternion = new BABYLON.Quaternion();
  49967. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  49968. this._tmpDeltaRotation = new BABYLON.Quaternion();
  49969. this._tmpUnityRotation = new BABYLON.Quaternion();
  49970. if (!this.isSupported()) {
  49971. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  49972. return;
  49973. }
  49974. this.world = new CANNON.World();
  49975. this.world.broadphase = new CANNON.NaiveBroadphase();
  49976. this.world.solver.iterations = iterations;
  49977. }
  49978. CannonJSPlugin.prototype.setGravity = function (gravity) {
  49979. this.world.gravity.copy(gravity);
  49980. };
  49981. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  49982. this._fixedTimeStep = timeStep;
  49983. };
  49984. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  49985. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta * 1000 : 0, 3);
  49986. };
  49987. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  49988. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  49989. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  49990. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  49991. };
  49992. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  49993. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  49994. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  49995. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  49996. };
  49997. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  49998. //parent-child relationship. Does this impostor has a parent impostor?
  49999. if (impostor.parent) {
  50000. if (impostor.physicsBody) {
  50001. this.removePhysicsBody(impostor);
  50002. //TODO is that needed?
  50003. impostor.forceUpdate();
  50004. }
  50005. return;
  50006. }
  50007. //should a new body be created for this impostor?
  50008. if (impostor.isBodyInitRequired()) {
  50009. var shape = this._createShape(impostor);
  50010. //unregister events, if body is being changed
  50011. var oldBody = impostor.physicsBody;
  50012. if (oldBody) {
  50013. this.removePhysicsBody(impostor);
  50014. }
  50015. //create the body and material
  50016. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  50017. var bodyCreationObject = {
  50018. mass: impostor.getParam("mass"),
  50019. material: material
  50020. };
  50021. // A simple extend, in case native options were used.
  50022. var nativeOptions = impostor.getParam("nativeOptions");
  50023. for (var key in nativeOptions) {
  50024. if (nativeOptions.hasOwnProperty(key)) {
  50025. bodyCreationObject[key] = nativeOptions[key];
  50026. }
  50027. }
  50028. impostor.physicsBody = new CANNON.Body(bodyCreationObject);
  50029. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  50030. this.world.addEventListener("preStep", impostor.beforeStep);
  50031. this.world.addEventListener("postStep", impostor.afterStep);
  50032. impostor.physicsBody.addShape(shape);
  50033. this.world.add(impostor.physicsBody);
  50034. //try to keep the body moving in the right direction by taking old properties.
  50035. //Should be tested!
  50036. if (oldBody) {
  50037. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  50038. impostor.physicsBody[param].copy(oldBody[param]);
  50039. });
  50040. }
  50041. this._processChildMeshes(impostor);
  50042. }
  50043. //now update the body's transformation
  50044. this._updatePhysicsBodyTransformation(impostor);
  50045. };
  50046. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  50047. var _this = this;
  50048. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes() : [];
  50049. if (meshChildren.length) {
  50050. var processMesh = function (localPosition, mesh) {
  50051. var childImpostor = mesh.getPhysicsImpostor();
  50052. if (childImpostor) {
  50053. var parent = childImpostor.parent;
  50054. if (parent !== mainImpostor) {
  50055. var localPosition = mesh.position;
  50056. if (childImpostor.physicsBody) {
  50057. _this.removePhysicsBody(childImpostor);
  50058. childImpostor.physicsBody = null;
  50059. }
  50060. childImpostor.parent = mainImpostor;
  50061. childImpostor.resetUpdateFlags();
  50062. mainImpostor.physicsBody.addShape(_this._createShape(childImpostor), new CANNON.Vec3(localPosition.x, localPosition.y, localPosition.z));
  50063. //Add the mass of the children.
  50064. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  50065. }
  50066. }
  50067. mesh.getChildMeshes().forEach(processMesh.bind(_this, mesh.position));
  50068. };
  50069. meshChildren.forEach(processMesh.bind(this, BABYLON.Vector3.Zero()));
  50070. }
  50071. };
  50072. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  50073. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  50074. this.world.removeEventListener("preStep", impostor.beforeStep);
  50075. this.world.removeEventListener("postStep", impostor.afterStep);
  50076. this.world.remove(impostor.physicsBody);
  50077. };
  50078. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  50079. var mainBody = impostorJoint.mainImpostor.physicsBody;
  50080. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  50081. if (!mainBody || !connectedBody) {
  50082. return;
  50083. }
  50084. var constraint;
  50085. var jointData = impostorJoint.joint.jointData;
  50086. //TODO - https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  50087. var constraintData = {
  50088. pivotA: jointData.mainPivot ? new CANNON.Vec3().copy(jointData.mainPivot) : null,
  50089. pivotB: jointData.connectedPivot ? new CANNON.Vec3().copy(jointData.connectedPivot) : null,
  50090. axisA: jointData.mainAxis ? new CANNON.Vec3().copy(jointData.mainAxis) : null,
  50091. axisB: jointData.connectedAxis ? new CANNON.Vec3().copy(jointData.connectedAxis) : null,
  50092. maxForce: jointData.nativeParams.maxForce,
  50093. collideConnected: !!jointData.collision
  50094. };
  50095. //Not needed, Cannon has a collideConnected flag
  50096. /*if (!jointData.collision) {
  50097. //add 1st body to a collision group of its own, if it is not in 1
  50098. if (mainBody.collisionFilterGroup === 1) {
  50099. mainBody.collisionFilterGroup = this._currentCollisionGroup;
  50100. this._currentCollisionGroup <<= 1;
  50101. }
  50102. if (connectedBody.collisionFilterGroup === 1) {
  50103. connectedBody.collisionFilterGroup = this._currentCollisionGroup;
  50104. this._currentCollisionGroup <<= 1;
  50105. }
  50106. //add their mask to the collisionFilterMask of each other:
  50107. connectedBody.collisionFilterMask = connectedBody.collisionFilterMask | ~mainBody.collisionFilterGroup;
  50108. mainBody.collisionFilterMask = mainBody.collisionFilterMask | ~connectedBody.collisionFilterGroup;
  50109. }*/
  50110. switch (impostorJoint.joint.type) {
  50111. case BABYLON.PhysicsJoint.HingeJoint:
  50112. case BABYLON.PhysicsJoint.Hinge2Joint:
  50113. constraint = new CANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  50114. break;
  50115. case BABYLON.PhysicsJoint.DistanceJoint:
  50116. constraint = new CANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  50117. break;
  50118. case BABYLON.PhysicsJoint.SpringJoint:
  50119. var springData = jointData;
  50120. constraint = new CANNON.Spring(mainBody, connectedBody, {
  50121. restLength: springData.length,
  50122. stiffness: springData.stiffness,
  50123. damping: springData.damping,
  50124. localAnchorA: constraintData.pivotA,
  50125. localAnchorB: constraintData.pivotB
  50126. });
  50127. break;
  50128. case BABYLON.PhysicsJoint.LockJoint:
  50129. constraint = new CANNON.LockConstraint(mainBody, connectedBody, constraintData);
  50130. break;
  50131. case BABYLON.PhysicsJoint.PointToPointJoint:
  50132. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  50133. default:
  50134. constraint = new CANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  50135. break;
  50136. }
  50137. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  50138. constraint.collideConnected = !!jointData.collision;
  50139. impostorJoint.joint.physicsJoint = constraint;
  50140. //don't add spring as constraint, as it is not one.
  50141. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  50142. this.world.addConstraint(constraint);
  50143. }
  50144. else {
  50145. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  50146. constraint.applyForce();
  50147. });
  50148. }
  50149. };
  50150. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  50151. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  50152. };
  50153. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  50154. var index;
  50155. var mat;
  50156. for (index = 0; index < this._physicsMaterials.length; index++) {
  50157. mat = this._physicsMaterials[index];
  50158. if (mat.friction === friction && mat.restitution === restitution) {
  50159. return mat;
  50160. }
  50161. }
  50162. var currentMat = new CANNON.Material(name);
  50163. currentMat.friction = friction;
  50164. currentMat.restitution = restitution;
  50165. this._physicsMaterials.push(currentMat);
  50166. return currentMat;
  50167. };
  50168. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  50169. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  50170. };
  50171. CannonJSPlugin.prototype._createShape = function (impostor) {
  50172. var object = impostor.object;
  50173. var returnValue;
  50174. var extendSize = impostor.getObjectExtendSize();
  50175. switch (impostor.type) {
  50176. case BABYLON.PhysicsEngine.SphereImpostor:
  50177. var radiusX = extendSize.x;
  50178. var radiusY = extendSize.y;
  50179. var radiusZ = extendSize.z;
  50180. returnValue = new CANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  50181. break;
  50182. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  50183. case BABYLON.PhysicsImpostor.CylinderImpostor:
  50184. returnValue = new CANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  50185. break;
  50186. case BABYLON.PhysicsImpostor.BoxImpostor:
  50187. var box = extendSize.scale(0.5);
  50188. returnValue = new CANNON.Box(new CANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  50189. break;
  50190. case BABYLON.PhysicsImpostor.PlaneImpostor:
  50191. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  50192. returnValue = new CANNON.Plane();
  50193. break;
  50194. case BABYLON.PhysicsImpostor.MeshImpostor:
  50195. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  50196. var rawFaces = object.getIndices ? object.getIndices() : [];
  50197. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  50198. returnValue = new CANNON.Trimesh(rawVerts, rawFaces);
  50199. break;
  50200. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  50201. returnValue = this._createHeightmap(object);
  50202. break;
  50203. case BABYLON.PhysicsImpostor.ParticleImpostor:
  50204. returnValue = new CANNON.Particle();
  50205. break;
  50206. }
  50207. return returnValue;
  50208. };
  50209. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  50210. var pos = object.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  50211. var matrix = [];
  50212. //For now pointDepth will not be used and will be automatically calculated.
  50213. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  50214. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  50215. var dim = Math.min(object.getBoundingInfo().boundingBox.extendSize.x, object.getBoundingInfo().boundingBox.extendSize.z);
  50216. var elementSize = dim * 2 / arraySize;
  50217. var minY = object.getBoundingInfo().boundingBox.extendSize.y;
  50218. for (var i = 0; i < pos.length; i = i + 3) {
  50219. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  50220. var z = Math.round(((pos[i + 2]) / elementSize - arraySize / 2) * -1);
  50221. var y = pos[i + 1] + minY;
  50222. if (!matrix[x]) {
  50223. matrix[x] = [];
  50224. }
  50225. if (!matrix[x][z]) {
  50226. matrix[x][z] = y;
  50227. }
  50228. matrix[x][z] = Math.max(y, matrix[x][z]);
  50229. }
  50230. for (var x = 0; x <= arraySize; ++x) {
  50231. if (!matrix[x]) {
  50232. var loc = 1;
  50233. while (!matrix[(x + loc) % arraySize]) {
  50234. loc++;
  50235. }
  50236. matrix[x] = matrix[(x + loc) % arraySize].slice();
  50237. }
  50238. for (var z = 0; z <= arraySize; ++z) {
  50239. if (!matrix[x][z]) {
  50240. var loc = 1;
  50241. var newValue;
  50242. while (newValue === undefined) {
  50243. newValue = matrix[x][(z + loc++) % arraySize];
  50244. }
  50245. matrix[x][z] = newValue;
  50246. }
  50247. }
  50248. }
  50249. var shape = new CANNON.Heightfield(matrix, {
  50250. elementSize: elementSize
  50251. });
  50252. //For future reference, needed for body transformation
  50253. shape.minY = minY;
  50254. return shape;
  50255. };
  50256. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  50257. var object = impostor.object;
  50258. //make sure it is updated...
  50259. object.computeWorldMatrix && object.computeWorldMatrix(true);
  50260. // The delta between the mesh position and the mesh bounding box center
  50261. var center = impostor.getObjectCenter();
  50262. var extendSize = impostor.getObjectExtendSize();
  50263. this._tmpDeltaPosition.copyFrom(object.position.subtract(center));
  50264. this._tmpPosition.copyFrom(center);
  50265. var quaternion = object.rotationQuaternion;
  50266. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  50267. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  50268. //-90 DEG in X, precalculated
  50269. quaternion = quaternion.multiply(this._minus90X);
  50270. //Invert! (Precalculated, 90 deg in X)
  50271. //No need to clone. this will never change.
  50272. impostor.setDeltaRotation(this._plus90X);
  50273. }
  50274. //If it is a heightfield, if should be centered.
  50275. if (impostor.type === BABYLON.PhysicsEngine.HeightmapImpostor) {
  50276. var mesh = object;
  50277. //calculate the correct body position:
  50278. var rotationQuaternion = mesh.rotationQuaternion;
  50279. mesh.rotationQuaternion = this._tmpUnityRotation;
  50280. mesh.computeWorldMatrix(true);
  50281. //get original center with no rotation
  50282. var c = center.clone();
  50283. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  50284. //rotation is back
  50285. mesh.rotationQuaternion = rotationQuaternion;
  50286. //calculate the new center using a pivot (since Cannon.js doesn't center height maps)
  50287. var p = BABYLON.Matrix.Translation(mesh.getBoundingInfo().boundingBox.extendSize.x, 0, -mesh.getBoundingInfo().boundingBox.extendSize.z);
  50288. mesh.setPivotMatrix(p);
  50289. mesh.computeWorldMatrix(true);
  50290. //calculate the translation
  50291. var translation = mesh.getBoundingInfo().boundingBox.center.subtract(center).subtract(mesh.position).negate();
  50292. this._tmpPosition.copyFromFloats(translation.x, translation.y - mesh.getBoundingInfo().boundingBox.extendSize.y, translation.z);
  50293. //add it inverted to the delta
  50294. this._tmpDeltaPosition.copyFrom(mesh.getBoundingInfo().boundingBox.center.subtract(c));
  50295. this._tmpDeltaPosition.y += mesh.getBoundingInfo().boundingBox.extendSize.y;
  50296. mesh.setPivotMatrix(oldPivot);
  50297. mesh.computeWorldMatrix(true);
  50298. }
  50299. else if (impostor.type === BABYLON.PhysicsEngine.MeshImpostor) {
  50300. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  50301. this._tmpPosition.copyFrom(object.position);
  50302. }
  50303. impostor.setDeltaPosition(this._tmpDeltaPosition);
  50304. //Now update the impostor object
  50305. impostor.physicsBody.position.copy(this._tmpPosition);
  50306. impostor.physicsBody.quaternion.copy(quaternion);
  50307. };
  50308. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  50309. impostor.object.position.copyFrom(impostor.physicsBody.position);
  50310. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  50311. };
  50312. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  50313. impostor.physicsBody.position.copy(newPosition);
  50314. impostor.physicsBody.quaternion.copy(newRotation);
  50315. };
  50316. CannonJSPlugin.prototype.isSupported = function () {
  50317. return window.CANNON !== undefined;
  50318. };
  50319. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  50320. impostor.physicsBody.velocity.copy(velocity);
  50321. };
  50322. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  50323. impostor.physicsBody.angularVelocity.copy(velocity);
  50324. };
  50325. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  50326. var v = impostor.physicsBody.velocity;
  50327. if (!v)
  50328. return null;
  50329. return new BABYLON.Vector3(v.x, v.y, v.z);
  50330. };
  50331. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  50332. var v = impostor.physicsBody.angularVelocity;
  50333. if (!v)
  50334. return null;
  50335. return new BABYLON.Vector3(v.x, v.y, v.z);
  50336. };
  50337. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  50338. impostor.physicsBody.mass = mass;
  50339. impostor.physicsBody.updateMassProperties();
  50340. };
  50341. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  50342. impostor.physicsBody.sleep();
  50343. };
  50344. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  50345. impostor.physicsBody.wakeUp();
  50346. };
  50347. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  50348. joint.physicsJoint.distance = maxDistance;
  50349. };
  50350. CannonJSPlugin.prototype.enableMotor = function (joint, motorIndex) {
  50351. if (!motorIndex) {
  50352. joint.physicsJoint.enableMotor();
  50353. }
  50354. };
  50355. CannonJSPlugin.prototype.disableMotor = function (joint, motorIndex) {
  50356. if (!motorIndex) {
  50357. joint.physicsJoint.disableMotor();
  50358. }
  50359. };
  50360. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  50361. if (!motorIndex) {
  50362. joint.physicsJoint.enableMotor();
  50363. joint.physicsJoint.setMotorSpeed(speed);
  50364. if (maxForce) {
  50365. this.setLimit(joint, maxForce);
  50366. }
  50367. }
  50368. };
  50369. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  50370. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  50371. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  50372. };
  50373. CannonJSPlugin.prototype.dispose = function () {
  50374. //nothing to do, actually.
  50375. };
  50376. return CannonJSPlugin;
  50377. }());
  50378. BABYLON.CannonJSPlugin = CannonJSPlugin;
  50379. })(BABYLON || (BABYLON = {}));
  50380. var BABYLON;
  50381. (function (BABYLON) {
  50382. var OimoJSPlugin = (function () {
  50383. function OimoJSPlugin(iterations) {
  50384. this.name = "OimoJSPlugin";
  50385. this._tmpImpostorsArray = [];
  50386. this._tmpPositionVector = BABYLON.Vector3.Zero();
  50387. this.world = new OIMO.World(1 / 60, 2, iterations, true);
  50388. this.world.clear();
  50389. //making sure no stats are calculated
  50390. this.world.isNoStat = true;
  50391. }
  50392. OimoJSPlugin.prototype.setGravity = function (gravity) {
  50393. this.world.gravity.copy(gravity);
  50394. };
  50395. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  50396. this.world.timeStep = timeStep;
  50397. };
  50398. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  50399. var _this = this;
  50400. impostors.forEach(function (impostor) {
  50401. impostor.beforeStep();
  50402. });
  50403. this.world.step();
  50404. impostors.forEach(function (impostor) {
  50405. impostor.afterStep();
  50406. //update the ordered impostors array
  50407. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  50408. });
  50409. //check for collisions
  50410. var contact = this.world.contacts;
  50411. while (contact !== null) {
  50412. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  50413. contact = contact.next;
  50414. continue;
  50415. }
  50416. //is this body colliding with any other? get the impostor
  50417. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  50418. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  50419. if (!mainImpostor || !collidingImpostor) {
  50420. contact = contact.next;
  50421. continue;
  50422. }
  50423. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  50424. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  50425. contact = contact.next;
  50426. }
  50427. };
  50428. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  50429. var mass = impostor.physicsBody.massInfo.mass;
  50430. impostor.physicsBody.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  50431. };
  50432. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  50433. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  50434. this.applyImpulse(impostor, force, contactPoint);
  50435. };
  50436. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  50437. var _this = this;
  50438. //parent-child relationship. Does this impostor has a parent impostor?
  50439. if (impostor.parent) {
  50440. if (impostor.physicsBody) {
  50441. this.removePhysicsBody(impostor);
  50442. //TODO is that needed?
  50443. impostor.forceUpdate();
  50444. }
  50445. return;
  50446. }
  50447. if (impostor.isBodyInitRequired()) {
  50448. var bodyConfig = {
  50449. name: impostor.uniqueId,
  50450. //Oimo must have mass, also for static objects.
  50451. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  50452. size: [],
  50453. type: [],
  50454. pos: [],
  50455. rot: [],
  50456. move: impostor.getParam("mass") !== 0,
  50457. //Supporting older versions of Oimo
  50458. world: this.world
  50459. };
  50460. var impostors = [impostor];
  50461. function addToArray(parent) {
  50462. if (!parent.getChildMeshes)
  50463. return;
  50464. parent.getChildMeshes().forEach(function (m) {
  50465. if (m.physicsImpostor) {
  50466. impostors.push(m.physicsImpostor);
  50467. m.physicsImpostor._init();
  50468. }
  50469. });
  50470. }
  50471. addToArray(impostor.object);
  50472. function checkWithEpsilon(value) {
  50473. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  50474. }
  50475. impostors.forEach(function (i) {
  50476. //get the correct bounding box
  50477. var oldQuaternion = i.object.rotationQuaternion;
  50478. var rot = new OIMO.Euler().setFromQuaternion({
  50479. x: impostor.object.rotationQuaternion.x,
  50480. y: impostor.object.rotationQuaternion.y,
  50481. z: impostor.object.rotationQuaternion.z,
  50482. s: impostor.object.rotationQuaternion.w
  50483. });
  50484. var extendSize = i.getObjectExtendSize();
  50485. if (i === impostor) {
  50486. var center = impostor.getObjectCenter();
  50487. impostor.object.position.subtractToRef(center, _this._tmpPositionVector);
  50488. //Can also use Array.prototype.push.apply
  50489. bodyConfig.pos.push(center.x);
  50490. bodyConfig.pos.push(center.y);
  50491. bodyConfig.pos.push(center.z);
  50492. //tmp solution
  50493. bodyConfig.rot.push(rot.x / (OIMO.degtorad || OIMO.TO_RAD));
  50494. bodyConfig.rot.push(rot.y / (OIMO.degtorad || OIMO.TO_RAD));
  50495. bodyConfig.rot.push(rot.z / (OIMO.degtorad || OIMO.TO_RAD));
  50496. }
  50497. else {
  50498. bodyConfig.pos.push(i.object.position.x);
  50499. bodyConfig.pos.push(i.object.position.y);
  50500. bodyConfig.pos.push(i.object.position.z);
  50501. //tmp solution until https://github.com/lo-th/Oimo.js/pull/37 is merged
  50502. bodyConfig.rot.push(0);
  50503. bodyConfig.rot.push(0);
  50504. bodyConfig.rot.push(0);
  50505. }
  50506. // register mesh
  50507. switch (i.type) {
  50508. case BABYLON.PhysicsImpostor.ParticleImpostor:
  50509. BABYLON.Tools.Warn("No Particle support in Oimo.js. using SphereImpostor instead");
  50510. case BABYLON.PhysicsImpostor.SphereImpostor:
  50511. var radiusX = extendSize.x;
  50512. var radiusY = extendSize.y;
  50513. var radiusZ = extendSize.z;
  50514. var size = Math.max(checkWithEpsilon(radiusX), checkWithEpsilon(radiusY), checkWithEpsilon(radiusZ)) / 2;
  50515. bodyConfig.type.push('sphere');
  50516. //due to the way oimo works with compounds, add 3 times
  50517. bodyConfig.size.push(size);
  50518. bodyConfig.size.push(size);
  50519. bodyConfig.size.push(size);
  50520. break;
  50521. case BABYLON.PhysicsImpostor.CylinderImpostor:
  50522. var sizeX = checkWithEpsilon(extendSize.x) / 2;
  50523. var sizeY = checkWithEpsilon(extendSize.y);
  50524. bodyConfig.type.push('cylinder');
  50525. bodyConfig.size.push(sizeX);
  50526. bodyConfig.size.push(sizeY);
  50527. //due to the way oimo works with compounds, add one more value.
  50528. bodyConfig.size.push(sizeY);
  50529. break;
  50530. case BABYLON.PhysicsImpostor.PlaneImpostor:
  50531. case BABYLON.PhysicsImpostor.BoxImpostor:
  50532. default:
  50533. var sizeX = checkWithEpsilon(extendSize.x);
  50534. var sizeY = checkWithEpsilon(extendSize.y);
  50535. var sizeZ = checkWithEpsilon(extendSize.z);
  50536. bodyConfig.type.push('box');
  50537. bodyConfig.size.push(sizeX);
  50538. bodyConfig.size.push(sizeY);
  50539. bodyConfig.size.push(sizeZ);
  50540. break;
  50541. }
  50542. //actually not needed, but hey...
  50543. i.object.rotationQuaternion = oldQuaternion;
  50544. });
  50545. impostor.physicsBody = new OIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  50546. }
  50547. else {
  50548. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  50549. }
  50550. impostor.setDeltaPosition(this._tmpPositionVector);
  50551. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  50552. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  50553. };
  50554. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  50555. //impostor.physicsBody.dispose();
  50556. //Same as : (older oimo versions)
  50557. this.world.removeRigidBody(impostor.physicsBody);
  50558. };
  50559. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  50560. var mainBody = impostorJoint.mainImpostor.physicsBody;
  50561. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  50562. if (!mainBody || !connectedBody) {
  50563. return;
  50564. }
  50565. var jointData = impostorJoint.joint.jointData;
  50566. var options = jointData.nativeParams || {};
  50567. var type;
  50568. var nativeJointData = {
  50569. body1: mainBody,
  50570. body2: connectedBody,
  50571. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  50572. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  50573. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  50574. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  50575. min: options.min,
  50576. max: options.max,
  50577. collision: options.collision || jointData.collision,
  50578. spring: options.spring,
  50579. //supporting older version of Oimo
  50580. world: this.world
  50581. };
  50582. switch (impostorJoint.joint.type) {
  50583. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  50584. type = "jointBall";
  50585. break;
  50586. case BABYLON.PhysicsJoint.SpringJoint:
  50587. BABYLON.Tools.Warn("Oimo.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  50588. var springData = jointData;
  50589. nativeJointData.min = springData.length || nativeJointData.min;
  50590. //Max should also be set, just make sure it is at least min
  50591. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  50592. case BABYLON.PhysicsJoint.DistanceJoint:
  50593. type = "jointDistance";
  50594. nativeJointData.max = jointData.maxDistance;
  50595. break;
  50596. case BABYLON.PhysicsJoint.PrismaticJoint:
  50597. type = "jointPrisme";
  50598. break;
  50599. case BABYLON.PhysicsJoint.SliderJoint:
  50600. type = "jointSlide";
  50601. break;
  50602. case BABYLON.PhysicsJoint.WheelJoint:
  50603. type = "jointWheel";
  50604. break;
  50605. case BABYLON.PhysicsJoint.HingeJoint:
  50606. default:
  50607. type = "jointHinge";
  50608. break;
  50609. }
  50610. nativeJointData.type = type;
  50611. impostorJoint.joint.physicsJoint = new OIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  50612. };
  50613. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  50614. //Bug in Oimo prevents us from disposing a joint in the playground
  50615. //joint.joint.physicsJoint.dispose();
  50616. //So we will bruteforce it!
  50617. try {
  50618. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  50619. }
  50620. catch (e) {
  50621. BABYLON.Tools.Warn(e);
  50622. }
  50623. };
  50624. OimoJSPlugin.prototype.isSupported = function () {
  50625. return OIMO !== undefined;
  50626. };
  50627. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  50628. if (!impostor.physicsBody.sleeping) {
  50629. //TODO check that
  50630. if (impostor.physicsBody.shapes.next) {
  50631. var parentShape = this._getLastShape(impostor.physicsBody);
  50632. impostor.object.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  50633. impostor.object.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  50634. impostor.object.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  50635. }
  50636. else {
  50637. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  50638. }
  50639. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  50640. impostor.object.rotationQuaternion.normalize();
  50641. }
  50642. };
  50643. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  50644. var body = impostor.physicsBody;
  50645. body.position.init(newPosition.x * OIMO.INV_SCALE, newPosition.y * OIMO.INV_SCALE, newPosition.z * OIMO.INV_SCALE);
  50646. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  50647. body.syncShapes();
  50648. body.awake();
  50649. };
  50650. OimoJSPlugin.prototype._getLastShape = function (body) {
  50651. var lastShape = body.shapes;
  50652. while (lastShape.next) {
  50653. lastShape = lastShape.next;
  50654. }
  50655. return lastShape;
  50656. };
  50657. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  50658. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  50659. };
  50660. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  50661. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  50662. };
  50663. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  50664. var v = impostor.physicsBody.linearVelocity;
  50665. if (!v)
  50666. return null;
  50667. return new BABYLON.Vector3(v.x, v.y, v.z);
  50668. };
  50669. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  50670. var v = impostor.physicsBody.angularVelocity;
  50671. if (!v)
  50672. return null;
  50673. return new BABYLON.Vector3(v.x, v.y, v.z);
  50674. };
  50675. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  50676. var staticBody = mass === 0;
  50677. //this will actually set the body's density and not its mass.
  50678. //But this is how oimo treats the mass variable.
  50679. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  50680. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  50681. };
  50682. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  50683. impostor.physicsBody.sleep();
  50684. };
  50685. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  50686. impostor.physicsBody.awake();
  50687. };
  50688. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  50689. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  50690. if (minDistance !== void 0) {
  50691. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  50692. }
  50693. };
  50694. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  50695. //TODO separate rotational and transational motors.
  50696. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  50697. if (motor) {
  50698. motor.setMotor(speed, maxForce);
  50699. }
  50700. };
  50701. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  50702. //TODO separate rotational and transational motors.
  50703. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  50704. if (motor) {
  50705. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  50706. }
  50707. };
  50708. OimoJSPlugin.prototype.dispose = function () {
  50709. this.world.clear();
  50710. };
  50711. return OimoJSPlugin;
  50712. }());
  50713. BABYLON.OimoJSPlugin = OimoJSPlugin;
  50714. })(BABYLON || (BABYLON = {}));
  50715. var BABYLON;
  50716. (function (BABYLON) {
  50717. var DisplayPassPostProcess = (function (_super) {
  50718. __extends(DisplayPassPostProcess, _super);
  50719. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  50720. _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable);
  50721. }
  50722. return DisplayPassPostProcess;
  50723. }(BABYLON.PostProcess));
  50724. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  50725. })(BABYLON || (BABYLON = {}));
  50726. var BABYLON;
  50727. (function (BABYLON) {
  50728. var SimplificationSettings = (function () {
  50729. function SimplificationSettings(quality, distance, optimizeMesh) {
  50730. this.quality = quality;
  50731. this.distance = distance;
  50732. this.optimizeMesh = optimizeMesh;
  50733. }
  50734. return SimplificationSettings;
  50735. }());
  50736. BABYLON.SimplificationSettings = SimplificationSettings;
  50737. var SimplificationQueue = (function () {
  50738. function SimplificationQueue() {
  50739. this.running = false;
  50740. this._simplificationArray = [];
  50741. }
  50742. SimplificationQueue.prototype.addTask = function (task) {
  50743. this._simplificationArray.push(task);
  50744. };
  50745. SimplificationQueue.prototype.executeNext = function () {
  50746. var task = this._simplificationArray.pop();
  50747. if (task) {
  50748. this.running = true;
  50749. this.runSimplification(task);
  50750. }
  50751. else {
  50752. this.running = false;
  50753. }
  50754. };
  50755. SimplificationQueue.prototype.runSimplification = function (task) {
  50756. var _this = this;
  50757. if (task.parallelProcessing) {
  50758. //parallel simplifier
  50759. task.settings.forEach(function (setting) {
  50760. var simplifier = _this.getSimplifier(task);
  50761. simplifier.simplify(setting, function (newMesh) {
  50762. task.mesh.addLODLevel(setting.distance, newMesh);
  50763. newMesh.isVisible = true;
  50764. //check if it is the last
  50765. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  50766. //all done, run the success callback.
  50767. task.successCallback();
  50768. }
  50769. _this.executeNext();
  50770. });
  50771. });
  50772. }
  50773. else {
  50774. //single simplifier.
  50775. var simplifier = this.getSimplifier(task);
  50776. var runDecimation = function (setting, callback) {
  50777. simplifier.simplify(setting, function (newMesh) {
  50778. task.mesh.addLODLevel(setting.distance, newMesh);
  50779. newMesh.isVisible = true;
  50780. //run the next quality level
  50781. callback();
  50782. });
  50783. };
  50784. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  50785. runDecimation(task.settings[loop.index], function () {
  50786. loop.executeNext();
  50787. });
  50788. }, function () {
  50789. //execution ended, run the success callback.
  50790. if (task.successCallback) {
  50791. task.successCallback();
  50792. }
  50793. _this.executeNext();
  50794. });
  50795. }
  50796. };
  50797. SimplificationQueue.prototype.getSimplifier = function (task) {
  50798. switch (task.simplificationType) {
  50799. case SimplificationType.QUADRATIC:
  50800. default:
  50801. return new QuadraticErrorSimplification(task.mesh);
  50802. }
  50803. };
  50804. return SimplificationQueue;
  50805. }());
  50806. BABYLON.SimplificationQueue = SimplificationQueue;
  50807. /**
  50808. * The implemented types of simplification.
  50809. * At the moment only Quadratic Error Decimation is implemented.
  50810. */
  50811. (function (SimplificationType) {
  50812. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  50813. })(BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  50814. var SimplificationType = BABYLON.SimplificationType;
  50815. var DecimationTriangle = (function () {
  50816. function DecimationTriangle(vertices) {
  50817. this.vertices = vertices;
  50818. this.error = new Array(4);
  50819. this.deleted = false;
  50820. this.isDirty = false;
  50821. this.deletePending = false;
  50822. this.borderFactor = 0;
  50823. }
  50824. return DecimationTriangle;
  50825. }());
  50826. BABYLON.DecimationTriangle = DecimationTriangle;
  50827. var DecimationVertex = (function () {
  50828. function DecimationVertex(position, id) {
  50829. this.position = position;
  50830. this.id = id;
  50831. this.isBorder = true;
  50832. this.q = new QuadraticMatrix();
  50833. this.triangleCount = 0;
  50834. this.triangleStart = 0;
  50835. this.originalOffsets = [];
  50836. }
  50837. DecimationVertex.prototype.updatePosition = function (newPosition) {
  50838. this.position.copyFrom(newPosition);
  50839. };
  50840. return DecimationVertex;
  50841. }());
  50842. BABYLON.DecimationVertex = DecimationVertex;
  50843. var QuadraticMatrix = (function () {
  50844. function QuadraticMatrix(data) {
  50845. this.data = new Array(10);
  50846. for (var i = 0; i < 10; ++i) {
  50847. if (data && data[i]) {
  50848. this.data[i] = data[i];
  50849. }
  50850. else {
  50851. this.data[i] = 0;
  50852. }
  50853. }
  50854. }
  50855. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  50856. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  50857. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  50858. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  50859. return det;
  50860. };
  50861. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  50862. for (var i = 0; i < 10; ++i) {
  50863. this.data[i] += matrix.data[i];
  50864. }
  50865. };
  50866. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  50867. for (var i = 0; i < 10; ++i) {
  50868. this.data[i] += data[i];
  50869. }
  50870. };
  50871. QuadraticMatrix.prototype.add = function (matrix) {
  50872. var m = new QuadraticMatrix();
  50873. for (var i = 0; i < 10; ++i) {
  50874. m.data[i] = this.data[i] + matrix.data[i];
  50875. }
  50876. return m;
  50877. };
  50878. QuadraticMatrix.FromData = function (a, b, c, d) {
  50879. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  50880. };
  50881. //returning an array to avoid garbage collection
  50882. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  50883. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  50884. };
  50885. return QuadraticMatrix;
  50886. }());
  50887. BABYLON.QuadraticMatrix = QuadraticMatrix;
  50888. var Reference = (function () {
  50889. function Reference(vertexId, triangleId) {
  50890. this.vertexId = vertexId;
  50891. this.triangleId = triangleId;
  50892. }
  50893. return Reference;
  50894. }());
  50895. BABYLON.Reference = Reference;
  50896. /**
  50897. * An implementation of the Quadratic Error simplification algorithm.
  50898. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  50899. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  50900. * @author RaananW
  50901. */
  50902. var QuadraticErrorSimplification = (function () {
  50903. function QuadraticErrorSimplification(_mesh) {
  50904. this._mesh = _mesh;
  50905. this.initialized = false;
  50906. this.syncIterations = 5000;
  50907. this.aggressiveness = 7;
  50908. this.decimationIterations = 100;
  50909. this.boundingBoxEpsilon = BABYLON.Epsilon;
  50910. }
  50911. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  50912. var _this = this;
  50913. this.initDecimatedMesh();
  50914. //iterating through the submeshes array, one after the other.
  50915. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  50916. _this.initWithMesh(loop.index, function () {
  50917. _this.runDecimation(settings, loop.index, function () {
  50918. loop.executeNext();
  50919. });
  50920. }, settings.optimizeMesh);
  50921. }, function () {
  50922. setTimeout(function () {
  50923. successCallback(_this._reconstructedMesh);
  50924. }, 0);
  50925. });
  50926. };
  50927. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  50928. var _this = this;
  50929. var gCount = 0;
  50930. triangle.vertices.forEach(function (vertex) {
  50931. var count = 0;
  50932. var vPos = vertex.position;
  50933. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  50934. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  50935. ++count;
  50936. if (bbox.maximum.y === vPos.y || vPos.y === bbox.minimum.y)
  50937. ++count;
  50938. if (bbox.maximum.z === vPos.z || vPos.z === bbox.minimum.z)
  50939. ++count;
  50940. if (count > 1) {
  50941. ++gCount;
  50942. }
  50943. ;
  50944. });
  50945. if (gCount > 1) {
  50946. console.log(triangle, gCount);
  50947. }
  50948. return gCount > 1;
  50949. };
  50950. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  50951. var _this = this;
  50952. var targetCount = ~~(this.triangles.length * settings.quality);
  50953. var deletedTriangles = 0;
  50954. var triangleCount = this.triangles.length;
  50955. var iterationFunction = function (iteration, callback) {
  50956. setTimeout(function () {
  50957. if (iteration % 5 === 0) {
  50958. _this.updateMesh(iteration === 0);
  50959. }
  50960. for (var i = 0; i < _this.triangles.length; ++i) {
  50961. _this.triangles[i].isDirty = false;
  50962. }
  50963. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  50964. var trianglesIterator = function (i) {
  50965. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  50966. var t = _this.triangles[tIdx];
  50967. if (!t)
  50968. return;
  50969. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  50970. return;
  50971. }
  50972. for (var j = 0; j < 3; ++j) {
  50973. if (t.error[j] < threshold) {
  50974. var deleted0 = [];
  50975. var deleted1 = [];
  50976. var v0 = t.vertices[j];
  50977. var v1 = t.vertices[(j + 1) % 3];
  50978. if (v0.isBorder || v1.isBorder)
  50979. continue;
  50980. var p = BABYLON.Vector3.Zero();
  50981. var n = BABYLON.Vector3.Zero();
  50982. var uv = BABYLON.Vector2.Zero();
  50983. var color = new BABYLON.Color4(0, 0, 0, 1);
  50984. _this.calculateError(v0, v1, p, n, uv, color);
  50985. var delTr = [];
  50986. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  50987. continue;
  50988. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  50989. continue;
  50990. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  50991. continue;
  50992. var uniqueArray = [];
  50993. delTr.forEach(function (deletedT) {
  50994. if (uniqueArray.indexOf(deletedT) === -1) {
  50995. deletedT.deletePending = true;
  50996. uniqueArray.push(deletedT);
  50997. }
  50998. });
  50999. if (uniqueArray.length % 2 !== 0) {
  51000. continue;
  51001. }
  51002. v0.q = v1.q.add(v0.q);
  51003. v0.updatePosition(p);
  51004. var tStart = _this.references.length;
  51005. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  51006. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  51007. var tCount = _this.references.length - tStart;
  51008. if (tCount <= v0.triangleCount) {
  51009. if (tCount) {
  51010. for (var c = 0; c < tCount; c++) {
  51011. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  51012. }
  51013. }
  51014. }
  51015. else {
  51016. v0.triangleStart = tStart;
  51017. }
  51018. v0.triangleCount = tCount;
  51019. break;
  51020. }
  51021. }
  51022. };
  51023. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  51024. }, 0);
  51025. };
  51026. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  51027. if (triangleCount - deletedTriangles <= targetCount)
  51028. loop.breakLoop();
  51029. else {
  51030. iterationFunction(loop.index, function () {
  51031. loop.executeNext();
  51032. });
  51033. }
  51034. }, function () {
  51035. setTimeout(function () {
  51036. //reconstruct this part of the mesh
  51037. _this.reconstructMesh(submeshIndex);
  51038. successCallback();
  51039. }, 0);
  51040. });
  51041. };
  51042. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  51043. var _this = this;
  51044. this.vertices = [];
  51045. this.triangles = [];
  51046. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  51047. var indices = this._mesh.getIndices();
  51048. var submesh = this._mesh.subMeshes[submeshIndex];
  51049. var findInVertices = function (positionToSearch) {
  51050. if (optimizeMesh) {
  51051. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  51052. if (_this.vertices[ii].position.equals(positionToSearch)) {
  51053. return _this.vertices[ii];
  51054. }
  51055. }
  51056. }
  51057. return null;
  51058. };
  51059. var vertexReferences = [];
  51060. var vertexInit = function (i) {
  51061. var offset = i + submesh.verticesStart;
  51062. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  51063. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  51064. vertex.originalOffsets.push(offset);
  51065. if (vertex.id === _this.vertices.length) {
  51066. _this.vertices.push(vertex);
  51067. }
  51068. vertexReferences.push(vertex.id);
  51069. };
  51070. //var totalVertices = mesh.getTotalVertices();
  51071. var totalVertices = submesh.verticesCount;
  51072. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  51073. var indicesInit = function (i) {
  51074. var offset = (submesh.indexStart / 3) + i;
  51075. var pos = (offset * 3);
  51076. var i0 = indices[pos + 0];
  51077. var i1 = indices[pos + 1];
  51078. var i2 = indices[pos + 2];
  51079. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  51080. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  51081. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  51082. var triangle = new DecimationTriangle([v0, v1, v2]);
  51083. triangle.originalOffset = pos;
  51084. _this.triangles.push(triangle);
  51085. };
  51086. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  51087. _this.init(callback);
  51088. });
  51089. });
  51090. };
  51091. QuadraticErrorSimplification.prototype.init = function (callback) {
  51092. var _this = this;
  51093. var triangleInit1 = function (i) {
  51094. var t = _this.triangles[i];
  51095. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  51096. for (var j = 0; j < 3; j++) {
  51097. 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))));
  51098. }
  51099. };
  51100. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  51101. var triangleInit2 = function (i) {
  51102. var t = _this.triangles[i];
  51103. for (var j = 0; j < 3; ++j) {
  51104. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  51105. }
  51106. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  51107. };
  51108. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  51109. _this.initialized = true;
  51110. callback();
  51111. });
  51112. });
  51113. };
  51114. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  51115. var newTriangles = [];
  51116. var i;
  51117. for (i = 0; i < this.vertices.length; ++i) {
  51118. this.vertices[i].triangleCount = 0;
  51119. }
  51120. var t;
  51121. var j;
  51122. for (i = 0; i < this.triangles.length; ++i) {
  51123. if (!this.triangles[i].deleted) {
  51124. t = this.triangles[i];
  51125. for (j = 0; j < 3; ++j) {
  51126. t.vertices[j].triangleCount = 1;
  51127. }
  51128. newTriangles.push(t);
  51129. }
  51130. }
  51131. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  51132. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  51133. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  51134. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  51135. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  51136. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  51137. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  51138. var vertexCount = 0;
  51139. for (i = 0; i < this.vertices.length; ++i) {
  51140. var vertex = this.vertices[i];
  51141. vertex.id = vertexCount;
  51142. if (vertex.triangleCount) {
  51143. vertex.originalOffsets.forEach(function (originalOffset) {
  51144. newPositionData.push(vertex.position.x);
  51145. newPositionData.push(vertex.position.y);
  51146. newPositionData.push(vertex.position.z);
  51147. newNormalData.push(normalData[originalOffset * 3]);
  51148. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  51149. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  51150. if (uvs && uvs.length) {
  51151. newUVsData.push(uvs[(originalOffset * 2)]);
  51152. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  51153. }
  51154. else if (colorsData && colorsData.length) {
  51155. newColorsData.push(colorsData[(originalOffset * 4)]);
  51156. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  51157. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  51158. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  51159. }
  51160. ++vertexCount;
  51161. });
  51162. }
  51163. }
  51164. var startingIndex = this._reconstructedMesh.getTotalIndices();
  51165. var startingVertex = this._reconstructedMesh.getTotalVertices();
  51166. var submeshesArray = this._reconstructedMesh.subMeshes;
  51167. this._reconstructedMesh.subMeshes = [];
  51168. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  51169. var originalIndices = this._mesh.getIndices();
  51170. for (i = 0; i < newTriangles.length; ++i) {
  51171. t = newTriangles[i]; //now get the new referencing point for each vertex
  51172. [0, 1, 2].forEach(function (idx) {
  51173. var id = originalIndices[t.originalOffset + idx];
  51174. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  51175. if (offset < 0)
  51176. offset = 0;
  51177. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  51178. });
  51179. }
  51180. //overwriting the old vertex buffers and indices.
  51181. this._reconstructedMesh.setIndices(newIndicesArray);
  51182. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  51183. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  51184. if (newUVsData.length > 0)
  51185. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  51186. if (newColorsData.length > 0)
  51187. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  51188. //create submesh
  51189. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  51190. if (submeshIndex > 0) {
  51191. this._reconstructedMesh.subMeshes = [];
  51192. submeshesArray.forEach(function (submesh) {
  51193. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  51194. });
  51195. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  51196. }
  51197. };
  51198. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  51199. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  51200. this._reconstructedMesh.material = this._mesh.material;
  51201. this._reconstructedMesh.parent = this._mesh.parent;
  51202. this._reconstructedMesh.isVisible = false;
  51203. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  51204. };
  51205. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  51206. for (var i = 0; i < vertex1.triangleCount; ++i) {
  51207. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  51208. if (t.deleted)
  51209. continue;
  51210. var s = this.references[vertex1.triangleStart + i].vertexId;
  51211. var v1 = t.vertices[(s + 1) % 3];
  51212. var v2 = t.vertices[(s + 2) % 3];
  51213. if ((v1 === vertex2 || v2 === vertex2) /* && !this.isTriangleOnBoundingBox(t)*/) {
  51214. deletedArray[i] = true;
  51215. delTr.push(t);
  51216. continue;
  51217. }
  51218. var d1 = v1.position.subtract(point);
  51219. d1 = d1.normalize();
  51220. var d2 = v2.position.subtract(point);
  51221. d2 = d2.normalize();
  51222. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  51223. return true;
  51224. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  51225. deletedArray[i] = false;
  51226. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  51227. return true;
  51228. }
  51229. return false;
  51230. };
  51231. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  51232. var newDeleted = deletedTriangles;
  51233. for (var i = 0; i < vertex.triangleCount; ++i) {
  51234. var ref = this.references[vertex.triangleStart + i];
  51235. var t = this.triangles[ref.triangleId];
  51236. if (t.deleted)
  51237. continue;
  51238. if (deletedArray[i] && t.deletePending) {
  51239. t.deleted = true;
  51240. newDeleted++;
  51241. continue;
  51242. }
  51243. t.vertices[ref.vertexId] = origVertex;
  51244. t.isDirty = true;
  51245. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  51246. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  51247. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  51248. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  51249. this.references.push(ref);
  51250. }
  51251. return newDeleted;
  51252. };
  51253. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  51254. for (var i = 0; i < this.vertices.length; ++i) {
  51255. var vCount = [];
  51256. var vId = [];
  51257. var v = this.vertices[i];
  51258. var j;
  51259. for (j = 0; j < v.triangleCount; ++j) {
  51260. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  51261. for (var ii = 0; ii < 3; ii++) {
  51262. var ofs = 0;
  51263. var vv = triangle.vertices[ii];
  51264. while (ofs < vCount.length) {
  51265. if (vId[ofs] === vv.id)
  51266. break;
  51267. ++ofs;
  51268. }
  51269. if (ofs === vCount.length) {
  51270. vCount.push(1);
  51271. vId.push(vv.id);
  51272. }
  51273. else {
  51274. vCount[ofs]++;
  51275. }
  51276. }
  51277. }
  51278. for (j = 0; j < vCount.length; ++j) {
  51279. if (vCount[j] === 1) {
  51280. this.vertices[vId[j]].isBorder = true;
  51281. }
  51282. else {
  51283. this.vertices[vId[j]].isBorder = false;
  51284. }
  51285. }
  51286. }
  51287. };
  51288. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  51289. if (identifyBorders === void 0) { identifyBorders = false; }
  51290. var i;
  51291. if (!identifyBorders) {
  51292. var newTrianglesVector = [];
  51293. for (i = 0; i < this.triangles.length; ++i) {
  51294. if (!this.triangles[i].deleted) {
  51295. newTrianglesVector.push(this.triangles[i]);
  51296. }
  51297. }
  51298. this.triangles = newTrianglesVector;
  51299. }
  51300. for (i = 0; i < this.vertices.length; ++i) {
  51301. this.vertices[i].triangleCount = 0;
  51302. this.vertices[i].triangleStart = 0;
  51303. }
  51304. var t;
  51305. var j;
  51306. var v;
  51307. for (i = 0; i < this.triangles.length; ++i) {
  51308. t = this.triangles[i];
  51309. for (j = 0; j < 3; ++j) {
  51310. v = t.vertices[j];
  51311. v.triangleCount++;
  51312. }
  51313. }
  51314. var tStart = 0;
  51315. for (i = 0; i < this.vertices.length; ++i) {
  51316. this.vertices[i].triangleStart = tStart;
  51317. tStart += this.vertices[i].triangleCount;
  51318. this.vertices[i].triangleCount = 0;
  51319. }
  51320. var newReferences = new Array(this.triangles.length * 3);
  51321. for (i = 0; i < this.triangles.length; ++i) {
  51322. t = this.triangles[i];
  51323. for (j = 0; j < 3; ++j) {
  51324. v = t.vertices[j];
  51325. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  51326. v.triangleCount++;
  51327. }
  51328. }
  51329. this.references = newReferences;
  51330. if (identifyBorders) {
  51331. this.identifyBorder();
  51332. }
  51333. };
  51334. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  51335. var x = point.x;
  51336. var y = point.y;
  51337. var z = point.z;
  51338. 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
  51339. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  51340. };
  51341. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  51342. var q = vertex1.q.add(vertex2.q);
  51343. var border = vertex1.isBorder && vertex2.isBorder;
  51344. var error = 0;
  51345. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  51346. if (qDet !== 0 && !border) {
  51347. if (!pointResult) {
  51348. pointResult = BABYLON.Vector3.Zero();
  51349. }
  51350. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  51351. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  51352. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  51353. error = this.vertexError(q, pointResult);
  51354. }
  51355. else {
  51356. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  51357. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  51358. var error1 = this.vertexError(q, vertex1.position);
  51359. var error2 = this.vertexError(q, vertex2.position);
  51360. var error3 = this.vertexError(q, p3);
  51361. error = Math.min(error1, error2, error3);
  51362. if (error === error1) {
  51363. if (pointResult) {
  51364. pointResult.copyFrom(vertex1.position);
  51365. }
  51366. }
  51367. else if (error === error2) {
  51368. if (pointResult) {
  51369. pointResult.copyFrom(vertex2.position);
  51370. }
  51371. }
  51372. else {
  51373. if (pointResult) {
  51374. pointResult.copyFrom(p3);
  51375. }
  51376. }
  51377. }
  51378. return error;
  51379. };
  51380. return QuadraticErrorSimplification;
  51381. }());
  51382. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  51383. })(BABYLON || (BABYLON = {}));
  51384. var BABYLON;
  51385. (function (BABYLON) {
  51386. var serializedGeometries = [];
  51387. var serializeGeometry = function (geometry, serializationGeometries) {
  51388. if (serializedGeometries[geometry.id]) {
  51389. return;
  51390. }
  51391. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  51392. serializationGeometries.boxes.push(geometry.serialize());
  51393. }
  51394. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  51395. serializationGeometries.spheres.push(geometry.serialize());
  51396. }
  51397. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  51398. serializationGeometries.cylinders.push(geometry.serialize());
  51399. }
  51400. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  51401. serializationGeometries.toruses.push(geometry.serialize());
  51402. }
  51403. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  51404. serializationGeometries.grounds.push(geometry.serialize());
  51405. }
  51406. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  51407. serializationGeometries.planes.push(geometry.serialize());
  51408. }
  51409. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  51410. serializationGeometries.torusKnots.push(geometry.serialize());
  51411. }
  51412. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  51413. throw new Error("Unknown primitive type");
  51414. }
  51415. else {
  51416. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  51417. }
  51418. serializedGeometries[geometry.id] = true;
  51419. };
  51420. var serializeMesh = function (mesh, serializationScene) {
  51421. var serializationObject = {};
  51422. serializationObject.name = mesh.name;
  51423. serializationObject.id = mesh.id;
  51424. if (BABYLON.Tags.HasTags(mesh)) {
  51425. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  51426. }
  51427. serializationObject.position = mesh.position.asArray();
  51428. if (mesh.rotationQuaternion) {
  51429. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  51430. }
  51431. else if (mesh.rotation) {
  51432. serializationObject.rotation = mesh.rotation.asArray();
  51433. }
  51434. serializationObject.scaling = mesh.scaling.asArray();
  51435. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  51436. serializationObject.isEnabled = mesh.isEnabled();
  51437. serializationObject.isVisible = mesh.isVisible;
  51438. serializationObject.infiniteDistance = mesh.infiniteDistance;
  51439. serializationObject.pickable = mesh.isPickable;
  51440. serializationObject.receiveShadows = mesh.receiveShadows;
  51441. serializationObject.billboardMode = mesh.billboardMode;
  51442. serializationObject.visibility = mesh.visibility;
  51443. serializationObject.checkCollisions = mesh.checkCollisions;
  51444. // Parent
  51445. if (mesh.parent) {
  51446. serializationObject.parentId = mesh.parent.id;
  51447. }
  51448. // Geometry
  51449. var geometry = mesh._geometry;
  51450. if (geometry) {
  51451. var geometryId = geometry.id;
  51452. serializationObject.geometryId = geometryId;
  51453. if (!mesh.getScene().getGeometryByID(geometryId)) {
  51454. // 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
  51455. serializeGeometry(geometry, serializationScene.geometries);
  51456. }
  51457. // SubMeshes
  51458. serializationObject.subMeshes = [];
  51459. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  51460. var subMesh = mesh.subMeshes[subIndex];
  51461. serializationObject.subMeshes.push({
  51462. materialIndex: subMesh.materialIndex,
  51463. verticesStart: subMesh.verticesStart,
  51464. verticesCount: subMesh.verticesCount,
  51465. indexStart: subMesh.indexStart,
  51466. indexCount: subMesh.indexCount
  51467. });
  51468. }
  51469. }
  51470. // Material
  51471. if (mesh.material) {
  51472. serializationObject.materialId = mesh.material.id;
  51473. }
  51474. else {
  51475. mesh.material = null;
  51476. }
  51477. // Skeleton
  51478. if (mesh.skeleton) {
  51479. serializationObject.skeletonId = mesh.skeleton.id;
  51480. }
  51481. // Physics
  51482. //TODO implement correct serialization for physics impostors.
  51483. if (mesh.getPhysicsImpostor()) {
  51484. serializationObject.physicsMass = mesh.getPhysicsMass();
  51485. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  51486. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  51487. serializationObject.physicsImpostor = mesh.getPhysicsImpostor().type;
  51488. }
  51489. // Instances
  51490. serializationObject.instances = [];
  51491. for (var index = 0; index < mesh.instances.length; index++) {
  51492. var instance = mesh.instances[index];
  51493. var serializationInstance = {
  51494. name: instance.name,
  51495. position: instance.position.asArray(),
  51496. scaling: instance.scaling.asArray()
  51497. };
  51498. if (instance.rotationQuaternion) {
  51499. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  51500. }
  51501. else if (instance.rotation) {
  51502. serializationInstance.rotation = instance.rotation.asArray();
  51503. }
  51504. serializationObject.instances.push(serializationInstance);
  51505. // Animations
  51506. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  51507. serializationInstance.ranges = instance.serializeAnimationRanges();
  51508. }
  51509. // Animations
  51510. BABYLON.Animation.AppendSerializedAnimations(mesh, serializationObject);
  51511. serializationObject.ranges = mesh.serializeAnimationRanges();
  51512. // Layer mask
  51513. serializationObject.layerMask = mesh.layerMask;
  51514. // Action Manager
  51515. if (mesh.actionManager) {
  51516. serializationObject.actions = mesh.actionManager.serialize(mesh.name);
  51517. }
  51518. return serializationObject;
  51519. };
  51520. var finalizeSingleMesh = function (mesh, serializationObject) {
  51521. //only works if the mesh is already loaded
  51522. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  51523. //serialize material
  51524. if (mesh.material) {
  51525. if (mesh.material instanceof BABYLON.StandardMaterial) {
  51526. serializationObject.materials = serializationObject.materials || [];
  51527. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  51528. serializationObject.materials.push(mesh.material.serialize());
  51529. }
  51530. }
  51531. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  51532. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  51533. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  51534. serializationObject.multiMaterials.push(mesh.material.serialize());
  51535. }
  51536. }
  51537. }
  51538. //serialize geometry
  51539. var geometry = mesh._geometry;
  51540. if (geometry) {
  51541. if (!serializationObject.geometries) {
  51542. serializationObject.geometries = {};
  51543. serializationObject.geometries.boxes = [];
  51544. serializationObject.geometries.spheres = [];
  51545. serializationObject.geometries.cylinders = [];
  51546. serializationObject.geometries.toruses = [];
  51547. serializationObject.geometries.grounds = [];
  51548. serializationObject.geometries.planes = [];
  51549. serializationObject.geometries.torusKnots = [];
  51550. serializationObject.geometries.vertexData = [];
  51551. }
  51552. serializeGeometry(geometry, serializationObject.geometries);
  51553. }
  51554. // Skeletons
  51555. if (mesh.skeleton) {
  51556. serializationObject.skeletons = serializationObject.skeletons || [];
  51557. serializationObject.skeletons.push(mesh.skeleton.serialize());
  51558. }
  51559. //serialize the actual mesh
  51560. serializationObject.meshes = serializationObject.meshes || [];
  51561. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  51562. }
  51563. };
  51564. var SceneSerializer = (function () {
  51565. function SceneSerializer() {
  51566. }
  51567. SceneSerializer.ClearCache = function () {
  51568. serializedGeometries = [];
  51569. };
  51570. SceneSerializer.Serialize = function (scene) {
  51571. var serializationObject = {};
  51572. // Scene
  51573. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  51574. serializationObject.autoClear = scene.autoClear;
  51575. serializationObject.clearColor = scene.clearColor.asArray();
  51576. serializationObject.ambientColor = scene.ambientColor.asArray();
  51577. serializationObject.gravity = scene.gravity.asArray();
  51578. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  51579. serializationObject.workerCollisions = scene.workerCollisions;
  51580. // Fog
  51581. if (scene.fogMode && scene.fogMode !== 0) {
  51582. serializationObject.fogMode = scene.fogMode;
  51583. serializationObject.fogColor = scene.fogColor.asArray();
  51584. serializationObject.fogStart = scene.fogStart;
  51585. serializationObject.fogEnd = scene.fogEnd;
  51586. serializationObject.fogDensity = scene.fogDensity;
  51587. }
  51588. //Physics
  51589. if (scene.isPhysicsEnabled()) {
  51590. serializationObject.physicsEnabled = true;
  51591. serializationObject.physicsGravity = scene.getPhysicsEngine().gravity.asArray();
  51592. serializationObject.physicsEngine = scene.getPhysicsEngine().getPhysicsPluginName();
  51593. }
  51594. // Lights
  51595. serializationObject.lights = [];
  51596. var index;
  51597. var light;
  51598. for (index = 0; index < scene.lights.length; index++) {
  51599. light = scene.lights[index];
  51600. serializationObject.lights.push(light.serialize());
  51601. }
  51602. // Cameras
  51603. serializationObject.cameras = [];
  51604. for (index = 0; index < scene.cameras.length; index++) {
  51605. var camera = scene.cameras[index];
  51606. serializationObject.cameras.push(camera.serialize());
  51607. }
  51608. if (scene.activeCamera) {
  51609. serializationObject.activeCameraID = scene.activeCamera.id;
  51610. }
  51611. // Animations
  51612. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  51613. // Materials
  51614. serializationObject.materials = [];
  51615. serializationObject.multiMaterials = [];
  51616. var material;
  51617. for (index = 0; index < scene.materials.length; index++) {
  51618. material = scene.materials[index];
  51619. serializationObject.materials.push(material.serialize());
  51620. }
  51621. // MultiMaterials
  51622. serializationObject.multiMaterials = [];
  51623. for (index = 0; index < scene.multiMaterials.length; index++) {
  51624. var multiMaterial = scene.multiMaterials[index];
  51625. serializationObject.multiMaterials.push(multiMaterial.serialize());
  51626. }
  51627. // Skeletons
  51628. serializationObject.skeletons = [];
  51629. for (index = 0; index < scene.skeletons.length; index++) {
  51630. serializationObject.skeletons.push(scene.skeletons[index].serialize());
  51631. }
  51632. // Geometries
  51633. serializationObject.geometries = {};
  51634. serializationObject.geometries.boxes = [];
  51635. serializationObject.geometries.spheres = [];
  51636. serializationObject.geometries.cylinders = [];
  51637. serializationObject.geometries.toruses = [];
  51638. serializationObject.geometries.grounds = [];
  51639. serializationObject.geometries.planes = [];
  51640. serializationObject.geometries.torusKnots = [];
  51641. serializationObject.geometries.vertexData = [];
  51642. serializedGeometries = [];
  51643. var geometries = scene.getGeometries();
  51644. for (index = 0; index < geometries.length; index++) {
  51645. var geometry = geometries[index];
  51646. if (geometry.isReady()) {
  51647. serializeGeometry(geometry, serializationObject.geometries);
  51648. }
  51649. }
  51650. // Meshes
  51651. serializationObject.meshes = [];
  51652. for (index = 0; index < scene.meshes.length; index++) {
  51653. var abstractMesh = scene.meshes[index];
  51654. if (abstractMesh instanceof BABYLON.Mesh) {
  51655. var mesh = abstractMesh;
  51656. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  51657. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  51658. }
  51659. }
  51660. }
  51661. // Particles Systems
  51662. serializationObject.particleSystems = [];
  51663. for (index = 0; index < scene.particleSystems.length; index++) {
  51664. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  51665. }
  51666. // Lens flares
  51667. serializationObject.lensFlareSystems = [];
  51668. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  51669. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  51670. }
  51671. // Shadows
  51672. serializationObject.shadowGenerators = [];
  51673. for (index = 0; index < scene.lights.length; index++) {
  51674. light = scene.lights[index];
  51675. var shadowGenerator = light.getShadowGenerator();
  51676. // Only support serialization for official generator so far.
  51677. if (shadowGenerator && shadowGenerator instanceof BABYLON.ShadowGenerator) {
  51678. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  51679. }
  51680. }
  51681. // Action Manager
  51682. if (scene.actionManager) {
  51683. serializationObject.actions = scene.actionManager.serialize("scene");
  51684. }
  51685. // Audio
  51686. serializationObject.sounds = [];
  51687. for (index = 0; index < scene.soundTracks.length; index++) {
  51688. var soundtrack = scene.soundTracks[index];
  51689. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  51690. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  51691. }
  51692. }
  51693. return serializationObject;
  51694. };
  51695. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  51696. if (withParents === void 0) { withParents = false; }
  51697. if (withChildren === void 0) { withChildren = false; }
  51698. var serializationObject = {};
  51699. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  51700. if (withParents || withChildren) {
  51701. //deliberate for loop! not for each, appended should be processed as well.
  51702. for (var i = 0; i < toSerialize.length; ++i) {
  51703. if (withChildren) {
  51704. toSerialize[i].getDescendants().forEach(function (node) {
  51705. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  51706. toSerialize.push(node);
  51707. }
  51708. });
  51709. }
  51710. //make sure the array doesn't contain the object already
  51711. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  51712. toSerialize.push(toSerialize[i].parent);
  51713. }
  51714. }
  51715. }
  51716. toSerialize.forEach(function (mesh) {
  51717. finalizeSingleMesh(mesh, serializationObject);
  51718. });
  51719. return serializationObject;
  51720. };
  51721. return SceneSerializer;
  51722. }());
  51723. BABYLON.SceneSerializer = SceneSerializer;
  51724. })(BABYLON || (BABYLON = {}));
  51725. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  51726. // Huge respect for a such great lib.
  51727. // Earcut license:
  51728. // Copyright (c) 2016, Mapbox
  51729. //
  51730. // Permission to use, copy, modify, and/or distribute this software for any purpose
  51731. // with or without fee is hereby granted, provided that the above copyright notice
  51732. // and this permission notice appear in all copies.
  51733. //
  51734. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  51735. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  51736. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  51737. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  51738. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  51739. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  51740. // THIS SOFTWARE.
  51741. var Earcut;
  51742. (function (Earcut) {
  51743. /**
  51744. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  51745. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  51746. * @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).
  51747. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  51748. */
  51749. function earcut(data, holeIndices, dim) {
  51750. dim = dim || 2;
  51751. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = [];
  51752. if (!outerNode)
  51753. return triangles;
  51754. var minX, minY, maxX, maxY, x, y, size;
  51755. if (hasHoles)
  51756. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  51757. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  51758. if (data.length > 80 * dim) {
  51759. minX = maxX = data[0];
  51760. minY = maxY = data[1];
  51761. for (var i = dim; i < outerLen; i += dim) {
  51762. x = data[i];
  51763. y = data[i + 1];
  51764. if (x < minX)
  51765. minX = x;
  51766. if (y < minY)
  51767. minY = y;
  51768. if (x > maxX)
  51769. maxX = x;
  51770. if (y > maxY)
  51771. maxY = y;
  51772. }
  51773. // minX, minY and size are later used to transform coords into integers for z-order calculation
  51774. size = Math.max(maxX - minX, maxY - minY);
  51775. }
  51776. earcutLinked(outerNode, triangles, dim, minX, minY, size, undefined);
  51777. return triangles;
  51778. }
  51779. Earcut.earcut = earcut;
  51780. // create a circular doubly linked list from polygon points in the specified winding order
  51781. function linkedList(data, start, end, dim, clockwise) {
  51782. var i, last;
  51783. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  51784. for (i = start; i < end; i += dim)
  51785. last = insertNode(i, data[i], data[i + 1], last);
  51786. }
  51787. else {
  51788. for (i = end - dim; i >= start; i -= dim)
  51789. last = insertNode(i, data[i], data[i + 1], last);
  51790. }
  51791. if (last && equals(last, last.next)) {
  51792. removeNode(last);
  51793. last = last.next;
  51794. }
  51795. return last;
  51796. }
  51797. // eliminate colinear or duplicate points
  51798. function filterPoints(start, end) {
  51799. if (!start)
  51800. return start;
  51801. if (!end)
  51802. end = start;
  51803. var p = start, again;
  51804. do {
  51805. again = false;
  51806. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  51807. removeNode(p);
  51808. p = end = p.prev;
  51809. if (p === p.next)
  51810. return null;
  51811. again = true;
  51812. }
  51813. else {
  51814. p = p.next;
  51815. }
  51816. } while (again || p !== end);
  51817. return end;
  51818. }
  51819. // main ear slicing loop which triangulates a polygon (given as a linked list)
  51820. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  51821. if (!ear)
  51822. return;
  51823. // interlink polygon nodes in z-order
  51824. if (!pass && size)
  51825. indexCurve(ear, minX, minY, size);
  51826. var stop = ear, prev, next;
  51827. // iterate through ears, slicing them one by one
  51828. while (ear.prev !== ear.next) {
  51829. prev = ear.prev;
  51830. next = ear.next;
  51831. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  51832. // cut off the triangle
  51833. triangles.push(prev.i / dim);
  51834. triangles.push(ear.i / dim);
  51835. triangles.push(next.i / dim);
  51836. removeNode(ear);
  51837. // skipping the next vertice leads to less sliver triangles
  51838. ear = next.next;
  51839. stop = next.next;
  51840. continue;
  51841. }
  51842. ear = next;
  51843. // if we looped through the whole remaining polygon and can't find any more ears
  51844. if (ear === stop) {
  51845. // try filtering points and slicing again
  51846. if (!pass) {
  51847. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  51848. }
  51849. else if (pass === 1) {
  51850. ear = cureLocalIntersections(ear, triangles, dim);
  51851. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  51852. }
  51853. else if (pass === 2) {
  51854. splitEarcut(ear, triangles, dim, minX, minY, size);
  51855. }
  51856. break;
  51857. }
  51858. }
  51859. }
  51860. // check whether a polygon node forms a valid ear with adjacent nodes
  51861. function isEar(ear) {
  51862. var a = ear.prev, b = ear, c = ear.next;
  51863. if (area(a, b, c) >= 0)
  51864. return false; // reflex, can't be an ear
  51865. // now make sure we don't have other points inside the potential ear
  51866. var p = ear.next.next;
  51867. while (p !== ear.prev) {
  51868. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  51869. area(p.prev, p, p.next) >= 0)
  51870. return false;
  51871. p = p.next;
  51872. }
  51873. return true;
  51874. }
  51875. function isEarHashed(ear, minX, minY, size) {
  51876. var a = ear.prev, b = ear, c = ear.next;
  51877. if (area(a, b, c) >= 0)
  51878. return false; // reflex, can't be an ear
  51879. // triangle bbox; min & max are calculated like this for speed
  51880. 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);
  51881. // z-order range for the current triangle bbox;
  51882. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  51883. // first look for points inside the triangle in increasing z-order
  51884. var p = ear.nextZ;
  51885. while (p && p.z <= maxZ) {
  51886. if (p !== ear.prev &&
  51887. p !== ear.next &&
  51888. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  51889. area(p.prev, p, p.next) >= 0)
  51890. return false;
  51891. p = p.nextZ;
  51892. }
  51893. // then look for points in decreasing z-order
  51894. p = ear.prevZ;
  51895. while (p && p.z >= minZ) {
  51896. if (p !== ear.prev &&
  51897. p !== ear.next &&
  51898. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  51899. area(p.prev, p, p.next) >= 0)
  51900. return false;
  51901. p = p.prevZ;
  51902. }
  51903. return true;
  51904. }
  51905. // go through all polygon nodes and cure small local self-intersections
  51906. function cureLocalIntersections(start, triangles, dim) {
  51907. var p = start;
  51908. do {
  51909. var a = p.prev, b = p.next.next;
  51910. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  51911. triangles.push(a.i / dim);
  51912. triangles.push(p.i / dim);
  51913. triangles.push(b.i / dim);
  51914. // remove two nodes involved
  51915. removeNode(p);
  51916. removeNode(p.next);
  51917. p = start = b;
  51918. }
  51919. p = p.next;
  51920. } while (p !== start);
  51921. return p;
  51922. }
  51923. // try splitting polygon into two and triangulate them independently
  51924. function splitEarcut(start, triangles, dim, minX, minY, size) {
  51925. // look for a valid diagonal that divides the polygon into two
  51926. var a = start;
  51927. do {
  51928. var b = a.next.next;
  51929. while (b !== a.prev) {
  51930. if (a.i !== b.i && isValidDiagonal(a, b)) {
  51931. // split the polygon in two by the diagonal
  51932. var c = splitPolygon(a, b);
  51933. // filter colinear points around the cuts
  51934. a = filterPoints(a, a.next);
  51935. c = filterPoints(c, c.next);
  51936. // run earcut on each half
  51937. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  51938. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  51939. return;
  51940. }
  51941. b = b.next;
  51942. }
  51943. a = a.next;
  51944. } while (a !== start);
  51945. }
  51946. // link every hole into the outer loop, producing a single-ring polygon without holes
  51947. function eliminateHoles(data, holeIndices, outerNode, dim) {
  51948. var queue = [], i, len, start, end, list;
  51949. for (i = 0, len = holeIndices.length; i < len; i++) {
  51950. start = holeIndices[i] * dim;
  51951. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  51952. list = linkedList(data, start, end, dim, false);
  51953. if (list === list.next)
  51954. list.steiner = true;
  51955. queue.push(getLeftmost(list));
  51956. }
  51957. queue.sort(compareX);
  51958. // process holes from left to right
  51959. for (i = 0; i < queue.length; i++) {
  51960. eliminateHole(queue[i], outerNode);
  51961. outerNode = filterPoints(outerNode, outerNode.next);
  51962. }
  51963. return outerNode;
  51964. }
  51965. function compareX(a, b) {
  51966. return a.x - b.x;
  51967. }
  51968. // find a bridge between vertices that connects hole with an outer ring and and link it
  51969. function eliminateHole(hole, outerNode) {
  51970. outerNode = findHoleBridge(hole, outerNode);
  51971. if (outerNode) {
  51972. var b = splitPolygon(outerNode, hole);
  51973. filterPoints(b, b.next);
  51974. }
  51975. }
  51976. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  51977. function findHoleBridge(hole, outerNode) {
  51978. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  51979. // find a segment intersected by a ray from the hole's leftmost point to the left;
  51980. // segment's endpoint with lesser x will be potential connection point
  51981. do {
  51982. if (hy <= p.y && hy >= p.next.y) {
  51983. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  51984. if (x <= hx && x > qx) {
  51985. qx = x;
  51986. if (x === hx) {
  51987. if (hy === p.y)
  51988. return p;
  51989. if (hy === p.next.y)
  51990. return p.next;
  51991. }
  51992. m = p.x < p.next.x ? p : p.next;
  51993. }
  51994. }
  51995. p = p.next;
  51996. } while (p !== outerNode);
  51997. if (!m)
  51998. return null;
  51999. if (hx === qx)
  52000. return m.prev; // hole touches outer segment; pick lower endpoint
  52001. // look for points inside the triangle of hole point, segment intersection and endpoint;
  52002. // if there are no points found, we have a valid connection;
  52003. // otherwise choose the point of the minimum angle with the ray as connection point
  52004. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  52005. p = m.next;
  52006. while (p !== stop) {
  52007. if (hx >= p.x &&
  52008. p.x >= mx &&
  52009. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  52010. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  52011. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  52012. m = p;
  52013. tanMin = tan;
  52014. }
  52015. }
  52016. p = p.next;
  52017. }
  52018. return m;
  52019. }
  52020. // interlink polygon nodes in z-order
  52021. function indexCurve(start, minX, minY, size) {
  52022. var p = start;
  52023. do {
  52024. if (p.z === null)
  52025. p.z = zOrder(p.x, p.y, minX, minY, size);
  52026. p.prevZ = p.prev;
  52027. p.nextZ = p.next;
  52028. p = p.next;
  52029. } while (p !== start);
  52030. p.prevZ.nextZ = null;
  52031. p.prevZ = null;
  52032. sortLinked(p);
  52033. }
  52034. // Simon Tatham's linked list merge sort algorithm
  52035. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  52036. function sortLinked(list) {
  52037. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  52038. do {
  52039. p = list;
  52040. list = null;
  52041. tail = null;
  52042. numMerges = 0;
  52043. while (p) {
  52044. numMerges++;
  52045. q = p;
  52046. pSize = 0;
  52047. for (i = 0; i < inSize; i++) {
  52048. pSize++;
  52049. q = q.nextZ;
  52050. if (!q)
  52051. break;
  52052. }
  52053. qSize = inSize;
  52054. while (pSize > 0 || (qSize > 0 && q)) {
  52055. if (pSize === 0) {
  52056. e = q;
  52057. q = q.nextZ;
  52058. qSize--;
  52059. }
  52060. else if (qSize === 0 || !q) {
  52061. e = p;
  52062. p = p.nextZ;
  52063. pSize--;
  52064. }
  52065. else if (p.z <= q.z) {
  52066. e = p;
  52067. p = p.nextZ;
  52068. pSize--;
  52069. }
  52070. else {
  52071. e = q;
  52072. q = q.nextZ;
  52073. qSize--;
  52074. }
  52075. if (tail)
  52076. tail.nextZ = e;
  52077. else
  52078. list = e;
  52079. e.prevZ = tail;
  52080. tail = e;
  52081. }
  52082. p = q;
  52083. }
  52084. tail.nextZ = null;
  52085. inSize *= 2;
  52086. } while (numMerges > 1);
  52087. return list;
  52088. }
  52089. // z-order of a point given coords and size of the data bounding box
  52090. function zOrder(x, y, minX, minY, size) {
  52091. // coords are transformed into non-negative 15-bit integer range
  52092. x = 32767 * (x - minX) / size;
  52093. y = 32767 * (y - minY) / size;
  52094. x = (x | (x << 8)) & 0x00FF00FF;
  52095. x = (x | (x << 4)) & 0x0F0F0F0F;
  52096. x = (x | (x << 2)) & 0x33333333;
  52097. x = (x | (x << 1)) & 0x55555555;
  52098. y = (y | (y << 8)) & 0x00FF00FF;
  52099. y = (y | (y << 4)) & 0x0F0F0F0F;
  52100. y = (y | (y << 2)) & 0x33333333;
  52101. y = (y | (y << 1)) & 0x55555555;
  52102. return x | (y << 1);
  52103. }
  52104. // find the leftmost node of a polygon ring
  52105. function getLeftmost(start) {
  52106. var p = start, leftmost = start;
  52107. do {
  52108. if (p.x < leftmost.x)
  52109. leftmost = p;
  52110. p = p.next;
  52111. } while (p !== start);
  52112. return leftmost;
  52113. }
  52114. // check if a point lies within a convex triangle
  52115. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  52116. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  52117. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  52118. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  52119. }
  52120. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  52121. function isValidDiagonal(a, b) {
  52122. return a.next.i !== b.i &&
  52123. a.prev.i !== b.i &&
  52124. !intersectsPolygon(a, b) &&
  52125. locallyInside(a, b) &&
  52126. locallyInside(b, a) &&
  52127. middleInside(a, b);
  52128. }
  52129. // signed area of a triangle
  52130. function area(p, q, r) {
  52131. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  52132. }
  52133. // check if two points are equal
  52134. function equals(p1, p2) {
  52135. return p1.x === p2.x && p1.y === p2.y;
  52136. }
  52137. // check if two segments intersect
  52138. function intersects(p1, q1, p2, q2) {
  52139. if ((equals(p1, q1) && equals(p2, q2)) ||
  52140. (equals(p1, q2) && equals(p2, q1)))
  52141. return true;
  52142. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  52143. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  52144. }
  52145. // check if a polygon diagonal intersects any polygon segments
  52146. function intersectsPolygon(a, b) {
  52147. var p = a;
  52148. do {
  52149. if (p.i !== a.i &&
  52150. p.next.i !== a.i &&
  52151. p.i !== b.i &&
  52152. p.next.i !== b.i &&
  52153. intersects(p, p.next, a, b))
  52154. return true;
  52155. p = p.next;
  52156. } while (p !== a);
  52157. return false;
  52158. }
  52159. // check if a polygon diagonal is locally inside the polygon
  52160. function locallyInside(a, b) {
  52161. return area(a.prev, a, a.next) < 0
  52162. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  52163. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  52164. }
  52165. // check if the middle point of a polygon diagonal is inside the polygon
  52166. function middleInside(a, b) {
  52167. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  52168. do {
  52169. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  52170. inside = !inside;
  52171. p = p.next;
  52172. } while (p !== a);
  52173. return inside;
  52174. }
  52175. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  52176. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  52177. function splitPolygon(a, b) {
  52178. 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;
  52179. a.next = b;
  52180. b.prev = a;
  52181. a2.next = an;
  52182. an.prev = a2;
  52183. b2.next = a2;
  52184. a2.prev = b2;
  52185. bp.next = b2;
  52186. b2.prev = bp;
  52187. return b2;
  52188. }
  52189. // create a node and optionally link it with previous one (in a circular doubly linked list)
  52190. function insertNode(i, x, y, last) {
  52191. var p = new Node(i, x, y);
  52192. if (!last) {
  52193. p.prev = p;
  52194. p.next = p;
  52195. }
  52196. else {
  52197. p.next = last.next;
  52198. p.prev = last;
  52199. last.next.prev = p;
  52200. last.next = p;
  52201. }
  52202. return p;
  52203. }
  52204. function removeNode(p) {
  52205. p.next.prev = p.prev;
  52206. p.prev.next = p.next;
  52207. if (p.prevZ)
  52208. p.prevZ.nextZ = p.nextZ;
  52209. if (p.nextZ)
  52210. p.nextZ.prevZ = p.prevZ;
  52211. }
  52212. function Node(i, x, y) {
  52213. // vertice index in coordinates array
  52214. this.i = i;
  52215. // vertex coordinates
  52216. this.x = x;
  52217. this.y = y;
  52218. // previous and next vertice nodes in a polygon ring
  52219. this.prev = null;
  52220. this.next = null;
  52221. // z-order curve value
  52222. this.z = null;
  52223. // previous and next nodes in z-order
  52224. this.prevZ = null;
  52225. this.nextZ = null;
  52226. // indicates whether this is a steiner point
  52227. this.steiner = false;
  52228. }
  52229. /**
  52230. * return a percentage difference between the polygon area and its triangulation area;
  52231. * used to verify correctness of triangulation
  52232. */
  52233. function deviation(data, holeIndices, dim, triangles) {
  52234. var hasHoles = holeIndices && holeIndices.length;
  52235. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  52236. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  52237. if (hasHoles) {
  52238. for (var i = 0, len = holeIndices.length; i < len; i++) {
  52239. var start = holeIndices[i] * dim;
  52240. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  52241. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  52242. }
  52243. }
  52244. var trianglesArea = 0;
  52245. for (i = 0; i < triangles.length; i += 3) {
  52246. var a = triangles[i] * dim;
  52247. var b = triangles[i + 1] * dim;
  52248. var c = triangles[i + 2] * dim;
  52249. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  52250. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  52251. }
  52252. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  52253. }
  52254. Earcut.deviation = deviation;
  52255. ;
  52256. function signedArea(data, start, end, dim) {
  52257. var sum = 0;
  52258. for (var i = start, j = end - dim; i < end; i += dim) {
  52259. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  52260. j = i;
  52261. }
  52262. return sum;
  52263. }
  52264. /**
  52265. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  52266. */
  52267. function flatten(data) {
  52268. var dim = data[0][0].length, result = { vertices: [], holes: [], dimensions: dim }, holeIndex = 0;
  52269. for (var i = 0; i < data.length; i++) {
  52270. for (var j = 0; j < data[i].length; j++) {
  52271. for (var d = 0; d < dim; d++)
  52272. result.vertices.push(data[i][j][d]);
  52273. }
  52274. if (i > 0) {
  52275. holeIndex += data[i - 1].length;
  52276. result.holes.push(holeIndex);
  52277. }
  52278. }
  52279. return result;
  52280. }
  52281. Earcut.flatten = flatten;
  52282. ;
  52283. })(Earcut || (Earcut = {}));
  52284. var BABYLON;
  52285. (function (BABYLON) {
  52286. // Unique ID when we import meshes from Babylon to CSG
  52287. var currentCSGMeshId = 0;
  52288. // # class Vertex
  52289. // Represents a vertex of a polygon. Use your own vertex class instead of this
  52290. // one to provide additional features like texture coordinates and vertex
  52291. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  52292. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  52293. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  52294. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  52295. // is not used anywhere else.
  52296. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  52297. var Vertex = (function () {
  52298. function Vertex(pos, normal, uv) {
  52299. this.pos = pos;
  52300. this.normal = normal;
  52301. this.uv = uv;
  52302. }
  52303. Vertex.prototype.clone = function () {
  52304. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  52305. };
  52306. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  52307. // orientation of a polygon is flipped.
  52308. Vertex.prototype.flip = function () {
  52309. this.normal = this.normal.scale(-1);
  52310. };
  52311. // Create a new vertex between this vertex and `other` by linearly
  52312. // interpolating all properties using a parameter of `t`. Subclasses should
  52313. // override this to interpolate additional properties.
  52314. Vertex.prototype.interpolate = function (other, t) {
  52315. 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));
  52316. };
  52317. return Vertex;
  52318. }());
  52319. // # class Plane
  52320. // Represents a plane in 3D space.
  52321. var Plane = (function () {
  52322. function Plane(normal, w) {
  52323. this.normal = normal;
  52324. this.w = w;
  52325. }
  52326. Plane.FromPoints = function (a, b, c) {
  52327. var v0 = c.subtract(a);
  52328. var v1 = b.subtract(a);
  52329. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  52330. return null;
  52331. }
  52332. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  52333. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  52334. };
  52335. Plane.prototype.clone = function () {
  52336. return new Plane(this.normal.clone(), this.w);
  52337. };
  52338. Plane.prototype.flip = function () {
  52339. this.normal.scaleInPlace(-1);
  52340. this.w = -this.w;
  52341. };
  52342. // Split `polygon` by this plane if needed, then put the polygon or polygon
  52343. // fragments in the appropriate lists. Coplanar polygons go into either
  52344. // `coplanarFront` or `coplanarBack` depending on their orientation with
  52345. // respect to this plane. Polygons in front or in back of this plane go into
  52346. // either `front` or `back`.
  52347. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  52348. var COPLANAR = 0;
  52349. var FRONT = 1;
  52350. var BACK = 2;
  52351. var SPANNING = 3;
  52352. // Classify each point as well as the entire polygon into one of the above
  52353. // four classes.
  52354. var polygonType = 0;
  52355. var types = [];
  52356. var i;
  52357. var t;
  52358. for (i = 0; i < polygon.vertices.length; i++) {
  52359. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  52360. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  52361. polygonType |= type;
  52362. types.push(type);
  52363. }
  52364. // Put the polygon in the correct list, splitting it when necessary.
  52365. switch (polygonType) {
  52366. case COPLANAR:
  52367. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  52368. break;
  52369. case FRONT:
  52370. front.push(polygon);
  52371. break;
  52372. case BACK:
  52373. back.push(polygon);
  52374. break;
  52375. case SPANNING:
  52376. var f = [], b = [];
  52377. for (i = 0; i < polygon.vertices.length; i++) {
  52378. var j = (i + 1) % polygon.vertices.length;
  52379. var ti = types[i], tj = types[j];
  52380. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  52381. if (ti !== BACK)
  52382. f.push(vi);
  52383. if (ti !== FRONT)
  52384. b.push(ti !== BACK ? vi.clone() : vi);
  52385. if ((ti | tj) === SPANNING) {
  52386. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  52387. var v = vi.interpolate(vj, t);
  52388. f.push(v);
  52389. b.push(v.clone());
  52390. }
  52391. }
  52392. var poly;
  52393. if (f.length >= 3) {
  52394. poly = new Polygon(f, polygon.shared);
  52395. if (poly.plane)
  52396. front.push(poly);
  52397. }
  52398. if (b.length >= 3) {
  52399. poly = new Polygon(b, polygon.shared);
  52400. if (poly.plane)
  52401. back.push(poly);
  52402. }
  52403. break;
  52404. }
  52405. };
  52406. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  52407. // point is on the plane.
  52408. Plane.EPSILON = 1e-5;
  52409. return Plane;
  52410. }());
  52411. // # class Polygon
  52412. // Represents a convex polygon. The vertices used to initialize a polygon must
  52413. // be coplanar and form a convex loop.
  52414. //
  52415. // Each convex polygon has a `shared` property, which is shared between all
  52416. // polygons that are clones of each other or were split from the same polygon.
  52417. // This can be used to define per-polygon properties (such as surface color).
  52418. var Polygon = (function () {
  52419. function Polygon(vertices, shared) {
  52420. this.vertices = vertices;
  52421. this.shared = shared;
  52422. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  52423. }
  52424. Polygon.prototype.clone = function () {
  52425. var vertices = this.vertices.map(function (v) { return v.clone(); });
  52426. return new Polygon(vertices, this.shared);
  52427. };
  52428. Polygon.prototype.flip = function () {
  52429. this.vertices.reverse().map(function (v) { v.flip(); });
  52430. this.plane.flip();
  52431. };
  52432. return Polygon;
  52433. }());
  52434. // # class Node
  52435. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  52436. // by picking a polygon to split along. That polygon (and all other coplanar
  52437. // polygons) are added directly to that node and the other polygons are added to
  52438. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  52439. // no distinction between internal and leaf nodes.
  52440. var Node = (function () {
  52441. function Node(polygons) {
  52442. this.plane = null;
  52443. this.front = null;
  52444. this.back = null;
  52445. this.polygons = [];
  52446. if (polygons) {
  52447. this.build(polygons);
  52448. }
  52449. }
  52450. Node.prototype.clone = function () {
  52451. var node = new Node();
  52452. node.plane = this.plane && this.plane.clone();
  52453. node.front = this.front && this.front.clone();
  52454. node.back = this.back && this.back.clone();
  52455. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  52456. return node;
  52457. };
  52458. // Convert solid space to empty space and empty space to solid space.
  52459. Node.prototype.invert = function () {
  52460. for (var i = 0; i < this.polygons.length; i++) {
  52461. this.polygons[i].flip();
  52462. }
  52463. if (this.plane) {
  52464. this.plane.flip();
  52465. }
  52466. if (this.front) {
  52467. this.front.invert();
  52468. }
  52469. if (this.back) {
  52470. this.back.invert();
  52471. }
  52472. var temp = this.front;
  52473. this.front = this.back;
  52474. this.back = temp;
  52475. };
  52476. // Recursively remove all polygons in `polygons` that are inside this BSP
  52477. // tree.
  52478. Node.prototype.clipPolygons = function (polygons) {
  52479. if (!this.plane)
  52480. return polygons.slice();
  52481. var front = [], back = [];
  52482. for (var i = 0; i < polygons.length; i++) {
  52483. this.plane.splitPolygon(polygons[i], front, back, front, back);
  52484. }
  52485. if (this.front) {
  52486. front = this.front.clipPolygons(front);
  52487. }
  52488. if (this.back) {
  52489. back = this.back.clipPolygons(back);
  52490. }
  52491. else {
  52492. back = [];
  52493. }
  52494. return front.concat(back);
  52495. };
  52496. // Remove all polygons in this BSP tree that are inside the other BSP tree
  52497. // `bsp`.
  52498. Node.prototype.clipTo = function (bsp) {
  52499. this.polygons = bsp.clipPolygons(this.polygons);
  52500. if (this.front)
  52501. this.front.clipTo(bsp);
  52502. if (this.back)
  52503. this.back.clipTo(bsp);
  52504. };
  52505. // Return a list of all polygons in this BSP tree.
  52506. Node.prototype.allPolygons = function () {
  52507. var polygons = this.polygons.slice();
  52508. if (this.front)
  52509. polygons = polygons.concat(this.front.allPolygons());
  52510. if (this.back)
  52511. polygons = polygons.concat(this.back.allPolygons());
  52512. return polygons;
  52513. };
  52514. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  52515. // new polygons are filtered down to the bottom of the tree and become new
  52516. // nodes there. Each set of polygons is partitioned using the first polygon
  52517. // (no heuristic is used to pick a good split).
  52518. Node.prototype.build = function (polygons) {
  52519. if (!polygons.length)
  52520. return;
  52521. if (!this.plane)
  52522. this.plane = polygons[0].plane.clone();
  52523. var front = [], back = [];
  52524. for (var i = 0; i < polygons.length; i++) {
  52525. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  52526. }
  52527. if (front.length) {
  52528. if (!this.front)
  52529. this.front = new Node();
  52530. this.front.build(front);
  52531. }
  52532. if (back.length) {
  52533. if (!this.back)
  52534. this.back = new Node();
  52535. this.back.build(back);
  52536. }
  52537. };
  52538. return Node;
  52539. }());
  52540. var CSG = (function () {
  52541. function CSG() {
  52542. this.polygons = new Array();
  52543. }
  52544. // Convert BABYLON.Mesh to BABYLON.CSG
  52545. CSG.FromMesh = function (mesh) {
  52546. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  52547. var matrix, meshPosition, meshRotation, meshRotationQuaternion, meshScaling;
  52548. if (mesh instanceof BABYLON.Mesh) {
  52549. mesh.computeWorldMatrix(true);
  52550. matrix = mesh.getWorldMatrix();
  52551. meshPosition = mesh.position.clone();
  52552. meshRotation = mesh.rotation.clone();
  52553. if (mesh.rotationQuaternion) {
  52554. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  52555. }
  52556. meshScaling = mesh.scaling.clone();
  52557. }
  52558. else {
  52559. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  52560. }
  52561. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  52562. var subMeshes = mesh.subMeshes;
  52563. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  52564. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  52565. vertices = [];
  52566. for (var j = 0; j < 3; j++) {
  52567. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  52568. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  52569. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  52570. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  52571. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  52572. vertex = new Vertex(position, normal, uv);
  52573. vertices.push(vertex);
  52574. }
  52575. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  52576. // To handle the case of degenerated triangle
  52577. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  52578. if (polygon.plane)
  52579. polygons.push(polygon);
  52580. }
  52581. }
  52582. var csg = CSG.FromPolygons(polygons);
  52583. csg.matrix = matrix;
  52584. csg.position = meshPosition;
  52585. csg.rotation = meshRotation;
  52586. csg.scaling = meshScaling;
  52587. csg.rotationQuaternion = meshRotationQuaternion;
  52588. currentCSGMeshId++;
  52589. return csg;
  52590. };
  52591. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  52592. CSG.FromPolygons = function (polygons) {
  52593. var csg = new CSG();
  52594. csg.polygons = polygons;
  52595. return csg;
  52596. };
  52597. CSG.prototype.clone = function () {
  52598. var csg = new CSG();
  52599. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  52600. csg.copyTransformAttributes(this);
  52601. return csg;
  52602. };
  52603. CSG.prototype.toPolygons = function () {
  52604. return this.polygons;
  52605. };
  52606. CSG.prototype.union = function (csg) {
  52607. var a = new Node(this.clone().polygons);
  52608. var b = new Node(csg.clone().polygons);
  52609. a.clipTo(b);
  52610. b.clipTo(a);
  52611. b.invert();
  52612. b.clipTo(a);
  52613. b.invert();
  52614. a.build(b.allPolygons());
  52615. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  52616. };
  52617. CSG.prototype.unionInPlace = function (csg) {
  52618. var a = new Node(this.polygons);
  52619. var b = new Node(csg.polygons);
  52620. a.clipTo(b);
  52621. b.clipTo(a);
  52622. b.invert();
  52623. b.clipTo(a);
  52624. b.invert();
  52625. a.build(b.allPolygons());
  52626. this.polygons = a.allPolygons();
  52627. };
  52628. CSG.prototype.subtract = function (csg) {
  52629. var a = new Node(this.clone().polygons);
  52630. var b = new Node(csg.clone().polygons);
  52631. a.invert();
  52632. a.clipTo(b);
  52633. b.clipTo(a);
  52634. b.invert();
  52635. b.clipTo(a);
  52636. b.invert();
  52637. a.build(b.allPolygons());
  52638. a.invert();
  52639. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  52640. };
  52641. CSG.prototype.subtractInPlace = function (csg) {
  52642. var a = new Node(this.polygons);
  52643. var b = new Node(csg.polygons);
  52644. a.invert();
  52645. a.clipTo(b);
  52646. b.clipTo(a);
  52647. b.invert();
  52648. b.clipTo(a);
  52649. b.invert();
  52650. a.build(b.allPolygons());
  52651. a.invert();
  52652. this.polygons = a.allPolygons();
  52653. };
  52654. CSG.prototype.intersect = function (csg) {
  52655. var a = new Node(this.clone().polygons);
  52656. var b = new Node(csg.clone().polygons);
  52657. a.invert();
  52658. b.clipTo(a);
  52659. b.invert();
  52660. a.clipTo(b);
  52661. b.clipTo(a);
  52662. a.build(b.allPolygons());
  52663. a.invert();
  52664. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  52665. };
  52666. CSG.prototype.intersectInPlace = function (csg) {
  52667. var a = new Node(this.polygons);
  52668. var b = new Node(csg.polygons);
  52669. a.invert();
  52670. b.clipTo(a);
  52671. b.invert();
  52672. a.clipTo(b);
  52673. b.clipTo(a);
  52674. a.build(b.allPolygons());
  52675. a.invert();
  52676. this.polygons = a.allPolygons();
  52677. };
  52678. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  52679. // not modified.
  52680. CSG.prototype.inverse = function () {
  52681. var csg = this.clone();
  52682. csg.inverseInPlace();
  52683. return csg;
  52684. };
  52685. CSG.prototype.inverseInPlace = function () {
  52686. this.polygons.map(function (p) { p.flip(); });
  52687. };
  52688. // This is used to keep meshes transformations so they can be restored
  52689. // when we build back a Babylon Mesh
  52690. // NB : All CSG operations are performed in world coordinates
  52691. CSG.prototype.copyTransformAttributes = function (csg) {
  52692. this.matrix = csg.matrix;
  52693. this.position = csg.position;
  52694. this.rotation = csg.rotation;
  52695. this.scaling = csg.scaling;
  52696. this.rotationQuaternion = csg.rotationQuaternion;
  52697. return this;
  52698. };
  52699. // Build Raw mesh from CSG
  52700. // Coordinates here are in world space
  52701. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  52702. var matrix = this.matrix.clone();
  52703. matrix.invert();
  52704. 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;
  52705. if (keepSubMeshes) {
  52706. // Sort Polygons, since subMeshes are indices range
  52707. polygons.sort(function (a, b) {
  52708. if (a.shared.meshId === b.shared.meshId) {
  52709. return a.shared.subMeshId - b.shared.subMeshId;
  52710. }
  52711. else {
  52712. return a.shared.meshId - b.shared.meshId;
  52713. }
  52714. });
  52715. }
  52716. for (var i = 0, il = polygons.length; i < il; i++) {
  52717. polygon = polygons[i];
  52718. // Building SubMeshes
  52719. if (!subMesh_dict[polygon.shared.meshId]) {
  52720. subMesh_dict[polygon.shared.meshId] = {};
  52721. }
  52722. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  52723. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  52724. indexStart: +Infinity,
  52725. indexEnd: -Infinity,
  52726. materialIndex: polygon.shared.materialIndex
  52727. };
  52728. }
  52729. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  52730. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  52731. polygonIndices[0] = 0;
  52732. polygonIndices[1] = j - 1;
  52733. polygonIndices[2] = j;
  52734. for (var k = 0; k < 3; k++) {
  52735. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  52736. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  52737. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  52738. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  52739. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  52740. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  52741. // Check if 2 points can be merged
  52742. if (!(typeof vertex_idx !== 'undefined' &&
  52743. normals[vertex_idx * 3] === localNormal.x &&
  52744. normals[vertex_idx * 3 + 1] === localNormal.y &&
  52745. normals[vertex_idx * 3 + 2] === localNormal.z &&
  52746. uvs[vertex_idx * 2] === uv.x &&
  52747. uvs[vertex_idx * 2 + 1] === uv.y)) {
  52748. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  52749. uvs.push(uv.x, uv.y);
  52750. normals.push(normal.x, normal.y, normal.z);
  52751. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  52752. }
  52753. indices.push(vertex_idx);
  52754. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  52755. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  52756. currentIndex++;
  52757. }
  52758. }
  52759. }
  52760. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  52761. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  52762. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  52763. mesh.setIndices(indices);
  52764. if (keepSubMeshes) {
  52765. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  52766. var materialIndexOffset = 0, materialMaxIndex;
  52767. mesh.subMeshes = new Array();
  52768. for (var m in subMesh_dict) {
  52769. materialMaxIndex = -1;
  52770. for (var sm in subMesh_dict[m]) {
  52771. subMesh_obj = subMesh_dict[m][sm];
  52772. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  52773. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  52774. }
  52775. materialIndexOffset += ++materialMaxIndex;
  52776. }
  52777. }
  52778. return mesh;
  52779. };
  52780. // Build Mesh from CSG taking material and transforms into account
  52781. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  52782. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  52783. mesh.material = material;
  52784. mesh.position.copyFrom(this.position);
  52785. mesh.rotation.copyFrom(this.rotation);
  52786. if (this.rotationQuaternion) {
  52787. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  52788. }
  52789. mesh.scaling.copyFrom(this.scaling);
  52790. mesh.computeWorldMatrix(true);
  52791. return mesh;
  52792. };
  52793. return CSG;
  52794. }());
  52795. BABYLON.CSG = CSG;
  52796. })(BABYLON || (BABYLON = {}));
  52797. var BABYLON;
  52798. (function (BABYLON) {
  52799. var VRDistortionCorrectionPostProcess = (function (_super) {
  52800. __extends(VRDistortionCorrectionPostProcess, _super);
  52801. //ANY
  52802. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  52803. var _this = this;
  52804. _super.call(this, name, "vrDistortionCorrection", [
  52805. 'LensCenter',
  52806. 'Scale',
  52807. 'ScaleIn',
  52808. 'HmdWarpParam'
  52809. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
  52810. this._isRightEye = isRightEye;
  52811. this._distortionFactors = vrMetrics.distortionK;
  52812. this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  52813. this._lensCenterOffset = vrMetrics.lensCenterOffset;
  52814. this.onSizeChangedObservable.add(function () {
  52815. _this.aspectRatio = _this.width * .5 / _this.height;
  52816. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  52817. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  52818. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  52819. });
  52820. this.onApplyObservable.add(function (effect) {
  52821. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  52822. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  52823. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  52824. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  52825. });
  52826. }
  52827. return VRDistortionCorrectionPostProcess;
  52828. }(BABYLON.PostProcess));
  52829. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  52830. })(BABYLON || (BABYLON = {}));
  52831. // Mainly based on these 2 articles :
  52832. // 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
  52833. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  52834. var BABYLON;
  52835. (function (BABYLON) {
  52836. (function (JoystickAxis) {
  52837. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  52838. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  52839. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  52840. })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  52841. var JoystickAxis = BABYLON.JoystickAxis;
  52842. var VirtualJoystick = (function () {
  52843. function VirtualJoystick(leftJoystick) {
  52844. var _this = this;
  52845. if (leftJoystick) {
  52846. this._leftJoystick = true;
  52847. }
  52848. else {
  52849. this._leftJoystick = false;
  52850. }
  52851. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  52852. VirtualJoystick._globalJoystickIndex++;
  52853. // By default left & right arrow keys are moving the X
  52854. // and up & down keys are moving the Y
  52855. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  52856. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  52857. this.reverseLeftRight = false;
  52858. this.reverseUpDown = false;
  52859. // collections of pointers
  52860. this._touches = new BABYLON.StringDictionary();
  52861. this.deltaPosition = BABYLON.Vector3.Zero();
  52862. this._joystickSensibility = 25;
  52863. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  52864. this._rotationSpeed = 25;
  52865. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  52866. this._rotateOnAxisRelativeToMesh = false;
  52867. this._onResize = function (evt) {
  52868. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  52869. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  52870. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  52871. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  52872. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  52873. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  52874. };
  52875. // injecting a canvas element on top of the canvas 3D game
  52876. if (!VirtualJoystick.vjCanvas) {
  52877. window.addEventListener("resize", this._onResize, false);
  52878. VirtualJoystick.vjCanvas = document.createElement("canvas");
  52879. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  52880. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  52881. VirtualJoystick.vjCanvas.width = window.innerWidth;
  52882. VirtualJoystick.vjCanvas.height = window.innerHeight;
  52883. VirtualJoystick.vjCanvas.style.width = "100%";
  52884. VirtualJoystick.vjCanvas.style.height = "100%";
  52885. VirtualJoystick.vjCanvas.style.position = "absolute";
  52886. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  52887. VirtualJoystick.vjCanvas.style.top = "0px";
  52888. VirtualJoystick.vjCanvas.style.left = "0px";
  52889. VirtualJoystick.vjCanvas.style.zIndex = "5";
  52890. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  52891. // Support for jQuery PEP polyfill
  52892. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  52893. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  52894. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  52895. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  52896. document.body.appendChild(VirtualJoystick.vjCanvas);
  52897. }
  52898. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  52899. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  52900. this.pressed = false;
  52901. // default joystick color
  52902. this._joystickColor = "cyan";
  52903. this._joystickPointerID = -1;
  52904. // current joystick position
  52905. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  52906. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  52907. // origin joystick position
  52908. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  52909. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  52910. this._onPointerDownHandlerRef = function (evt) {
  52911. _this._onPointerDown(evt);
  52912. };
  52913. this._onPointerMoveHandlerRef = function (evt) {
  52914. _this._onPointerMove(evt);
  52915. };
  52916. this._onPointerOutHandlerRef = function (evt) {
  52917. _this._onPointerUp(evt);
  52918. };
  52919. this._onPointerUpHandlerRef = function (evt) {
  52920. _this._onPointerUp(evt);
  52921. };
  52922. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  52923. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  52924. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  52925. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  52926. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  52927. evt.preventDefault(); // Disables system menu
  52928. }, false);
  52929. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  52930. }
  52931. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  52932. this._joystickSensibility = newJoystickSensibility;
  52933. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  52934. };
  52935. VirtualJoystick.prototype._onPointerDown = function (e) {
  52936. var positionOnScreenCondition;
  52937. e.preventDefault();
  52938. if (this._leftJoystick === true) {
  52939. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  52940. }
  52941. else {
  52942. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  52943. }
  52944. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  52945. // First contact will be dedicated to the virtual joystick
  52946. this._joystickPointerID = e.pointerId;
  52947. this._joystickPointerStartPos.x = e.clientX;
  52948. this._joystickPointerStartPos.y = e.clientY;
  52949. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  52950. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  52951. this._deltaJoystickVector.x = 0;
  52952. this._deltaJoystickVector.y = 0;
  52953. this.pressed = true;
  52954. this._touches.add(e.pointerId.toString(), e);
  52955. }
  52956. else {
  52957. // You can only trigger the action buttons with a joystick declared
  52958. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  52959. this._action();
  52960. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  52961. }
  52962. }
  52963. };
  52964. VirtualJoystick.prototype._onPointerMove = function (e) {
  52965. // If the current pointer is the one associated to the joystick (first touch contact)
  52966. if (this._joystickPointerID == e.pointerId) {
  52967. this._joystickPointerPos.x = e.clientX;
  52968. this._joystickPointerPos.y = e.clientY;
  52969. this._deltaJoystickVector = this._joystickPointerPos.clone();
  52970. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  52971. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  52972. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  52973. switch (this._axisTargetedByLeftAndRight) {
  52974. case JoystickAxis.X:
  52975. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  52976. break;
  52977. case JoystickAxis.Y:
  52978. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  52979. break;
  52980. case JoystickAxis.Z:
  52981. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  52982. break;
  52983. }
  52984. var directionUpDown = this.reverseUpDown ? 1 : -1;
  52985. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  52986. switch (this._axisTargetedByUpAndDown) {
  52987. case JoystickAxis.X:
  52988. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  52989. break;
  52990. case JoystickAxis.Y:
  52991. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  52992. break;
  52993. case JoystickAxis.Z:
  52994. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  52995. break;
  52996. }
  52997. }
  52998. else {
  52999. var data = this._touches.get(e.pointerId.toString());
  53000. if (data) {
  53001. data.x = e.clientX;
  53002. data.y = e.clientY;
  53003. }
  53004. }
  53005. };
  53006. VirtualJoystick.prototype._onPointerUp = function (e) {
  53007. if (this._joystickPointerID == e.pointerId) {
  53008. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 63, this._joystickPointerStartPos.y - 63, 126, 126);
  53009. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 41, this._joystickPreviousPointerPos.y - 41, 82, 82);
  53010. this._joystickPointerID = -1;
  53011. this.pressed = false;
  53012. }
  53013. else {
  53014. var touch = this._touches.get(e.pointerId.toString());
  53015. if (touch) {
  53016. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  53017. }
  53018. }
  53019. this._deltaJoystickVector.x = 0;
  53020. this._deltaJoystickVector.y = 0;
  53021. this._touches.remove(e.pointerId.toString());
  53022. };
  53023. /**
  53024. * Change the color of the virtual joystick
  53025. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  53026. */
  53027. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  53028. this._joystickColor = newColor;
  53029. };
  53030. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  53031. this._action = action;
  53032. };
  53033. // Define which axis you'd like to control for left & right
  53034. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  53035. switch (axis) {
  53036. case JoystickAxis.X:
  53037. case JoystickAxis.Y:
  53038. case JoystickAxis.Z:
  53039. this._axisTargetedByLeftAndRight = axis;
  53040. break;
  53041. default:
  53042. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  53043. break;
  53044. }
  53045. };
  53046. // Define which axis you'd like to control for up & down
  53047. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  53048. switch (axis) {
  53049. case JoystickAxis.X:
  53050. case JoystickAxis.Y:
  53051. case JoystickAxis.Z:
  53052. this._axisTargetedByUpAndDown = axis;
  53053. break;
  53054. default:
  53055. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  53056. break;
  53057. }
  53058. };
  53059. VirtualJoystick.prototype._clearCanvas = function () {
  53060. if (this._leftJoystick) {
  53061. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  53062. }
  53063. else {
  53064. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  53065. }
  53066. };
  53067. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  53068. var _this = this;
  53069. if (this.pressed) {
  53070. this._touches.forEach(function (touch) {
  53071. if (touch.pointerId === _this._joystickPointerID) {
  53072. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 63, _this._joystickPointerStartPos.y - 63, 126, 126);
  53073. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 41, _this._joystickPreviousPointerPos.y - 41, 82, 82);
  53074. VirtualJoystick.vjCanvasContext.beginPath();
  53075. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  53076. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  53077. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  53078. VirtualJoystick.vjCanvasContext.stroke();
  53079. VirtualJoystick.vjCanvasContext.closePath();
  53080. VirtualJoystick.vjCanvasContext.beginPath();
  53081. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  53082. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  53083. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  53084. VirtualJoystick.vjCanvasContext.stroke();
  53085. VirtualJoystick.vjCanvasContext.closePath();
  53086. VirtualJoystick.vjCanvasContext.beginPath();
  53087. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  53088. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  53089. VirtualJoystick.vjCanvasContext.stroke();
  53090. VirtualJoystick.vjCanvasContext.closePath();
  53091. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  53092. }
  53093. else {
  53094. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  53095. VirtualJoystick.vjCanvasContext.beginPath();
  53096. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  53097. VirtualJoystick.vjCanvasContext.beginPath();
  53098. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  53099. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  53100. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  53101. VirtualJoystick.vjCanvasContext.stroke();
  53102. VirtualJoystick.vjCanvasContext.closePath();
  53103. touch.prevX = touch.x;
  53104. touch.prevY = touch.y;
  53105. }
  53106. ;
  53107. });
  53108. }
  53109. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  53110. };
  53111. VirtualJoystick.prototype.releaseCanvas = function () {
  53112. if (VirtualJoystick.vjCanvas) {
  53113. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  53114. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  53115. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  53116. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  53117. window.removeEventListener("resize", this._onResize);
  53118. document.body.removeChild(VirtualJoystick.vjCanvas);
  53119. VirtualJoystick.vjCanvas = null;
  53120. }
  53121. };
  53122. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  53123. VirtualJoystick._globalJoystickIndex = 0;
  53124. return VirtualJoystick;
  53125. }());
  53126. BABYLON.VirtualJoystick = VirtualJoystick;
  53127. })(BABYLON || (BABYLON = {}));
  53128. var BABYLON;
  53129. (function (BABYLON) {
  53130. // We're mainly based on the logic defined into the FreeCamera code
  53131. var VirtualJoysticksCamera = (function (_super) {
  53132. __extends(VirtualJoysticksCamera, _super);
  53133. function VirtualJoysticksCamera(name, position, scene) {
  53134. _super.call(this, name, position, scene);
  53135. this.inputs.addVirtualJoystick();
  53136. }
  53137. return VirtualJoysticksCamera;
  53138. }(BABYLON.FreeCamera));
  53139. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  53140. })(BABYLON || (BABYLON = {}));
  53141. var BABYLON;
  53142. (function (BABYLON) {
  53143. var FreeCameraVirtualJoystickInput = (function () {
  53144. function FreeCameraVirtualJoystickInput() {
  53145. }
  53146. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  53147. return this._leftjoystick;
  53148. };
  53149. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  53150. return this._rightjoystick;
  53151. };
  53152. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  53153. if (this._leftjoystick) {
  53154. var camera = this.camera;
  53155. var speed = camera._computeLocalCameraSpeed() * 50;
  53156. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  53157. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  53158. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  53159. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  53160. if (!this._leftjoystick.pressed) {
  53161. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  53162. }
  53163. if (!this._rightjoystick.pressed) {
  53164. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  53165. }
  53166. }
  53167. };
  53168. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  53169. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  53170. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  53171. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  53172. this._leftjoystick.setJoystickSensibility(0.15);
  53173. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  53174. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  53175. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  53176. this._rightjoystick.reverseUpDown = true;
  53177. this._rightjoystick.setJoystickSensibility(0.05);
  53178. this._rightjoystick.setJoystickColor("yellow");
  53179. };
  53180. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  53181. this._leftjoystick.releaseCanvas();
  53182. this._rightjoystick.releaseCanvas();
  53183. };
  53184. FreeCameraVirtualJoystickInput.prototype.getTypeName = function () {
  53185. return "FreeCameraVirtualJoystickInput";
  53186. };
  53187. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  53188. return "virtualJoystick";
  53189. };
  53190. return FreeCameraVirtualJoystickInput;
  53191. }());
  53192. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  53193. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  53194. })(BABYLON || (BABYLON = {}));
  53195. var BABYLON;
  53196. (function (BABYLON) {
  53197. var AnaglyphPostProcess = (function (_super) {
  53198. __extends(AnaglyphPostProcess, _super);
  53199. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  53200. var _this = this;
  53201. _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable);
  53202. this._passedProcess = rigCameras[0]._rigPostProcess;
  53203. this.onApplyObservable.add(function (effect) {
  53204. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  53205. });
  53206. }
  53207. return AnaglyphPostProcess;
  53208. }(BABYLON.PostProcess));
  53209. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  53210. })(BABYLON || (BABYLON = {}));
  53211. var BABYLON;
  53212. (function (BABYLON) {
  53213. var OutlineRenderer = (function () {
  53214. function OutlineRenderer(scene) {
  53215. this._scene = scene;
  53216. }
  53217. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  53218. var _this = this;
  53219. if (useOverlay === void 0) { useOverlay = false; }
  53220. var scene = this._scene;
  53221. var engine = this._scene.getEngine();
  53222. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  53223. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  53224. return;
  53225. }
  53226. var mesh = subMesh.getRenderingMesh();
  53227. var material = subMesh.getMaterial();
  53228. engine.enableEffect(this._effect);
  53229. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  53230. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  53231. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  53232. // Bones
  53233. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  53234. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  53235. }
  53236. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  53237. // Alpha test
  53238. if (material && material.needAlphaTesting()) {
  53239. var alphaTexture = material.getAlphaTestTexture();
  53240. this._effect.setTexture("diffuseSampler", alphaTexture);
  53241. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  53242. }
  53243. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  53244. };
  53245. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  53246. var defines = [];
  53247. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  53248. var mesh = subMesh.getMesh();
  53249. var material = subMesh.getMaterial();
  53250. // Alpha test
  53251. if (material && material.needAlphaTesting()) {
  53252. defines.push("#define ALPHATEST");
  53253. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  53254. attribs.push(BABYLON.VertexBuffer.UVKind);
  53255. defines.push("#define UV1");
  53256. }
  53257. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  53258. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  53259. defines.push("#define UV2");
  53260. }
  53261. }
  53262. // Bones
  53263. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  53264. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  53265. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  53266. if (mesh.numBoneInfluencers > 4) {
  53267. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  53268. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  53269. }
  53270. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  53271. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  53272. }
  53273. else {
  53274. defines.push("#define NUM_BONE_INFLUENCERS 0");
  53275. }
  53276. // Instances
  53277. if (useInstances) {
  53278. defines.push("#define INSTANCES");
  53279. attribs.push("world0");
  53280. attribs.push("world1");
  53281. attribs.push("world2");
  53282. attribs.push("world3");
  53283. }
  53284. // Get correct effect
  53285. var join = defines.join("\n");
  53286. if (this._cachedDefines !== join) {
  53287. this._cachedDefines = join;
  53288. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  53289. }
  53290. return this._effect.isReady();
  53291. };
  53292. return OutlineRenderer;
  53293. }());
  53294. BABYLON.OutlineRenderer = OutlineRenderer;
  53295. })(BABYLON || (BABYLON = {}));
  53296. var BABYLON;
  53297. (function (BABYLON) {
  53298. var MeshAssetTask = (function () {
  53299. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  53300. this.name = name;
  53301. this.meshesNames = meshesNames;
  53302. this.rootUrl = rootUrl;
  53303. this.sceneFilename = sceneFilename;
  53304. this.isCompleted = false;
  53305. }
  53306. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  53307. var _this = this;
  53308. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  53309. _this.loadedMeshes = meshes;
  53310. _this.loadedParticleSystems = particleSystems;
  53311. _this.loadedSkeletons = skeletons;
  53312. _this.isCompleted = true;
  53313. if (_this.onSuccess) {
  53314. _this.onSuccess(_this);
  53315. }
  53316. onSuccess();
  53317. }, null, function () {
  53318. if (_this.onError) {
  53319. _this.onError(_this);
  53320. }
  53321. onError();
  53322. });
  53323. };
  53324. return MeshAssetTask;
  53325. }());
  53326. BABYLON.MeshAssetTask = MeshAssetTask;
  53327. var TextFileAssetTask = (function () {
  53328. function TextFileAssetTask(name, url) {
  53329. this.name = name;
  53330. this.url = url;
  53331. this.isCompleted = false;
  53332. }
  53333. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  53334. var _this = this;
  53335. BABYLON.Tools.LoadFile(this.url, function (data) {
  53336. _this.text = data;
  53337. _this.isCompleted = true;
  53338. if (_this.onSuccess) {
  53339. _this.onSuccess(_this);
  53340. }
  53341. onSuccess();
  53342. }, null, scene.database, false, function () {
  53343. if (_this.onError) {
  53344. _this.onError(_this);
  53345. }
  53346. onError();
  53347. });
  53348. };
  53349. return TextFileAssetTask;
  53350. }());
  53351. BABYLON.TextFileAssetTask = TextFileAssetTask;
  53352. var BinaryFileAssetTask = (function () {
  53353. function BinaryFileAssetTask(name, url) {
  53354. this.name = name;
  53355. this.url = url;
  53356. this.isCompleted = false;
  53357. }
  53358. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  53359. var _this = this;
  53360. BABYLON.Tools.LoadFile(this.url, function (data) {
  53361. _this.data = data;
  53362. _this.isCompleted = true;
  53363. if (_this.onSuccess) {
  53364. _this.onSuccess(_this);
  53365. }
  53366. onSuccess();
  53367. }, null, scene.database, true, function () {
  53368. if (_this.onError) {
  53369. _this.onError(_this);
  53370. }
  53371. onError();
  53372. });
  53373. };
  53374. return BinaryFileAssetTask;
  53375. }());
  53376. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  53377. var ImageAssetTask = (function () {
  53378. function ImageAssetTask(name, url) {
  53379. this.name = name;
  53380. this.url = url;
  53381. this.isCompleted = false;
  53382. }
  53383. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  53384. var _this = this;
  53385. var img = new Image();
  53386. BABYLON.Tools.SetCorsBehavior(this.url, img);
  53387. img.onload = function () {
  53388. _this.image = img;
  53389. _this.isCompleted = true;
  53390. if (_this.onSuccess) {
  53391. _this.onSuccess(_this);
  53392. }
  53393. onSuccess();
  53394. };
  53395. img.onerror = function () {
  53396. if (_this.onError) {
  53397. _this.onError(_this);
  53398. }
  53399. onError();
  53400. };
  53401. img.src = this.url;
  53402. };
  53403. return ImageAssetTask;
  53404. }());
  53405. BABYLON.ImageAssetTask = ImageAssetTask;
  53406. var TextureAssetTask = (function () {
  53407. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  53408. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  53409. this.name = name;
  53410. this.url = url;
  53411. this.noMipmap = noMipmap;
  53412. this.invertY = invertY;
  53413. this.samplingMode = samplingMode;
  53414. this.isCompleted = false;
  53415. }
  53416. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  53417. var _this = this;
  53418. var onload = function () {
  53419. _this.isCompleted = true;
  53420. if (_this.onSuccess) {
  53421. _this.onSuccess(_this);
  53422. }
  53423. onSuccess();
  53424. };
  53425. var onerror = function () {
  53426. if (_this.onError) {
  53427. _this.onError(_this);
  53428. }
  53429. onError();
  53430. };
  53431. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  53432. };
  53433. return TextureAssetTask;
  53434. }());
  53435. BABYLON.TextureAssetTask = TextureAssetTask;
  53436. var AssetsManager = (function () {
  53437. function AssetsManager(scene) {
  53438. this.tasks = new Array();
  53439. this.waitingTasksCount = 0;
  53440. this.useDefaultLoadingScreen = true;
  53441. this._scene = scene;
  53442. }
  53443. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  53444. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  53445. this.tasks.push(task);
  53446. return task;
  53447. };
  53448. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  53449. var task = new TextFileAssetTask(taskName, url);
  53450. this.tasks.push(task);
  53451. return task;
  53452. };
  53453. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  53454. var task = new BinaryFileAssetTask(taskName, url);
  53455. this.tasks.push(task);
  53456. return task;
  53457. };
  53458. AssetsManager.prototype.addImageTask = function (taskName, url) {
  53459. var task = new ImageAssetTask(taskName, url);
  53460. this.tasks.push(task);
  53461. return task;
  53462. };
  53463. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  53464. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  53465. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  53466. this.tasks.push(task);
  53467. return task;
  53468. };
  53469. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  53470. this.waitingTasksCount--;
  53471. if (this.waitingTasksCount === 0) {
  53472. if (this.onFinish) {
  53473. this.onFinish(this.tasks);
  53474. }
  53475. this._scene.getEngine().hideLoadingUI();
  53476. }
  53477. };
  53478. AssetsManager.prototype._runTask = function (task) {
  53479. var _this = this;
  53480. task.run(this._scene, function () {
  53481. if (_this.onTaskSuccess) {
  53482. _this.onTaskSuccess(task);
  53483. }
  53484. _this._decreaseWaitingTasksCount();
  53485. }, function () {
  53486. if (_this.onTaskError) {
  53487. _this.onTaskError(task);
  53488. }
  53489. _this._decreaseWaitingTasksCount();
  53490. });
  53491. };
  53492. AssetsManager.prototype.reset = function () {
  53493. this.tasks = new Array();
  53494. return this;
  53495. };
  53496. AssetsManager.prototype.load = function () {
  53497. this.waitingTasksCount = this.tasks.length;
  53498. if (this.waitingTasksCount === 0) {
  53499. if (this.onFinish) {
  53500. this.onFinish(this.tasks);
  53501. }
  53502. return this;
  53503. }
  53504. if (this.useDefaultLoadingScreen) {
  53505. this._scene.getEngine().displayLoadingUI();
  53506. }
  53507. for (var index = 0; index < this.tasks.length; index++) {
  53508. var task = this.tasks[index];
  53509. this._runTask(task);
  53510. }
  53511. return this;
  53512. };
  53513. return AssetsManager;
  53514. }());
  53515. BABYLON.AssetsManager = AssetsManager;
  53516. })(BABYLON || (BABYLON = {}));
  53517. var BABYLON;
  53518. (function (BABYLON) {
  53519. var VRCameraMetrics = (function () {
  53520. function VRCameraMetrics() {
  53521. this.compensateDistortion = true;
  53522. }
  53523. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  53524. get: function () {
  53525. return this.hResolution / (2 * this.vResolution);
  53526. },
  53527. enumerable: true,
  53528. configurable: true
  53529. });
  53530. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  53531. get: function () {
  53532. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  53533. },
  53534. enumerable: true,
  53535. configurable: true
  53536. });
  53537. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  53538. get: function () {
  53539. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  53540. var h = (4 * meters) / this.hScreenSize;
  53541. return BABYLON.Matrix.Translation(h, 0, 0);
  53542. },
  53543. enumerable: true,
  53544. configurable: true
  53545. });
  53546. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  53547. get: function () {
  53548. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  53549. var h = (4 * meters) / this.hScreenSize;
  53550. return BABYLON.Matrix.Translation(-h, 0, 0);
  53551. },
  53552. enumerable: true,
  53553. configurable: true
  53554. });
  53555. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  53556. get: function () {
  53557. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  53558. },
  53559. enumerable: true,
  53560. configurable: true
  53561. });
  53562. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  53563. get: function () {
  53564. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  53565. },
  53566. enumerable: true,
  53567. configurable: true
  53568. });
  53569. VRCameraMetrics.GetDefault = function () {
  53570. var result = new VRCameraMetrics();
  53571. result.hResolution = 1280;
  53572. result.vResolution = 800;
  53573. result.hScreenSize = 0.149759993;
  53574. result.vScreenSize = 0.0935999975;
  53575. result.vScreenCenter = 0.0467999987,
  53576. result.eyeToScreenDistance = 0.0410000011;
  53577. result.lensSeparationDistance = 0.0635000020;
  53578. result.interpupillaryDistance = 0.0640000030;
  53579. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  53580. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  53581. result.postProcessScaleFactor = 1.714605507808412;
  53582. result.lensCenterOffset = 0.151976421;
  53583. return result;
  53584. };
  53585. return VRCameraMetrics;
  53586. }());
  53587. BABYLON.VRCameraMetrics = VRCameraMetrics;
  53588. })(BABYLON || (BABYLON = {}));
  53589. var BABYLON;
  53590. (function (BABYLON) {
  53591. var WebVRFreeCamera = (function (_super) {
  53592. __extends(WebVRFreeCamera, _super);
  53593. function WebVRFreeCamera(name, position, scene, compensateDistortion, webVROptions) {
  53594. var _this = this;
  53595. if (compensateDistortion === void 0) { compensateDistortion = false; }
  53596. if (webVROptions === void 0) { webVROptions = {}; }
  53597. _super.call(this, name, position, scene);
  53598. this.webVROptions = webVROptions;
  53599. this._vrDevice = null;
  53600. this._cacheState = null;
  53601. this._vrEnabled = false;
  53602. //enable VR
  53603. this.getEngine().initWebVR();
  53604. if (!this.getEngine().vrDisplaysPromise) {
  53605. BABYLON.Tools.Error("WebVR is not enabled on your browser");
  53606. }
  53607. else {
  53608. //TODO get the metrics updated using the device's eye parameters!
  53609. //TODO also check that the device has the right capabilities!
  53610. this.getEngine().vrDisplaysPromise.then(function (devices) {
  53611. if (devices.length > 0) {
  53612. _this._vrEnabled = true;
  53613. if (_this.webVROptions.displayName) {
  53614. var found = devices.some(function (device) {
  53615. if (device.displayName === _this.webVROptions.displayName) {
  53616. _this._vrDevice = device;
  53617. return true;
  53618. }
  53619. else {
  53620. return false;
  53621. }
  53622. });
  53623. if (!found) {
  53624. _this._vrDevice = devices[0];
  53625. BABYLON.Tools.Warn("Display " + _this.webVROptions.displayName + " was not found. Using " + _this._vrDevice.displayName);
  53626. }
  53627. }
  53628. else {
  53629. //choose the first one
  53630. _this._vrDevice = devices[0];
  53631. }
  53632. //reset the rig parameters.
  53633. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { vrDisplay: _this._vrDevice });
  53634. }
  53635. else {
  53636. BABYLON.Tools.Error("No WebVR devices found!");
  53637. }
  53638. });
  53639. }
  53640. this.rotationQuaternion = new BABYLON.Quaternion();
  53641. this._quaternionCache = new BABYLON.Quaternion();
  53642. }
  53643. WebVRFreeCamera.prototype._checkInputs = function () {
  53644. if (this._vrEnabled) {
  53645. var currentPost = this._vrDevice.getPose();
  53646. //make sure we have data
  53647. if (currentPost && currentPost.orientation) {
  53648. this._cacheState = currentPost;
  53649. this.rotationQuaternion.copyFromFloats(this._cacheState.orientation[0], this._cacheState.orientation[1], this._cacheState.orientation[2], this._cacheState.orientation[3]);
  53650. if (this.webVROptions.trackPosition && this._cacheState.position) {
  53651. this.position.copyFromFloats(this._cacheState.position[0], this._cacheState.position[1], -this._cacheState.position[2]);
  53652. this.webVROptions.positionScale && this.position.scaleInPlace(this.webVROptions.positionScale);
  53653. }
  53654. //Flip in XY plane
  53655. this.rotationQuaternion.z *= -1;
  53656. this.rotationQuaternion.w *= -1;
  53657. }
  53658. }
  53659. _super.prototype._checkInputs.call(this);
  53660. };
  53661. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  53662. _super.prototype.attachControl.call(this, element, noPreventDefault);
  53663. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  53664. if (this._vrEnabled) {
  53665. this.getEngine().enableVR(this._vrDevice);
  53666. }
  53667. };
  53668. WebVRFreeCamera.prototype.detachControl = function (element) {
  53669. _super.prototype.detachControl.call(this, element);
  53670. this._vrEnabled = false;
  53671. this.getEngine().disableVR();
  53672. };
  53673. WebVRFreeCamera.prototype.requestVRFullscreen = function (requestPointerlock) {
  53674. //Backwards comp.
  53675. BABYLON.Tools.Warn("requestVRFullscreen is deprecated. call attachControl() to start sending frames to the VR display.");
  53676. //this.getEngine().switchFullscreen(requestPointerlock);
  53677. };
  53678. WebVRFreeCamera.prototype.getTypeName = function () {
  53679. return "WebVRFreeCamera";
  53680. };
  53681. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  53682. //uses the vrDisplay's "resetPose()".
  53683. //pitch and roll won't be affected.
  53684. this._vrDevice.resetPose();
  53685. };
  53686. return WebVRFreeCamera;
  53687. }(BABYLON.FreeCamera));
  53688. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  53689. })(BABYLON || (BABYLON = {}));
  53690. var BABYLON;
  53691. (function (BABYLON) {
  53692. // Standard optimizations
  53693. var SceneOptimization = (function () {
  53694. function SceneOptimization(priority) {
  53695. if (priority === void 0) { priority = 0; }
  53696. this.priority = priority;
  53697. this.apply = function (scene) {
  53698. return true; // Return true if everything that can be done was applied
  53699. };
  53700. }
  53701. return SceneOptimization;
  53702. }());
  53703. BABYLON.SceneOptimization = SceneOptimization;
  53704. var TextureOptimization = (function (_super) {
  53705. __extends(TextureOptimization, _super);
  53706. function TextureOptimization(priority, maximumSize) {
  53707. var _this = this;
  53708. if (priority === void 0) { priority = 0; }
  53709. if (maximumSize === void 0) { maximumSize = 1024; }
  53710. _super.call(this, priority);
  53711. this.priority = priority;
  53712. this.maximumSize = maximumSize;
  53713. this.apply = function (scene) {
  53714. var allDone = true;
  53715. for (var index = 0; index < scene.textures.length; index++) {
  53716. var texture = scene.textures[index];
  53717. if (!texture.canRescale) {
  53718. continue;
  53719. }
  53720. var currentSize = texture.getSize();
  53721. var maxDimension = Math.max(currentSize.width, currentSize.height);
  53722. if (maxDimension > _this.maximumSize) {
  53723. texture.scale(0.5);
  53724. allDone = false;
  53725. }
  53726. }
  53727. return allDone;
  53728. };
  53729. }
  53730. return TextureOptimization;
  53731. }(SceneOptimization));
  53732. BABYLON.TextureOptimization = TextureOptimization;
  53733. var HardwareScalingOptimization = (function (_super) {
  53734. __extends(HardwareScalingOptimization, _super);
  53735. function HardwareScalingOptimization(priority, maximumScale) {
  53736. var _this = this;
  53737. if (priority === void 0) { priority = 0; }
  53738. if (maximumScale === void 0) { maximumScale = 2; }
  53739. _super.call(this, priority);
  53740. this.priority = priority;
  53741. this.maximumScale = maximumScale;
  53742. this._currentScale = 1;
  53743. this.apply = function (scene) {
  53744. _this._currentScale++;
  53745. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  53746. return _this._currentScale >= _this.maximumScale;
  53747. };
  53748. }
  53749. return HardwareScalingOptimization;
  53750. }(SceneOptimization));
  53751. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  53752. var ShadowsOptimization = (function (_super) {
  53753. __extends(ShadowsOptimization, _super);
  53754. function ShadowsOptimization() {
  53755. _super.apply(this, arguments);
  53756. this.apply = function (scene) {
  53757. scene.shadowsEnabled = false;
  53758. return true;
  53759. };
  53760. }
  53761. return ShadowsOptimization;
  53762. }(SceneOptimization));
  53763. BABYLON.ShadowsOptimization = ShadowsOptimization;
  53764. var PostProcessesOptimization = (function (_super) {
  53765. __extends(PostProcessesOptimization, _super);
  53766. function PostProcessesOptimization() {
  53767. _super.apply(this, arguments);
  53768. this.apply = function (scene) {
  53769. scene.postProcessesEnabled = false;
  53770. return true;
  53771. };
  53772. }
  53773. return PostProcessesOptimization;
  53774. }(SceneOptimization));
  53775. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  53776. var LensFlaresOptimization = (function (_super) {
  53777. __extends(LensFlaresOptimization, _super);
  53778. function LensFlaresOptimization() {
  53779. _super.apply(this, arguments);
  53780. this.apply = function (scene) {
  53781. scene.lensFlaresEnabled = false;
  53782. return true;
  53783. };
  53784. }
  53785. return LensFlaresOptimization;
  53786. }(SceneOptimization));
  53787. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  53788. var ParticlesOptimization = (function (_super) {
  53789. __extends(ParticlesOptimization, _super);
  53790. function ParticlesOptimization() {
  53791. _super.apply(this, arguments);
  53792. this.apply = function (scene) {
  53793. scene.particlesEnabled = false;
  53794. return true;
  53795. };
  53796. }
  53797. return ParticlesOptimization;
  53798. }(SceneOptimization));
  53799. BABYLON.ParticlesOptimization = ParticlesOptimization;
  53800. var RenderTargetsOptimization = (function (_super) {
  53801. __extends(RenderTargetsOptimization, _super);
  53802. function RenderTargetsOptimization() {
  53803. _super.apply(this, arguments);
  53804. this.apply = function (scene) {
  53805. scene.renderTargetsEnabled = false;
  53806. return true;
  53807. };
  53808. }
  53809. return RenderTargetsOptimization;
  53810. }(SceneOptimization));
  53811. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  53812. var MergeMeshesOptimization = (function (_super) {
  53813. __extends(MergeMeshesOptimization, _super);
  53814. function MergeMeshesOptimization() {
  53815. var _this = this;
  53816. _super.apply(this, arguments);
  53817. this._canBeMerged = function (abstractMesh) {
  53818. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  53819. return false;
  53820. }
  53821. var mesh = abstractMesh;
  53822. if (!mesh.isVisible || !mesh.isEnabled()) {
  53823. return false;
  53824. }
  53825. if (mesh.instances.length > 0) {
  53826. return false;
  53827. }
  53828. if (mesh.skeleton || mesh.hasLODLevels) {
  53829. return false;
  53830. }
  53831. if (mesh.parent) {
  53832. return false;
  53833. }
  53834. return true;
  53835. };
  53836. this.apply = function (scene, updateSelectionTree) {
  53837. var globalPool = scene.meshes.slice(0);
  53838. var globalLength = globalPool.length;
  53839. for (var index = 0; index < globalLength; index++) {
  53840. var currentPool = new Array();
  53841. var current = globalPool[index];
  53842. // Checks
  53843. if (!_this._canBeMerged(current)) {
  53844. continue;
  53845. }
  53846. currentPool.push(current);
  53847. // Find compatible meshes
  53848. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  53849. var otherMesh = globalPool[subIndex];
  53850. if (!_this._canBeMerged(otherMesh)) {
  53851. continue;
  53852. }
  53853. if (otherMesh.material !== current.material) {
  53854. continue;
  53855. }
  53856. if (otherMesh.checkCollisions !== current.checkCollisions) {
  53857. continue;
  53858. }
  53859. currentPool.push(otherMesh);
  53860. globalLength--;
  53861. globalPool.splice(subIndex, 1);
  53862. subIndex--;
  53863. }
  53864. if (currentPool.length < 2) {
  53865. continue;
  53866. }
  53867. // Merge meshes
  53868. BABYLON.Mesh.MergeMeshes(currentPool);
  53869. }
  53870. if (updateSelectionTree != undefined) {
  53871. if (updateSelectionTree) {
  53872. scene.createOrUpdateSelectionOctree();
  53873. }
  53874. }
  53875. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  53876. scene.createOrUpdateSelectionOctree();
  53877. }
  53878. return true;
  53879. };
  53880. }
  53881. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  53882. get: function () {
  53883. return MergeMeshesOptimization._UpdateSelectionTree;
  53884. },
  53885. set: function (value) {
  53886. MergeMeshesOptimization._UpdateSelectionTree = value;
  53887. },
  53888. enumerable: true,
  53889. configurable: true
  53890. });
  53891. MergeMeshesOptimization._UpdateSelectionTree = false;
  53892. return MergeMeshesOptimization;
  53893. }(SceneOptimization));
  53894. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  53895. // Options
  53896. var SceneOptimizerOptions = (function () {
  53897. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  53898. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  53899. if (trackerDuration === void 0) { trackerDuration = 2000; }
  53900. this.targetFrameRate = targetFrameRate;
  53901. this.trackerDuration = trackerDuration;
  53902. this.optimizations = new Array();
  53903. }
  53904. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  53905. var result = new SceneOptimizerOptions(targetFrameRate);
  53906. var priority = 0;
  53907. result.optimizations.push(new MergeMeshesOptimization(priority));
  53908. result.optimizations.push(new ShadowsOptimization(priority));
  53909. result.optimizations.push(new LensFlaresOptimization(priority));
  53910. // Next priority
  53911. priority++;
  53912. result.optimizations.push(new PostProcessesOptimization(priority));
  53913. result.optimizations.push(new ParticlesOptimization(priority));
  53914. // Next priority
  53915. priority++;
  53916. result.optimizations.push(new TextureOptimization(priority, 1024));
  53917. return result;
  53918. };
  53919. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  53920. var result = new SceneOptimizerOptions(targetFrameRate);
  53921. var priority = 0;
  53922. result.optimizations.push(new MergeMeshesOptimization(priority));
  53923. result.optimizations.push(new ShadowsOptimization(priority));
  53924. result.optimizations.push(new LensFlaresOptimization(priority));
  53925. // Next priority
  53926. priority++;
  53927. result.optimizations.push(new PostProcessesOptimization(priority));
  53928. result.optimizations.push(new ParticlesOptimization(priority));
  53929. // Next priority
  53930. priority++;
  53931. result.optimizations.push(new TextureOptimization(priority, 512));
  53932. // Next priority
  53933. priority++;
  53934. result.optimizations.push(new RenderTargetsOptimization(priority));
  53935. // Next priority
  53936. priority++;
  53937. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  53938. return result;
  53939. };
  53940. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  53941. var result = new SceneOptimizerOptions(targetFrameRate);
  53942. var priority = 0;
  53943. result.optimizations.push(new MergeMeshesOptimization(priority));
  53944. result.optimizations.push(new ShadowsOptimization(priority));
  53945. result.optimizations.push(new LensFlaresOptimization(priority));
  53946. // Next priority
  53947. priority++;
  53948. result.optimizations.push(new PostProcessesOptimization(priority));
  53949. result.optimizations.push(new ParticlesOptimization(priority));
  53950. // Next priority
  53951. priority++;
  53952. result.optimizations.push(new TextureOptimization(priority, 256));
  53953. // Next priority
  53954. priority++;
  53955. result.optimizations.push(new RenderTargetsOptimization(priority));
  53956. // Next priority
  53957. priority++;
  53958. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  53959. return result;
  53960. };
  53961. return SceneOptimizerOptions;
  53962. }());
  53963. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  53964. // Scene optimizer tool
  53965. var SceneOptimizer = (function () {
  53966. function SceneOptimizer() {
  53967. }
  53968. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  53969. // TODO: add an epsilon
  53970. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  53971. if (onSuccess) {
  53972. onSuccess();
  53973. }
  53974. return;
  53975. }
  53976. // Apply current level of optimizations
  53977. var allDone = true;
  53978. var noOptimizationApplied = true;
  53979. for (var index = 0; index < options.optimizations.length; index++) {
  53980. var optimization = options.optimizations[index];
  53981. if (optimization.priority === currentPriorityLevel) {
  53982. noOptimizationApplied = false;
  53983. allDone = allDone && optimization.apply(scene);
  53984. }
  53985. }
  53986. // If no optimization was applied, this is a failure :(
  53987. if (noOptimizationApplied) {
  53988. if (onFailure) {
  53989. onFailure();
  53990. }
  53991. return;
  53992. }
  53993. // If all optimizations were done, move to next level
  53994. if (allDone) {
  53995. currentPriorityLevel++;
  53996. }
  53997. // Let's the system running for a specific amount of time before checking FPS
  53998. scene.executeWhenReady(function () {
  53999. setTimeout(function () {
  54000. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  54001. }, options.trackerDuration);
  54002. });
  54003. };
  54004. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  54005. if (!options) {
  54006. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  54007. }
  54008. // Let's the system running for a specific amount of time before checking FPS
  54009. scene.executeWhenReady(function () {
  54010. setTimeout(function () {
  54011. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  54012. }, options.trackerDuration);
  54013. });
  54014. };
  54015. return SceneOptimizer;
  54016. }());
  54017. BABYLON.SceneOptimizer = SceneOptimizer;
  54018. })(BABYLON || (BABYLON = {}));
  54019. var BABYLON;
  54020. (function (BABYLON) {
  54021. var Internals;
  54022. (function (Internals) {
  54023. var MeshLODLevel = (function () {
  54024. function MeshLODLevel(distance, mesh) {
  54025. this.distance = distance;
  54026. this.mesh = mesh;
  54027. }
  54028. return MeshLODLevel;
  54029. }());
  54030. Internals.MeshLODLevel = MeshLODLevel;
  54031. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  54032. })(BABYLON || (BABYLON = {}));
  54033. var BABYLON;
  54034. (function (BABYLON) {
  54035. var RawTexture = (function (_super) {
  54036. __extends(RawTexture, _super);
  54037. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  54038. if (generateMipMaps === void 0) { generateMipMaps = true; }
  54039. if (invertY === void 0) { invertY = false; }
  54040. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  54041. _super.call(this, null, scene, !generateMipMaps, invertY);
  54042. this.format = format;
  54043. this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  54044. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54045. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54046. }
  54047. RawTexture.prototype.update = function (data) {
  54048. this.getScene().getEngine().updateRawTexture(this._texture, data, this.format, this._invertY);
  54049. };
  54050. // Statics
  54051. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  54052. if (generateMipMaps === void 0) { generateMipMaps = true; }
  54053. if (invertY === void 0) { invertY = false; }
  54054. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  54055. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  54056. };
  54057. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  54058. if (generateMipMaps === void 0) { generateMipMaps = true; }
  54059. if (invertY === void 0) { invertY = false; }
  54060. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  54061. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  54062. };
  54063. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  54064. if (generateMipMaps === void 0) { generateMipMaps = true; }
  54065. if (invertY === void 0) { invertY = false; }
  54066. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  54067. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  54068. };
  54069. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  54070. if (generateMipMaps === void 0) { generateMipMaps = true; }
  54071. if (invertY === void 0) { invertY = false; }
  54072. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  54073. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  54074. };
  54075. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  54076. if (generateMipMaps === void 0) { generateMipMaps = true; }
  54077. if (invertY === void 0) { invertY = false; }
  54078. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  54079. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  54080. };
  54081. return RawTexture;
  54082. }(BABYLON.Texture));
  54083. BABYLON.RawTexture = RawTexture;
  54084. })(BABYLON || (BABYLON = {}));
  54085. var BABYLON;
  54086. (function (BABYLON) {
  54087. var IndexedVector2 = (function (_super) {
  54088. __extends(IndexedVector2, _super);
  54089. function IndexedVector2(original, index) {
  54090. _super.call(this, original.x, original.y);
  54091. this.index = index;
  54092. }
  54093. return IndexedVector2;
  54094. }(BABYLON.Vector2));
  54095. var PolygonPoints = (function () {
  54096. function PolygonPoints() {
  54097. this.elements = new Array();
  54098. }
  54099. PolygonPoints.prototype.add = function (originalPoints) {
  54100. var _this = this;
  54101. var result = new Array();
  54102. originalPoints.forEach(function (point) {
  54103. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  54104. var newPoint = new IndexedVector2(point, _this.elements.length);
  54105. result.push(newPoint);
  54106. _this.elements.push(newPoint);
  54107. }
  54108. });
  54109. return result;
  54110. };
  54111. PolygonPoints.prototype.computeBounds = function () {
  54112. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  54113. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  54114. this.elements.forEach(function (point) {
  54115. // x
  54116. if (point.x < lmin.x) {
  54117. lmin.x = point.x;
  54118. }
  54119. else if (point.x > lmax.x) {
  54120. lmax.x = point.x;
  54121. }
  54122. // y
  54123. if (point.y < lmin.y) {
  54124. lmin.y = point.y;
  54125. }
  54126. else if (point.y > lmax.y) {
  54127. lmax.y = point.y;
  54128. }
  54129. });
  54130. return {
  54131. min: lmin,
  54132. max: lmax,
  54133. width: lmax.x - lmin.x,
  54134. height: lmax.y - lmin.y
  54135. };
  54136. };
  54137. return PolygonPoints;
  54138. }());
  54139. var Polygon = (function () {
  54140. function Polygon() {
  54141. }
  54142. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  54143. return [
  54144. new BABYLON.Vector2(xmin, ymin),
  54145. new BABYLON.Vector2(xmax, ymin),
  54146. new BABYLON.Vector2(xmax, ymax),
  54147. new BABYLON.Vector2(xmin, ymax)
  54148. ];
  54149. };
  54150. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  54151. if (cx === void 0) { cx = 0; }
  54152. if (cy === void 0) { cy = 0; }
  54153. if (numberOfSides === void 0) { numberOfSides = 32; }
  54154. var result = new Array();
  54155. var angle = 0;
  54156. var increment = (Math.PI * 2) / numberOfSides;
  54157. for (var i = 0; i < numberOfSides; i++) {
  54158. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  54159. angle -= increment;
  54160. }
  54161. return result;
  54162. };
  54163. Polygon.Parse = function (input) {
  54164. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  54165. var i, result = [];
  54166. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  54167. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  54168. }
  54169. return result;
  54170. };
  54171. Polygon.StartingAt = function (x, y) {
  54172. return BABYLON.Path2.StartingAt(x, y);
  54173. };
  54174. return Polygon;
  54175. }());
  54176. BABYLON.Polygon = Polygon;
  54177. var PolygonMeshBuilder = (function () {
  54178. function PolygonMeshBuilder(name, contours, scene) {
  54179. this._points = new PolygonPoints();
  54180. this._outlinepoints = new PolygonPoints();
  54181. this._holes = [];
  54182. this._epoints = new Array();
  54183. this._eholes = new Array();
  54184. this._name = name;
  54185. this._scene = scene;
  54186. var points;
  54187. if (contours instanceof BABYLON.Path2) {
  54188. points = contours.getPoints();
  54189. }
  54190. else {
  54191. points = contours;
  54192. }
  54193. this._addToepoint(points);
  54194. this._points.add(points);
  54195. this._outlinepoints.add(points);
  54196. }
  54197. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  54198. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  54199. var p = points_1[_i];
  54200. this._epoints.push(p.x, p.y);
  54201. }
  54202. };
  54203. PolygonMeshBuilder.prototype.addHole = function (hole) {
  54204. this._points.add(hole);
  54205. var holepoints = new PolygonPoints();
  54206. holepoints.add(hole);
  54207. this._holes.push(holepoints);
  54208. this._eholes.push(this._epoints.length / 2);
  54209. this._addToepoint(hole);
  54210. return this;
  54211. };
  54212. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  54213. var _this = this;
  54214. if (updatable === void 0) { updatable = false; }
  54215. var result = new BABYLON.Mesh(this._name, this._scene);
  54216. var normals = [];
  54217. var positions = [];
  54218. var uvs = [];
  54219. var bounds = this._points.computeBounds();
  54220. this._points.elements.forEach(function (p) {
  54221. normals.push(0, 1.0, 0);
  54222. positions.push(p.x, 0, p.y);
  54223. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  54224. });
  54225. var indices = [];
  54226. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  54227. for (var i = 0; i < res.length; i++) {
  54228. indices.push(res[i]);
  54229. }
  54230. if (depth > 0) {
  54231. var positionscount = (positions.length / 3); //get the current pointcount
  54232. this._points.elements.forEach(function (p) {
  54233. normals.push(0, -1.0, 0);
  54234. positions.push(p.x, -depth, p.y);
  54235. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  54236. });
  54237. var totalCount = indices.length;
  54238. for (var i = 0; i < totalCount; i += 3) {
  54239. var i0 = indices[i + 0];
  54240. var i1 = indices[i + 1];
  54241. var i2 = indices[i + 2];
  54242. indices.push(i2 + positionscount);
  54243. indices.push(i1 + positionscount);
  54244. indices.push(i0 + positionscount);
  54245. }
  54246. //Add the sides
  54247. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  54248. this._holes.forEach(function (hole) {
  54249. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  54250. });
  54251. }
  54252. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  54253. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  54254. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  54255. result.setIndices(indices);
  54256. return result;
  54257. };
  54258. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  54259. var StartIndex = positions.length / 3;
  54260. var ulength = 0;
  54261. for (var i = 0; i < points.elements.length; i++) {
  54262. var p = points.elements[i];
  54263. var p1;
  54264. if ((i + 1) > points.elements.length - 1) {
  54265. p1 = points.elements[0];
  54266. }
  54267. else {
  54268. p1 = points.elements[i + 1];
  54269. }
  54270. positions.push(p.x, 0, p.y);
  54271. positions.push(p.x, -depth, p.y);
  54272. positions.push(p1.x, 0, p1.y);
  54273. positions.push(p1.x, -depth, p1.y);
  54274. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  54275. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  54276. var v3 = v2.subtract(v1);
  54277. var v4 = new BABYLON.Vector3(0, 1, 0);
  54278. var vn = BABYLON.Vector3.Cross(v3, v4);
  54279. vn = vn.normalize();
  54280. uvs.push(ulength / bounds.width, 0);
  54281. uvs.push(ulength / bounds.width, 1);
  54282. ulength += v3.length();
  54283. uvs.push((ulength / bounds.width), 0);
  54284. uvs.push((ulength / bounds.width), 1);
  54285. if (!flip) {
  54286. normals.push(-vn.x, -vn.y, -vn.z);
  54287. normals.push(-vn.x, -vn.y, -vn.z);
  54288. normals.push(-vn.x, -vn.y, -vn.z);
  54289. normals.push(-vn.x, -vn.y, -vn.z);
  54290. indices.push(StartIndex);
  54291. indices.push(StartIndex + 1);
  54292. indices.push(StartIndex + 2);
  54293. indices.push(StartIndex + 1);
  54294. indices.push(StartIndex + 3);
  54295. indices.push(StartIndex + 2);
  54296. }
  54297. else {
  54298. normals.push(vn.x, vn.y, vn.z);
  54299. normals.push(vn.x, vn.y, vn.z);
  54300. normals.push(vn.x, vn.y, vn.z);
  54301. normals.push(vn.x, vn.y, vn.z);
  54302. indices.push(StartIndex);
  54303. indices.push(StartIndex + 2);
  54304. indices.push(StartIndex + 1);
  54305. indices.push(StartIndex + 1);
  54306. indices.push(StartIndex + 2);
  54307. indices.push(StartIndex + 3);
  54308. }
  54309. StartIndex += 4;
  54310. }
  54311. ;
  54312. };
  54313. return PolygonMeshBuilder;
  54314. }());
  54315. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  54316. })(BABYLON || (BABYLON = {}));
  54317. var BABYLON;
  54318. (function (BABYLON) {
  54319. var Octree = (function () {
  54320. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  54321. if (maxDepth === void 0) { maxDepth = 2; }
  54322. this.maxDepth = maxDepth;
  54323. this.dynamicContent = new Array();
  54324. this._maxBlockCapacity = maxBlockCapacity || 64;
  54325. this._selectionContent = new BABYLON.SmartArray(1024);
  54326. this._creationFunc = creationFunc;
  54327. }
  54328. // Methods
  54329. Octree.prototype.update = function (worldMin, worldMax, entries) {
  54330. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  54331. };
  54332. Octree.prototype.addMesh = function (entry) {
  54333. for (var index = 0; index < this.blocks.length; index++) {
  54334. var block = this.blocks[index];
  54335. block.addEntry(entry);
  54336. }
  54337. };
  54338. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  54339. this._selectionContent.reset();
  54340. for (var index = 0; index < this.blocks.length; index++) {
  54341. var block = this.blocks[index];
  54342. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  54343. }
  54344. if (allowDuplicate) {
  54345. this._selectionContent.concat(this.dynamicContent);
  54346. }
  54347. else {
  54348. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  54349. }
  54350. return this._selectionContent;
  54351. };
  54352. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  54353. this._selectionContent.reset();
  54354. for (var index = 0; index < this.blocks.length; index++) {
  54355. var block = this.blocks[index];
  54356. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  54357. }
  54358. if (allowDuplicate) {
  54359. this._selectionContent.concat(this.dynamicContent);
  54360. }
  54361. else {
  54362. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  54363. }
  54364. return this._selectionContent;
  54365. };
  54366. Octree.prototype.intersectsRay = function (ray) {
  54367. this._selectionContent.reset();
  54368. for (var index = 0; index < this.blocks.length; index++) {
  54369. var block = this.blocks[index];
  54370. block.intersectsRay(ray, this._selectionContent);
  54371. }
  54372. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  54373. return this._selectionContent;
  54374. };
  54375. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  54376. target.blocks = new Array();
  54377. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  54378. // Segmenting space
  54379. for (var x = 0; x < 2; x++) {
  54380. for (var y = 0; y < 2; y++) {
  54381. for (var z = 0; z < 2; z++) {
  54382. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  54383. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  54384. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  54385. block.addEntries(entries);
  54386. target.blocks.push(block);
  54387. }
  54388. }
  54389. }
  54390. };
  54391. Octree.CreationFuncForMeshes = function (entry, block) {
  54392. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  54393. block.entries.push(entry);
  54394. }
  54395. };
  54396. Octree.CreationFuncForSubMeshes = function (entry, block) {
  54397. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  54398. block.entries.push(entry);
  54399. }
  54400. };
  54401. return Octree;
  54402. }());
  54403. BABYLON.Octree = Octree;
  54404. })(BABYLON || (BABYLON = {}));
  54405. var BABYLON;
  54406. (function (BABYLON) {
  54407. var OctreeBlock = (function () {
  54408. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  54409. this.entries = new Array();
  54410. this._boundingVectors = new Array();
  54411. this._capacity = capacity;
  54412. this._depth = depth;
  54413. this._maxDepth = maxDepth;
  54414. this._creationFunc = creationFunc;
  54415. this._minPoint = minPoint;
  54416. this._maxPoint = maxPoint;
  54417. this._boundingVectors.push(minPoint.clone());
  54418. this._boundingVectors.push(maxPoint.clone());
  54419. this._boundingVectors.push(minPoint.clone());
  54420. this._boundingVectors[2].x = maxPoint.x;
  54421. this._boundingVectors.push(minPoint.clone());
  54422. this._boundingVectors[3].y = maxPoint.y;
  54423. this._boundingVectors.push(minPoint.clone());
  54424. this._boundingVectors[4].z = maxPoint.z;
  54425. this._boundingVectors.push(maxPoint.clone());
  54426. this._boundingVectors[5].z = minPoint.z;
  54427. this._boundingVectors.push(maxPoint.clone());
  54428. this._boundingVectors[6].x = minPoint.x;
  54429. this._boundingVectors.push(maxPoint.clone());
  54430. this._boundingVectors[7].y = minPoint.y;
  54431. }
  54432. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  54433. // Property
  54434. get: function () {
  54435. return this._capacity;
  54436. },
  54437. enumerable: true,
  54438. configurable: true
  54439. });
  54440. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  54441. get: function () {
  54442. return this._minPoint;
  54443. },
  54444. enumerable: true,
  54445. configurable: true
  54446. });
  54447. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  54448. get: function () {
  54449. return this._maxPoint;
  54450. },
  54451. enumerable: true,
  54452. configurable: true
  54453. });
  54454. // Methods
  54455. OctreeBlock.prototype.addEntry = function (entry) {
  54456. if (this.blocks) {
  54457. for (var index = 0; index < this.blocks.length; index++) {
  54458. var block = this.blocks[index];
  54459. block.addEntry(entry);
  54460. }
  54461. return;
  54462. }
  54463. this._creationFunc(entry, this);
  54464. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  54465. this.createInnerBlocks();
  54466. }
  54467. };
  54468. OctreeBlock.prototype.addEntries = function (entries) {
  54469. for (var index = 0; index < entries.length; index++) {
  54470. var mesh = entries[index];
  54471. this.addEntry(mesh);
  54472. }
  54473. };
  54474. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  54475. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  54476. if (this.blocks) {
  54477. for (var index = 0; index < this.blocks.length; index++) {
  54478. var block = this.blocks[index];
  54479. block.select(frustumPlanes, selection, allowDuplicate);
  54480. }
  54481. return;
  54482. }
  54483. if (allowDuplicate) {
  54484. selection.concat(this.entries);
  54485. }
  54486. else {
  54487. selection.concatWithNoDuplicate(this.entries);
  54488. }
  54489. }
  54490. };
  54491. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  54492. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  54493. if (this.blocks) {
  54494. for (var index = 0; index < this.blocks.length; index++) {
  54495. var block = this.blocks[index];
  54496. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  54497. }
  54498. return;
  54499. }
  54500. if (allowDuplicate) {
  54501. selection.concat(this.entries);
  54502. }
  54503. else {
  54504. selection.concatWithNoDuplicate(this.entries);
  54505. }
  54506. }
  54507. };
  54508. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  54509. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  54510. if (this.blocks) {
  54511. for (var index = 0; index < this.blocks.length; index++) {
  54512. var block = this.blocks[index];
  54513. block.intersectsRay(ray, selection);
  54514. }
  54515. return;
  54516. }
  54517. selection.concatWithNoDuplicate(this.entries);
  54518. }
  54519. };
  54520. OctreeBlock.prototype.createInnerBlocks = function () {
  54521. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  54522. };
  54523. return OctreeBlock;
  54524. }());
  54525. BABYLON.OctreeBlock = OctreeBlock;
  54526. })(BABYLON || (BABYLON = {}));
  54527. var BABYLON;
  54528. (function (BABYLON) {
  54529. var BlurPostProcess = (function (_super) {
  54530. __extends(BlurPostProcess, _super);
  54531. function BlurPostProcess(name, direction, blurWidth, options, camera, samplingMode, engine, reusable) {
  54532. var _this = this;
  54533. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  54534. _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable);
  54535. this.direction = direction;
  54536. this.blurWidth = blurWidth;
  54537. this.onApplyObservable.add(function (effect) {
  54538. effect.setFloat2("screenSize", _this.width, _this.height);
  54539. effect.setVector2("direction", _this.direction);
  54540. effect.setFloat("blurWidth", _this.blurWidth);
  54541. });
  54542. }
  54543. return BlurPostProcess;
  54544. }(BABYLON.PostProcess));
  54545. BABYLON.BlurPostProcess = BlurPostProcess;
  54546. })(BABYLON || (BABYLON = {}));
  54547. var BABYLON;
  54548. (function (BABYLON) {
  54549. var RefractionPostProcess = (function (_super) {
  54550. __extends(RefractionPostProcess, _super);
  54551. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  54552. var _this = this;
  54553. _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable);
  54554. this.color = color;
  54555. this.depth = depth;
  54556. this.colorLevel = colorLevel;
  54557. this.onActivateObservable.add(function (cam) {
  54558. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  54559. });
  54560. this.onApplyObservable.add(function (effect) {
  54561. effect.setColor3("baseColor", _this.color);
  54562. effect.setFloat("depth", _this.depth);
  54563. effect.setFloat("colorLevel", _this.colorLevel);
  54564. effect.setTexture("refractionSampler", _this._refRexture);
  54565. });
  54566. }
  54567. // Methods
  54568. RefractionPostProcess.prototype.dispose = function (camera) {
  54569. if (this._refRexture) {
  54570. this._refRexture.dispose();
  54571. }
  54572. _super.prototype.dispose.call(this, camera);
  54573. };
  54574. return RefractionPostProcess;
  54575. }(BABYLON.PostProcess));
  54576. BABYLON.RefractionPostProcess = RefractionPostProcess;
  54577. })(BABYLON || (BABYLON = {}));
  54578. var BABYLON;
  54579. (function (BABYLON) {
  54580. var BlackAndWhitePostProcess = (function (_super) {
  54581. __extends(BlackAndWhitePostProcess, _super);
  54582. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  54583. _super.call(this, name, "blackAndWhite", null, null, options, camera, samplingMode, engine, reusable);
  54584. }
  54585. return BlackAndWhitePostProcess;
  54586. }(BABYLON.PostProcess));
  54587. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  54588. })(BABYLON || (BABYLON = {}));
  54589. var BABYLON;
  54590. (function (BABYLON) {
  54591. var ConvolutionPostProcess = (function (_super) {
  54592. __extends(ConvolutionPostProcess, _super);
  54593. function ConvolutionPostProcess(name, kernel, options, camera, samplingMode, engine, reusable) {
  54594. var _this = this;
  54595. _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable);
  54596. this.kernel = kernel;
  54597. this.onApply = function (effect) {
  54598. effect.setFloat2("screenSize", _this.width, _this.height);
  54599. effect.setArray("kernel", _this.kernel);
  54600. };
  54601. }
  54602. // Statics
  54603. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  54604. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  54605. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  54606. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  54607. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  54608. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  54609. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  54610. return ConvolutionPostProcess;
  54611. }(BABYLON.PostProcess));
  54612. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  54613. })(BABYLON || (BABYLON = {}));
  54614. var BABYLON;
  54615. (function (BABYLON) {
  54616. var FilterPostProcess = (function (_super) {
  54617. __extends(FilterPostProcess, _super);
  54618. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  54619. var _this = this;
  54620. _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable);
  54621. this.kernelMatrix = kernelMatrix;
  54622. this.onApply = function (effect) {
  54623. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  54624. };
  54625. }
  54626. return FilterPostProcess;
  54627. }(BABYLON.PostProcess));
  54628. BABYLON.FilterPostProcess = FilterPostProcess;
  54629. })(BABYLON || (BABYLON = {}));
  54630. var BABYLON;
  54631. (function (BABYLON) {
  54632. var FxaaPostProcess = (function (_super) {
  54633. __extends(FxaaPostProcess, _super);
  54634. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable) {
  54635. var _this = this;
  54636. _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode, engine, reusable);
  54637. this.onSizeChangedObservable.add(function () {
  54638. _this.texelWidth = 1.0 / _this.width;
  54639. _this.texelHeight = 1.0 / _this.height;
  54640. });
  54641. this.onApplyObservable.add(function (effect) {
  54642. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  54643. });
  54644. }
  54645. return FxaaPostProcess;
  54646. }(BABYLON.PostProcess));
  54647. BABYLON.FxaaPostProcess = FxaaPostProcess;
  54648. })(BABYLON || (BABYLON = {}));
  54649. var BABYLON;
  54650. (function (BABYLON) {
  54651. var StereoscopicInterlacePostProcess = (function (_super) {
  54652. __extends(StereoscopicInterlacePostProcess, _super);
  54653. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  54654. var _this = this;
  54655. _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined);
  54656. this._passedProcess = rigCameras[0]._rigPostProcess;
  54657. this._stepSize = new BABYLON.Vector2(1 / this.width, 1 / this.height);
  54658. this.onSizeChangedObservable.add(function () {
  54659. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  54660. });
  54661. this.onApplyObservable.add(function (effect) {
  54662. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  54663. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  54664. });
  54665. }
  54666. return StereoscopicInterlacePostProcess;
  54667. }(BABYLON.PostProcess));
  54668. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  54669. })(BABYLON || (BABYLON = {}));
  54670. var BABYLON;
  54671. (function (BABYLON) {
  54672. var LensFlare = (function () {
  54673. function LensFlare(size, position, color, imgUrl, system) {
  54674. this.size = size;
  54675. this.position = position;
  54676. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  54677. this.dispose = function () {
  54678. if (this.texture) {
  54679. this.texture.dispose();
  54680. }
  54681. // Remove from scene
  54682. var index = this._system.lensFlares.indexOf(this);
  54683. this._system.lensFlares.splice(index, 1);
  54684. };
  54685. this.color = color || new BABYLON.Color3(1, 1, 1);
  54686. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  54687. this._system = system;
  54688. system.lensFlares.push(this);
  54689. }
  54690. return LensFlare;
  54691. }());
  54692. BABYLON.LensFlare = LensFlare;
  54693. })(BABYLON || (BABYLON = {}));
  54694. var BABYLON;
  54695. (function (BABYLON) {
  54696. var LensFlareSystem = (function () {
  54697. function LensFlareSystem(name, emitter, scene) {
  54698. this.name = name;
  54699. this.lensFlares = new Array();
  54700. this.borderLimit = 300;
  54701. this.viewportBorder = 0;
  54702. this.layerMask = 0x0FFFFFFF;
  54703. this._vertexBuffers = {};
  54704. this._isEnabled = true;
  54705. this._scene = scene;
  54706. this._emitter = emitter;
  54707. this.id = name;
  54708. scene.lensFlareSystems.push(this);
  54709. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  54710. var engine = scene.getEngine();
  54711. // VBO
  54712. var vertices = [];
  54713. vertices.push(1, 1);
  54714. vertices.push(-1, 1);
  54715. vertices.push(-1, -1);
  54716. vertices.push(1, -1);
  54717. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  54718. // Indices
  54719. var indices = [];
  54720. indices.push(0);
  54721. indices.push(1);
  54722. indices.push(2);
  54723. indices.push(0);
  54724. indices.push(2);
  54725. indices.push(3);
  54726. this._indexBuffer = engine.createIndexBuffer(indices);
  54727. // Effects
  54728. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  54729. }
  54730. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  54731. get: function () {
  54732. return this._isEnabled;
  54733. },
  54734. set: function (value) {
  54735. this._isEnabled = value;
  54736. },
  54737. enumerable: true,
  54738. configurable: true
  54739. });
  54740. LensFlareSystem.prototype.getScene = function () {
  54741. return this._scene;
  54742. };
  54743. LensFlareSystem.prototype.getEmitter = function () {
  54744. return this._emitter;
  54745. };
  54746. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  54747. this._emitter = newEmitter;
  54748. };
  54749. LensFlareSystem.prototype.getEmitterPosition = function () {
  54750. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  54751. };
  54752. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  54753. var position = this.getEmitterPosition();
  54754. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  54755. this._positionX = position.x;
  54756. this._positionY = position.y;
  54757. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  54758. if (this.viewportBorder > 0) {
  54759. globalViewport.x -= this.viewportBorder;
  54760. globalViewport.y -= this.viewportBorder;
  54761. globalViewport.width += this.viewportBorder * 2;
  54762. globalViewport.height += this.viewportBorder * 2;
  54763. position.x += this.viewportBorder;
  54764. position.y += this.viewportBorder;
  54765. this._positionX += this.viewportBorder;
  54766. this._positionY += this.viewportBorder;
  54767. }
  54768. if (position.z > 0) {
  54769. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  54770. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  54771. return true;
  54772. }
  54773. return true;
  54774. }
  54775. return false;
  54776. };
  54777. LensFlareSystem.prototype._isVisible = function () {
  54778. if (!this._isEnabled) {
  54779. return false;
  54780. }
  54781. var emitterPosition = this.getEmitterPosition();
  54782. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  54783. var distance = direction.length();
  54784. direction.normalize();
  54785. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  54786. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  54787. return !pickInfo.hit || pickInfo.distance > distance;
  54788. };
  54789. LensFlareSystem.prototype.render = function () {
  54790. if (!this._effect.isReady())
  54791. return false;
  54792. var engine = this._scene.getEngine();
  54793. var viewport = this._scene.activeCamera.viewport;
  54794. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  54795. // Position
  54796. if (!this.computeEffectivePosition(globalViewport)) {
  54797. return false;
  54798. }
  54799. // Visibility
  54800. if (!this._isVisible()) {
  54801. return false;
  54802. }
  54803. // Intensity
  54804. var awayX;
  54805. var awayY;
  54806. if (this._positionX < this.borderLimit + globalViewport.x) {
  54807. awayX = this.borderLimit + globalViewport.x - this._positionX;
  54808. }
  54809. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  54810. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  54811. }
  54812. else {
  54813. awayX = 0;
  54814. }
  54815. if (this._positionY < this.borderLimit + globalViewport.y) {
  54816. awayY = this.borderLimit + globalViewport.y - this._positionY;
  54817. }
  54818. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  54819. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  54820. }
  54821. else {
  54822. awayY = 0;
  54823. }
  54824. var away = (awayX > awayY) ? awayX : awayY;
  54825. away -= this.viewportBorder;
  54826. if (away > this.borderLimit) {
  54827. away = this.borderLimit;
  54828. }
  54829. var intensity = 1.0 - (away / this.borderLimit);
  54830. if (intensity < 0) {
  54831. return false;
  54832. }
  54833. if (intensity > 1.0) {
  54834. intensity = 1.0;
  54835. }
  54836. if (this.viewportBorder > 0) {
  54837. globalViewport.x += this.viewportBorder;
  54838. globalViewport.y += this.viewportBorder;
  54839. globalViewport.width -= this.viewportBorder * 2;
  54840. globalViewport.height -= this.viewportBorder * 2;
  54841. this._positionX -= this.viewportBorder;
  54842. this._positionY -= this.viewportBorder;
  54843. }
  54844. // Position
  54845. var centerX = globalViewport.x + globalViewport.width / 2;
  54846. var centerY = globalViewport.y + globalViewport.height / 2;
  54847. var distX = centerX - this._positionX;
  54848. var distY = centerY - this._positionY;
  54849. // Effects
  54850. engine.enableEffect(this._effect);
  54851. engine.setState(false);
  54852. engine.setDepthBuffer(false);
  54853. // VBOs
  54854. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  54855. // Flares
  54856. for (var index = 0; index < this.lensFlares.length; index++) {
  54857. var flare = this.lensFlares[index];
  54858. engine.setAlphaMode(flare.alphaMode);
  54859. var x = centerX - (distX * flare.position);
  54860. var y = centerY - (distY * flare.position);
  54861. var cw = flare.size;
  54862. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  54863. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  54864. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  54865. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  54866. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  54867. // Texture
  54868. this._effect.setTexture("textureSampler", flare.texture);
  54869. // Color
  54870. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  54871. // Draw order
  54872. engine.draw(true, 0, 6);
  54873. }
  54874. engine.setDepthBuffer(true);
  54875. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  54876. return true;
  54877. };
  54878. LensFlareSystem.prototype.dispose = function () {
  54879. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  54880. if (vertexBuffer) {
  54881. vertexBuffer.dispose();
  54882. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  54883. }
  54884. if (this._indexBuffer) {
  54885. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  54886. this._indexBuffer = null;
  54887. }
  54888. while (this.lensFlares.length) {
  54889. this.lensFlares[0].dispose();
  54890. }
  54891. // Remove from scene
  54892. var index = this._scene.lensFlareSystems.indexOf(this);
  54893. this._scene.lensFlareSystems.splice(index, 1);
  54894. };
  54895. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  54896. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  54897. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  54898. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  54899. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  54900. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  54901. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  54902. var parsedFlare = parsedLensFlareSystem.flares[index];
  54903. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  54904. }
  54905. return lensFlareSystem;
  54906. };
  54907. LensFlareSystem.prototype.serialize = function () {
  54908. var serializationObject = {};
  54909. serializationObject.id = this.id;
  54910. serializationObject.name = this.name;
  54911. serializationObject.emitterId = this.getEmitter().id;
  54912. serializationObject.borderLimit = this.borderLimit;
  54913. serializationObject.flares = [];
  54914. for (var index = 0; index < this.lensFlares.length; index++) {
  54915. var flare = this.lensFlares[index];
  54916. serializationObject.flares.push({
  54917. size: flare.size,
  54918. position: flare.position,
  54919. color: flare.color.asArray(),
  54920. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  54921. });
  54922. }
  54923. return serializationObject;
  54924. };
  54925. return LensFlareSystem;
  54926. }());
  54927. BABYLON.LensFlareSystem = LensFlareSystem;
  54928. })(BABYLON || (BABYLON = {}));
  54929. var BABYLON;
  54930. (function (BABYLON) {
  54931. // We're mainly based on the logic defined into the FreeCamera code
  54932. var DeviceOrientationCamera = (function (_super) {
  54933. __extends(DeviceOrientationCamera, _super);
  54934. function DeviceOrientationCamera(name, position, scene) {
  54935. _super.call(this, name, position, scene);
  54936. this._quaternionCache = new BABYLON.Quaternion();
  54937. this.inputs.addDeviceOrientation();
  54938. }
  54939. DeviceOrientationCamera.prototype.getTypeName = function () {
  54940. return "DeviceOrientationCamera";
  54941. };
  54942. DeviceOrientationCamera.prototype._checkInputs = function () {
  54943. _super.prototype._checkInputs.call(this);
  54944. this._quaternionCache.copyFrom(this.rotationQuaternion);
  54945. if (this._initialQuaternion) {
  54946. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  54947. }
  54948. };
  54949. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  54950. var _this = this;
  54951. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  54952. //can only work if this camera has a rotation quaternion already.
  54953. if (!this.rotationQuaternion)
  54954. return;
  54955. if (!this._initialQuaternion) {
  54956. this._initialQuaternion = new BABYLON.Quaternion();
  54957. }
  54958. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  54959. ['x', 'y', 'z'].forEach(function (axisName) {
  54960. if (!axis[axisName]) {
  54961. _this._initialQuaternion[axisName] = 0;
  54962. }
  54963. else {
  54964. _this._initialQuaternion[axisName] *= -1;
  54965. }
  54966. });
  54967. this._initialQuaternion.normalize();
  54968. //force rotation update
  54969. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  54970. };
  54971. return DeviceOrientationCamera;
  54972. }(BABYLON.FreeCamera));
  54973. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  54974. })(BABYLON || (BABYLON = {}));
  54975. var BABYLON;
  54976. (function (BABYLON) {
  54977. var VRDeviceOrientationFreeCamera = (function (_super) {
  54978. __extends(VRDeviceOrientationFreeCamera, _super);
  54979. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  54980. if (compensateDistortion === void 0) { compensateDistortion = true; }
  54981. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  54982. _super.call(this, name, position, scene);
  54983. vrCameraMetrics.compensateDistortion = compensateDistortion;
  54984. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  54985. }
  54986. VRDeviceOrientationFreeCamera.prototype.getTypeName = function () {
  54987. return "VRDeviceOrientationFreeCamera";
  54988. };
  54989. return VRDeviceOrientationFreeCamera;
  54990. }(BABYLON.DeviceOrientationCamera));
  54991. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  54992. var VRDeviceOrientationArcRotateCamera = (function (_super) {
  54993. __extends(VRDeviceOrientationArcRotateCamera, _super);
  54994. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  54995. if (compensateDistortion === void 0) { compensateDistortion = true; }
  54996. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  54997. _super.call(this, name, alpha, beta, radius, target, scene);
  54998. vrCameraMetrics.compensateDistortion = compensateDistortion;
  54999. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  55000. this.inputs.addVRDeviceOrientation();
  55001. }
  55002. VRDeviceOrientationArcRotateCamera.prototype.getTypeName = function () {
  55003. return "VRDeviceOrientationArcRotateCamera";
  55004. };
  55005. return VRDeviceOrientationArcRotateCamera;
  55006. }(BABYLON.ArcRotateCamera));
  55007. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  55008. })(BABYLON || (BABYLON = {}));
  55009. var BABYLON;
  55010. (function (BABYLON) {
  55011. // We're mainly based on the logic defined into the FreeCamera code
  55012. var UniversalCamera = (function (_super) {
  55013. __extends(UniversalCamera, _super);
  55014. //-- end properties for backward compatibility for inputs
  55015. function UniversalCamera(name, position, scene) {
  55016. _super.call(this, name, position, scene);
  55017. this.inputs.addGamepad();
  55018. }
  55019. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  55020. //-- Begin properties for backward compatibility for inputs
  55021. get: function () {
  55022. var gamepad = this.inputs.attached["gamepad"];
  55023. if (gamepad)
  55024. return gamepad.gamepadAngularSensibility;
  55025. },
  55026. set: function (value) {
  55027. var gamepad = this.inputs.attached["gamepad"];
  55028. if (gamepad)
  55029. gamepad.gamepadAngularSensibility = value;
  55030. },
  55031. enumerable: true,
  55032. configurable: true
  55033. });
  55034. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  55035. get: function () {
  55036. var gamepad = this.inputs.attached["gamepad"];
  55037. if (gamepad)
  55038. return gamepad.gamepadMoveSensibility;
  55039. },
  55040. set: function (value) {
  55041. var gamepad = this.inputs.attached["gamepad"];
  55042. if (gamepad)
  55043. gamepad.gamepadMoveSensibility = value;
  55044. },
  55045. enumerable: true,
  55046. configurable: true
  55047. });
  55048. UniversalCamera.prototype.getTypeName = function () {
  55049. return "UniversalCamera";
  55050. };
  55051. return UniversalCamera;
  55052. }(BABYLON.TouchCamera));
  55053. BABYLON.UniversalCamera = UniversalCamera;
  55054. })(BABYLON || (BABYLON = {}));
  55055. var BABYLON;
  55056. (function (BABYLON) {
  55057. var Gamepads = (function () {
  55058. function Gamepads(ongamedpadconnected) {
  55059. var _this = this;
  55060. this.babylonGamepads = [];
  55061. this.oneGamepadConnected = false;
  55062. this.isMonitoring = false;
  55063. this.gamepadEventSupported = 'GamepadEvent' in window;
  55064. this.gamepadSupportAvailable = (navigator.getGamepads ||
  55065. !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  55066. this._callbackGamepadConnected = ongamedpadconnected;
  55067. if (this.gamepadSupportAvailable) {
  55068. // Checking if the gamepad connected event is supported (like in Firefox)
  55069. if (this.gamepadEventSupported) {
  55070. this._onGamepadConnectedEvent = function (evt) {
  55071. _this._onGamepadConnected(evt);
  55072. };
  55073. this._onGamepadDisonnectedEvent = function (evt) {
  55074. _this._onGamepadDisconnected(evt);
  55075. };
  55076. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  55077. window.addEventListener('gamepaddisconnected', this._onGamepadDisonnectedEvent, false);
  55078. }
  55079. else {
  55080. this._startMonitoringGamepads();
  55081. }
  55082. }
  55083. }
  55084. Gamepads.prototype.dispose = function () {
  55085. if (Gamepads.gamepadDOMInfo) {
  55086. document.body.removeChild(Gamepads.gamepadDOMInfo);
  55087. }
  55088. if (this._onGamepadConnectedEvent) {
  55089. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  55090. window.removeEventListener('gamepaddisconnected', this._onGamepadDisonnectedEvent, false);
  55091. this._onGamepadConnectedEvent = null;
  55092. this._onGamepadDisonnectedEvent = null;
  55093. }
  55094. };
  55095. Gamepads.prototype._onGamepadConnected = function (evt) {
  55096. var newGamepad = this._addNewGamepad(evt.gamepad);
  55097. if (this._callbackGamepadConnected)
  55098. this._callbackGamepadConnected(newGamepad);
  55099. this._startMonitoringGamepads();
  55100. };
  55101. Gamepads.prototype._addNewGamepad = function (gamepad) {
  55102. if (!this.oneGamepadConnected) {
  55103. this.oneGamepadConnected = true;
  55104. if (Gamepads.gamepadDOMInfo) {
  55105. document.body.removeChild(Gamepads.gamepadDOMInfo);
  55106. Gamepads.gamepadDOMInfo = null;
  55107. }
  55108. }
  55109. var newGamepad;
  55110. if (gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  55111. newGamepad = new Xbox360Pad(gamepad.id, gamepad.index, gamepad);
  55112. }
  55113. else {
  55114. newGamepad = new GenericPad(gamepad.id, gamepad.index, gamepad);
  55115. }
  55116. this.babylonGamepads.push(newGamepad);
  55117. return newGamepad;
  55118. };
  55119. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  55120. // Remove the gamepad from the list of gamepads to monitor.
  55121. for (var i in this.babylonGamepads) {
  55122. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  55123. this.babylonGamepads.splice(+i, 1);
  55124. break;
  55125. }
  55126. }
  55127. // If no gamepads are left, stop the polling loop.
  55128. if (this.babylonGamepads.length == 0) {
  55129. this._stopMonitoringGamepads();
  55130. }
  55131. };
  55132. Gamepads.prototype._startMonitoringGamepads = function () {
  55133. if (!this.isMonitoring) {
  55134. this.isMonitoring = true;
  55135. this._checkGamepadsStatus();
  55136. }
  55137. };
  55138. Gamepads.prototype._stopMonitoringGamepads = function () {
  55139. this.isMonitoring = false;
  55140. };
  55141. Gamepads.prototype._checkGamepadsStatus = function () {
  55142. var _this = this;
  55143. // updating gamepad objects
  55144. this._updateGamepadObjects();
  55145. for (var i in this.babylonGamepads) {
  55146. this.babylonGamepads[i].update();
  55147. }
  55148. if (this.isMonitoring) {
  55149. if (window.requestAnimationFrame) {
  55150. window.requestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  55151. }
  55152. else if (window.mozRequestAnimationFrame) {
  55153. window.mozRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  55154. }
  55155. else if (window.webkitRequestAnimationFrame) {
  55156. window.webkitRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  55157. }
  55158. }
  55159. };
  55160. // This function is called only on Chrome, which does not yet support
  55161. // connection/disconnection events, but requires you to monitor
  55162. // an array for changes.
  55163. Gamepads.prototype._updateGamepadObjects = function () {
  55164. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  55165. for (var i = 0; i < gamepads.length; i++) {
  55166. if (gamepads[i]) {
  55167. if (!(gamepads[i].index in this.babylonGamepads)) {
  55168. var newGamepad = this._addNewGamepad(gamepads[i]);
  55169. if (this._callbackGamepadConnected) {
  55170. this._callbackGamepadConnected(newGamepad);
  55171. }
  55172. }
  55173. else {
  55174. this.babylonGamepads[i].browserGamepad = gamepads[i];
  55175. }
  55176. }
  55177. }
  55178. };
  55179. return Gamepads;
  55180. }());
  55181. BABYLON.Gamepads = Gamepads;
  55182. var StickValues = (function () {
  55183. function StickValues(x, y) {
  55184. this.x = x;
  55185. this.y = y;
  55186. }
  55187. return StickValues;
  55188. }());
  55189. BABYLON.StickValues = StickValues;
  55190. var Gamepad = (function () {
  55191. function Gamepad(id, index, browserGamepad) {
  55192. this.id = id;
  55193. this.index = index;
  55194. this.browserGamepad = browserGamepad;
  55195. if (this.browserGamepad.axes.length >= 2) {
  55196. this._leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  55197. }
  55198. if (this.browserGamepad.axes.length >= 4) {
  55199. this._rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  55200. }
  55201. }
  55202. Gamepad.prototype.onleftstickchanged = function (callback) {
  55203. this._onleftstickchanged = callback;
  55204. };
  55205. Gamepad.prototype.onrightstickchanged = function (callback) {
  55206. this._onrightstickchanged = callback;
  55207. };
  55208. Object.defineProperty(Gamepad.prototype, "leftStick", {
  55209. get: function () {
  55210. return this._leftStick;
  55211. },
  55212. set: function (newValues) {
  55213. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  55214. this._onleftstickchanged(newValues);
  55215. }
  55216. this._leftStick = newValues;
  55217. },
  55218. enumerable: true,
  55219. configurable: true
  55220. });
  55221. Object.defineProperty(Gamepad.prototype, "rightStick", {
  55222. get: function () {
  55223. return this._rightStick;
  55224. },
  55225. set: function (newValues) {
  55226. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  55227. this._onrightstickchanged(newValues);
  55228. }
  55229. this._rightStick = newValues;
  55230. },
  55231. enumerable: true,
  55232. configurable: true
  55233. });
  55234. Gamepad.prototype.update = function () {
  55235. if (this._leftStick) {
  55236. this.leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  55237. }
  55238. if (this._rightStick) {
  55239. this.rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  55240. }
  55241. };
  55242. return Gamepad;
  55243. }());
  55244. BABYLON.Gamepad = Gamepad;
  55245. var GenericPad = (function (_super) {
  55246. __extends(GenericPad, _super);
  55247. function GenericPad(id, index, gamepad) {
  55248. _super.call(this, id, index, gamepad);
  55249. this.id = id;
  55250. this.index = index;
  55251. this.gamepad = gamepad;
  55252. this._buttons = new Array(gamepad.buttons.length);
  55253. }
  55254. GenericPad.prototype.onbuttondown = function (callback) {
  55255. this._onbuttondown = callback;
  55256. };
  55257. GenericPad.prototype.onbuttonup = function (callback) {
  55258. this._onbuttonup = callback;
  55259. };
  55260. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  55261. if (newValue !== currentValue) {
  55262. if (this._onbuttondown && newValue === 1) {
  55263. this._onbuttondown(buttonIndex);
  55264. }
  55265. if (this._onbuttonup && newValue === 0) {
  55266. this._onbuttonup(buttonIndex);
  55267. }
  55268. }
  55269. return newValue;
  55270. };
  55271. GenericPad.prototype.update = function () {
  55272. _super.prototype.update.call(this);
  55273. for (var index = 0; index < this._buttons.length; index++) {
  55274. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  55275. }
  55276. };
  55277. return GenericPad;
  55278. }(Gamepad));
  55279. BABYLON.GenericPad = GenericPad;
  55280. (function (Xbox360Button) {
  55281. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  55282. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  55283. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  55284. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  55285. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  55286. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  55287. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  55288. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  55289. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  55290. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  55291. })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  55292. var Xbox360Button = BABYLON.Xbox360Button;
  55293. (function (Xbox360Dpad) {
  55294. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  55295. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  55296. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  55297. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  55298. })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  55299. var Xbox360Dpad = BABYLON.Xbox360Dpad;
  55300. var Xbox360Pad = (function (_super) {
  55301. __extends(Xbox360Pad, _super);
  55302. function Xbox360Pad() {
  55303. _super.apply(this, arguments);
  55304. this._leftTrigger = 0;
  55305. this._rightTrigger = 0;
  55306. this._buttonA = 0;
  55307. this._buttonB = 0;
  55308. this._buttonX = 0;
  55309. this._buttonY = 0;
  55310. this._buttonBack = 0;
  55311. this._buttonStart = 0;
  55312. this._buttonLB = 0;
  55313. this._buttonRB = 0;
  55314. this._buttonLeftStick = 0;
  55315. this._buttonRightStick = 0;
  55316. this._dPadUp = 0;
  55317. this._dPadDown = 0;
  55318. this._dPadLeft = 0;
  55319. this._dPadRight = 0;
  55320. }
  55321. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  55322. this._onlefttriggerchanged = callback;
  55323. };
  55324. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  55325. this._onrighttriggerchanged = callback;
  55326. };
  55327. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  55328. get: function () {
  55329. return this._leftTrigger;
  55330. },
  55331. set: function (newValue) {
  55332. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  55333. this._onlefttriggerchanged(newValue);
  55334. }
  55335. this._leftTrigger = newValue;
  55336. },
  55337. enumerable: true,
  55338. configurable: true
  55339. });
  55340. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  55341. get: function () {
  55342. return this._rightTrigger;
  55343. },
  55344. set: function (newValue) {
  55345. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  55346. this._onrighttriggerchanged(newValue);
  55347. }
  55348. this._rightTrigger = newValue;
  55349. },
  55350. enumerable: true,
  55351. configurable: true
  55352. });
  55353. Xbox360Pad.prototype.onbuttondown = function (callback) {
  55354. this._onbuttondown = callback;
  55355. };
  55356. Xbox360Pad.prototype.onbuttonup = function (callback) {
  55357. this._onbuttonup = callback;
  55358. };
  55359. Xbox360Pad.prototype.ondpaddown = function (callback) {
  55360. this._ondpaddown = callback;
  55361. };
  55362. Xbox360Pad.prototype.ondpadup = function (callback) {
  55363. this._ondpadup = callback;
  55364. };
  55365. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  55366. if (newValue !== currentValue) {
  55367. if (this._onbuttondown && newValue === 1) {
  55368. this._onbuttondown(buttonType);
  55369. }
  55370. if (this._onbuttonup && newValue === 0) {
  55371. this._onbuttonup(buttonType);
  55372. }
  55373. }
  55374. return newValue;
  55375. };
  55376. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  55377. if (newValue !== currentValue) {
  55378. if (this._ondpaddown && newValue === 1) {
  55379. this._ondpaddown(buttonType);
  55380. }
  55381. if (this._ondpadup && newValue === 0) {
  55382. this._ondpadup(buttonType);
  55383. }
  55384. }
  55385. return newValue;
  55386. };
  55387. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  55388. get: function () {
  55389. return this._buttonA;
  55390. },
  55391. set: function (value) {
  55392. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  55393. },
  55394. enumerable: true,
  55395. configurable: true
  55396. });
  55397. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  55398. get: function () {
  55399. return this._buttonB;
  55400. },
  55401. set: function (value) {
  55402. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  55403. },
  55404. enumerable: true,
  55405. configurable: true
  55406. });
  55407. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  55408. get: function () {
  55409. return this._buttonX;
  55410. },
  55411. set: function (value) {
  55412. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  55413. },
  55414. enumerable: true,
  55415. configurable: true
  55416. });
  55417. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  55418. get: function () {
  55419. return this._buttonY;
  55420. },
  55421. set: function (value) {
  55422. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  55423. },
  55424. enumerable: true,
  55425. configurable: true
  55426. });
  55427. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  55428. get: function () {
  55429. return this._buttonStart;
  55430. },
  55431. set: function (value) {
  55432. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  55433. },
  55434. enumerable: true,
  55435. configurable: true
  55436. });
  55437. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  55438. get: function () {
  55439. return this._buttonBack;
  55440. },
  55441. set: function (value) {
  55442. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  55443. },
  55444. enumerable: true,
  55445. configurable: true
  55446. });
  55447. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  55448. get: function () {
  55449. return this._buttonLB;
  55450. },
  55451. set: function (value) {
  55452. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  55453. },
  55454. enumerable: true,
  55455. configurable: true
  55456. });
  55457. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  55458. get: function () {
  55459. return this._buttonRB;
  55460. },
  55461. set: function (value) {
  55462. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  55463. },
  55464. enumerable: true,
  55465. configurable: true
  55466. });
  55467. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  55468. get: function () {
  55469. return this._buttonLeftStick;
  55470. },
  55471. set: function (value) {
  55472. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  55473. },
  55474. enumerable: true,
  55475. configurable: true
  55476. });
  55477. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  55478. get: function () {
  55479. return this._buttonRightStick;
  55480. },
  55481. set: function (value) {
  55482. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  55483. },
  55484. enumerable: true,
  55485. configurable: true
  55486. });
  55487. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  55488. get: function () {
  55489. return this._dPadUp;
  55490. },
  55491. set: function (value) {
  55492. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  55493. },
  55494. enumerable: true,
  55495. configurable: true
  55496. });
  55497. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  55498. get: function () {
  55499. return this._dPadDown;
  55500. },
  55501. set: function (value) {
  55502. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  55503. },
  55504. enumerable: true,
  55505. configurable: true
  55506. });
  55507. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  55508. get: function () {
  55509. return this._dPadLeft;
  55510. },
  55511. set: function (value) {
  55512. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  55513. },
  55514. enumerable: true,
  55515. configurable: true
  55516. });
  55517. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  55518. get: function () {
  55519. return this._dPadRight;
  55520. },
  55521. set: function (value) {
  55522. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  55523. },
  55524. enumerable: true,
  55525. configurable: true
  55526. });
  55527. Xbox360Pad.prototype.update = function () {
  55528. _super.prototype.update.call(this);
  55529. this.buttonA = this.browserGamepad.buttons[0].value;
  55530. this.buttonB = this.browserGamepad.buttons[1].value;
  55531. this.buttonX = this.browserGamepad.buttons[2].value;
  55532. this.buttonY = this.browserGamepad.buttons[3].value;
  55533. this.buttonLB = this.browserGamepad.buttons[4].value;
  55534. this.buttonRB = this.browserGamepad.buttons[5].value;
  55535. this.leftTrigger = this.browserGamepad.buttons[6].value;
  55536. this.rightTrigger = this.browserGamepad.buttons[7].value;
  55537. this.buttonBack = this.browserGamepad.buttons[8].value;
  55538. this.buttonStart = this.browserGamepad.buttons[9].value;
  55539. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  55540. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  55541. this.dPadUp = this.browserGamepad.buttons[12].value;
  55542. this.dPadDown = this.browserGamepad.buttons[13].value;
  55543. this.dPadLeft = this.browserGamepad.buttons[14].value;
  55544. this.dPadRight = this.browserGamepad.buttons[15].value;
  55545. };
  55546. return Xbox360Pad;
  55547. }(Gamepad));
  55548. BABYLON.Xbox360Pad = Xbox360Pad;
  55549. })(BABYLON || (BABYLON = {}));
  55550. var BABYLON;
  55551. (function (BABYLON) {
  55552. // We're mainly based on the logic defined into the FreeCamera code
  55553. var GamepadCamera = (function (_super) {
  55554. __extends(GamepadCamera, _super);
  55555. //-- end properties for backward compatibility for inputs
  55556. function GamepadCamera(name, position, scene) {
  55557. BABYLON.Tools.Warn("Deprecated. Please use Universal Camera instead.");
  55558. _super.call(this, name, position, scene);
  55559. }
  55560. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  55561. //-- Begin properties for backward compatibility for inputs
  55562. get: function () {
  55563. var gamepad = this.inputs.attached["gamepad"];
  55564. if (gamepad)
  55565. return gamepad.gamepadAngularSensibility;
  55566. },
  55567. set: function (value) {
  55568. var gamepad = this.inputs.attached["gamepad"];
  55569. if (gamepad)
  55570. gamepad.gamepadAngularSensibility = value;
  55571. },
  55572. enumerable: true,
  55573. configurable: true
  55574. });
  55575. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  55576. get: function () {
  55577. var gamepad = this.inputs.attached["gamepad"];
  55578. if (gamepad)
  55579. return gamepad.gamepadMoveSensibility;
  55580. },
  55581. set: function (value) {
  55582. var gamepad = this.inputs.attached["gamepad"];
  55583. if (gamepad)
  55584. gamepad.gamepadMoveSensibility = value;
  55585. },
  55586. enumerable: true,
  55587. configurable: true
  55588. });
  55589. GamepadCamera.prototype.getTypeName = function () {
  55590. return "GamepadCamera";
  55591. };
  55592. return GamepadCamera;
  55593. }(BABYLON.UniversalCamera));
  55594. BABYLON.GamepadCamera = GamepadCamera;
  55595. })(BABYLON || (BABYLON = {}));
  55596. var BABYLON;
  55597. (function (BABYLON) {
  55598. var Analyser = (function () {
  55599. function Analyser(scene) {
  55600. this.SMOOTHING = 0.75;
  55601. this.FFT_SIZE = 512;
  55602. this.BARGRAPHAMPLITUDE = 256;
  55603. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  55604. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  55605. this._scene = scene;
  55606. this._audioEngine = BABYLON.Engine.audioEngine;
  55607. if (this._audioEngine.canUseWebAudio) {
  55608. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  55609. this._webAudioAnalyser.minDecibels = -140;
  55610. this._webAudioAnalyser.maxDecibels = 0;
  55611. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  55612. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  55613. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  55614. }
  55615. }
  55616. Analyser.prototype.getFrequencyBinCount = function () {
  55617. if (this._audioEngine.canUseWebAudio) {
  55618. return this._webAudioAnalyser.frequencyBinCount;
  55619. }
  55620. else {
  55621. return 0;
  55622. }
  55623. };
  55624. Analyser.prototype.getByteFrequencyData = function () {
  55625. if (this._audioEngine.canUseWebAudio) {
  55626. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  55627. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  55628. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  55629. }
  55630. return this._byteFreqs;
  55631. };
  55632. Analyser.prototype.getByteTimeDomainData = function () {
  55633. if (this._audioEngine.canUseWebAudio) {
  55634. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  55635. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  55636. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  55637. }
  55638. return this._byteTime;
  55639. };
  55640. Analyser.prototype.getFloatFrequencyData = function () {
  55641. if (this._audioEngine.canUseWebAudio) {
  55642. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  55643. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  55644. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  55645. }
  55646. return this._floatFreqs;
  55647. };
  55648. Analyser.prototype.drawDebugCanvas = function () {
  55649. var _this = this;
  55650. if (this._audioEngine.canUseWebAudio) {
  55651. if (!this._debugCanvas) {
  55652. this._debugCanvas = document.createElement("canvas");
  55653. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  55654. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  55655. this._debugCanvas.style.position = "absolute";
  55656. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  55657. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  55658. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  55659. document.body.appendChild(this._debugCanvas);
  55660. this._registerFunc = function () {
  55661. _this.drawDebugCanvas();
  55662. };
  55663. this._scene.registerBeforeRender(this._registerFunc);
  55664. }
  55665. if (this._registerFunc) {
  55666. var workingArray = this.getByteFrequencyData();
  55667. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  55668. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  55669. // Draw the frequency domain chart.
  55670. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  55671. var value = workingArray[i];
  55672. var percent = value / this.BARGRAPHAMPLITUDE;
  55673. var height = this.DEBUGCANVASSIZE.height * percent;
  55674. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  55675. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  55676. var hue = i / this.getFrequencyBinCount() * 360;
  55677. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  55678. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  55679. }
  55680. }
  55681. }
  55682. };
  55683. Analyser.prototype.stopDebugCanvas = function () {
  55684. if (this._debugCanvas) {
  55685. this._scene.unregisterBeforeRender(this._registerFunc);
  55686. this._registerFunc = null;
  55687. document.body.removeChild(this._debugCanvas);
  55688. this._debugCanvas = null;
  55689. this._debugCanvasContext = null;
  55690. }
  55691. };
  55692. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  55693. if (this._audioEngine.canUseWebAudio) {
  55694. inputAudioNode.connect(this._webAudioAnalyser);
  55695. this._webAudioAnalyser.connect(outputAudioNode);
  55696. }
  55697. };
  55698. Analyser.prototype.dispose = function () {
  55699. if (this._audioEngine.canUseWebAudio) {
  55700. this._webAudioAnalyser.disconnect();
  55701. }
  55702. };
  55703. return Analyser;
  55704. }());
  55705. BABYLON.Analyser = Analyser;
  55706. })(BABYLON || (BABYLON = {}));
  55707. var BABYLON;
  55708. (function (BABYLON) {
  55709. var DepthRenderer = (function () {
  55710. function DepthRenderer(scene, type) {
  55711. var _this = this;
  55712. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  55713. this._viewMatrix = BABYLON.Matrix.Zero();
  55714. this._projectionMatrix = BABYLON.Matrix.Zero();
  55715. this._transformMatrix = BABYLON.Matrix.Zero();
  55716. this._worldViewProjection = BABYLON.Matrix.Zero();
  55717. this._scene = scene;
  55718. var engine = scene.getEngine();
  55719. // Render target
  55720. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  55721. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  55722. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  55723. this._depthMap.refreshRate = 1;
  55724. this._depthMap.renderParticles = false;
  55725. this._depthMap.renderList = null;
  55726. // set default depth value to 1.0 (far away)
  55727. this._depthMap.onClearObservable.add(function (engine) {
  55728. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  55729. });
  55730. // Custom render function
  55731. var renderSubMesh = function (subMesh) {
  55732. var mesh = subMesh.getRenderingMesh();
  55733. var scene = _this._scene;
  55734. var engine = scene.getEngine();
  55735. // Culling
  55736. engine.setState(subMesh.getMaterial().backFaceCulling);
  55737. // Managing instances
  55738. var batch = mesh._getInstancesRenderList(subMesh._id);
  55739. if (batch.mustReturn) {
  55740. return;
  55741. }
  55742. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  55743. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  55744. engine.enableEffect(_this._effect);
  55745. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  55746. var material = subMesh.getMaterial();
  55747. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  55748. _this._effect.setFloat("far", scene.activeCamera.maxZ);
  55749. // Alpha test
  55750. if (material && material.needAlphaTesting()) {
  55751. var alphaTexture = material.getAlphaTestTexture();
  55752. _this._effect.setTexture("diffuseSampler", alphaTexture);
  55753. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  55754. }
  55755. // Bones
  55756. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  55757. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  55758. }
  55759. // Draw
  55760. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  55761. }
  55762. };
  55763. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  55764. var index;
  55765. for (index = 0; index < opaqueSubMeshes.length; index++) {
  55766. renderSubMesh(opaqueSubMeshes.data[index]);
  55767. }
  55768. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  55769. renderSubMesh(alphaTestSubMeshes.data[index]);
  55770. }
  55771. };
  55772. }
  55773. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  55774. var material = subMesh.getMaterial();
  55775. if (material.disableDepthWrite) {
  55776. return false;
  55777. }
  55778. var defines = [];
  55779. var attribs = [BABYLON.VertexBuffer.PositionKind];
  55780. var mesh = subMesh.getMesh();
  55781. var scene = mesh.getScene();
  55782. // Alpha test
  55783. if (material && material.needAlphaTesting()) {
  55784. defines.push("#define ALPHATEST");
  55785. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  55786. attribs.push(BABYLON.VertexBuffer.UVKind);
  55787. defines.push("#define UV1");
  55788. }
  55789. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  55790. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  55791. defines.push("#define UV2");
  55792. }
  55793. }
  55794. // Bones
  55795. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  55796. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  55797. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  55798. if (mesh.numBoneInfluencers > 4) {
  55799. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  55800. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  55801. }
  55802. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  55803. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  55804. }
  55805. else {
  55806. defines.push("#define NUM_BONE_INFLUENCERS 0");
  55807. }
  55808. // Instances
  55809. if (useInstances) {
  55810. defines.push("#define INSTANCES");
  55811. attribs.push("world0");
  55812. attribs.push("world1");
  55813. attribs.push("world2");
  55814. attribs.push("world3");
  55815. }
  55816. // Get correct effect
  55817. var join = defines.join("\n");
  55818. if (this._cachedDefines !== join) {
  55819. this._cachedDefines = join;
  55820. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler"], join);
  55821. }
  55822. return this._effect.isReady();
  55823. };
  55824. DepthRenderer.prototype.getDepthMap = function () {
  55825. return this._depthMap;
  55826. };
  55827. // Methods
  55828. DepthRenderer.prototype.dispose = function () {
  55829. this._depthMap.dispose();
  55830. };
  55831. return DepthRenderer;
  55832. }());
  55833. BABYLON.DepthRenderer = DepthRenderer;
  55834. })(BABYLON || (BABYLON = {}));
  55835. var BABYLON;
  55836. (function (BABYLON) {
  55837. var SSAORenderingPipeline = (function (_super) {
  55838. __extends(SSAORenderingPipeline, _super);
  55839. /**
  55840. * @constructor
  55841. * @param {string} name - The rendering pipeline name
  55842. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  55843. * @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 }
  55844. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  55845. */
  55846. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  55847. var _this = this;
  55848. _super.call(this, scene.getEngine(), name);
  55849. // Members
  55850. /**
  55851. * The PassPostProcess id in the pipeline that contains the original scene color
  55852. * @type {string}
  55853. */
  55854. this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  55855. /**
  55856. * The SSAO PostProcess id in the pipeline
  55857. * @type {string}
  55858. */
  55859. this.SSAORenderEffect = "SSAORenderEffect";
  55860. /**
  55861. * The horizontal blur PostProcess id in the pipeline
  55862. * @type {string}
  55863. */
  55864. this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  55865. /**
  55866. * The vertical blur PostProcess id in the pipeline
  55867. * @type {string}
  55868. */
  55869. this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  55870. /**
  55871. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  55872. * @type {string}
  55873. */
  55874. this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  55875. /**
  55876. * The output strength of the SSAO post-process. Default value is 1.0.
  55877. * @type {number}
  55878. */
  55879. this.totalStrength = 1.0;
  55880. /**
  55881. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  55882. * @type {number}
  55883. */
  55884. this.radius = 0.0001;
  55885. /**
  55886. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  55887. * Must not be equal to fallOff and superior to fallOff.
  55888. * Default value is 0.975
  55889. * @type {number}
  55890. */
  55891. this.area = 0.0075;
  55892. /**
  55893. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  55894. * Must not be equal to area and inferior to area.
  55895. * Default value is 0.0
  55896. * @type {number}
  55897. */
  55898. this.fallOff = 0.000001;
  55899. /**
  55900. * The base color of the SSAO post-process
  55901. * The final result is "base + ssao" between [0, 1]
  55902. * @type {number}
  55903. */
  55904. this.base = 0.5;
  55905. this._firstUpdate = true;
  55906. this._scene = scene;
  55907. // Set up assets
  55908. this._createRandomTexture();
  55909. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  55910. var ssaoRatio = ratio.ssaoRatio || ratio;
  55911. var combineRatio = ratio.combineRatio || ratio;
  55912. this._ratio = {
  55913. ssaoRatio: ssaoRatio,
  55914. combineRatio: combineRatio
  55915. };
  55916. this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  55917. this._createSSAOPostProcess(ssaoRatio);
  55918. this._createBlurPostProcess(ssaoRatio);
  55919. this._createSSAOCombinePostProcess(combineRatio);
  55920. // Set up pipeline
  55921. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  55922. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  55923. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  55924. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  55925. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  55926. // Finish
  55927. scene.postProcessRenderPipelineManager.addPipeline(this);
  55928. if (cameras)
  55929. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  55930. }
  55931. // Public Methods
  55932. /**
  55933. * Returns the horizontal blur PostProcess
  55934. * @return {BABYLON.BlurPostProcess} The horizontal blur post-process
  55935. */
  55936. SSAORenderingPipeline.prototype.getBlurHPostProcess = function () {
  55937. BABYLON.Tools.Error("SSAORenderinPipeline.getBlurHPostProcess() is deprecated, no more blur post-process exists");
  55938. return null;
  55939. };
  55940. /**
  55941. * Returns the vertical blur PostProcess
  55942. * @return {BABYLON.BlurPostProcess} The vertical blur post-process
  55943. */
  55944. SSAORenderingPipeline.prototype.getBlurVPostProcess = function () {
  55945. BABYLON.Tools.Error("SSAORenderinPipeline.getBlurVPostProcess() is deprecated, no more blur post-process exists");
  55946. return null;
  55947. };
  55948. /**
  55949. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  55950. */
  55951. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  55952. if (disableDepthRender === void 0) { disableDepthRender = false; }
  55953. for (var i = 0; i < this._scene.cameras.length; i++) {
  55954. var camera = this._scene.cameras[i];
  55955. this._originalColorPostProcess.dispose(camera);
  55956. this._ssaoPostProcess.dispose(camera);
  55957. this._blurHPostProcess.dispose(camera);
  55958. this._blurVPostProcess.dispose(camera);
  55959. this._ssaoCombinePostProcess.dispose(camera);
  55960. }
  55961. this._randomTexture.dispose();
  55962. if (disableDepthRender)
  55963. this._scene.disableDepthRenderer();
  55964. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  55965. };
  55966. // Private Methods
  55967. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  55968. var _this = this;
  55969. /*
  55970. var samplerOffsets = [
  55971. -8.0, -6.0, -4.0, -2.0,
  55972. 0.0,
  55973. 2.0, 4.0, 6.0, 8.0
  55974. ];
  55975. */
  55976. var samples = 16;
  55977. var samplerOffsets = [];
  55978. for (var i = -8; i < 8; i++) {
  55979. samplerOffsets.push(i * 2);
  55980. }
  55981. 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");
  55982. this._blurHPostProcess.onApply = function (effect) {
  55983. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width);
  55984. effect.setTexture("depthSampler", _this._depthTexture);
  55985. if (_this._firstUpdate) {
  55986. effect.setArray("samplerOffsets", samplerOffsets);
  55987. }
  55988. };
  55989. 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");
  55990. this._blurVPostProcess.onApply = function (effect) {
  55991. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height);
  55992. effect.setTexture("depthSampler", _this._depthTexture);
  55993. if (_this._firstUpdate) {
  55994. effect.setArray("samplerOffsets", samplerOffsets);
  55995. _this._firstUpdate = false;
  55996. }
  55997. };
  55998. };
  55999. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  56000. var _this = this;
  56001. var numSamples = 16;
  56002. var sampleSphere = [
  56003. 0.5381, 0.1856, -0.4319,
  56004. 0.1379, 0.2486, 0.4430,
  56005. 0.3371, 0.5679, -0.0057,
  56006. -0.6999, -0.0451, -0.0019,
  56007. 0.0689, -0.1598, -0.8547,
  56008. 0.0560, 0.0069, -0.1843,
  56009. -0.0146, 0.1402, 0.0762,
  56010. 0.0100, -0.1924, -0.0344,
  56011. -0.3577, -0.5301, -0.4358,
  56012. -0.3169, 0.1063, 0.0158,
  56013. 0.0103, -0.5869, 0.0046,
  56014. -0.0897, -0.4940, 0.3287,
  56015. 0.7119, -0.0154, -0.0918,
  56016. -0.0533, 0.0596, -0.5411,
  56017. 0.0352, -0.0631, 0.5460,
  56018. -0.4776, 0.2847, -0.0271
  56019. ];
  56020. var samplesFactor = 1.0 / numSamples;
  56021. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  56022. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  56023. "area", "fallOff", "base", "range", "viewport"
  56024. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  56025. var viewport = new BABYLON.Vector2(0, 0);
  56026. this._ssaoPostProcess.onApply = function (effect) {
  56027. if (_this._firstUpdate) {
  56028. effect.setArray3("sampleSphere", sampleSphere);
  56029. effect.setFloat("samplesFactor", samplesFactor);
  56030. effect.setFloat("randTextureTiles", 4.0);
  56031. }
  56032. effect.setFloat("totalStrength", _this.totalStrength);
  56033. effect.setFloat("radius", _this.radius);
  56034. effect.setFloat("area", _this.area);
  56035. effect.setFloat("fallOff", _this.fallOff);
  56036. effect.setFloat("base", _this.base);
  56037. effect.setTexture("textureSampler", _this._depthTexture);
  56038. effect.setTexture("randomSampler", _this._randomTexture);
  56039. };
  56040. };
  56041. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  56042. var _this = this;
  56043. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  56044. this._ssaoCombinePostProcess.onApply = function (effect) {
  56045. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  56046. };
  56047. };
  56048. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  56049. var size = 512;
  56050. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  56051. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  56052. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  56053. var context = this._randomTexture.getContext();
  56054. var rand = function (min, max) {
  56055. return Math.random() * (max - min) + min;
  56056. };
  56057. var randVector = BABYLON.Vector3.Zero();
  56058. for (var x = 0; x < size; x++) {
  56059. for (var y = 0; y < size; y++) {
  56060. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  56061. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  56062. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  56063. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  56064. context.fillRect(x, y, 1, 1);
  56065. }
  56066. }
  56067. this._randomTexture.update(false);
  56068. };
  56069. __decorate([
  56070. BABYLON.serialize()
  56071. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  56072. __decorate([
  56073. BABYLON.serialize()
  56074. ], SSAORenderingPipeline.prototype, "radius", void 0);
  56075. __decorate([
  56076. BABYLON.serialize()
  56077. ], SSAORenderingPipeline.prototype, "area", void 0);
  56078. __decorate([
  56079. BABYLON.serialize()
  56080. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  56081. __decorate([
  56082. BABYLON.serialize()
  56083. ], SSAORenderingPipeline.prototype, "base", void 0);
  56084. __decorate([
  56085. BABYLON.serialize()
  56086. ], SSAORenderingPipeline.prototype, "_ratio", void 0);
  56087. return SSAORenderingPipeline;
  56088. }(BABYLON.PostProcessRenderPipeline));
  56089. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  56090. })(BABYLON || (BABYLON = {}));
  56091. var BABYLON;
  56092. (function (BABYLON) {
  56093. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  56094. var VolumetricLightScatteringPostProcess = (function (_super) {
  56095. __extends(VolumetricLightScatteringPostProcess, _super);
  56096. /**
  56097. * @constructor
  56098. * @param {string} name - The post-process name
  56099. * @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)
  56100. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  56101. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  56102. * @param {number} samples - The post-process quality, default 100
  56103. * @param {number} samplingMode - The post-process filtering mode
  56104. * @param {BABYLON.Engine} engine - The babylon engine
  56105. * @param {boolean} reusable - If the post-process is reusable
  56106. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  56107. */
  56108. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  56109. var _this = this;
  56110. if (samples === void 0) { samples = 100; }
  56111. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  56112. _super.call(this, name, "volumetricLightScattering", ["decay", "exposure", "weight", "meshPositionOnScreen", "density"], ["lightScatteringSampler"], ratio.postProcessRatio || ratio, camera, samplingMode, engine, reusable, "#define NUM_SAMPLES " + samples);
  56113. this._screenCoordinates = BABYLON.Vector2.Zero();
  56114. /**
  56115. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  56116. * @type {Vector3}
  56117. */
  56118. this.customMeshPosition = BABYLON.Vector3.Zero();
  56119. /**
  56120. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  56121. * @type {boolean}
  56122. */
  56123. this.useCustomMeshPosition = false;
  56124. /**
  56125. * If the post-process should inverse the light scattering direction
  56126. * @type {boolean}
  56127. */
  56128. this.invert = true;
  56129. /**
  56130. * Array containing the excluded meshes not rendered in the internal pass
  56131. */
  56132. this.excludedMeshes = new Array();
  56133. /**
  56134. * Controls the overall intensity of the post-process
  56135. * @type {number}
  56136. */
  56137. this.exposure = 0.3;
  56138. /**
  56139. * Dissipates each sample's contribution in range [0, 1]
  56140. * @type {number}
  56141. */
  56142. this.decay = 0.96815;
  56143. /**
  56144. * Controls the overall intensity of each sample
  56145. * @type {number}
  56146. */
  56147. this.weight = 0.58767;
  56148. /**
  56149. * Controls the density of each sample
  56150. * @type {number}
  56151. */
  56152. this.density = 0.926;
  56153. scene = (camera === null) ? scene : camera.getScene(); // parameter "scene" can be null.
  56154. var engine = scene.getEngine();
  56155. this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  56156. // Configure mesh
  56157. this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  56158. // Configure
  56159. this._createPass(scene, ratio.passRatio || ratio);
  56160. this.onActivate = function (camera) {
  56161. if (!_this.isSupported) {
  56162. _this.dispose(camera);
  56163. }
  56164. _this.onActivate = null;
  56165. };
  56166. this.onApplyObservable.add(function (effect) {
  56167. _this._updateMeshScreenCoordinates(scene);
  56168. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  56169. effect.setFloat("exposure", _this.exposure);
  56170. effect.setFloat("decay", _this.decay);
  56171. effect.setFloat("weight", _this.weight);
  56172. effect.setFloat("density", _this.density);
  56173. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  56174. });
  56175. }
  56176. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  56177. get: function () {
  56178. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  56179. return false;
  56180. },
  56181. set: function (useDiffuseColor) {
  56182. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  56183. },
  56184. enumerable: true,
  56185. configurable: true
  56186. });
  56187. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  56188. var mesh = subMesh.getMesh();
  56189. // Render this.mesh as default
  56190. if (mesh === this.mesh) {
  56191. return mesh.material.isReady(mesh);
  56192. }
  56193. var defines = [];
  56194. var attribs = [BABYLON.VertexBuffer.PositionKind];
  56195. var material = subMesh.getMaterial();
  56196. var needUV = false;
  56197. // Alpha test
  56198. if (material) {
  56199. if (material.needAlphaTesting()) {
  56200. defines.push("#define ALPHATEST");
  56201. }
  56202. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  56203. attribs.push(BABYLON.VertexBuffer.UVKind);
  56204. defines.push("#define UV1");
  56205. }
  56206. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  56207. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  56208. defines.push("#define UV2");
  56209. }
  56210. }
  56211. // Bones
  56212. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  56213. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  56214. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  56215. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  56216. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  56217. }
  56218. else {
  56219. defines.push("#define NUM_BONE_INFLUENCERS 0");
  56220. }
  56221. // Instances
  56222. if (useInstances) {
  56223. defines.push("#define INSTANCES");
  56224. attribs.push("world0");
  56225. attribs.push("world1");
  56226. attribs.push("world2");
  56227. attribs.push("world3");
  56228. }
  56229. // Get correct effect
  56230. var join = defines.join("\n");
  56231. if (this._cachedDefines !== join) {
  56232. this._cachedDefines = join;
  56233. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  56234. }
  56235. return this._volumetricLightScatteringPass.isReady();
  56236. };
  56237. /**
  56238. * Sets the new light position for light scattering effect
  56239. * @param {BABYLON.Vector3} The new custom light position
  56240. */
  56241. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  56242. this.customMeshPosition = position;
  56243. };
  56244. /**
  56245. * Returns the light position for light scattering effect
  56246. * @return {BABYLON.Vector3} The custom light position
  56247. */
  56248. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  56249. return this.customMeshPosition;
  56250. };
  56251. /**
  56252. * Disposes the internal assets and detaches the post-process from the camera
  56253. */
  56254. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  56255. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  56256. if (rttIndex !== -1) {
  56257. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  56258. }
  56259. this._volumetricLightScatteringRTT.dispose();
  56260. _super.prototype.dispose.call(this, camera);
  56261. };
  56262. /**
  56263. * Returns the render target texture used by the post-process
  56264. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  56265. */
  56266. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  56267. return this._volumetricLightScatteringRTT;
  56268. };
  56269. // Private methods
  56270. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  56271. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  56272. return true;
  56273. }
  56274. return false;
  56275. };
  56276. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  56277. var _this = this;
  56278. var engine = scene.getEngine();
  56279. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  56280. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  56281. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  56282. this._volumetricLightScatteringRTT.renderList = null;
  56283. this._volumetricLightScatteringRTT.renderParticles = false;
  56284. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  56285. // Custom render function for submeshes
  56286. var renderSubMesh = function (subMesh) {
  56287. var mesh = subMesh.getRenderingMesh();
  56288. if (_this._meshExcluded(mesh)) {
  56289. return;
  56290. }
  56291. var scene = mesh.getScene();
  56292. var engine = scene.getEngine();
  56293. // Culling
  56294. engine.setState(subMesh.getMaterial().backFaceCulling);
  56295. // Managing instances
  56296. var batch = mesh._getInstancesRenderList(subMesh._id);
  56297. if (batch.mustReturn) {
  56298. return;
  56299. }
  56300. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  56301. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  56302. var effect = _this._volumetricLightScatteringPass;
  56303. if (mesh === _this.mesh) {
  56304. effect = subMesh.getMaterial().getEffect();
  56305. }
  56306. engine.enableEffect(effect);
  56307. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  56308. if (mesh === _this.mesh) {
  56309. subMesh.getMaterial().bind(mesh.getWorldMatrix(), mesh);
  56310. }
  56311. else {
  56312. var material = subMesh.getMaterial();
  56313. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  56314. // Alpha test
  56315. if (material && material.needAlphaTesting()) {
  56316. var alphaTexture = material.getAlphaTestTexture();
  56317. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  56318. if (alphaTexture) {
  56319. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  56320. }
  56321. }
  56322. // Bones
  56323. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  56324. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  56325. }
  56326. }
  56327. // Draw
  56328. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  56329. }
  56330. };
  56331. // Render target texture callbacks
  56332. var savedSceneClearColor;
  56333. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  56334. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  56335. savedSceneClearColor = scene.clearColor;
  56336. scene.clearColor = sceneClearColor;
  56337. });
  56338. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  56339. scene.clearColor = savedSceneClearColor;
  56340. });
  56341. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  56342. var engine = scene.getEngine();
  56343. var index;
  56344. for (index = 0; index < opaqueSubMeshes.length; index++) {
  56345. renderSubMesh(opaqueSubMeshes.data[index]);
  56346. }
  56347. engine.setAlphaTesting(true);
  56348. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  56349. renderSubMesh(alphaTestSubMeshes.data[index]);
  56350. }
  56351. engine.setAlphaTesting(false);
  56352. if (transparentSubMeshes.length) {
  56353. // Sort sub meshes
  56354. for (index = 0; index < transparentSubMeshes.length; index++) {
  56355. var submesh = transparentSubMeshes.data[index];
  56356. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  56357. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  56358. }
  56359. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  56360. sortedArray.sort(function (a, b) {
  56361. // Alpha index first
  56362. if (a._alphaIndex > b._alphaIndex) {
  56363. return 1;
  56364. }
  56365. if (a._alphaIndex < b._alphaIndex) {
  56366. return -1;
  56367. }
  56368. // Then distance to camera
  56369. if (a._distanceToCamera < b._distanceToCamera) {
  56370. return 1;
  56371. }
  56372. if (a._distanceToCamera > b._distanceToCamera) {
  56373. return -1;
  56374. }
  56375. return 0;
  56376. });
  56377. // Render sub meshes
  56378. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  56379. for (index = 0; index < sortedArray.length; index++) {
  56380. renderSubMesh(sortedArray[index]);
  56381. }
  56382. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  56383. }
  56384. };
  56385. };
  56386. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  56387. var transform = scene.getTransformMatrix();
  56388. var meshPosition;
  56389. if (this.useCustomMeshPosition) {
  56390. meshPosition = this.customMeshPosition;
  56391. }
  56392. else if (this.attachedNode) {
  56393. meshPosition = this.attachedNode.position;
  56394. }
  56395. else {
  56396. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  56397. }
  56398. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  56399. this._screenCoordinates.x = pos.x / this._viewPort.width;
  56400. this._screenCoordinates.y = pos.y / this._viewPort.height;
  56401. if (this.invert)
  56402. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  56403. };
  56404. // Static methods
  56405. /**
  56406. * Creates a default mesh for the Volumeric Light Scattering post-process
  56407. * @param {string} The mesh name
  56408. * @param {BABYLON.Scene} The scene where to create the mesh
  56409. * @return {BABYLON.Mesh} the default mesh
  56410. */
  56411. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  56412. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  56413. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  56414. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  56415. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  56416. mesh.material = material;
  56417. return mesh;
  56418. };
  56419. __decorate([
  56420. BABYLON.serializeAsVector3()
  56421. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  56422. __decorate([
  56423. BABYLON.serialize()
  56424. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  56425. __decorate([
  56426. BABYLON.serialize()
  56427. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  56428. __decorate([
  56429. BABYLON.serializeAsMeshReference()
  56430. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  56431. __decorate([
  56432. BABYLON.serialize()
  56433. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  56434. __decorate([
  56435. BABYLON.serialize()
  56436. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  56437. __decorate([
  56438. BABYLON.serialize()
  56439. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  56440. __decorate([
  56441. BABYLON.serialize()
  56442. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  56443. __decorate([
  56444. BABYLON.serialize()
  56445. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  56446. return VolumetricLightScatteringPostProcess;
  56447. }(BABYLON.PostProcess));
  56448. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  56449. })(BABYLON || (BABYLON = {}));
  56450. // BABYLON.JS Chromatic Aberration GLSL Shader
  56451. // Author: Olivier Guyot
  56452. // Separates very slightly R, G and B colors on the edges of the screen
  56453. // Inspired by Francois Tarlier & Martins Upitis
  56454. var BABYLON;
  56455. (function (BABYLON) {
  56456. var LensRenderingPipeline = (function (_super) {
  56457. __extends(LensRenderingPipeline, _super);
  56458. /**
  56459. * @constructor
  56460. *
  56461. * Effect parameters are as follow:
  56462. * {
  56463. * chromatic_aberration: number; // from 0 to x (1 for realism)
  56464. * edge_blur: number; // from 0 to x (1 for realism)
  56465. * distortion: number; // from 0 to x (1 for realism)
  56466. * grain_amount: number; // from 0 to 1
  56467. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  56468. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  56469. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  56470. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  56471. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  56472. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  56473. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  56474. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  56475. * }
  56476. * Note: if an effect parameter is unset, effect is disabled
  56477. *
  56478. * @param {string} name - The rendering pipeline name
  56479. * @param {object} parameters - An object containing all parameters (see above)
  56480. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  56481. * @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)
  56482. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  56483. */
  56484. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  56485. var _this = this;
  56486. if (ratio === void 0) { ratio = 1.0; }
  56487. _super.call(this, scene.getEngine(), name);
  56488. // Lens effects can be of the following:
  56489. // - chromatic aberration (slight shift of RGB colors)
  56490. // - blur on the edge of the lens
  56491. // - lens distortion
  56492. // - depth-of-field blur & highlights enhancing
  56493. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  56494. // - grain effect (noise or custom texture)
  56495. // Two additional texture samplers are needed:
  56496. // - depth map (for depth-of-field)
  56497. // - grain texture
  56498. /**
  56499. * The chromatic aberration PostProcess id in the pipeline
  56500. * @type {string}
  56501. */
  56502. this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  56503. /**
  56504. * The highlights enhancing PostProcess id in the pipeline
  56505. * @type {string}
  56506. */
  56507. this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  56508. /**
  56509. * The depth-of-field PostProcess id in the pipeline
  56510. * @type {string}
  56511. */
  56512. this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  56513. this._scene = scene;
  56514. // Fetch texture samplers
  56515. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  56516. if (parameters.grain_texture) {
  56517. this._grainTexture = parameters.grain_texture;
  56518. }
  56519. else {
  56520. this._createGrainTexture();
  56521. }
  56522. // save parameters
  56523. this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  56524. this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  56525. this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  56526. this._distortion = parameters.distortion ? parameters.distortion : 0;
  56527. this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  56528. this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  56529. this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  56530. this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  56531. this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  56532. this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  56533. this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  56534. // Create effects
  56535. this._createChromaticAberrationPostProcess(ratio);
  56536. this._createHighlightsPostProcess(ratio);
  56537. this._createDepthOfFieldPostProcess(ratio / 4);
  56538. // Set up pipeline
  56539. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  56540. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  56541. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  56542. if (this._highlightsGain === -1) {
  56543. this._disableEffect(this.HighlightsEnhancingEffect, null);
  56544. }
  56545. // Finish
  56546. scene.postProcessRenderPipelineManager.addPipeline(this);
  56547. if (cameras) {
  56548. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  56549. }
  56550. }
  56551. // public methods (self explanatory)
  56552. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  56553. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  56554. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  56555. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  56556. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  56557. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  56558. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  56559. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  56560. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  56561. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  56562. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  56563. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  56564. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  56565. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  56566. };
  56567. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  56568. this._highlightsPostProcess.updateEffect();
  56569. };
  56570. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  56571. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  56572. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  56573. this._highlightsGain = amount;
  56574. };
  56575. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  56576. if (this._highlightsGain === -1) {
  56577. this._highlightsGain = 1.0;
  56578. }
  56579. this._highlightsThreshold = amount;
  56580. };
  56581. LensRenderingPipeline.prototype.disableHighlights = function () {
  56582. this._highlightsGain = -1;
  56583. };
  56584. /**
  56585. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  56586. */
  56587. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  56588. if (disableDepthRender === void 0) { disableDepthRender = false; }
  56589. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  56590. this._chromaticAberrationPostProcess = undefined;
  56591. this._highlightsPostProcess = undefined;
  56592. this._depthOfFieldPostProcess = undefined;
  56593. this._grainTexture.dispose();
  56594. if (disableDepthRender)
  56595. this._scene.disableDepthRenderer();
  56596. };
  56597. // colors shifting and distortion
  56598. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  56599. var _this = this;
  56600. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  56601. [], // samplers
  56602. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  56603. this._chromaticAberrationPostProcess.onApply = function (effect) {
  56604. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  56605. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  56606. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  56607. };
  56608. };
  56609. // highlights enhancing
  56610. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  56611. var _this = this;
  56612. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  56613. [], // samplers
  56614. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  56615. this._highlightsPostProcess.onApply = function (effect) {
  56616. effect.setFloat('gain', _this._highlightsGain);
  56617. effect.setFloat('threshold', _this._highlightsThreshold);
  56618. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  56619. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  56620. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  56621. };
  56622. };
  56623. // colors shifting and distortion
  56624. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  56625. var _this = this;
  56626. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  56627. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  56628. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  56629. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  56630. this._depthOfFieldPostProcess.onApply = function (effect) {
  56631. effect.setTexture("depthSampler", _this._depthTexture);
  56632. effect.setTexture("grainSampler", _this._grainTexture);
  56633. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  56634. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  56635. effect.setFloat('grain_amount', _this._grainAmount);
  56636. effect.setBool('blur_noise', _this._blurNoise);
  56637. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  56638. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  56639. effect.setFloat('distortion', _this._distortion);
  56640. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  56641. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  56642. effect.setFloat('aperture', _this._dofAperture);
  56643. effect.setFloat('darken', _this._dofDarken);
  56644. effect.setFloat('edge_blur', _this._edgeBlur);
  56645. effect.setBool('highlights', (_this._highlightsGain !== -1));
  56646. effect.setFloat('near', _this._scene.activeCamera.minZ);
  56647. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  56648. };
  56649. };
  56650. // creates a black and white random noise texture, 512x512
  56651. LensRenderingPipeline.prototype._createGrainTexture = function () {
  56652. var size = 512;
  56653. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  56654. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  56655. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  56656. var context = this._grainTexture.getContext();
  56657. var rand = function (min, max) {
  56658. return Math.random() * (max - min) + min;
  56659. };
  56660. var value;
  56661. for (var x = 0; x < size; x++) {
  56662. for (var y = 0; y < size; y++) {
  56663. value = Math.floor(rand(0.42, 0.58) * 255);
  56664. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  56665. context.fillRect(x, y, 1, 1);
  56666. }
  56667. }
  56668. this._grainTexture.update(false);
  56669. };
  56670. return LensRenderingPipeline;
  56671. }(BABYLON.PostProcessRenderPipeline));
  56672. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  56673. })(BABYLON || (BABYLON = {}));
  56674. //
  56675. // This post-process allows the modification of rendered colors by using
  56676. // a 'look-up table' (LUT). This effect is also called Color Grading.
  56677. //
  56678. // The object needs to be provided an url to a texture containing the color
  56679. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  56680. // Use an image editing software to tweak the LUT to match your needs.
  56681. //
  56682. // For an example of a color LUT, see here:
  56683. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  56684. // For explanations on color grading, see here:
  56685. // http://udn.epicgames.com/Three/ColorGrading.html
  56686. //
  56687. var BABYLON;
  56688. (function (BABYLON) {
  56689. var ColorCorrectionPostProcess = (function (_super) {
  56690. __extends(ColorCorrectionPostProcess, _super);
  56691. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  56692. var _this = this;
  56693. _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable);
  56694. this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  56695. this._colorTableTexture.anisotropicFilteringLevel = 1;
  56696. this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  56697. this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  56698. this.onApply = function (effect) {
  56699. effect.setTexture("colorTable", _this._colorTableTexture);
  56700. };
  56701. }
  56702. return ColorCorrectionPostProcess;
  56703. }(BABYLON.PostProcess));
  56704. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  56705. })(BABYLON || (BABYLON = {}));
  56706. var BABYLON;
  56707. (function (BABYLON) {
  56708. var AnaglyphFreeCamera = (function (_super) {
  56709. __extends(AnaglyphFreeCamera, _super);
  56710. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  56711. _super.call(this, name, position, scene);
  56712. this.interaxialDistance = interaxialDistance;
  56713. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  56714. }
  56715. AnaglyphFreeCamera.prototype.getTypeName = function () {
  56716. return "AnaglyphFreeCamera";
  56717. };
  56718. return AnaglyphFreeCamera;
  56719. }(BABYLON.FreeCamera));
  56720. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  56721. var AnaglyphArcRotateCamera = (function (_super) {
  56722. __extends(AnaglyphArcRotateCamera, _super);
  56723. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  56724. _super.call(this, name, alpha, beta, radius, target, scene);
  56725. this.interaxialDistance = interaxialDistance;
  56726. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  56727. }
  56728. AnaglyphArcRotateCamera.prototype.getTypeName = function () {
  56729. return "AnaglyphArcRotateCamera";
  56730. };
  56731. return AnaglyphArcRotateCamera;
  56732. }(BABYLON.ArcRotateCamera));
  56733. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  56734. var AnaglyphGamepadCamera = (function (_super) {
  56735. __extends(AnaglyphGamepadCamera, _super);
  56736. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  56737. _super.call(this, name, position, scene);
  56738. this.interaxialDistance = interaxialDistance;
  56739. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  56740. }
  56741. AnaglyphGamepadCamera.prototype.getTypeName = function () {
  56742. return "AnaglyphGamepadCamera";
  56743. };
  56744. return AnaglyphGamepadCamera;
  56745. }(BABYLON.GamepadCamera));
  56746. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  56747. var AnaglyphUniversalCamera = (function (_super) {
  56748. __extends(AnaglyphUniversalCamera, _super);
  56749. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  56750. _super.call(this, name, position, scene);
  56751. this.interaxialDistance = interaxialDistance;
  56752. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  56753. }
  56754. AnaglyphUniversalCamera.prototype.getTypeName = function () {
  56755. return "AnaglyphUniversalCamera";
  56756. };
  56757. return AnaglyphUniversalCamera;
  56758. }(BABYLON.UniversalCamera));
  56759. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  56760. var StereoscopicFreeCamera = (function (_super) {
  56761. __extends(StereoscopicFreeCamera, _super);
  56762. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  56763. _super.call(this, name, position, scene);
  56764. this.interaxialDistance = interaxialDistance;
  56765. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  56766. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  56767. }
  56768. StereoscopicFreeCamera.prototype.getTypeName = function () {
  56769. return "StereoscopicFreeCamera";
  56770. };
  56771. return StereoscopicFreeCamera;
  56772. }(BABYLON.FreeCamera));
  56773. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  56774. var StereoscopicArcRotateCamera = (function (_super) {
  56775. __extends(StereoscopicArcRotateCamera, _super);
  56776. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  56777. _super.call(this, name, alpha, beta, radius, target, scene);
  56778. this.interaxialDistance = interaxialDistance;
  56779. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  56780. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  56781. }
  56782. StereoscopicArcRotateCamera.prototype.getTypeName = function () {
  56783. return "StereoscopicArcRotateCamera";
  56784. };
  56785. return StereoscopicArcRotateCamera;
  56786. }(BABYLON.ArcRotateCamera));
  56787. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  56788. var StereoscopicGamepadCamera = (function (_super) {
  56789. __extends(StereoscopicGamepadCamera, _super);
  56790. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  56791. _super.call(this, name, position, scene);
  56792. this.interaxialDistance = interaxialDistance;
  56793. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  56794. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  56795. }
  56796. StereoscopicGamepadCamera.prototype.getTypeName = function () {
  56797. return "StereoscopicGamepadCamera";
  56798. };
  56799. return StereoscopicGamepadCamera;
  56800. }(BABYLON.GamepadCamera));
  56801. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  56802. var StereoscopicUniversalCamera = (function (_super) {
  56803. __extends(StereoscopicUniversalCamera, _super);
  56804. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  56805. _super.call(this, name, position, scene);
  56806. this.interaxialDistance = interaxialDistance;
  56807. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  56808. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  56809. }
  56810. StereoscopicUniversalCamera.prototype.getTypeName = function () {
  56811. return "StereoscopicUniversalCamera";
  56812. };
  56813. return StereoscopicUniversalCamera;
  56814. }(BABYLON.UniversalCamera));
  56815. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  56816. })(BABYLON || (BABYLON = {}));
  56817. var BABYLON;
  56818. (function (BABYLON) {
  56819. var HDRRenderingPipeline = (function (_super) {
  56820. __extends(HDRRenderingPipeline, _super);
  56821. /**
  56822. * @constructor
  56823. * @param {string} name - The rendering pipeline name
  56824. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  56825. * @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)
  56826. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  56827. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  56828. */
  56829. function HDRRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  56830. var _this = this;
  56831. if (originalPostProcess === void 0) { originalPostProcess = null; }
  56832. _super.call(this, scene.getEngine(), name);
  56833. /**
  56834. * Public members
  56835. */
  56836. // Gaussian Blur
  56837. /**
  56838. * Gaussian blur coefficient
  56839. * @type {number}
  56840. */
  56841. this.gaussCoeff = 0.3;
  56842. /**
  56843. * Gaussian blur mean
  56844. * @type {number}
  56845. */
  56846. this.gaussMean = 1.0;
  56847. /**
  56848. * Gaussian blur standard deviation
  56849. * @type {number}
  56850. */
  56851. this.gaussStandDev = 0.8;
  56852. /**
  56853. * Gaussian blur multiplier. Multiplies the blur effect
  56854. * @type {number}
  56855. */
  56856. this.gaussMultiplier = 4.0;
  56857. // HDR
  56858. /**
  56859. * Exposure, controls the overall intensity of the pipeline
  56860. * @type {number}
  56861. */
  56862. this.exposure = 1.0;
  56863. /**
  56864. * Minimum luminance that the post-process can output. Luminance is >= 0
  56865. * @type {number}
  56866. */
  56867. this.minimumLuminance = 1.0;
  56868. /**
  56869. * Maximum luminance that the post-process can output. Must be suprerior to minimumLuminance
  56870. * @type {number}
  56871. */
  56872. this.maximumLuminance = 1e20;
  56873. /**
  56874. * Increase rate for luminance: eye adaptation speed to dark
  56875. * @type {number}
  56876. */
  56877. this.luminanceIncreaserate = 0.5;
  56878. /**
  56879. * Decrease rate for luminance: eye adaptation speed to bright
  56880. * @type {number}
  56881. */
  56882. this.luminanceDecreaseRate = 0.5;
  56883. // Bright pass
  56884. /**
  56885. * Minimum luminance needed to compute HDR
  56886. * @type {number}
  56887. */
  56888. this.brightThreshold = 0.8;
  56889. this._needUpdate = true;
  56890. this._scene = scene;
  56891. // Bright pass
  56892. this._createBrightPassPostProcess(scene, ratio);
  56893. // Down sample X4
  56894. this._createDownSampleX4PostProcess(scene, ratio);
  56895. // Create gaussian blur post-processes
  56896. this._createGaussianBlurPostProcess(scene, ratio);
  56897. // Texture adder
  56898. this._createTextureAdderPostProcess(scene, ratio);
  56899. // Luminance generator
  56900. this._createLuminanceGeneratorPostProcess(scene);
  56901. // HDR
  56902. this._createHDRPostProcess(scene, ratio);
  56903. // Pass postprocess
  56904. if (originalPostProcess === null) {
  56905. this._originalPostProcess = new BABYLON.PassPostProcess("hdr", ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  56906. }
  56907. else {
  56908. this._originalPostProcess = originalPostProcess;
  56909. }
  56910. // Configure pipeline
  56911. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this._originalPostProcess; }, true));
  56912. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this._brightPassPostProcess; }, true));
  56913. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this._downSampleX4PostProcess; }, true));
  56914. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurH", function () { return _this._guassianBlurHPostProcess; }, true));
  56915. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurV", function () { return _this._guassianBlurVPostProcess; }, true));
  56916. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this._textureAdderPostProcess; }, true));
  56917. var addDownSamplerPostProcess = function (id) {
  56918. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampler" + id, function () { return _this._downSamplePostProcesses[id]; }, true));
  56919. };
  56920. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  56921. addDownSamplerPostProcess(i);
  56922. }
  56923. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this._hdrPostProcess; }, true));
  56924. // Finish
  56925. scene.postProcessRenderPipelineManager.addPipeline(this);
  56926. if (cameras !== null) {
  56927. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  56928. }
  56929. this.update();
  56930. }
  56931. /**
  56932. * Tells the pipeline to update its post-processes
  56933. */
  56934. HDRRenderingPipeline.prototype.update = function () {
  56935. this._needUpdate = true;
  56936. };
  56937. /**
  56938. * Returns the current calculated luminance
  56939. */
  56940. HDRRenderingPipeline.prototype.getCurrentLuminance = function () {
  56941. return this._hdrCurrentLuminance;
  56942. };
  56943. /**
  56944. * Returns the currently drawn luminance
  56945. */
  56946. HDRRenderingPipeline.prototype.getOutputLuminance = function () {
  56947. return this._hdrOutputLuminance;
  56948. };
  56949. /**
  56950. * Releases the rendering pipeline and its internal effects. Detaches pipeline from cameras
  56951. */
  56952. HDRRenderingPipeline.prototype.dispose = function () {
  56953. this._originalPostProcess = undefined;
  56954. this._brightPassPostProcess = undefined;
  56955. this._downSampleX4PostProcess = undefined;
  56956. this._guassianBlurHPostProcess = undefined;
  56957. this._guassianBlurVPostProcess = undefined;
  56958. this._textureAdderPostProcess = undefined;
  56959. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  56960. this._downSamplePostProcesses[i] = undefined;
  56961. }
  56962. this._hdrPostProcess = undefined;
  56963. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  56964. };
  56965. /**
  56966. * Creates the HDR post-process and computes the luminance adaptation
  56967. */
  56968. HDRRenderingPipeline.prototype._createHDRPostProcess = function (scene, ratio) {
  56969. var _this = this;
  56970. var hdrLastLuminance = 0.0;
  56971. this._hdrOutputLuminance = -1.0;
  56972. this._hdrCurrentLuminance = 1.0;
  56973. this._hdrPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["exposure", "avgLuminance"], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define HDR");
  56974. this._hdrPostProcess.onApply = function (effect) {
  56975. if (_this._hdrOutputLuminance < 0.0) {
  56976. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  56977. }
  56978. else {
  56979. var dt = (hdrLastLuminance - (hdrLastLuminance + scene.getEngine().getDeltaTime())) / 1000.0;
  56980. if (_this._hdrCurrentLuminance < _this._hdrOutputLuminance + _this.luminanceDecreaseRate * dt) {
  56981. _this._hdrOutputLuminance += _this.luminanceDecreaseRate * dt;
  56982. }
  56983. else if (_this._hdrCurrentLuminance > _this._hdrOutputLuminance - _this.luminanceIncreaserate * dt) {
  56984. _this._hdrOutputLuminance -= _this.luminanceIncreaserate * dt;
  56985. }
  56986. else {
  56987. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  56988. }
  56989. }
  56990. _this._hdrOutputLuminance = BABYLON.MathTools.Clamp(_this._hdrOutputLuminance, _this.minimumLuminance, _this.maximumLuminance);
  56991. hdrLastLuminance += scene.getEngine().getDeltaTime();
  56992. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  56993. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  56994. effect.setFloat("exposure", _this.exposure);
  56995. effect.setFloat("avgLuminance", _this._hdrOutputLuminance);
  56996. _this._needUpdate = false;
  56997. };
  56998. };
  56999. /**
  57000. * Texture Adder post-process
  57001. */
  57002. HDRRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  57003. var _this = this;
  57004. this._textureAdderPostProcess = new BABYLON.PostProcess("hdr", "hdr", [], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define TEXTURE_ADDER");
  57005. this._textureAdderPostProcess.onApply = function (effect) {
  57006. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  57007. };
  57008. };
  57009. /**
  57010. * Down sample X4 post-process
  57011. */
  57012. HDRRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  57013. var _this = this;
  57014. var downSampleX4Offsets = new Array(32);
  57015. this._downSampleX4PostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets"], [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define DOWN_SAMPLE_X4");
  57016. this._downSampleX4PostProcess.onApply = function (effect) {
  57017. if (_this._needUpdate) {
  57018. var id = 0;
  57019. for (var i = -2; i < 2; i++) {
  57020. for (var j = -2; j < 2; j++) {
  57021. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this._downSampleX4PostProcess.width);
  57022. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this._downSampleX4PostProcess.height);
  57023. id += 2;
  57024. }
  57025. }
  57026. }
  57027. effect.setArray2("dsOffsets", downSampleX4Offsets);
  57028. };
  57029. };
  57030. /**
  57031. * Bright pass post-process
  57032. */
  57033. HDRRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  57034. var _this = this;
  57035. var brightOffsets = new Array(8);
  57036. var brightPassCallback = function (effect) {
  57037. if (_this._needUpdate) {
  57038. var sU = (1.0 / _this._brightPassPostProcess.width);
  57039. var sV = (1.0 / _this._brightPassPostProcess.height);
  57040. brightOffsets[0] = -0.5 * sU;
  57041. brightOffsets[1] = 0.5 * sV;
  57042. brightOffsets[2] = 0.5 * sU;
  57043. brightOffsets[3] = 0.5 * sV;
  57044. brightOffsets[4] = -0.5 * sU;
  57045. brightOffsets[5] = -0.5 * sV;
  57046. brightOffsets[6] = 0.5 * sU;
  57047. brightOffsets[7] = -0.5 * sV;
  57048. }
  57049. effect.setArray2("dsOffsets", brightOffsets);
  57050. effect.setFloat("brightThreshold", _this.brightThreshold);
  57051. };
  57052. this._brightPassPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "brightThreshold"], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define BRIGHT_PASS");
  57053. this._brightPassPostProcess.onApply = brightPassCallback;
  57054. };
  57055. /**
  57056. * Luminance generator. Creates the luminance post-process and down sample post-processes
  57057. */
  57058. HDRRenderingPipeline.prototype._createLuminanceGeneratorPostProcess = function (scene) {
  57059. var _this = this;
  57060. var lumSteps = HDRRenderingPipeline.LUM_STEPS;
  57061. var luminanceOffsets = new Array(8);
  57062. var downSampleOffsets = new Array(18);
  57063. var halfDestPixelSize;
  57064. this._downSamplePostProcesses = new Array(lumSteps);
  57065. // Utils for luminance
  57066. var luminanceUpdateSourceOffsets = function (width, height) {
  57067. var sU = (1.0 / width);
  57068. var sV = (1.0 / height);
  57069. luminanceOffsets[0] = -0.5 * sU;
  57070. luminanceOffsets[1] = 0.5 * sV;
  57071. luminanceOffsets[2] = 0.5 * sU;
  57072. luminanceOffsets[3] = 0.5 * sV;
  57073. luminanceOffsets[4] = -0.5 * sU;
  57074. luminanceOffsets[5] = -0.5 * sV;
  57075. luminanceOffsets[6] = 0.5 * sU;
  57076. luminanceOffsets[7] = -0.5 * sV;
  57077. };
  57078. var luminanceUpdateDestOffsets = function (width, height) {
  57079. var id = 0;
  57080. for (var x = -1; x < 2; x++) {
  57081. for (var y = -1; y < 2; y++) {
  57082. downSampleOffsets[id] = (x) / width;
  57083. downSampleOffsets[id + 1] = (y) / height;
  57084. id += 2;
  57085. }
  57086. }
  57087. };
  57088. // Luminance callback
  57089. var luminanceCallback = function (effect) {
  57090. if (_this._needUpdate) {
  57091. luminanceUpdateSourceOffsets(_this._textureAdderPostProcess.width, _this._textureAdderPostProcess.height);
  57092. }
  57093. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  57094. effect.setArray2("lumOffsets", luminanceOffsets);
  57095. };
  57096. // Down sample callbacks
  57097. var downSampleCallback = function (indice) {
  57098. var i = indice;
  57099. return function (effect) {
  57100. luminanceUpdateSourceOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  57101. luminanceUpdateDestOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  57102. halfDestPixelSize = 0.5 / _this._downSamplePostProcesses[i].width;
  57103. effect.setTextureFromPostProcess("textureSampler", _this._downSamplePostProcesses[i + 1]);
  57104. effect.setFloat("halfDestPixelSize", halfDestPixelSize);
  57105. effect.setArray2("dsOffsets", downSampleOffsets);
  57106. };
  57107. };
  57108. var downSampleAfterRenderCallback = function (effect) {
  57109. // Unpack result
  57110. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  57111. 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);
  57112. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  57113. };
  57114. // Create luminance post-process
  57115. var ratio = { width: Math.pow(3, lumSteps - 1), height: Math.pow(3, lumSteps - 1) };
  57116. 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);
  57117. this._downSamplePostProcesses[lumSteps - 1].onApply = luminanceCallback;
  57118. // Create down sample post-processes
  57119. for (var i = lumSteps - 2; i >= 0; i--) {
  57120. var length = Math.pow(3, i);
  57121. ratio = { width: length, height: length };
  57122. var defines = "#define DOWN_SAMPLE\n";
  57123. if (i === 0) {
  57124. defines += "#define FINAL_DOWN_SAMPLE\n"; // To pack the result
  57125. }
  57126. this._downSamplePostProcesses[i] = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "halfDestPixelSize"], [], ratio, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, scene.getEngine(), false, defines, BABYLON.Engine.TEXTURETYPE_FLOAT);
  57127. this._downSamplePostProcesses[i].onApply = downSampleCallback(i);
  57128. if (i === 0) {
  57129. this._downSamplePostProcesses[i].onAfterRender = downSampleAfterRenderCallback;
  57130. }
  57131. }
  57132. };
  57133. /**
  57134. * Gaussian blur post-processes. Horizontal and Vertical
  57135. */
  57136. HDRRenderingPipeline.prototype._createGaussianBlurPostProcess = function (scene, ratio) {
  57137. var _this = this;
  57138. var blurOffsetsW = new Array(9);
  57139. var blurOffsetsH = new Array(9);
  57140. var blurWeights = new Array(9);
  57141. var uniforms = ["blurOffsets", "blurWeights", "multiplier"];
  57142. // Utils for gaussian blur
  57143. var calculateBlurOffsets = function (height) {
  57144. var lastOutputDimensions = {
  57145. width: scene.getEngine().getRenderWidth(),
  57146. height: scene.getEngine().getRenderHeight()
  57147. };
  57148. for (var i = 0; i < 9; i++) {
  57149. var value = (i - 4.0) * (1.0 / (height === true ? lastOutputDimensions.height : lastOutputDimensions.width));
  57150. if (height) {
  57151. blurOffsetsH[i] = value;
  57152. }
  57153. else {
  57154. blurOffsetsW[i] = value;
  57155. }
  57156. }
  57157. };
  57158. var calculateWeights = function () {
  57159. var x = 0.0;
  57160. for (var i = 0; i < 9; i++) {
  57161. x = (i - 4.0) / 4.0;
  57162. 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));
  57163. }
  57164. };
  57165. // Callback
  57166. var gaussianBlurCallback = function (height) {
  57167. return function (effect) {
  57168. if (_this._needUpdate) {
  57169. calculateWeights();
  57170. calculateBlurOffsets(height);
  57171. }
  57172. effect.setArray("blurOffsets", height ? blurOffsetsH : blurOffsetsW);
  57173. effect.setArray("blurWeights", blurWeights);
  57174. effect.setFloat("multiplier", _this.gaussMultiplier);
  57175. };
  57176. };
  57177. // Create horizontal gaussian blur post-processes
  57178. this._guassianBlurHPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_H");
  57179. this._guassianBlurHPostProcess.onApply = gaussianBlurCallback(false);
  57180. // Create vertical gaussian blur post-process
  57181. this._guassianBlurVPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_V");
  57182. this._guassianBlurVPostProcess.onApply = gaussianBlurCallback(true);
  57183. };
  57184. // Luminance generator
  57185. HDRRenderingPipeline.LUM_STEPS = 6;
  57186. return HDRRenderingPipeline;
  57187. }(BABYLON.PostProcessRenderPipeline));
  57188. BABYLON.HDRRenderingPipeline = HDRRenderingPipeline;
  57189. })(BABYLON || (BABYLON = {}));
  57190. var BABYLON;
  57191. (function (BABYLON) {
  57192. var FaceAdjacencies = (function () {
  57193. function FaceAdjacencies() {
  57194. this.edges = new Array();
  57195. this.edgesConnectedCount = 0;
  57196. }
  57197. return FaceAdjacencies;
  57198. }());
  57199. var EdgesRenderer = (function () {
  57200. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  57201. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  57202. if (epsilon === void 0) { epsilon = 0.95; }
  57203. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  57204. this.edgesWidthScalerForOrthographic = 1000.0;
  57205. this.edgesWidthScalerForPerspective = 50.0;
  57206. this._linesPositions = new Array();
  57207. this._linesNormals = new Array();
  57208. this._linesIndices = new Array();
  57209. this._buffers = {};
  57210. this._checkVerticesInsteadOfIndices = false;
  57211. this._source = source;
  57212. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  57213. this._epsilon = epsilon;
  57214. this._prepareRessources();
  57215. this._generateEdgesLines();
  57216. }
  57217. EdgesRenderer.prototype._prepareRessources = function () {
  57218. if (this._lineShader) {
  57219. return;
  57220. }
  57221. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  57222. attributes: ["position", "normal"],
  57223. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  57224. });
  57225. this._lineShader.disableDepthWrite = true;
  57226. this._lineShader.backFaceCulling = false;
  57227. };
  57228. EdgesRenderer.prototype.dispose = function () {
  57229. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  57230. if (buffer) {
  57231. buffer.dispose();
  57232. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  57233. }
  57234. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  57235. if (buffer) {
  57236. buffer.dispose();
  57237. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  57238. }
  57239. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  57240. this._lineShader.dispose();
  57241. };
  57242. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  57243. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  57244. return 0;
  57245. }
  57246. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  57247. return 1;
  57248. }
  57249. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  57250. return 2;
  57251. }
  57252. return -1;
  57253. };
  57254. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  57255. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  57256. return 0;
  57257. }
  57258. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  57259. return 1;
  57260. }
  57261. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  57262. return 2;
  57263. }
  57264. return -1;
  57265. };
  57266. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  57267. var needToCreateLine;
  57268. if (edge === undefined) {
  57269. needToCreateLine = true;
  57270. }
  57271. else {
  57272. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  57273. needToCreateLine = dotProduct < this._epsilon;
  57274. }
  57275. if (needToCreateLine) {
  57276. var offset = this._linesPositions.length / 3;
  57277. var normal = p0.subtract(p1);
  57278. normal.normalize();
  57279. // Positions
  57280. this._linesPositions.push(p0.x);
  57281. this._linesPositions.push(p0.y);
  57282. this._linesPositions.push(p0.z);
  57283. this._linesPositions.push(p0.x);
  57284. this._linesPositions.push(p0.y);
  57285. this._linesPositions.push(p0.z);
  57286. this._linesPositions.push(p1.x);
  57287. this._linesPositions.push(p1.y);
  57288. this._linesPositions.push(p1.z);
  57289. this._linesPositions.push(p1.x);
  57290. this._linesPositions.push(p1.y);
  57291. this._linesPositions.push(p1.z);
  57292. // Normals
  57293. this._linesNormals.push(p1.x);
  57294. this._linesNormals.push(p1.y);
  57295. this._linesNormals.push(p1.z);
  57296. this._linesNormals.push(-1);
  57297. this._linesNormals.push(p1.x);
  57298. this._linesNormals.push(p1.y);
  57299. this._linesNormals.push(p1.z);
  57300. this._linesNormals.push(1);
  57301. this._linesNormals.push(p0.x);
  57302. this._linesNormals.push(p0.y);
  57303. this._linesNormals.push(p0.z);
  57304. this._linesNormals.push(-1);
  57305. this._linesNormals.push(p0.x);
  57306. this._linesNormals.push(p0.y);
  57307. this._linesNormals.push(p0.z);
  57308. this._linesNormals.push(1);
  57309. // Indices
  57310. this._linesIndices.push(offset);
  57311. this._linesIndices.push(offset + 1);
  57312. this._linesIndices.push(offset + 2);
  57313. this._linesIndices.push(offset);
  57314. this._linesIndices.push(offset + 2);
  57315. this._linesIndices.push(offset + 3);
  57316. }
  57317. };
  57318. EdgesRenderer.prototype._generateEdgesLines = function () {
  57319. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  57320. var indices = this._source.getIndices();
  57321. // First let's find adjacencies
  57322. var adjacencies = new Array();
  57323. var faceNormals = new Array();
  57324. var index;
  57325. var faceAdjacencies;
  57326. // Prepare faces
  57327. for (index = 0; index < indices.length; index += 3) {
  57328. faceAdjacencies = new FaceAdjacencies();
  57329. var p0Index = indices[index];
  57330. var p1Index = indices[index + 1];
  57331. var p2Index = indices[index + 2];
  57332. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  57333. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  57334. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  57335. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  57336. faceNormal.normalize();
  57337. faceNormals.push(faceNormal);
  57338. adjacencies.push(faceAdjacencies);
  57339. }
  57340. // Scan
  57341. for (index = 0; index < adjacencies.length; index++) {
  57342. faceAdjacencies = adjacencies[index];
  57343. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  57344. var otherFaceAdjacencies = adjacencies[otherIndex];
  57345. if (faceAdjacencies.edgesConnectedCount === 3) {
  57346. break;
  57347. }
  57348. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  57349. continue;
  57350. }
  57351. var otherP0 = indices[otherIndex * 3];
  57352. var otherP1 = indices[otherIndex * 3 + 1];
  57353. var otherP2 = indices[otherIndex * 3 + 2];
  57354. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  57355. var otherEdgeIndex;
  57356. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  57357. continue;
  57358. }
  57359. switch (edgeIndex) {
  57360. case 0:
  57361. if (this._checkVerticesInsteadOfIndices) {
  57362. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  57363. }
  57364. else {
  57365. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  57366. }
  57367. break;
  57368. case 1:
  57369. if (this._checkVerticesInsteadOfIndices) {
  57370. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  57371. }
  57372. else {
  57373. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  57374. }
  57375. break;
  57376. case 2:
  57377. if (this._checkVerticesInsteadOfIndices) {
  57378. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  57379. }
  57380. else {
  57381. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  57382. }
  57383. break;
  57384. }
  57385. if (otherEdgeIndex === -1) {
  57386. continue;
  57387. }
  57388. faceAdjacencies.edges[edgeIndex] = otherIndex;
  57389. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  57390. faceAdjacencies.edgesConnectedCount++;
  57391. otherFaceAdjacencies.edgesConnectedCount++;
  57392. if (faceAdjacencies.edgesConnectedCount === 3) {
  57393. break;
  57394. }
  57395. }
  57396. }
  57397. }
  57398. // Create lines
  57399. for (index = 0; index < adjacencies.length; index++) {
  57400. // 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
  57401. var current = adjacencies[index];
  57402. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  57403. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  57404. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  57405. }
  57406. // Merge into a single mesh
  57407. var engine = this._source.getScene().getEngine();
  57408. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  57409. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  57410. this._ib = engine.createIndexBuffer(this._linesIndices);
  57411. this._indicesCount = this._linesIndices.length;
  57412. };
  57413. EdgesRenderer.prototype.render = function () {
  57414. if (!this._lineShader.isReady()) {
  57415. return;
  57416. }
  57417. var scene = this._source.getScene();
  57418. var engine = scene.getEngine();
  57419. this._lineShader._preBind();
  57420. // VBOs
  57421. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  57422. scene.resetCachedMaterial();
  57423. this._lineShader.setColor4("color", this._source.edgesColor);
  57424. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  57425. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  57426. }
  57427. else {
  57428. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  57429. }
  57430. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  57431. this._lineShader.bind(this._source.getWorldMatrix());
  57432. // Draw order
  57433. engine.draw(true, 0, this._indicesCount);
  57434. this._lineShader.unbind();
  57435. engine.setDepthWrite(true);
  57436. };
  57437. return EdgesRenderer;
  57438. }());
  57439. BABYLON.EdgesRenderer = EdgesRenderer;
  57440. })(BABYLON || (BABYLON = {}));
  57441. var BABYLON;
  57442. (function (BABYLON) {
  57443. (function (TonemappingOperator) {
  57444. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  57445. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  57446. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  57447. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  57448. })(BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  57449. var TonemappingOperator = BABYLON.TonemappingOperator;
  57450. ;
  57451. var TonemapPostProcess = (function (_super) {
  57452. __extends(TonemapPostProcess, _super);
  57453. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  57454. var _this = this;
  57455. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  57456. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  57457. _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, defines, textureFormat);
  57458. this._operator = _operator;
  57459. this.exposureAdjustment = exposureAdjustment;
  57460. var defines = "#define ";
  57461. if (this._operator === TonemappingOperator.Hable)
  57462. defines += "HABLE_TONEMAPPING";
  57463. else if (this._operator === TonemappingOperator.Reinhard)
  57464. defines += "REINHARD_TONEMAPPING";
  57465. else if (this._operator === TonemappingOperator.HejiDawson)
  57466. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  57467. else if (this._operator === TonemappingOperator.Photographic)
  57468. defines += "PHOTOGRAPHIC_TONEMAPPING";
  57469. //sadly a second call to create the effect.
  57470. this.updateEffect(defines);
  57471. this.onApply = function (effect) {
  57472. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  57473. };
  57474. }
  57475. return TonemapPostProcess;
  57476. }(BABYLON.PostProcess));
  57477. BABYLON.TonemapPostProcess = TonemapPostProcess;
  57478. })(BABYLON || (BABYLON = {}));
  57479. var BABYLON;
  57480. (function (BABYLON) {
  57481. var ReflectionProbe = (function () {
  57482. function ReflectionProbe(name, size, scene, generateMipMaps) {
  57483. var _this = this;
  57484. if (generateMipMaps === void 0) { generateMipMaps = true; }
  57485. this.name = name;
  57486. this._viewMatrix = BABYLON.Matrix.Identity();
  57487. this._target = BABYLON.Vector3.Zero();
  57488. this._add = BABYLON.Vector3.Zero();
  57489. this.invertYAxis = false;
  57490. this.position = BABYLON.Vector3.Zero();
  57491. this._scene = scene;
  57492. this._scene.reflectionProbes.push(this);
  57493. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  57494. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  57495. switch (faceIndex) {
  57496. case 0:
  57497. _this._add.copyFromFloats(1, 0, 0);
  57498. break;
  57499. case 1:
  57500. _this._add.copyFromFloats(-1, 0, 0);
  57501. break;
  57502. case 2:
  57503. _this._add.copyFromFloats(0, _this.invertYAxis ? 1 : -1, 0);
  57504. break;
  57505. case 3:
  57506. _this._add.copyFromFloats(0, _this.invertYAxis ? -1 : 1, 0);
  57507. break;
  57508. case 4:
  57509. _this._add.copyFromFloats(0, 0, 1);
  57510. break;
  57511. case 5:
  57512. _this._add.copyFromFloats(0, 0, -1);
  57513. break;
  57514. }
  57515. if (_this._attachedMesh) {
  57516. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  57517. }
  57518. _this.position.addToRef(_this._add, _this._target);
  57519. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  57520. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  57521. });
  57522. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  57523. scene.updateTransformMatrix(true);
  57524. });
  57525. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  57526. }
  57527. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  57528. get: function () {
  57529. return this._renderTargetTexture.refreshRate;
  57530. },
  57531. set: function (value) {
  57532. this._renderTargetTexture.refreshRate = value;
  57533. },
  57534. enumerable: true,
  57535. configurable: true
  57536. });
  57537. ReflectionProbe.prototype.getScene = function () {
  57538. return this._scene;
  57539. };
  57540. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  57541. get: function () {
  57542. return this._renderTargetTexture;
  57543. },
  57544. enumerable: true,
  57545. configurable: true
  57546. });
  57547. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  57548. get: function () {
  57549. return this._renderTargetTexture.renderList;
  57550. },
  57551. enumerable: true,
  57552. configurable: true
  57553. });
  57554. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  57555. this._attachedMesh = mesh;
  57556. };
  57557. ReflectionProbe.prototype.dispose = function () {
  57558. var index = this._scene.reflectionProbes.indexOf(this);
  57559. if (index !== -1) {
  57560. // Remove from the scene if found
  57561. this._scene.reflectionProbes.splice(index, 1);
  57562. }
  57563. if (this._renderTargetTexture) {
  57564. this._renderTargetTexture.dispose();
  57565. this._renderTargetTexture = null;
  57566. }
  57567. };
  57568. return ReflectionProbe;
  57569. }());
  57570. BABYLON.ReflectionProbe = ReflectionProbe;
  57571. })(BABYLON || (BABYLON = {}));
  57572. var BABYLON;
  57573. (function (BABYLON) {
  57574. var SolidParticle = (function () {
  57575. function SolidParticle(particleIndex, positionIndex, model, shapeId, idxInShape) {
  57576. this.color = new BABYLON.Color4(1, 1, 1, 1); // color
  57577. this.position = BABYLON.Vector3.Zero(); // position
  57578. this.rotation = BABYLON.Vector3.Zero(); // rotation
  57579. this.scaling = new BABYLON.Vector3(1, 1, 1); // scaling
  57580. this.uvs = new BABYLON.Vector4(0, 0, 1, 1); // uvs
  57581. this.velocity = BABYLON.Vector3.Zero(); // velocity
  57582. this.alive = true; // alive
  57583. this.isVisible = true; // visibility
  57584. this.idx = particleIndex;
  57585. this._pos = positionIndex;
  57586. this._model = model;
  57587. this.shapeId = shapeId;
  57588. this.idxInShape = idxInShape;
  57589. }
  57590. Object.defineProperty(SolidParticle.prototype, "scale", {
  57591. //legacy support, changed scale to scaling
  57592. get: function () {
  57593. return this.scaling;
  57594. },
  57595. set: function (scale) {
  57596. this.scaling = scale;
  57597. },
  57598. enumerable: true,
  57599. configurable: true
  57600. });
  57601. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  57602. //legacy support, changed quaternion to rotationQuaternion
  57603. get: function () {
  57604. return this.rotationQuaternion;
  57605. },
  57606. set: function (q) {
  57607. this.rotationQuaternion = q;
  57608. },
  57609. enumerable: true,
  57610. configurable: true
  57611. });
  57612. return SolidParticle;
  57613. }());
  57614. BABYLON.SolidParticle = SolidParticle;
  57615. var ModelShape = (function () {
  57616. function ModelShape(id, shape, shapeUV, posFunction, vtxFunction) {
  57617. this.shapeID = id;
  57618. this._shape = shape;
  57619. this._shapeUV = shapeUV;
  57620. this._positionFunction = posFunction;
  57621. this._vertexFunction = vtxFunction;
  57622. }
  57623. return ModelShape;
  57624. }());
  57625. BABYLON.ModelShape = ModelShape;
  57626. })(BABYLON || (BABYLON = {}));
  57627. var BABYLON;
  57628. (function (BABYLON) {
  57629. /**
  57630. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  57631. */
  57632. var SolidParticleSystem = (function () {
  57633. /**
  57634. * Creates a SPS (Solid Particle System) object.
  57635. * `name` (String) is the SPS name, this will be the underlying mesh name.
  57636. * `scene` (Scene) is the scene in which the SPS is added.
  57637. * `updatable` (default true) : if the SPS must be updatable or immutable.
  57638. * `isPickable` (default false) : if the solid particles must be pickable.
  57639. */
  57640. function SolidParticleSystem(name, scene, options) {
  57641. // public members
  57642. /**
  57643. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  57644. * Example : var p = SPS.particles[i];
  57645. */
  57646. this.particles = new Array();
  57647. /**
  57648. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  57649. */
  57650. this.nbParticles = 0;
  57651. /**
  57652. * If the particles must ever face the camera (default false). Useful for planar particles.
  57653. */
  57654. this.billboard = false;
  57655. /**
  57656. * Recompute normals when adding a shape
  57657. */
  57658. this.recomputeNormals = true;
  57659. /**
  57660. * This a counter ofr your own usage. It's not set by any SPS functions.
  57661. */
  57662. this.counter = 0;
  57663. /**
  57664. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  57665. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  57666. */
  57667. this.vars = {};
  57668. this._positions = new Array();
  57669. this._indices = new Array();
  57670. this._normals = new Array();
  57671. this._colors = new Array();
  57672. this._uvs = new Array();
  57673. this._index = 0; // indices index
  57674. this._updatable = true;
  57675. this._pickable = false;
  57676. this._isVisibilityBoxLocked = false;
  57677. this._alwaysVisible = false;
  57678. this._shapeCounter = 0;
  57679. this._copy = new BABYLON.SolidParticle(null, null, null, null, null);
  57680. this._color = new BABYLON.Color4(0, 0, 0, 0);
  57681. this._computeParticleColor = true;
  57682. this._computeParticleTexture = true;
  57683. this._computeParticleRotation = true;
  57684. this._computeParticleVertex = false;
  57685. this._computeBoundingBox = false;
  57686. this._cam_axisZ = BABYLON.Vector3.Zero();
  57687. this._cam_axisY = BABYLON.Vector3.Zero();
  57688. this._cam_axisX = BABYLON.Vector3.Zero();
  57689. this._axisX = BABYLON.Axis.X;
  57690. this._axisY = BABYLON.Axis.Y;
  57691. this._axisZ = BABYLON.Axis.Z;
  57692. this._camDir = BABYLON.Vector3.Zero();
  57693. this._rotMatrix = new BABYLON.Matrix();
  57694. this._invertMatrix = new BABYLON.Matrix();
  57695. this._rotated = BABYLON.Vector3.Zero();
  57696. this._quaternion = new BABYLON.Quaternion();
  57697. this._vertex = BABYLON.Vector3.Zero();
  57698. this._normal = BABYLON.Vector3.Zero();
  57699. this._yaw = 0.0;
  57700. this._pitch = 0.0;
  57701. this._roll = 0.0;
  57702. this._halfroll = 0.0;
  57703. this._halfpitch = 0.0;
  57704. this._halfyaw = 0.0;
  57705. this._sinRoll = 0.0;
  57706. this._cosRoll = 0.0;
  57707. this._sinPitch = 0.0;
  57708. this._cosPitch = 0.0;
  57709. this._sinYaw = 0.0;
  57710. this._cosYaw = 0.0;
  57711. this._w = 0.0;
  57712. this._minimum = BABYLON.Tmp.Vector3[0];
  57713. this._maximum = BABYLON.Tmp.Vector3[1];
  57714. this.name = name;
  57715. this._scene = scene;
  57716. this._camera = scene.activeCamera;
  57717. this._pickable = options ? options.isPickable : false;
  57718. if (options && options.updatable) {
  57719. this._updatable = options.updatable;
  57720. }
  57721. else {
  57722. this._updatable = true;
  57723. }
  57724. if (this._pickable) {
  57725. this.pickedParticles = [];
  57726. }
  57727. }
  57728. /**
  57729. * Builds the SPS underlying mesh. Returns a standard Mesh.
  57730. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  57731. */
  57732. SolidParticleSystem.prototype.buildMesh = function () {
  57733. if (this.nbParticles === 0) {
  57734. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  57735. this.addShape(triangle, 1);
  57736. triangle.dispose();
  57737. }
  57738. this._positions32 = new Float32Array(this._positions);
  57739. this._uvs32 = new Float32Array(this._uvs);
  57740. this._colors32 = new Float32Array(this._colors);
  57741. if (this.recomputeNormals) {
  57742. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals);
  57743. }
  57744. this._normals32 = new Float32Array(this._normals);
  57745. this._fixedNormal32 = new Float32Array(this._normals);
  57746. var vertexData = new BABYLON.VertexData();
  57747. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  57748. vertexData.indices = this._indices;
  57749. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  57750. if (this._uvs32) {
  57751. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  57752. ;
  57753. }
  57754. if (this._colors32) {
  57755. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  57756. }
  57757. var mesh = new BABYLON.Mesh(this.name, this._scene);
  57758. vertexData.applyToMesh(mesh, this._updatable);
  57759. this.mesh = mesh;
  57760. this.mesh.isPickable = this._pickable;
  57761. // free memory
  57762. this._positions = null;
  57763. this._normals = null;
  57764. this._uvs = null;
  57765. this._colors = null;
  57766. if (!this._updatable) {
  57767. this.particles.length = 0;
  57768. }
  57769. return mesh;
  57770. };
  57771. /**
  57772. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  57773. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  57774. * Thus the particles generated from `digest()` have their property `position` set yet.
  57775. * `mesh` ( Mesh ) is the mesh to be digested
  57776. * `facetNb` (optional integer, default 1) is the number of mesh facets per particle, this parameter is overriden by the parameter `number` if any
  57777. * `delta` (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  57778. * `number` (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  57779. */
  57780. SolidParticleSystem.prototype.digest = function (mesh, options) {
  57781. var size = (options && options.facetNb) || 1;
  57782. var number = (options && options.number);
  57783. var delta = (options && options.delta) || 0;
  57784. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  57785. var meshInd = mesh.getIndices();
  57786. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  57787. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  57788. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  57789. var f = 0; // facet counter
  57790. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  57791. // compute size from number
  57792. if (number) {
  57793. number = (number > totalFacets) ? totalFacets : number;
  57794. size = Math.round(totalFacets / number);
  57795. delta = 0;
  57796. }
  57797. else {
  57798. size = (size > totalFacets) ? totalFacets : size;
  57799. }
  57800. var facetPos = []; // submesh positions
  57801. var facetInd = []; // submesh indices
  57802. var facetUV = []; // submesh UV
  57803. var facetCol = []; // submesh colors
  57804. var barycenter = BABYLON.Tmp.Vector3[0];
  57805. var rand;
  57806. var sizeO = size;
  57807. while (f < totalFacets) {
  57808. size = sizeO + Math.floor((1 + delta) * Math.random());
  57809. if (f > totalFacets - size) {
  57810. size = totalFacets - f;
  57811. }
  57812. // reset temp arrays
  57813. facetPos.length = 0;
  57814. facetInd.length = 0;
  57815. facetUV.length = 0;
  57816. facetCol.length = 0;
  57817. // iterate over "size" facets
  57818. var fi = 0;
  57819. for (var j = f * 3; j < (f + size) * 3; j++) {
  57820. facetInd.push(fi);
  57821. var i = meshInd[j];
  57822. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  57823. if (meshUV) {
  57824. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  57825. }
  57826. if (meshCol) {
  57827. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  57828. }
  57829. fi++;
  57830. }
  57831. // create a model shape for each single particle
  57832. var idx = this.nbParticles;
  57833. var shape = this._posToShape(facetPos);
  57834. var shapeUV = this._uvsToShapeUV(facetUV);
  57835. // compute the barycenter of the shape
  57836. var v;
  57837. for (v = 0; v < shape.length; v++) {
  57838. barycenter.addInPlace(shape[v]);
  57839. }
  57840. barycenter.scaleInPlace(1 / shape.length);
  57841. // shift the shape from its barycenter to the origin
  57842. for (v = 0; v < shape.length; v++) {
  57843. shape[v].subtractInPlace(barycenter);
  57844. }
  57845. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, null, null);
  57846. // add the particle in the SPS
  57847. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  57848. this._addParticle(idx, this._positions.length, modelShape, this._shapeCounter, 0);
  57849. // initialize the particle position
  57850. this.particles[this.nbParticles].position.addInPlace(barycenter);
  57851. this._index += shape.length;
  57852. idx++;
  57853. this.nbParticles++;
  57854. this._shapeCounter++;
  57855. f += size;
  57856. }
  57857. return this;
  57858. };
  57859. //reset copy
  57860. SolidParticleSystem.prototype._resetCopy = function () {
  57861. this._copy.position.x = 0;
  57862. this._copy.position.y = 0;
  57863. this._copy.position.z = 0;
  57864. this._copy.rotation.x = 0;
  57865. this._copy.rotation.y = 0;
  57866. this._copy.rotation.z = 0;
  57867. this._copy.rotationQuaternion = null;
  57868. this._copy.scaling.x = 1;
  57869. this._copy.scaling.y = 1;
  57870. this._copy.scaling.z = 1;
  57871. this._copy.uvs.x = 0;
  57872. this._copy.uvs.y = 0;
  57873. this._copy.uvs.z = 1;
  57874. this._copy.uvs.w = 1;
  57875. this._copy.color = null;
  57876. };
  57877. // _meshBuilder : inserts the shape model in the global SPS mesh
  57878. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  57879. var i;
  57880. var u = 0;
  57881. var c = 0;
  57882. var n = 0;
  57883. this._resetCopy();
  57884. if (options && options.positionFunction) {
  57885. options.positionFunction(this._copy, idx, idxInShape);
  57886. }
  57887. if (this._copy.rotationQuaternion) {
  57888. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  57889. }
  57890. else {
  57891. this._yaw = this._copy.rotation.y;
  57892. this._pitch = this._copy.rotation.x;
  57893. this._roll = this._copy.rotation.z;
  57894. this._quaternionRotationYPR();
  57895. }
  57896. this._quaternionToRotationMatrix();
  57897. for (i = 0; i < shape.length; i++) {
  57898. this._vertex.x = shape[i].x;
  57899. this._vertex.y = shape[i].y;
  57900. this._vertex.z = shape[i].z;
  57901. if (options && options.vertexFunction) {
  57902. options.vertexFunction(this._copy, this._vertex, i);
  57903. }
  57904. this._vertex.x *= this._copy.scaling.x;
  57905. this._vertex.y *= this._copy.scaling.y;
  57906. this._vertex.z *= this._copy.scaling.z;
  57907. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  57908. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  57909. if (meshUV) {
  57910. 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);
  57911. u += 2;
  57912. }
  57913. if (this._copy.color) {
  57914. this._color = this._copy.color;
  57915. }
  57916. else if (meshCol && meshCol[c] !== undefined) {
  57917. this._color.r = meshCol[c];
  57918. this._color.g = meshCol[c + 1];
  57919. this._color.b = meshCol[c + 2];
  57920. this._color.a = meshCol[c + 3];
  57921. }
  57922. else {
  57923. this._color.r = 1;
  57924. this._color.g = 1;
  57925. this._color.b = 1;
  57926. this._color.a = 1;
  57927. }
  57928. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  57929. c += 4;
  57930. if (!this.recomputeNormals && meshNor) {
  57931. this._normal.x = meshNor[n];
  57932. this._normal.y = meshNor[n + 1];
  57933. this._normal.z = meshNor[n + 2];
  57934. BABYLON.Vector3.TransformCoordinatesToRef(this._normal, this._rotMatrix, this._normal);
  57935. normals.push(this._normal.x, this._normal.y, this._normal.z);
  57936. n += 3;
  57937. }
  57938. }
  57939. for (i = 0; i < meshInd.length; i++) {
  57940. indices.push(p + meshInd[i]);
  57941. }
  57942. if (this._pickable) {
  57943. var nbfaces = meshInd.length / 3;
  57944. for (i = 0; i < nbfaces; i++) {
  57945. this.pickedParticles.push({ idx: idx, faceId: i });
  57946. }
  57947. }
  57948. };
  57949. // returns a shape array from positions array
  57950. SolidParticleSystem.prototype._posToShape = function (positions) {
  57951. var shape = [];
  57952. for (var i = 0; i < positions.length; i += 3) {
  57953. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  57954. }
  57955. return shape;
  57956. };
  57957. // returns a shapeUV array from a Vector4 uvs
  57958. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  57959. var shapeUV = [];
  57960. if (uvs) {
  57961. for (var i = 0; i < uvs.length; i++)
  57962. shapeUV.push(uvs[i]);
  57963. }
  57964. return shapeUV;
  57965. };
  57966. // adds a new particle object in the particles array
  57967. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, model, shapeId, idxInShape) {
  57968. this.particles.push(new BABYLON.SolidParticle(idx, idxpos, model, shapeId, idxInShape));
  57969. };
  57970. /**
  57971. * Adds some particles to the SPS from the model shape. Returns the shape id.
  57972. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  57973. * `mesh` is any Mesh object that will be used as a model for the solid particles.
  57974. * `nb` (positive integer) the number of particles to be created from this model
  57975. * `positionFunction` is an optional javascript function to called for each particle on SPS creation.
  57976. * `vertexFunction` is an optional javascript function to called for each vertex of each particle on SPS creation
  57977. */
  57978. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  57979. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  57980. var meshInd = mesh.getIndices();
  57981. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  57982. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  57983. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  57984. var shape = this._posToShape(meshPos);
  57985. var shapeUV = this._uvsToShapeUV(meshUV);
  57986. var posfunc = options ? options.positionFunction : null;
  57987. var vtxfunc = options ? options.vertexFunction : null;
  57988. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, posfunc, vtxfunc);
  57989. // particles
  57990. var idx = this.nbParticles;
  57991. for (var i = 0; i < nb; i++) {
  57992. this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  57993. if (this._updatable) {
  57994. this._addParticle(idx, this._positions.length, modelShape, this._shapeCounter, i);
  57995. }
  57996. this._index += shape.length;
  57997. idx++;
  57998. }
  57999. this.nbParticles += nb;
  58000. this._shapeCounter++;
  58001. return this._shapeCounter - 1;
  58002. };
  58003. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  58004. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  58005. this._resetCopy();
  58006. if (particle._model._positionFunction) {
  58007. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  58008. }
  58009. if (this._copy.rotationQuaternion) {
  58010. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  58011. }
  58012. else {
  58013. this._yaw = this._copy.rotation.y;
  58014. this._pitch = this._copy.rotation.x;
  58015. this._roll = this._copy.rotation.z;
  58016. this._quaternionRotationYPR();
  58017. }
  58018. this._quaternionToRotationMatrix();
  58019. this._shape = particle._model._shape;
  58020. for (var pt = 0; pt < this._shape.length; pt++) {
  58021. this._vertex.x = this._shape[pt].x;
  58022. this._vertex.y = this._shape[pt].y;
  58023. this._vertex.z = this._shape[pt].z;
  58024. if (particle._model._vertexFunction) {
  58025. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  58026. }
  58027. this._vertex.x *= this._copy.scaling.x;
  58028. this._vertex.y *= this._copy.scaling.y;
  58029. this._vertex.z *= this._copy.scaling.z;
  58030. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  58031. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  58032. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  58033. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  58034. }
  58035. particle.position.x = 0;
  58036. particle.position.y = 0;
  58037. particle.position.z = 0;
  58038. particle.rotation.x = 0;
  58039. particle.rotation.y = 0;
  58040. particle.rotation.z = 0;
  58041. particle.rotationQuaternion = null;
  58042. particle.scaling.x = 1;
  58043. particle.scaling.y = 1;
  58044. particle.scaling.z = 1;
  58045. };
  58046. /**
  58047. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  58048. */
  58049. SolidParticleSystem.prototype.rebuildMesh = function () {
  58050. for (var p = 0; p < this.particles.length; p++) {
  58051. this._rebuildParticle(this.particles[p]);
  58052. }
  58053. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  58054. };
  58055. /**
  58056. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  58057. * This method calls `updateParticle()` for each particle of the SPS.
  58058. * For an animated SPS, it is usually called within the render loop.
  58059. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  58060. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  58061. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  58062. */
  58063. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  58064. if (start === void 0) { start = 0; }
  58065. if (end === void 0) { end = this.nbParticles - 1; }
  58066. if (update === void 0) { update = true; }
  58067. if (!this._updatable) {
  58068. return;
  58069. }
  58070. // custom beforeUpdate
  58071. this.beforeUpdateParticles(start, end, update);
  58072. this._cam_axisX.x = 1.0;
  58073. this._cam_axisX.y = 0.0;
  58074. this._cam_axisX.z = 0.0;
  58075. this._cam_axisY.x = 0.0;
  58076. this._cam_axisY.y = 1.0;
  58077. this._cam_axisY.z = 0.0;
  58078. this._cam_axisZ.x = 0.0;
  58079. this._cam_axisZ.y = 0.0;
  58080. this._cam_axisZ.z = 1.0;
  58081. // if the particles will always face the camera
  58082. if (this.billboard) {
  58083. // compute the camera position and un-rotate it by the current mesh rotation
  58084. this._yaw = this.mesh.rotation.y;
  58085. this._pitch = this.mesh.rotation.x;
  58086. this._roll = this.mesh.rotation.z;
  58087. this._quaternionRotationYPR();
  58088. this._quaternionToRotationMatrix();
  58089. this._rotMatrix.invertToRef(this._invertMatrix);
  58090. this._camera._currentTarget.subtractToRef(this._camera.globalPosition, this._camDir);
  58091. BABYLON.Vector3.TransformCoordinatesToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  58092. this._cam_axisZ.normalize();
  58093. // set two orthogonal vectors (_cam_axisX and and _cam_axisY) to the rotated camDir axis (_cam_axisZ)
  58094. BABYLON.Vector3.CrossToRef(this._cam_axisZ, this._axisX, this._cam_axisY);
  58095. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  58096. this._cam_axisY.normalize();
  58097. this._cam_axisX.normalize();
  58098. }
  58099. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  58100. var idx = 0;
  58101. var index = 0;
  58102. var colidx = 0;
  58103. var colorIndex = 0;
  58104. var uvidx = 0;
  58105. var uvIndex = 0;
  58106. var pt = 0;
  58107. if (this._computeBoundingBox) {
  58108. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  58109. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  58110. }
  58111. // particle loop
  58112. end = (end > this.nbParticles - 1) ? this.nbParticles - 1 : end;
  58113. for (var p = start; p <= end; p++) {
  58114. this._particle = this.particles[p];
  58115. this._shape = this._particle._model._shape;
  58116. this._shapeUV = this._particle._model._shapeUV;
  58117. // call to custom user function to update the particle properties
  58118. this.updateParticle(this._particle);
  58119. if (this._particle.isVisible) {
  58120. // particle rotation matrix
  58121. if (this.billboard) {
  58122. this._particle.rotation.x = 0.0;
  58123. this._particle.rotation.y = 0.0;
  58124. }
  58125. if (this._computeParticleRotation || this.billboard) {
  58126. if (this._particle.rotationQuaternion) {
  58127. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  58128. }
  58129. else {
  58130. this._yaw = this._particle.rotation.y;
  58131. this._pitch = this._particle.rotation.x;
  58132. this._roll = this._particle.rotation.z;
  58133. this._quaternionRotationYPR();
  58134. }
  58135. this._quaternionToRotationMatrix();
  58136. }
  58137. // particle vertex loop
  58138. for (pt = 0; pt < this._shape.length; pt++) {
  58139. idx = index + pt * 3;
  58140. colidx = colorIndex + pt * 4;
  58141. uvidx = uvIndex + pt * 2;
  58142. this._vertex.x = this._shape[pt].x;
  58143. this._vertex.y = this._shape[pt].y;
  58144. this._vertex.z = this._shape[pt].z;
  58145. if (this._computeParticleVertex) {
  58146. this.updateParticleVertex(this._particle, this._vertex, pt);
  58147. }
  58148. // positions
  58149. this._vertex.x *= this._particle.scaling.x;
  58150. this._vertex.y *= this._particle.scaling.y;
  58151. this._vertex.z *= this._particle.scaling.z;
  58152. 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];
  58153. 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;
  58154. 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;
  58155. 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;
  58156. 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;
  58157. 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;
  58158. 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;
  58159. if (this._computeBoundingBox) {
  58160. if (this._positions32[idx] < this._minimum.x) {
  58161. this._minimum.x = this._positions32[idx];
  58162. }
  58163. if (this._positions32[idx] > this._maximum.x) {
  58164. this._maximum.x = this._positions32[idx];
  58165. }
  58166. if (this._positions32[idx + 1] < this._minimum.y) {
  58167. this._minimum.y = this._positions32[idx + 1];
  58168. }
  58169. if (this._positions32[idx + 1] > this._maximum.y) {
  58170. this._maximum.y = this._positions32[idx + 1];
  58171. }
  58172. if (this._positions32[idx + 2] < this._minimum.z) {
  58173. this._minimum.z = this._positions32[idx + 2];
  58174. }
  58175. if (this._positions32[idx + 2] > this._maximum.z) {
  58176. this._maximum.z = this._positions32[idx + 2];
  58177. }
  58178. }
  58179. // normals : if the particles can't be morphed then just rotate the normals, what if much more faster than ComputeNormals()
  58180. if (!this._computeParticleVertex) {
  58181. this._normal.x = this._fixedNormal32[idx];
  58182. this._normal.y = this._fixedNormal32[idx + 1];
  58183. this._normal.z = this._fixedNormal32[idx + 2];
  58184. 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];
  58185. 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;
  58186. 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;
  58187. 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;
  58188. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  58189. 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;
  58190. 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;
  58191. }
  58192. if (this._computeParticleColor) {
  58193. this._colors32[colidx] = this._particle.color.r;
  58194. this._colors32[colidx + 1] = this._particle.color.g;
  58195. this._colors32[colidx + 2] = this._particle.color.b;
  58196. this._colors32[colidx + 3] = this._particle.color.a;
  58197. }
  58198. if (this._computeParticleTexture) {
  58199. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  58200. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  58201. }
  58202. }
  58203. }
  58204. else {
  58205. for (pt = 0; pt < this._shape.length; pt++) {
  58206. idx = index + pt * 3;
  58207. colidx = colorIndex + pt * 4;
  58208. uvidx = uvIndex + pt * 2;
  58209. this._positions32[idx] = this._camera.position.x;
  58210. this._positions32[idx + 1] = this._camera.position.y;
  58211. this._positions32[idx + 2] = this._camera.position.z;
  58212. this._normals32[idx] = 0.0;
  58213. this._normals32[idx + 1] = 0.0;
  58214. this._normals32[idx + 2] = 0.0;
  58215. if (this._computeParticleColor) {
  58216. this._colors32[colidx] = this._particle.color.r;
  58217. this._colors32[colidx + 1] = this._particle.color.g;
  58218. this._colors32[colidx + 2] = this._particle.color.b;
  58219. this._colors32[colidx + 3] = this._particle.color.a;
  58220. }
  58221. if (this._computeParticleTexture) {
  58222. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  58223. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  58224. }
  58225. }
  58226. }
  58227. // increment indexes for the next particle
  58228. index = idx + 3;
  58229. colorIndex = colidx + 4;
  58230. uvIndex = uvidx + 2;
  58231. }
  58232. // if the VBO must be updated
  58233. if (update) {
  58234. if (this._computeParticleColor) {
  58235. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  58236. }
  58237. if (this._computeParticleTexture) {
  58238. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  58239. }
  58240. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  58241. if (!this.mesh.areNormalsFrozen) {
  58242. if (this._computeParticleVertex) {
  58243. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  58244. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals32);
  58245. for (var i = 0; i < this._normals32.length; i++) {
  58246. this._fixedNormal32[i] = this._normals32[i];
  58247. }
  58248. }
  58249. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  58250. }
  58251. }
  58252. if (this._computeBoundingBox) {
  58253. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  58254. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  58255. }
  58256. this.afterUpdateParticles(start, end, update);
  58257. };
  58258. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  58259. this._halfroll = this._roll * 0.5;
  58260. this._halfpitch = this._pitch * 0.5;
  58261. this._halfyaw = this._yaw * 0.5;
  58262. this._sinRoll = Math.sin(this._halfroll);
  58263. this._cosRoll = Math.cos(this._halfroll);
  58264. this._sinPitch = Math.sin(this._halfpitch);
  58265. this._cosPitch = Math.cos(this._halfpitch);
  58266. this._sinYaw = Math.sin(this._halfyaw);
  58267. this._cosYaw = Math.cos(this._halfyaw);
  58268. this._quaternion.x = (this._cosYaw * this._sinPitch * this._cosRoll) + (this._sinYaw * this._cosPitch * this._sinRoll);
  58269. this._quaternion.y = (this._sinYaw * this._cosPitch * this._cosRoll) - (this._cosYaw * this._sinPitch * this._sinRoll);
  58270. this._quaternion.z = (this._cosYaw * this._cosPitch * this._sinRoll) - (this._sinYaw * this._sinPitch * this._cosRoll);
  58271. this._quaternion.w = (this._cosYaw * this._cosPitch * this._cosRoll) + (this._sinYaw * this._sinPitch * this._sinRoll);
  58272. };
  58273. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  58274. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  58275. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  58276. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  58277. this._rotMatrix.m[3] = 0;
  58278. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  58279. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  58280. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  58281. this._rotMatrix.m[7] = 0;
  58282. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  58283. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  58284. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  58285. this._rotMatrix.m[11] = 0;
  58286. this._rotMatrix.m[12] = 0;
  58287. this._rotMatrix.m[13] = 0;
  58288. this._rotMatrix.m[14] = 0;
  58289. this._rotMatrix.m[15] = 1.0;
  58290. };
  58291. /**
  58292. * Disposes the SPS
  58293. */
  58294. SolidParticleSystem.prototype.dispose = function () {
  58295. this.mesh.dispose();
  58296. this.vars = null;
  58297. // drop references to internal big arrays for the GC
  58298. this._positions = null;
  58299. this._indices = null;
  58300. this._normals = null;
  58301. this._uvs = null;
  58302. this._colors = null;
  58303. this._positions32 = null;
  58304. this._normals32 = null;
  58305. this._fixedNormal32 = null;
  58306. this._uvs32 = null;
  58307. this._colors32 = null;
  58308. this.pickedParticles = null;
  58309. };
  58310. /**
  58311. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  58312. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  58313. */
  58314. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  58315. if (!this._isVisibilityBoxLocked) {
  58316. this.mesh.refreshBoundingInfo();
  58317. }
  58318. };
  58319. /**
  58320. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  58321. * @param size the size (float) of the visibility box
  58322. * note : this doesn't lock the SPS mesh bounding box.
  58323. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  58324. */
  58325. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  58326. var vis = size / 2;
  58327. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  58328. };
  58329. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  58330. // getter and setter
  58331. get: function () {
  58332. return this._alwaysVisible;
  58333. },
  58334. /**
  58335. * Sets the SPS as always visible or not
  58336. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  58337. */
  58338. set: function (val) {
  58339. this._alwaysVisible = val;
  58340. this.mesh.alwaysSelectAsActiveMesh = val;
  58341. },
  58342. enumerable: true,
  58343. configurable: true
  58344. });
  58345. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  58346. get: function () {
  58347. return this._isVisibilityBoxLocked;
  58348. },
  58349. /**
  58350. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  58351. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  58352. */
  58353. set: function (val) {
  58354. this._isVisibilityBoxLocked = val;
  58355. this.mesh.getBoundingInfo().isLocked = val;
  58356. },
  58357. enumerable: true,
  58358. configurable: true
  58359. });
  58360. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  58361. // getters
  58362. get: function () {
  58363. return this._computeParticleRotation;
  58364. },
  58365. // Optimizer setters
  58366. /**
  58367. * Tells to `setParticles()` to compute the particle rotations or not.
  58368. * Default value : true. The SPS is faster when it's set to false.
  58369. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  58370. */
  58371. set: function (val) {
  58372. this._computeParticleRotation = val;
  58373. },
  58374. enumerable: true,
  58375. configurable: true
  58376. });
  58377. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  58378. get: function () {
  58379. return this._computeParticleColor;
  58380. },
  58381. /**
  58382. * Tells to `setParticles()` to compute the particle colors or not.
  58383. * Default value : true. The SPS is faster when it's set to false.
  58384. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  58385. */
  58386. set: function (val) {
  58387. this._computeParticleColor = val;
  58388. },
  58389. enumerable: true,
  58390. configurable: true
  58391. });
  58392. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  58393. get: function () {
  58394. return this._computeParticleTexture;
  58395. },
  58396. /**
  58397. * Tells to `setParticles()` to compute the particle textures or not.
  58398. * Default value : true. The SPS is faster when it's set to false.
  58399. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  58400. */
  58401. set: function (val) {
  58402. this._computeParticleTexture = val;
  58403. },
  58404. enumerable: true,
  58405. configurable: true
  58406. });
  58407. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  58408. get: function () {
  58409. return this._computeParticleVertex;
  58410. },
  58411. /**
  58412. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  58413. * Default value : false. The SPS is faster when it's set to false.
  58414. * Note : the particle custom vertex positions aren't stored values.
  58415. */
  58416. set: function (val) {
  58417. this._computeParticleVertex = val;
  58418. },
  58419. enumerable: true,
  58420. configurable: true
  58421. });
  58422. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  58423. get: function () {
  58424. return this._computeBoundingBox;
  58425. },
  58426. /**
  58427. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  58428. */
  58429. set: function (val) {
  58430. this._computeBoundingBox = val;
  58431. },
  58432. enumerable: true,
  58433. configurable: true
  58434. });
  58435. // =======================================================================
  58436. // Particle behavior logic
  58437. // these following methods may be overwritten by the user to fit his needs
  58438. /**
  58439. * This function does nothing. It may be overwritten to set all the particle first values.
  58440. * The SPS doesn't call this function, you may have to call it by your own.
  58441. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  58442. */
  58443. SolidParticleSystem.prototype.initParticles = function () {
  58444. };
  58445. /**
  58446. * This function does nothing. It may be overwritten to recycle a particle.
  58447. * The SPS doesn't call this function, you may have to call it by your own.
  58448. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  58449. */
  58450. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  58451. return particle;
  58452. };
  58453. /**
  58454. * Updates a particle : this function should be overwritten by the user.
  58455. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  58456. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  58457. * ex : just set a particle position or velocity and recycle conditions
  58458. */
  58459. SolidParticleSystem.prototype.updateParticle = function (particle) {
  58460. return particle;
  58461. };
  58462. /**
  58463. * Updates a vertex of a particle : it can be overwritten by the user.
  58464. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  58465. * @param particle the current particle
  58466. * @param vertex the current index of the current particle
  58467. * @param pt the index of the current vertex in the particle shape
  58468. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  58469. * ex : just set a vertex particle position
  58470. */
  58471. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  58472. return vertex;
  58473. };
  58474. /**
  58475. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  58476. * This does nothing and may be overwritten by the user.
  58477. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  58478. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  58479. * @param update the boolean update value actually passed to setParticles()
  58480. */
  58481. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  58482. };
  58483. /**
  58484. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  58485. * This will be passed three parameters.
  58486. * This does nothing and may be overwritten by the user.
  58487. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  58488. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  58489. * @param update the boolean update value actually passed to setParticles()
  58490. */
  58491. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  58492. };
  58493. return SolidParticleSystem;
  58494. }());
  58495. BABYLON.SolidParticleSystem = SolidParticleSystem;
  58496. })(BABYLON || (BABYLON = {}));
  58497. var BABYLON;
  58498. (function (BABYLON) {
  58499. var Internals;
  58500. (function (Internals) {
  58501. var FileFaceOrientation = (function () {
  58502. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  58503. this.name = name;
  58504. this.worldAxisForNormal = worldAxisForNormal;
  58505. this.worldAxisForFileX = worldAxisForFileX;
  58506. this.worldAxisForFileY = worldAxisForFileY;
  58507. }
  58508. return FileFaceOrientation;
  58509. }());
  58510. ;
  58511. /**
  58512. * Helper class dealing with the extraction of spherical polynomial dataArray
  58513. * from a cube map.
  58514. */
  58515. var CubeMapToSphericalPolynomialTools = (function () {
  58516. function CubeMapToSphericalPolynomialTools() {
  58517. }
  58518. /**
  58519. * Converts a cubemap to the according Spherical Polynomial data.
  58520. * This extracts the first 3 orders only as they are the only one used in the lighting.
  58521. *
  58522. * @param cubeInfo The Cube map to extract the information from.
  58523. * @return The Spherical Polynomial data.
  58524. */
  58525. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  58526. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  58527. var totalSolidAngle = 0.0;
  58528. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  58529. var du = 2.0 / cubeInfo.size;
  58530. var dv = du;
  58531. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  58532. var minUV = du * 0.5 - 1.0;
  58533. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  58534. var fileFace = this.FileFaces[faceIndex];
  58535. var dataArray = cubeInfo[fileFace.name];
  58536. var v = minUV;
  58537. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  58538. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  58539. // Because SP is still linear, so summation is fine in that basis.
  58540. for (var y = 0; y < cubeInfo.size; y++) {
  58541. var u = minUV;
  58542. for (var x = 0; x < cubeInfo.size; x++) {
  58543. // World direction (not normalised)
  58544. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  58545. worldDirection.normalize();
  58546. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  58547. if (1) {
  58548. var r = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0];
  58549. var g = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1];
  58550. var b = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2];
  58551. var color = new BABYLON.Color3(r, g, b);
  58552. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  58553. }
  58554. else {
  58555. if (faceIndex == 0) {
  58556. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  58557. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  58558. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  58559. }
  58560. else if (faceIndex == 1) {
  58561. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  58562. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  58563. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  58564. }
  58565. else if (faceIndex == 2) {
  58566. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  58567. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  58568. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  58569. }
  58570. else if (faceIndex == 3) {
  58571. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  58572. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  58573. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  58574. }
  58575. else if (faceIndex == 4) {
  58576. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  58577. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  58578. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  58579. }
  58580. else if (faceIndex == 5) {
  58581. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  58582. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  58583. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  58584. }
  58585. 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]);
  58586. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  58587. }
  58588. totalSolidAngle += deltaSolidAngle;
  58589. u += du;
  58590. }
  58591. v += dv;
  58592. }
  58593. }
  58594. var correctSolidAngle = 4.0 * Math.PI; // Solid angle for entire sphere is 4*pi
  58595. var correction = correctSolidAngle / totalSolidAngle;
  58596. sphericalHarmonics.scale(correction);
  58597. // Additionally scale by pi -- audit needed
  58598. sphericalHarmonics.scale(1.0 / Math.PI);
  58599. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  58600. };
  58601. CubeMapToSphericalPolynomialTools.FileFaces = [
  58602. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  58603. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  58604. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  58605. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  58606. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  58607. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  58608. ];
  58609. return CubeMapToSphericalPolynomialTools;
  58610. }());
  58611. Internals.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  58612. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  58613. })(BABYLON || (BABYLON = {}));
  58614. var BABYLON;
  58615. (function (BABYLON) {
  58616. var Internals;
  58617. (function (Internals) {
  58618. /**
  58619. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  58620. */
  58621. var PanoramaToCubeMapTools = (function () {
  58622. function PanoramaToCubeMapTools() {
  58623. }
  58624. /**
  58625. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  58626. *
  58627. * @param float32Array The source data.
  58628. * @param inputWidth The width of the input panorama.
  58629. * @param inputhHeight The height of the input panorama.
  58630. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  58631. * @return The cubemap data
  58632. */
  58633. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  58634. if (!float32Array) {
  58635. throw "ConvertPanoramaToCubemap: input cannot be null";
  58636. }
  58637. if (float32Array.length != inputWidth * inputHeight * 3) {
  58638. throw "ConvertPanoramaToCubemap: input size is wrong";
  58639. }
  58640. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  58641. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  58642. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  58643. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  58644. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  58645. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  58646. return {
  58647. front: textureFront,
  58648. back: textureBack,
  58649. left: textureLeft,
  58650. right: textureRight,
  58651. up: textureUp,
  58652. down: textureDown,
  58653. size: size
  58654. };
  58655. };
  58656. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  58657. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  58658. var textureArray = new Float32Array(buffer);
  58659. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  58660. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  58661. var dy = 1 / texSize;
  58662. var fy = 0;
  58663. for (var y = 0; y < texSize; y++) {
  58664. var xv1 = faceData[0];
  58665. var xv2 = faceData[2];
  58666. for (var x = 0; x < texSize; x++) {
  58667. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  58668. v.normalize();
  58669. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  58670. // 3 channels per pixels
  58671. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  58672. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  58673. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  58674. xv1 = xv1.add(rotDX1);
  58675. xv2 = xv2.add(rotDX2);
  58676. }
  58677. fy += dy;
  58678. }
  58679. return textureArray;
  58680. };
  58681. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  58682. var theta = Math.atan2(vDir.z, vDir.x);
  58683. var phi = Math.acos(vDir.y);
  58684. while (theta < -Math.PI)
  58685. theta += 2 * Math.PI;
  58686. while (theta > Math.PI)
  58687. theta -= 2 * Math.PI;
  58688. var dx = theta / Math.PI;
  58689. var dy = phi / Math.PI;
  58690. // recenter.
  58691. dx = dx * 0.5 + 0.5;
  58692. var px = Math.round(dx * inputWidth);
  58693. if (px < 0)
  58694. px = 0;
  58695. else if (px >= inputWidth)
  58696. px = inputWidth - 1;
  58697. var py = Math.round(dy * inputHeight);
  58698. if (py < 0)
  58699. py = 0;
  58700. else if (py >= inputHeight)
  58701. py = inputHeight - 1;
  58702. var inputY = (inputHeight - py - 1);
  58703. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  58704. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  58705. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  58706. return {
  58707. r: r,
  58708. g: g,
  58709. b: b
  58710. };
  58711. };
  58712. PanoramaToCubeMapTools.FACE_FRONT = [
  58713. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  58714. new BABYLON.Vector3(1.0, -1.0, -1.0),
  58715. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  58716. new BABYLON.Vector3(1.0, 1.0, -1.0)
  58717. ];
  58718. PanoramaToCubeMapTools.FACE_BACK = [
  58719. new BABYLON.Vector3(1.0, -1.0, 1.0),
  58720. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  58721. new BABYLON.Vector3(1.0, 1.0, 1.0),
  58722. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  58723. ];
  58724. PanoramaToCubeMapTools.FACE_RIGHT = [
  58725. new BABYLON.Vector3(1.0, -1.0, -1.0),
  58726. new BABYLON.Vector3(1.0, -1.0, 1.0),
  58727. new BABYLON.Vector3(1.0, 1.0, -1.0),
  58728. new BABYLON.Vector3(1.0, 1.0, 1.0)
  58729. ];
  58730. PanoramaToCubeMapTools.FACE_LEFT = [
  58731. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  58732. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  58733. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  58734. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  58735. ];
  58736. PanoramaToCubeMapTools.FACE_DOWN = [
  58737. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  58738. new BABYLON.Vector3(1.0, 1.0, -1.0),
  58739. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  58740. new BABYLON.Vector3(1.0, 1.0, 1.0)
  58741. ];
  58742. PanoramaToCubeMapTools.FACE_UP = [
  58743. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  58744. new BABYLON.Vector3(1.0, -1.0, 1.0),
  58745. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  58746. new BABYLON.Vector3(1.0, -1.0, -1.0)
  58747. ];
  58748. return PanoramaToCubeMapTools;
  58749. }());
  58750. Internals.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  58751. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  58752. })(BABYLON || (BABYLON = {}));
  58753. var BABYLON;
  58754. (function (BABYLON) {
  58755. var Internals;
  58756. (function (Internals) {
  58757. ;
  58758. /**
  58759. * This groups tools to convert HDR texture to native colors array.
  58760. */
  58761. var HDRTools = (function () {
  58762. function HDRTools() {
  58763. }
  58764. HDRTools.Ldexp = function (mantissa, exponent) {
  58765. if (exponent > 1023) {
  58766. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  58767. }
  58768. if (exponent < -1074) {
  58769. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  58770. }
  58771. return mantissa * Math.pow(2, exponent);
  58772. };
  58773. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  58774. if (exponent > 0) {
  58775. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  58776. float32array[index + 0] = red * exponent;
  58777. float32array[index + 1] = green * exponent;
  58778. float32array[index + 2] = blue * exponent;
  58779. }
  58780. else {
  58781. float32array[index + 0] = 0;
  58782. float32array[index + 1] = 0;
  58783. float32array[index + 2] = 0;
  58784. }
  58785. };
  58786. HDRTools.readStringLine = function (uint8array, startIndex) {
  58787. var line = "";
  58788. var character = "";
  58789. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  58790. character = String.fromCharCode(uint8array[i]);
  58791. if (character == "\n") {
  58792. break;
  58793. }
  58794. line += character;
  58795. }
  58796. return line;
  58797. };
  58798. /**
  58799. * Reads header information from an RGBE texture stored in a native array.
  58800. * More information on this format are available here:
  58801. * https://en.wikipedia.org/wiki/RGBE_image_format
  58802. *
  58803. * @param uint8array The binary file stored in native array.
  58804. * @return The header information.
  58805. */
  58806. HDRTools.RGBE_ReadHeader = function (uint8array) {
  58807. var height = 0;
  58808. var width = 0;
  58809. var line = this.readStringLine(uint8array, 0);
  58810. if (line[0] != '#' || line[1] != '?') {
  58811. throw "Bad HDR Format.";
  58812. }
  58813. var endOfHeader = false;
  58814. var findFormat = false;
  58815. var lineIndex = 0;
  58816. do {
  58817. lineIndex += (line.length + 1);
  58818. line = this.readStringLine(uint8array, lineIndex);
  58819. if (line == "FORMAT=32-bit_rle_rgbe") {
  58820. findFormat = true;
  58821. }
  58822. else if (line.length == 0) {
  58823. endOfHeader = true;
  58824. }
  58825. } while (!endOfHeader);
  58826. if (!findFormat) {
  58827. throw "HDR Bad header format, unsupported FORMAT";
  58828. }
  58829. lineIndex += (line.length + 1);
  58830. line = this.readStringLine(uint8array, lineIndex);
  58831. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  58832. var match = sizeRegexp.exec(line);
  58833. // TODO. Support +Y and -X if needed.
  58834. if (match.length < 3) {
  58835. throw "HDR Bad header format, no size";
  58836. }
  58837. width = parseInt(match[2]);
  58838. height = parseInt(match[1]);
  58839. if (width < 8 || width > 0x7fff) {
  58840. throw "HDR Bad header format, unsupported size";
  58841. }
  58842. lineIndex += (line.length + 1);
  58843. return {
  58844. height: height,
  58845. width: width,
  58846. dataPosition: lineIndex
  58847. };
  58848. };
  58849. /**
  58850. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  58851. * This RGBE texture needs to store the information as a panorama.
  58852. *
  58853. * More information on this format are available here:
  58854. * https://en.wikipedia.org/wiki/RGBE_image_format
  58855. *
  58856. * @param buffer The binary file stored in an array buffer.
  58857. * @param size The expected size of the extracted cubemap.
  58858. * @return The Cube Map information.
  58859. */
  58860. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  58861. var uint8array = new Uint8Array(buffer);
  58862. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  58863. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  58864. var cubeMapData = Internals.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  58865. return cubeMapData;
  58866. };
  58867. /**
  58868. * Returns the pixels data extracted from an RGBE texture.
  58869. * This pixels will be stored left to right up to down in the R G B order in one array.
  58870. *
  58871. * More information on this format are available here:
  58872. * https://en.wikipedia.org/wiki/RGBE_image_format
  58873. *
  58874. * @param uint8array The binary file stored in an array buffer.
  58875. * @param hdrInfo The header information of the file.
  58876. * @return The pixels data in RGB right to left up to down order.
  58877. */
  58878. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  58879. // Keep for multi format supports.
  58880. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  58881. };
  58882. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  58883. var num_scanlines = hdrInfo.height;
  58884. var scanline_width = hdrInfo.width;
  58885. var a, b, c, d, count;
  58886. var dataIndex = hdrInfo.dataPosition;
  58887. var index = 0, endIndex = 0, i = 0;
  58888. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  58889. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  58890. // 3 channels of 4 bytes per pixel in float.
  58891. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  58892. var resultArray = new Float32Array(resultBuffer);
  58893. // read in each successive scanline
  58894. while (num_scanlines > 0) {
  58895. a = uint8array[dataIndex++];
  58896. b = uint8array[dataIndex++];
  58897. c = uint8array[dataIndex++];
  58898. d = uint8array[dataIndex++];
  58899. if (a != 2 || b != 2 || (c & 0x80)) {
  58900. // this file is not run length encoded
  58901. throw "HDR Bad header format, not RLE";
  58902. }
  58903. if (((c << 8) | d) != scanline_width) {
  58904. throw "HDR Bad header format, wrong scan line width";
  58905. }
  58906. index = 0;
  58907. // read each of the four channels for the scanline into the buffer
  58908. for (i = 0; i < 4; i++) {
  58909. endIndex = (i + 1) * scanline_width;
  58910. while (index < endIndex) {
  58911. a = uint8array[dataIndex++];
  58912. b = uint8array[dataIndex++];
  58913. if (a > 128) {
  58914. // a run of the same value
  58915. count = a - 128;
  58916. if ((count == 0) || (count > endIndex - index)) {
  58917. throw "HDR Bad Format, bad scanline data (run)";
  58918. }
  58919. while (count-- > 0) {
  58920. scanLineArray[index++] = b;
  58921. }
  58922. }
  58923. else {
  58924. // a non-run
  58925. count = a;
  58926. if ((count == 0) || (count > endIndex - index)) {
  58927. throw "HDR Bad Format, bad scanline data (non-run)";
  58928. }
  58929. scanLineArray[index++] = b;
  58930. if (--count > 0) {
  58931. for (var j = 0; j < count; j++) {
  58932. scanLineArray[index++] = uint8array[dataIndex++];
  58933. }
  58934. }
  58935. }
  58936. }
  58937. }
  58938. // now convert data from buffer into floats
  58939. for (i = 0; i < scanline_width; i++) {
  58940. a = scanLineArray[i];
  58941. b = scanLineArray[i + scanline_width];
  58942. c = scanLineArray[i + 2 * scanline_width];
  58943. d = scanLineArray[i + 3 * scanline_width];
  58944. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  58945. }
  58946. num_scanlines--;
  58947. }
  58948. return resultArray;
  58949. };
  58950. return HDRTools;
  58951. }());
  58952. Internals.HDRTools = HDRTools;
  58953. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  58954. })(BABYLON || (BABYLON = {}));
  58955. //_______________________________________________________________
  58956. // Extracted from CubeMapGen:
  58957. // https://code.google.com/archive/p/cubemapgen/
  58958. //
  58959. // Following https://seblagarde.wordpress.com/2012/06/10/amd-cubemapgen-for-physically-based-rendering/
  58960. //_______________________________________________________________
  58961. var BABYLON;
  58962. (function (BABYLON) {
  58963. var Internals;
  58964. (function (Internals) {
  58965. /**
  58966. * The bounding box information used during the conversion process.
  58967. */
  58968. var CMGBoundinBox = (function () {
  58969. function CMGBoundinBox() {
  58970. this.min = new BABYLON.Vector3(0, 0, 0);
  58971. this.max = new BABYLON.Vector3(0, 0, 0);
  58972. this.clear();
  58973. }
  58974. CMGBoundinBox.prototype.clear = function () {
  58975. this.min.x = CMGBoundinBox.MAX;
  58976. this.min.y = CMGBoundinBox.MAX;
  58977. this.min.z = CMGBoundinBox.MAX;
  58978. this.max.x = CMGBoundinBox.MIN;
  58979. this.max.y = CMGBoundinBox.MIN;
  58980. this.max.z = CMGBoundinBox.MIN;
  58981. };
  58982. CMGBoundinBox.prototype.augment = function (x, y, z) {
  58983. this.min.x = Math.min(this.min.x, x);
  58984. this.min.y = Math.min(this.min.y, y);
  58985. this.min.z = Math.min(this.min.z, z);
  58986. this.max.x = Math.max(this.max.x, x);
  58987. this.max.y = Math.max(this.max.y, y);
  58988. this.max.z = Math.max(this.max.z, z);
  58989. };
  58990. CMGBoundinBox.prototype.clampMin = function (x, y, z) {
  58991. this.min.x = Math.max(this.min.x, x);
  58992. this.min.y = Math.max(this.min.y, y);
  58993. this.min.z = Math.max(this.min.z, z);
  58994. };
  58995. CMGBoundinBox.prototype.clampMax = function (x, y, z) {
  58996. this.max.x = Math.min(this.max.x, x);
  58997. this.max.y = Math.min(this.max.y, y);
  58998. this.max.z = Math.min(this.max.z, z);
  58999. };
  59000. CMGBoundinBox.prototype.empty = function () {
  59001. if ((this.min.x > this.max.y) ||
  59002. (this.min.y > this.max.y) ||
  59003. (this.min.z > this.max.y)) {
  59004. return true;
  59005. }
  59006. else {
  59007. return false;
  59008. }
  59009. };
  59010. CMGBoundinBox.MAX = Number.MAX_VALUE;
  59011. CMGBoundinBox.MIN = Number.MIN_VALUE;
  59012. return CMGBoundinBox;
  59013. }());
  59014. /**
  59015. * Helper class to PreProcess a cubemap in order to generate mipmap according to the level of blur
  59016. * required by the glossinees of a material.
  59017. *
  59018. * This only supports the cosine drop power as well as Warp fixup generation method.
  59019. *
  59020. * This is using the process from CubeMapGen described here:
  59021. * https://seblagarde.wordpress.com/2012/06/10/amd-cubemapgen-for-physically-based-rendering/
  59022. */
  59023. var PMREMGenerator = (function () {
  59024. /**
  59025. * Constructor of the generator.
  59026. *
  59027. * @param input The different faces data from the original cubemap in the order X+ X- Y+ Y- Z+ Z-
  59028. * @param inputSize The size of the cubemap faces
  59029. * @param outputSize The size of the output cubemap faces
  59030. * @param maxNumMipLevels The max number of mip map to generate (0 means all)
  59031. * @param numChannels The number of channels stored in the cubemap (3 for RBGE for instance)
  59032. * @param isFloat Specifies if the input texture is in float or int (hdr is usually in float)
  59033. * @param specularPower The max specular level of the desired cubemap
  59034. * @param cosinePowerDropPerMip The amount of drop the specular power will follow on each mip
  59035. * @param excludeBase Specifies wether to process the level 0 (original level) or not
  59036. * @param fixup Specifies wether to apply the edge fixup algorythm or not
  59037. */
  59038. function PMREMGenerator(input, inputSize, outputSize, maxNumMipLevels, numChannels, isFloat, specularPower, cosinePowerDropPerMip, excludeBase, fixup) {
  59039. this.input = input;
  59040. this.inputSize = inputSize;
  59041. this.outputSize = outputSize;
  59042. this.maxNumMipLevels = maxNumMipLevels;
  59043. this.numChannels = numChannels;
  59044. this.isFloat = isFloat;
  59045. this.specularPower = specularPower;
  59046. this.cosinePowerDropPerMip = cosinePowerDropPerMip;
  59047. this.excludeBase = excludeBase;
  59048. this.fixup = fixup;
  59049. this._outputSurface = [];
  59050. this._numMipLevels = 0;
  59051. }
  59052. /**
  59053. * Launches the filter process and return the result.
  59054. *
  59055. * @return the filter cubemap in the form mip0 [faces1..6] .. mipN [faces1..6]
  59056. */
  59057. PMREMGenerator.prototype.filterCubeMap = function () {
  59058. // Init cubemap processor
  59059. this.init();
  59060. // Filters the cubemap
  59061. this.filterCubeMapMipChain();
  59062. // Returns the filtered mips.
  59063. return this._outputSurface;
  59064. };
  59065. PMREMGenerator.prototype.init = function () {
  59066. var i;
  59067. var j;
  59068. var mipLevelSize;
  59069. //if nax num mip levels is set to 0, set it to generate the entire mip chain
  59070. if (this.maxNumMipLevels == 0) {
  59071. this.maxNumMipLevels = PMREMGenerator.CP_MAX_MIPLEVELS;
  59072. }
  59073. //first miplevel size
  59074. mipLevelSize = this.outputSize;
  59075. //Iterate over mip chain, and init ArrayBufferView for mip-chain
  59076. for (j = 0; j < this.maxNumMipLevels; j++) {
  59077. this._outputSurface.length++;
  59078. this._outputSurface[j] = [];
  59079. //Iterate over faces for output images
  59080. for (i = 0; i < 6; i++) {
  59081. this._outputSurface[j].length++;
  59082. // Initializes a new array for the output.
  59083. if (this.isFloat) {
  59084. this._outputSurface[j][i] = new Float32Array(mipLevelSize * mipLevelSize * this.numChannels);
  59085. }
  59086. else {
  59087. this._outputSurface[j][i] = new Uint32Array(mipLevelSize * mipLevelSize * this.numChannels);
  59088. }
  59089. }
  59090. //next mip level is half size
  59091. mipLevelSize >>= 1;
  59092. this._numMipLevels++;
  59093. //terminate if mip chain becomes too small
  59094. if (mipLevelSize == 0) {
  59095. this.maxNumMipLevels = j;
  59096. return;
  59097. }
  59098. }
  59099. };
  59100. //--------------------------------------------------------------------------------------
  59101. //Cube map filtering and mip chain generation.
  59102. // the cube map filtereing is specified using a number of parameters:
  59103. // Filtering per miplevel is specified using 2D cone angle (in degrees) that
  59104. // indicates the region of the hemisphere to filter over for each tap.
  59105. //
  59106. // Note that the top mip level is also a filtered version of the original input images
  59107. // as well in order to create mip chains for diffuse environment illumination.
  59108. // The cone angle for the top level is specified by a_BaseAngle. This can be used to
  59109. // generate mipchains used to store the resutls of preintegration across the hemisphere.
  59110. //
  59111. // Then the mip angle used to genreate the next level of the mip chain from the first level
  59112. // is a_InitialMipAngle
  59113. //
  59114. // The angle for the subsequent levels of the mip chain are specified by their parents
  59115. // filtering angle and a per-level scale and bias
  59116. // newAngle = oldAngle * a_MipAnglePerLevelScale;
  59117. //
  59118. //--------------------------------------------------------------------------------------
  59119. PMREMGenerator.prototype.filterCubeMapMipChain = function () {
  59120. // First, take count of the lighting model to modify SpecularPower
  59121. // 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;
  59122. // var refSpecularPower = this.specularPower; // Only Phong BRDF yet. This explains the line below using this.specularpower.
  59123. //Cone angle start (for generating subsequent mip levels)
  59124. var currentSpecularPower = this.specularPower;
  59125. //Build filter lookup tables based on the source miplevel size
  59126. this.precomputeFilterLookupTables(this.inputSize);
  59127. // Note that we need to filter the first level before generating mipmap
  59128. // So LevelIndex == 0 is base filtering hen LevelIndex > 0 is mipmap generation
  59129. for (var levelIndex = 0; levelIndex < this._numMipLevels; levelIndex++) {
  59130. // TODO : Write a function to copy and scale the base mipmap in output
  59131. // I am just lazy here and just put a high specular power value, and do some if.
  59132. if (this.excludeBase && (levelIndex == 0)) {
  59133. // 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).
  59134. currentSpecularPower = 100000.0;
  59135. }
  59136. // Special case for cosine power mipmap chain. For quality requirement, we always process the current mipmap from the top mipmap
  59137. var srcCubeImage = this.input;
  59138. var dstCubeImage = this._outputSurface[levelIndex];
  59139. var dstSize = this.outputSize >> levelIndex;
  59140. // Compute required angle.
  59141. var angle = this.getBaseFilterAngle(currentSpecularPower);
  59142. // filter cube surfaces
  59143. this.filterCubeSurfaces(srcCubeImage, this.inputSize, dstCubeImage, dstSize, angle, currentSpecularPower);
  59144. // fix seams
  59145. if (this.fixup) {
  59146. this.fixupCubeEdges(dstCubeImage, dstSize);
  59147. }
  59148. // Decrease the specular power to generate the mipmap chain
  59149. // TODO : Use another method for Exclude (see first comment at start of the function
  59150. if (this.excludeBase && (levelIndex == 0)) {
  59151. currentSpecularPower = this.specularPower;
  59152. }
  59153. currentSpecularPower *= this.cosinePowerDropPerMip;
  59154. }
  59155. };
  59156. //--------------------------------------------------------------------------------------
  59157. // This function return the BaseFilterAngle require by PMREMGenerator to its FilterExtends
  59158. // It allow to optimize the texel to access base on the specular power.
  59159. //--------------------------------------------------------------------------------------
  59160. PMREMGenerator.prototype.getBaseFilterAngle = function (cosinePower) {
  59161. // We want to find the alpha such that:
  59162. // cos(alpha)^cosinePower = epsilon
  59163. // That's: acos(epsilon^(1/cosinePower))
  59164. var threshold = 0.000001; // Empirical threshold (Work perfectly, didn't check for a more big number, may get some performance and still god approximation)
  59165. var angle = 180.0;
  59166. angle = Math.acos(Math.pow(threshold, 1.0 / cosinePower));
  59167. angle *= 180.0 / Math.PI; // Convert to degree
  59168. angle *= 2.0; // * 2.0f because PMREMGenerator divide by 2 later
  59169. return angle;
  59170. };
  59171. //--------------------------------------------------------------------------------------
  59172. //Builds the following lookup tables prior to filtering:
  59173. // -normalizer cube map
  59174. // -tap weight lookup table
  59175. //
  59176. //--------------------------------------------------------------------------------------
  59177. PMREMGenerator.prototype.precomputeFilterLookupTables = function (srcCubeMapWidth) {
  59178. var srcTexelAngle;
  59179. var iCubeFace;
  59180. //clear pre-existing normalizer cube map
  59181. this._normCubeMap = [];
  59182. //Normalized vectors per cubeface and per-texel solid angle
  59183. this.buildNormalizerSolidAngleCubemap(srcCubeMapWidth);
  59184. };
  59185. //--------------------------------------------------------------------------------------
  59186. //Builds a normalizer cubemap, with the texels solid angle stored in the fourth component
  59187. //
  59188. //Takes in a cube face size, and an array of 6 surfaces to write the cube faces into
  59189. //
  59190. //Note that this normalizer cube map stores the vectors in unbiased -1 to 1 range.
  59191. // if _bx2 style scaled and biased vectors are needed, uncomment the SCALE and BIAS
  59192. // below
  59193. //--------------------------------------------------------------------------------------
  59194. PMREMGenerator.prototype.buildNormalizerSolidAngleCubemap = function (size) {
  59195. var iCubeFace;
  59196. var u;
  59197. var v;
  59198. //iterate over cube faces
  59199. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  59200. //First three channels for norm cube, and last channel for solid angle
  59201. this._normCubeMap.push(new Float32Array(size * size * 4));
  59202. //fast texture walk, build normalizer cube map
  59203. var facesData = this.input[iCubeFace];
  59204. for (v = 0; v < size; v++) {
  59205. for (u = 0; u < size; u++) {
  59206. var vect = this.texelCoordToVect(iCubeFace, u, v, size, this.fixup);
  59207. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 0] = vect.x;
  59208. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 1] = vect.y;
  59209. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 2] = vect.z;
  59210. var solidAngle = this.texelCoordSolidAngle(iCubeFace, u, v, size);
  59211. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 4] = solidAngle;
  59212. }
  59213. }
  59214. }
  59215. };
  59216. //--------------------------------------------------------------------------------------
  59217. // Convert cubemap face texel coordinates and face idx to 3D vector
  59218. // note the U and V coords are integer coords and range from 0 to size-1
  59219. // this routine can be used to generate a normalizer cube map
  59220. //--------------------------------------------------------------------------------------
  59221. // SL BEGIN
  59222. PMREMGenerator.prototype.texelCoordToVect = function (faceIdx, u, v, size, fixup) {
  59223. var nvcU;
  59224. var nvcV;
  59225. var tempVec;
  59226. // Change from original AMD code
  59227. // transform from [0..res - 1] to [- (1 - 1 / res) .. (1 - 1 / res)]
  59228. // + 0.5f is for texel center addressing
  59229. nvcU = (2.0 * (u + 0.5) / size) - 1.0;
  59230. nvcV = (2.0 * (v + 0.5) / size) - 1.0;
  59231. // warp fixup
  59232. if (fixup && size > 1) {
  59233. // Code from Nvtt : http://code.google.com/p/nvidia-texture-tools/source/browse/trunk/src/nvtt/CubeSurface.cpp
  59234. var a = Math.pow(size, 2.0) / Math.pow(size - 1, 3.0);
  59235. nvcU = a * Math.pow(nvcU, 3) + nvcU;
  59236. nvcV = a * Math.pow(nvcV, 3) + nvcV;
  59237. }
  59238. // Get current vector
  59239. // generate x,y,z vector (xform 2d NVC coord to 3D vector)
  59240. // U contribution
  59241. var UVec = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_UDIR];
  59242. PMREMGenerator._vectorTemp.x = UVec[0] * nvcU;
  59243. PMREMGenerator._vectorTemp.y = UVec[1] * nvcU;
  59244. PMREMGenerator._vectorTemp.z = UVec[2] * nvcU;
  59245. // V contribution and Sum
  59246. var VVec = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_VDIR];
  59247. PMREMGenerator._vectorTemp.x += VVec[0] * nvcV;
  59248. PMREMGenerator._vectorTemp.y += VVec[1] * nvcV;
  59249. PMREMGenerator._vectorTemp.z += VVec[2] * nvcV;
  59250. //add face axis
  59251. var faceAxis = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_FACEAXIS];
  59252. PMREMGenerator._vectorTemp.x += faceAxis[0];
  59253. PMREMGenerator._vectorTemp.y += faceAxis[1];
  59254. PMREMGenerator._vectorTemp.z += faceAxis[2];
  59255. //normalize vector
  59256. PMREMGenerator._vectorTemp.normalize();
  59257. return PMREMGenerator._vectorTemp;
  59258. };
  59259. //--------------------------------------------------------------------------------------
  59260. // Convert 3D vector to cubemap face texel coordinates and face idx
  59261. // note the U and V coords are integer coords and range from 0 to size-1
  59262. // this routine can be used to generate a normalizer cube map
  59263. //
  59264. // returns face IDX and texel coords
  59265. //--------------------------------------------------------------------------------------
  59266. // SL BEGIN
  59267. /*
  59268. Mapping Texture Coordinates to Cube Map Faces
  59269. Because there are multiple faces, the mapping of texture coordinates to positions on cube map faces
  59270. is more complicated than the other texturing targets. The EXT_texture_cube_map extension is purposefully
  59271. designed to be consistent with DirectX 7's cube map arrangement. This is also consistent with the cube
  59272. map arrangement in Pixar's RenderMan package.
  59273. For cube map texturing, the (s,t,r) texture coordinates are treated as a direction vector (rx,ry,rz)
  59274. emanating from the center of a cube. (The q coordinate can be ignored since it merely scales the vector
  59275. without affecting the direction.) At texture application time, the interpolated per-fragment (s,t,r)
  59276. selects one of the cube map face's 2D mipmap sets based on the largest magnitude coordinate direction
  59277. the major axis direction). The target column in the table below explains how the major axis direction
  59278. maps to the 2D image of a particular cube map target.
  59279. major axis
  59280. direction target sc tc ma
  59281. ---------- --------------------------------- --- --- ---
  59282. +rx GL_TEXTURE_CUBE_MAP_POSITIVE_X_EXT -rz -ry rx
  59283. -rx GL_TEXTURE_CUBE_MAP_NEGATIVE_X_EXT +rz -ry rx
  59284. +ry GL_TEXTURE_CUBE_MAP_POSITIVE_Y_EXT +rx +rz ry
  59285. -ry GL_TEXTURE_CUBE_MAP_NEGATIVE_Y_EXT +rx -rz ry
  59286. +rz GL_TEXTURE_CUBE_MAP_POSITIVE_Z_EXT +rx -ry rz
  59287. -rz GL_TEXTURE_CUBE_MAP_NEGATIVE_Z_EXT -rx -ry rz
  59288. Using the sc, tc, and ma determined by the major axis direction as specified in the table above,
  59289. an updated (s,t) is calculated as follows
  59290. s = ( sc/|ma| + 1 ) / 2
  59291. t = ( tc/|ma| + 1 ) / 2
  59292. If |ma| is zero or very nearly zero, the results of the above two equations need not be defined
  59293. (though the result may not lead to GL interruption or termination). Once the cube map face's 2D mipmap
  59294. set and (s,t) is determined, texture fetching and filtering proceeds like standard OpenGL 2D texturing.
  59295. */
  59296. // Note this method return U and V in range from 0 to size-1
  59297. // SL END
  59298. // Store the information in vector3 for convenience (faceindex, u, v)
  59299. PMREMGenerator.prototype.vectToTexelCoord = function (x, y, z, size) {
  59300. var maxCoord;
  59301. var faceIdx;
  59302. //absolute value 3
  59303. var absX = Math.abs(x);
  59304. var absY = Math.abs(y);
  59305. var absZ = Math.abs(z);
  59306. if (absX >= absY && absX >= absZ) {
  59307. maxCoord = absX;
  59308. if (x >= 0) {
  59309. faceIdx = PMREMGenerator.CP_FACE_X_POS;
  59310. }
  59311. else {
  59312. faceIdx = PMREMGenerator.CP_FACE_X_NEG;
  59313. }
  59314. }
  59315. else if (absY >= absX && absY >= absZ) {
  59316. maxCoord = absY;
  59317. if (y >= 0) {
  59318. faceIdx = PMREMGenerator.CP_FACE_Y_POS;
  59319. }
  59320. else {
  59321. faceIdx = PMREMGenerator.CP_FACE_Y_NEG;
  59322. }
  59323. }
  59324. else {
  59325. maxCoord = absZ;
  59326. if (z >= 0) {
  59327. faceIdx = PMREMGenerator.CP_FACE_Z_POS;
  59328. }
  59329. else {
  59330. faceIdx = PMREMGenerator.CP_FACE_Z_NEG;
  59331. }
  59332. }
  59333. //divide through by max coord so face vector lies on cube face
  59334. var scale = 1 / maxCoord;
  59335. x *= scale;
  59336. y *= scale;
  59337. z *= scale;
  59338. var temp = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_UDIR];
  59339. var nvcU = temp[0] * x + temp[1] * y + temp[2] * z;
  59340. temp = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_VDIR];
  59341. var nvcV = temp[0] * x + temp[1] * y + temp[2] * z;
  59342. // Modify original AMD code to return value from 0 to Size - 1
  59343. var u = Math.floor((size - 1) * 0.5 * (nvcU + 1.0));
  59344. var v = Math.floor((size - 1) * 0.5 * (nvcV + 1.0));
  59345. PMREMGenerator._vectorTemp.x = faceIdx;
  59346. PMREMGenerator._vectorTemp.y = u;
  59347. PMREMGenerator._vectorTemp.z = v;
  59348. return PMREMGenerator._vectorTemp;
  59349. };
  59350. //--------------------------------------------------------------------------------------
  59351. //Original code from Ignacio CastaÒo
  59352. // This formula is from Manne ÷hrstrˆm's thesis.
  59353. // Take two coordiantes in the range [-1, 1] that define a portion of a
  59354. // cube face and return the area of the projection of that portion on the
  59355. // surface of the sphere.
  59356. //--------------------------------------------------------------------------------------
  59357. PMREMGenerator.prototype.areaElement = function (x, y) {
  59358. return Math.atan2(x * y, Math.sqrt(x * x + y * y + 1));
  59359. };
  59360. PMREMGenerator.prototype.texelCoordSolidAngle = function (faceIdx, u, v, size) {
  59361. // transform from [0..res - 1] to [- (1 - 1 / res) .. (1 - 1 / res)]
  59362. // (+ 0.5f is for texel center addressing)
  59363. u = (2.0 * (u + 0.5) / size) - 1.0;
  59364. v = (2.0 * (v + 0.5) / size) - 1.0;
  59365. // Shift from a demi texel, mean 1.0f / a_Size with U and V in [-1..1]
  59366. var invResolution = 1.0 / size;
  59367. // U and V are the -1..1 texture coordinate on the current face.
  59368. // Get projected area for this texel
  59369. var x0 = u - invResolution;
  59370. var y0 = v - invResolution;
  59371. var x1 = u + invResolution;
  59372. var y1 = v + invResolution;
  59373. var solidAngle = this.areaElement(x0, y0) - this.areaElement(x0, y1) - this.areaElement(x1, y0) + this.areaElement(x1, y1);
  59374. return solidAngle;
  59375. };
  59376. //--------------------------------------------------------------------------------------
  59377. //The key to the speed of these filtering routines is to quickly define a per-face
  59378. // bounding box of pixels which enclose all the taps in the filter kernel efficiently.
  59379. // Later these pixels are selectively processed based on their dot products to see if
  59380. // they reside within the filtering cone.
  59381. //
  59382. //This is done by computing the smallest per-texel angle to get a conservative estimate
  59383. // of the number of texels needed to be covered in width and height order to filter the
  59384. // region. the bounding box for the center taps face is defined first, and if the
  59385. // filtereing region bleeds onto the other faces, bounding boxes for the other faces are
  59386. // defined next
  59387. //--------------------------------------------------------------------------------------
  59388. PMREMGenerator.prototype.filterCubeSurfaces = function (srcCubeMap, srcSize, dstCubeMap, dstSize, filterConeAngle, specularPower) {
  59389. // note that pixels within these regions may be rejected
  59390. // based on the anlge
  59391. var iCubeFace;
  59392. var u;
  59393. var v;
  59394. // bounding box per face to specify region to process
  59395. var filterExtents = [];
  59396. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  59397. filterExtents.push(new CMGBoundinBox());
  59398. }
  59399. // min angle a src texel can cover (in degrees)
  59400. var srcTexelAngle = (180.0 / (Math.PI) * Math.atan2(1.0, srcSize));
  59401. // angle about center tap to define filter cone
  59402. // filter angle is 1/2 the cone angle
  59403. var filterAngle = filterConeAngle / 2.0;
  59404. //ensure filter angle is larger than a texel
  59405. if (filterAngle < srcTexelAngle) {
  59406. filterAngle = srcTexelAngle;
  59407. }
  59408. //ensure filter cone is always smaller than the hemisphere
  59409. if (filterAngle > 90.0) {
  59410. filterAngle = 90.0;
  59411. }
  59412. // the maximum number of texels in 1D the filter cone angle will cover
  59413. // used to determine bounding box size for filter extents
  59414. var filterSize = Math.ceil(filterAngle / srcTexelAngle);
  59415. // ensure conservative region always covers at least one texel
  59416. if (filterSize < 1) {
  59417. filterSize = 1;
  59418. }
  59419. // dotProdThresh threshold based on cone angle to determine whether or not taps
  59420. // reside within the cone angle
  59421. var dotProdThresh = Math.cos((Math.PI / 180.0) * filterAngle);
  59422. // process required faces
  59423. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  59424. //iterate over dst cube map face texel
  59425. for (v = 0; v < dstSize; v++) {
  59426. for (u = 0; u < dstSize; u++) {
  59427. //get center tap direction
  59428. var centerTapDir = this.texelCoordToVect(iCubeFace, u, v, dstSize, this.fixup).clone();
  59429. //clear old per-face filter extents
  59430. this.clearFilterExtents(filterExtents);
  59431. //define per-face filter extents
  59432. this.determineFilterExtents(centerTapDir, srcSize, filterSize, filterExtents);
  59433. //perform filtering of src faces using filter extents
  59434. var vect = this.processFilterExtents(centerTapDir, dotProdThresh, filterExtents, srcCubeMap, srcSize, specularPower);
  59435. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 0] = vect.x;
  59436. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 1] = vect.y;
  59437. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 2] = vect.z;
  59438. }
  59439. }
  59440. }
  59441. };
  59442. //--------------------------------------------------------------------------------------
  59443. //Clear filter extents for the 6 cube map faces
  59444. //--------------------------------------------------------------------------------------
  59445. PMREMGenerator.prototype.clearFilterExtents = function (filterExtents) {
  59446. for (var iCubeFaces = 0; iCubeFaces < 6; iCubeFaces++) {
  59447. filterExtents[iCubeFaces].clear();
  59448. }
  59449. };
  59450. //--------------------------------------------------------------------------------------
  59451. //Define per-face bounding box filter extents
  59452. //
  59453. // These define conservative texel regions in each of the faces the filter can possibly
  59454. // process. When the pixels in the regions are actually processed, the dot product
  59455. // between the tap vector and the center tap vector is used to determine the weight of
  59456. // the tap and whether or not the tap is within the cone.
  59457. //
  59458. //--------------------------------------------------------------------------------------
  59459. PMREMGenerator.prototype.determineFilterExtents = function (centerTapDir, srcSize, bboxSize, filterExtents) {
  59460. //neighboring face and bleed over amount, and width of BBOX for
  59461. // left, right, top, and bottom edges of this face
  59462. var bleedOverAmount = [0, 0, 0, 0];
  59463. var bleedOverBBoxMin = [0, 0, 0, 0];
  59464. var bleedOverBBoxMax = [0, 0, 0, 0];
  59465. var neighborFace;
  59466. var neighborEdge;
  59467. var oppositeFaceIdx;
  59468. //get face idx, and u, v info from center tap dir
  59469. var result = this.vectToTexelCoord(centerTapDir.x, centerTapDir.y, centerTapDir.z, srcSize);
  59470. var faceIdx = result.x;
  59471. var u = result.y;
  59472. var v = result.z;
  59473. //define bbox size within face
  59474. filterExtents[faceIdx].augment(u - bboxSize, v - bboxSize, 0);
  59475. filterExtents[faceIdx].augment(u + bboxSize, v + bboxSize, 0);
  59476. filterExtents[faceIdx].clampMin(0, 0, 0);
  59477. filterExtents[faceIdx].clampMax(srcSize - 1, srcSize - 1, 0);
  59478. //u and v extent in face corresponding to center tap
  59479. var minU = filterExtents[faceIdx].min.x;
  59480. var minV = filterExtents[faceIdx].min.y;
  59481. var maxU = filterExtents[faceIdx].max.x;
  59482. var maxV = filterExtents[faceIdx].max.y;
  59483. //bleed over amounts for face across u=0 edge (left)
  59484. bleedOverAmount[0] = (bboxSize - u);
  59485. bleedOverBBoxMin[0] = minV;
  59486. bleedOverBBoxMax[0] = maxV;
  59487. //bleed over amounts for face across u=1 edge (right)
  59488. bleedOverAmount[1] = (u + bboxSize) - (srcSize - 1);
  59489. bleedOverBBoxMin[1] = minV;
  59490. bleedOverBBoxMax[1] = maxV;
  59491. //bleed over to face across v=0 edge (up)
  59492. bleedOverAmount[2] = (bboxSize - v);
  59493. bleedOverBBoxMin[2] = minU;
  59494. bleedOverBBoxMax[2] = maxU;
  59495. //bleed over to face across v=1 edge (down)
  59496. bleedOverAmount[3] = (v + bboxSize) - (srcSize - 1);
  59497. bleedOverBBoxMin[3] = minU;
  59498. bleedOverBBoxMax[3] = maxU;
  59499. //compute bleed over regions in neighboring faces
  59500. for (var i = 0; i < 4; i++) {
  59501. if (bleedOverAmount[i] > 0) {
  59502. neighborFace = PMREMGenerator._sgCubeNgh[faceIdx][i][0];
  59503. neighborEdge = PMREMGenerator._sgCubeNgh[faceIdx][i][1];
  59504. //For certain types of edge abutments, the bleedOverBBoxMin, and bleedOverBBoxMax need to
  59505. // be flipped: the cases are
  59506. // if a left edge mates with a left or bottom edge on the neighbor
  59507. // if a top edge mates with a top or right edge on the neighbor
  59508. // if a right edge mates with a right or top edge on the neighbor
  59509. // if a bottom edge mates with a bottom or left edge on the neighbor
  59510. //Seeing as the edges are enumerated as follows
  59511. // left =0
  59512. // right =1
  59513. // top =2
  59514. // bottom =3
  59515. //
  59516. // so if the edge enums are the same, or the sum of the enums == 3,
  59517. // the bbox needs to be flipped
  59518. if ((i == neighborEdge) || ((i + neighborEdge) == 3)) {
  59519. bleedOverBBoxMin[i] = (srcSize - 1) - bleedOverBBoxMin[i];
  59520. bleedOverBBoxMax[i] = (srcSize - 1) - bleedOverBBoxMax[i];
  59521. }
  59522. //The way the bounding box is extended onto the neighboring face
  59523. // depends on which edge of neighboring face abuts with this one
  59524. switch (PMREMGenerator._sgCubeNgh[faceIdx][i][1]) {
  59525. case PMREMGenerator.CP_EDGE_LEFT:
  59526. filterExtents[neighborFace].augment(0, bleedOverBBoxMin[i], 0);
  59527. filterExtents[neighborFace].augment(bleedOverAmount[i], bleedOverBBoxMax[i], 0);
  59528. break;
  59529. case PMREMGenerator.CP_EDGE_RIGHT:
  59530. filterExtents[neighborFace].augment((srcSize - 1), bleedOverBBoxMin[i], 0);
  59531. filterExtents[neighborFace].augment((srcSize - 1) - bleedOverAmount[i], bleedOverBBoxMax[i], 0);
  59532. break;
  59533. case PMREMGenerator.CP_EDGE_TOP:
  59534. filterExtents[neighborFace].augment(bleedOverBBoxMin[i], 0, 0);
  59535. filterExtents[neighborFace].augment(bleedOverBBoxMax[i], bleedOverAmount[i], 0);
  59536. break;
  59537. case PMREMGenerator.CP_EDGE_BOTTOM:
  59538. filterExtents[neighborFace].augment(bleedOverBBoxMin[i], (srcSize - 1), 0);
  59539. filterExtents[neighborFace].augment(bleedOverBBoxMax[i], (srcSize - 1) - bleedOverAmount[i], 0);
  59540. break;
  59541. }
  59542. //clamp filter extents in non-center tap faces to remain within surface
  59543. filterExtents[neighborFace].clampMin(0, 0, 0);
  59544. filterExtents[neighborFace].clampMax(srcSize - 1, srcSize - 1, 0);
  59545. }
  59546. //If the bleed over amount bleeds past the adjacent face onto the opposite face
  59547. // from the center tap face, then process the opposite face entirely for now.
  59548. //Note that the cases in which this happens, what usually happens is that
  59549. // more than one edge bleeds onto the opposite face, and the bounding box
  59550. // encompasses the entire cube map face.
  59551. if (bleedOverAmount[i] > srcSize) {
  59552. //determine opposite face
  59553. switch (faceIdx) {
  59554. case PMREMGenerator.CP_FACE_X_POS:
  59555. oppositeFaceIdx = PMREMGenerator.CP_FACE_X_NEG;
  59556. break;
  59557. case PMREMGenerator.CP_FACE_X_NEG:
  59558. oppositeFaceIdx = PMREMGenerator.CP_FACE_X_POS;
  59559. break;
  59560. case PMREMGenerator.CP_FACE_Y_POS:
  59561. oppositeFaceIdx = PMREMGenerator.CP_FACE_Y_NEG;
  59562. break;
  59563. case PMREMGenerator.CP_FACE_Y_NEG:
  59564. oppositeFaceIdx = PMREMGenerator.CP_FACE_Y_POS;
  59565. break;
  59566. case PMREMGenerator.CP_FACE_Z_POS:
  59567. oppositeFaceIdx = PMREMGenerator.CP_FACE_Z_NEG;
  59568. break;
  59569. case PMREMGenerator.CP_FACE_Z_NEG:
  59570. oppositeFaceIdx = PMREMGenerator.CP_FACE_Z_POS;
  59571. break;
  59572. default:
  59573. break;
  59574. }
  59575. //just encompass entire face for now
  59576. filterExtents[oppositeFaceIdx].augment(0, 0, 0);
  59577. filterExtents[oppositeFaceIdx].augment((srcSize - 1), (srcSize - 1), 0);
  59578. }
  59579. }
  59580. };
  59581. //--------------------------------------------------------------------------------------
  59582. //ProcessFilterExtents
  59583. // Process bounding box in each cube face
  59584. //
  59585. //--------------------------------------------------------------------------------------
  59586. PMREMGenerator.prototype.processFilterExtents = function (centerTapDir, dotProdThresh, filterExtents, srcCubeMap, srcSize, specularPower) {
  59587. //accumulators are 64-bit floats in order to have the precision needed
  59588. // over a summation of a large number of pixels
  59589. var dstAccum = [0, 0, 0, 0];
  59590. var weightAccum = 0;
  59591. var k = 0;
  59592. var nSrcChannels = this.numChannels;
  59593. // norm cube map and srcCubeMap have same face width
  59594. var faceWidth = srcSize;
  59595. //amount to add to pointer to move to next scanline in images
  59596. var normCubePitch = faceWidth * 4; // 4 channels in normCubeMap.
  59597. var srcCubePitch = faceWidth * this.numChannels; // numChannels correponds to the cubemap number of channel
  59598. var IsPhongBRDF = 1; // Only works in Phong BRDF yet.
  59599. //(a_LightingModel == CP_LIGHTINGMODEL_PHONG_BRDF || a_LightingModel == CP_LIGHTINGMODEL_BLINN_BRDF) ? 1 : 0; // This value will be added to the specular power
  59600. // iterate over cubefaces
  59601. for (var iFaceIdx = 0; iFaceIdx < 6; iFaceIdx++) {
  59602. //if bbox is non empty
  59603. if (!filterExtents[iFaceIdx].empty()) {
  59604. var uStart = filterExtents[iFaceIdx].min.x;
  59605. var vStart = filterExtents[iFaceIdx].min.y;
  59606. var uEnd = filterExtents[iFaceIdx].max.x;
  59607. var vEnd = filterExtents[iFaceIdx].max.y;
  59608. var startIndexNormCubeMap = (4 * ((vStart * faceWidth) + uStart));
  59609. var startIndexSrcCubeMap = (this.numChannels * ((vStart * faceWidth) + uStart));
  59610. //note that <= is used to ensure filter extents always encompass at least one pixel if bbox is non empty
  59611. for (var v = vStart; v <= vEnd; v++) {
  59612. var normCubeRowWalk = 0;
  59613. var srcCubeRowWalk = 0;
  59614. for (var u = uStart; u <= uEnd; u++) {
  59615. //pointer to direction in cube map associated with texel
  59616. var texelVectX = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 0];
  59617. var texelVectY = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 1];
  59618. var texelVectZ = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 2];
  59619. //check dot product to see if texel is within cone
  59620. var tapDotProd = texelVectX * centerTapDir.x +
  59621. texelVectY * centerTapDir.y +
  59622. texelVectZ * centerTapDir.z;
  59623. if (tapDotProd >= dotProdThresh && tapDotProd > 0.0) {
  59624. //solid angle stored in 4th channel of normalizer/solid angle cube map
  59625. var weight = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 3];
  59626. // Here we decide if we use a Phong/Blinn or a Phong/Blinn BRDF.
  59627. // Phong/Blinn BRDF is just the Phong/Blinn model multiply by the cosine of the lambert law
  59628. // so just adding one to specularpower do the trick.
  59629. weight *= Math.pow(tapDotProd, (specularPower + IsPhongBRDF));
  59630. //iterate over channels
  59631. for (k = 0; k < nSrcChannels; k++) {
  59632. dstAccum[k] += weight * srcCubeMap[iFaceIdx][startIndexSrcCubeMap + srcCubeRowWalk];
  59633. srcCubeRowWalk++;
  59634. }
  59635. weightAccum += weight; //accumulate weight
  59636. }
  59637. else {
  59638. //step across source pixel
  59639. srcCubeRowWalk += nSrcChannels;
  59640. }
  59641. normCubeRowWalk += 4; // 4 channels per norm cube map.
  59642. }
  59643. startIndexNormCubeMap += normCubePitch;
  59644. startIndexSrcCubeMap += srcCubePitch;
  59645. }
  59646. }
  59647. }
  59648. //divide through by weights if weight is non zero
  59649. if (weightAccum != 0.0) {
  59650. PMREMGenerator._vectorTemp.x = (dstAccum[0] / weightAccum);
  59651. PMREMGenerator._vectorTemp.y = (dstAccum[1] / weightAccum);
  59652. PMREMGenerator._vectorTemp.z = (dstAccum[2] / weightAccum);
  59653. if (this.numChannels > 3) {
  59654. PMREMGenerator._vectorTemp.w = (dstAccum[3] / weightAccum);
  59655. }
  59656. }
  59657. else {
  59658. // otherwise sample nearest
  59659. // get face idx and u, v texel coordinate in face
  59660. var coord = this.vectToTexelCoord(centerTapDir.x, centerTapDir.y, centerTapDir.z, srcSize).clone();
  59661. PMREMGenerator._vectorTemp.x = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 0];
  59662. PMREMGenerator._vectorTemp.y = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 1];
  59663. PMREMGenerator._vectorTemp.z = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 2];
  59664. if (this.numChannels > 3) {
  59665. PMREMGenerator._vectorTemp.z = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 3];
  59666. }
  59667. }
  59668. return PMREMGenerator._vectorTemp;
  59669. };
  59670. //--------------------------------------------------------------------------------------
  59671. // Fixup cube edges
  59672. //
  59673. // average texels on cube map faces across the edges
  59674. // WARP/BENT Method Only.
  59675. //--------------------------------------------------------------------------------------
  59676. PMREMGenerator.prototype.fixupCubeEdges = function (cubeMap, cubeMapSize) {
  59677. var k;
  59678. var j;
  59679. var i;
  59680. var iFace;
  59681. var iCorner = 0;
  59682. var cornerNumPtrs = [0, 0, 0, 0, 0, 0, 0, 0]; //indexed by corner and face idx
  59683. var faceCornerStartIndicies = [[], [], [], []]; //corner pointers for face keeping track of the face they belong to.
  59684. // note that if functionality to filter across the three texels for each corner, then
  59685. //indexed by corner and face idx. the array contains the face the start points belongs to.
  59686. var cornerPtr = [
  59687. [[], [], []],
  59688. [[], [], []],
  59689. [[], [], []],
  59690. [[], [], []],
  59691. [[], [], []],
  59692. [[], [], []],
  59693. [[], [], []],
  59694. [[], [], []]
  59695. ];
  59696. //if there is no fixup, or fixup width = 0, do nothing
  59697. if (cubeMapSize < 1) {
  59698. return;
  59699. }
  59700. //special case 1x1 cubemap, average face colors
  59701. if (cubeMapSize == 1) {
  59702. //iterate over channels
  59703. for (k = 0; k < this.numChannels; k++) {
  59704. var accum = 0.0;
  59705. //iterate over faces to accumulate face colors
  59706. for (iFace = 0; iFace < 6; iFace++) {
  59707. accum += cubeMap[iFace][k];
  59708. }
  59709. //compute average over 6 face colors
  59710. accum /= 6.0;
  59711. //iterate over faces to distribute face colors
  59712. for (iFace = 0; iFace < 6; iFace++) {
  59713. cubeMap[iFace][k] = accum;
  59714. }
  59715. }
  59716. return;
  59717. }
  59718. //iterate over faces to collect list of corner texel pointers
  59719. for (iFace = 0; iFace < 6; iFace++) {
  59720. //the 4 corner pointers for this face
  59721. faceCornerStartIndicies[0] = [iFace, 0];
  59722. faceCornerStartIndicies[1] = [iFace, ((cubeMapSize - 1) * this.numChannels)];
  59723. faceCornerStartIndicies[2] = [iFace, ((cubeMapSize) * (cubeMapSize - 1) * this.numChannels)];
  59724. faceCornerStartIndicies[3] = [iFace, ((((cubeMapSize) * (cubeMapSize - 1)) + (cubeMapSize - 1)) * this.numChannels)];
  59725. //iterate over face corners to collect cube corner pointers
  59726. for (iCorner = 0; iCorner < 4; iCorner++) {
  59727. var corner = PMREMGenerator._sgCubeCornerList[iFace][iCorner];
  59728. cornerPtr[corner][cornerNumPtrs[corner]] = faceCornerStartIndicies[iCorner];
  59729. cornerNumPtrs[corner]++;
  59730. }
  59731. }
  59732. //iterate over corners to average across corner tap values
  59733. for (iCorner = 0; iCorner < 8; iCorner++) {
  59734. for (k = 0; k < this.numChannels; k++) {
  59735. var cornerTapAccum = 0.0;
  59736. //iterate over corner texels and average results
  59737. for (i = 0; i < 3; i++) {
  59738. cornerTapAccum += cubeMap[cornerPtr[iCorner][i][0]][cornerPtr[iCorner][i][1] + k]; // Get in the cube map face the start point + channel.
  59739. }
  59740. //divide by 3 to compute average of corner tap values
  59741. cornerTapAccum *= (1.0 / 3.0);
  59742. //iterate over corner texels and average results
  59743. for (i = 0; i < 3; i++) {
  59744. cubeMap[cornerPtr[iCorner][i][0]][cornerPtr[iCorner][i][1] + k] = cornerTapAccum;
  59745. }
  59746. }
  59747. }
  59748. //iterate over the twelve edges of the cube to average across edges
  59749. for (i = 0; i < 12; i++) {
  59750. var face = PMREMGenerator._sgCubeEdgeList[i][0];
  59751. var edge = PMREMGenerator._sgCubeEdgeList[i][1];
  59752. var neighborFace = PMREMGenerator._sgCubeNgh[face][edge][0];
  59753. var neighborEdge = PMREMGenerator._sgCubeNgh[face][edge][1];
  59754. var edgeStartIndex = 0; // a_CubeMap[face].m_ImgData;
  59755. var neighborEdgeStartIndex = 0; // a_CubeMap[neighborFace].m_ImgData;
  59756. var edgeWalk = 0;
  59757. var neighborEdgeWalk = 0;
  59758. //Determine walking pointers based on edge type
  59759. // e.g. CP_EDGE_LEFT, CP_EDGE_RIGHT, CP_EDGE_TOP, CP_EDGE_BOTTOM
  59760. switch (edge) {
  59761. case PMREMGenerator.CP_EDGE_LEFT:
  59762. // no change to faceEdgeStartPtr
  59763. edgeWalk = this.numChannels * cubeMapSize;
  59764. break;
  59765. case PMREMGenerator.CP_EDGE_RIGHT:
  59766. edgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  59767. edgeWalk = this.numChannels * cubeMapSize;
  59768. break;
  59769. case PMREMGenerator.CP_EDGE_TOP:
  59770. // no change to faceEdgeStartPtr
  59771. edgeWalk = this.numChannels;
  59772. break;
  59773. case PMREMGenerator.CP_EDGE_BOTTOM:
  59774. edgeStartIndex += (cubeMapSize) * (cubeMapSize - 1) * this.numChannels;
  59775. edgeWalk = this.numChannels;
  59776. break;
  59777. }
  59778. //For certain types of edge abutments, the neighbor edge walk needs to
  59779. // be flipped: the cases are
  59780. // if a left edge mates with a left or bottom edge on the neighbor
  59781. // if a top edge mates with a top or right edge on the neighbor
  59782. // if a right edge mates with a right or top edge on the neighbor
  59783. // if a bottom edge mates with a bottom or left edge on the neighbor
  59784. //Seeing as the edges are enumerated as follows
  59785. // left =0
  59786. // right =1
  59787. // top =2
  59788. // bottom =3
  59789. //
  59790. //If the edge enums are the same, or the sum of the enums == 3,
  59791. // the neighbor edge walk needs to be flipped
  59792. if ((edge == neighborEdge) || ((edge + neighborEdge) == 3)) {
  59793. switch (neighborEdge) {
  59794. case PMREMGenerator.CP_EDGE_LEFT:
  59795. neighborEdgeStartIndex += (cubeMapSize - 1) * (cubeMapSize) * this.numChannels;
  59796. neighborEdgeWalk = -(this.numChannels * cubeMapSize);
  59797. break;
  59798. case PMREMGenerator.CP_EDGE_RIGHT:
  59799. neighborEdgeStartIndex += ((cubeMapSize - 1) * (cubeMapSize) + (cubeMapSize - 1)) * this.numChannels;
  59800. neighborEdgeWalk = -(this.numChannels * cubeMapSize);
  59801. break;
  59802. case PMREMGenerator.CP_EDGE_TOP:
  59803. neighborEdgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  59804. neighborEdgeWalk = -this.numChannels;
  59805. break;
  59806. case PMREMGenerator.CP_EDGE_BOTTOM:
  59807. neighborEdgeStartIndex += ((cubeMapSize - 1) * (cubeMapSize) + (cubeMapSize - 1)) * this.numChannels;
  59808. neighborEdgeWalk = -this.numChannels;
  59809. break;
  59810. }
  59811. }
  59812. else {
  59813. //swapped direction neighbor edge walk
  59814. switch (neighborEdge) {
  59815. case PMREMGenerator.CP_EDGE_LEFT:
  59816. //no change to neighborEdgeStartPtr for this case since it points
  59817. // to the upper left corner already
  59818. neighborEdgeWalk = this.numChannels * cubeMapSize;
  59819. break;
  59820. case PMREMGenerator.CP_EDGE_RIGHT:
  59821. neighborEdgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  59822. neighborEdgeWalk = this.numChannels * cubeMapSize;
  59823. break;
  59824. case PMREMGenerator.CP_EDGE_TOP:
  59825. //no change to neighborEdgeStartPtr for this case since it points
  59826. // to the upper left corner already
  59827. neighborEdgeWalk = this.numChannels;
  59828. break;
  59829. case PMREMGenerator.CP_EDGE_BOTTOM:
  59830. neighborEdgeStartIndex += (cubeMapSize) * (cubeMapSize - 1) * this.numChannels;
  59831. neighborEdgeWalk = this.numChannels;
  59832. break;
  59833. }
  59834. }
  59835. //Perform edge walk, to average across the 12 edges and smoothly propagate change to
  59836. //nearby neighborhood
  59837. //step ahead one texel on edge
  59838. edgeStartIndex += edgeWalk;
  59839. neighborEdgeStartIndex += neighborEdgeWalk;
  59840. // note that this loop does not process the corner texels, since they have already been
  59841. // averaged across faces across earlier
  59842. for (j = 1; j < (cubeMapSize - 1); j++) {
  59843. //for each set of taps along edge, average them
  59844. // and rewrite the results into the edges
  59845. for (k = 0; k < this.numChannels; k++) {
  59846. var edgeTap = cubeMap[face][edgeStartIndex + k];
  59847. var neighborEdgeTap = cubeMap[neighborFace][neighborEdgeStartIndex + k];
  59848. //compute average of tap intensity values
  59849. var avgTap = 0.5 * (edgeTap + neighborEdgeTap);
  59850. //propagate average of taps to edge taps
  59851. cubeMap[face][edgeStartIndex + k] = avgTap;
  59852. cubeMap[neighborFace][neighborEdgeStartIndex + k] = avgTap;
  59853. }
  59854. edgeStartIndex += edgeWalk;
  59855. neighborEdgeStartIndex += neighborEdgeWalk;
  59856. }
  59857. }
  59858. };
  59859. PMREMGenerator.CP_MAX_MIPLEVELS = 16;
  59860. PMREMGenerator.CP_UDIR = 0;
  59861. PMREMGenerator.CP_VDIR = 1;
  59862. PMREMGenerator.CP_FACEAXIS = 2;
  59863. //used to index cube faces
  59864. PMREMGenerator.CP_FACE_X_POS = 0;
  59865. PMREMGenerator.CP_FACE_X_NEG = 1;
  59866. PMREMGenerator.CP_FACE_Y_POS = 2;
  59867. PMREMGenerator.CP_FACE_Y_NEG = 3;
  59868. PMREMGenerator.CP_FACE_Z_POS = 4;
  59869. PMREMGenerator.CP_FACE_Z_NEG = 5;
  59870. //used to index image edges
  59871. // NOTE.. the actual number corresponding to the edge is important
  59872. // do not change these, or the code will break
  59873. //
  59874. // CP_EDGE_LEFT is u = 0
  59875. // CP_EDGE_RIGHT is u = width-1
  59876. // CP_EDGE_TOP is v = 0
  59877. // CP_EDGE_BOTTOM is v = height-1
  59878. PMREMGenerator.CP_EDGE_LEFT = 0;
  59879. PMREMGenerator.CP_EDGE_RIGHT = 1;
  59880. PMREMGenerator.CP_EDGE_TOP = 2;
  59881. PMREMGenerator.CP_EDGE_BOTTOM = 3;
  59882. //corners of CUBE map (P or N specifys if it corresponds to the
  59883. // positive or negative direction each of X, Y, and Z
  59884. PMREMGenerator.CP_CORNER_NNN = 0;
  59885. PMREMGenerator.CP_CORNER_NNP = 1;
  59886. PMREMGenerator.CP_CORNER_NPN = 2;
  59887. PMREMGenerator.CP_CORNER_NPP = 3;
  59888. PMREMGenerator.CP_CORNER_PNN = 4;
  59889. PMREMGenerator.CP_CORNER_PNP = 5;
  59890. PMREMGenerator.CP_CORNER_PPN = 6;
  59891. PMREMGenerator.CP_CORNER_PPP = 7;
  59892. PMREMGenerator._vectorTemp = new BABYLON.Vector4(0, 0, 0, 0);
  59893. //3x2 matrices that map cube map indexing vectors in 3d
  59894. // (after face selection and divide through by the
  59895. // _ABSOLUTE VALUE_ of the max coord)
  59896. // into NVC space
  59897. //Note this currently assumes the D3D cube face ordering and orientation
  59898. PMREMGenerator._sgFace2DMapping = [
  59899. //XPOS face
  59900. [[0, 0, -1],
  59901. [0, -1, 0],
  59902. [1, 0, 0]],
  59903. //XNEG face
  59904. [[0, 0, 1],
  59905. [0, -1, 0],
  59906. [-1, 0, 0]],
  59907. //YPOS face
  59908. [[1, 0, 0],
  59909. [0, 0, 1],
  59910. [0, 1, 0]],
  59911. //YNEG face
  59912. [[1, 0, 0],
  59913. [0, 0, -1],
  59914. [0, -1, 0]],
  59915. //ZPOS face
  59916. [[1, 0, 0],
  59917. [0, -1, 0],
  59918. [0, 0, 1]],
  59919. //ZNEG face
  59920. [[-1, 0, 0],
  59921. [0, -1, 0],
  59922. [0, 0, -1]],
  59923. ];
  59924. //------------------------------------------------------------------------------
  59925. // D3D cube map face specification
  59926. // mapping from 3D x,y,z cube map lookup coordinates
  59927. // to 2D within face u,v coordinates
  59928. //
  59929. // --------------------> U direction
  59930. // | (within-face texture space)
  59931. // | _____
  59932. // | | |
  59933. // | | +Y |
  59934. // | _____|_____|_____ _____
  59935. // | | | | | |
  59936. // | | -X | +Z | +X | -Z |
  59937. // | |_____|_____|_____|_____|
  59938. // | | |
  59939. // | | -Y |
  59940. // | |_____|
  59941. // |
  59942. // v V direction
  59943. // (within-face texture space)
  59944. //------------------------------------------------------------------------------
  59945. //Information about neighbors and how texture coorrdinates change across faces
  59946. // in ORDER of left, right, top, bottom (e.g. edges corresponding to u=0,
  59947. // u=1, v=0, v=1 in the 2D coordinate system of the particular face.
  59948. //Note this currently assumes the D3D cube face ordering and orientation
  59949. PMREMGenerator._sgCubeNgh = [
  59950. //XPOS face
  59951. [[PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_RIGHT],
  59952. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_LEFT],
  59953. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_RIGHT],
  59954. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_RIGHT]],
  59955. //XNEG face
  59956. [[PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  59957. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_LEFT],
  59958. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_LEFT],
  59959. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_LEFT]],
  59960. //YPOS face
  59961. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_TOP],
  59962. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_TOP],
  59963. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_TOP],
  59964. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_TOP]],
  59965. //YNEG face
  59966. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_BOTTOM],
  59967. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  59968. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  59969. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_BOTTOM]],
  59970. //ZPOS face
  59971. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  59972. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_LEFT],
  59973. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  59974. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_TOP]],
  59975. //ZNEG face
  59976. [[PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_RIGHT],
  59977. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_LEFT],
  59978. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_TOP],
  59979. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_BOTTOM]]
  59980. ];
  59981. //The 12 edges of the cubemap, (entries are used to index into the neighbor table)
  59982. // this table is used to average over the edges.
  59983. PMREMGenerator._sgCubeEdgeList = [
  59984. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_LEFT],
  59985. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_RIGHT],
  59986. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_TOP],
  59987. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  59988. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_LEFT],
  59989. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  59990. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_TOP],
  59991. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_BOTTOM],
  59992. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_TOP],
  59993. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  59994. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_TOP],
  59995. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_BOTTOM]
  59996. ];
  59997. //Information about which of the 8 cube corners are correspond to the
  59998. // the 4 corners in each cube face
  59999. // the order is upper left, upper right, lower left, lower right
  60000. PMREMGenerator._sgCubeCornerList = [
  60001. [PMREMGenerator.CP_CORNER_PPP, PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_PNP, PMREMGenerator.CP_CORNER_PNN],
  60002. [PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_NNN, PMREMGenerator.CP_CORNER_NNP],
  60003. [PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_PPP],
  60004. [PMREMGenerator.CP_CORNER_NNP, PMREMGenerator.CP_CORNER_PNP, PMREMGenerator.CP_CORNER_NNN, PMREMGenerator.CP_CORNER_PNN],
  60005. [PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_PPP, PMREMGenerator.CP_CORNER_NNP, PMREMGenerator.CP_CORNER_PNP],
  60006. [PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_PNN, PMREMGenerator.CP_CORNER_NNN] // ZNEG face
  60007. ];
  60008. return PMREMGenerator;
  60009. }());
  60010. Internals.PMREMGenerator = PMREMGenerator;
  60011. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  60012. })(BABYLON || (BABYLON = {}));
  60013. var BABYLON;
  60014. (function (BABYLON) {
  60015. /**
  60016. * This represents a texture coming from an HDR input.
  60017. *
  60018. * The only supported format is currently panorama picture stored in RGBE format.
  60019. * Example of such files can be found on HDRLib: http://hdrlib.com/
  60020. */
  60021. var HDRCubeTexture = (function (_super) {
  60022. __extends(HDRCubeTexture, _super);
  60023. /**
  60024. * Instantiates an HDRTexture from the following parameters.
  60025. *
  60026. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  60027. * @param scene The scene the texture will be used in
  60028. * @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.
  60029. * @param noMipmap Forces to not generate the mipmap if true
  60030. * @param generateHarmonics Specifies wether you want to extract the polynomial harmonics during the generation process
  60031. * @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)
  60032. * @param usePMREMGenerator Specifies wether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  60033. */
  60034. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  60035. if (noMipmap === void 0) { noMipmap = false; }
  60036. if (generateHarmonics === void 0) { generateHarmonics = true; }
  60037. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  60038. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  60039. _super.call(this, scene);
  60040. this._useInGammaSpace = false;
  60041. this._generateHarmonics = true;
  60042. this._isBABYLONPreprocessed = false;
  60043. /**
  60044. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  60045. */
  60046. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  60047. /**
  60048. * The spherical polynomial data extracted from the texture.
  60049. */
  60050. this.sphericalPolynomial = null;
  60051. /**
  60052. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  60053. * This is usefull at run time to apply the good shader.
  60054. */
  60055. this.isPMREM = false;
  60056. if (!url) {
  60057. return;
  60058. }
  60059. this.name = url;
  60060. this.url = url;
  60061. this.hasAlpha = false;
  60062. this.isCube = true;
  60063. this._textureMatrix = BABYLON.Matrix.Identity();
  60064. if (size) {
  60065. this._isBABYLONPreprocessed = false;
  60066. this._noMipmap = noMipmap;
  60067. this._size = size;
  60068. this._useInGammaSpace = useInGammaSpace;
  60069. this._usePMREMGenerator = usePMREMGenerator &&
  60070. scene.getEngine().getCaps().textureLOD &&
  60071. this.getScene().getEngine().getCaps().textureFloat &&
  60072. !this._useInGammaSpace;
  60073. }
  60074. else {
  60075. this._isBABYLONPreprocessed = true;
  60076. this._noMipmap = false;
  60077. this._useInGammaSpace = false;
  60078. this._usePMREMGenerator = scene.getEngine().getCaps().textureLOD &&
  60079. this.getScene().getEngine().getCaps().textureFloat &&
  60080. !this._useInGammaSpace;
  60081. }
  60082. this.isPMREM = this._usePMREMGenerator;
  60083. this._texture = this._getFromCache(url, this._noMipmap);
  60084. if (!this._texture) {
  60085. if (!scene.useDelayedTextureLoading) {
  60086. this.loadTexture();
  60087. }
  60088. else {
  60089. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  60090. }
  60091. }
  60092. }
  60093. /**
  60094. * Occurs when the file is a preprocessed .babylon.hdr file.
  60095. */
  60096. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  60097. var _this = this;
  60098. var mipLevels = 0;
  60099. var floatArrayView = null;
  60100. var mipmapGenerator = (!this._useInGammaSpace && this.getScene().getEngine().getCaps().textureFloat) ? function (data) {
  60101. var mips = [];
  60102. var startIndex = 30;
  60103. for (var level = 0; level < mipLevels; level++) {
  60104. mips.push([]);
  60105. // Fill each pixel of the mip level.
  60106. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  60107. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  60108. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  60109. mips[level].push(faceData);
  60110. startIndex += faceSize;
  60111. }
  60112. }
  60113. return mips;
  60114. } : null;
  60115. var callback = function (buffer) {
  60116. // Create Native Array Views
  60117. var intArrayView = new Int32Array(buffer);
  60118. floatArrayView = new Float32Array(buffer);
  60119. // Fill header.
  60120. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  60121. _this._size = intArrayView[1]; // CubeMap max mip face size.
  60122. // Update Texture Information.
  60123. _this.getScene().getEngine().updateTextureSize(_this._texture, _this._size, _this._size);
  60124. // Fill polynomial information.
  60125. _this.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  60126. _this.sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  60127. _this.sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  60128. _this.sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  60129. _this.sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  60130. _this.sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  60131. _this.sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  60132. _this.sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  60133. _this.sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  60134. _this.sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  60135. // Fill pixel data.
  60136. mipLevels = intArrayView[29]; // Number of mip levels.
  60137. var startIndex = 30;
  60138. var data = [];
  60139. var faceSize = Math.pow(_this._size, 2) * 3;
  60140. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  60141. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  60142. startIndex += faceSize;
  60143. }
  60144. var results = [];
  60145. var byteArray = null;
  60146. // Push each faces.
  60147. for (var k = 0; k < 6; k++) {
  60148. var dataFace = null;
  60149. // If special cases.
  60150. if (!mipmapGenerator) {
  60151. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y... if no mipmapgenerator...
  60152. dataFace = data[j];
  60153. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  60154. // 3 channels of 1 bytes per pixel in bytes.
  60155. var byteBuffer = new ArrayBuffer(faceSize);
  60156. byteArray = new Uint8Array(byteBuffer);
  60157. }
  60158. for (var i = 0; i < _this._size * _this._size; i++) {
  60159. // Put in gamma space if requested.
  60160. if (_this._useInGammaSpace) {
  60161. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  60162. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  60163. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  60164. }
  60165. // Convert to int texture for fallback.
  60166. if (byteArray) {
  60167. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  60168. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  60169. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  60170. // May use luminance instead if the result is not accurate.
  60171. var max = Math.max(Math.max(r, g), b);
  60172. if (max > 255) {
  60173. var scale = 255 / max;
  60174. r *= scale;
  60175. g *= scale;
  60176. b *= scale;
  60177. }
  60178. byteArray[(i * 3) + 0] = r;
  60179. byteArray[(i * 3) + 1] = g;
  60180. byteArray[(i * 3) + 2] = b;
  60181. }
  60182. }
  60183. }
  60184. else {
  60185. dataFace = data[k];
  60186. }
  60187. // Fill the array accordingly.
  60188. if (byteArray) {
  60189. results.push(byteArray);
  60190. }
  60191. else {
  60192. results.push(dataFace);
  60193. }
  60194. }
  60195. return results;
  60196. };
  60197. 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);
  60198. };
  60199. /**
  60200. * Occurs when the file is raw .hdr file.
  60201. */
  60202. HDRCubeTexture.prototype.loadHDRTexture = function () {
  60203. var _this = this;
  60204. var callback = function (buffer) {
  60205. // Extract the raw linear data.
  60206. var data = BABYLON.Internals.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  60207. // Generate harmonics if needed.
  60208. if (_this._generateHarmonics) {
  60209. _this.sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  60210. }
  60211. var results = [];
  60212. var byteArray = null;
  60213. // Push each faces.
  60214. for (var j = 0; j < 6; j++) {
  60215. // Create uintarray fallback.
  60216. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  60217. // 3 channels of 1 bytes per pixel in bytes.
  60218. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  60219. byteArray = new Uint8Array(byteBuffer);
  60220. }
  60221. var dataFace = data[HDRCubeTexture._facesMapping[j]];
  60222. // If special cases.
  60223. if (_this._useInGammaSpace || byteArray) {
  60224. for (var i = 0; i < _this._size * _this._size; i++) {
  60225. // Put in gamma space if requested.
  60226. if (_this._useInGammaSpace) {
  60227. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  60228. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  60229. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  60230. }
  60231. // Convert to int texture for fallback.
  60232. if (byteArray) {
  60233. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  60234. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  60235. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  60236. // May use luminance instead if the result is not accurate.
  60237. var max = Math.max(Math.max(r, g), b);
  60238. if (max > 255) {
  60239. var scale = 255 / max;
  60240. r *= scale;
  60241. g *= scale;
  60242. b *= scale;
  60243. }
  60244. byteArray[(i * 3) + 0] = r;
  60245. byteArray[(i * 3) + 1] = g;
  60246. byteArray[(i * 3) + 2] = b;
  60247. }
  60248. }
  60249. }
  60250. if (byteArray) {
  60251. results.push(byteArray);
  60252. }
  60253. else {
  60254. results.push(dataFace);
  60255. }
  60256. }
  60257. return results;
  60258. };
  60259. var mipmapGenerator = null;
  60260. if (!this._noMipmap &&
  60261. this._usePMREMGenerator) {
  60262. mipmapGenerator = function (data) {
  60263. // Custom setup of the generator matching with the PBR shader values.
  60264. var generator = new BABYLON.Internals.PMREMGenerator(data, _this._size, _this._size, 0, 3, _this.getScene().getEngine().getCaps().textureFloat, 2048, 0.25, false, true);
  60265. return generator.filterCubeMap();
  60266. };
  60267. }
  60268. 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);
  60269. };
  60270. /**
  60271. * Starts the loading process of the texture.
  60272. */
  60273. HDRCubeTexture.prototype.loadTexture = function () {
  60274. if (this._isBABYLONPreprocessed) {
  60275. this.loadBabylonTexture();
  60276. }
  60277. else {
  60278. this.loadHDRTexture();
  60279. }
  60280. };
  60281. HDRCubeTexture.prototype.clone = function () {
  60282. var size = this._isBABYLONPreprocessed ? null : this._size;
  60283. var newTexture = new HDRCubeTexture(this.url, this.getScene(), size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  60284. // Base texture
  60285. newTexture.level = this.level;
  60286. newTexture.wrapU = this.wrapU;
  60287. newTexture.wrapV = this.wrapV;
  60288. newTexture.coordinatesIndex = this.coordinatesIndex;
  60289. newTexture.coordinatesMode = this.coordinatesMode;
  60290. return newTexture;
  60291. };
  60292. // Methods
  60293. HDRCubeTexture.prototype.delayLoad = function () {
  60294. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  60295. return;
  60296. }
  60297. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  60298. this._texture = this._getFromCache(this.url, this._noMipmap);
  60299. if (!this._texture) {
  60300. this.loadTexture();
  60301. }
  60302. };
  60303. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  60304. return this._textureMatrix;
  60305. };
  60306. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  60307. var texture = null;
  60308. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  60309. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  60310. texture = new BABYLON.HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, texture.generateHarmonics, texture.useInGammaSpace, texture.usePMREMGenerator);
  60311. texture.name = parsedTexture.name;
  60312. texture.hasAlpha = parsedTexture.hasAlpha;
  60313. texture.level = parsedTexture.level;
  60314. texture.coordinatesMode = parsedTexture.coordinatesMode;
  60315. }
  60316. return texture;
  60317. };
  60318. HDRCubeTexture.prototype.serialize = function () {
  60319. if (!this.name) {
  60320. return null;
  60321. }
  60322. var serializationObject = {};
  60323. serializationObject.name = this.name;
  60324. serializationObject.hasAlpha = this.hasAlpha;
  60325. serializationObject.isCube = true;
  60326. serializationObject.level = this.level;
  60327. serializationObject.size = this._size;
  60328. serializationObject.coordinatesMode = this.coordinatesMode;
  60329. serializationObject.useInGammaSpace = this._useInGammaSpace;
  60330. serializationObject.generateHarmonics = this._generateHarmonics;
  60331. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  60332. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  60333. serializationObject.customType = "BABYLON.HDRCubeTexture";
  60334. return serializationObject;
  60335. };
  60336. /**
  60337. * Saves as a file the data contained in the texture in a binary format.
  60338. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  60339. * as the spherical used in the lighting.
  60340. * @param url The HDR file url.
  60341. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  60342. * @param onError Method called if any error happens during download.
  60343. * @return The packed binary data.
  60344. */
  60345. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  60346. if (onError === void 0) { onError = null; }
  60347. var callback = function (buffer) {
  60348. var data = new Blob([buffer], { type: 'application/octet-stream' });
  60349. // Returns a URL you can use as a href.
  60350. var objUrl = window.URL.createObjectURL(data);
  60351. // Simulates a link to it and click to dowload.
  60352. var a = document.createElement("a");
  60353. document.body.appendChild(a);
  60354. a.style.display = "none";
  60355. a.href = objUrl;
  60356. a.download = "envmap.babylon.hdr";
  60357. a.click();
  60358. };
  60359. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  60360. };
  60361. /**
  60362. * Serializes the data contained in the texture in a binary format.
  60363. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  60364. * as the spherical used in the lighting.
  60365. * @param url The HDR file url.
  60366. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  60367. * @param onError Method called if any error happens during download.
  60368. * @return The packed binary data.
  60369. */
  60370. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  60371. if (onError === void 0) { onError = null; }
  60372. // Needs the url tho create the texture.
  60373. if (!url) {
  60374. return null;
  60375. }
  60376. // Check Power of two size.
  60377. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  60378. return null;
  60379. }
  60380. var getDataCallback = function (dataBuffer) {
  60381. // Extract the raw linear data.
  60382. var cubeData = BABYLON.Internals.HDRTools.GetCubeMapTextureData(dataBuffer, size);
  60383. // Generate harmonics if needed.
  60384. var sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(cubeData);
  60385. // Generate seamless faces
  60386. var mipGeneratorArray = [];
  60387. // Data are known to be in +X +Y +Z -X -Y -Z
  60388. // mipmmapGenerator data is expected to be order in +X -X +Y -Y +Z -Z
  60389. mipGeneratorArray.push(cubeData.right); // +X
  60390. mipGeneratorArray.push(cubeData.left); // -X
  60391. mipGeneratorArray.push(cubeData.up); // +Y
  60392. mipGeneratorArray.push(cubeData.down); // -Y
  60393. mipGeneratorArray.push(cubeData.front); // +Z
  60394. mipGeneratorArray.push(cubeData.back); // -Z
  60395. // Custom setup of the generator matching with the PBR shader values.
  60396. var generator = new BABYLON.Internals.PMREMGenerator(mipGeneratorArray, size, size, 0, 3, true, 2048, 0.25, false, true);
  60397. var mippedData = generator.filterCubeMap();
  60398. // Compute required byte length.
  60399. var byteLength = 1 * 4; // Raw Data Version int32.
  60400. byteLength += 4; // CubeMap max mip face size int32.
  60401. byteLength += (9 * 3 * 4); // Spherical polynomial byte length 9 Vector 3 of floats.
  60402. // Add data size.
  60403. byteLength += 4; // Number of mip levels int32.
  60404. for (var level = 0; level < mippedData.length; level++) {
  60405. var mipSize = size >> level;
  60406. byteLength += (6 * mipSize * mipSize * 3 * 4); // 6 faces of size squared rgb float pixels.
  60407. }
  60408. // Prepare binary structure.
  60409. var buffer = new ArrayBuffer(byteLength);
  60410. var intArrayView = new Int32Array(buffer);
  60411. var floatArrayView = new Float32Array(buffer);
  60412. // Fill header.
  60413. intArrayView[0] = 1; // Version 1.
  60414. intArrayView[1] = size; // CubeMap max mip face size.
  60415. // Fill polynomial information.
  60416. sphericalPolynomial.x.toArray(floatArrayView, 2);
  60417. sphericalPolynomial.y.toArray(floatArrayView, 5);
  60418. sphericalPolynomial.z.toArray(floatArrayView, 8);
  60419. sphericalPolynomial.xx.toArray(floatArrayView, 11);
  60420. sphericalPolynomial.yy.toArray(floatArrayView, 14);
  60421. sphericalPolynomial.zz.toArray(floatArrayView, 17);
  60422. sphericalPolynomial.xy.toArray(floatArrayView, 20);
  60423. sphericalPolynomial.yz.toArray(floatArrayView, 23);
  60424. sphericalPolynomial.zx.toArray(floatArrayView, 26);
  60425. // Fill pixel data.
  60426. intArrayView[29] = mippedData.length; // Number of mip levels.
  60427. var startIndex = 30;
  60428. for (var level = 0; level < mippedData.length; level++) {
  60429. // Fill each pixel of the mip level.
  60430. var faceSize = Math.pow(size >> level, 2) * 3;
  60431. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  60432. floatArrayView.set(mippedData[level][faceIndex], startIndex);
  60433. startIndex += faceSize;
  60434. }
  60435. }
  60436. // Callback.
  60437. callback(buffer);
  60438. };
  60439. // Download and process.
  60440. BABYLON.Tools.LoadFile(url, function (data) {
  60441. getDataCallback(data);
  60442. }, null, null, true, onError);
  60443. };
  60444. HDRCubeTexture._facesMapping = [
  60445. "right",
  60446. "up",
  60447. "front",
  60448. "left",
  60449. "down",
  60450. "back"
  60451. ];
  60452. return HDRCubeTexture;
  60453. }(BABYLON.BaseTexture));
  60454. BABYLON.HDRCubeTexture = HDRCubeTexture;
  60455. })(BABYLON || (BABYLON = {}));
  60456. var BABYLON;
  60457. (function (BABYLON) {
  60458. var Debug;
  60459. (function (Debug) {
  60460. /**
  60461. * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
  60462. */
  60463. var SkeletonViewer = (function () {
  60464. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  60465. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  60466. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  60467. this.skeleton = skeleton;
  60468. this.mesh = mesh;
  60469. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  60470. this.renderingGroupId = renderingGroupId;
  60471. this.color = BABYLON.Color3.White();
  60472. this._debugLines = [];
  60473. this._isEnabled = false;
  60474. this._scene = scene;
  60475. this.update();
  60476. this._renderFunction = this.update.bind(this);
  60477. }
  60478. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  60479. get: function () {
  60480. return this._isEnabled;
  60481. },
  60482. set: function (value) {
  60483. if (this._isEnabled === value) {
  60484. return;
  60485. }
  60486. this._isEnabled = value;
  60487. if (value) {
  60488. this._scene.registerBeforeRender(this._renderFunction);
  60489. }
  60490. else {
  60491. this._scene.unregisterBeforeRender(this._renderFunction);
  60492. }
  60493. },
  60494. enumerable: true,
  60495. configurable: true
  60496. });
  60497. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  60498. if (x === void 0) { x = 0; }
  60499. if (y === void 0) { y = 0; }
  60500. if (z === void 0) { z = 0; }
  60501. var tmat = BABYLON.Tmp.Matrix[0];
  60502. var parentBone = bone.getParent();
  60503. tmat.copyFrom(bone.getLocalMatrix());
  60504. if (x !== 0 || y !== 0 || z !== 0) {
  60505. var tmat2 = BABYLON.Tmp.Matrix[1];
  60506. BABYLON.Matrix.IdentityToRef(tmat2);
  60507. tmat2.m[12] = x;
  60508. tmat2.m[13] = y;
  60509. tmat2.m[14] = z;
  60510. tmat2.multiplyToRef(tmat, tmat);
  60511. }
  60512. if (parentBone) {
  60513. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  60514. }
  60515. tmat.multiplyToRef(meshMat, tmat);
  60516. position.x = tmat.m[12];
  60517. position.y = tmat.m[13];
  60518. position.z = tmat.m[14];
  60519. };
  60520. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  60521. var len = bones.length;
  60522. for (var i = 0; i < len; i++) {
  60523. var bone = bones[i];
  60524. var points = this._debugLines[i];
  60525. if (!points) {
  60526. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  60527. this._debugLines[i] = points;
  60528. }
  60529. this._getBonePosition(points[0], bone, meshMat);
  60530. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  60531. }
  60532. };
  60533. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  60534. var len = bones.length;
  60535. var boneNum = 0;
  60536. for (var i = len - 1; i >= 0; i--) {
  60537. var childBone = bones[i];
  60538. var parentBone = childBone.getParent();
  60539. if (!parentBone) {
  60540. continue;
  60541. }
  60542. var points = this._debugLines[boneNum];
  60543. if (!points) {
  60544. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  60545. this._debugLines[boneNum] = points;
  60546. }
  60547. this._getBonePosition(points[0], childBone, meshMat);
  60548. this._getBonePosition(points[1], parentBone, meshMat);
  60549. boneNum++;
  60550. }
  60551. };
  60552. SkeletonViewer.prototype.update = function () {
  60553. if (this.autoUpdateBonesMatrices) {
  60554. this._updateBoneMatrix(this.skeleton.bones[0]);
  60555. }
  60556. if (this.skeleton.bones[0].length === undefined) {
  60557. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  60558. }
  60559. else {
  60560. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  60561. }
  60562. if (!this._debugMesh) {
  60563. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true }, this._scene);
  60564. this._debugMesh.renderingGroupId = this.renderingGroupId;
  60565. }
  60566. else {
  60567. BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  60568. }
  60569. this._debugMesh.color = this.color;
  60570. };
  60571. SkeletonViewer.prototype._updateBoneMatrix = function (bone) {
  60572. if (bone.getParent()) {
  60573. bone.getLocalMatrix().multiplyToRef(bone.getParent().getAbsoluteTransform(), bone.getAbsoluteTransform());
  60574. }
  60575. var children = bone.children;
  60576. var len = children.length;
  60577. for (var i = 0; i < len; i++) {
  60578. this._updateBoneMatrix(children[i]);
  60579. }
  60580. };
  60581. SkeletonViewer.prototype.dispose = function () {
  60582. if (this._debugMesh) {
  60583. this.isEnabled = false;
  60584. this._debugMesh.dispose();
  60585. this._debugMesh = null;
  60586. }
  60587. };
  60588. return SkeletonViewer;
  60589. }());
  60590. Debug.SkeletonViewer = SkeletonViewer;
  60591. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  60592. })(BABYLON || (BABYLON = {}));
  60593. var BABYLON;
  60594. (function (BABYLON) {
  60595. /**
  60596. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  60597. * It can help converting any input color in a desired output one. This can then be used to create effects
  60598. * from sepia, black and white to sixties or futuristic rendering...
  60599. *
  60600. * The only supported format is currently 3dl.
  60601. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  60602. */
  60603. var ColorGradingTexture = (function (_super) {
  60604. __extends(ColorGradingTexture, _super);
  60605. /**
  60606. * Instantiates a ColorGradingTexture from the following parameters.
  60607. *
  60608. * @param url The location of the color gradind data (currently only supporting 3dl)
  60609. * @param scene The scene the texture will be used in
  60610. */
  60611. function ColorGradingTexture(url, scene) {
  60612. _super.call(this, scene);
  60613. if (!url) {
  60614. return;
  60615. }
  60616. this._textureMatrix = BABYLON.Matrix.Identity();
  60617. this.name = url;
  60618. this.url = url;
  60619. this.hasAlpha = false;
  60620. this.isCube = false;
  60621. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60622. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60623. this.anisotropicFilteringLevel = 1;
  60624. this._texture = this._getFromCache(url, true);
  60625. if (!this._texture) {
  60626. if (!scene.useDelayedTextureLoading) {
  60627. this.loadTexture();
  60628. }
  60629. else {
  60630. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  60631. }
  60632. }
  60633. }
  60634. /**
  60635. * Returns the texture matrix used in most of the material.
  60636. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  60637. */
  60638. ColorGradingTexture.prototype.getTextureMatrix = function () {
  60639. return this._textureMatrix;
  60640. };
  60641. /**
  60642. * Occurs when the file being loaded is a .3dl LUT file.
  60643. */
  60644. ColorGradingTexture.prototype.load3dlTexture = function () {
  60645. var _this = this;
  60646. var mipLevels = 0;
  60647. var floatArrayView = null;
  60648. var texture = this.getScene().getEngine().createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  60649. this._texture = texture;
  60650. var callback = function (text) {
  60651. var data;
  60652. var tempData;
  60653. var line;
  60654. var lines = text.split('\n');
  60655. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  60656. var maxColor = 0;
  60657. for (var i = 0; i < lines.length; i++) {
  60658. line = lines[i];
  60659. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  60660. continue;
  60661. if (line.indexOf('#') === 0)
  60662. continue;
  60663. var words = line.split(" ");
  60664. if (size === 0) {
  60665. // Number of space + one
  60666. size = words.length;
  60667. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  60668. tempData = new Float32Array(size * size * size * 4);
  60669. continue;
  60670. }
  60671. if (size != 0) {
  60672. var r = Math.max(parseInt(words[0]), 0);
  60673. var g = Math.max(parseInt(words[1]), 0);
  60674. var b = Math.max(parseInt(words[2]), 0);
  60675. maxColor = Math.max(r, maxColor);
  60676. maxColor = Math.max(g, maxColor);
  60677. maxColor = Math.max(b, maxColor);
  60678. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  60679. tempData[pixelStorageIndex + 0] = r;
  60680. tempData[pixelStorageIndex + 1] = g;
  60681. tempData[pixelStorageIndex + 2] = b;
  60682. tempData[pixelStorageIndex + 3] = 0;
  60683. pixelIndexSlice++;
  60684. if (pixelIndexSlice % size == 0) {
  60685. pixelIndexH++;
  60686. pixelIndexSlice = 0;
  60687. if (pixelIndexH % size == 0) {
  60688. pixelIndexW++;
  60689. pixelIndexH = 0;
  60690. }
  60691. }
  60692. }
  60693. }
  60694. for (var i = 0; i < tempData.length; i++) {
  60695. var value = tempData[i];
  60696. data[i] = (value / maxColor * 255);
  60697. }
  60698. _this.getScene().getEngine().updateTextureSize(texture, size * size, size);
  60699. _this.getScene().getEngine().updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  60700. };
  60701. BABYLON.Tools.LoadFile(this.url, callback);
  60702. return this._texture;
  60703. };
  60704. /**
  60705. * Starts the loading process of the texture.
  60706. */
  60707. ColorGradingTexture.prototype.loadTexture = function () {
  60708. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  60709. this.load3dlTexture();
  60710. }
  60711. };
  60712. /**
  60713. * Clones the color gradind texture.
  60714. */
  60715. ColorGradingTexture.prototype.clone = function () {
  60716. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  60717. // Base texture
  60718. newTexture.level = this.level;
  60719. return newTexture;
  60720. };
  60721. /**
  60722. * Called during delayed load for textures.
  60723. */
  60724. ColorGradingTexture.prototype.delayLoad = function () {
  60725. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  60726. return;
  60727. }
  60728. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  60729. this._texture = this._getFromCache(this.url, true);
  60730. if (!this._texture) {
  60731. this.loadTexture();
  60732. }
  60733. };
  60734. /**
  60735. * Binds the color grading to the shader.
  60736. * @param colorGrading The texture to bind
  60737. * @param effect The effect to bind to
  60738. */
  60739. ColorGradingTexture.Bind = function (colorGrading, effect) {
  60740. effect.setTexture("cameraColorGrading2DSampler", colorGrading);
  60741. var x = colorGrading.level; // Texture Level
  60742. var y = colorGrading.getSize().height; // Texture Size example with 8
  60743. var z = y - 1.0; // SizeMinusOne 8 - 1
  60744. var w = 1 / y; // Space of 1 slice 1 / 8
  60745. effect.setFloat4("vCameraColorGradingInfos", x, y, z, w);
  60746. var slicePixelSizeU = w / y; // Space of 1 pixel in U direction, e.g. 1/64
  60747. 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
  60748. 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
  60749. 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
  60750. var z2 = 0.5 * slicePixelSizeU; // Offset of lookup range in U to align sample position with texel centre, for example 0.5/64
  60751. var w2 = 0.5 * slicePixelSizeV; // Offset of lookup range in V to align sample position with texel centre, for example 0.5/8
  60752. effect.setFloat4("vCameraColorGradingScaleOffset", x2, y2, z2, w2);
  60753. };
  60754. /**
  60755. * Prepare the list of uniforms associated with the ColorGrading effects.
  60756. * @param uniformsList The list of uniforms used in the effect
  60757. * @param samplersList The list of samplers used in the effect
  60758. */
  60759. ColorGradingTexture.PrepareUniformsAndSamplers = function (uniformsList, samplersList) {
  60760. uniformsList.push("vCameraColorGradingInfos", "vCameraColorGradingScaleOffset");
  60761. samplersList.push("cameraColorGrading2DSampler");
  60762. };
  60763. /**
  60764. * Parses a color grading texture serialized by Babylon.
  60765. * @param parsedTexture The texture information being parsedTexture
  60766. * @param scene The scene to load the texture in
  60767. * @param rootUrl The root url of the data assets to load
  60768. * @return A color gradind texture
  60769. */
  60770. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  60771. var texture = null;
  60772. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  60773. texture = new BABYLON.ColorGradingTexture(parsedTexture.name, scene);
  60774. texture.name = parsedTexture.name;
  60775. texture.level = parsedTexture.level;
  60776. }
  60777. return texture;
  60778. };
  60779. /**
  60780. * Serializes the LUT texture to json format.
  60781. */
  60782. ColorGradingTexture.prototype.serialize = function () {
  60783. if (!this.name) {
  60784. return null;
  60785. }
  60786. var serializationObject = {};
  60787. serializationObject.name = this.name;
  60788. serializationObject.level = this.level;
  60789. serializationObject.customType = "BABYLON.ColorGradingTexture";
  60790. return serializationObject;
  60791. };
  60792. /**
  60793. * Empty line regex stored for GC.
  60794. */
  60795. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  60796. return ColorGradingTexture;
  60797. }(BABYLON.BaseTexture));
  60798. BABYLON.ColorGradingTexture = ColorGradingTexture;
  60799. })(BABYLON || (BABYLON = {}));
  60800. var BABYLON;
  60801. (function (BABYLON) {
  60802. /**
  60803. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  60804. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  60805. * 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;
  60806. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  60807. */
  60808. var ColorCurves = (function () {
  60809. function ColorCurves() {
  60810. this._dirty = true;
  60811. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  60812. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  60813. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  60814. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  60815. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  60816. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  60817. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  60818. this._globalHue = 30;
  60819. this._globalDensity = 0;
  60820. this._globalSaturation = 0;
  60821. this._globalExposure = 0;
  60822. this._highlightsHue = 30;
  60823. this._highlightsDensity = 0;
  60824. this._highlightsSaturation = 0;
  60825. this._highlightsExposure = 0;
  60826. this._midtonesHue = 30;
  60827. this._midtonesDensity = 0;
  60828. this._midtonesSaturation = 0;
  60829. this._midtonesExposure = 0;
  60830. this._shadowsHue = 30;
  60831. this._shadowsDensity = 0;
  60832. this._shadowsSaturation = 0;
  60833. this._shadowsExposure = 0;
  60834. }
  60835. Object.defineProperty(ColorCurves.prototype, "GlobalHue", {
  60836. /**
  60837. * Gets the global Hue value.
  60838. * 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).
  60839. */
  60840. get: function () {
  60841. return this._globalHue;
  60842. },
  60843. /**
  60844. * Sets the global Hue value.
  60845. * 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).
  60846. */
  60847. set: function (value) {
  60848. this._globalHue = value;
  60849. this._dirty = true;
  60850. },
  60851. enumerable: true,
  60852. configurable: true
  60853. });
  60854. Object.defineProperty(ColorCurves.prototype, "GlobalDensity", {
  60855. /**
  60856. * Gets the global Density value.
  60857. * 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.
  60858. * Values less than zero provide a filter of opposite hue.
  60859. */
  60860. get: function () {
  60861. return this._globalDensity;
  60862. },
  60863. /**
  60864. * Sets the global Density value.
  60865. * 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.
  60866. * Values less than zero provide a filter of opposite hue.
  60867. */
  60868. set: function (value) {
  60869. this._globalDensity = value;
  60870. this._dirty = true;
  60871. },
  60872. enumerable: true,
  60873. configurable: true
  60874. });
  60875. Object.defineProperty(ColorCurves.prototype, "GlobalSaturation", {
  60876. /**
  60877. * Gets the global Saturation value.
  60878. * 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.
  60879. */
  60880. get: function () {
  60881. return this._globalSaturation;
  60882. },
  60883. /**
  60884. * Sets the global Saturation value.
  60885. * 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.
  60886. */
  60887. set: function (value) {
  60888. this._globalSaturation = value;
  60889. this._dirty = true;
  60890. },
  60891. enumerable: true,
  60892. configurable: true
  60893. });
  60894. Object.defineProperty(ColorCurves.prototype, "HighlightsHue", {
  60895. /**
  60896. * Gets the highlights Hue value.
  60897. * 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).
  60898. */
  60899. get: function () {
  60900. return this._highlightsHue;
  60901. },
  60902. /**
  60903. * Sets the highlights Hue value.
  60904. * 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).
  60905. */
  60906. set: function (value) {
  60907. this._highlightsHue = value;
  60908. this._dirty = true;
  60909. },
  60910. enumerable: true,
  60911. configurable: true
  60912. });
  60913. Object.defineProperty(ColorCurves.prototype, "HighlightsDensity", {
  60914. /**
  60915. * Gets the highlights Density value.
  60916. * 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.
  60917. * Values less than zero provide a filter of opposite hue.
  60918. */
  60919. get: function () {
  60920. return this._highlightsDensity;
  60921. },
  60922. /**
  60923. * Sets the highlights Density value.
  60924. * 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.
  60925. * Values less than zero provide a filter of opposite hue.
  60926. */
  60927. set: function (value) {
  60928. this._highlightsDensity = value;
  60929. this._dirty = true;
  60930. },
  60931. enumerable: true,
  60932. configurable: true
  60933. });
  60934. Object.defineProperty(ColorCurves.prototype, "HighlightsSaturation", {
  60935. /**
  60936. * Gets the highlights Saturation value.
  60937. * 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.
  60938. */
  60939. get: function () {
  60940. return this._highlightsSaturation;
  60941. },
  60942. /**
  60943. * Sets the highlights Saturation value.
  60944. * 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.
  60945. */
  60946. set: function (value) {
  60947. this._highlightsSaturation = value;
  60948. this._dirty = true;
  60949. },
  60950. enumerable: true,
  60951. configurable: true
  60952. });
  60953. Object.defineProperty(ColorCurves.prototype, "HighlightsExposure", {
  60954. /**
  60955. * Gets the highlights Exposure value.
  60956. * 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.
  60957. */
  60958. get: function () {
  60959. return this._highlightsExposure;
  60960. },
  60961. /**
  60962. * Sets the highlights Exposure value.
  60963. * 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.
  60964. */
  60965. set: function (value) {
  60966. this._highlightsExposure = value;
  60967. this._dirty = true;
  60968. },
  60969. enumerable: true,
  60970. configurable: true
  60971. });
  60972. Object.defineProperty(ColorCurves.prototype, "MidtonesHue", {
  60973. /**
  60974. * Gets the midtones Hue value.
  60975. * 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).
  60976. */
  60977. get: function () {
  60978. return this._midtonesHue;
  60979. },
  60980. /**
  60981. * Sets the midtones Hue value.
  60982. * 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).
  60983. */
  60984. set: function (value) {
  60985. this._midtonesHue = value;
  60986. this._dirty = true;
  60987. },
  60988. enumerable: true,
  60989. configurable: true
  60990. });
  60991. Object.defineProperty(ColorCurves.prototype, "MidtonesDensity", {
  60992. /**
  60993. * Gets the midtones Density value.
  60994. * 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.
  60995. * Values less than zero provide a filter of opposite hue.
  60996. */
  60997. get: function () {
  60998. return this._midtonesDensity;
  60999. },
  61000. /**
  61001. * Sets the midtones Density value.
  61002. * 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.
  61003. * Values less than zero provide a filter of opposite hue.
  61004. */
  61005. set: function (value) {
  61006. this._midtonesDensity = value;
  61007. this._dirty = true;
  61008. },
  61009. enumerable: true,
  61010. configurable: true
  61011. });
  61012. Object.defineProperty(ColorCurves.prototype, "MidtonesSaturation", {
  61013. /**
  61014. * Gets the midtones Saturation value.
  61015. * 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.
  61016. */
  61017. get: function () {
  61018. return this._midtonesSaturation;
  61019. },
  61020. /**
  61021. * Sets the midtones Saturation value.
  61022. * 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.
  61023. */
  61024. set: function (value) {
  61025. this._midtonesSaturation = value;
  61026. this._dirty = true;
  61027. },
  61028. enumerable: true,
  61029. configurable: true
  61030. });
  61031. Object.defineProperty(ColorCurves.prototype, "MidtonesExposure", {
  61032. /**
  61033. * Gets the midtones Exposure value.
  61034. * 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.
  61035. */
  61036. get: function () {
  61037. return this._midtonesExposure;
  61038. },
  61039. /**
  61040. * Sets the midtones Exposure value.
  61041. * 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.
  61042. */
  61043. set: function (value) {
  61044. this._midtonesExposure = value;
  61045. this._dirty = true;
  61046. },
  61047. enumerable: true,
  61048. configurable: true
  61049. });
  61050. Object.defineProperty(ColorCurves.prototype, "ShadowsHue", {
  61051. /**
  61052. * Gets the shadows Hue value.
  61053. * 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).
  61054. */
  61055. get: function () {
  61056. return this._shadowsHue;
  61057. },
  61058. /**
  61059. * Sets the shadows Hue value.
  61060. * 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).
  61061. */
  61062. set: function (value) {
  61063. this._shadowsHue = value;
  61064. this._dirty = true;
  61065. },
  61066. enumerable: true,
  61067. configurable: true
  61068. });
  61069. Object.defineProperty(ColorCurves.prototype, "ShadowsDensity", {
  61070. /**
  61071. * Gets the shadows Density value.
  61072. * 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.
  61073. * Values less than zero provide a filter of opposite hue.
  61074. */
  61075. get: function () {
  61076. return this._shadowsDensity;
  61077. },
  61078. /**
  61079. * Sets the shadows Density value.
  61080. * 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.
  61081. * Values less than zero provide a filter of opposite hue.
  61082. */
  61083. set: function (value) {
  61084. this._shadowsDensity = value;
  61085. this._dirty = true;
  61086. },
  61087. enumerable: true,
  61088. configurable: true
  61089. });
  61090. Object.defineProperty(ColorCurves.prototype, "ShadowsSaturation", {
  61091. /**
  61092. * Gets the shadows Saturation value.
  61093. * 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.
  61094. */
  61095. get: function () {
  61096. return this._shadowsSaturation;
  61097. },
  61098. /**
  61099. * Sets the shadows Saturation value.
  61100. * 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.
  61101. */
  61102. set: function (value) {
  61103. this._shadowsSaturation = value;
  61104. this._dirty = true;
  61105. },
  61106. enumerable: true,
  61107. configurable: true
  61108. });
  61109. Object.defineProperty(ColorCurves.prototype, "ShadowsExposure", {
  61110. /**
  61111. * Gets the shadows Exposure value.
  61112. * 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.
  61113. */
  61114. get: function () {
  61115. return this._shadowsExposure;
  61116. },
  61117. /**
  61118. * Sets the shadows Exposure value.
  61119. * 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.
  61120. */
  61121. set: function (value) {
  61122. this._shadowsExposure = value;
  61123. this._dirty = true;
  61124. },
  61125. enumerable: true,
  61126. configurable: true
  61127. });
  61128. /**
  61129. * Binds the color curves to the shader.
  61130. * @param colorCurves The color curve to bind
  61131. * @param effect The effect to bind to
  61132. */
  61133. ColorCurves.Bind = function (colorCurves, effect) {
  61134. if (colorCurves._dirty) {
  61135. colorCurves._dirty = false;
  61136. // Fill in global info.
  61137. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  61138. // Compute highlights info.
  61139. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  61140. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  61141. // Compute midtones info.
  61142. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  61143. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  61144. // Compute shadows info.
  61145. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  61146. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  61147. // Compute deltas (neutral is midtones).
  61148. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  61149. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  61150. }
  61151. effect.setFloat4("vCameraColorCurvePositive", colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  61152. effect.setFloat4("vCameraColorCurveNeutral", colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  61153. effect.setFloat4("vCameraColorCurveNegative", colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  61154. };
  61155. /**
  61156. * Prepare the list of uniforms associated with the ColorCurves effects.
  61157. * @param uniformsList The list of uniforms used in the effect
  61158. */
  61159. ColorCurves.PrepareUniforms = function (uniformsList) {
  61160. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  61161. };
  61162. /**
  61163. * Returns color grading data based on a hue, density, saturation and exposure value.
  61164. * @param filterHue The hue of the color filter.
  61165. * @param filterDensity The density of the color filter.
  61166. * @param saturation The saturation.
  61167. * @param exposure The exposure.
  61168. * @param result The result data container.
  61169. */
  61170. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  61171. if (hue == null) {
  61172. return;
  61173. }
  61174. hue = ColorCurves.clamp(hue, 0, 360);
  61175. density = ColorCurves.clamp(density, -100, 100);
  61176. saturation = ColorCurves.clamp(saturation, -100, 100);
  61177. exposure = ColorCurves.clamp(exposure, -100, 100);
  61178. // Remap the slider/config filter density with non-linear mapping and also scale by half
  61179. // so that the maximum filter density is only 50% control. This provides fine control
  61180. // for small values and reasonable range.
  61181. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  61182. density *= 0.5;
  61183. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  61184. if (density < 0) {
  61185. density *= -1;
  61186. hue = (hue + 180) % 360;
  61187. }
  61188. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  61189. result.scaleToRef(2, result);
  61190. result.a = 1 + 0.01 * saturation;
  61191. };
  61192. /**
  61193. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  61194. * @param value The input slider value in range [-100,100].
  61195. * @returns Adjusted value.
  61196. */
  61197. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  61198. value /= 100;
  61199. var x = Math.abs(value);
  61200. x = Math.pow(x, 2);
  61201. if (value < 0) {
  61202. x *= -1;
  61203. }
  61204. x *= 100;
  61205. return x;
  61206. };
  61207. /**
  61208. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  61209. * @param hue The hue (H) input.
  61210. * @param saturation The saturation (S) input.
  61211. * @param brightness The brightness (B) input.
  61212. * @result An RGBA color represented as Vector4.
  61213. */
  61214. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  61215. var h = ColorCurves.clamp(hue, 0, 360);
  61216. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  61217. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  61218. if (s === 0) {
  61219. result.r = v;
  61220. result.g = v;
  61221. result.b = v;
  61222. }
  61223. else {
  61224. // sector 0 to 5
  61225. h /= 60;
  61226. var i = Math.floor(h);
  61227. // fractional part of h
  61228. var f = h - i;
  61229. var p = v * (1 - s);
  61230. var q = v * (1 - s * f);
  61231. var t = v * (1 - s * (1 - f));
  61232. switch (i) {
  61233. case 0:
  61234. result.r = v;
  61235. result.g = t;
  61236. result.b = p;
  61237. break;
  61238. case 1:
  61239. result.r = q;
  61240. result.g = v;
  61241. result.b = p;
  61242. break;
  61243. case 2:
  61244. result.r = p;
  61245. result.g = v;
  61246. result.b = t;
  61247. break;
  61248. case 3:
  61249. result.r = p;
  61250. result.g = q;
  61251. result.b = v;
  61252. break;
  61253. case 4:
  61254. result.r = t;
  61255. result.g = p;
  61256. result.b = v;
  61257. break;
  61258. default:
  61259. result.r = v;
  61260. result.g = p;
  61261. result.b = q;
  61262. break;
  61263. }
  61264. }
  61265. result.a = 1;
  61266. };
  61267. /**
  61268. * Returns a value clamped between min and max
  61269. * @param value The value to clamp
  61270. * @param min The minimum of value
  61271. * @param max The maximum of value
  61272. * @returns The clamped value.
  61273. */
  61274. ColorCurves.clamp = function (value, min, max) {
  61275. return Math.min(Math.max(value, min), max);
  61276. };
  61277. /**
  61278. * Clones the current color curve instance.
  61279. * @return The cloned curves
  61280. */
  61281. ColorCurves.prototype.clone = function () {
  61282. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  61283. };
  61284. /**
  61285. * Serializes the current color curve instance to a json representation.
  61286. * @return a JSON representation
  61287. */
  61288. ColorCurves.prototype.serialize = function () {
  61289. return BABYLON.SerializationHelper.Serialize(this);
  61290. };
  61291. /**
  61292. * Parses the color curve from a json representation.
  61293. * @param source the JSON source to parse
  61294. * @return The parsed curves
  61295. */
  61296. ColorCurves.Parse = function (source) {
  61297. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  61298. };
  61299. __decorate([
  61300. BABYLON.serialize()
  61301. ], ColorCurves.prototype, "_globalHue", void 0);
  61302. __decorate([
  61303. BABYLON.serialize()
  61304. ], ColorCurves.prototype, "_globalDensity", void 0);
  61305. __decorate([
  61306. BABYLON.serialize()
  61307. ], ColorCurves.prototype, "_globalSaturation", void 0);
  61308. __decorate([
  61309. BABYLON.serialize()
  61310. ], ColorCurves.prototype, "_globalExposure", void 0);
  61311. __decorate([
  61312. BABYLON.serialize()
  61313. ], ColorCurves.prototype, "_highlightsHue", void 0);
  61314. __decorate([
  61315. BABYLON.serialize()
  61316. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  61317. __decorate([
  61318. BABYLON.serialize()
  61319. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  61320. __decorate([
  61321. BABYLON.serialize()
  61322. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  61323. __decorate([
  61324. BABYLON.serialize()
  61325. ], ColorCurves.prototype, "_midtonesHue", void 0);
  61326. __decorate([
  61327. BABYLON.serialize()
  61328. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  61329. __decorate([
  61330. BABYLON.serialize()
  61331. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  61332. __decorate([
  61333. BABYLON.serialize()
  61334. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  61335. return ColorCurves;
  61336. }());
  61337. BABYLON.ColorCurves = ColorCurves;
  61338. })(BABYLON || (BABYLON = {}));
  61339. var BABYLON;
  61340. (function (BABYLON) {
  61341. var PBRMaterialDefines = (function (_super) {
  61342. __extends(PBRMaterialDefines, _super);
  61343. function PBRMaterialDefines() {
  61344. _super.call(this);
  61345. this.ALBEDO = false;
  61346. this.AMBIENT = false;
  61347. this.OPACITY = false;
  61348. this.OPACITYRGB = false;
  61349. this.REFLECTION = false;
  61350. this.EMISSIVE = false;
  61351. this.REFLECTIVITY = false;
  61352. this.BUMP = false;
  61353. this.PARALLAX = false;
  61354. this.PARALLAXOCCLUSION = false;
  61355. this.SPECULAROVERALPHA = false;
  61356. this.CLIPPLANE = false;
  61357. this.ALPHATEST = false;
  61358. this.ALPHAFROMALBEDO = false;
  61359. this.POINTSIZE = false;
  61360. this.FOG = false;
  61361. this.SPECULARTERM = false;
  61362. this.OPACITYFRESNEL = false;
  61363. this.EMISSIVEFRESNEL = false;
  61364. this.FRESNEL = false;
  61365. this.NORMAL = false;
  61366. this.UV1 = false;
  61367. this.UV2 = false;
  61368. this.VERTEXCOLOR = false;
  61369. this.VERTEXALPHA = false;
  61370. this.NUM_BONE_INFLUENCERS = 0;
  61371. this.BonesPerMesh = 0;
  61372. this.INSTANCES = false;
  61373. this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  61374. this.MICROSURFACEAUTOMATIC = false;
  61375. this.EMISSIVEASILLUMINATION = false;
  61376. this.LINKEMISSIVEWITHALBEDO = false;
  61377. this.LIGHTMAP = false;
  61378. this.USELIGHTMAPASSHADOWMAP = false;
  61379. this.REFLECTIONMAP_3D = false;
  61380. this.REFLECTIONMAP_SPHERICAL = false;
  61381. this.REFLECTIONMAP_PLANAR = false;
  61382. this.REFLECTIONMAP_CUBIC = false;
  61383. this.REFLECTIONMAP_PROJECTION = false;
  61384. this.REFLECTIONMAP_SKYBOX = false;
  61385. this.REFLECTIONMAP_EXPLICIT = false;
  61386. this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  61387. this.INVERTCUBICMAP = false;
  61388. this.LOGARITHMICDEPTH = false;
  61389. this.CAMERATONEMAP = false;
  61390. this.CAMERACONTRAST = false;
  61391. this.CAMERACOLORGRADING = false;
  61392. this.CAMERACOLORCURVES = false;
  61393. this.OVERLOADEDVALUES = false;
  61394. this.OVERLOADEDSHADOWVALUES = false;
  61395. this.USESPHERICALFROMREFLECTIONMAP = false;
  61396. this.REFRACTION = false;
  61397. this.REFRACTIONMAP_3D = false;
  61398. this.LINKREFRACTIONTOTRANSPARENCY = false;
  61399. this.REFRACTIONMAPINLINEARSPACE = false;
  61400. this.LODBASEDMICROSFURACE = false;
  61401. this.USEPHYSICALLIGHTFALLOFF = false;
  61402. this.RADIANCEOVERALPHA = false;
  61403. this.USEPMREMREFLECTION = false;
  61404. this.USEPMREMREFRACTION = false;
  61405. this.OPENGLNORMALMAP = false;
  61406. this.INVERTNORMALMAPX = false;
  61407. this.INVERTNORMALMAPY = false;
  61408. this.SHADOWFULLFLOAT = false;
  61409. this.rebuild();
  61410. }
  61411. return PBRMaterialDefines;
  61412. }(BABYLON.MaterialDefines));
  61413. /**
  61414. * The Physically based material of BJS.
  61415. *
  61416. * This offers the main features of a standard PBR material.
  61417. * For more information, please refer to the documentation :
  61418. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  61419. */
  61420. var PBRMaterial = (function (_super) {
  61421. __extends(PBRMaterial, _super);
  61422. /**
  61423. * Instantiates a new PBRMaterial instance.
  61424. *
  61425. * @param name The material name
  61426. * @param scene The scene the material will be use in.
  61427. */
  61428. function PBRMaterial(name, scene) {
  61429. var _this = this;
  61430. _super.call(this, name, scene);
  61431. /**
  61432. * Intensity of the direct lights e.g. the four lights available in your scene.
  61433. * This impacts both the direct diffuse and specular highlights.
  61434. */
  61435. this.directIntensity = 1.0;
  61436. /**
  61437. * Intensity of the emissive part of the material.
  61438. * This helps controlling the emissive effect without modifying the emissive color.
  61439. */
  61440. this.emissiveIntensity = 1.0;
  61441. /**
  61442. * Intensity of the environment e.g. how much the environment will light the object
  61443. * either through harmonics for rough material or through the refelction for shiny ones.
  61444. */
  61445. this.environmentIntensity = 1.0;
  61446. /**
  61447. * This is a special control allowing the reduction of the specular highlights coming from the
  61448. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  61449. */
  61450. this.specularIntensity = 1.0;
  61451. this._lightingInfos = new BABYLON.Vector4(this.directIntensity, this.emissiveIntensity, this.environmentIntensity, this.specularIntensity);
  61452. /**
  61453. * Debug Control allowing disabling the bump map on this material.
  61454. */
  61455. this.disableBumpMap = false;
  61456. /**
  61457. * Debug Control helping enforcing or dropping the darkness of shadows.
  61458. * 1.0 means the shadows have their normal darkness, 0.0 means the shadows are not visible.
  61459. */
  61460. this.overloadedShadowIntensity = 1.0;
  61461. /**
  61462. * Debug Control helping dropping the shading effect coming from the diffuse lighting.
  61463. * 1.0 means the shade have their normal impact, 0.0 means no shading at all.
  61464. */
  61465. this.overloadedShadeIntensity = 1.0;
  61466. this._overloadedShadowInfos = new BABYLON.Vector4(this.overloadedShadowIntensity, this.overloadedShadeIntensity, 0.0, 0.0);
  61467. /**
  61468. * The camera exposure used on this material.
  61469. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  61470. * This corresponds to a photographic exposure.
  61471. */
  61472. this.cameraExposure = 1.0;
  61473. /**
  61474. * The camera contrast used on this material.
  61475. * This property is here and not in the camera to allow controlling contrast without full screen post process.
  61476. */
  61477. this.cameraContrast = 1.0;
  61478. /**
  61479. * Color Grading 2D Lookup Texture.
  61480. * This allows special effects like sepia, black and white to sixties rendering style.
  61481. */
  61482. this.cameraColorGradingTexture = null;
  61483. /**
  61484. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  61485. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  61486. * 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;
  61487. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  61488. */
  61489. this.cameraColorCurves = null;
  61490. this._cameraInfos = new BABYLON.Vector4(1.0, 1.0, 0.0, 0.0);
  61491. this._microsurfaceTextureLods = new BABYLON.Vector2(0.0, 0.0);
  61492. /**
  61493. * Debug Control allowing to overload the ambient color.
  61494. * This as to be use with the overloadedAmbientIntensity parameter.
  61495. */
  61496. this.overloadedAmbient = BABYLON.Color3.White();
  61497. /**
  61498. * Debug Control indicating how much the overloaded ambient color is used against the default one.
  61499. */
  61500. this.overloadedAmbientIntensity = 0.0;
  61501. /**
  61502. * Debug Control allowing to overload the albedo color.
  61503. * This as to be use with the overloadedAlbedoIntensity parameter.
  61504. */
  61505. this.overloadedAlbedo = BABYLON.Color3.White();
  61506. /**
  61507. * Debug Control indicating how much the overloaded albedo color is used against the default one.
  61508. */
  61509. this.overloadedAlbedoIntensity = 0.0;
  61510. /**
  61511. * Debug Control allowing to overload the reflectivity color.
  61512. * This as to be use with the overloadedReflectivityIntensity parameter.
  61513. */
  61514. this.overloadedReflectivity = new BABYLON.Color3(0.3, 0.3, 0.3);
  61515. /**
  61516. * Debug Control indicating how much the overloaded reflectivity color is used against the default one.
  61517. */
  61518. this.overloadedReflectivityIntensity = 0.0;
  61519. /**
  61520. * Debug Control allowing to overload the emissive color.
  61521. * This as to be use with the overloadedEmissiveIntensity parameter.
  61522. */
  61523. this.overloadedEmissive = BABYLON.Color3.White();
  61524. /**
  61525. * Debug Control indicating how much the overloaded emissive color is used against the default one.
  61526. */
  61527. this.overloadedEmissiveIntensity = 0.0;
  61528. this._overloadedIntensity = new BABYLON.Vector4(this.overloadedAmbientIntensity, this.overloadedAlbedoIntensity, this.overloadedReflectivityIntensity, this.overloadedEmissiveIntensity);
  61529. /**
  61530. * Debug Control allowing to overload the reflection color.
  61531. * This as to be use with the overloadedReflectionIntensity parameter.
  61532. */
  61533. this.overloadedReflection = BABYLON.Color3.White();
  61534. /**
  61535. * Debug Control indicating how much the overloaded reflection color is used against the default one.
  61536. */
  61537. this.overloadedReflectionIntensity = 0.0;
  61538. /**
  61539. * Debug Control allowing to overload the microsurface.
  61540. * This as to be use with the overloadedMicroSurfaceIntensity parameter.
  61541. */
  61542. this.overloadedMicroSurface = 0.0;
  61543. /**
  61544. * Debug Control indicating how much the overloaded microsurface is used against the default one.
  61545. */
  61546. this.overloadedMicroSurfaceIntensity = 0.0;
  61547. this._overloadedMicroSurface = new BABYLON.Vector3(this.overloadedMicroSurface, this.overloadedMicroSurfaceIntensity, this.overloadedReflectionIntensity);
  61548. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  61549. /**
  61550. * AKA Diffuse Color in other nomenclature.
  61551. */
  61552. this.albedoColor = new BABYLON.Color3(1, 1, 1);
  61553. /**
  61554. * AKA Specular Color in other nomenclature.
  61555. */
  61556. this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  61557. this.reflectionColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  61558. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  61559. /**
  61560. * AKA Glossiness in other nomenclature.
  61561. */
  61562. this.microSurface = 0.9;
  61563. /**
  61564. * source material index of refraction (IOR)' / 'destination material IOR.
  61565. */
  61566. this.indexOfRefraction = 0.66;
  61567. /**
  61568. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  61569. */
  61570. this.invertRefractionY = false;
  61571. /**
  61572. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  61573. * Materials half opaque for instance using refraction could benefit from this control.
  61574. */
  61575. this.linkRefractionWithTransparency = false;
  61576. /**
  61577. * The emissive and albedo are linked to never be more than one (Energy conservation).
  61578. */
  61579. this.linkEmissiveWithAlbedo = false;
  61580. this.useLightmapAsShadowmap = false;
  61581. /**
  61582. * In this mode, the emissive informtaion will always be added to the lighting once.
  61583. * A light for instance can be thought as emissive.
  61584. */
  61585. this.useEmissiveAsIllumination = false;
  61586. /**
  61587. * Secifies that the alpha is coming form the albedo channel alpha channel.
  61588. */
  61589. this.useAlphaFromAlbedoTexture = false;
  61590. /**
  61591. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  61592. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  61593. */
  61594. this.useSpecularOverAlpha = true;
  61595. /**
  61596. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  61597. */
  61598. this.useMicroSurfaceFromReflectivityMapAlpha = false;
  61599. /**
  61600. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  61601. * The material will try to infer what glossiness each pixel should be.
  61602. */
  61603. this.useAutoMicroSurfaceFromReflectivityMap = false;
  61604. /**
  61605. * Allows to work with scalar in linear mode. This is definitely a matter of preferences and tools used during
  61606. * the creation of the material.
  61607. */
  61608. this.useScalarInLinearSpace = false;
  61609. /**
  61610. * BJS is using an harcoded light falloff based on a manually sets up range.
  61611. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  61612. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  61613. */
  61614. this.usePhysicalLightFalloff = true;
  61615. /**
  61616. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  61617. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  61618. */
  61619. this.useRadianceOverAlpha = true;
  61620. /**
  61621. * Allows using the bump map in parallax mode.
  61622. */
  61623. this.useParallax = false;
  61624. /**
  61625. * Allows using the bump map in parallax occlusion mode.
  61626. */
  61627. this.useParallaxOcclusion = false;
  61628. /**
  61629. * Controls the scale bias of the parallax mode.
  61630. */
  61631. this.parallaxScaleBias = 0.05;
  61632. /**
  61633. * If sets to true, disables all the lights affecting the material.
  61634. */
  61635. this.disableLighting = false;
  61636. /**
  61637. * Number of Simultaneous lights allowed on the material.
  61638. */
  61639. this.maxSimultaneousLights = 4;
  61640. /**
  61641. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  61642. */
  61643. this.invertNormalMapX = false;
  61644. /**
  61645. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  61646. */
  61647. this.invertNormalMapY = false;
  61648. this._renderTargets = new BABYLON.SmartArray(16);
  61649. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  61650. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  61651. this._tempColor = new BABYLON.Color3();
  61652. this._defines = new PBRMaterialDefines();
  61653. this._cachedDefines = new PBRMaterialDefines();
  61654. this._myScene = null;
  61655. this._myShadowGenerator = null;
  61656. this._cachedDefines.BonesPerMesh = -1;
  61657. this.getRenderTargetTextures = function () {
  61658. _this._renderTargets.reset();
  61659. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  61660. _this._renderTargets.push(_this.reflectionTexture);
  61661. }
  61662. if (_this.refractionTexture && _this.refractionTexture.isRenderTarget) {
  61663. _this._renderTargets.push(_this.refractionTexture);
  61664. }
  61665. return _this._renderTargets;
  61666. };
  61667. }
  61668. Object.defineProperty(PBRMaterial.prototype, "useLogarithmicDepth", {
  61669. get: function () {
  61670. return this._useLogarithmicDepth;
  61671. },
  61672. set: function (value) {
  61673. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  61674. },
  61675. enumerable: true,
  61676. configurable: true
  61677. });
  61678. PBRMaterial.prototype.needAlphaBlending = function () {
  61679. if (this.linkRefractionWithTransparency) {
  61680. return false;
  61681. }
  61682. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  61683. };
  61684. PBRMaterial.prototype.needAlphaTesting = function () {
  61685. if (this.linkRefractionWithTransparency) {
  61686. return false;
  61687. }
  61688. return this.albedoTexture != null && this.albedoTexture.hasAlpha;
  61689. };
  61690. PBRMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  61691. return this.albedoTexture != null && this.albedoTexture.hasAlpha && this.useAlphaFromAlbedoTexture;
  61692. };
  61693. PBRMaterial.prototype.getAlphaTestTexture = function () {
  61694. return this.albedoTexture;
  61695. };
  61696. PBRMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  61697. if (!mesh) {
  61698. return true;
  61699. }
  61700. if (this._defines.INSTANCES !== useInstances) {
  61701. return false;
  61702. }
  61703. if (mesh._materialDefines && mesh._materialDefines.isEqual(this._defines)) {
  61704. return true;
  61705. }
  61706. return false;
  61707. };
  61708. PBRMaterial.prototype.convertColorToLinearSpaceToRef = function (color, ref) {
  61709. PBRMaterial.convertColorToLinearSpaceToRef(color, ref, this.useScalarInLinearSpace);
  61710. };
  61711. PBRMaterial.convertColorToLinearSpaceToRef = function (color, ref, useScalarInLinear) {
  61712. if (!useScalarInLinear) {
  61713. color.toLinearSpaceToRef(ref);
  61714. }
  61715. else {
  61716. ref.r = color.r;
  61717. ref.g = color.g;
  61718. ref.b = color.b;
  61719. }
  61720. };
  61721. PBRMaterial.BindLights = function (scene, mesh, effect, defines, useScalarInLinearSpace, maxSimultaneousLights, usePhysicalLightFalloff) {
  61722. var lightIndex = 0;
  61723. var depthValuesAlreadySet = false;
  61724. for (var index = 0; index < scene.lights.length; index++) {
  61725. var light = scene.lights[index];
  61726. if (!light.isEnabled()) {
  61727. continue;
  61728. }
  61729. if (!light.canAffectMesh(mesh)) {
  61730. continue;
  61731. }
  61732. BABYLON.MaterialHelper.BindLightProperties(light, effect, lightIndex);
  61733. // GAMMA CORRECTION.
  61734. this.convertColorToLinearSpaceToRef(light.diffuse, PBRMaterial._scaledAlbedo, useScalarInLinearSpace);
  61735. PBRMaterial._scaledAlbedo.scaleToRef(light.intensity, PBRMaterial._scaledAlbedo);
  61736. effect.setColor4("vLightDiffuse" + lightIndex, PBRMaterial._scaledAlbedo, usePhysicalLightFalloff ? light.radius : light.range);
  61737. if (defines["SPECULARTERM"]) {
  61738. this.convertColorToLinearSpaceToRef(light.specular, PBRMaterial._scaledReflectivity, useScalarInLinearSpace);
  61739. PBRMaterial._scaledReflectivity.scaleToRef(light.intensity, PBRMaterial._scaledReflectivity);
  61740. effect.setColor3("vLightSpecular" + lightIndex, PBRMaterial._scaledReflectivity);
  61741. }
  61742. // Shadows
  61743. if (scene.shadowsEnabled) {
  61744. depthValuesAlreadySet = BABYLON.MaterialHelper.BindLightShadow(light, scene, mesh, lightIndex, effect, depthValuesAlreadySet);
  61745. }
  61746. lightIndex++;
  61747. if (lightIndex === maxSimultaneousLights)
  61748. break;
  61749. }
  61750. };
  61751. PBRMaterial.prototype.isReady = function (mesh, useInstances) {
  61752. if (this.checkReadyOnlyOnce) {
  61753. if (this._wasPreviouslyReady) {
  61754. return true;
  61755. }
  61756. }
  61757. var scene = this.getScene();
  61758. if (!this.checkReadyOnEveryCall) {
  61759. if (this._renderId === scene.getRenderId()) {
  61760. if (this._checkCache(scene, mesh, useInstances)) {
  61761. return true;
  61762. }
  61763. }
  61764. }
  61765. var engine = scene.getEngine();
  61766. var needNormals = false;
  61767. var needUVs = false;
  61768. this._defines.reset();
  61769. if (scene.texturesEnabled) {
  61770. // Textures
  61771. if (scene.texturesEnabled) {
  61772. if (scene.getEngine().getCaps().textureLOD) {
  61773. this._defines.LODBASEDMICROSFURACE = true;
  61774. }
  61775. if (this.albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  61776. if (!this.albedoTexture.isReady()) {
  61777. return false;
  61778. }
  61779. else {
  61780. needUVs = true;
  61781. this._defines.ALBEDO = true;
  61782. }
  61783. }
  61784. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  61785. if (!this.ambientTexture.isReady()) {
  61786. return false;
  61787. }
  61788. else {
  61789. needUVs = true;
  61790. this._defines.AMBIENT = true;
  61791. }
  61792. }
  61793. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  61794. if (!this.opacityTexture.isReady()) {
  61795. return false;
  61796. }
  61797. else {
  61798. needUVs = true;
  61799. this._defines.OPACITY = true;
  61800. if (this.opacityTexture.getAlphaFromRGB) {
  61801. this._defines.OPACITYRGB = true;
  61802. }
  61803. }
  61804. }
  61805. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  61806. if (!this.reflectionTexture.isReady()) {
  61807. return false;
  61808. }
  61809. else {
  61810. needNormals = true;
  61811. this._defines.REFLECTION = true;
  61812. if (this.reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  61813. this._defines.INVERTCUBICMAP = true;
  61814. }
  61815. this._defines.REFLECTIONMAP_3D = this.reflectionTexture.isCube;
  61816. switch (this.reflectionTexture.coordinatesMode) {
  61817. case BABYLON.Texture.CUBIC_MODE:
  61818. case BABYLON.Texture.INVCUBIC_MODE:
  61819. this._defines.REFLECTIONMAP_CUBIC = true;
  61820. break;
  61821. case BABYLON.Texture.EXPLICIT_MODE:
  61822. this._defines.REFLECTIONMAP_EXPLICIT = true;
  61823. break;
  61824. case BABYLON.Texture.PLANAR_MODE:
  61825. this._defines.REFLECTIONMAP_PLANAR = true;
  61826. break;
  61827. case BABYLON.Texture.PROJECTION_MODE:
  61828. this._defines.REFLECTIONMAP_PROJECTION = true;
  61829. break;
  61830. case BABYLON.Texture.SKYBOX_MODE:
  61831. this._defines.REFLECTIONMAP_SKYBOX = true;
  61832. break;
  61833. case BABYLON.Texture.SPHERICAL_MODE:
  61834. this._defines.REFLECTIONMAP_SPHERICAL = true;
  61835. break;
  61836. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  61837. this._defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  61838. break;
  61839. }
  61840. if (this.reflectionTexture instanceof BABYLON.HDRCubeTexture && this.reflectionTexture) {
  61841. this._defines.USESPHERICALFROMREFLECTIONMAP = true;
  61842. needNormals = true;
  61843. if (this.reflectionTexture.isPMREM) {
  61844. this._defines.USEPMREMREFLECTION = true;
  61845. }
  61846. }
  61847. }
  61848. }
  61849. if (this.lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  61850. if (!this.lightmapTexture.isReady()) {
  61851. return false;
  61852. }
  61853. else {
  61854. needUVs = true;
  61855. this._defines.LIGHTMAP = true;
  61856. this._defines.USELIGHTMAPASSHADOWMAP = this.useLightmapAsShadowmap;
  61857. }
  61858. }
  61859. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  61860. if (!this.emissiveTexture.isReady()) {
  61861. return false;
  61862. }
  61863. else {
  61864. needUVs = true;
  61865. this._defines.EMISSIVE = true;
  61866. }
  61867. }
  61868. if (this.reflectivityTexture && BABYLON.StandardMaterial.SpecularTextureEnabled) {
  61869. if (!this.reflectivityTexture.isReady()) {
  61870. return false;
  61871. }
  61872. else {
  61873. needUVs = true;
  61874. this._defines.REFLECTIVITY = true;
  61875. this._defines.MICROSURFACEFROMREFLECTIVITYMAP = this.useMicroSurfaceFromReflectivityMapAlpha;
  61876. this._defines.MICROSURFACEAUTOMATIC = this.useAutoMicroSurfaceFromReflectivityMap;
  61877. }
  61878. }
  61879. }
  61880. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this.disableBumpMap) {
  61881. if (!this.bumpTexture.isReady()) {
  61882. return false;
  61883. }
  61884. else {
  61885. needUVs = true;
  61886. this._defines.BUMP = true;
  61887. if (this.useParallax) {
  61888. this._defines.PARALLAX = true;
  61889. if (this.useParallaxOcclusion) {
  61890. this._defines.PARALLAXOCCLUSION = true;
  61891. }
  61892. }
  61893. if (this.invertNormalMapX) {
  61894. this._defines.INVERTNORMALMAPX = true;
  61895. }
  61896. if (this.invertNormalMapY) {
  61897. this._defines.INVERTNORMALMAPY = true;
  61898. }
  61899. }
  61900. }
  61901. if (this.refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  61902. if (!this.refractionTexture.isReady()) {
  61903. return false;
  61904. }
  61905. else {
  61906. needUVs = true;
  61907. this._defines.REFRACTION = true;
  61908. this._defines.REFRACTIONMAP_3D = this.refractionTexture.isCube;
  61909. if (this.linkRefractionWithTransparency) {
  61910. this._defines.LINKREFRACTIONTOTRANSPARENCY = true;
  61911. }
  61912. if (this.refractionTexture instanceof BABYLON.HDRCubeTexture) {
  61913. this._defines.REFRACTIONMAPINLINEARSPACE = true;
  61914. if (this.refractionTexture.isPMREM) {
  61915. this._defines.USEPMREMREFRACTION = true;
  61916. }
  61917. }
  61918. }
  61919. }
  61920. if (this.cameraColorGradingTexture && BABYLON.StandardMaterial.ColorGradingTextureEnabled) {
  61921. if (!this.cameraColorGradingTexture.isReady()) {
  61922. return false;
  61923. }
  61924. else {
  61925. this._defines.CAMERACOLORGRADING = true;
  61926. }
  61927. }
  61928. }
  61929. // Effect
  61930. if (scene.clipPlane) {
  61931. this._defines.CLIPPLANE = true;
  61932. }
  61933. if (engine.getAlphaTesting()) {
  61934. this._defines.ALPHATEST = true;
  61935. }
  61936. if (this._shouldUseAlphaFromAlbedoTexture()) {
  61937. this._defines.ALPHAFROMALBEDO = true;
  61938. }
  61939. if (this.useEmissiveAsIllumination) {
  61940. this._defines.EMISSIVEASILLUMINATION = true;
  61941. }
  61942. if (this.linkEmissiveWithAlbedo) {
  61943. this._defines.LINKEMISSIVEWITHALBEDO = true;
  61944. }
  61945. if (this.useLogarithmicDepth) {
  61946. this._defines.LOGARITHMICDEPTH = true;
  61947. }
  61948. if (this.cameraContrast != 1) {
  61949. this._defines.CAMERACONTRAST = true;
  61950. }
  61951. if (this.cameraExposure != 1) {
  61952. this._defines.CAMERATONEMAP = true;
  61953. }
  61954. if (this.cameraColorCurves) {
  61955. this._defines.CAMERACOLORCURVES = true;
  61956. }
  61957. if (this.overloadedShadeIntensity != 1 ||
  61958. this.overloadedShadowIntensity != 1) {
  61959. this._defines.OVERLOADEDSHADOWVALUES = true;
  61960. }
  61961. if (this.overloadedMicroSurfaceIntensity > 0 ||
  61962. this.overloadedEmissiveIntensity > 0 ||
  61963. this.overloadedReflectivityIntensity > 0 ||
  61964. this.overloadedAlbedoIntensity > 0 ||
  61965. this.overloadedAmbientIntensity > 0 ||
  61966. this.overloadedReflectionIntensity > 0) {
  61967. this._defines.OVERLOADEDVALUES = true;
  61968. }
  61969. // Point size
  61970. if (this.pointsCloud || scene.forcePointsCloud) {
  61971. this._defines.POINTSIZE = true;
  61972. }
  61973. // Fog
  61974. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  61975. this._defines.FOG = true;
  61976. }
  61977. if (scene.lightsEnabled && !this.disableLighting) {
  61978. needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, this._defines, this.maxSimultaneousLights) || needNormals;
  61979. }
  61980. if (BABYLON.StandardMaterial.FresnelEnabled) {
  61981. // Fresnel
  61982. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  61983. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  61984. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  61985. this._defines.OPACITYFRESNEL = true;
  61986. }
  61987. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  61988. this._defines.EMISSIVEFRESNEL = true;
  61989. }
  61990. needNormals = true;
  61991. this._defines.FRESNEL = true;
  61992. }
  61993. }
  61994. if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
  61995. this._defines.SPECULAROVERALPHA = true;
  61996. }
  61997. if (this.usePhysicalLightFalloff) {
  61998. this._defines.USEPHYSICALLIGHTFALLOFF = true;
  61999. }
  62000. if (this.useRadianceOverAlpha) {
  62001. this._defines.RADIANCEOVERALPHA = true;
  62002. }
  62003. // Attribs
  62004. if (mesh) {
  62005. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  62006. this._defines.NORMAL = true;
  62007. }
  62008. if (needUVs) {
  62009. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  62010. this._defines.UV1 = true;
  62011. }
  62012. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  62013. this._defines.UV2 = true;
  62014. }
  62015. }
  62016. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  62017. this._defines.VERTEXCOLOR = true;
  62018. if (mesh.hasVertexAlpha) {
  62019. this._defines.VERTEXALPHA = true;
  62020. }
  62021. }
  62022. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  62023. this._defines.NUM_BONE_INFLUENCERS = mesh.numBoneInfluencers;
  62024. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  62025. }
  62026. // Instances
  62027. if (useInstances) {
  62028. this._defines.INSTANCES = true;
  62029. }
  62030. }
  62031. // Get correct effect
  62032. if (!this._defines.isEqual(this._cachedDefines)) {
  62033. this._defines.cloneTo(this._cachedDefines);
  62034. scene.resetCachedMaterial();
  62035. // Fallbacks
  62036. var fallbacks = new BABYLON.EffectFallbacks();
  62037. if (this._defines.REFLECTION) {
  62038. fallbacks.addFallback(0, "REFLECTION");
  62039. }
  62040. if (this._defines.REFRACTION) {
  62041. fallbacks.addFallback(0, "REFRACTION");
  62042. }
  62043. if (this._defines.REFLECTIVITY) {
  62044. fallbacks.addFallback(0, "REFLECTIVITY");
  62045. }
  62046. if (this._defines.BUMP) {
  62047. fallbacks.addFallback(0, "BUMP");
  62048. }
  62049. if (this._defines.PARALLAX) {
  62050. fallbacks.addFallback(1, "PARALLAX");
  62051. }
  62052. if (this._defines.PARALLAXOCCLUSION) {
  62053. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  62054. }
  62055. if (this._defines.SPECULAROVERALPHA) {
  62056. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  62057. }
  62058. if (this._defines.FOG) {
  62059. fallbacks.addFallback(1, "FOG");
  62060. }
  62061. if (this._defines.POINTSIZE) {
  62062. fallbacks.addFallback(0, "POINTSIZE");
  62063. }
  62064. if (this._defines.LOGARITHMICDEPTH) {
  62065. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  62066. }
  62067. BABYLON.MaterialHelper.HandleFallbacksForShadows(this._defines, fallbacks, this.maxSimultaneousLights);
  62068. if (this._defines.SPECULARTERM) {
  62069. fallbacks.addFallback(0, "SPECULARTERM");
  62070. }
  62071. if (this._defines.OPACITYFRESNEL) {
  62072. fallbacks.addFallback(1, "OPACITYFRESNEL");
  62073. }
  62074. if (this._defines.EMISSIVEFRESNEL) {
  62075. fallbacks.addFallback(2, "EMISSIVEFRESNEL");
  62076. }
  62077. if (this._defines.FRESNEL) {
  62078. fallbacks.addFallback(3, "FRESNEL");
  62079. }
  62080. if (this._defines.NUM_BONE_INFLUENCERS > 0) {
  62081. fallbacks.addCPUSkinningFallback(0, mesh);
  62082. }
  62083. //Attributes
  62084. var attribs = [BABYLON.VertexBuffer.PositionKind];
  62085. if (this._defines.NORMAL) {
  62086. attribs.push(BABYLON.VertexBuffer.NormalKind);
  62087. }
  62088. if (this._defines.UV1) {
  62089. attribs.push(BABYLON.VertexBuffer.UVKind);
  62090. }
  62091. if (this._defines.UV2) {
  62092. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  62093. }
  62094. if (this._defines.VERTEXCOLOR) {
  62095. attribs.push(BABYLON.VertexBuffer.ColorKind);
  62096. }
  62097. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, this._defines, fallbacks);
  62098. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, this._defines);
  62099. // Legacy browser patch
  62100. var shaderName = "pbr";
  62101. if (!scene.getEngine().getCaps().standardDerivatives) {
  62102. shaderName = "legacypbr";
  62103. }
  62104. var join = this._defines.toString();
  62105. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  62106. "vFogInfos", "vFogColor", "pointSize",
  62107. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vReflectivityInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  62108. "mBones",
  62109. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  62110. "depthValues",
  62111. "opacityParts", "emissiveLeftColor", "emissiveRightColor",
  62112. "vLightingIntensity", "vOverloadedShadowIntensity", "vOverloadedIntensity", "vOverloadedAlbedo", "vOverloadedReflection", "vOverloadedReflectivity", "vOverloadedEmissive", "vOverloadedMicroSurface",
  62113. "logarithmicDepthConstant",
  62114. "vSphericalX", "vSphericalY", "vSphericalZ",
  62115. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  62116. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  62117. "vMicrosurfaceTextureLods",
  62118. "vCameraInfos"
  62119. ];
  62120. var samplers = ["albedoSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "reflectivitySampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  62121. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  62122. BABYLON.ColorGradingTexture.PrepareUniformsAndSamplers(uniforms, samplers);
  62123. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList(uniforms, samplers, this._defines, this.maxSimultaneousLights);
  62124. this._effect = scene.getEngine().createEffect(shaderName, attribs, uniforms, samplers, join, fallbacks, this.onCompiled, this.onError, { maxSimultaneousLights: this.maxSimultaneousLights });
  62125. }
  62126. if (!this._effect.isReady()) {
  62127. return false;
  62128. }
  62129. this._renderId = scene.getRenderId();
  62130. this._wasPreviouslyReady = true;
  62131. if (mesh) {
  62132. if (!mesh._materialDefines) {
  62133. mesh._materialDefines = new PBRMaterialDefines();
  62134. }
  62135. this._defines.cloneTo(mesh._materialDefines);
  62136. }
  62137. return true;
  62138. };
  62139. PBRMaterial.prototype.unbind = function () {
  62140. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  62141. this._effect.setTexture("reflection2DSampler", null);
  62142. }
  62143. if (this.refractionTexture && this.refractionTexture.isRenderTarget) {
  62144. this._effect.setTexture("refraction2DSampler", null);
  62145. }
  62146. _super.prototype.unbind.call(this);
  62147. };
  62148. PBRMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  62149. this._effect.setMatrix("world", world);
  62150. };
  62151. PBRMaterial.prototype.bind = function (world, mesh) {
  62152. this._myScene = this.getScene();
  62153. // Matrices
  62154. this.bindOnlyWorldMatrix(world);
  62155. // Bones
  62156. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  62157. if (this._myScene.getCachedMaterial() !== this) {
  62158. this._effect.setMatrix("viewProjection", this._myScene.getTransformMatrix());
  62159. if (BABYLON.StandardMaterial.FresnelEnabled) {
  62160. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  62161. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  62162. }
  62163. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  62164. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  62165. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  62166. }
  62167. }
  62168. // Textures
  62169. if (this._myScene.texturesEnabled) {
  62170. if (this.albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  62171. this._effect.setTexture("albedoSampler", this.albedoTexture);
  62172. this._effect.setFloat2("vAlbedoInfos", this.albedoTexture.coordinatesIndex, this.albedoTexture.level);
  62173. this._effect.setMatrix("albedoMatrix", this.albedoTexture.getTextureMatrix());
  62174. }
  62175. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  62176. this._effect.setTexture("ambientSampler", this.ambientTexture);
  62177. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  62178. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  62179. }
  62180. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  62181. this._effect.setTexture("opacitySampler", this.opacityTexture);
  62182. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  62183. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  62184. }
  62185. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  62186. this._microsurfaceTextureLods.x = Math.round(Math.log(this.reflectionTexture.getSize().width) * Math.LOG2E);
  62187. if (this.reflectionTexture.isCube) {
  62188. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  62189. }
  62190. else {
  62191. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  62192. }
  62193. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  62194. this._effect.setFloat2("vReflectionInfos", this.reflectionTexture.level, 0);
  62195. if (this._defines.USESPHERICALFROMREFLECTIONMAP) {
  62196. this._effect.setFloat3("vSphericalX", this.reflectionTexture.sphericalPolynomial.x.x, this.reflectionTexture.sphericalPolynomial.x.y, this.reflectionTexture.sphericalPolynomial.x.z);
  62197. this._effect.setFloat3("vSphericalY", this.reflectionTexture.sphericalPolynomial.y.x, this.reflectionTexture.sphericalPolynomial.y.y, this.reflectionTexture.sphericalPolynomial.y.z);
  62198. this._effect.setFloat3("vSphericalZ", this.reflectionTexture.sphericalPolynomial.z.x, this.reflectionTexture.sphericalPolynomial.z.y, this.reflectionTexture.sphericalPolynomial.z.z);
  62199. this._effect.setFloat3("vSphericalXX", this.reflectionTexture.sphericalPolynomial.xx.x, this.reflectionTexture.sphericalPolynomial.xx.y, this.reflectionTexture.sphericalPolynomial.xx.z);
  62200. this._effect.setFloat3("vSphericalYY", this.reflectionTexture.sphericalPolynomial.yy.x, this.reflectionTexture.sphericalPolynomial.yy.y, this.reflectionTexture.sphericalPolynomial.yy.z);
  62201. this._effect.setFloat3("vSphericalZZ", this.reflectionTexture.sphericalPolynomial.zz.x, this.reflectionTexture.sphericalPolynomial.zz.y, this.reflectionTexture.sphericalPolynomial.zz.z);
  62202. this._effect.setFloat3("vSphericalXY", this.reflectionTexture.sphericalPolynomial.xy.x, this.reflectionTexture.sphericalPolynomial.xy.y, this.reflectionTexture.sphericalPolynomial.xy.z);
  62203. this._effect.setFloat3("vSphericalYZ", this.reflectionTexture.sphericalPolynomial.yz.x, this.reflectionTexture.sphericalPolynomial.yz.y, this.reflectionTexture.sphericalPolynomial.yz.z);
  62204. this._effect.setFloat3("vSphericalZX", this.reflectionTexture.sphericalPolynomial.zx.x, this.reflectionTexture.sphericalPolynomial.zx.y, this.reflectionTexture.sphericalPolynomial.zx.z);
  62205. }
  62206. }
  62207. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  62208. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  62209. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  62210. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  62211. }
  62212. if (this.lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  62213. this._effect.setTexture("lightmapSampler", this.lightmapTexture);
  62214. this._effect.setFloat2("vLightmapInfos", this.lightmapTexture.coordinatesIndex, this.lightmapTexture.level);
  62215. this._effect.setMatrix("lightmapMatrix", this.lightmapTexture.getTextureMatrix());
  62216. }
  62217. if (this.reflectivityTexture && BABYLON.StandardMaterial.SpecularTextureEnabled) {
  62218. this._effect.setTexture("reflectivitySampler", this.reflectivityTexture);
  62219. this._effect.setFloat2("vReflectivityInfos", this.reflectivityTexture.coordinatesIndex, this.reflectivityTexture.level);
  62220. this._effect.setMatrix("reflectivityMatrix", this.reflectivityTexture.getTextureMatrix());
  62221. }
  62222. if (this.bumpTexture && this._myScene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this.disableBumpMap) {
  62223. this._effect.setTexture("bumpSampler", this.bumpTexture);
  62224. this._effect.setFloat3("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level, this.parallaxScaleBias);
  62225. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  62226. }
  62227. if (this.refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  62228. this._microsurfaceTextureLods.y = Math.round(Math.log(this.refractionTexture.getSize().width) * Math.LOG2E);
  62229. var depth = 1.0;
  62230. if (this.refractionTexture.isCube) {
  62231. this._effect.setTexture("refractionCubeSampler", this.refractionTexture);
  62232. }
  62233. else {
  62234. this._effect.setTexture("refraction2DSampler", this.refractionTexture);
  62235. this._effect.setMatrix("refractionMatrix", this.refractionTexture.getReflectionTextureMatrix());
  62236. if (this.refractionTexture.depth) {
  62237. depth = this.refractionTexture.depth;
  62238. }
  62239. }
  62240. this._effect.setFloat4("vRefractionInfos", this.refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  62241. }
  62242. if ((this.reflectionTexture || this.refractionTexture)) {
  62243. this._effect.setFloat2("vMicrosurfaceTextureLods", this._microsurfaceTextureLods.x, this._microsurfaceTextureLods.y);
  62244. }
  62245. if (this.cameraColorGradingTexture && BABYLON.StandardMaterial.ColorGradingTextureEnabled) {
  62246. BABYLON.ColorGradingTexture.Bind(this.cameraColorGradingTexture, this._effect);
  62247. }
  62248. }
  62249. // Clip plane
  62250. BABYLON.MaterialHelper.BindClipPlane(this._effect, this._myScene);
  62251. // Point size
  62252. if (this.pointsCloud) {
  62253. this._effect.setFloat("pointSize", this.pointSize);
  62254. }
  62255. // Colors
  62256. this._myScene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  62257. // GAMMA CORRECTION.
  62258. this.convertColorToLinearSpaceToRef(this.reflectivityColor, PBRMaterial._scaledReflectivity);
  62259. this._effect.setVector3("vEyePosition", this._myScene._mirroredCameraPosition ? this._myScene._mirroredCameraPosition : this._myScene.activeCamera.position);
  62260. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  62261. this._effect.setColor4("vReflectivityColor", PBRMaterial._scaledReflectivity, this.microSurface);
  62262. // GAMMA CORRECTION.
  62263. this.convertColorToLinearSpaceToRef(this.emissiveColor, PBRMaterial._scaledEmissive);
  62264. this._effect.setColor3("vEmissiveColor", PBRMaterial._scaledEmissive);
  62265. // GAMMA CORRECTION.
  62266. this.convertColorToLinearSpaceToRef(this.reflectionColor, PBRMaterial._scaledReflection);
  62267. this._effect.setColor3("vReflectionColor", PBRMaterial._scaledReflection);
  62268. }
  62269. if (this._myScene.getCachedMaterial() !== this || !this.isFrozen) {
  62270. // GAMMA CORRECTION.
  62271. this.convertColorToLinearSpaceToRef(this.albedoColor, PBRMaterial._scaledAlbedo);
  62272. this._effect.setColor4("vAlbedoColor", PBRMaterial._scaledAlbedo, this.alpha * mesh.visibility);
  62273. // Lights
  62274. if (this._myScene.lightsEnabled && !this.disableLighting) {
  62275. PBRMaterial.BindLights(this._myScene, mesh, this._effect, this._defines, this.useScalarInLinearSpace, this.maxSimultaneousLights, this.usePhysicalLightFalloff);
  62276. }
  62277. // View
  62278. if (this._myScene.fogEnabled && mesh.applyFog && this._myScene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  62279. this._effect.setMatrix("view", this._myScene.getViewMatrix());
  62280. }
  62281. // Fog
  62282. BABYLON.MaterialHelper.BindFogParameters(this._myScene, mesh, this._effect);
  62283. this._lightingInfos.x = this.directIntensity;
  62284. this._lightingInfos.y = this.emissiveIntensity;
  62285. this._lightingInfos.z = this.environmentIntensity;
  62286. this._lightingInfos.w = this.specularIntensity;
  62287. this._effect.setVector4("vLightingIntensity", this._lightingInfos);
  62288. this._overloadedShadowInfos.x = this.overloadedShadowIntensity;
  62289. this._overloadedShadowInfos.y = this.overloadedShadeIntensity;
  62290. this._effect.setVector4("vOverloadedShadowIntensity", this._overloadedShadowInfos);
  62291. this._cameraInfos.x = this.cameraExposure;
  62292. this._cameraInfos.y = this.cameraContrast;
  62293. this._effect.setVector4("vCameraInfos", this._cameraInfos);
  62294. if (this.cameraColorCurves) {
  62295. BABYLON.ColorCurves.Bind(this.cameraColorCurves, this._effect);
  62296. }
  62297. this._overloadedIntensity.x = this.overloadedAmbientIntensity;
  62298. this._overloadedIntensity.y = this.overloadedAlbedoIntensity;
  62299. this._overloadedIntensity.z = this.overloadedReflectivityIntensity;
  62300. this._overloadedIntensity.w = this.overloadedEmissiveIntensity;
  62301. this._effect.setVector4("vOverloadedIntensity", this._overloadedIntensity);
  62302. this.convertColorToLinearSpaceToRef(this.overloadedAmbient, this._tempColor);
  62303. this._effect.setColor3("vOverloadedAmbient", this._tempColor);
  62304. this.convertColorToLinearSpaceToRef(this.overloadedAlbedo, this._tempColor);
  62305. this._effect.setColor3("vOverloadedAlbedo", this._tempColor);
  62306. this.convertColorToLinearSpaceToRef(this.overloadedReflectivity, this._tempColor);
  62307. this._effect.setColor3("vOverloadedReflectivity", this._tempColor);
  62308. this.convertColorToLinearSpaceToRef(this.overloadedEmissive, this._tempColor);
  62309. this._effect.setColor3("vOverloadedEmissive", this._tempColor);
  62310. this.convertColorToLinearSpaceToRef(this.overloadedReflection, this._tempColor);
  62311. this._effect.setColor3("vOverloadedReflection", this._tempColor);
  62312. this._overloadedMicroSurface.x = this.overloadedMicroSurface;
  62313. this._overloadedMicroSurface.y = this.overloadedMicroSurfaceIntensity;
  62314. this._overloadedMicroSurface.z = this.overloadedReflectionIntensity;
  62315. this._effect.setVector3("vOverloadedMicroSurface", this._overloadedMicroSurface);
  62316. // Log. depth
  62317. BABYLON.MaterialHelper.BindLogDepth(this._defines, this._effect, this._myScene);
  62318. }
  62319. _super.prototype.bind.call(this, world, mesh);
  62320. this._myScene = null;
  62321. };
  62322. PBRMaterial.prototype.getAnimatables = function () {
  62323. var results = [];
  62324. if (this.albedoTexture && this.albedoTexture.animations && this.albedoTexture.animations.length > 0) {
  62325. results.push(this.albedoTexture);
  62326. }
  62327. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  62328. results.push(this.ambientTexture);
  62329. }
  62330. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  62331. results.push(this.opacityTexture);
  62332. }
  62333. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  62334. results.push(this.reflectionTexture);
  62335. }
  62336. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  62337. results.push(this.emissiveTexture);
  62338. }
  62339. if (this.reflectivityTexture && this.reflectivityTexture.animations && this.reflectivityTexture.animations.length > 0) {
  62340. results.push(this.reflectivityTexture);
  62341. }
  62342. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  62343. results.push(this.bumpTexture);
  62344. }
  62345. if (this.lightmapTexture && this.lightmapTexture.animations && this.lightmapTexture.animations.length > 0) {
  62346. results.push(this.lightmapTexture);
  62347. }
  62348. if (this.refractionTexture && this.refractionTexture.animations && this.refractionTexture.animations.length > 0) {
  62349. results.push(this.refractionTexture);
  62350. }
  62351. if (this.cameraColorGradingTexture && this.cameraColorGradingTexture.animations && this.cameraColorGradingTexture.animations.length > 0) {
  62352. results.push(this.cameraColorGradingTexture);
  62353. }
  62354. return results;
  62355. };
  62356. PBRMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  62357. if (forceDisposeTextures) {
  62358. if (this.albedoTexture) {
  62359. this.albedoTexture.dispose();
  62360. }
  62361. if (this.ambientTexture) {
  62362. this.ambientTexture.dispose();
  62363. }
  62364. if (this.opacityTexture) {
  62365. this.opacityTexture.dispose();
  62366. }
  62367. if (this.reflectionTexture) {
  62368. this.reflectionTexture.dispose();
  62369. }
  62370. if (this.emissiveTexture) {
  62371. this.emissiveTexture.dispose();
  62372. }
  62373. if (this.reflectivityTexture) {
  62374. this.reflectivityTexture.dispose();
  62375. }
  62376. if (this.bumpTexture) {
  62377. this.bumpTexture.dispose();
  62378. }
  62379. if (this.lightmapTexture) {
  62380. this.lightmapTexture.dispose();
  62381. }
  62382. if (this.refractionTexture) {
  62383. this.refractionTexture.dispose();
  62384. }
  62385. if (this.cameraColorGradingTexture) {
  62386. this.cameraColorGradingTexture.dispose();
  62387. }
  62388. }
  62389. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  62390. };
  62391. PBRMaterial.prototype.clone = function (name) {
  62392. var _this = this;
  62393. return BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  62394. };
  62395. PBRMaterial.prototype.serialize = function () {
  62396. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  62397. serializationObject.customType = "BABYLON.PBRMaterial";
  62398. return serializationObject;
  62399. };
  62400. // Statics
  62401. PBRMaterial.Parse = function (source, scene, rootUrl) {
  62402. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  62403. };
  62404. PBRMaterial._scaledAlbedo = new BABYLON.Color3();
  62405. PBRMaterial._scaledReflectivity = new BABYLON.Color3();
  62406. PBRMaterial._scaledEmissive = new BABYLON.Color3();
  62407. PBRMaterial._scaledReflection = new BABYLON.Color3();
  62408. __decorate([
  62409. BABYLON.serialize()
  62410. ], PBRMaterial.prototype, "directIntensity", void 0);
  62411. __decorate([
  62412. BABYLON.serialize()
  62413. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  62414. __decorate([
  62415. BABYLON.serialize()
  62416. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  62417. __decorate([
  62418. BABYLON.serialize()
  62419. ], PBRMaterial.prototype, "specularIntensity", void 0);
  62420. __decorate([
  62421. BABYLON.serialize()
  62422. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  62423. __decorate([
  62424. BABYLON.serialize()
  62425. ], PBRMaterial.prototype, "overloadedShadowIntensity", void 0);
  62426. __decorate([
  62427. BABYLON.serialize()
  62428. ], PBRMaterial.prototype, "overloadedShadeIntensity", void 0);
  62429. __decorate([
  62430. BABYLON.serialize()
  62431. ], PBRMaterial.prototype, "cameraExposure", void 0);
  62432. __decorate([
  62433. BABYLON.serialize()
  62434. ], PBRMaterial.prototype, "cameraContrast", void 0);
  62435. __decorate([
  62436. BABYLON.serializeAsTexture()
  62437. ], PBRMaterial.prototype, "cameraColorGradingTexture", void 0);
  62438. __decorate([
  62439. BABYLON.serializeAsColorCurves()
  62440. ], PBRMaterial.prototype, "cameraColorCurves", void 0);
  62441. __decorate([
  62442. BABYLON.serializeAsColor3()
  62443. ], PBRMaterial.prototype, "overloadedAmbient", void 0);
  62444. __decorate([
  62445. BABYLON.serialize()
  62446. ], PBRMaterial.prototype, "overloadedAmbientIntensity", void 0);
  62447. __decorate([
  62448. BABYLON.serializeAsColor3()
  62449. ], PBRMaterial.prototype, "overloadedAlbedo", void 0);
  62450. __decorate([
  62451. BABYLON.serialize()
  62452. ], PBRMaterial.prototype, "overloadedAlbedoIntensity", void 0);
  62453. __decorate([
  62454. BABYLON.serializeAsColor3()
  62455. ], PBRMaterial.prototype, "overloadedReflectivity", void 0);
  62456. __decorate([
  62457. BABYLON.serialize()
  62458. ], PBRMaterial.prototype, "overloadedReflectivityIntensity", void 0);
  62459. __decorate([
  62460. BABYLON.serializeAsColor3()
  62461. ], PBRMaterial.prototype, "overloadedEmissive", void 0);
  62462. __decorate([
  62463. BABYLON.serialize()
  62464. ], PBRMaterial.prototype, "overloadedEmissiveIntensity", void 0);
  62465. __decorate([
  62466. BABYLON.serializeAsColor3()
  62467. ], PBRMaterial.prototype, "overloadedReflection", void 0);
  62468. __decorate([
  62469. BABYLON.serialize()
  62470. ], PBRMaterial.prototype, "overloadedReflectionIntensity", void 0);
  62471. __decorate([
  62472. BABYLON.serialize()
  62473. ], PBRMaterial.prototype, "overloadedMicroSurface", void 0);
  62474. __decorate([
  62475. BABYLON.serialize()
  62476. ], PBRMaterial.prototype, "overloadedMicroSurfaceIntensity", void 0);
  62477. __decorate([
  62478. BABYLON.serializeAsTexture()
  62479. ], PBRMaterial.prototype, "albedoTexture", void 0);
  62480. __decorate([
  62481. BABYLON.serializeAsTexture()
  62482. ], PBRMaterial.prototype, "ambientTexture", void 0);
  62483. __decorate([
  62484. BABYLON.serializeAsTexture()
  62485. ], PBRMaterial.prototype, "opacityTexture", void 0);
  62486. __decorate([
  62487. BABYLON.serializeAsTexture()
  62488. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  62489. __decorate([
  62490. BABYLON.serializeAsTexture()
  62491. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  62492. __decorate([
  62493. BABYLON.serializeAsTexture()
  62494. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  62495. __decorate([
  62496. BABYLON.serializeAsTexture()
  62497. ], PBRMaterial.prototype, "bumpTexture", void 0);
  62498. __decorate([
  62499. BABYLON.serializeAsTexture()
  62500. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  62501. __decorate([
  62502. BABYLON.serializeAsTexture()
  62503. ], PBRMaterial.prototype, "refractionTexture", void 0);
  62504. __decorate([
  62505. BABYLON.serializeAsColor3("ambient")
  62506. ], PBRMaterial.prototype, "ambientColor", void 0);
  62507. __decorate([
  62508. BABYLON.serializeAsColor3("albedo")
  62509. ], PBRMaterial.prototype, "albedoColor", void 0);
  62510. __decorate([
  62511. BABYLON.serializeAsColor3("reflectivity")
  62512. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  62513. __decorate([
  62514. BABYLON.serializeAsColor3("reflection")
  62515. ], PBRMaterial.prototype, "reflectionColor", void 0);
  62516. __decorate([
  62517. BABYLON.serializeAsColor3("emissive")
  62518. ], PBRMaterial.prototype, "emissiveColor", void 0);
  62519. __decorate([
  62520. BABYLON.serialize()
  62521. ], PBRMaterial.prototype, "microSurface", void 0);
  62522. __decorate([
  62523. BABYLON.serialize()
  62524. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  62525. __decorate([
  62526. BABYLON.serialize()
  62527. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  62528. __decorate([
  62529. BABYLON.serializeAsFresnelParameters()
  62530. ], PBRMaterial.prototype, "opacityFresnelParameters", void 0);
  62531. __decorate([
  62532. BABYLON.serializeAsFresnelParameters()
  62533. ], PBRMaterial.prototype, "emissiveFresnelParameters", void 0);
  62534. __decorate([
  62535. BABYLON.serialize()
  62536. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  62537. __decorate([
  62538. BABYLON.serialize()
  62539. ], PBRMaterial.prototype, "linkEmissiveWithAlbedo", void 0);
  62540. __decorate([
  62541. BABYLON.serialize()
  62542. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  62543. __decorate([
  62544. BABYLON.serialize()
  62545. ], PBRMaterial.prototype, "useEmissiveAsIllumination", void 0);
  62546. __decorate([
  62547. BABYLON.serialize()
  62548. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  62549. __decorate([
  62550. BABYLON.serialize()
  62551. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  62552. __decorate([
  62553. BABYLON.serialize()
  62554. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  62555. __decorate([
  62556. BABYLON.serialize()
  62557. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  62558. __decorate([
  62559. BABYLON.serialize()
  62560. ], PBRMaterial.prototype, "useScalarInLinearSpace", void 0);
  62561. __decorate([
  62562. BABYLON.serialize()
  62563. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  62564. __decorate([
  62565. BABYLON.serialize()
  62566. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  62567. __decorate([
  62568. BABYLON.serialize()
  62569. ], PBRMaterial.prototype, "useParallax", void 0);
  62570. __decorate([
  62571. BABYLON.serialize()
  62572. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  62573. __decorate([
  62574. BABYLON.serialize()
  62575. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  62576. __decorate([
  62577. BABYLON.serialize()
  62578. ], PBRMaterial.prototype, "disableLighting", void 0);
  62579. __decorate([
  62580. BABYLON.serialize()
  62581. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  62582. __decorate([
  62583. BABYLON.serialize()
  62584. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  62585. __decorate([
  62586. BABYLON.serialize()
  62587. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  62588. __decorate([
  62589. BABYLON.serialize()
  62590. ], PBRMaterial.prototype, "useLogarithmicDepth", null);
  62591. return PBRMaterial;
  62592. }(BABYLON.Material));
  62593. BABYLON.PBRMaterial = PBRMaterial;
  62594. })(BABYLON || (BABYLON = {}));
  62595. var BABYLON;
  62596. (function (BABYLON) {
  62597. var DebugLayer = (function () {
  62598. function DebugLayer(scene) {
  62599. var _this = this;
  62600. this._transformationMatrix = BABYLON.Matrix.Identity();
  62601. this._enabled = false;
  62602. this._labelsEnabled = false;
  62603. this._displayStatistics = true;
  62604. this._displayTree = false;
  62605. this._displayLogs = false;
  62606. this._skeletonViewers = new Array();
  62607. this._identityMatrix = BABYLON.Matrix.Identity();
  62608. this.axisRatio = 0.02;
  62609. this.accentColor = "orange";
  62610. this._scene = scene;
  62611. this._syncPositions = function () {
  62612. var engine = _this._scene.getEngine();
  62613. var canvasRect = engine.getRenderingCanvasClientRect();
  62614. if (_this._showUI) {
  62615. _this._statsDiv.style.left = (canvasRect.width - 410) + "px";
  62616. _this._statsDiv.style.top = (canvasRect.height - 290) + "px";
  62617. _this._statsDiv.style.width = "400px";
  62618. _this._statsDiv.style.height = "auto";
  62619. _this._statsSubsetDiv.style.maxHeight = "240px";
  62620. _this._optionsDiv.style.left = "0px";
  62621. _this._optionsDiv.style.top = "10px";
  62622. _this._optionsDiv.style.width = "200px";
  62623. _this._optionsDiv.style.height = "auto";
  62624. _this._optionsSubsetDiv.style.maxHeight = (canvasRect.height - 225) + "px";
  62625. _this._logDiv.style.left = "0px";
  62626. _this._logDiv.style.top = (canvasRect.height - 170) + "px";
  62627. _this._logDiv.style.width = "600px";
  62628. _this._logDiv.style.height = "160px";
  62629. _this._treeDiv.style.left = (canvasRect.width - 310) + "px";
  62630. _this._treeDiv.style.top = "10px";
  62631. _this._treeDiv.style.width = "300px";
  62632. _this._treeDiv.style.height = "auto";
  62633. _this._treeSubsetDiv.style.maxHeight = (canvasRect.height - 340) + "px";
  62634. }
  62635. _this._globalDiv.style.left = canvasRect.left + "px";
  62636. _this._globalDiv.style.top = canvasRect.top + "px";
  62637. _this._drawingCanvas.style.left = "0px";
  62638. _this._drawingCanvas.style.top = "0px";
  62639. _this._drawingCanvas.style.width = engine.getRenderWidth() + "px";
  62640. _this._drawingCanvas.style.height = engine.getRenderHeight() + "px";
  62641. var devicePixelRatio = window.devicePixelRatio || 1;
  62642. var context = _this._drawingContext;
  62643. var backingStoreRatio = context.webkitBackingStorePixelRatio ||
  62644. context.mozBackingStorePixelRatio ||
  62645. context.msBackingStorePixelRatio ||
  62646. context.oBackingStorePixelRatio ||
  62647. context.backingStorePixelRatio || 1;
  62648. _this._ratio = devicePixelRatio / backingStoreRatio;
  62649. _this._drawingCanvas.width = engine.getRenderWidth() * _this._ratio;
  62650. _this._drawingCanvas.height = engine.getRenderHeight() * _this._ratio;
  62651. };
  62652. this._onCanvasClick = function (evt) {
  62653. _this._clickPosition = {
  62654. x: evt.clientX * _this._ratio,
  62655. y: evt.clientY * _this._ratio
  62656. };
  62657. };
  62658. this._syncUI = function () {
  62659. if (_this._showUI) {
  62660. if (_this._displayStatistics) {
  62661. _this._displayStats();
  62662. _this._statsDiv.style.display = "";
  62663. }
  62664. else {
  62665. _this._statsDiv.style.display = "none";
  62666. }
  62667. if (_this._displayLogs) {
  62668. _this._logDiv.style.display = "";
  62669. }
  62670. else {
  62671. _this._logDiv.style.display = "none";
  62672. }
  62673. if (_this._displayTree) {
  62674. _this._treeDiv.style.display = "";
  62675. if (_this._needToRefreshMeshesTree) {
  62676. _this._needToRefreshMeshesTree = false;
  62677. _this._refreshMeshesTreeContent();
  62678. }
  62679. }
  62680. else {
  62681. _this._treeDiv.style.display = "none";
  62682. }
  62683. }
  62684. };
  62685. this._syncData = function () {
  62686. if (_this._labelsEnabled || !_this._showUI) {
  62687. _this._camera.getViewMatrix().multiplyToRef(_this._camera.getProjectionMatrix(), _this._transformationMatrix);
  62688. _this._drawingContext.clearRect(0, 0, _this._drawingCanvas.width, _this._drawingCanvas.height);
  62689. var engine = _this._scene.getEngine();
  62690. var viewport = _this._camera.viewport;
  62691. var globalViewport = viewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  62692. // Meshes
  62693. var meshes = _this._camera.getActiveMeshes();
  62694. var index;
  62695. var projectedPosition;
  62696. for (index = 0; index < meshes.length; index++) {
  62697. var mesh = meshes.data[index];
  62698. var position = mesh.getBoundingInfo().boundingSphere.center;
  62699. projectedPosition = BABYLON.Vector3.Project(position, mesh.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  62700. if (mesh.renderOverlay || _this.shouldDisplayAxis && _this.shouldDisplayAxis(mesh)) {
  62701. _this._renderAxis(projectedPosition, mesh, globalViewport);
  62702. }
  62703. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(mesh)) {
  62704. _this._renderLabel(mesh.name, projectedPosition, 12, function () { mesh.renderOverlay = !mesh.renderOverlay; }, function () { return mesh.renderOverlay ? 'red' : 'black'; });
  62705. }
  62706. }
  62707. // Cameras
  62708. var cameras = _this._scene.cameras;
  62709. for (index = 0; index < cameras.length; index++) {
  62710. var camera = cameras[index];
  62711. if (camera === _this._camera) {
  62712. continue;
  62713. }
  62714. projectedPosition = BABYLON.Vector3.Project(BABYLON.Vector3.Zero(), camera.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  62715. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(camera)) {
  62716. _this._renderLabel(camera.name, projectedPosition, 12, function () {
  62717. _this._camera.detachControl(engine.getRenderingCanvas());
  62718. _this._camera = camera;
  62719. _this._camera.attachControl(engine.getRenderingCanvas());
  62720. }, function () { return "purple"; });
  62721. }
  62722. }
  62723. // Lights
  62724. var lights = _this._scene.lights;
  62725. for (index = 0; index < lights.length; index++) {
  62726. var light = lights[index];
  62727. if (light.position) {
  62728. projectedPosition = BABYLON.Vector3.Project(light.getAbsolutePosition(), _this._identityMatrix, _this._transformationMatrix, globalViewport);
  62729. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(light)) {
  62730. _this._renderLabel(light.name, projectedPosition, -20, function () {
  62731. light.setEnabled(!light.isEnabled());
  62732. }, function () { return light.isEnabled() ? "orange" : "gray"; });
  62733. }
  62734. }
  62735. }
  62736. }
  62737. _this._clickPosition = undefined;
  62738. };
  62739. }
  62740. DebugLayer.prototype._refreshMeshesTreeContent = function () {
  62741. while (this._treeSubsetDiv.hasChildNodes()) {
  62742. this._treeSubsetDiv.removeChild(this._treeSubsetDiv.lastChild);
  62743. }
  62744. // Add meshes
  62745. var sortedArray = this._scene.meshes.slice(0, this._scene.meshes.length);
  62746. sortedArray.sort(function (a, b) {
  62747. if (a.name === b.name) {
  62748. return 0;
  62749. }
  62750. return (a.name > b.name) ? 1 : -1;
  62751. });
  62752. for (var index = 0; index < sortedArray.length; index++) {
  62753. var mesh = sortedArray[index];
  62754. if (!mesh.isEnabled()) {
  62755. continue;
  62756. }
  62757. this._generateAdvancedCheckBox(this._treeSubsetDiv, mesh.name, mesh.getTotalVertices() + " verts", mesh.isVisible, function (element, m) {
  62758. m.isVisible = element.checked;
  62759. }, mesh);
  62760. }
  62761. };
  62762. DebugLayer.prototype._renderSingleAxis = function (zero, unit, unitText, label, color) {
  62763. this._drawingContext.beginPath();
  62764. this._drawingContext.moveTo(zero.x, zero.y);
  62765. this._drawingContext.lineTo(unit.x, unit.y);
  62766. this._drawingContext.strokeStyle = color;
  62767. this._drawingContext.lineWidth = 4;
  62768. this._drawingContext.stroke();
  62769. this._drawingContext.font = "normal 14px Segoe UI";
  62770. this._drawingContext.fillStyle = color;
  62771. this._drawingContext.fillText(label, unitText.x, unitText.y);
  62772. };
  62773. DebugLayer.prototype._renderAxis = function (projectedPosition, mesh, globalViewport) {
  62774. var position = mesh.getBoundingInfo().boundingSphere.center;
  62775. var worldMatrix = mesh.getWorldMatrix();
  62776. var unprojectedVector = BABYLON.Vector3.UnprojectFromTransform(projectedPosition.add(new BABYLON.Vector3(this._drawingCanvas.width * this.axisRatio, 0, 0)), globalViewport.width, globalViewport.height, worldMatrix, this._transformationMatrix);
  62777. var unit = (unprojectedVector.subtract(position)).length();
  62778. var xAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  62779. var xAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit * 1.5, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  62780. this._renderSingleAxis(projectedPosition, xAxis, xAxisText, "x", "#FF0000");
  62781. var yAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  62782. var yAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit * 1.5, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  62783. this._renderSingleAxis(projectedPosition, yAxis, yAxisText, "y", "#00FF00");
  62784. var zAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit)), worldMatrix, this._transformationMatrix, globalViewport);
  62785. var zAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit * 1.5)), worldMatrix, this._transformationMatrix, globalViewport);
  62786. this._renderSingleAxis(projectedPosition, zAxis, zAxisText, "z", "#0000FF");
  62787. };
  62788. DebugLayer.prototype._renderLabel = function (text, projectedPosition, labelOffset, onClick, getFillStyle) {
  62789. if (projectedPosition.z > 0 && projectedPosition.z < 1.0) {
  62790. this._drawingContext.font = "normal 12px Segoe UI";
  62791. var textMetrics = this._drawingContext.measureText(text);
  62792. var centerX = projectedPosition.x - textMetrics.width / 2;
  62793. var centerY = projectedPosition.y;
  62794. var clientRect = this._drawingCanvas.getBoundingClientRect();
  62795. if (this._showUI && this._isClickInsideRect(clientRect.left * this._ratio + centerX - 5, clientRect.top * this._ratio + centerY - labelOffset - 12, textMetrics.width + 10, 17)) {
  62796. onClick();
  62797. }
  62798. this._drawingContext.beginPath();
  62799. this._drawingContext.rect(centerX - 5, centerY - labelOffset - 12, textMetrics.width + 10, 17);
  62800. this._drawingContext.fillStyle = getFillStyle();
  62801. this._drawingContext.globalAlpha = 0.5;
  62802. this._drawingContext.fill();
  62803. this._drawingContext.globalAlpha = 1.0;
  62804. this._drawingContext.strokeStyle = '#FFFFFF';
  62805. this._drawingContext.lineWidth = 1;
  62806. this._drawingContext.stroke();
  62807. this._drawingContext.fillStyle = "#FFFFFF";
  62808. this._drawingContext.fillText(text, centerX, centerY - labelOffset);
  62809. this._drawingContext.beginPath();
  62810. this._drawingContext.arc(projectedPosition.x, centerY, 5, 0, 2 * Math.PI, false);
  62811. this._drawingContext.fill();
  62812. }
  62813. };
  62814. DebugLayer.prototype._isClickInsideRect = function (x, y, width, height) {
  62815. if (!this._clickPosition) {
  62816. return false;
  62817. }
  62818. if (this._clickPosition.x < x || this._clickPosition.x > x + width) {
  62819. return false;
  62820. }
  62821. if (this._clickPosition.y < y || this._clickPosition.y > y + height) {
  62822. return false;
  62823. }
  62824. return true;
  62825. };
  62826. DebugLayer.prototype.isVisible = function () {
  62827. return this._enabled;
  62828. };
  62829. DebugLayer.prototype.hide = function () {
  62830. if (!this._enabled) {
  62831. return;
  62832. }
  62833. this._enabled = false;
  62834. var engine = this._scene.getEngine();
  62835. this._scene.unregisterBeforeRender(this._syncData);
  62836. this._scene.unregisterAfterRender(this._syncUI);
  62837. this._rootElement.removeChild(this._globalDiv);
  62838. this._scene.forceShowBoundingBoxes = false;
  62839. this._scene.forceWireframe = false;
  62840. BABYLON.StandardMaterial.DiffuseTextureEnabled = true;
  62841. BABYLON.StandardMaterial.AmbientTextureEnabled = true;
  62842. BABYLON.StandardMaterial.SpecularTextureEnabled = true;
  62843. BABYLON.StandardMaterial.EmissiveTextureEnabled = true;
  62844. BABYLON.StandardMaterial.BumpTextureEnabled = true;
  62845. BABYLON.StandardMaterial.OpacityTextureEnabled = true;
  62846. BABYLON.StandardMaterial.ReflectionTextureEnabled = true;
  62847. BABYLON.StandardMaterial.LightmapTextureEnabled = true;
  62848. BABYLON.StandardMaterial.RefractionTextureEnabled = true;
  62849. BABYLON.StandardMaterial.ColorGradingTextureEnabled = true;
  62850. this._scene.shadowsEnabled = true;
  62851. this._scene.particlesEnabled = true;
  62852. this._scene.postProcessesEnabled = true;
  62853. this._scene.collisionsEnabled = true;
  62854. this._scene.lightsEnabled = true;
  62855. this._scene.texturesEnabled = true;
  62856. this._scene.lensFlaresEnabled = true;
  62857. this._scene.proceduralTexturesEnabled = true;
  62858. this._scene.renderTargetsEnabled = true;
  62859. this._scene.probesEnabled = true;
  62860. engine.getRenderingCanvas().removeEventListener("click", this._onCanvasClick);
  62861. this._clearSkeletonViewers();
  62862. };
  62863. DebugLayer.prototype._clearSkeletonViewers = function () {
  62864. for (var index = 0; index < this._skeletonViewers.length; index++) {
  62865. this._skeletonViewers[index].dispose();
  62866. }
  62867. this._skeletonViewers = [];
  62868. };
  62869. DebugLayer.prototype.show = function (showUI, camera, rootElement) {
  62870. if (showUI === void 0) { showUI = true; }
  62871. if (camera === void 0) { camera = null; }
  62872. if (rootElement === void 0) { rootElement = null; }
  62873. if (this._enabled) {
  62874. return;
  62875. }
  62876. this._enabled = true;
  62877. if (camera) {
  62878. this._camera = camera;
  62879. }
  62880. else {
  62881. this._camera = this._scene.activeCamera;
  62882. }
  62883. this._showUI = showUI;
  62884. var engine = this._scene.getEngine();
  62885. this._globalDiv = document.createElement("div");
  62886. this._rootElement = rootElement || document.body;
  62887. this._rootElement.appendChild(this._globalDiv);
  62888. this._generateDOMelements();
  62889. engine.getRenderingCanvas().addEventListener("click", this._onCanvasClick);
  62890. this._syncPositions();
  62891. this._scene.registerBeforeRender(this._syncData);
  62892. this._scene.registerAfterRender(this._syncUI);
  62893. };
  62894. DebugLayer.prototype._clearLabels = function () {
  62895. this._drawingContext.clearRect(0, 0, this._drawingCanvas.width, this._drawingCanvas.height);
  62896. for (var index = 0; index < this._scene.meshes.length; index++) {
  62897. var mesh = this._scene.meshes[index];
  62898. mesh.renderOverlay = false;
  62899. }
  62900. };
  62901. DebugLayer.prototype._generateheader = function (root, text) {
  62902. var header = document.createElement("div");
  62903. header.innerHTML = text + "&nbsp;";
  62904. header.style.textAlign = "right";
  62905. header.style.width = "100%";
  62906. header.style.color = "white";
  62907. header.style.backgroundColor = "Black";
  62908. header.style.padding = "5px 5px 4px 0px";
  62909. header.style.marginLeft = "-5px";
  62910. header.style.fontWeight = "bold";
  62911. root.appendChild(header);
  62912. };
  62913. DebugLayer.prototype._generateTexBox = function (root, title, color) {
  62914. var label = document.createElement("label");
  62915. label.style.display = "inline";
  62916. label.innerHTML = title;
  62917. label.style.color = color;
  62918. root.appendChild(label);
  62919. root.appendChild(document.createElement("br"));
  62920. };
  62921. DebugLayer.prototype._generateAdvancedCheckBox = function (root, leftTitle, rightTitle, initialState, task, tag) {
  62922. if (tag === void 0) { tag = null; }
  62923. var label = document.createElement("label");
  62924. label.style.display = "inline";
  62925. var boundingBoxesCheckbox = document.createElement("input");
  62926. boundingBoxesCheckbox.type = "checkbox";
  62927. boundingBoxesCheckbox.checked = initialState;
  62928. boundingBoxesCheckbox.style.display = "inline";
  62929. boundingBoxesCheckbox.style.margin = "0px 5px 0px 0px";
  62930. boundingBoxesCheckbox.style.verticalAlign = "sub";
  62931. boundingBoxesCheckbox.addEventListener("change", function (evt) {
  62932. task(evt.target, tag);
  62933. });
  62934. label.appendChild(boundingBoxesCheckbox);
  62935. var container = document.createElement("span");
  62936. var leftPart = document.createElement("span");
  62937. var rightPart = document.createElement("span");
  62938. rightPart.style.cssFloat = "right";
  62939. leftPart.innerHTML = leftTitle;
  62940. rightPart.innerHTML = rightTitle;
  62941. rightPart.style.fontSize = "12px";
  62942. rightPart.style.maxWidth = "200px";
  62943. container.appendChild(leftPart);
  62944. container.appendChild(rightPart);
  62945. label.appendChild(container);
  62946. root.appendChild(label);
  62947. root.appendChild(document.createElement("br"));
  62948. };
  62949. DebugLayer.prototype._generateCheckBox = function (root, title, initialState, task, tag) {
  62950. if (tag === void 0) { tag = null; }
  62951. var label = document.createElement("label");
  62952. label.style.display = "inline";
  62953. var checkBox = document.createElement("input");
  62954. checkBox.type = "checkbox";
  62955. checkBox.checked = initialState;
  62956. checkBox.style.display = "inline";
  62957. checkBox.style.margin = "0px 5px 0px 0px";
  62958. checkBox.style.verticalAlign = "sub";
  62959. checkBox.addEventListener("change", function (evt) {
  62960. task(evt.target, tag);
  62961. });
  62962. label.appendChild(checkBox);
  62963. label.appendChild(document.createTextNode(title));
  62964. root.appendChild(label);
  62965. root.appendChild(document.createElement("br"));
  62966. };
  62967. DebugLayer.prototype._generateButton = function (root, title, task, tag) {
  62968. if (tag === void 0) { tag = null; }
  62969. var button = document.createElement("button");
  62970. button.innerHTML = title;
  62971. button.style.height = "24px";
  62972. button.style.width = "150px";
  62973. button.style.marginBottom = "5px";
  62974. button.style.color = "#444444";
  62975. button.style.border = "1px solid white";
  62976. button.className = "debugLayerButton";
  62977. button.addEventListener("click", function (evt) {
  62978. task(evt.target, tag);
  62979. });
  62980. root.appendChild(button);
  62981. root.appendChild(document.createElement("br"));
  62982. };
  62983. DebugLayer.prototype._generateRadio = function (root, title, name, initialState, task, tag) {
  62984. if (tag === void 0) { tag = null; }
  62985. var label = document.createElement("label");
  62986. label.style.display = "inline";
  62987. var boundingBoxesRadio = document.createElement("input");
  62988. boundingBoxesRadio.type = "radio";
  62989. boundingBoxesRadio.name = name;
  62990. boundingBoxesRadio.checked = initialState;
  62991. boundingBoxesRadio.style.display = "inline";
  62992. boundingBoxesRadio.style.margin = "0px 5px 0px 0px";
  62993. boundingBoxesRadio.style.verticalAlign = "sub";
  62994. boundingBoxesRadio.addEventListener("change", function (evt) {
  62995. task(evt.target, tag);
  62996. });
  62997. label.appendChild(boundingBoxesRadio);
  62998. label.appendChild(document.createTextNode(title));
  62999. root.appendChild(label);
  63000. root.appendChild(document.createElement("br"));
  63001. };
  63002. DebugLayer.prototype._generateDOMelements = function () {
  63003. var _this = this;
  63004. this._globalDiv.id = "DebugLayer";
  63005. this._globalDiv.style.position = "absolute";
  63006. this._globalDiv.style.fontFamily = "Segoe UI, Arial";
  63007. this._globalDiv.style.fontSize = "14px";
  63008. this._globalDiv.style.color = "white";
  63009. // Drawing canvas
  63010. this._drawingCanvas = document.createElement("canvas");
  63011. this._drawingCanvas.id = "DebugLayerDrawingCanvas";
  63012. this._drawingCanvas.style.position = "absolute";
  63013. this._drawingCanvas.style.pointerEvents = "none";
  63014. this._drawingCanvas.style.backgroundColor = "transparent";
  63015. this._drawingContext = this._drawingCanvas.getContext("2d");
  63016. this._globalDiv.appendChild(this._drawingCanvas);
  63017. if (this._showUI) {
  63018. var background = "rgba(128, 128, 128, 0.4)";
  63019. var border = "rgb(180, 180, 180) solid 1px";
  63020. // Stats
  63021. this._statsDiv = document.createElement("div");
  63022. this._statsDiv.id = "DebugLayerStats";
  63023. this._statsDiv.style.border = border;
  63024. this._statsDiv.style.position = "absolute";
  63025. this._statsDiv.style.background = background;
  63026. this._statsDiv.style.padding = "0px 0px 0px 5px";
  63027. this._generateheader(this._statsDiv, "STATISTICS");
  63028. this._statsSubsetDiv = document.createElement("div");
  63029. this._statsSubsetDiv.style.paddingTop = "5px";
  63030. this._statsSubsetDiv.style.paddingBottom = "5px";
  63031. this._statsSubsetDiv.style.overflowY = "auto";
  63032. this._statsDiv.appendChild(this._statsSubsetDiv);
  63033. // Tree
  63034. this._treeDiv = document.createElement("div");
  63035. this._treeDiv.id = "DebugLayerTree";
  63036. this._treeDiv.style.border = border;
  63037. this._treeDiv.style.position = "absolute";
  63038. this._treeDiv.style.background = background;
  63039. this._treeDiv.style.padding = "0px 0px 0px 5px";
  63040. this._treeDiv.style.display = "none";
  63041. this._generateheader(this._treeDiv, "MESHES TREE");
  63042. this._treeSubsetDiv = document.createElement("div");
  63043. this._treeSubsetDiv.style.paddingTop = "5px";
  63044. this._treeSubsetDiv.style.paddingRight = "5px";
  63045. this._treeSubsetDiv.style.overflowY = "auto";
  63046. this._treeSubsetDiv.style.maxHeight = "300px";
  63047. this._treeDiv.appendChild(this._treeSubsetDiv);
  63048. this._needToRefreshMeshesTree = true;
  63049. // Logs
  63050. this._logDiv = document.createElement("div");
  63051. this._logDiv.style.border = border;
  63052. this._logDiv.id = "DebugLayerLogs";
  63053. this._logDiv.style.position = "absolute";
  63054. this._logDiv.style.background = background;
  63055. this._logDiv.style.padding = "0px 0px 0px 5px";
  63056. this._logDiv.style.display = "none";
  63057. this._generateheader(this._logDiv, "LOGS");
  63058. this._logSubsetDiv = document.createElement("div");
  63059. this._logSubsetDiv.style.height = "127px";
  63060. this._logSubsetDiv.style.paddingTop = "5px";
  63061. this._logSubsetDiv.style.overflowY = "auto";
  63062. this._logSubsetDiv.style.fontSize = "12px";
  63063. this._logSubsetDiv.style.fontFamily = "consolas";
  63064. this._logSubsetDiv.innerHTML = BABYLON.Tools.LogCache;
  63065. this._logDiv.appendChild(this._logSubsetDiv);
  63066. BABYLON.Tools.OnNewCacheEntry = function (entry) {
  63067. _this._logSubsetDiv.innerHTML = entry + _this._logSubsetDiv.innerHTML;
  63068. };
  63069. // Options
  63070. this._optionsDiv = document.createElement("div");
  63071. this._optionsDiv.id = "DebugLayerOptions";
  63072. this._optionsDiv.style.border = border;
  63073. this._optionsDiv.style.position = "absolute";
  63074. this._optionsDiv.style.background = background;
  63075. this._optionsDiv.style.padding = "0px 0px 0px 5px";
  63076. this._optionsDiv.style.overflowY = "auto";
  63077. this._generateheader(this._optionsDiv, "OPTIONS");
  63078. this._optionsSubsetDiv = document.createElement("div");
  63079. this._optionsSubsetDiv.style.paddingTop = "5px";
  63080. this._optionsSubsetDiv.style.paddingBottom = "5px";
  63081. this._optionsSubsetDiv.style.overflowY = "auto";
  63082. this._optionsSubsetDiv.style.maxHeight = "200px";
  63083. this._optionsDiv.appendChild(this._optionsSubsetDiv);
  63084. this._generateTexBox(this._optionsSubsetDiv, "<b>Windows:</b>", this.accentColor);
  63085. this._generateCheckBox(this._optionsSubsetDiv, "Statistics", this._displayStatistics, function (element) { _this._displayStatistics = element.checked; });
  63086. this._generateCheckBox(this._optionsSubsetDiv, "Logs", this._displayLogs, function (element) { _this._displayLogs = element.checked; });
  63087. this._generateCheckBox(this._optionsSubsetDiv, "Meshes tree", this._displayTree, function (element) {
  63088. _this._displayTree = element.checked;
  63089. _this._needToRefreshMeshesTree = true;
  63090. });
  63091. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  63092. this._generateTexBox(this._optionsSubsetDiv, "<b>General:</b>", this.accentColor);
  63093. this._generateCheckBox(this._optionsSubsetDiv, "Bounding boxes", this._scene.forceShowBoundingBoxes, function (element) { _this._scene.forceShowBoundingBoxes = element.checked; });
  63094. this._generateCheckBox(this._optionsSubsetDiv, "Clickable labels", this._labelsEnabled, function (element) {
  63095. _this._labelsEnabled = element.checked;
  63096. if (!_this._labelsEnabled) {
  63097. _this._clearLabels();
  63098. }
  63099. });
  63100. this._generateCheckBox(this._optionsSubsetDiv, "Generate user marks (F12)", BABYLON.Tools.PerformanceLogLevel === BABYLON.Tools.PerformanceUserMarkLogLevel, function (element) {
  63101. if (element.checked) {
  63102. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceUserMarkLogLevel;
  63103. }
  63104. else {
  63105. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceNoneLogLevel;
  63106. }
  63107. });
  63108. ;
  63109. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  63110. this._generateTexBox(this._optionsSubsetDiv, "<b>Rendering mode:</b>", this.accentColor);
  63111. this._generateRadio(this._optionsSubsetDiv, "Solid", "renderMode", !this._scene.forceWireframe && !this._scene.forcePointsCloud, function (element) {
  63112. if (element.checked) {
  63113. _this._scene.forceWireframe = false;
  63114. _this._scene.forcePointsCloud = false;
  63115. }
  63116. });
  63117. this._generateRadio(this._optionsSubsetDiv, "Wireframe", "renderMode", this._scene.forceWireframe, function (element) {
  63118. if (element.checked) {
  63119. _this._scene.forceWireframe = true;
  63120. _this._scene.forcePointsCloud = false;
  63121. }
  63122. });
  63123. this._generateRadio(this._optionsSubsetDiv, "Point", "renderMode", this._scene.forcePointsCloud, function (element) {
  63124. if (element.checked) {
  63125. _this._scene.forceWireframe = false;
  63126. _this._scene.forcePointsCloud = true;
  63127. }
  63128. });
  63129. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  63130. this._generateTexBox(this._optionsSubsetDiv, "<b>Texture channels:</b>", this.accentColor);
  63131. this._generateCheckBox(this._optionsSubsetDiv, "Diffuse", BABYLON.StandardMaterial.DiffuseTextureEnabled, function (element) { BABYLON.StandardMaterial.DiffuseTextureEnabled = element.checked; });
  63132. this._generateCheckBox(this._optionsSubsetDiv, "Ambient", BABYLON.StandardMaterial.AmbientTextureEnabled, function (element) { BABYLON.StandardMaterial.AmbientTextureEnabled = element.checked; });
  63133. this._generateCheckBox(this._optionsSubsetDiv, "Specular", BABYLON.StandardMaterial.SpecularTextureEnabled, function (element) { BABYLON.StandardMaterial.SpecularTextureEnabled = element.checked; });
  63134. this._generateCheckBox(this._optionsSubsetDiv, "Emissive", BABYLON.StandardMaterial.EmissiveTextureEnabled, function (element) { BABYLON.StandardMaterial.EmissiveTextureEnabled = element.checked; });
  63135. this._generateCheckBox(this._optionsSubsetDiv, "Bump", BABYLON.StandardMaterial.BumpTextureEnabled, function (element) { BABYLON.StandardMaterial.BumpTextureEnabled = element.checked; });
  63136. this._generateCheckBox(this._optionsSubsetDiv, "Opacity", BABYLON.StandardMaterial.OpacityTextureEnabled, function (element) { BABYLON.StandardMaterial.OpacityTextureEnabled = element.checked; });
  63137. this._generateCheckBox(this._optionsSubsetDiv, "Reflection", BABYLON.StandardMaterial.ReflectionTextureEnabled, function (element) { BABYLON.StandardMaterial.ReflectionTextureEnabled = element.checked; });
  63138. this._generateCheckBox(this._optionsSubsetDiv, "Refraction", BABYLON.StandardMaterial.RefractionTextureEnabled, function (element) { BABYLON.StandardMaterial.RefractionTextureEnabled = element.checked; });
  63139. this._generateCheckBox(this._optionsSubsetDiv, "ColorGrading", BABYLON.StandardMaterial.ColorGradingTextureEnabled, function (element) { BABYLON.StandardMaterial.ColorGradingTextureEnabled = element.checked; });
  63140. this._generateCheckBox(this._optionsSubsetDiv, "Lightmap", BABYLON.StandardMaterial.LightmapTextureEnabled, function (element) { BABYLON.StandardMaterial.LightmapTextureEnabled = element.checked; });
  63141. this._generateCheckBox(this._optionsSubsetDiv, "Fresnel", BABYLON.StandardMaterial.FresnelEnabled, function (element) { BABYLON.StandardMaterial.FresnelEnabled = element.checked; });
  63142. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  63143. this._generateTexBox(this._optionsSubsetDiv, "<b>Options:</b>", this.accentColor);
  63144. this._generateCheckBox(this._optionsSubsetDiv, "Animations", this._scene.animationsEnabled, function (element) { _this._scene.animationsEnabled = element.checked; });
  63145. this._generateCheckBox(this._optionsSubsetDiv, "Collisions", this._scene.collisionsEnabled, function (element) { _this._scene.collisionsEnabled = element.checked; });
  63146. this._generateCheckBox(this._optionsSubsetDiv, "Fog", this._scene.fogEnabled, function (element) { _this._scene.fogEnabled = element.checked; });
  63147. this._generateCheckBox(this._optionsSubsetDiv, "Lens flares", this._scene.lensFlaresEnabled, function (element) { _this._scene.lensFlaresEnabled = element.checked; });
  63148. this._generateCheckBox(this._optionsSubsetDiv, "Lights", this._scene.lightsEnabled, function (element) { _this._scene.lightsEnabled = element.checked; });
  63149. this._generateCheckBox(this._optionsSubsetDiv, "Particles", this._scene.particlesEnabled, function (element) { _this._scene.particlesEnabled = element.checked; });
  63150. this._generateCheckBox(this._optionsSubsetDiv, "Post-processes", this._scene.postProcessesEnabled, function (element) { _this._scene.postProcessesEnabled = element.checked; });
  63151. this._generateCheckBox(this._optionsSubsetDiv, "Probes", this._scene.probesEnabled, function (element) { _this._scene.probesEnabled = element.checked; });
  63152. this._generateCheckBox(this._optionsSubsetDiv, "Procedural textures", this._scene.proceduralTexturesEnabled, function (element) { _this._scene.proceduralTexturesEnabled = element.checked; });
  63153. this._generateCheckBox(this._optionsSubsetDiv, "Render targets", this._scene.renderTargetsEnabled, function (element) { _this._scene.renderTargetsEnabled = element.checked; });
  63154. this._generateCheckBox(this._optionsSubsetDiv, "Shadows", this._scene.shadowsEnabled, function (element) { _this._scene.shadowsEnabled = element.checked; });
  63155. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", this._scene.skeletonsEnabled, function (element) { _this._scene.skeletonsEnabled = element.checked; });
  63156. this._generateCheckBox(this._optionsSubsetDiv, "Sprites", this._scene.spritesEnabled, function (element) { _this._scene.spritesEnabled = element.checked; });
  63157. this._generateCheckBox(this._optionsSubsetDiv, "Textures", this._scene.texturesEnabled, function (element) { _this._scene.texturesEnabled = element.checked; });
  63158. if (BABYLON.AudioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  63159. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  63160. this._generateTexBox(this._optionsSubsetDiv, "<b>Audio:</b>", this.accentColor);
  63161. this._generateRadio(this._optionsSubsetDiv, "Headphones", "panningModel", this._scene.headphone, function (element) {
  63162. if (element.checked) {
  63163. _this._scene.headphone = true;
  63164. }
  63165. });
  63166. this._generateRadio(this._optionsSubsetDiv, "Normal Speakers", "panningModel", !this._scene.headphone, function (element) {
  63167. if (element.checked) {
  63168. _this._scene.headphone = false;
  63169. }
  63170. });
  63171. this._generateCheckBox(this._optionsSubsetDiv, "Disable audio", !this._scene.audioEnabled, function (element) {
  63172. _this._scene.audioEnabled = !element.checked;
  63173. });
  63174. }
  63175. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  63176. this._generateTexBox(this._optionsSubsetDiv, "<b>Viewers:</b>", this.accentColor);
  63177. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", false, function (element) {
  63178. if (!element.checked) {
  63179. _this._clearSkeletonViewers();
  63180. return;
  63181. }
  63182. for (var index = 0; index < _this._scene.meshes.length; index++) {
  63183. var mesh = _this._scene.meshes[index];
  63184. if (mesh.skeleton) {
  63185. var found = false;
  63186. for (var sIndex = 0; sIndex < _this._skeletonViewers.length; sIndex++) {
  63187. if (_this._skeletonViewers[sIndex].skeleton === mesh.skeleton) {
  63188. found = true;
  63189. break;
  63190. }
  63191. }
  63192. if (found) {
  63193. continue;
  63194. }
  63195. var viewer = new BABYLON.Debug.SkeletonViewer(mesh.skeleton, mesh, _this._scene);
  63196. viewer.isEnabled = true;
  63197. _this._skeletonViewers.push(viewer);
  63198. }
  63199. }
  63200. });
  63201. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  63202. this._generateTexBox(this._optionsSubsetDiv, "<b>Tools:</b>", this.accentColor);
  63203. this._generateButton(this._optionsSubsetDiv, "Dump rendertargets", function (element) { _this._scene.dumpNextRenderTargets = true; });
  63204. this._generateButton(this._optionsSubsetDiv, "Run SceneOptimizer", function (element) { BABYLON.SceneOptimizer.OptimizeAsync(_this._scene); });
  63205. this._generateButton(this._optionsSubsetDiv, "Log camera object", function (element) {
  63206. if (_this._camera) {
  63207. console.log(_this._camera);
  63208. }
  63209. else {
  63210. console.warn("No camera defined, or debug layer created before camera creation!");
  63211. }
  63212. });
  63213. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  63214. this._globalDiv.appendChild(this._statsDiv);
  63215. this._globalDiv.appendChild(this._logDiv);
  63216. this._globalDiv.appendChild(this._optionsDiv);
  63217. this._globalDiv.appendChild(this._treeDiv);
  63218. }
  63219. };
  63220. DebugLayer.prototype._displayStats = function () {
  63221. var scene = this._scene;
  63222. var engine = scene.getEngine();
  63223. var glInfo = engine.getGlInfo();
  63224. this._statsSubsetDiv.innerHTML = "Babylon.js v" + BABYLON.Engine.Version + " - <b>" + BABYLON.Tools.Format(engine.getFps(), 0) + " fps</b><br><br>"
  63225. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  63226. + "<b>Count</b><br>"
  63227. + "Total meshes: " + scene.meshes.length + "<br>"
  63228. + "Total lights: " + scene.lights.length + "<br>"
  63229. + "Total vertices: " + scene.getTotalVertices() + "<br>"
  63230. + "Total materials: " + scene.materials.length + "<br>"
  63231. + "Total textures: " + scene.textures.length + "<br>"
  63232. + "Active meshes: " + scene.getActiveMeshes().length + "<br>"
  63233. + "Active indices: " + scene.getActiveIndices() + "<br>"
  63234. + "Active bones: " + scene.getActiveBones() + "<br>"
  63235. + "Active particles: " + scene.getActiveParticles() + "<br>"
  63236. + "<b>Draw calls: " + engine.drawCalls + "</b><br><br>"
  63237. + "<b>Duration</b><br>"
  63238. + "Meshes selection:</i> " + BABYLON.Tools.Format(scene.getEvaluateActiveMeshesDuration()) + " ms<br>"
  63239. + "Render Targets: " + BABYLON.Tools.Format(scene.getRenderTargetsDuration()) + " ms<br>"
  63240. + "Particles: " + BABYLON.Tools.Format(scene.getParticlesDuration()) + " ms<br>"
  63241. + "Sprites: " + BABYLON.Tools.Format(scene.getSpritesDuration()) + " ms<br><br>"
  63242. + "Render: <b>" + BABYLON.Tools.Format(scene.getRenderDuration()) + " ms</b><br>"
  63243. + "Frame: " + BABYLON.Tools.Format(scene.getLastFrameDuration()) + " ms<br>"
  63244. + "Potential FPS: " + BABYLON.Tools.Format(1000.0 / scene.getLastFrameDuration(), 0) + "<br>"
  63245. + "Resolution: " + engine.getRenderWidth() + "x" + engine.getRenderHeight() + "<br><br>"
  63246. + "</div>"
  63247. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  63248. + "<b>Extensions</b><br>"
  63249. + "Std derivatives: " + (engine.getCaps().standardDerivatives ? "Yes" : "No") + "<br>"
  63250. + "Compressed textures: " + (engine.getCaps().s3tc ? "Yes" : "No") + "<br>"
  63251. + "Hardware instances: " + (engine.getCaps().instancedArrays ? "Yes" : "No") + "<br>"
  63252. + "Texture float: " + (engine.getCaps().textureFloat ? "Yes" : "No") + "<br><br>"
  63253. + "32bits indices: " + (engine.getCaps().uintIndices ? "Yes" : "No") + "<br>"
  63254. + "Fragment depth: " + (engine.getCaps().fragmentDepthSupported ? "Yes" : "No") + "<br>"
  63255. + "High precision shaders: " + (engine.getCaps().highPrecisionShaderSupported ? "Yes" : "No") + "<br>"
  63256. + "Draw buffers: " + (engine.getCaps().drawBuffersExtension ? "Yes" : "No") + "<br>"
  63257. + "</div><br>"
  63258. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  63259. + "<b>Caps.</b><br>"
  63260. + "Stencil: " + (engine.isStencilEnable ? "Enabled" : "Disabled") + "<br>"
  63261. + "Max textures units: " + engine.getCaps().maxTexturesImageUnits + "<br>"
  63262. + "Max textures size: " + engine.getCaps().maxTextureSize + "<br>"
  63263. + "Max anisotropy: " + engine.getCaps().maxAnisotropy + "<br>"
  63264. + "<b>Info</b><br>"
  63265. + "WebGL feature level: " + engine.webGLVersion + "<br>"
  63266. + glInfo.version + "<br>"
  63267. + "</div><br>"
  63268. + glInfo.renderer + "<br>";
  63269. if (this.customStatsFunction) {
  63270. this._statsSubsetDiv.innerHTML += this.customStatsFunction();
  63271. }
  63272. };
  63273. return DebugLayer;
  63274. }());
  63275. BABYLON.DebugLayer = DebugLayer;
  63276. })(BABYLON || (BABYLON = {}));
  63277. var BABYLON;
  63278. (function (BABYLON) {
  63279. var StandardRenderingPipeline = (function (_super) {
  63280. __extends(StandardRenderingPipeline, _super);
  63281. /**
  63282. * @constructor
  63283. * @param {string} name - The rendering pipeline name
  63284. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  63285. * @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)
  63286. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  63287. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  63288. */
  63289. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  63290. var _this = this;
  63291. if (originalPostProcess === void 0) { originalPostProcess = null; }
  63292. _super.call(this, scene.getEngine(), name);
  63293. this.downSampleX4PostProcess = null;
  63294. this.brightPassPostProcess = null;
  63295. this.gaussianBlurHPostProcesses = [];
  63296. this.gaussianBlurVPostProcesses = [];
  63297. this.textureAdderPostProcess = null;
  63298. this.depthOfFieldSourcePostProcess = null;
  63299. this.depthOfFieldPostProcess = null;
  63300. this.brightThreshold = 1.0;
  63301. this.gaussianCoefficient = 0.25;
  63302. this.gaussianMean = 1.0;
  63303. this.gaussianStandardDeviation = 1.0;
  63304. this.exposure = 1.0;
  63305. this.lensTexture = null;
  63306. this.depthOfFieldDistance = 10.0;
  63307. this._depthRenderer = null;
  63308. // Getters and setters
  63309. this._blurEnabled = true;
  63310. this._depthOfFieldEnabled = false;
  63311. // Initialize
  63312. this._scene = scene;
  63313. // Create pass post-processe
  63314. if (!originalPostProcess) {
  63315. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), true, "#define PASS_POST_PROCESS", BABYLON.Engine.TEXTURETYPE_FLOAT);
  63316. }
  63317. else {
  63318. this.originalPostProcess = originalPostProcess;
  63319. }
  63320. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  63321. // Create down sample X4 post-process
  63322. this._createDownSampleX4PostProcess(scene, ratio / 2);
  63323. // Create bright pass post-process
  63324. this._createBrightPassPostProcess(scene, ratio / 2);
  63325. // Create gaussian blur post-processes (down sampling blurs)
  63326. this._createGaussianBlurPostProcesses(scene, ratio / 2, 0);
  63327. this._createGaussianBlurPostProcesses(scene, ratio / 4, 1);
  63328. this._createGaussianBlurPostProcesses(scene, ratio / 8, 2);
  63329. this._createGaussianBlurPostProcesses(scene, ratio / 16, 3);
  63330. // Create texture adder post-process
  63331. this._createTextureAdderPostProcess(scene, ratio);
  63332. // Create depth-of-field source post-process
  63333. this.depthOfFieldSourcePostProcess = new BABYLON.PostProcess("HDRDepthOfFieldSource", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), true, "#define PASS_POST_PROCESS", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  63334. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfFieldSource", function () { return _this.depthOfFieldSourcePostProcess; }, true));
  63335. // Create gaussian blur used by depth-of-field
  63336. this._createGaussianBlurPostProcesses(scene, ratio / 2, 4);
  63337. // Create depth-of-field post-process
  63338. this._createDepthOfFieldPostProcess(scene, ratio);
  63339. // Finish
  63340. scene.postProcessRenderPipelineManager.addPipeline(this);
  63341. if (cameras !== null) {
  63342. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  63343. }
  63344. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRDepthOfFieldSource", cameras);
  63345. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurH4", cameras);
  63346. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurV4", cameras);
  63347. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRDepthOfField", cameras);
  63348. }
  63349. Object.defineProperty(StandardRenderingPipeline.prototype, "BlurEnabled", {
  63350. get: function () {
  63351. return this._blurEnabled;
  63352. },
  63353. set: function (enabled) {
  63354. if (enabled && !this._blurEnabled || !enabled && this._blurEnabled) {
  63355. for (var i = 0; i < this.gaussianBlurHPostProcesses.length - 1; i++) {
  63356. if (enabled) {
  63357. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurH" + i, this._scene.cameras);
  63358. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurV" + i, this._scene.cameras);
  63359. }
  63360. else {
  63361. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurH" + i, this._scene.cameras);
  63362. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurV" + i, this._scene.cameras);
  63363. }
  63364. }
  63365. }
  63366. this._blurEnabled = enabled;
  63367. },
  63368. enumerable: true,
  63369. configurable: true
  63370. });
  63371. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  63372. get: function () {
  63373. return this._depthOfFieldEnabled;
  63374. },
  63375. set: function (enabled) {
  63376. if (enabled && !this._depthOfFieldEnabled) {
  63377. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRDepthOfFieldSource", this._scene.cameras);
  63378. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurH4", this._scene.cameras);
  63379. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurV4", this._scene.cameras);
  63380. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRDepthOfField", this._scene.cameras);
  63381. this._depthRenderer = this._scene.enableDepthRenderer();
  63382. }
  63383. else if (!enabled && this._depthOfFieldEnabled) {
  63384. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRDepthOfFieldSource", this._scene.cameras);
  63385. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurH4", this._scene.cameras);
  63386. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurV4", this._scene.cameras);
  63387. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRDepthOfField", this._scene.cameras);
  63388. }
  63389. this._depthOfFieldEnabled = enabled;
  63390. },
  63391. enumerable: true,
  63392. configurable: true
  63393. });
  63394. // Down Sample X4 Post-Processs
  63395. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  63396. var _this = this;
  63397. var downSampleX4Offsets = new Array(32);
  63398. this.downSampleX4PostProcess = new BABYLON.PostProcess("HDRDownSampleX4", "standard", ["dsOffsets"], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define DOWN_SAMPLE_X4", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  63399. this.downSampleX4PostProcess.onApply = function (effect) {
  63400. var id = 0;
  63401. for (var i = -2; i < 2; i++) {
  63402. for (var j = -2; j < 2; j++) {
  63403. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this.downSampleX4PostProcess.width);
  63404. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this.downSampleX4PostProcess.height);
  63405. id += 2;
  63406. }
  63407. }
  63408. effect.setArray2("dsOffsets", downSampleX4Offsets);
  63409. };
  63410. // Add to pipeline
  63411. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  63412. };
  63413. // Brightpass Post-Process
  63414. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  63415. var _this = this;
  63416. var brightOffsets = new Array(8);
  63417. this.brightPassPostProcess = new BABYLON.PostProcess("HDRBrightPass", "standard", ["dsOffsets", "brightThreshold"], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define BRIGHT_PASS", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  63418. this.brightPassPostProcess.onApply = function (effect) {
  63419. var sU = (1.0 / _this.brightPassPostProcess.width);
  63420. var sV = (1.0 / _this.brightPassPostProcess.height);
  63421. brightOffsets[0] = -0.5 * sU;
  63422. brightOffsets[1] = 0.5 * sV;
  63423. brightOffsets[2] = 0.5 * sU;
  63424. brightOffsets[3] = 0.5 * sV;
  63425. brightOffsets[4] = -0.5 * sU;
  63426. brightOffsets[5] = -0.5 * sV;
  63427. brightOffsets[6] = 0.5 * sU;
  63428. brightOffsets[7] = -0.5 * sV;
  63429. effect.setArray2("dsOffsets", brightOffsets);
  63430. effect.setFloat("brightThreshold", _this.brightThreshold);
  63431. };
  63432. // Add to pipeline
  63433. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  63434. };
  63435. // Create gaussian blur H&V post-processes
  63436. StandardRenderingPipeline.prototype._createGaussianBlurPostProcesses = function (scene, ratio, indice) {
  63437. var _this = this;
  63438. var blurOffsets = new Array(9);
  63439. var blurWeights = new Array(9);
  63440. var uniforms = ["blurOffsets", "blurWeights"];
  63441. var callback = function (height) {
  63442. return function (effect) {
  63443. // Weights
  63444. var x = 0.0;
  63445. for (var i = 0; i < 9; i++) {
  63446. x = (i - 4.0) / 4.0;
  63447. blurWeights[i] =
  63448. _this.gaussianCoefficient
  63449. * (1.0 / Math.sqrt(2.0 * Math.PI * _this.gaussianStandardDeviation))
  63450. * Math.exp((-((x - _this.gaussianMean) * (x - _this.gaussianMean))) / (2.0 * _this.gaussianStandardDeviation * _this.gaussianStandardDeviation));
  63451. }
  63452. var lastOutputDimensions = {
  63453. width: scene.getEngine().getRenderWidth(),
  63454. height: scene.getEngine().getRenderHeight()
  63455. };
  63456. for (var i = 0; i < 9; i++) {
  63457. var value = (i - 4.0) * (1.0 / (height === true ? lastOutputDimensions.height : lastOutputDimensions.width));
  63458. blurOffsets[i] = value;
  63459. }
  63460. effect.setArray("blurOffsets", blurOffsets);
  63461. effect.setArray("blurWeights", blurWeights);
  63462. };
  63463. };
  63464. // Create horizontal gaussian blur post-processes
  63465. var gaussianBlurHPostProcess = new BABYLON.PostProcess("HDRGaussianBlurH" + ratio, "standard", uniforms, [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_H", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  63466. gaussianBlurHPostProcess.onApply = callback(false);
  63467. // Create vertical gaussian blur post-process
  63468. var gaussianBlurVPostProcess = new BABYLON.PostProcess("HDRGaussianBlurV" + ratio, "standard", uniforms, [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_V", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  63469. gaussianBlurVPostProcess.onApply = callback(true);
  63470. // Add to pipeline
  63471. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurH" + indice, function () { return gaussianBlurHPostProcess; }, true));
  63472. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurV" + indice, function () { return gaussianBlurVPostProcess; }, true));
  63473. // Finish
  63474. this.gaussianBlurHPostProcesses.push(gaussianBlurHPostProcess);
  63475. this.gaussianBlurVPostProcesses.push(gaussianBlurVPostProcess);
  63476. };
  63477. // Create texture adder post-process
  63478. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  63479. var _this = this;
  63480. var lastGaussianBlurPostProcess = this.gaussianBlurVPostProcesses[3];
  63481. this.textureAdderPostProcess = new BABYLON.PostProcess("HDRTextureAdder", "standard", ["exposure"], ["otherSampler", "lensSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), true, "#define TEXTURE_ADDER", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  63482. this.textureAdderPostProcess.onApply = function (effect) {
  63483. effect.setTextureFromPostProcess("otherSampler", _this.originalPostProcess);
  63484. effect.setTexture("lensSampler", _this.lensTexture);
  63485. effect.setFloat("exposure", _this.exposure);
  63486. };
  63487. // Add to pipeline
  63488. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  63489. };
  63490. // Create depth-of-field post-process
  63491. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  63492. var _this = this;
  63493. this.depthOfFieldPostProcess = new BABYLON.PostProcess("HDRDepthOfField", "standard", ["distance"], ["otherSampler", "depthSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define DEPTH_OF_FIELD", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  63494. this.depthOfFieldPostProcess.onApply = function (effect) {
  63495. effect.setTextureFromPostProcess("otherSampler", _this.depthOfFieldSourcePostProcess);
  63496. effect.setTexture("depthSampler", _this._depthRenderer.getDepthMap());
  63497. effect.setFloat("distance", _this.depthOfFieldDistance);
  63498. };
  63499. // Add to pipeline
  63500. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  63501. };
  63502. return StandardRenderingPipeline;
  63503. }(BABYLON.PostProcessRenderPipeline));
  63504. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  63505. })(BABYLON || (BABYLON = {}));
  63506. BABYLON.Effect.ShadersStore={"anaglyphPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D leftSampler;\nvoid main(void)\n{\nvec4 leftFrag=texture2D(leftSampler,vUV);\nleftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);\nvec4 rightFrag=texture2D(textureSampler,vUV);\nrightFrag=vec4(rightFrag.r,1.0,1.0,1.0);\ngl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);\n}","blackAndWhitePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\nfloat luminance=dot(texture2D(textureSampler,vUV).rgb,vec3(0.3,0.59,0.11));\ngl_FragColor=vec4(luminance,luminance,luminance,1.0);\n}","blurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\nvoid main(void)\n{\nfloat weights[7];\nweights[0]=0.05;\nweights[1]=0.1;\nweights[2]=0.2;\nweights[3]=0.3;\nweights[4]=0.2;\nweights[5]=0.1;\nweights[6]=0.05;\nvec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);\nvec2 texelStep=texelSize*direction*blurWidth;\nvec2 start=vUV-3.0*texelStep;\nvec4 baseColor=vec4(0.,0.,0.,0.);\nvec2 texelOffset=vec2(0.,0.);\nfor (int i=0; i<7; i++)\n{\nbaseColor+=texture2D(textureSampler,start+texelOffset)*weights[i];\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\n}","chromaticAberrationPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float chromatic_aberration;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec2 centered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nfloat radius2=centered_screen_pos.x*centered_screen_pos.x\n+centered_screen_pos.y*centered_screen_pos.y;\nfloat radius=sqrt(radius2);\nvec4 original=texture2D(textureSampler,vUV);\nif (chromatic_aberration>0.0) {\n\nvec3 ref_indices=vec3(-0.3,0.0,0.3);\nfloat ref_shiftX=chromatic_aberration*radius*17.0/screen_width;\nfloat ref_shiftY=chromatic_aberration*radius*17.0/screen_height;\n\nvec2 ref_coords_r=vec2(vUV.x+ref_indices.r*ref_shiftX,vUV.y+ref_indices.r*ref_shiftY*0.5);\nvec2 ref_coords_g=vec2(vUV.x+ref_indices.g*ref_shiftX,vUV.y+ref_indices.g*ref_shiftY*0.5);\nvec2 ref_coords_b=vec2(vUV.x+ref_indices.b*ref_shiftX,vUV.y+ref_indices.b*ref_shiftY*0.5);\noriginal.r=texture2D(textureSampler,ref_coords_r).r;\noriginal.g=texture2D(textureSampler,ref_coords_g).g;\noriginal.b=texture2D(textureSampler,ref_coords_b).b;\n}\ngl_FragColor=original;\n}","colorPixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","colorVertexShader":"\nattribute vec3 position;\n\nuniform mat4 worldViewProjection;\nvoid main(void) {\ngl_Position=worldViewProjection*vec4(position,1.0);\n}","colorCorrectionPixelShader":"\nuniform sampler2D textureSampler; \nuniform sampler2D colorTable; \n\nvarying vec2 vUV;\n\nconst float SLICE_COUNT=16.0; \n\nvec4 sampleAs3DTexture(sampler2D texture,vec3 uv,float width) {\nfloat sliceSize=1.0/width; \nfloat slicePixelSize=sliceSize/width; \nfloat sliceInnerSize=slicePixelSize*(width-1.0); \nfloat zSlice0=min(floor(uv.z*width),width-1.0);\nfloat zSlice1=min(zSlice0+1.0,width-1.0);\nfloat xOffset=slicePixelSize*0.5+uv.x*sliceInnerSize;\nfloat s0=xOffset+(zSlice0*sliceSize);\nfloat s1=xOffset+(zSlice1*sliceSize);\nvec4 slice0Color=texture2D(texture,vec2(s0,uv.y));\nvec4 slice1Color=texture2D(texture,vec2(s1,uv.y));\nfloat zOffset=mod(uv.z*width,1.0);\nvec4 result=mix(slice0Color,slice1Color,zOffset);\nreturn result;\n}\nvoid main(void)\n{\nvec4 screen_color=texture2D(textureSampler,vUV);\ngl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);\n}","convolutionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform float kernel[9];\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 colorSum =\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];\nfloat kernelWeight =\nkernel[0] +\nkernel[1] +\nkernel[2] +\nkernel[3] +\nkernel[4] +\nkernel[5] +\nkernel[6] +\nkernel[7] +\nkernel[8];\nif (kernelWeight<=0.0) {\nkernelWeight=1.0;\n}\ngl_FragColor=vec4((colorSum/kernelWeight).rgb,1);\n}","defaultPixelShader":"#ifdef BUMP\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n\n#define RECIPROCAL_PI2 0.15915494\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<helperFunctions>\n\n#include<lightFragmentDeclaration>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform sampler2D diffuseSampler;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform sampler2D ambientSampler;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform vec2 vLightmapInfos;\nuniform sampler2D lightmapSampler;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\nuniform mat4 refractionMatrix;\n#endif\n#ifdef REFRACTIONFRESNEL\nuniform vec4 refractionLeftColor;\nuniform vec4 refractionRightColor;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform sampler2D specularSampler;\n#endif\n\n#include<fresnelFunction>\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvarying vec3 vDirectionW;\n#endif\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#endif\n#include<reflectionFunction>\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n#endif\n#ifdef CAMERACOLORGRADING\n#include<colorGradingDefinition> \n#include<colorGrading>\n#endif\n#ifdef CAMERACOLORCURVES\n#include<colorCurvesDefinition>\n#include<colorCurves>\n#endif\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\n#ifdef DIFFUSE\nvec2 diffuseUV=vDiffuseUV;\n#endif\n#include<bumpFragment>\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,diffuseUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#ifdef ALPHAFROMDIFFUSE\nalpha*=baseColor.a;\n#endif\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV).rgb*vAmbientInfos.y;\n#endif\n\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nvec4 specularMapColor=texture2D(specularSampler,vSpecularUV);\nspecularColor=specularMapColor.rgb;\n#ifdef GLOSSINESS\nglossiness=glossiness*specularMapColor.a;\n#endif\n#endif\n#else\nfloat glossiness=0.;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\nfloat shadow=1.;\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV).rgb*vLightmapInfos.y;\n#endif\n#include<lightFragment>[0..maxSimultaneousLights]\n\nvec3 refractionColor=vec3(0.,0.,0.);\n#ifdef REFRACTION\nvec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y));\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0)\n{\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb*vRefractionInfos.x;\n}\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\nrefractionColor=texture2D(refraction2DSampler,refractionCoords).rgb*vRefractionInfos.x;\n#endif\n#endif\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_3D\n#ifdef ROUGHNESS\nfloat bias=vReflectionInfos.y;\n#ifdef SPECULARTERM\n#ifdef SPECULAR\n#ifdef GLOSSINESS\nbias*=(1.0-specularMapColor.a);\n#endif\n#endif\n#endif\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias).rgb*vReflectionInfos.x;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb*vReflectionInfos.x;\n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb*vReflectionInfos.x;\n#endif\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\n#ifdef REFLECTIONFRESNELFROMSPECULAR\n#ifdef SPECULARTERM\nreflectionColor*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n#endif\n#ifdef REFRACTIONFRESNEL\nfloat refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);\nrefractionColor*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\n#ifdef LINKEMISSIVEWITHDIFFUSE\nvec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#endif\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n#ifdef REFLECTIONOVERALPHA\nalpha=clamp(alpha+dot(reflectionColor,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 color=vec4(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+emissiveColor+refractionColor,0.0,1.0),alpha);\n#else\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+refractionColor,alpha);\n#endif\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\ncolor.rgb*=lightmapColor;\n#else\ncolor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n#include<logDepthFragment>\n#include<fogFragment>\n#ifdef CAMERACOLORGRADING\ncolor=colorGrades(color);\n#endif\n#ifdef CAMERACOLORCURVES\ncolor.rgb=applyColorCurves(color.rgb);\n#endif\ngl_FragColor=color;\n}","defaultVertexShader":"\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#include<pointCloudVertexDeclaration>\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<shadowsVertexDeclaration>[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=position;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef DIFFUSE\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef AMBIENT\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef OPACITY\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef EMISSIVE\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef LIGHTMAP\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef BUMP\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n#include<pointCloudVertex>\n#include<logDepthVertex>\n}","depthPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nuniform float far;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\nfloat depth=(gl_FragCoord.z/gl_FragCoord.w)/far;\ngl_FragColor=vec4(depth,depth*depth,0.0,1.0);\n}","depthVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","depthBoxBlurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nvoid main(void)\n{\nvec4 colorDepth=vec4(0.0);\nfor (int x=-OFFSET; x<=OFFSET; x++)\nfor (int y=-OFFSET; y<=OFFSET; y++)\ncolorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);\ngl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));\n}","depthOfFieldPixelShader":"\n\n\n\n\nuniform sampler2D textureSampler;\nuniform sampler2D highlightsSampler;\nuniform sampler2D depthSampler;\nuniform sampler2D grainSampler;\n\nuniform float grain_amount;\nuniform bool blur_noise;\nuniform float screen_width;\nuniform float screen_height;\nuniform float distortion;\nuniform bool dof_enabled;\n\nuniform float screen_distance; \nuniform float aperture;\nuniform float darken;\nuniform float edge_blur;\nuniform bool highlights;\n\nuniform float near;\nuniform float far;\n\nvarying vec2 vUV;\n\n#define PI 3.14159265\n#define TWOPI 6.28318530\n#define inverse_focal_length 0.1 \n\nvec2 centered_screen_pos;\nvec2 distorted_coords;\nfloat radius2;\nfloat radius;\n\nvec2 rand(vec2 co)\n{\nfloat noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));\nfloat noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));\nreturn clamp(vec2(noise1,noise2),0.0,1.0);\n}\n\nvec2 getDistortedCoords(vec2 coords) {\nif (distortion == 0.0) { return coords; }\nvec2 direction=1.0*normalize(centered_screen_pos);\nvec2 dist_coords=vec2(0.5,0.5);\ndist_coords.x=0.5+direction.x*radius2*1.0;\ndist_coords.y=0.5+direction.y*radius2*1.0;\nfloat dist_amount=clamp(distortion*0.23,0.0,1.0);\ndist_coords=mix(coords,dist_coords,dist_amount);\nreturn dist_coords;\n}\n\nfloat sampleScreen(inout vec4 color,const in vec2 offset,const in float weight) {\n\nvec2 coords=distorted_coords;\nfloat angle=rand(coords*100.0).x*TWOPI;\ncoords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));\ncolor+=texture2D(textureSampler,coords)*weight;\nreturn weight;\n}\n\nfloat getBlurLevel(float size) {\nreturn min(3.0,ceil(size/1.0));\n}\n\nvec4 getBlurColor(float size) {\nvec4 col=texture2D(textureSampler,distorted_coords);\nif (size == 0.0) { return col; }\n\n\nfloat blur_level=getBlurLevel(size);\nfloat w=(size/screen_width);\nfloat h=(size/screen_height);\nfloat total_weight=1.0;\nvec2 sample_coords;\ntotal_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);\ntotal_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);\ntotal_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);\ntotal_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);\ntotal_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);\ntotal_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);\ntotal_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);\ntotal_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);\ntotal_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);\nif (blur_level>1.0) {\ntotal_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);\ntotal_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);\ntotal_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);\ntotal_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);\ntotal_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);\ntotal_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);\ntotal_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);\ntotal_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);\ntotal_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);\n}\nif (blur_level>2.0) {\ntotal_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);\ntotal_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);\ntotal_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);\ntotal_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);\ntotal_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);\ntotal_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);\ntotal_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);\ntotal_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);\ntotal_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);\n}\ncol/=total_weight; \n\nif (darken>0.0) {\ncol.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);\n}\n\n\n\n\nreturn col;\n}\nvoid main(void)\n{\n\ncentered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nradius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;\nradius=sqrt(radius2);\ndistorted_coords=getDistortedCoords(vUV); \nvec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); \nfloat depth=texture2D(depthSampler,distorted_coords).r; \nfloat distance=near+(far-near)*depth; \nvec4 color=texture2D(textureSampler,vUV); \n\n\nfloat coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));\n\nif (dof_enabled == false || coc<0.07) { coc=0.0; }\n\nfloat edge_blur_amount=0.0;\nif (edge_blur>0.0) {\nedge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;\n}\n\nfloat blur_amount=max(edge_blur_amount,coc);\n\nif (blur_amount == 0.0) {\ngl_FragColor=texture2D(textureSampler,distorted_coords);\n}\nelse {\n\ngl_FragColor=getBlurColor(blur_amount*1.7);\n\nif (highlights) {\ngl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;\n}\nif (blur_noise) {\n\nvec2 noise=rand(distorted_coords)*0.01*blur_amount;\nvec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);\ngl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;\n}\n}\n\nif (grain_amount>0.0) {\nvec4 grain_color=texture2D(grainSampler,texels_coords*0.003);\ngl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;\n}\n}\n","displayPassPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D passSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(passSampler,vUV);\n}","ellipse2dPixelShader":"varying vec4 vColor;\nvoid main(void) {\ngl_FragColor=vColor;\n}","ellipse2dVertexShader":"\n#ifdef Instanced\n#define att attribute\n#else\n#define att uniform\n#endif\nattribute float index;\natt vec2 zBias;\natt vec4 transformX;\natt vec4 transformY;\natt float opacity;\n#ifdef Border\natt float borderThickness;\n#endif\n#ifdef FillSolid\natt vec4 fillSolidColor;\n#endif\n#ifdef BorderSolid\natt vec4 borderSolidColor;\n#endif\n#ifdef FillGradient\natt vec4 fillGradientColor1;\natt vec4 fillGradientColor2;\natt vec4 fillGradientTY;\n#endif\n#ifdef BorderGradient\natt vec4 borderGradientColor1;\natt vec4 borderGradientColor2;\natt vec4 borderGradientTY;\n#endif\n\natt vec3 properties;\n#define TWOPI 6.28318530\n\nvarying vec2 vUV;\nvarying vec4 vColor;\nvoid main(void) {\nvec2 pos2;\n#ifdef Border\nfloat w=properties.x;\nfloat h=properties.y;\nfloat ms=properties.z;\nvec2 borderOffset=vec2(1.0,1.0);\nfloat segi=index;\nif (index<ms) {\nborderOffset=vec2(1.0-(borderThickness*2.0/w),1.0-(borderThickness*2.0/h));\n}\nelse {\nsegi-=ms;\n}\nfloat angle=TWOPI*segi/ms;\npos2.x=(cos(angle)/2.0)+0.5;\npos2.y=(sin(angle)/2.0)+0.5;\npos2.x=((pos2.x-0.5)*borderOffset.x)+0.5;\npos2.y=((pos2.y-0.5)*borderOffset.y)+0.5;\n#else\nif (index == 0.0) {\npos2=vec2(0.5,0.5);\n}\nelse {\nfloat ms=properties.z;\nfloat angle=TWOPI*(index-1.0)/ms;\npos2.x=(cos(angle)/2.0)+0.5;\npos2.y=(sin(angle)/2.0)+0.5;\n}\n#endif\n#ifdef FillSolid\nvColor=fillSolidColor;\n#endif\n#ifdef BorderSolid\nvColor=borderSolidColor;\n#endif\n#ifdef FillGradient\nfloat v=dot(vec4(pos2.xy,1,1),fillGradientTY);\nvColor=mix(fillGradientColor2,fillGradientColor1,v); \n#endif\n#ifdef BorderGradient\nfloat v=dot(vec4(pos2.xy,1,1),borderGradientTY);\nvColor=mix(borderGradientColor2,borderGradientColor1,v); \n#endif\nvColor.a*=opacity;\nvec4 pos;\npos.xy=pos2.xy*properties.xy;\npos.z=1.0;\npos.w=1.0;\ngl_Position=vec4(dot(pos,transformX),dot(pos,transformY),zBias.x,1);\n}","filterPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform mat4 kernelMatrix;\nvoid main(void)\n{\nvec3 baseColor=texture2D(textureSampler,vUV).rgb;\nvec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;\ngl_FragColor=vec4(updatedColor,1.0);\n}","fxaaPixelShader":"#define FXAA_REDUCE_MIN (1.0/128.0)\n#define FXAA_REDUCE_MUL (1.0/8.0)\n#define FXAA_SPAN_MAX 8.0\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 texelSize;\nvoid main(){\nvec2 localTexelSize=texelSize;\nvec4 rgbNW=texture2D(textureSampler,(vUV+vec2(-1.0,-1.0)*localTexelSize));\nvec4 rgbNE=texture2D(textureSampler,(vUV+vec2(1.0,-1.0)*localTexelSize));\nvec4 rgbSW=texture2D(textureSampler,(vUV+vec2(-1.0,1.0)*localTexelSize));\nvec4 rgbSE=texture2D(textureSampler,(vUV+vec2(1.0,1.0)*localTexelSize));\nvec4 rgbM=texture2D(textureSampler,vUV);\nvec4 luma=vec4(0.299,0.587,0.114,1.0);\nfloat lumaNW=dot(rgbNW,luma);\nfloat lumaNE=dot(rgbNE,luma);\nfloat lumaSW=dot(rgbSW,luma);\nfloat lumaSE=dot(rgbSE,luma);\nfloat lumaM=dot(rgbM,luma);\nfloat lumaMin=min(lumaM,min(min(lumaNW,lumaNE),min(lumaSW,lumaSE)));\nfloat lumaMax=max(lumaM,max(max(lumaNW,lumaNE),max(lumaSW,lumaSE)));\nvec2 dir=vec2(-((lumaNW+lumaNE)-(lumaSW+lumaSE)),((lumaNW+lumaSW)-(lumaNE+lumaSE)));\nfloat dirReduce=max(\n(lumaNW+lumaNE+lumaSW+lumaSE)*(0.25*FXAA_REDUCE_MUL),\nFXAA_REDUCE_MIN);\nfloat rcpDirMin=1.0/(min(abs(dir.x),abs(dir.y))+dirReduce);\ndir=min(vec2(FXAA_SPAN_MAX,FXAA_SPAN_MAX),\nmax(vec2(-FXAA_SPAN_MAX,-FXAA_SPAN_MAX),\ndir*rcpDirMin))*localTexelSize;\nvec4 rgbA=0.5*(\ntexture2D(textureSampler,vUV+dir*(1.0/3.0-0.5)) +\ntexture2D(textureSampler,vUV+dir*(2.0/3.0-0.5)));\nvec4 rgbB=rgbA*0.5+0.25*(\ntexture2D(textureSampler,vUV+dir*-0.5) +\ntexture2D(textureSampler,vUV+dir*0.5));\nfloat lumaB=dot(rgbB,luma);\nif ((lumaB<lumaMin) || (lumaB>lumaMax)) {\ngl_FragColor=rgbA;\n}\nelse {\ngl_FragColor=rgbB;\n}\n}","glowBlurPostProcessPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\n\nfloat getLuminance(vec3 color)\n{\nreturn dot(color,vec3(0.2126,0.7152,0.0722));\n}\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{\n\nvec4 texel=texture2D(textureSampler,start+texelOffset);\nbaseColor.a+=texel.a*weights[i];\n\nfloat luminance=getLuminance(baseColor.rgb);\nfloat luminanceTexel=getLuminance(texel.rgb);\nfloat choice=step(luminanceTexel,luminance);\nbaseColor.rgb=choice*baseColor.rgb+(1.0-choice)*texel.rgb;\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\n}","glowMapGenerationPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nuniform vec4 color;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragColor=color;\n}","glowMapGenerationVertexShader":"\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}","glowMapMergePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float offset;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\nbaseColor.a=abs(offset-baseColor.a);\ngl_FragColor=baseColor;\n}","glowMapMergeVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) {\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","hdrPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(GAUSSIAN_BLUR_H) || defined(GAUSSIAN_BLUR_V)\nuniform float blurOffsets[9];\nuniform float blurWeights[9];\nuniform float multiplier;\nvoid main(void) {\nvec4 color=vec4(0.0,0.0,0.0,0.0);\nfor (int i=0; i<9; i++) {\n#ifdef GAUSSIAN_BLUR_H\ncolor+=(texture2D(textureSampler,vUV+vec2(blurOffsets[i]*multiplier,0.0))*blurWeights[i]);\n#else\ncolor+=(texture2D(textureSampler,vUV+vec2(0.0,blurOffsets[i]*multiplier))*blurWeights[i]);\n#endif\n}\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nvoid main() {\nvec4 sum=texture2D(textureSampler,vUV)+texture2D(otherSampler,vUV);\nsum.a=clamp(sum.a,0.0,1.0);\ngl_FragColor=sum;\n}\n#endif\n#if defined(LUMINANCE_GENERATOR)\nuniform vec2 lumOffsets[4];\nvoid main() {\nfloat average=0.0;\nvec4 color=vec4(0.0,0.0,0.0,0.0);\nfloat maximum=-1e20;\nfor (int i=0; i<4; i++) {\ncolor=texture2D(textureSampler,vUV+lumOffsets[i]);\nfloat GreyValue=length(color.rgb);\nmaximum=max(maximum,GreyValue);\naverage+=(0.25*log(1e-5+GreyValue));\n}\naverage=exp(average);\ngl_FragColor=vec4(average,maximum,0.0,1.0);\n}\n#endif\n#if defined(DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];\nuniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLE\nvec4 pack(float value) {\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(value*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvoid main() {\nvec4 color=vec4(0.0,0.0,0.0,0.0);\nfloat average=0.0;\nfor (int i=0; i<9; i++) {\ncolor=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);\naverage+=color.r;\n}\naverage/=9.0;\n#ifndef FINAL_DOWN_SAMPLE\ngl_FragColor=vec4(average,average,0.0,1.0);\n#else\ngl_FragColor=pack(average);\n#endif\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main() {\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main() {\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(HDR)\nuniform sampler2D otherSampler;\nuniform float exposure;\nuniform float avgLuminance;\nvoid main() {\nvec4 color=texture2D(textureSampler,vUV)+texture2D(otherSampler,vUV);\nvec4 adjustedColor=color/avgLuminance*exposure;\ncolor=adjustedColor;\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n","layerPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=baseColor*color;\n}","layerVertexShader":"\nattribute vec2 position;\n\nuniform vec2 scale;\nuniform vec2 offset;\nuniform mat4 textureMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvec2 shiftedPosition=position*scale+offset;\nvUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));\ngl_Position=vec4(shiftedPosition,0.0,1.0);\n}","legacydefaultPixelShader":"#define MAP_PROJECTION 4.\n\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\n\nvarying vec3 vPositionW;\nvarying vec3 vNormalW;\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<lightFragmentDeclaration>[0..3]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform sampler2D diffuseSampler;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform sampler2D ambientSampler;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef REFLECTION\nvarying vec3 vReflectionUVW;\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\nuniform vec2 vReflectionInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform sampler2D emissiveSampler;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform sampler2D specularSampler;\n#endif\n\n#include<fresnelFunction>\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n#include<clipPlaneFragmentDeclaration>\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n\nvec3 normalW=normalize(vNormalW);\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV).rgb*vAmbientInfos.y;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\nfloat glossiness=0.;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\nglossiness=vSpecularColor.a;\n#endif\nfloat shadow=1.;\n#include<lightFragment>[0..3]\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb*vReflectionInfos.x;\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb*vReflectionInfos.x;\n#endif\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n\nfloat alpha=vDiffuseColor.a;\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef SPECULARTERM\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nspecularColor=texture2D(specularSampler,vSpecularUV).rgb*vSpecularInfos.y;\n#endif\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor,alpha);\n#include<fogFragment>\ngl_FragColor=color;\n}","legacydefaultVertexShader":"\nattribute vec3 position;\nattribute vec3 normal;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\nuniform mat4 world;\nuniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform vec2 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n\nvarying vec3 vPositionW;\nvarying vec3 vNormalW;\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<shadowsVertexDeclaration>[0..maxSimultaneousLights]\n#ifdef REFLECTION\nuniform vec3 vEyePosition;\nvarying vec3 vReflectionUVW;\nuniform mat4 reflectionMatrix;\nvec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#ifdef REFLECTIONMAP_SPHERICAL\nvec3 coords=vec3(view*vec4(worldNormal,0.0));\nreturn vec3(reflectionMatrix*vec4(coords,1.0));\n#endif\n#ifdef REFLECTIONMAP_PLANAR\nvec3 viewDir=worldPos.xyz-vEyePosition;\nvec3 coords=normalize(reflect(viewDir,worldNormal));\nreturn vec3(reflectionMatrix*vec4(coords,1));\n#endif\n#ifdef REFLECTIONMAP_CUBIC\nvec3 viewDir=worldPos.xyz-vEyePosition;\nvec3 coords=reflect(viewDir,worldNormal);\n#ifdef INVERTCUBICMAP\ncoords.y=1.0-coords.y;\n#endif\nreturn vec3(reflectionMatrix*vec4(coords,0));\n#endif\n#ifdef REFLECTIONMAP_PROJECTION\nreturn vec3(reflectionMatrix*(view*worldPos));\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nreturn position;\n#endif\n#ifdef REFLECTIONMAP_EXPLICIT\nreturn vec3(0,0,0);\n#endif\n}\n#endif\nvoid main(void) {\nmat4 finalWorld=world;\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef DIFFUSE\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef AMBIENT\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef OPACITY\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef REFLECTION\nvReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),vNormalW);\n#endif\n#ifdef EMISSIVE\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef BUMP\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n}","legacypbrPixelShader":"precision mediump float;\n\n#define RECIPROCAL_PI2 0.15915494\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vAlbedoColor;\nuniform vec3 vReflectionColor;\n\nuniform vec4 vLightingIntensity;\nuniform vec4 vCameraInfos;\n#ifdef OVERLOADEDVALUES\nuniform vec4 vOverloadedIntensity;\nuniform vec3 vOverloadedAmbient;\nuniform vec3 vOverloadedAlbedo;\nuniform vec3 vOverloadedReflectivity;\nuniform vec3 vOverloadedEmissive;\nuniform vec3 vOverloadedReflection;\nuniform vec3 vOverloadedMicroSurface;\n#endif\n#ifdef OVERLOADEDSHADOWVALUES\nuniform vec4 vOverloadedShadowIntensity;\n#endif\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<lightFragmentDeclaration>[0..maxSimultaneousLights]\n\n#ifdef ALBEDO\nvarying vec2 vAlbedoUV;\nuniform sampler2D albedoSampler;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform sampler2D ambientSampler;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform vec2 vLightmapInfos;\nuniform sampler2D lightmapSampler;\n#endif\n#if defined(REFLECTIVITY)\nvarying vec2 vReflectivityUV;\nuniform vec2 vReflectivityInfos;\nuniform sampler2D reflectivitySampler;\n#endif\n#include<clipPlaneFragmentDeclaration>\n#ifdef CAMERACOLORGRADING\nuniform sampler2D cameraColorGrading2DSampler;\nuniform vec4 vCameraColorGradingInfos;\nuniform vec4 vCameraColorGradingScaleOffset;\n#endif\n\n#include<pbrFunctions>\n#include<harmonicsFunctions>\n#include<pbrLightFunctions>\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 surfaceAlbedo=vec4(1.,1.,1.,1.);\nvec3 surfaceAlbedoContribution=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nsurfaceAlbedo=texture2D(albedoSampler,vAlbedoUV);\nsurfaceAlbedo=vec4(toLinearSpace(surfaceAlbedo.rgb),surfaceAlbedo.a);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#ifdef ALPHAFROMALBEDO\nalpha*=surfaceAlbedo.a;\n#endif\nsurfaceAlbedo.rgb*=vAlbedoInfos.y;\n#else\n\nsurfaceAlbedo.rgb=surfaceAlbedoContribution;\nsurfaceAlbedoContribution=vec3(1.,1.,1.);\n#endif\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n#ifdef OVERLOADEDVALUES\nsurfaceAlbedo.rgb=mix(surfaceAlbedo.rgb,vOverloadedAlbedo,vOverloadedIntensity.y);\n#endif\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\n\nvec3 ambientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nambientColor=texture2D(ambientSampler,vAmbientUV).rgb*vAmbientInfos.y;\n#ifdef OVERLOADEDVALUES\nambientColor.rgb=mix(ambientColor.rgb,vOverloadedAmbient,vOverloadedIntensity.x);\n#endif\n#endif\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef OVERLOADEDVALUES\nsurfaceReflectivityColor.rgb=mix(surfaceReflectivityColor.rgb,vOverloadedReflectivity,vOverloadedIntensity.z);\n#endif\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV);\nsurfaceReflectivityColor=surfaceReflectivityColorMap.rgb;\nsurfaceReflectivityColor=toLinearSpace(surfaceReflectivityColor);\n#ifdef OVERLOADEDVALUES\nsurfaceReflectivityColor=mix(surfaceReflectivityColor,vOverloadedReflectivity,vOverloadedIntensity.z);\n#endif\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface=surfaceReflectivityColorMap.a;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#endif\n#endif\n#ifdef OVERLOADEDVALUES\nmicroSurface=mix(microSurface,vOverloadedMicroSurface.x,vOverloadedMicroSurface.y);\n#endif\n\nfloat NdotV=max(0.00000000001,dot(normalW,viewDirectionW));\n\nmicroSurface=clamp(microSurface,0.,1.)*0.98;\n\nfloat roughness=clamp(1.-microSurface,0.000001,1.0);\n\nvec3 lightDiffuseContribution=vec3(0.,0.,0.);\n#ifdef OVERLOADEDSHADOWVALUES\nvec3 shadowedOnlyLightDiffuseContribution=vec3(1.,1.,1.);\n#endif\n#ifdef SPECULARTERM\nvec3 lightSpecularContribution= vec3(0.,0.,0.);\n#endif\nfloat notShadowLevel=1.; \nfloat NdotL=-1.;\nlightingInfo info;\n#include<pbrLightFunctionsCall>[0..maxSimultaneousLights]\n#ifdef SPECULARTERM\nlightSpecularContribution*=vLightingIntensity.w;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n\nvec3 environmentRadiance=vReflectionColor.rgb;\nvec3 environmentIrradiance=vReflectionColor.rgb;\n#ifdef OVERLOADEDVALUES\nenvironmentIrradiance=mix(environmentIrradiance,vOverloadedReflection,vOverloadedMicroSurface.z);\nenvironmentRadiance=mix(environmentRadiance,vOverloadedReflection,vOverloadedMicroSurface.z);\n#endif\nenvironmentRadiance*=vLightingIntensity.z;\nenvironmentIrradiance*=vLightingIntensity.z;\n\nvec3 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0);\nvec3 specularEnvironmentReflectance=FresnelSchlickEnvironmentGGX(clamp(NdotV,0.,1.),specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\nenvironmentRadiance*=specularEnvironmentReflectance;\n\nvec3 surfaceEmissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV).rgb;\nsurfaceEmissiveColor=toLinearSpace(emissiveColorTex.rgb)*surfaceEmissiveColor*vEmissiveInfos.y;\n#endif\n#ifdef OVERLOADEDVALUES\nsurfaceEmissiveColor=mix(surfaceEmissiveColor,vOverloadedEmissive,vOverloadedIntensity.w);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=max(lightDiffuseContribution*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#ifdef OVERLOADEDSHADOWVALUES\nshadowedOnlyLightDiffuseContribution=max(shadowedOnlyLightDiffuseContribution*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#endif\n#else\n#ifdef LINKEMISSIVEWITHALBEDO\nvec3 finalDiffuse=max((lightDiffuseContribution+surfaceEmissiveColor)*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#ifdef OVERLOADEDSHADOWVALUES\nshadowedOnlyLightDiffuseContribution=max((shadowedOnlyLightDiffuseContribution+surfaceEmissiveColor)*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#endif\n#else\nvec3 finalDiffuse=max(lightDiffuseContribution*surfaceAlbedoContribution+surfaceEmissiveColor+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#ifdef OVERLOADEDSHADOWVALUES\nshadowedOnlyLightDiffuseContribution=max(shadowedOnlyLightDiffuseContribution*surfaceAlbedoContribution+surfaceEmissiveColor+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#endif\n#endif\n#endif\n#ifdef OVERLOADEDSHADOWVALUES\nfinalDiffuse=mix(finalDiffuse,shadowedOnlyLightDiffuseContribution,(1.0-vOverloadedShadowIntensity.y));\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=lightSpecularContribution*surfaceReflectivityColor;\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+getLuminance(finalSpecular),0.,1.);\n#endif\n#ifdef RADIANCEOVERALPHA\nalpha=clamp(alpha+getLuminance(environmentRadiance),0.,1.);\n#endif\n\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 finalColor=vec4(finalDiffuse*ambientColor*vLightingIntensity.x+surfaceAlbedo.rgb*environmentIrradiance+finalSpecular*vLightingIntensity.x+environmentRadiance+surfaceEmissiveColor*vLightingIntensity.y,alpha);\n#else\nvec4 finalColor=vec4(finalDiffuse*ambientColor*vLightingIntensity.x+surfaceAlbedo.rgb*environmentIrradiance+finalSpecular*vLightingIntensity.x+environmentRadiance,alpha);\n#endif\nfinalColor=max(finalColor,0.0);\n#ifdef CAMERATONEMAP\nfinalColor.rgb=toneMaps(finalColor.rgb);\n#endif\nfinalColor.rgb=toGammaSpace(finalColor.rgb);\n#ifdef CAMERACONTRAST\nfinalColor=contrasts(finalColor);\n#endif\nfinalColor.rgb=clamp(finalColor.rgb,0.,1.);\n#ifdef CAMERACOLORGRADING\nfinalColor=colorGrades(finalColor,cameraColorGrading2DSampler,vCameraColorGradingInfos,vCameraColorGradingScaleOffset);\n#endif\ngl_FragColor=finalColor;\n}","legacypbrVertexShader":"precision mediump float;\n\nattribute vec3 position;\nattribute vec3 normal;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\nuniform mat4 world;\nuniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef ALBEDO\nvarying vec2 vAlbedoUV;\nuniform mat4 albedoMatrix;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#if defined(REFLECTIVITY)\nvarying vec2 vReflectivityUV;\nuniform vec2 vReflectivityInfos;\nuniform mat4 reflectivityMatrix;\n#endif\n\nvarying vec3 vPositionW;\nvarying vec3 vNormalW;\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<clipPlaneVertexDeclaration>\nvoid main(void) {\nmat4 finalWorld=world;\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef ALBEDO\nif (vAlbedoInfos.x == 0.)\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef AMBIENT\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef OPACITY\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef EMISSIVE\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(REFLECTIVITY)\nif (vReflectivityInfos.x == 0.)\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<clipPlaneVertex>\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n}","lensFlarePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\ngl_FragColor=baseColor*color;\n}","lensFlareVertexShader":"\nattribute vec2 position;\n\nuniform mat4 viewportMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=position*madd+madd;\ngl_Position=viewportMatrix*vec4(position,0.0,1.0);\n}","lensHighlightsPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float gain;\nuniform float threshold;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\n\nvec4 highlightColor(vec4 color) {\nvec4 highlight=color;\nfloat luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));\nfloat lum_threshold;\nif (threshold>1.0) { lum_threshold=0.94+0.01*threshold; }\nelse { lum_threshold=0.5+0.44*threshold; }\nluminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);\nhighlight*=luminance*gain;\nhighlight.a=1.0;\nreturn highlight;\n}\nvoid main(void)\n{\nvec4 original=texture2D(textureSampler,vUV);\n\nif (gain == -1.0) {\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nreturn;\n}\nfloat w=2.0/screen_width;\nfloat h=2.0/screen_height;\nfloat weight=1.0;\n\nvec4 blurred=vec4(0.0,0.0,0.0,0.0);\n#ifdef PENTAGON\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h)));\n#else\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h)));\n#endif\nblurred/=39.0;\ngl_FragColor=blurred;\n\n}","linePixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","lineVertexShader":"\nattribute vec3 position;\nattribute vec4 normal;\n\nuniform mat4 worldViewProjection;\nuniform float width;\nuniform float aspectRatio;\nvoid main(void) {\nvec4 viewPosition=worldViewProjection*vec4(position,1.0);\nvec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);\nvec2 currentScreen=viewPosition.xy/viewPosition.w;\nvec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;\ncurrentScreen.x*=aspectRatio;\nnextScreen.x*=aspectRatio;\nvec2 dir=normalize(nextScreen-currentScreen);\nvec2 normalDir=vec2(-dir.y,dir.x);\nnormalDir*=width/2.0;\nnormalDir.x/=aspectRatio;\nvec4 offset=vec4(normalDir*normal.w,0.0,0.0);\ngl_Position=viewPosition+offset;\n}","lines2dPixelShader":"varying vec4 vColor;\nvoid main(void) {\ngl_FragColor=vColor;\n}","lines2dVertexShader":"\n#ifdef Instanced\n#define att attribute\n#else\n#define att uniform\n#endif\nattribute vec2 position;\natt vec2 zBias;\natt vec4 transformX;\natt vec4 transformY;\natt float opacity;\n#ifdef FillSolid\natt vec4 fillSolidColor;\n#endif\n#ifdef BorderSolid\natt vec4 borderSolidColor;\n#endif\n#ifdef FillGradient\natt vec2 boundingMin;\natt vec2 boundingMax;\natt vec4 fillGradientColor1;\natt vec4 fillGradientColor2;\natt vec4 fillGradientTY;\n#endif\n#ifdef BorderGradient\natt vec4 borderGradientColor1;\natt vec4 borderGradientColor2;\natt vec4 borderGradientTY;\n#endif\n#define TWOPI 6.28318530\n\nvarying vec2 vUV;\nvarying vec4 vColor;\nvoid main(void) {\n#ifdef FillSolid\nvColor=fillSolidColor;\n#endif\n#ifdef BorderSolid\nvColor=borderSolidColor;\n#endif\n#ifdef FillGradient\nfloat v=dot(vec4((position.xy-boundingMin)/(boundingMax-boundingMin),1,1),fillGradientTY);\nvColor=mix(fillGradientColor2,fillGradientColor1,v); \n#endif\n#ifdef BorderGradient\nfloat v=dot(vec4((position.xy-boundingMin)/(boundingMax-boundingMin),1,1),borderGradientTY);\nvColor=mix(borderGradientColor2,borderGradientColor1,v); \n#endif\nvColor.a*=opacity;\nvec4 pos;\npos.xy=position.xy;\npos.z=1.0;\npos.w=1.0;\ngl_Position=vec4(dot(pos,transformX),dot(pos,transformY),zBias.x,1);\n}","outlinePixelShader":"uniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void) {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragColor=color;\n}","outlineVertexShader":"\nattribute vec3 position;\nattribute vec3 normal;\n#include<bonesDeclaration>\n\nuniform float offset;\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\nvec3 offsetPosition=position+normal*offset;\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(offsetPosition,1.0);\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}\n","particlesPixelShader":"\nvarying vec2 vUV;\nvarying vec4 vColor;\nuniform vec4 textureMask;\nuniform sampler2D diffuseSampler;\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\nvoid main(void) {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif\nvec4 baseColor=texture2D(diffuseSampler,vUV);\ngl_FragColor=(baseColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;\n}","particlesVertexShader":"\nattribute vec3 position;\nattribute vec4 color;\nattribute vec4 options;\n\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nvarying float fClipDistance;\n#endif\nvoid main(void) { \nvec3 viewPos=(view*vec4(position,1.0)).xyz; \nvec3 cornerPos;\nfloat size=options.y;\nfloat angle=options.x;\nvec2 offset=options.zw;\ncornerPos=vec3(offset.x-0.5,offset.y-0.5,0.)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \nvColor=color;\nvUV=offset;\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*vec4(viewPos,1.0);\nfClipDistance=dot(worldPos,vClipPlane);\n#endif\n}","passPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\n}","pbrPixelShader":"#ifdef BUMP\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LODBASEDMICROSFURACE\n#extension GL_EXT_shader_texture_lod : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nprecision highp float;\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\n\nuniform vec4 vLightingIntensity;\nuniform vec4 vCameraInfos;\n#ifdef OVERLOADEDVALUES\nuniform vec4 vOverloadedIntensity;\nuniform vec3 vOverloadedAmbient;\nuniform vec3 vOverloadedAlbedo;\nuniform vec3 vOverloadedReflectivity;\nuniform vec3 vOverloadedEmissive;\nuniform vec3 vOverloadedReflection;\nuniform vec3 vOverloadedMicroSurface;\n#endif\n#ifdef OVERLOADEDSHADOWVALUES\nuniform vec4 vOverloadedShadowIntensity;\n#endif\n#if defined(REFLECTION) || defined(REFRACTION)\nuniform vec2 vMicrosurfaceTextureLods;\n#endif\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<lightFragmentDeclaration>[0..maxSimultaneousLights]\n\n#ifdef ALBEDO\nvarying vec2 vAlbedoUV;\nuniform sampler2D albedoSampler;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform sampler2D ambientSampler;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform vec2 vLightmapInfos;\nuniform sampler2D lightmapSampler;\n#endif\n#if defined(REFLECTIVITY)\nvarying vec2 vReflectivityUV;\nuniform vec2 vReflectivityInfos;\nuniform sampler2D reflectivitySampler;\n#endif\n\n#include<fresnelFunction>\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\nuniform mat4 refractionMatrix;\n#endif\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvarying vec3 vDirectionW;\n#endif\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#ifdef CAMERACOLORGRADING\n#include<colorGradingDefinition>\n#endif\n#ifdef CAMERACOLORCURVES\n#include<colorCurvesDefinition>\n#endif\n\n#include<pbrShadowFunctions>\n#include<pbrFunctions>\n#ifdef CAMERACOLORGRADING\n#include<colorGrading>\n#endif\n#ifdef CAMERACOLORCURVES\n#include<colorCurves>\n#endif\n#include<harmonicsFunctions>\n#include<pbrLightFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 surfaceAlbedo=vec4(1.,1.,1.,1.);\nvec3 surfaceAlbedoContribution=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nsurfaceAlbedo=texture2D(albedoSampler,vAlbedoUV);\nsurfaceAlbedo=vec4(toLinearSpace(surfaceAlbedo.rgb),surfaceAlbedo.a);\n#ifndef LINKREFRACTIONTOTRANSPARENCY\n#ifdef ALPHATEST\nif (surfaceAlbedo.a<0.4)\ndiscard;\n#endif\n#endif\n#ifdef ALPHAFROMALBEDO\nalpha*=surfaceAlbedo.a;\n#endif\nsurfaceAlbedo.rgb*=vAlbedoInfos.y;\n#else\n\nsurfaceAlbedo.rgb=surfaceAlbedoContribution;\nsurfaceAlbedoContribution=vec3(1.,1.,1.);\n#endif\n#ifdef VERTEXCOLOR\nsurfaceAlbedo.rgb*=vColor.rgb;\n#endif\n#ifdef OVERLOADEDVALUES\nsurfaceAlbedo.rgb=mix(surfaceAlbedo.rgb,vOverloadedAlbedo,vOverloadedIntensity.y);\n#endif\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\n#include<bumpFragment>\n\nvec3 ambientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nambientColor=texture2D(ambientSampler,vAmbientUV).rgb*vAmbientInfos.y;\n#ifdef OVERLOADEDVALUES\nambientColor.rgb=mix(ambientColor.rgb,vOverloadedAmbient,vOverloadedIntensity.x);\n#endif\n#endif\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef OVERLOADEDVALUES\nsurfaceReflectivityColor.rgb=mix(surfaceReflectivityColor.rgb,vOverloadedReflectivity,vOverloadedIntensity.z);\n#endif\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV);\nsurfaceReflectivityColor=surfaceReflectivityColorMap.rgb;\nsurfaceReflectivityColor=toLinearSpace(surfaceReflectivityColor);\n#ifdef OVERLOADEDVALUES\nsurfaceReflectivityColor=mix(surfaceReflectivityColor,vOverloadedReflectivity,vOverloadedIntensity.z);\n#endif\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface=surfaceReflectivityColorMap.a;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#endif\n#endif\n#ifdef OVERLOADEDVALUES\nmicroSurface=mix(microSurface,vOverloadedMicroSurface.x,vOverloadedMicroSurface.y);\n#endif\n\nfloat NdotV=max(0.00000000001,dot(normalW,viewDirectionW));\n\nmicroSurface=clamp(microSurface,0.,1.)*0.98;\n\nfloat roughness=clamp(1.-microSurface,0.000001,1.0);\n\nvec3 lightDiffuseContribution=vec3(0.,0.,0.);\n#ifdef OVERLOADEDSHADOWVALUES\nvec3 shadowedOnlyLightDiffuseContribution=vec3(1.,1.,1.);\n#endif\n#ifdef SPECULARTERM\nvec3 lightSpecularContribution=vec3(0.,0.,0.);\n#endif\nfloat notShadowLevel=1.; \n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV).rgb*vLightmapInfos.y;\n#endif\nfloat NdotL=-1.;\nlightingInfo info;\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\n\n\nfloat reflectance90=clamp(reflectance*25.0,0.0,1.0);\nvec3 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0)*reflectance90;\n#include<pbrLightFunctionsCall>[0..maxSimultaneousLights]\n#ifdef SPECULARTERM\nlightSpecularContribution*=vLightingIntensity.w;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 surfaceRefractionColor=vec3(0.,0.,0.);\n\n#ifdef LODBASEDMICROSFURACE\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\n#endif\n#ifdef REFRACTION\nvec3 refractionVector=refract(-viewDirectionW,normalW,vRefractionInfos.y);\n#ifdef LODBASEDMICROSFURACE\n#ifdef USEPMREMREFRACTION\nfloat lodRefraction=getMipMapIndexFromAverageSlopeWithPMREM(vMicrosurfaceTextureLods.y,alphaG);\n#else\nfloat lodRefraction=getMipMapIndexFromAverageSlope(vMicrosurfaceTextureLods.y,alphaG);\n#endif\n#else\nfloat biasRefraction=(vMicrosurfaceTextureLods.y+2.)*(1.0-microSurface);\n#endif\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0)\n{\n#ifdef LODBASEDMICROSFURACE\n#ifdef USEPMREMREFRACTION\n\nif ((vMicrosurfaceTextureLods.y-lodRefraction)>4.0)\n{\n\nfloat scaleRefraction=1.-exp2(lodRefraction)/exp2(vMicrosurfaceTextureLods.y); \nfloat maxRefraction=max(max(abs(refractionVector.x),abs(refractionVector.y)),abs(refractionVector.z));\nif (abs(refractionVector.x) != maxRefraction) refractionVector.x*=scaleRefraction;\nif (abs(refractionVector.y) != maxRefraction) refractionVector.y*=scaleRefraction;\nif (abs(refractionVector.z) != maxRefraction) refractionVector.z*=scaleRefraction;\n}\n#endif\nsurfaceRefractionColor=textureCubeLodEXT(refractionCubeSampler,refractionVector,lodRefraction).rgb*vRefractionInfos.x;\n#else\nsurfaceRefractionColor=textureCube(refractionCubeSampler,refractionVector,biasRefraction).rgb*vRefractionInfos.x;\n#endif\n}\n#ifndef REFRACTIONMAPINLINEARSPACE\nsurfaceRefractionColor=toLinearSpace(surfaceRefractionColor.rgb);\n#endif\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\n#ifdef LODBASEDMICROSFURACE\nsurfaceRefractionColor=texture2DLodEXT(refraction2DSampler,refractionCoords,lodRefraction).rgb*vRefractionInfos.x;\n#else\nsurfaceRefractionColor=texture2D(refraction2DSampler,refractionCoords,biasRefraction).rgb*vRefractionInfos.x;\n#endif \nsurfaceRefractionColor=toLinearSpace(surfaceRefractionColor.rgb);\n#endif\n#endif\n\nvec3 environmentRadiance=vReflectionColor.rgb;\nvec3 environmentIrradiance=vReflectionColor.rgb;\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef LODBASEDMICROSFURACE\n#ifdef USEPMREMREFLECTION\nfloat lodReflection=getMipMapIndexFromAverageSlopeWithPMREM(vMicrosurfaceTextureLods.x,alphaG);\n#else\nfloat lodReflection=getMipMapIndexFromAverageSlope(vMicrosurfaceTextureLods.x,alphaG);\n#endif\n#else\nfloat biasReflection=(vMicrosurfaceTextureLods.x+2.)*(1.0-microSurface);\n#endif\n#ifdef REFLECTIONMAP_3D\n#ifdef LODBASEDMICROSFURACE\n#ifdef USEPMREMREFLECTION\n\nif ((vMicrosurfaceTextureLods.y-lodReflection)>4.0)\n{\n\nfloat scaleReflection=1.-exp2(lodReflection)/exp2(vMicrosurfaceTextureLods.x); \nfloat maxReflection=max(max(abs(vReflectionUVW.x),abs(vReflectionUVW.y)),abs(vReflectionUVW.z));\nif (abs(vReflectionUVW.x) != maxReflection) vReflectionUVW.x*=scaleReflection;\nif (abs(vReflectionUVW.y) != maxReflection) vReflectionUVW.y*=scaleReflection;\nif (abs(vReflectionUVW.z) != maxReflection) vReflectionUVW.z*=scaleReflection;\n}\n#endif\nenvironmentRadiance=textureCubeLodEXT(reflectionCubeSampler,vReflectionUVW,lodReflection).rgb*vReflectionInfos.x;\n#else\nenvironmentRadiance=textureCube(reflectionCubeSampler,vReflectionUVW,biasReflection).rgb*vReflectionInfos.x;\n#endif\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#ifndef REFLECTIONMAP_SKYBOX\nvec3 normalEnvironmentSpace=(reflectionMatrix*vec4(normalW,1)).xyz;\nenvironmentIrradiance=EnvironmentIrradiance(normalEnvironmentSpace);\n#endif\n#else\nenvironmentRadiance=toLinearSpace(environmentRadiance.rgb);\nenvironmentIrradiance=textureCube(reflectionCubeSampler,normalW,20.).rgb*vReflectionInfos.x;\nenvironmentIrradiance=toLinearSpace(environmentIrradiance.rgb);\nenvironmentIrradiance*=0.2; \n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\n#ifdef LODBASEDMICROSFURACE\nenvironmentRadiance=texture2DLodEXT(reflection2DSampler,coords,lodReflection).rgb*vReflectionInfos.x;\n#else\nenvironmentRadiance=texture2D(reflection2DSampler,coords,biasReflection).rgb*vReflectionInfos.x;\n#endif\nenvironmentRadiance=toLinearSpace(environmentRadiance.rgb);\nenvironmentIrradiance=texture2D(reflection2DSampler,coords,20.).rgb*vReflectionInfos.x;\nenvironmentIrradiance=toLinearSpace(environmentIrradiance.rgb);\n#endif\n#endif\n#ifdef OVERLOADEDVALUES\nenvironmentIrradiance=mix(environmentIrradiance,vOverloadedReflection,vOverloadedMicroSurface.z);\nenvironmentRadiance=mix(environmentRadiance,vOverloadedReflection,vOverloadedMicroSurface.z);\n#endif\nenvironmentRadiance*=vLightingIntensity.z;\nenvironmentIrradiance*=vLightingIntensity.z;\n\nvec3 specularEnvironmentReflectance=FresnelSchlickEnvironmentGGX(clamp(NdotV,0.,1.),specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n\nvec3 refractance=vec3(0.0,0.0,0.0);\n#ifdef REFRACTION\nvec3 transmission=vec3(1.0,1.0,1.0);\n#ifdef LINKREFRACTIONTOTRANSPARENCY\n\ntransmission*=(1.0-alpha);\n\n\nvec3 mixedAlbedo=surfaceAlbedoContribution.rgb*surfaceAlbedo.rgb;\nfloat maxChannel=max(max(mixedAlbedo.r,mixedAlbedo.g),mixedAlbedo.b);\nvec3 tint=clamp(maxChannel*mixedAlbedo,0.0,1.0);\n\nsurfaceAlbedoContribution*=alpha;\n\nenvironmentIrradiance*=alpha;\n\nsurfaceRefractionColor*=tint;\n\nalpha=1.0;\n#endif\n\nvec3 bounceSpecularEnvironmentReflectance=(2.0*specularEnvironmentReflectance)/(1.0+specularEnvironmentReflectance);\nspecularEnvironmentReflectance=mix(bounceSpecularEnvironmentReflectance,specularEnvironmentReflectance,alpha);\n\ntransmission*=1.0-specularEnvironmentReflectance;\n\nrefractance=surfaceRefractionColor*transmission;\n#endif\n\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\nrefractance*=vLightingIntensity.z;\nenvironmentRadiance*=specularEnvironmentReflectance;\n\nvec3 surfaceEmissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV).rgb;\nsurfaceEmissiveColor=toLinearSpace(emissiveColorTex.rgb)*surfaceEmissiveColor*vEmissiveInfos.y;\n#endif\n#ifdef OVERLOADEDVALUES\nsurfaceEmissiveColor=mix(surfaceEmissiveColor,vOverloadedEmissive,vOverloadedIntensity.w);\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nsurfaceEmissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=max(lightDiffuseContribution*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#ifdef OVERLOADEDSHADOWVALUES\nshadowedOnlyLightDiffuseContribution=max(shadowedOnlyLightDiffuseContribution*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#endif\n#else\n#ifdef LINKEMISSIVEWITHALBEDO\nvec3 finalDiffuse=max((lightDiffuseContribution+surfaceEmissiveColor)*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#ifdef OVERLOADEDSHADOWVALUES\nshadowedOnlyLightDiffuseContribution=max((shadowedOnlyLightDiffuseContribution+surfaceEmissiveColor)*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#endif\n#else\nvec3 finalDiffuse=max(lightDiffuseContribution*surfaceAlbedoContribution+surfaceEmissiveColor+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#ifdef OVERLOADEDSHADOWVALUES\nshadowedOnlyLightDiffuseContribution=max(shadowedOnlyLightDiffuseContribution*surfaceAlbedoContribution+surfaceEmissiveColor+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#endif\n#endif\n#endif\n#ifdef OVERLOADEDSHADOWVALUES\nfinalDiffuse=mix(finalDiffuse,shadowedOnlyLightDiffuseContribution,(1.0-vOverloadedShadowIntensity.y));\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=lightSpecularContribution*surfaceReflectivityColor;\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+getLuminance(finalSpecular),0.,1.);\n#endif\n#ifdef RADIANCEOVERALPHA\nalpha=clamp(alpha+getLuminance(environmentRadiance),0.,1.);\n#endif\n\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 finalColor=vec4(finalDiffuse*ambientColor*vLightingIntensity.x+surfaceAlbedo.rgb*environmentIrradiance+finalSpecular*vLightingIntensity.x+environmentRadiance+surfaceEmissiveColor*vLightingIntensity.y+refractance,alpha);\n#else\nvec4 finalColor=vec4(finalDiffuse*ambientColor*vLightingIntensity.x+surfaceAlbedo.rgb*environmentIrradiance+finalSpecular*vLightingIntensity.x+environmentRadiance+refractance,alpha);\n#endif\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\nfinalColor.rgb*=lightmapColor;\n#else\nfinalColor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\nfinalColor=max(finalColor,0.0);\n#ifdef CAMERATONEMAP\nfinalColor.rgb=toneMaps(finalColor.rgb);\n#endif\nfinalColor.rgb=toGammaSpace(finalColor.rgb);\n#include<logDepthFragment>\n#include<fogFragment>(color,finalColor)\n#ifdef CAMERACONTRAST\nfinalColor=contrasts(finalColor);\n#endif\nfinalColor.rgb=clamp(finalColor.rgb,0.,1.);\n#ifdef CAMERACOLORGRADING\nfinalColor=colorGrades(finalColor);\n#endif\n#ifdef CAMERACOLORCURVES\nfinalColor.rgb=applyColorCurves(finalColor.rgb);\n#endif\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\ngl_FragColor=finalColor;\n}","pbrVertexShader":"precision highp float;\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef ALBEDO\nvarying vec2 vAlbedoUV;\nuniform mat4 albedoMatrix;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(REFLECTIVITY)\nvarying vec2 vReflectivityUV;\nuniform vec2 vReflectivityInfos;\nuniform mat4 reflectivityMatrix;\n#endif\n#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<shadowsVertexDeclaration>[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=position;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef ALBEDO\nif (vAlbedoInfos.x == 0.)\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef AMBIENT\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef OPACITY\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef EMISSIVE\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef LIGHTMAP\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(REFLECTIVITY)\nif (vReflectivityInfos.x == 0.)\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef BUMP\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n\n#include<logDepthVertex>\n}","postprocessVertexShader":"\nattribute vec2 position;\nuniform vec2 scale;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd)*scale;\ngl_Position=vec4(position,0.0,1.0);\n}","proceduralVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvPosition=position;\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","rect2dPixelShader":"varying vec4 vColor;\nvoid main(void) {\ngl_FragColor=vColor;\n}","rect2dVertexShader":"\n#ifdef Instanced\n#define att attribute\n#else\n#define att uniform\n#endif\nattribute float index;\natt vec2 zBias;\natt vec4 transformX;\natt vec4 transformY;\natt float opacity;\n#ifdef Border\natt float borderThickness;\n#endif\n#ifdef FillSolid\natt vec4 fillSolidColor;\n#endif\n#ifdef BorderSolid\natt vec4 borderSolidColor;\n#endif\n#ifdef FillGradient\natt vec4 fillGradientColor1;\natt vec4 fillGradientColor2;\natt vec4 fillGradientTY;\n#endif\n#ifdef BorderGradient\natt vec4 borderGradientColor1;\natt vec4 borderGradientColor2;\natt vec4 borderGradientTY;\n#endif\n\natt vec3 properties;\n\n#define rsub0 17.0\n#define rsub1 33.0\n#define rsub2 49.0\n#define rsub3 65.0\n#define rsub 64.0\n#define TWOPI 6.28318530\n\nvarying vec2 vUV;\nvarying vec4 vColor;\nvoid main(void) {\nvec2 pos2;\n\nif (properties.z == 0.0) {\n#ifdef Border\nfloat w=properties.x;\nfloat h=properties.y;\nvec2 borderOffset=vec2(1.0,1.0);\nfloat segi=index;\nif (index<4.0) {\nborderOffset=vec2(1.0-(borderThickness*2.0/w),1.0-(borderThickness*2.0/h));\n}\nelse {\nsegi-=4.0;\n}\nif (segi == 0.0) {\npos2=vec2(1.0,1.0);\n} \nelse if (segi == 1.0) {\npos2=vec2(1.0,0.0);\n}\nelse if (segi == 2.0) {\npos2=vec2(0.0,0.0);\n} \nelse {\npos2=vec2(0.0,1.0);\n}\npos2.x=((pos2.x-0.5)*borderOffset.x)+0.5;\npos2.y=((pos2.y-0.5)*borderOffset.y)+0.5;\n#else\nif (index == 0.0) {\npos2=vec2(0.5,0.5);\n}\nelse if (index == 1.0) {\npos2=vec2(1.0,1.0);\n}\nelse if (index == 2.0) {\npos2=vec2(1.0,0.0);\n}\nelse if (index == 3.0) {\npos2=vec2(0.0,0.0);\n}\nelse {\npos2=vec2(0.0,1.0);\n}\n#endif\n}\nelse\n{\n#ifdef Border\nfloat w=properties.x;\nfloat h=properties.y;\nfloat r=properties.z;\nfloat nru=r/w;\nfloat nrv=r/h;\nvec2 borderOffset=vec2(1.0,1.0);\nfloat segi=index;\nif (index<rsub) {\nborderOffset=vec2(1.0-(borderThickness*2.0/w),1.0-(borderThickness*2.0/h));\n}\nelse {\nsegi-=rsub;\n}\n\nif (segi<rsub0) {\npos2=vec2(1.0-nru,nrv);\n}\n\nelse if (segi<rsub1) {\npos2=vec2(nru,nrv);\n}\n\nelse if (segi<rsub2) {\npos2=vec2(nru,1.0-nrv);\n}\n\nelse {\npos2=vec2(1.0-nru,1.0-nrv);\n}\nfloat angle=TWOPI-((index-1.0)*TWOPI/(rsub-0.5));\npos2.x+=cos(angle)*nru;\npos2.y+=sin(angle)*nrv;\npos2.x=((pos2.x-0.5)*borderOffset.x)+0.5;\npos2.y=((pos2.y-0.5)*borderOffset.y)+0.5;\n#else\nif (index == 0.0) {\npos2=vec2(0.5,0.5);\n}\nelse {\nfloat w=properties.x;\nfloat h=properties.y;\nfloat r=properties.z;\nfloat nru=r/w;\nfloat nrv=r/h;\n\nif (index<rsub0) {\npos2=vec2(1.0-nru,nrv);\n}\n\nelse if (index<rsub1) {\npos2=vec2(nru,nrv);\n}\n\nelse if (index<rsub2) {\npos2=vec2(nru,1.0-nrv);\n}\n\nelse {\npos2=vec2(1.0-nru,1.0-nrv);\n}\nfloat angle=TWOPI-((index-1.0)*TWOPI/(rsub-0.5));\npos2.x+=cos(angle)*nru;\npos2.y+=sin(angle)*nrv;\n}\n#endif\n}\n#ifdef FillSolid\nvColor=fillSolidColor;\n#endif\n#ifdef BorderSolid\nvColor=borderSolidColor;\n#endif\n#ifdef FillGradient\nfloat v=dot(vec4(pos2.xy,1,1),fillGradientTY);\nvColor=mix(fillGradientColor2,fillGradientColor1,v); \n#endif\n#ifdef BorderGradient\nfloat v=dot(vec4(pos2.xy,1,1),borderGradientTY);\nvColor=mix(borderGradientColor2,borderGradientColor1,v); \n#endif\nvColor.a*=opacity;\nvec4 pos;\npos.xy=pos2.xy*properties.xy;\npos.z=1.0;\npos.w=1.0;\ngl_Position=vec4(dot(pos,transformX),dot(pos,transformY),zBias.x,1);\n}","refractionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\nvoid main() {\nfloat ref=1.0-texture2D(refractionSampler,vUV).r;\nvec2 uv=vUV-vec2(0.5);\nvec2 offset=uv*depth*ref;\nvec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;\ngl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);\n}","shadowMapPixelShader":"#ifndef FULLFLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n\nvec2 packHalf(float depth) \n{ \nconst vec2 bitOffset=vec2(1.0/255.,0.);\nvec2 color=vec2(depth,fract(depth*255.));\nreturn color-(color.yy*bitOffset);\n}\n#endif\nvarying vec4 vPosition;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef CUBEMAP\nuniform vec3 lightPosition;\nuniform vec2 depthValues;\n#endif\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#ifdef CUBEMAP\nvec3 directionToLight=vPosition.xyz-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth-depthValues.x)/(depthValues.y-depthValues.x);\ndepth=clamp(depth,0.,1.0);\n#else\nfloat depth=vPosition.z/vPosition.w;\ndepth=depth*0.5+0.5;\n#endif\n#ifdef VSM\nfloat moment1=depth;\nfloat moment2=moment1*moment1;\n#ifndef FULLFLOAT\ngl_FragColor=vec4(packHalf(moment1),packHalf(moment2));\n#else\ngl_FragColor=vec4(moment1,moment2,1.0,1.0);\n#endif\n#else\n#ifndef FULLFLOAT\ngl_FragColor=pack(depth);\n#else\ngl_FragColor=vec4(depth,1.0,1.0,1.0);\n#endif\n#endif\n}","shadowMapVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nvarying vec4 vPosition;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(position,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(position,1.0);\ngl_Position=vPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","sprite2dPixelShader":"varying vec2 vUV;\nvarying float vOpacity;\nuniform bool alphaTest;\nuniform sampler2D diffuseSampler;\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\nif (alphaTest)\n{\nif (color.a<0.95) {\ndiscard;\n}\n}\ncolor.a*=vOpacity;\ngl_FragColor=color;\n}","sprite2dVertexShader":"\n#ifdef Instanced\n#define att attribute\n#else\n#define att uniform\n#endif\n\nattribute float index;\natt vec2 topLeftUV;\natt vec2 sizeUV;\natt vec2 scaleFactor;\natt vec2 textureSize;\n\natt vec3 properties;\natt vec2 zBias;\natt vec4 transformX;\natt vec4 transformY;\natt float opacity;\n\n\nvarying vec2 vUV;\nvarying float vOpacity;\nvoid main(void) {\nvec2 pos2;\n\nvec2 off=vec2(0.0,0.0);\nvec2 sfSizeUV=sizeUV*scaleFactor;\nfloat frame=properties.x;\nfloat invertY=properties.y;\nfloat alignToPixel=properties.z;\n\nif (index == 0.0) {\npos2=vec2(0.0,0.0);\nvUV=vec2(topLeftUV.x+(frame*sfSizeUV.x)+off.x,topLeftUV.y-off.y);\n}\n\nelse if (index == 1.0) {\npos2=vec2(0.0,1.0);\nvUV=vec2(topLeftUV.x+(frame*sfSizeUV.x)+off.x,(topLeftUV.y+sfSizeUV.y));\n}\n\nelse if (index == 2.0) {\npos2=vec2( 1.0,1.0);\nvUV=vec2(topLeftUV.x+sfSizeUV.x+(frame*sfSizeUV.x),(topLeftUV.y+sfSizeUV.y));\n}\n\nelse if (index == 3.0) {\npos2=vec2( 1.0,0.0);\nvUV=vec2(topLeftUV.x+sfSizeUV.x+(frame*sfSizeUV.x),topLeftUV.y-off.y);\n}\nif (invertY == 1.0) {\nvUV.y=1.0-vUV.y;\n}\nvec4 pos;\nif (alignToPixel == 1.0)\n{\npos.xy=floor(pos2.xy*sizeUV*textureSize);\n} else {\npos.xy=pos2.xy*sizeUV*textureSize;\n}\nvOpacity=opacity;\npos.z=1.0;\npos.w=1.0;\ngl_Position=vec4(dot(pos,transformX),dot(pos,transformY),zBias.x,1);\n} ","spritesPixelShader":"uniform bool alphaTest;\nvarying vec4 vColor;\n\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\nif (alphaTest) \n{\nif (color.a<0.95)\ndiscard;\n}\ncolor*=vColor;\n#include<fogFragment>\ngl_FragColor=color;\n}","spritesVertexShader":"\nattribute vec4 position;\nattribute vec4 options;\nattribute vec4 cellInfo;\nattribute vec4 color;\n\nuniform vec2 textureInfos;\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#include<fogVertexDeclaration>\nvoid main(void) { \nvec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; \nvec2 cornerPos;\nfloat angle=position.w;\nvec2 size=vec2(options.x,options.y);\nvec2 offset=options.zw;\nvec2 uvScale=textureInfos.xy;\ncornerPos=vec2(offset.x-0.5,offset.y-0.5)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \n\nvColor=color;\n\nvec2 uvOffset=vec2(abs(offset.x-cellInfo.x),1.0-abs(offset.y-cellInfo.y));\nvUV=(uvOffset+cellInfo.zw)*uvScale;\n\n#ifdef FOG\nfFogDistance=viewPos.z;\n#endif\n}","ssaoPixelShader":"\nuniform sampler2D textureSampler;\nvarying vec2 vUV;\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float radius;\nuniform float area;\nuniform float fallOff;\nuniform float base;\nvec3 normalFromDepth(float depth,vec2 coords)\n{\nvec2 offset1=vec2(0.0,radius);\nvec2 offset2=vec2(radius,0.0);\nfloat depth1=texture2D(textureSampler,coords+offset1).r;\nfloat depth2=texture2D(textureSampler,coords+offset2).r;\nvec3 p1=vec3(offset1,depth1-depth);\nvec3 p2=vec3(offset2,depth2-depth);\nvec3 normal=cross(p1,p2);\nnormal.z=-normal.z;\nreturn normalize(normal);\n}\nvoid main()\n{\nvec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);\nfloat depth=texture2D(textureSampler,vUV).r;\nvec3 position=vec3(vUV,depth);\nvec3 normal=normalFromDepth(depth,vUV);\nfloat radiusDepth=radius/depth;\nfloat occlusion=0.0;\nvec3 ray;\nvec3 hemiRay;\nfloat occlusionDepth;\nfloat difference;\nfor (int i=0; i<SAMPLES; i++)\n{\nray=radiusDepth*reflect(sampleSphere[i],random);\nhemiRay=position+sign(dot(ray,normal))*ray;\nocclusionDepth=texture2D(textureSampler,clamp(hemiRay.xy,vec2(0.001,0.001),vec2(0.999,0.999))).r;\ndifference=depth-occlusionDepth;\nocclusion+=step(fallOff,difference)*(1.0-smoothstep(fallOff,area,difference));\n}\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor.r=result;\ngl_FragColor.g=result;\ngl_FragColor.b=result;\ngl_FragColor.a=1.0;\n}\n#endif\n#ifdef BILATERAL_BLUR\nuniform sampler2D depthSampler;\nuniform float outSize;\nuniform float samplerOffsets[SAMPLES];\nvoid main()\n{\nfloat texelsize=1.0/outSize;\nfloat compareDepth=texture2D(depthSampler,vUV).r;\nfloat result=0.0;\nfloat weightSum=0.0;\nfor (int i=0; i<SAMPLES; ++i)\n{\n#ifdef BILATERAL_BLUR_H\nvec2 sampleOffset=vec2(texelsize*samplerOffsets[i],0.0);\n#else\nvec2 sampleOffset=vec2(0.0,texelsize*samplerOffsets[i]);\n#endif\nvec2 samplePos=vUV+sampleOffset;\nfloat sampleDepth=texture2D(depthSampler,samplePos).r;\nfloat weight=(1.0/(0.0001+abs(compareDepth-sampleDepth)));\nresult+=texture2D(textureSampler,samplePos).r*weight;\nweightSum+=weight;\n}\nresult/=weightSum;\ngl_FragColor.rgb=vec3(result);\ngl_FragColor.a=1.0;\n}\n#endif\n","ssaoCombinePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D originalColor;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,vUV);\nvec4 sceneColor=texture2D(originalColor,vUV);\ngl_FragColor=sceneColor*ssaoColor;\n}\n","standardPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(PASS_POST_PROCESS)\nvoid main(void)\n{\nvec4 color=texture2D(textureSampler,vUV);\ngl_FragColor=color;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(GAUSSIAN_BLUR_H) || defined(GAUSSIAN_BLUR_V)\nuniform float blurOffsets[9];\nuniform float blurWeights[9];\nvoid main(void)\n{\nvec4 color=vec4(0.0,0.0,0.0,0.0);\nfor (int i=0; i<9; i++) {\n#ifdef GAUSSIAN_BLUR_H\ncolor+=(texture2D(textureSampler,vUV+vec2(blurOffsets[i]*2.0,0.0))*blurWeights[i]);\ncolor+=(texture2D(textureSampler,vUV-vec2(blurOffsets[i]*2.0,0.0))*blurWeights[i]);\n#else\ncolor+=(texture2D(textureSampler,vUV+vec2(0.0,blurOffsets[i]*2.0))*blurWeights[i]);\ncolor+=(texture2D(textureSampler,vUV-vec2(0.0,blurOffsets[i]*2.0))*blurWeights[i]);\n#endif\n}\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nuniform sampler2D lensSampler;\nuniform float exposure;\nvoid main(void)\n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\ncolour*=exposure;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\ncolour+=colour*texture2D(lensSampler,vUV).rgb;\ngl_FragColor=vec4(colour.rgb,1.0)+texture2D(otherSampler,vUV);\n}\n#endif\n#if defined(DEPTH_OF_FIELD)\nuniform sampler2D otherSampler;\nuniform sampler2D depthSampler;\nuniform float distance;\nvoid main(void)\n{\nvec4 sharp=texture2D(otherSampler,vUV);\nvec4 blur=texture2D(textureSampler,vUV);\nfloat dist=clamp(texture2D(depthSampler,vUV).r*distance,0.0,1.0);\nfloat factor=0.0;\nif (dist<0.05)\nfactor=1.0;\nelse if (dist<0.1)\nfactor=20.0*(0.1-dist);\nelse if (dist<0.5)\nfactor=0.0;\nelse\nfactor=2.0*(dist-0.5);\nfactor=clamp(factor,0.0,0.90);\ngl_FragColor=mix(sharp,blur,factor);\n}\n#endif\n","stereoscopicInterlacePixelShader":"const vec3 TWO=vec3(2.0,2.0,2.0);\nvarying vec2 vUV;\nuniform sampler2D camASampler;\nuniform sampler2D textureSampler;\nuniform vec2 stepSize;\nvoid main(void)\n{\nbool useCamB;\nvec2 texCoord1;\nvec2 texCoord2;\nvec3 frag1;\nvec3 frag2;\n#ifdef IS_STEREOSCOPIC_HORIZ\nuseCamB=vUV.x>0.5;\ntexCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);\ntexCoord2=vec2(texCoord1.x+stepSize.x,vUV.y);\n#else\nuseCamB=vUV.y>0.5;\ntexCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);\ntexCoord2=vec2(vUV.x,texCoord1.y+stepSize.y);\n#endif\n\nif (useCamB){\nfrag1=texture2D(textureSampler,texCoord1).rgb;\nfrag2=texture2D(textureSampler,texCoord2).rgb;\n}else{\nfrag1=texture2D(camASampler ,texCoord1).rgb;\nfrag2=texture2D(camASampler ,texCoord2).rgb;\n}\ngl_FragColor=vec4((frag1+frag2)/TWO,1.0);\n}","text2dPixelShader":"varying vec4 vColor;\nvarying vec2 vUV;\n\nuniform sampler2D diffuseSampler;\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\ngl_FragColor=color*vColor;\n}","text2dVertexShader":"\n#ifdef Instanced\n#define att attribute\n#else\n#define att uniform\n#endif\n\nattribute float index;\natt vec2 zBias;\natt vec4 transformX;\natt vec4 transformY;\natt float opacity;\natt vec2 topLeftUV;\natt vec2 sizeUV;\natt vec2 textureSize;\natt vec4 color;\natt float superSampleFactor;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\nvoid main(void) {\nvec2 pos2;\n\nif (index == 0.0) {\npos2=vec2(0.0,0.0);\nvUV=vec2(topLeftUV.x,topLeftUV.y+sizeUV.y);\n}\n\nelse if (index == 1.0) {\npos2=vec2(0.0,1.0);\nvUV=vec2(topLeftUV.x,topLeftUV.y);\n}\n\nelse if (index == 2.0) {\npos2=vec2(1.0,1.0);\nvUV=vec2(topLeftUV.x+sizeUV.x,topLeftUV.y);\n}\n\nelse if (index == 3.0) {\npos2=vec2(1.0,0.0);\nvUV=vec2(topLeftUV.x+sizeUV.x,topLeftUV.y+sizeUV.y);\n}\n\nvUV=(floor(vUV*textureSize)+vec2(0.0,0.0))/textureSize;\nvColor=color;\nvColor.a*=opacity;\nvec4 pos;\npos.xy=floor(pos2.xy*superSampleFactor*sizeUV*textureSize); \npos.z=1.0;\npos.w=1.0;\ngl_Position=vec4(dot(pos,transformX),dot(pos,transformY),zBias.x,1);\n}","tonemapPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float _ExposureAdjustment;\n#if defined(HABLE_TONEMAPPING)\nconst float A=0.15;\nconst float B=0.50;\nconst float C=0.10;\nconst float D=0.20;\nconst float E=0.02;\nconst float F=0.30;\nconst float W=11.2;\n#endif\nfloat Luminance(vec3 c)\n{\nreturn dot(c,vec3(0.22,0.707,0.071));\n}\nvoid main(void) \n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\n#if defined(REINHARD_TONEMAPPING)\nfloat lum=Luminance(colour.rgb); \nfloat lumTm=lum*_ExposureAdjustment;\nfloat scale=lumTm/(1.0+lumTm); \ncolour*=scale/lum;\n#elif defined(HABLE_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nconst float ExposureBias=2.0;\nvec3 x=ExposureBias*colour;\nvec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;\nx=vec3(W,W,W);\nvec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);\ncolour=curr*whiteScale;\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\ncolour=vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour);\n#endif\ngl_FragColor=vec4(colour.rgb,1.0);\n}","volumetricLightScatteringPixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D lightScatteringSampler;\nuniform float decay;\nuniform float exposure;\nuniform float weight;\nuniform float density;\nuniform vec2 meshPositionOnScreen;\nvarying vec2 vUV;\nvoid main(void) {\nvec2 tc=vUV;\nvec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);\ndeltaTexCoord*=1.0/float(NUM_SAMPLES)*density;\nfloat illuminationDecay=1.0;\nvec4 color=texture2D(lightScatteringSampler,tc)*0.4;\nfor(int i=0; i<NUM_SAMPLES; i++) {\ntc-=deltaTexCoord;\nvec4 sample=texture2D(lightScatteringSampler,tc)*0.4;\nsample*=illuminationDecay*weight;\ncolor+=sample;\nilluminationDecay*=decay;\n}\nvec4 realColor=texture2D(textureSampler,vUV);\ngl_FragColor=((vec4((vec3(color.r,color.g,color.b)*exposure),1))+(realColor*(1.5-0.4)));\n}\n","volumetricLightScatteringPassPixelShader":"#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\n#endif\n#if defined(ALPHATEST)\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void)\n{\n#if defined(ALPHATEST)\nvec4 diffuseColor=texture2D(diffuseSampler,vUV);\nif (diffuseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\n","vrDistortionCorrectionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\nvec2 HmdWarp(vec2 in01) {\nvec2 theta=(in01-LensCenter)*ScaleIn; \nfloat rSq=theta.x*theta.x+theta.y*theta.y;\nvec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);\nreturn LensCenter+Scale*rvector;\n}\nvoid main(void)\n{\nvec2 tc=HmdWarp(vUV);\nif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nelse{\ngl_FragColor=vec4(texture2D(textureSampler,tc).rgb,1.0);\n}\n}"};
  63507. BABYLON.Effect.IncludesShadersStore={"bonesDeclaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nattribute vec4 matricesIndicesExtra;\nattribute vec4 matricesWeightsExtra;\n#endif\n#endif","bonesVertex":"#if NUM_BONE_INFLUENCERS>0\nmat4 influence;\ninfluence=mBones[int(matricesIndices[0])]*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence+=mBones[int(matricesIndices[1])]*matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence+=mBones[int(matricesIndices[2])]*matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence+=mBones[int(matricesIndices[3])]*matricesWeights[3];\n#endif \n#if NUM_BONE_INFLUENCERS>4\ninfluence+=mBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\ninfluence+=mBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence+=mBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence+=mBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];\n#endif \nfinalWorld=finalWorld*influence;\n#endif","bumpFragment":"#ifdef BUMP\nvec2 bumpUV=vBumpUV;\n#endif\n#if defined(BUMP) || defined(PARALLAX)\nmat3 TBN=cotangent_frame(normalW*vBumpInfos.y,-viewDirectionW,bumpUV);\n#endif\n#ifdef PARALLAX\nmat3 invTBN=transposeMat3(TBN);\n#ifdef PARALLAXOCCLUSION\nvec2 uvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,bumpUV,vBumpInfos.z);\n#else\nvec2 uvOffset=parallaxOffset(invTBN*viewDirectionW,vBumpInfos.z);\n#endif\ndiffuseUV+=uvOffset;\nbumpUV+=uvOffset;\n#endif\n#ifdef BUMP\nnormalW=perturbNormal(viewDirectionW,TBN,bumpUV);\n#endif","bumpFragmentFunctions":"#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform vec3 vBumpInfos;\nuniform sampler2D bumpSampler;\n\nmat3 cotangent_frame(vec3 normal,vec3 p,vec2 uv)\n{\n\nvec3 dp1=dFdx(p);\nvec3 dp2=dFdy(p);\nvec2 duv1=dFdx(uv);\nvec2 duv2=dFdy(uv);\n\nvec3 dp2perp=cross(dp2,normal);\nvec3 dp1perp=cross(normal,dp1);\nvec3 tangent=dp2perp*duv1.x+dp1perp*duv2.x;\nvec3 binormal=dp2perp*duv1.y+dp1perp*duv2.y;\n\nfloat invmax=inversesqrt(max(dot(tangent,tangent),dot(binormal,binormal)));\nreturn mat3(tangent*invmax,binormal*invmax,normal);\n}\nvec3 perturbNormal(vec3 viewDir,mat3 cotangentFrame,vec2 uv)\n{\nvec3 map=texture2D(bumpSampler,uv).xyz;\n#ifdef INVERTNORMALMAPX\nmap.x=1.0-map.x;\n#endif\n#ifdef INVERTNORMALMAPY\nmap.y=1.0-map.y;\n#endif\nmap=map*255./127.-128./127.;\nreturn normalize(cotangentFrame*map);\n}\n#ifdef PARALLAX\nconst float minSamples=4.;\nconst float maxSamples=15.;\nconst int iMaxSamples=15;\n\nvec2 parallaxOcclusion(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale) {\nfloat parallaxLimit=length(vViewDirCoT.xy)/vViewDirCoT.z;\nparallaxLimit*=parallaxScale;\nvec2 vOffsetDir=normalize(vViewDirCoT.xy);\nvec2 vMaxOffset=vOffsetDir*parallaxLimit;\nfloat numSamples=maxSamples+(dot(vViewDirCoT,vNormalCoT)*(minSamples-maxSamples));\nfloat stepSize=1.0/numSamples;\n\nfloat currRayHeight=1.0;\nvec2 vCurrOffset=vec2(0,0);\nvec2 vLastOffset=vec2(0,0);\nfloat lastSampledHeight=1.0;\nfloat currSampledHeight=1.0;\nfor (int i=0; i<iMaxSamples; i++)\n{\ncurrSampledHeight=texture2D(bumpSampler,vBumpUV+vCurrOffset).w;\n\nif (currSampledHeight>currRayHeight)\n{\nfloat delta1=currSampledHeight-currRayHeight;\nfloat delta2=(currRayHeight+stepSize)-lastSampledHeight;\nfloat ratio=delta1/(delta1+delta2);\nvCurrOffset=(ratio)* vLastOffset+(1.0-ratio)*vCurrOffset;\n\nbreak;\n}\nelse\n{\ncurrRayHeight-=stepSize;\nvLastOffset=vCurrOffset;\nvCurrOffset+=stepSize*vMaxOffset;\nlastSampledHeight=currSampledHeight;\n}\n}\nreturn vCurrOffset;\n}\nvec2 parallaxOffset(vec3 viewDir,float heightScale)\n{\n\nfloat height=texture2D(bumpSampler,vBumpUV).w;\nvec2 texCoordOffset=heightScale*viewDir.xy*height;\nreturn -texCoordOffset;\n}\n#endif\n#endif","clipPlaneFragment":"#ifdef CLIPPLANE\nif (fClipDistance>0.0)\n{\ndiscard;\n}\n#endif","clipPlaneFragmentDeclaration":"#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif","clipPlaneVertex":"#ifdef CLIPPLANE\nfClipDistance=dot(worldPos,vClipPlane);\n#endif","clipPlaneVertexDeclaration":"#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif","colorCurves":"const vec3 HDTVRec709_RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\nvec3 applyColorCurves(vec3 original) {\nvec3 result=original;\n\n\n\nfloat luma=dot(result.rgb,HDTVRec709_RGBLuminanceCoefficients);\nvec2 curveMix=clamp(vec2(luma*3.0-1.5,luma*-3.0+1.5),vec2(0.0,0.0),vec2(1.0,1.0));\nvec4 colorCurve=vCameraColorCurveNeutral+curveMix.x*vCameraColorCurvePositive-curveMix.y*vCameraColorCurveNegative;\nresult.rgb*=colorCurve.rgb;\nresult.rgb=mix(vec3(luma,luma,luma),result.rgb,colorCurve.a);\nreturn result;\n}","colorCurvesDefinition":"uniform vec4 vCameraColorCurveNeutral;\nuniform vec4 vCameraColorCurvePositive;\nuniform vec4 vCameraColorCurveNegative;","colorGrading":"vec4 colorGrades(vec4 color) \n{ \n\nfloat sliceContinuous=color.z*vCameraColorGradingInfos.z;\nfloat sliceInteger=floor(sliceContinuous);\n\n\nfloat sliceFraction=sliceContinuous-sliceInteger; \n\nvec2 sliceUV=color.xy*vCameraColorGradingScaleOffset.xy+vCameraColorGradingScaleOffset.zw;\n\n\nsliceUV.x+=sliceInteger*vCameraColorGradingInfos.w;\nvec4 slice0Color=texture2D(cameraColorGrading2DSampler,sliceUV);\nsliceUV.x+=vCameraColorGradingInfos.w;\nvec4 slice1Color=texture2D(cameraColorGrading2DSampler,sliceUV);\nvec3 result=mix(slice0Color.rgb,slice1Color.rgb,sliceFraction);\ncolor.rgb=mix(color.rgb,result,vCameraColorGradingInfos.x);\nreturn color;\n}","colorGradingDefinition":"uniform sampler2D cameraColorGrading2DSampler;\nuniform vec4 vCameraColorGradingInfos;\nuniform vec4 vCameraColorGradingScaleOffset;","fogFragment":"#ifdef FOG\nfloat fog=CalcFogFactor();\ncolor.rgb=fog*color.rgb+(1.0-fog)*vFogColor;\n#endif","fogFragmentDeclaration":"#ifdef FOG\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying float fFogDistance;\nfloat CalcFogFactor()\n{\nfloat fogCoeff=1.0;\nfloat fogStart=vFogInfos.y;\nfloat fogEnd=vFogInfos.z;\nfloat fogDensity=vFogInfos.w;\nif (FOGMODE_LINEAR == vFogInfos.x)\n{\nfogCoeff=(fogEnd-fFogDistance)/(fogEnd-fogStart);\n}\nelse if (FOGMODE_EXP == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fFogDistance*fogDensity);\n}\nelse if (FOGMODE_EXP2 == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fFogDistance*fFogDistance*fogDensity*fogDensity);\n}\nreturn clamp(fogCoeff,0.0,1.0);\n}\n#endif","fogVertex":"#ifdef FOG\nfFogDistance=(view*worldPos).z;\n#endif","fogVertexDeclaration":"#ifdef FOG\nvarying float fFogDistance;\n#endif","fresnelFunction":"#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection,vec3 worldNormal,float bias,float power)\n{\nfloat fresnelTerm=pow(bias+abs(dot(viewDirection,worldNormal)),power);\nreturn clamp(fresnelTerm,0.,1.);\n}\n#endif","harmonicsFunctions":"#ifdef USESPHERICALFROMREFLECTIONMAP\nuniform vec3 vSphericalX;\nuniform vec3 vSphericalY;\nuniform vec3 vSphericalZ;\nuniform vec3 vSphericalXX;\nuniform vec3 vSphericalYY;\nuniform vec3 vSphericalZZ;\nuniform vec3 vSphericalXY;\nuniform vec3 vSphericalYZ;\nuniform vec3 vSphericalZX;\nvec3 EnvironmentIrradiance(vec3 normal)\n{\n\n\n\nvec3 result =\nvSphericalX*normal.x +\nvSphericalY*normal.y +\nvSphericalZ*normal.z +\nvSphericalXX*normal.x*normal.x +\nvSphericalYY*normal.y*normal.y +\nvSphericalZZ*normal.z*normal.z +\nvSphericalYZ*normal.y*normal.z +\nvSphericalZX*normal.z*normal.x +\nvSphericalXY*normal.x*normal.y;\nreturn result.rgb;\n}\n#endif","helperFunctions":"mat3 transposeMat3(mat3 inMatrix) {\nvec3 i0=inMatrix[0];\nvec3 i1=inMatrix[1];\nvec3 i2=inMatrix[2];\nmat3 outMatrix=mat3(\nvec3(i0.x,i1.x,i2.x),\nvec3(i0.y,i1.y,i2.y),\nvec3(i0.z,i1.z,i2.z)\n);\nreturn outMatrix;\n}","instancesDeclaration":"#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif","instancesVertex":"#ifdef INSTANCES\nmat4 finalWorld=mat4(world0,world1,world2,world3);\n#else\nmat4 finalWorld=world;\n#endif","lightFragment":"#ifdef LIGHT{X}\n#if defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X})\n\n#else\n#ifndef SPECULARTERM\nvec3 vLightSpecular{X}=vec3(0.);\n#endif\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,vLightData{X},vLightDirection{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightDiffuse{X}.a,glossiness);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,vLightData{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightGround{X},glossiness);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,vLightData{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightDiffuse{X}.a,glossiness);\n#endif\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWVSM{X}\nshadow=computeShadowWithVSM(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.z,shadowsInfo{X}.x);\n#else\n#ifdef SHADOWPCF{X}\n#if defined(POINTLIGHT{X})\nshadow=computeShadowWithPCFCube(vLightData{X}.xyz,shadowSampler{X},shadowsInfo{X}.y,shadowsInfo{X}.z,shadowsInfo{X}.x);\n#else\nshadow=computeShadowWithPCF(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.y,shadowsInfo{X}.z,shadowsInfo{X}.x);\n#endif\n#else\n#if defined(POINTLIGHT{X})\nshadow=computeShadowCube(vLightData{X}.xyz,shadowSampler{X},shadowsInfo{X}.x,shadowsInfo{X}.z);\n#else\nshadow=computeShadow(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.x,shadowsInfo{X}.z);\n#endif\n#endif\n#endif\n#else\nshadow=1.;\n#endif\n#if defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X})\ndiffuseBase+=lightmapColor*shadow;\n#ifdef SPECULARTERM\n#ifndef LIGHTMAPNOSPECULAR{X}\nspecularBase+=info.specular*shadow*lightmapColor;\n#endif\n#endif\n#else\ndiffuseBase+=info.diffuse*shadow;\n#ifdef SPECULARTERM\nspecularBase+=info.specular*shadow;\n#endif\n#endif\n#endif","lightFragmentDeclaration":"#ifdef LIGHT{X}\nuniform vec4 vLightData{X};\nuniform vec4 vLightDiffuse{X};\n#ifdef SPECULARTERM\nuniform vec3 vLightSpecular{X};\n#endif\n#ifdef SHADOW{X}\n#if defined(SPOTLIGHT{X}) || defined(DIRLIGHT{X})\nvarying vec4 vPositionFromLight{X};\nuniform sampler2D shadowSampler{X};\n#else\nuniform samplerCube shadowSampler{X};\n#endif\nuniform vec3 shadowsInfo{X};\n#endif\n#ifdef SPOTLIGHT{X}\nuniform vec4 vLightDirection{X};\n#endif\n#ifdef HEMILIGHT{X}\nuniform vec3 vLightGround{X};\n#endif\n#endif","lightsFragmentFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n};\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 lightVectorW;\nfloat attenuation=1.0;\nif (lightData.w == 0.)\n{\nvec3 direction=lightData.xyz-vPositionW;\nattenuation=max(0.,1.0-length(direction)/range);\nlightVectorW=normalize(direction);\n}\nelse\n{\nlightVectorW=normalize(-lightData.xyz);\n}\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 direction=lightData.xyz-vPositionW;\nvec3 lightVectorW=normalize(direction);\nfloat attenuation=max(0.,1.0-length(direction)/range);\n\nfloat cosAngle=max(0.,dot(-lightDirection.xyz,lightVectorW));\nif (cosAngle>=lightDirection.w)\n{\ncosAngle=max(0.,pow(cosAngle,lightData.w));\nattenuation*=cosAngle;\n\nfloat ndl=max(0.,dot(vNormal,-lightDirection.xyz));\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW-lightDirection.xyz);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nresult.diffuse=vec3(0.);\n#ifdef SPECULARTERM\nresult.specular=vec3(0.);\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float glossiness) {\nlightingInfo result;\n\nfloat ndl=dot(vNormal,lightData.xyz)*0.5+0.5;\nresult.diffuse=mix(groundColor,diffuseColor,ndl);\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightData.xyz);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor;\n#endif\nreturn result;\n}\n","logDepthDeclaration":"#ifdef LOGARITHMICDEPTH\nuniform float logarithmicDepthConstant;\nvarying float vFragmentDepth;\n#endif","logDepthFragment":"#ifdef LOGARITHMICDEPTH\ngl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5;\n#endif","logDepthVertex":"#ifdef LOGARITHMICDEPTH\nvFragmentDepth=1.0+gl_Position.w;\ngl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant;\n#endif","pbrFunctions":"\n#define RECIPROCAL_PI2 0.15915494\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\n\nconst float kPi=3.1415926535897932384626433832795;\nconst float kRougnhessToAlphaScale=0.1;\nconst float kRougnhessToAlphaOffset=0.29248125;\nfloat Square(float value)\n{\nreturn value*value;\n}\nfloat getLuminance(vec3 color)\n{\nreturn clamp(dot(color,vec3(0.2126,0.7152,0.0722)),0.,1.);\n}\nfloat convertRoughnessToAverageSlope(float roughness)\n{\n\nconst float kMinimumVariance=0.0005;\nfloat alphaG=Square(roughness)+kMinimumVariance;\nreturn alphaG;\n}\n\nfloat getMipMapIndexFromAverageSlope(float maxMipLevel,float alpha)\n{\n\n\n\n\n\n\n\nfloat mip=kRougnhessToAlphaOffset+maxMipLevel+(maxMipLevel*kRougnhessToAlphaScale*log2(alpha));\nreturn clamp(mip,0.,maxMipLevel);\n}\nfloat getMipMapIndexFromAverageSlopeWithPMREM(float maxMipLevel,float alphaG)\n{\nfloat specularPower=clamp(2./alphaG-2.,0.000001,2048.);\n\nreturn clamp(- 0.5*log2(specularPower)+5.5,0.,maxMipLevel);\n}\n\nfloat smithVisibilityG1_TrowbridgeReitzGGX(float dot,float alphaG)\n{\nfloat tanSquared=(1.0-dot*dot)/(dot*dot);\nreturn 2.0/(1.0+sqrt(1.0+alphaG*alphaG*tanSquared));\n}\nfloat smithVisibilityG_TrowbridgeReitzGGX_Walter(float NdotL,float NdotV,float alphaG)\n{\nreturn smithVisibilityG1_TrowbridgeReitzGGX(NdotL,alphaG)*smithVisibilityG1_TrowbridgeReitzGGX(NdotV,alphaG);\n}\n\n\nfloat normalDistributionFunction_TrowbridgeReitzGGX(float NdotH,float alphaG)\n{\n\n\n\nfloat a2=Square(alphaG);\nfloat d=NdotH*NdotH*(a2-1.0)+1.0;\nreturn a2/(kPi*d*d);\n}\nvec3 fresnelSchlickGGX(float VdotH,vec3 reflectance0,vec3 reflectance90)\n{\nreturn reflectance0+(reflectance90-reflectance0)*pow(clamp(1.0-VdotH,0.,1.),5.0);\n}\nvec3 FresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n\nvec3 computeSpecularTerm(float NdotH,float NdotL,float NdotV,float VdotH,float roughness,vec3 specularColor,vec3 reflectance90)\n{\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\nfloat distribution=normalDistributionFunction_TrowbridgeReitzGGX(NdotH,alphaG);\nfloat visibility=smithVisibilityG_TrowbridgeReitzGGX_Walter(NdotL,NdotV,alphaG);\nvisibility/=(4.0*NdotL*NdotV); \nvec3 fresnel=fresnelSchlickGGX(VdotH,specularColor,reflectance90);\nfloat specTerm=max(0.,visibility*distribution)*NdotL;\nreturn fresnel*specTerm*kPi; \n}\nfloat computeDiffuseTerm(float NdotL,float NdotV,float VdotH,float roughness)\n{\n\n\nfloat diffuseFresnelNV=pow(clamp(1.0-NdotL,0.000001,1.),5.0);\nfloat diffuseFresnelNL=pow(clamp(1.0-NdotV,0.000001,1.),5.0);\nfloat diffuseFresnel90=0.5+2.0*VdotH*VdotH*roughness;\nfloat diffuseFresnelTerm =\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNL) *\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNV);\nreturn diffuseFresnelTerm*NdotL;\n\n\n}\nfloat adjustRoughnessFromLightProperties(float roughness,float lightRadius,float lightDistance)\n{\n#ifdef USEPHYSICALLIGHTFALLOFF\n\nfloat lightRoughness=lightRadius/lightDistance;\n\nfloat totalRoughness=clamp(lightRoughness+roughness,0.,1.);\nreturn totalRoughness;\n#else\nreturn roughness;\n#endif\n}\nfloat computeDefaultMicroSurface(float microSurface,vec3 reflectivityColor)\n{\nfloat kReflectivityNoAlphaWorkflow_SmoothnessMax=0.95;\nfloat reflectivityLuminance=getLuminance(reflectivityColor);\nfloat reflectivityLuma=sqrt(reflectivityLuminance);\nmicroSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;\nreturn microSurface;\n}\nvec3 toLinearSpace(vec3 color)\n{\nreturn vec3(pow(color.r,2.2),pow(color.g,2.2),pow(color.b,2.2));\n}\nvec3 toGammaSpace(vec3 color)\n{\nreturn vec3(pow(color.r,1.0/2.2),pow(color.g,1.0/2.2),pow(color.b,1.0/2.2));\n}\n#ifdef CAMERATONEMAP\nvec3 toneMaps(vec3 color)\n{\ncolor=max(color,0.0);\n\ncolor.rgb=color.rgb*vCameraInfos.x;\nfloat tuning=1.5; \n\n\nvec3 tonemapped=1.0-exp2(-color.rgb*tuning); \ncolor.rgb=mix(color.rgb,tonemapped,1.0);\nreturn color;\n}\n#endif\n#ifdef CAMERACONTRAST\nvec4 contrasts(vec4 color)\n{\ncolor=clamp(color,0.0,1.0);\nvec3 resultHighContrast=color.rgb*color.rgb*(3.0-2.0*color.rgb);\nfloat contrast=vCameraInfos.y;\nif (contrast<1.0)\n{\n\ncolor.rgb=mix(vec3(0.5,0.5,0.5),color.rgb,contrast);\n}\nelse\n{\n\ncolor.rgb=mix(color.rgb,resultHighContrast,contrast-1.0);\n}\nreturn color;\n}\n#endif","pbrLightFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n};\nfloat computeDistanceLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range)\n{ \n#ifdef USEPHYSICALLIGHTFALLOFF\nfloat lightDistanceFalloff=1.0/((lightDistanceSquared+0.0001));\n#else\nfloat lightDistanceFalloff=max(0.,1.0-length(lightOffset)/range);\n#endif\nreturn lightDistanceFalloff;\n}\nfloat computeDirectionalLightFalloff(vec3 lightDirection,vec3 directionToLightCenterW,float lightAngle,float exponent)\n{\nfloat falloff=0.0;\n#ifdef USEPHYSICALLIGHTFALLOFF\nfloat cosHalfAngle=cos(lightAngle*0.5);\nconst float kMinusLog2ConeAngleIntensityRatio=6.64385618977; \n\n\n\n\n\nfloat concentrationKappa=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);\n\n\nvec4 lightDirectionSpreadSG=vec4(-lightDirection*concentrationKappa,-concentrationKappa);\nfalloff=exp2(dot(vec4(directionToLightCenterW,1.0),lightDirectionSpreadSG));\n#else\nfloat cosAngle=max(0.000000000000001,dot(-lightDirection,directionToLightCenterW));\nif (cosAngle>=lightAngle)\n{\nfalloff=max(0.,pow(cosAngle,exponent));\n}\n#endif\nreturn falloff;\n}\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\nvec3 lightDirection;\nfloat attenuation=1.0;\nfloat lightDistance;\n\nif (lightData.w == 0.)\n{\nvec3 lightOffset=lightData.xyz-vPositionW;\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nattenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\nlightDistance=sqrt(lightDistanceSquared);\nlightDirection=normalize(lightOffset);\n}\n\nelse\n{\nlightDistance=length(-lightData.xyz);\nlightDirection=normalize(-lightData.xyz);\n}\n\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+lightDirection);\nNdotL=max(0.00000000001,dot(vNormal,lightDirection));\nfloat VdotH=clamp(0.00000000001,1.0,dot(viewDirectionW,H));\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=max(0.00000000001,dot(vNormal,H));\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,specularColor,reflectance90);\nresult.specular=specTerm*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\nvec3 lightOffset=lightData.xyz-vPositionW;\nvec3 directionToLightCenterW=normalize(lightOffset);\n\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nfloat attenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\n\nfloat directionalAttenuation=computeDirectionalLightFalloff(lightDirection.xyz,directionToLightCenterW,lightDirection.w,lightData.w);\nattenuation*=directionalAttenuation;\n\nfloat lightDistance=sqrt(lightDistanceSquared);\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW-lightDirection.xyz);\nNdotL=max(0.00000000001,dot(vNormal,-lightDirection.xyz));\nfloat VdotH=clamp(dot(viewDirectionW,H),0.00000000001,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=max(0.00000000001,dot(vNormal,H));\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,specularColor,reflectance90);\nresult.specular=specTerm*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float roughness,float NdotV,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\n\n\n\nNdotL=dot(vNormal,lightData.xyz)*0.5+0.5;\nresult.diffuse=mix(groundColor,diffuseColor,NdotL);\n#ifdef SPECULARTERM\n\nvec3 lightVectorW=normalize(lightData.xyz);\nvec3 H=normalize(viewDirectionW+lightVectorW);\nfloat NdotH=max(0.00000000001,dot(vNormal,H));\nNdotL=max(0.00000000001,NdotL);\nfloat VdotH=clamp(0.00000000001,1.0,dot(viewDirectionW,H));\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,specularColor,reflectance90);\nresult.specular=specTerm;\n#endif\nreturn result;\n}","pbrLightFunctionsCall":"#ifdef LIGHT{X}\n#if defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X})\n\n#else\n#ifndef SPECULARTERM\nvec3 vLightSpecular{X}=vec3(0.0);\n#endif\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,vLightData{X},vLightDirection{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightDiffuse{X}.a,roughness,NdotV,specularEnvironmentR90,NdotL);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,vLightData{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightGround{X},roughness,NdotV,specularEnvironmentR90,NdotL);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,vLightData{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightDiffuse{X}.a,roughness,NdotV,specularEnvironmentR90,NdotL);\n#endif\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWVSM{X}\nnotShadowLevel=computeShadowWithVSM(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.z,shadowsInfo{X}.x);\n#else\n#ifdef SHADOWPCF{X}\n#if defined(POINTLIGHT{X})\nnotShadowLevel=computeShadowWithPCFCube(vLightData{X}.xyz,shadowSampler{X},shadowsInfo{X}.y,shadowsInfo{X}.z,shadowsInfo{X}.x);\n#else\nnotShadowLevel=computeShadowWithPCF(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.y,shadowsInfo{X}.z,shadowsInfo{X}.x);\n#endif\n#else\n#if defined(POINTLIGHT{X})\nnotShadowLevel=computeShadowCube(vLightData{X}.xyz,shadowSampler{X},shadowsInfo{X}.x,shadowsInfo{X}.z);\n#else\nnotShadowLevel=computeShadow(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.x,shadowsInfo{X}.z);\n#endif\n#endif\n#endif\n#else\nnotShadowLevel=1.;\n#endif\n#if defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X})\nlightDiffuseContribution+=lightmapColor*notShadowLevel;\n#ifdef SPECULARTERM\n#ifndef LIGHTMAPNOSPECULAR{X}\nlightSpecularContribution+=info.specular*notShadowLevel*lightmapColor;\n#endif\n#endif\n#else\nlightDiffuseContribution+=info.diffuse*notShadowLevel;\n#ifdef OVERLOADEDSHADOWVALUES\nif (NdotL<0.000000000011)\n{\nnotShadowLevel=1.;\n}\nshadowedOnlyLightDiffuseContribution*=notShadowLevel;\n#endif\n#ifdef SPECULARTERM\nlightSpecularContribution+=info.specular*notShadowLevel;\n#endif\n#endif\n#endif","pbrShadowFunctions":"\n#ifdef SHADOWS\n#ifndef SHADOWFULLFLOAT\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nuniform vec2 depthValues;\nfloat computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float bias)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y =-directionToLight.y;\n#ifndef SHADOWFULLFLOAT\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight))+bias;\n#else\nfloat shadow=textureCube(shadowSampler,directionToLight).x+bias;\n#endif\nif (depth>shadow)\n{\n#ifdef OVERLOADEDSHADOWVALUES\nreturn mix(1.0,darkness,vOverloadedShadowIntensity.x);\n#else\nreturn darkness;\n#endif\n}\nreturn 1.0;\n}\nfloat computeShadowWithPCFCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float bias,float darkness)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth-depthValues.x)/(depthValues.y-depthValues.x);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\nfloat visibility=1.;\nvec3 poissonDisk[4];\npoissonDisk[0]=vec3(-1.0,1.0,-1.0);\npoissonDisk[1]=vec3(1.0,-1.0,-1.0);\npoissonDisk[2]=vec3(-1.0,-1.0,-1.0);\npoissonDisk[3]=vec3(1.0,-1.0,1.0);\n\nfloat biasedDepth=depth-bias;\n#ifndef SHADOWFULLFLOAT\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<biasedDepth) visibility-=0.25;\n#else\nif (textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize).x<biasedDepth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize).x<biasedDepth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize).x<biasedDepth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize).x<biasedDepth) visibility-=0.25;\n#endif\n#ifdef OVERLOADEDSHADOWVALUES\nreturn min(1.0,mix(1.0,visibility+darkness,vOverloadedShadowIntensity.x));\n#else\nreturn min(1.0,visibility+darkness);\n#endif\n}\nfloat computeShadow(vec4 vPositionFromLight,sampler2D shadowSampler,float darkness,float bias)\n{\nvec3 depth=vPositionFromLight.xyz/vPositionFromLight.w;\ndepth=0.5*depth+vec3(0.5);\nvec2 uv=depth.xy;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\n#ifndef SHADOWFULLFLOAT\nfloat shadow=unpack(texture2D(shadowSampler,uv))+bias;\n#else\nfloat shadow=texture2D(shadowSampler,uv).x+bias;\n#endif\nif (depth.z>shadow)\n{\n#ifdef OVERLOADEDSHADOWVALUES\nreturn mix(1.0,darkness,vOverloadedShadowIntensity.x);\n#else\nreturn darkness;\n#endif\n}\nreturn 1.;\n}\nfloat computeShadowWithPCF(vec4 vPositionFromLight,sampler2D shadowSampler,float mapSize,float bias,float darkness)\n{\nvec3 depth=vPositionFromLight.xyz/vPositionFromLight.w;\ndepth=0.5*depth+vec3(0.5);\nvec2 uv=depth.xy;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat visibility=1.;\nvec2 poissonDisk[4];\npoissonDisk[0]=vec2(-0.94201624,-0.39906216);\npoissonDisk[1]=vec2(0.94558609,-0.76890725);\npoissonDisk[2]=vec2(-0.094184101,-0.92938870);\npoissonDisk[3]=vec2(0.34495938,0.29387760);\n\nfloat biasedDepth=depth.z-bias;\n#ifndef SHADOWFULLFLOAT\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[0]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[1]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[2]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[3]*mapSize))<biasedDepth) visibility-=0.25;\n#else\nif (texture2D(shadowSampler,uv+poissonDisk[0]*mapSize).x<biasedDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[1]*mapSize).x<biasedDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[2]*mapSize).x<biasedDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[3]*mapSize).x<biasedDepth) visibility-=0.25;\n#endif\n#ifdef OVERLOADEDSHADOWVALUES\nreturn min(1.0,mix(1.0,visibility+darkness,vOverloadedShadowIntensity.x));\n#else\nreturn min(1.0,visibility+darkness);\n#endif\n}\n#ifndef SHADOWFULLFLOAT\n\nfloat unpackHalf(vec2 color)\n{\nreturn color.x+(color.y/255.0);\n}\n#endif\nfloat linstep(float low,float high,float v) {\nreturn clamp((v-low)/(high-low),0.0,1.0);\n}\nfloat ChebychevInequality(vec2 moments,float compare,float bias)\n{\nfloat p=smoothstep(compare-bias,compare,moments.x);\nfloat variance=max(moments.y-moments.x*moments.x,0.02);\nfloat d=compare-moments.x;\nfloat p_max=linstep(0.2,1.0,variance/(variance+d*d));\nreturn clamp(max(p,p_max),0.0,1.0);\n}\nfloat computeShadowWithVSM(vec4 vPositionFromLight,sampler2D shadowSampler,float bias,float darkness)\n{\nvec3 depth=vPositionFromLight.xyz/vPositionFromLight.w;\ndepth=0.5*depth+vec3(0.5);\nvec2 uv=depth.xy;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0 || depth.z>=1.0)\n{\nreturn 1.0;\n}\nvec4 texel=texture2D(shadowSampler,uv);\n#ifndef SHADOWFULLFLOAT\nvec2 moments=vec2(unpackHalf(texel.xy),unpackHalf(texel.zw));\n#else\nvec2 moments=texel.xy;\n#endif\n#ifdef OVERLOADEDSHADOWVALUES\nreturn min(1.0,mix(1.0,1.0-ChebychevInequality(moments,depth.z,bias)+darkness,vOverloadedShadowIntensity.x));\n#else\nreturn min(1.0,1.0-ChebychevInequality(moments,depth.z,bias)+darkness);\n#endif\n}\n#endif","pointCloudVertex":"#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif","pointCloudVertexDeclaration":"#ifdef POINTSIZE\nuniform float pointSize;\n#endif","reflectionFunction":"vec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvec3 direction=normalize(vDirectionW);\nfloat t=clamp(direction.y*-0.5+0.5,0.,1.0);\nfloat s=atan(direction.z,direction.x)*RECIPROCAL_PI2+0.5;\nreturn vec3(s,t,0);\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR\nvec3 cameraToVertex=normalize(worldPos.xyz-vEyePosition);\nvec3 r=reflect(cameraToVertex,worldNormal);\nfloat t=clamp(r.y*-0.5+0.5,0.,1.0);\nfloat s=atan(r.z,r.x)*RECIPROCAL_PI2+0.5;\nreturn vec3(s,t,0);\n#endif\n#ifdef REFLECTIONMAP_SPHERICAL\nvec3 viewDir=normalize(vec3(view*worldPos));\nvec3 viewNormal=normalize(vec3(view*vec4(worldNormal,0.0)));\nvec3 r=reflect(viewDir,viewNormal);\nr.z=r.z-1.0;\nfloat m=2.0*length(r);\nreturn vec3(r.x/m+0.5,1.0-r.y/m-0.5,0);\n#endif\n#ifdef REFLECTIONMAP_PLANAR\nvec3 viewDir=worldPos.xyz-vEyePosition;\nvec3 coords=normalize(reflect(viewDir,worldNormal));\nreturn vec3(reflectionMatrix*vec4(coords,1));\n#endif\n#ifdef REFLECTIONMAP_CUBIC\nvec3 viewDir=worldPos.xyz-vEyePosition;\nvec3 coords=reflect(viewDir,worldNormal);\n#ifdef INVERTCUBICMAP\ncoords.y=1.0-coords.y;\n#endif\nreturn vec3(reflectionMatrix*vec4(coords,0));\n#endif\n#ifdef REFLECTIONMAP_PROJECTION\nreturn vec3(reflectionMatrix*(view*worldPos));\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nreturn vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EXPLICIT\nreturn vec3(0,0,0);\n#endif\n}","shadowsFragmentFunctions":"#ifdef SHADOWS\n#ifndef SHADOWFULLFLOAT\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nuniform vec2 depthValues;\nfloat computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float bias)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth-depthValues.x)/(depthValues.y-depthValues.x);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFULLFLOAT\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight))+bias;\n#else\nfloat shadow=textureCube(shadowSampler,directionToLight).x+bias;\n#endif\nif (depth>shadow)\n{\nreturn darkness;\n}\nreturn 1.0;\n}\nfloat computeShadowWithPCFCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float bias,float darkness)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth-depthValues.x)/(depthValues.y-depthValues.x);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\nfloat visibility=1.;\nvec3 poissonDisk[4];\npoissonDisk[0]=vec3(-1.0,1.0,-1.0);\npoissonDisk[1]=vec3(1.0,-1.0,-1.0);\npoissonDisk[2]=vec3(-1.0,-1.0,-1.0);\npoissonDisk[3]=vec3(1.0,-1.0,1.0);\n\nfloat biasedDepth=depth-bias;\n#ifndef SHADOWFULLFLOAT\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<biasedDepth) visibility-=0.25;\n#else\nif (textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize).x<biasedDepth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize).x<biasedDepth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize).x<biasedDepth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize).x<biasedDepth) visibility-=0.25;\n#endif\nreturn min(1.0,visibility+darkness);\n}\nfloat computeShadow(vec4 vPositionFromLight,sampler2D shadowSampler,float darkness,float bias)\n{\nvec3 depth=vPositionFromLight.xyz/vPositionFromLight.w;\ndepth=0.5*depth+vec3(0.5);\nvec2 uv=depth.xy;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\n#ifndef SHADOWFULLFLOAT\nfloat shadow=unpack(texture2D(shadowSampler,uv))+bias;\n#else\nfloat shadow=texture2D(shadowSampler,uv).x+bias;\n#endif\nif (depth.z>shadow)\n{\nreturn darkness;\n}\nreturn 1.;\n}\nfloat computeShadowWithPCF(vec4 vPositionFromLight,sampler2D shadowSampler,float mapSize,float bias,float darkness)\n{\nvec3 depth=vPositionFromLight.xyz/vPositionFromLight.w;\ndepth=0.5*depth+vec3(0.5);\nvec2 uv=depth.xy;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat visibility=1.;\nvec2 poissonDisk[4];\npoissonDisk[0]=vec2(-0.94201624,-0.39906216);\npoissonDisk[1]=vec2(0.94558609,-0.76890725);\npoissonDisk[2]=vec2(-0.094184101,-0.92938870);\npoissonDisk[3]=vec2(0.34495938,0.29387760);\n\nfloat biasedDepth=depth.z-bias;\n#ifndef SHADOWFULLFLOAT\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[0]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[1]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[2]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[3]*mapSize))<biasedDepth) visibility-=0.25;\n#else\nif (texture2D(shadowSampler,uv+poissonDisk[0]*mapSize).x<biasedDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[1]*mapSize).x<biasedDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[2]*mapSize).x<biasedDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[3]*mapSize).x<biasedDepth) visibility-=0.25;\n#endif\nreturn min(1.0,visibility+darkness);\n}\n#ifndef SHADOWFULLFLOAT\n\nfloat unpackHalf(vec2 color)\n{\nreturn color.x+(color.y/255.0);\n}\n#endif\nfloat linstep(float low,float high,float v) {\nreturn clamp((v-low)/(high-low),0.0,1.0);\n}\nfloat ChebychevInequality(vec2 moments,float compare,float bias)\n{\nfloat p=smoothstep(compare-bias,compare,moments.x);\nfloat variance=max(moments.y-moments.x*moments.x,0.02);\nfloat d=compare-moments.x;\nfloat p_max=linstep(0.2,1.0,variance/(variance+d*d));\nreturn clamp(max(p,p_max),0.0,1.0);\n}\nfloat computeShadowWithVSM(vec4 vPositionFromLight,sampler2D shadowSampler,float bias,float darkness)\n{\nvec3 depth=vPositionFromLight.xyz/vPositionFromLight.w;\ndepth=0.5*depth+vec3(0.5);\nvec2 uv=depth.xy;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0 || depth.z>=1.0)\n{\nreturn 1.0;\n}\nvec4 texel=texture2D(shadowSampler,uv);\n#ifndef SHADOWFULLFLOAT\nvec2 moments=vec2(unpackHalf(texel.xy),unpackHalf(texel.zw));\n#else\nvec2 moments=texel.xy;\n#endif\nreturn min(1.0,1.0-ChebychevInequality(moments,depth.z,bias)+darkness);\n}\n#endif","shadowsVertex":"#ifdef SHADOWS\n#if defined(SPOTLIGHT{X}) || defined(DIRLIGHT{X})\nvPositionFromLight{X}=lightMatrix{X}*worldPos;\n#endif\n#endif","shadowsVertexDeclaration":"#ifdef SHADOWS\n#if defined(SPOTLIGHT{X}) || defined(DIRLIGHT{X})\nuniform mat4 lightMatrix{X};\nvarying vec4 vPositionFromLight{X};\n#endif\n#endif\n"};
  63508. BABYLON.CollisionWorker="var BABYLON;!function(t){var e=function(t,e,o,i){return!(t.x>o.x+i)&&(!(o.x-i>e.x)&&(!(t.y>o.y+i)&&(!(o.y-i>e.y)&&(!(t.z>o.z+i)&&!(o.z-i>e.z)))))},o=function(){var t={root:0,found:!1};return function(e,o,i,s){t.root=0,t.found=!1;var r=o*o-4*e*i;if(r<0)return t;var n=Math.sqrt(r),c=(-o-n)/(2*e),h=(-o+n)/(2*e);if(c>h){var a=h;h=c,c=a}return c>0&&c<s?(t.root=c,t.found=!0,t):h>0&&h<s?(t.root=h,t.found=!0,t):t}}(),i=function(){function i(){this.radius=new t.Vector3(1,1,1),this.retry=0,this.basePointWorld=t.Vector3.Zero(),this.velocityWorld=t.Vector3.Zero(),this.normalizedVelocity=t.Vector3.Zero(),this._collisionPoint=t.Vector3.Zero(),this._planeIntersectionPoint=t.Vector3.Zero(),this._tempVector=t.Vector3.Zero(),this._tempVector2=t.Vector3.Zero(),this._tempVector3=t.Vector3.Zero(),this._tempVector4=t.Vector3.Zero(),this._edge=t.Vector3.Zero(),this._baseToVertex=t.Vector3.Zero(),this._destinationPoint=t.Vector3.Zero(),this._slidePlaneNormal=t.Vector3.Zero(),this._displacementVector=t.Vector3.Zero()}return i.prototype._initialize=function(e,o,i){this.velocity=o,t.Vector3.NormalizeToRef(o,this.normalizedVelocity),this.basePoint=e,e.multiplyToRef(this.radius,this.basePointWorld),o.multiplyToRef(this.radius,this.velocityWorld),this.velocityWorldLength=this.velocityWorld.length(),this.epsilon=i,this.collisionFound=!1},i.prototype._checkPointInTriangle=function(e,o,i,s,r){o.subtractToRef(e,this._tempVector),i.subtractToRef(e,this._tempVector2),t.Vector3.CrossToRef(this._tempVector,this._tempVector2,this._tempVector4);var n=t.Vector3.Dot(this._tempVector4,r);return!(n<0)&&(s.subtractToRef(e,this._tempVector3),t.Vector3.CrossToRef(this._tempVector2,this._tempVector3,this._tempVector4),n=t.Vector3.Dot(this._tempVector4,r),!(n<0)&&(t.Vector3.CrossToRef(this._tempVector3,this._tempVector,this._tempVector4),n=t.Vector3.Dot(this._tempVector4,r),n>=0))},i.prototype._canDoCollision=function(o,i,s,r){var n=t.Vector3.Distance(this.basePointWorld,o),c=Math.max(this.radius.x,this.radius.y,this.radius.z);return!(n>this.velocityWorldLength+c+i)&&!!e(s,r,this.basePointWorld,this.velocityWorldLength+c)},i.prototype._testTriangle=function(e,i,s,r,n,c){var h,a=!1;i||(i=[]),i[e]||(i[e]=new t.Plane(0,0,0,0),i[e].copyFromPoints(s,r,n));var l=i[e];if(c||l.isFrontFacingTo(this.normalizedVelocity,0)){var _=l.signedDistanceTo(this.basePoint),d=t.Vector3.Dot(l.normal,this.velocity);if(0==d){if(Math.abs(_)>=1)return;a=!0,h=0}else{h=(-1-_)/d;var V=(1-_)/d;if(h>V){var u=V;V=h,h=u}if(h>1||V<0)return;h<0&&(h=0),h>1&&(h=1)}this._collisionPoint.copyFromFloats(0,0,0);var P=!1,p=1;if(a||(this.basePoint.subtractToRef(l.normal,this._planeIntersectionPoint),this.velocity.scaleToRef(h,this._tempVector),this._planeIntersectionPoint.addInPlace(this._tempVector),this._checkPointInTriangle(this._planeIntersectionPoint,s,r,n,l.normal)&&(P=!0,p=h,this._collisionPoint.copyFrom(this._planeIntersectionPoint))),!P){var f=this.velocity.lengthSquared(),m=f;this.basePoint.subtractToRef(s,this._tempVector);var T=2*t.Vector3.Dot(this.velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,y=o(m,T,b,p);y.found&&(p=y.root,P=!0,this._collisionPoint.copyFrom(s)),this.basePoint.subtractToRef(r,this._tempVector),T=2*t.Vector3.Dot(this.velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,y=o(m,T,b,p),y.found&&(p=y.root,P=!0,this._collisionPoint.copyFrom(r)),this.basePoint.subtractToRef(n,this._tempVector),T=2*t.Vector3.Dot(this.velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,y=o(m,T,b,p),y.found&&(p=y.root,P=!0,this._collisionPoint.copyFrom(n)),r.subtractToRef(s,this._edge),s.subtractToRef(this.basePoint,this._baseToVertex);var g=this._edge.lengthSquared(),v=t.Vector3.Dot(this._edge,this.velocity),R=t.Vector3.Dot(this._edge,this._baseToVertex);if(m=g*-f+v*v,T=g*(2*t.Vector3.Dot(this.velocity,this._baseToVertex))-2*v*R,b=g*(1-this._baseToVertex.lengthSquared())+R*R,y=o(m,T,b,p),y.found){var D=(v*y.root-R)/g;D>=0&&D<=1&&(p=y.root,P=!0,this._edge.scaleInPlace(D),s.addToRef(this._edge,this._collisionPoint))}n.subtractToRef(r,this._edge),r.subtractToRef(this.basePoint,this._baseToVertex),g=this._edge.lengthSquared(),v=t.Vector3.Dot(this._edge,this.velocity),R=t.Vector3.Dot(this._edge,this._baseToVertex),m=g*-f+v*v,T=g*(2*t.Vector3.Dot(this.velocity,this._baseToVertex))-2*v*R,b=g*(1-this._baseToVertex.lengthSquared())+R*R,y=o(m,T,b,p),y.found&&(D=(v*y.root-R)/g,D>=0&&D<=1&&(p=y.root,P=!0,this._edge.scaleInPlace(D),r.addToRef(this._edge,this._collisionPoint))),s.subtractToRef(n,this._edge),n.subtractToRef(this.basePoint,this._baseToVertex),g=this._edge.lengthSquared(),v=t.Vector3.Dot(this._edge,this.velocity),R=t.Vector3.Dot(this._edge,this._baseToVertex),m=g*-f+v*v,T=g*(2*t.Vector3.Dot(this.velocity,this._baseToVertex))-2*v*R,b=g*(1-this._baseToVertex.lengthSquared())+R*R,y=o(m,T,b,p),y.found&&(D=(v*y.root-R)/g,D>=0&&D<=1&&(p=y.root,P=!0,this._edge.scaleInPlace(D),n.addToRef(this._edge,this._collisionPoint)))}if(P){var x=p*this.velocity.length();(!this.collisionFound||x<this.nearestDistance)&&(this.intersectionPoint?this.intersectionPoint.copyFrom(this._collisionPoint):this.intersectionPoint=this._collisionPoint.clone(),this.nearestDistance=x,this.collisionFound=!0)}}},i.prototype._collide=function(t,e,o,i,s,r,n){for(var c=i;c<s;c+=3){var h=e[o[c]-r],a=e[o[c+1]-r],l=e[o[c+2]-r];this._testTriangle(c,t,l,a,h,n)}},i.prototype._getResponse=function(e,o){e.addToRef(o,this._destinationPoint),o.scaleInPlace(this.nearestDistance/o.length()),this.basePoint.addToRef(o,e),e.subtractToRef(this.intersectionPoint,this._slidePlaneNormal),this._slidePlaneNormal.normalize(),this._slidePlaneNormal.scaleToRef(this.epsilon,this._displacementVector),e.addInPlace(this._displacementVector),this.intersectionPoint.addInPlace(this._displacementVector),this._slidePlaneNormal.scaleInPlace(t.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint,this._slidePlaneNormal,this._destinationPoint)),this._destinationPoint.subtractInPlace(this._slidePlaneNormal),this._destinationPoint.subtractToRef(this.intersectionPoint,o)},i}();t.Collider=i}(BABYLON||(BABYLON={}));var BABYLON;!function(o){o.WorkerIncluded=!0;var e=function(){function o(){this._meshes={},this._geometries={}}return o.prototype.getMeshes=function(){return this._meshes},o.prototype.getGeometries=function(){return this._geometries},o.prototype.getMesh=function(o){return this._meshes[o]},o.prototype.addMesh=function(o){this._meshes[o.uniqueId]=o},o.prototype.removeMesh=function(o){delete this._meshes[o]},o.prototype.getGeometry=function(o){return this._geometries[o]},o.prototype.addGeometry=function(o){this._geometries[o.id]=o},o.prototype.removeGeometry=function(o){delete this._geometries[o]},o}();o.CollisionCache=e;var i=function(){function e(e,i,r){this.collider=e,this._collisionCache=i,this.finalPosition=r,this.collisionsScalingMatrix=o.Matrix.Zero(),this.collisionTranformationMatrix=o.Matrix.Zero()}return e.prototype.collideWithWorld=function(o,e,i,r){var t=.01;if(this.collider.retry>=i)return void this.finalPosition.copyFrom(o);this.collider._initialize(o,e,t);for(var s,l=this._collisionCache.getMeshes(),n=Object.keys(l),a=n.length,c=0;c<a;++c)if(s=n[c],parseInt(s)!=r){var d=l[s];d.checkCollisions&&this.checkCollision(d)}return this.collider.collisionFound?(0===e.x&&0===e.y&&0===e.z||this.collider._getResponse(o,e),e.length()<=t?void this.finalPosition.copyFrom(o):(this.collider.retry++,void this.collideWithWorld(o,e,i,r))):void o.addToRef(e,this.finalPosition)},e.prototype.checkCollision=function(e){if(this.collider._canDoCollision(o.Vector3.FromArray(e.sphereCenter),e.sphereRadius,o.Vector3.FromArray(e.boxMinimum),o.Vector3.FromArray(e.boxMaximum))){o.Matrix.ScalingToRef(1/this.collider.radius.x,1/this.collider.radius.y,1/this.collider.radius.z,this.collisionsScalingMatrix);var i=o.Matrix.FromArray(e.worldMatrixFromCache);i.multiplyToRef(this.collisionsScalingMatrix,this.collisionTranformationMatrix),this.processCollisionsForSubMeshes(this.collisionTranformationMatrix,e)}},e.prototype.processCollisionsForSubMeshes=function(o,e){var i=e.subMeshes,r=i.length;if(!e.geometryId)return void console.log(\"no mesh geometry id\");var t=this._collisionCache.getGeometry(e.geometryId);if(!t)return void console.log(\"couldn't find geometry\",e.geometryId);for(var s=0;s<r;s++){var l=i[s];r>1&&!this.checkSubmeshCollision(l)||(this.collideForSubMesh(l,o,t),this.collider.collisionFound&&(this.collider.collidedMesh=e.uniqueId))}},e.prototype.collideForSubMesh=function(e,i,r){if(!r.positionsArray){r.positionsArray=[];for(var t=0,s=r.positions.length;t<s;t+=3){var l=o.Vector3.FromArray([r.positions[t],r.positions[t+1],r.positions[t+2]]);r.positionsArray.push(l)}}if(!e._lastColliderWorldVertices||!e._lastColliderTransformMatrix.equals(i)){e._lastColliderTransformMatrix=i.clone(),e._lastColliderWorldVertices=[],e._trianglePlanes=[];for(var n=e.verticesStart,a=e.verticesStart+e.verticesCount,t=n;t<a;t++)e._lastColliderWorldVertices.push(o.Vector3.TransformCoordinates(r.positionsArray[t],i))}this.collider._collide(e._trianglePlanes,e._lastColliderWorldVertices,r.indices,e.indexStart,e.indexStart+e.indexCount,e.verticesStart,e.hasMaterial)},e.prototype.checkSubmeshCollision=function(e){return this.collider._canDoCollision(o.Vector3.FromArray(e.sphereCenter),e.sphereRadius,o.Vector3.FromArray(e.boxMinimum),o.Vector3.FromArray(e.boxMaximum))},e}();o.CollideWorker=i;var r=function(){function r(){}return r.prototype.onInit=function(i){this._collisionCache=new e;var r={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.INIT};postMessage(r,void 0)},r.prototype.onUpdate=function(e){var i=this,r={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.UPDATE};try{for(var t in e.updatedGeometries)e.updatedGeometries.hasOwnProperty(t)&&this._collisionCache.addGeometry(e.updatedGeometries[t]);for(var s in e.updatedMeshes)e.updatedMeshes.hasOwnProperty(s)&&this._collisionCache.addMesh(e.updatedMeshes[s]);e.removedGeometries.forEach(function(o){i._collisionCache.removeGeometry(o)}),e.removedMeshes.forEach(function(o){i._collisionCache.removeMesh(o)})}catch(l){r.error=o.WorkerReplyType.UNKNOWN_ERROR}postMessage(r,void 0)},r.prototype.onCollision=function(e){var r=o.Vector3.Zero(),t=new o.Collider;t.radius=o.Vector3.FromArray(e.collider.radius);var s=new i(t,this._collisionCache,r);s.collideWithWorld(o.Vector3.FromArray(e.collider.position),o.Vector3.FromArray(e.collider.velocity),e.maximumRetry,e.excludedMeshUniqueId);var l={collidedMeshUniqueId:t.collidedMesh,collisionId:e.collisionId,newPosition:r.asArray()},n={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.COLLIDE,payload:l};postMessage(n,void 0)},r}();o.CollisionDetectorTransferable=r;try{if(self&&self instanceof WorkerGlobalScope){window={},o.Collider||(importScripts(\"./babylon.collisionCoordinator.js\"),importScripts(\"./babylon.collider.js\"),importScripts(\"../Math/babylon.math.js\"));var t=new r,s=function(e){var i=e.data;switch(i.taskType){case o.WorkerTaskType.INIT:t.onInit(i.payload);break;case o.WorkerTaskType.COLLIDE:t.onCollision(i.payload);break;case o.WorkerTaskType.UPDATE:t.onUpdate(i.payload)}};self.onmessage=s}}catch(l){console.log(\"single worker init\")}}(BABYLON||(BABYLON={}));var BABYLON;!function(e){e.CollisionWorker=\"\",function(e){e[e.INIT=0]=\"INIT\",e[e.UPDATE=1]=\"UPDATE\",e[e.COLLIDE=2]=\"COLLIDE\"}(e.WorkerTaskType||(e.WorkerTaskType={}));var o=e.WorkerTaskType;!function(e){e[e.SUCCESS=0]=\"SUCCESS\",e[e.UNKNOWN_ERROR=1]=\"UNKNOWN_ERROR\"}(e.WorkerReplyType||(e.WorkerReplyType={}));var i=e.WorkerReplyType,t=function(){function t(){var r=this;this._scaledPosition=e.Vector3.Zero(),this._scaledVelocity=e.Vector3.Zero(),this.onMeshUpdated=function(e){r._addUpdateMeshesList[e.uniqueId]=t.SerializeMesh(e)},this.onGeometryUpdated=function(e){r._addUpdateGeometriesList[e.id]=t.SerializeGeometry(e)},this._afterRender=function(){if(r._init&&!(0==r._toRemoveGeometryArray.length&&0==r._toRemoveMeshesArray.length&&0==Object.keys(r._addUpdateGeometriesList).length&&0==Object.keys(r._addUpdateMeshesList).length||r._runningUpdated>4)){++r._runningUpdated;var e={updatedMeshes:r._addUpdateMeshesList,updatedGeometries:r._addUpdateGeometriesList,removedGeometries:r._toRemoveGeometryArray,removedMeshes:r._toRemoveMeshesArray},i={payload:e,taskType:o.UPDATE},t=[];for(var s in e.updatedGeometries)e.updatedGeometries.hasOwnProperty(s)&&(t.push(i.payload.updatedGeometries[s].indices.buffer),t.push(i.payload.updatedGeometries[s].normals.buffer),t.push(i.payload.updatedGeometries[s].positions.buffer));r._worker.postMessage(i,t),r._addUpdateMeshesList={},r._addUpdateGeometriesList={},r._toRemoveGeometryArray=[],r._toRemoveMeshesArray=[]}},this._onMessageFromWorker=function(t){var s=t.data;if(s.error!=i.SUCCESS)return void e.Tools.Warn(\"error returned from worker!\");switch(s.taskType){case o.INIT:r._init=!0,r._scene.meshes.forEach(function(e){r.onMeshAdded(e)}),r._scene.getGeometries().forEach(function(e){r.onGeometryAdded(e)});break;case o.UPDATE:r._runningUpdated--;break;case o.COLLIDE:r._runningCollisionTask=!1;var n=s.payload;if(!r._collisionsCallbackArray[n.collisionId])return;r._collisionsCallbackArray[n.collisionId](n.collisionId,e.Vector3.FromArray(n.newPosition),r._scene.getMeshByUniqueID(n.collidedMeshUniqueId)),r._collisionsCallbackArray[n.collisionId]=void 0}},this._collisionsCallbackArray=[],this._init=!1,this._runningUpdated=0,this._runningCollisionTask=!1,this._addUpdateMeshesList={},this._addUpdateGeometriesList={},this._toRemoveGeometryArray=[],this._toRemoveMeshesArray=[]}return t.prototype.getNewPosition=function(e,i,t,r,s,n,a){if(this._init&&!this._collisionsCallbackArray[a]&&!this._collisionsCallbackArray[a+1e5]){e.divideToRef(t.radius,this._scaledPosition),i.divideToRef(t.radius,this._scaledVelocity),this._collisionsCallbackArray[a]=n;var d={collider:{position:this._scaledPosition.asArray(),velocity:this._scaledVelocity.asArray(),radius:t.radius.asArray()},collisionId:a,excludedMeshUniqueId:s?s.uniqueId:null,maximumRetry:r},l={payload:d,taskType:o.COLLIDE};this._worker.postMessage(l)}},t.prototype.init=function(i){this._scene=i,this._scene.registerAfterRender(this._afterRender);var t=e.WorkerIncluded?e.Engine.CodeRepository+\"Collisions/babylon.collisionWorker.js\":URL.createObjectURL(new Blob([e.CollisionWorker],{type:\"application/javascript\"}));this._worker=new Worker(t),this._worker.onmessage=this._onMessageFromWorker;var r={payload:{},taskType:o.INIT};this._worker.postMessage(r)},t.prototype.destroy=function(){this._scene.unregisterAfterRender(this._afterRender),this._worker.terminate()},t.prototype.onMeshAdded=function(e){e.registerAfterWorldMatrixUpdate(this.onMeshUpdated),this.onMeshUpdated(e)},t.prototype.onMeshRemoved=function(e){this._toRemoveMeshesArray.push(e.uniqueId)},t.prototype.onGeometryAdded=function(e){e.onGeometryUpdated=this.onGeometryUpdated,this.onGeometryUpdated(e)},t.prototype.onGeometryDeleted=function(e){this._toRemoveGeometryArray.push(e.id)},t.SerializeMesh=function(o){var i=[];o.subMeshes&&(i=o.subMeshes.map(function(e,o){return{position:o,verticesStart:e.verticesStart,verticesCount:e.verticesCount,indexStart:e.indexStart,indexCount:e.indexCount,hasMaterial:!!e.getMaterial(),sphereCenter:e.getBoundingInfo().boundingSphere.centerWorld.asArray(),sphereRadius:e.getBoundingInfo().boundingSphere.radiusWorld,boxMinimum:e.getBoundingInfo().boundingBox.minimumWorld.asArray(),boxMaximum:e.getBoundingInfo().boundingBox.maximumWorld.asArray()}}));var t=null;return o instanceof e.Mesh?t=o.geometry?o.geometry.id:null:o instanceof e.InstancedMesh&&(t=o.sourceMesh&&o.sourceMesh.geometry?o.sourceMesh.geometry.id:null),{uniqueId:o.uniqueId,id:o.id,name:o.name,geometryId:t,sphereCenter:o.getBoundingInfo().boundingSphere.centerWorld.asArray(),sphereRadius:o.getBoundingInfo().boundingSphere.radiusWorld,boxMinimum:o.getBoundingInfo().boundingBox.minimumWorld.asArray(),boxMaximum:o.getBoundingInfo().boundingBox.maximumWorld.asArray(),worldMatrixFromCache:o.worldMatrixFromCache.asArray(),subMeshes:i,checkCollisions:o.checkCollisions}},t.SerializeGeometry=function(o){return{id:o.id,positions:new Float32Array(o.getVerticesData(e.VertexBuffer.PositionKind)||[]),normals:new Float32Array(o.getVerticesData(e.VertexBuffer.NormalKind)||[]),indices:new Int32Array(o.getIndices()||[])}},t}();e.CollisionCoordinatorWorker=t;var r=function(){function o(){this._scaledPosition=e.Vector3.Zero(),this._scaledVelocity=e.Vector3.Zero(),this._finalPosition=e.Vector3.Zero()}return o.prototype.getNewPosition=function(e,o,i,t,r,s,n){e.divideToRef(i.radius,this._scaledPosition),o.divideToRef(i.radius,this._scaledVelocity),i.collidedMesh=null,i.retry=0,i.initialVelocity=this._scaledVelocity,i.initialPosition=this._scaledPosition,this._collideWithWorld(this._scaledPosition,this._scaledVelocity,i,t,this._finalPosition,r),this._finalPosition.multiplyInPlace(i.radius),s(n,this._finalPosition,i.collidedMesh)},o.prototype.init=function(e){this._scene=e},o.prototype.destroy=function(){},o.prototype.onMeshAdded=function(e){},o.prototype.onMeshUpdated=function(e){},o.prototype.onMeshRemoved=function(e){},o.prototype.onGeometryAdded=function(e){},o.prototype.onGeometryUpdated=function(e){},o.prototype.onGeometryDeleted=function(e){},o.prototype._collideWithWorld=function(o,i,t,r,s,n){void 0===n&&(n=null);var a=10*e.Engine.CollisionsEpsilon;if(t.retry>=r)return void s.copyFrom(o);t._initialize(o,i,a);for(var d=0;d<this._scene.meshes.length;d++){var l=this._scene.meshes[d];l.isEnabled()&&l.checkCollisions&&l.subMeshes&&l!==n&&l._checkCollision(t)}return t.collisionFound?(0===i.x&&0===i.y&&0===i.z||t._getResponse(o,i),i.length()<=a?void s.copyFrom(o):(t.retry++,void this._collideWithWorld(o,i,t,r,s,n))):void o.addToRef(i,s)},o}();e.CollisionCoordinatorLegacy=r}(BABYLON||(BABYLON={}));var BABYLON;!function(t){t.ToGammaSpace=1/2.2,t.ToLinearSpace=2.2,t.Epsilon=.001;var i=function(){function t(){}return t.WithinEpsilon=function(t,i,r){void 0===r&&(r=1.401298e-45);var n=t-i;return-r<=n&&n<=r},t.ToHex=function(t){var i=t.toString(16);return t<=15?(\"0\"+i).toUpperCase():i.toUpperCase()},t.Sign=function(t){return t=+t,0===t||isNaN(t)?t:t>0?1:-1},t.Clamp=function(t,i,r){return void 0===i&&(i=0),void 0===r&&(r=1),Math.min(r,Math.max(i,t))},t}();t.MathTools=i;var r=function(){function r(t,i,r){void 0===t&&(t=0),void 0===i&&(i=0),void 0===r&&(r=0),this.r=t,this.g=i,this.b=r}return r.prototype.toString=function(){return\"{R: \"+this.r+\" G:\"+this.g+\" B:\"+this.b+\"}\"},r.prototype.getClassName=function(){return\"Color3\"},r.prototype.getHashCode=function(){var t=this.r||0;return t=397*t^(this.g||0),t=397*t^(this.b||0)},r.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.r,t[i+1]=this.g,t[i+2]=this.b,this},r.prototype.toColor4=function(t){return void 0===t&&(t=1),new n(this.r,this.g,this.b,t)},r.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},r.prototype.toLuminance=function(){return.3*this.r+.59*this.g+.11*this.b},r.prototype.multiply=function(t){return new r(this.r*t.r,this.g*t.g,this.b*t.b)},r.prototype.multiplyToRef=function(t,i){return i.r=this.r*t.r,i.g=this.g*t.g,i.b=this.b*t.b,this},r.prototype.equals=function(t){return t&&this.r===t.r&&this.g===t.g&&this.b===t.b},r.prototype.equalsFloats=function(t,i,r){return this.r===t&&this.g===i&&this.b===r},r.prototype.scale=function(t){return new r(this.r*t,this.g*t,this.b*t)},r.prototype.scaleToRef=function(t,i){return i.r=this.r*t,i.g=this.g*t,i.b=this.b*t,this},r.prototype.add=function(t){return new r(this.r+t.r,this.g+t.g,this.b+t.b)},r.prototype.addToRef=function(t,i){return i.r=this.r+t.r,i.g=this.g+t.g,i.b=this.b+t.b,this},r.prototype.subtract=function(t){return new r(this.r-t.r,this.g-t.g,this.b-t.b)},r.prototype.subtractToRef=function(t,i){return i.r=this.r-t.r,i.g=this.g-t.g,i.b=this.b-t.b,this},r.prototype.clone=function(){return new r(this.r,this.g,this.b)},r.prototype.copyFrom=function(t){return this.r=t.r,this.g=t.g,this.b=t.b,this},r.prototype.copyFromFloats=function(t,i,r){return this.r=t,this.g=i,this.b=r,this},r.prototype.toHexString=function(){var t=255*this.r|0,r=255*this.g|0,n=255*this.b|0;return\"#\"+i.ToHex(t)+i.ToHex(r)+i.ToHex(n)},r.prototype.toLinearSpace=function(){var t=new r;return this.toLinearSpaceToRef(t),t},r.prototype.toLinearSpaceToRef=function(i){return i.r=Math.pow(this.r,t.ToLinearSpace),i.g=Math.pow(this.g,t.ToLinearSpace),i.b=Math.pow(this.b,t.ToLinearSpace),this},r.prototype.toGammaSpace=function(){var t=new r;return this.toGammaSpaceToRef(t),t},r.prototype.toGammaSpaceToRef=function(i){return i.r=Math.pow(this.r,t.ToGammaSpace),i.g=Math.pow(this.g,t.ToGammaSpace),i.b=Math.pow(this.b,t.ToGammaSpace),this},r.FromHexString=function(t){if(\"#\"!==t.substring(0,1)||7!==t.length)return new r(0,0,0);var i=parseInt(t.substring(1,3),16),n=parseInt(t.substring(3,5),16),o=parseInt(t.substring(5,7),16);return r.FromInts(i,n,o)},r.FromArray=function(t,i){return void 0===i&&(i=0),new r(t[i],t[i+1],t[i+2])},r.FromInts=function(t,i,n){return new r(t/255,i/255,n/255)},r.Lerp=function(t,i,n){var o=t.r+(i.r-t.r)*n,e=t.g+(i.g-t.g)*n,s=t.b+(i.b-t.b)*n;return new r(o,e,s)},r.Red=function(){return new r(1,0,0)},r.Green=function(){return new r(0,1,0)},r.Blue=function(){return new r(0,0,1)},r.Black=function(){return new r(0,0,0)},r.White=function(){return new r(1,1,1)},r.Purple=function(){return new r(.5,0,.5)},r.Magenta=function(){return new r(1,0,1)},r.Yellow=function(){return new r(1,1,0)},r.Gray=function(){return new r(.5,.5,.5)},r}();t.Color3=r;var n=function(){function t(t,i,r,n){this.r=t,this.g=i,this.b=r,this.a=n}return t.prototype.addInPlace=function(t){return this.r+=t.r,this.g+=t.g,this.b+=t.b,this.a+=t.a,this},t.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},t.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.r,t[i+1]=this.g,t[i+2]=this.b,t[i+3]=this.a,this},t.prototype.add=function(i){return new t(this.r+i.r,this.g+i.g,this.b+i.b,this.a+i.a)},t.prototype.subtract=function(i){return new t(this.r-i.r,this.g-i.g,this.b-i.b,this.a-i.a)},t.prototype.subtractToRef=function(t,i){return i.r=this.r-t.r,i.g=this.g-t.g,i.b=this.b-t.b,i.a=this.a-t.a,this},t.prototype.scale=function(i){return new t(this.r*i,this.g*i,this.b*i,this.a*i)},t.prototype.scaleToRef=function(t,i){return i.r=this.r*t,i.g=this.g*t,i.b=this.b*t,i.a=this.a*t,this},t.prototype.multiply=function(i){return new t(this.r*i.r,this.g*i.g,this.b*i.b,this.a*i.a)},t.prototype.multiplyToRef=function(t,i){return i.r=this.r*t.r,i.g=this.g*t.g,i.b=this.b*t.b,i.a=this.a*t.a,i},t.prototype.toString=function(){return\"{R: \"+this.r+\" G:\"+this.g+\" B:\"+this.b+\" A:\"+this.a+\"}\"},t.prototype.getClassName=function(){return\"Color4\"},t.prototype.getHashCode=function(){var t=this.r||0;return t=397*t^(this.g||0),t=397*t^(this.b||0),t=397*t^(this.a||0)},t.prototype.clone=function(){return new t(this.r,this.g,this.b,this.a)},t.prototype.copyFrom=function(t){return this.r=t.r,this.g=t.g,this.b=t.b,this.a=t.a,this},t.prototype.toHexString=function(){var t=255*this.r|0,r=255*this.g|0,n=255*this.b|0,o=255*this.a|0;return\"#\"+i.ToHex(t)+i.ToHex(r)+i.ToHex(n)+i.ToHex(o)},t.FromHexString=function(i){if(\"#\"!==i.substring(0,1)||9!==i.length)return new t(0,0,0,0);var r=parseInt(i.substring(1,3),16),n=parseInt(i.substring(3,5),16),o=parseInt(i.substring(5,7),16),e=parseInt(i.substring(7,9),16);return t.FromInts(r,n,o,e)},t.Lerp=function(i,r,n){var o=new t(0,0,0,0);return t.LerpToRef(i,r,n,o),o},t.LerpToRef=function(t,i,r,n){n.r=t.r+(i.r-t.r)*r,n.g=t.g+(i.g-t.g)*r,n.b=t.b+(i.b-t.b)*r,n.a=t.a+(i.a-t.a)*r},t.FromArray=function(i,r){return void 0===r&&(r=0),new t(i[r],i[r+1],i[r+2],i[r+3])},t.FromInts=function(i,r,n,o){return new t(i/255,r/255,n/255,o/255)},t.CheckColors4=function(t,i){if(t.length===3*i){for(var r=[],n=0;n<t.length;n+=3){var o=n/3*4;r[o]=t[n],r[o+1]=t[n+1],r[o+2]=t[n+2],r[o+3]=1}return r}return t},t}();t.Color4=n;var o=function(){function r(t,i){this.x=t,this.y=i}return r.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\"}\"},r.prototype.getClassName=function(){return\"Vector2\"},r.prototype.getHashCode=function(){var t=this.x||0;return t=397*t^(this.y||0)},r.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,this},r.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},r.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this},r.prototype.copyFromFloats=function(t,i){return this.x=t,this.y=i,this},r.prototype.add=function(t){return new r(this.x+t.x,this.y+t.y)},r.prototype.addToRef=function(t,i){return i.x=this.x+t.x,i.y=this.y+t.y,this},r.prototype.addInPlace=function(t){return this.x+=t.x,this.y+=t.y,this},r.prototype.addVector3=function(t){return new r(this.x+t.x,this.y+t.y)},r.prototype.subtract=function(t){return new r(this.x-t.x,this.y-t.y)},r.prototype.subtractToRef=function(t,i){return i.x=this.x-t.x,i.y=this.y-t.y,this},r.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this},r.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this},r.prototype.multiply=function(t){return new r(this.x*t.x,this.y*t.y)},r.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,this},r.prototype.multiplyByFloats=function(t,i){return new r(this.x*t,this.y*i)},r.prototype.divide=function(t){return new r(this.x/t.x,this.y/t.y)},r.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,this},r.prototype.negate=function(){return new r((-this.x),(-this.y))},r.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this},r.prototype.scale=function(t){return new r(this.x*t,this.y*t)},r.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y},r.prototype.equalsWithEpsilon=function(r,n){return void 0===n&&(n=t.Epsilon),r&&i.WithinEpsilon(this.x,r.x,n)&&i.WithinEpsilon(this.y,r.y,n)},r.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y)},r.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y},r.prototype.normalize=function(){var t=this.length();if(0===t)return this;var i=1/t;return this.x*=i,this.y*=i,this},r.prototype.clone=function(){return new r(this.x,this.y)},r.Zero=function(){return new r(0,0)},r.FromArray=function(t,i){return void 0===i&&(i=0),new r(t[i],t[i+1])},r.FromArrayToRef=function(t,i,r){r.x=t[i],r.y=t[i+1]},r.CatmullRom=function(t,i,n,o,e){var s=e*e,h=e*s,a=.5*(2*i.x+(-t.x+n.x)*e+(2*t.x-5*i.x+4*n.x-o.x)*s+(-t.x+3*i.x-3*n.x+o.x)*h),u=.5*(2*i.y+(-t.y+n.y)*e+(2*t.y-5*i.y+4*n.y-o.y)*s+(-t.y+3*i.y-3*n.y+o.y)*h);return new r(a,u)},r.Clamp=function(t,i,n){var o=t.x;o=o>n.x?n.x:o,o=o<i.x?i.x:o;var e=t.y;return e=e>n.y?n.y:e,e=e<i.y?i.y:e,new r(o,e)},r.Hermite=function(t,i,n,o,e){var s=e*e,h=e*s,a=2*h-3*s+1,u=-2*h+3*s,m=h-2*s+e,y=h-s,c=t.x*a+n.x*u+i.x*m+o.x*y,p=t.y*a+n.y*u+i.y*m+o.y*y;return new r(c,p)},r.Lerp=function(t,i,n){var o=t.x+(i.x-t.x)*n,e=t.y+(i.y-t.y)*n;return new r(o,e)},r.Dot=function(t,i){return t.x*i.x+t.y*i.y},r.Normalize=function(t){var i=t.clone();return i.normalize(),i},r.Minimize=function(t,i){var n=t.x<i.x?t.x:i.x,o=t.y<i.y?t.y:i.y;return new r(n,o)},r.Maximize=function(t,i){var n=t.x>i.x?t.x:i.x,o=t.y>i.y?t.y:i.y;return new r(n,o)},r.Transform=function(t,i){var n=r.Zero();return r.TransformToRef(t,i,n),n},r.TransformToRef=function(t,i,r){var n=t.x*i.m[0]+t.y*i.m[4]+i.m[12],o=t.x*i.m[1]+t.y*i.m[5]+i.m[13];r.x=n,r.y=o},r.PointInTriangle=function(t,i,r,n){var o=.5*(-r.y*n.x+i.y*(-r.x+n.x)+i.x*(r.y-n.y)+r.x*n.y),e=o<0?-1:1,s=(i.y*n.x-i.x*n.y+(n.y-i.y)*t.x+(i.x-n.x)*t.y)*e,h=(i.x*r.y-i.y*r.x+(i.y-r.y)*t.x+(r.x-i.x)*t.y)*e;return s>0&&h>0&&s+h<2*o*e},r.Distance=function(t,i){return Math.sqrt(r.DistanceSquared(t,i))},r.DistanceSquared=function(t,i){var r=t.x-i.x,n=t.y-i.y;return r*r+n*n},r.Center=function(t,i){var r=t.add(i);return r.scaleInPlace(.5),r},r.DistanceOfPointFromSegment=function(t,i,n){var o=r.DistanceSquared(i,n);if(0===o)return r.Distance(t,i);var e=n.subtract(i),s=Math.max(0,Math.min(1,r.Dot(t.subtract(i),e)/o)),h=i.add(e.multiplyByFloats(s,s));return r.Distance(t,h)},r}();t.Vector2=o;var e=function(){function r(t,i,r){this.x=t,this.y=i,this.z=r}return r.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\"}\"},r.prototype.getClassName=function(){return\"Vector3\"},r.prototype.getHashCode=function(){var t=this.x||0;return t=397*t^(this.y||0),t=397*t^(this.z||0)},r.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},r.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,t[i+2]=this.z,this},r.prototype.toQuaternion=function(){var t=new a(0,0,0,1),i=Math.cos(.5*(this.x+this.z)),r=Math.sin(.5*(this.x+this.z)),n=Math.cos(.5*(this.z-this.x)),o=Math.sin(.5*(this.z-this.x)),e=Math.cos(.5*this.y),s=Math.sin(.5*this.y);return t.x=n*s,t.y=-o*s,t.z=r*e,t.w=i*e,t},r.prototype.addInPlace=function(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this},r.prototype.add=function(t){return new r(this.x+t.x,this.y+t.y,this.z+t.z)},r.prototype.addToRef=function(t,i){return i.x=this.x+t.x,i.y=this.y+t.y,i.z=this.z+t.z,this},r.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this},r.prototype.subtract=function(t){return new r(this.x-t.x,this.y-t.y,this.z-t.z)},r.prototype.subtractToRef=function(t,i){return i.x=this.x-t.x,i.y=this.y-t.y,i.z=this.z-t.z,this},r.prototype.subtractFromFloats=function(t,i,n){return new r(this.x-t,this.y-i,this.z-n)},r.prototype.subtractFromFloatsToRef=function(t,i,r,n){return n.x=this.x-t,n.y=this.y-i,n.z=this.z-r,this},r.prototype.negate=function(){return new r((-this.x),(-this.y),(-this.z))},r.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this.z*=t,this},r.prototype.scale=function(t){return new r(this.x*t,this.y*t,this.z*t)},r.prototype.scaleToRef=function(t,i){i.x=this.x*t,i.y=this.y*t,i.z=this.z*t},r.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z},r.prototype.equalsWithEpsilon=function(r,n){return void 0===n&&(n=t.Epsilon),r&&i.WithinEpsilon(this.x,r.x,n)&&i.WithinEpsilon(this.y,r.y,n)&&i.WithinEpsilon(this.z,r.z,n)},r.prototype.equalsToFloats=function(t,i,r){return this.x===t&&this.y===i&&this.z===r},r.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this},r.prototype.multiply=function(t){return new r(this.x*t.x,this.y*t.y,this.z*t.z)},r.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,i.z=this.z*t.z,this},r.prototype.multiplyByFloats=function(t,i,n){return new r(this.x*t,this.y*i,this.z*n)},r.prototype.divide=function(t){return new r(this.x/t.x,this.y/t.y,this.z/t.z)},r.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,i.z=this.z/t.z,this},r.prototype.MinimizeInPlace=function(t){return t.x<this.x&&(this.x=t.x),t.y<this.y&&(this.y=t.y),t.z<this.z&&(this.z=t.z),this},r.prototype.MaximizeInPlace=function(t){return t.x>this.x&&(this.x=t.x),t.y>this.y&&(this.y=t.y),t.z>this.z&&(this.z=t.z),this},r.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)},r.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y+this.z*this.z},r.prototype.normalize=function(){var t=this.length();if(0===t||1===t)return this;var i=1/t;return this.x*=i,this.y*=i,this.z*=i,this},r.prototype.clone=function(){return new r(this.x,this.y,this.z)},r.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this},r.prototype.copyFromFloats=function(t,i,r){return this.x=t,this.y=i,this.z=r,this},r.GetClipFactor=function(t,i,n,o){var e=r.Dot(t,n)-o,s=r.Dot(i,n)-o,h=e/(e-s);return h},r.FromArray=function(t,i){return i||(i=0),new r(t[i],t[i+1],t[i+2])},r.FromFloatArray=function(t,i){return i||(i=0),new r(t[i],t[i+1],t[i+2])},r.FromArrayToRef=function(t,i,r){r.x=t[i],r.y=t[i+1],r.z=t[i+2]},r.FromFloatArrayToRef=function(t,i,r){r.x=t[i],r.y=t[i+1],r.z=t[i+2]},r.FromFloatsToRef=function(t,i,r,n){n.x=t,n.y=i,n.z=r},r.Zero=function(){return new r(0,0,0)},r.Up=function(){return new r(0,1,0)},r.TransformCoordinates=function(t,i){var n=r.Zero();return r.TransformCoordinatesToRef(t,i,n),n},r.TransformCoordinatesToRef=function(t,i,r){var n=t.x*i.m[0]+t.y*i.m[4]+t.z*i.m[8]+i.m[12],o=t.x*i.m[1]+t.y*i.m[5]+t.z*i.m[9]+i.m[13],e=t.x*i.m[2]+t.y*i.m[6]+t.z*i.m[10]+i.m[14],s=t.x*i.m[3]+t.y*i.m[7]+t.z*i.m[11]+i.m[15];r.x=n/s,r.y=o/s,r.z=e/s},r.TransformCoordinatesFromFloatsToRef=function(t,i,r,n,o){var e=t*n.m[0]+i*n.m[4]+r*n.m[8]+n.m[12],s=t*n.m[1]+i*n.m[5]+r*n.m[9]+n.m[13],h=t*n.m[2]+i*n.m[6]+r*n.m[10]+n.m[14],a=t*n.m[3]+i*n.m[7]+r*n.m[11]+n.m[15];o.x=e/a,o.y=s/a,o.z=h/a},r.TransformNormal=function(t,i){var n=r.Zero();return r.TransformNormalToRef(t,i,n),n},r.TransformNormalToRef=function(t,i,r){r.x=t.x*i.m[0]+t.y*i.m[4]+t.z*i.m[8],r.y=t.x*i.m[1]+t.y*i.m[5]+t.z*i.m[9],r.z=t.x*i.m[2]+t.y*i.m[6]+t.z*i.m[10]},r.TransformNormalFromFloatsToRef=function(t,i,r,n,o){o.x=t*n.m[0]+i*n.m[4]+r*n.m[8],o.y=t*n.m[1]+i*n.m[5]+r*n.m[9],o.z=t*n.m[2]+i*n.m[6]+r*n.m[10]},r.CatmullRom=function(t,i,n,o,e){var s=e*e,h=e*s,a=.5*(2*i.x+(-t.x+n.x)*e+(2*t.x-5*i.x+4*n.x-o.x)*s+(-t.x+3*i.x-3*n.x+o.x)*h),u=.5*(2*i.y+(-t.y+n.y)*e+(2*t.y-5*i.y+4*n.y-o.y)*s+(-t.y+3*i.y-3*n.y+o.y)*h),m=.5*(2*i.z+(-t.z+n.z)*e+(2*t.z-5*i.z+4*n.z-o.z)*s+(-t.z+3*i.z-3*n.z+o.z)*h);return new r(a,u,m)},r.Clamp=function(t,i,n){var o=t.x;o=o>n.x?n.x:o,o=o<i.x?i.x:o;var e=t.y;e=e>n.y?n.y:e,e=e<i.y?i.y:e;var s=t.z;return s=s>n.z?n.z:s,s=s<i.z?i.z:s,new r(o,e,s)},r.Hermite=function(t,i,n,o,e){var s=e*e,h=e*s,a=2*h-3*s+1,u=-2*h+3*s,m=h-2*s+e,y=h-s,c=t.x*a+n.x*u+i.x*m+o.x*y,p=t.y*a+n.y*u+i.y*m+o.y*y,f=t.z*a+n.z*u+i.z*m+o.z*y;return new r(c,p,f)},r.Lerp=function(t,i,n){var o=t.x+(i.x-t.x)*n,e=t.y+(i.y-t.y)*n,s=t.z+(i.z-t.z)*n;return new r(o,e,s)},r.Dot=function(t,i){return t.x*i.x+t.y*i.y+t.z*i.z},r.Cross=function(t,i){var n=r.Zero();return r.CrossToRef(t,i,n),n},r.CrossToRef=function(t,i,r){M.Vector3[0].x=t.y*i.z-t.z*i.y,M.Vector3[0].y=t.z*i.x-t.x*i.z,M.Vector3[0].z=t.x*i.y-t.y*i.x,r.copyFrom(M.Vector3[0])},r.Normalize=function(t){var i=r.Zero();return r.NormalizeToRef(t,i),i},r.NormalizeToRef=function(t,i){i.copyFrom(t),i.normalize()},r.Project=function(t,i,n,o){var e=o.width,s=o.height,h=o.x,a=o.y,m=r._viewportMatrixCache?r._viewportMatrixCache:r._viewportMatrixCache=new u;u.FromValuesToRef(e/2,0,0,0,0,-s/2,0,0,0,0,1,0,h+e/2,s/2+a,0,1,m);var y=r._matrixCache?r._matrixCache:r._matrixCache=new u;return i.multiplyToRef(n,y),y.multiplyToRef(m,y),r.TransformCoordinates(t,y)},r.UnprojectFromTransform=function(t,n,o,e,s){var h=r._matrixCache?r._matrixCache:r._matrixCache=new u;e.multiplyToRef(s,h),h.invert(),t.x=t.x/n*2-1,t.y=-(t.y/o*2-1);var a=r.TransformCoordinates(t,h),m=t.x*h.m[3]+t.y*h.m[7]+t.z*h.m[11]+h.m[15];return i.WithinEpsilon(m,1)&&(a=a.scale(1/m)),a},r.Unproject=function(t,n,o,e,s,h){var a=r._matrixCache?r._matrixCache:r._matrixCache=new u;e.multiplyToRef(s,a),a.multiplyToRef(h,a),a.invert();var m=new r(t.x/n*2-1,(-(t.y/o*2-1)),t.z),y=r.TransformCoordinates(m,a),c=m.x*a.m[3]+m.y*a.m[7]+m.z*a.m[11]+a.m[15];return i.WithinEpsilon(c,1)&&(y=y.scale(1/c)),y},r.Minimize=function(t,i){var r=t.clone();return r.MinimizeInPlace(i),r},r.Maximize=function(t,i){var r=t.clone();return r.MaximizeInPlace(i),r},r.Distance=function(t,i){return Math.sqrt(r.DistanceSquared(t,i))},r.DistanceSquared=function(t,i){var r=t.x-i.x,n=t.y-i.y,o=t.z-i.z;return r*r+n*n+o*o},r.Center=function(t,i){var r=t.add(i);return r.scaleInPlace(.5),r},r.RotationFromAxis=function(t,i,n){var o=r.Zero();return r.RotationFromAxisToRef(t,i,n,o),o},r.RotationFromAxisToRef=function(n,o,e,s){var h=n.normalize(),a=e.normalize(),u=p.X,m=p.Y,y=0,c=0,f=0,x=0,l=0,z=0,w=0,v=-1,d=0,g=M.Vector3[0],R=0,T=M.Vector3[1];i.WithinEpsilon(a.z,0,t.Epsilon)?z=1:i.WithinEpsilon(a.x,0,t.Epsilon)?x=1:(w=a.z/a.x,x=-w*Math.sqrt(1/(1+w*w)),z=Math.sqrt(1/(1+w*w))),T.x=x,T.y=l,T.z=z,T.normalize(),r.CrossToRef(h,T,g),g.normalize(),r.Dot(a,g)<0&&(v=1),R=r.Dot(h,T),R=Math.min(1,Math.max(-1,R)),f=Math.acos(R)*v,r.Dot(T,u)<0&&(f=Math.PI+f,T=T.scaleInPlace(-1),d++);var _=M.Vector3[2],A=M.Vector3[3];x=0,l=0,z=0,v=-1,i.WithinEpsilon(a.z,0,t.Epsilon)?x=1:(w=T.z/T.x,x=-w*Math.sqrt(1/(1+w*w)),z=Math.sqrt(1/(1+w*w))),_.x=x,_.y=l,_.z=z,_.normalize(),r.CrossToRef(_,T,A),A.normalize(),r.CrossToRef(a,_,g),g.normalize(),r.Dot(T,g)<0&&(v=1),R=r.Dot(a,_),R=Math.min(1,Math.max(-1,R)),c=Math.acos(R)*v,r.Dot(A,m)<0&&(c=Math.PI+c,d++),v=-1,r.CrossToRef(u,T,g),g.normalize(),r.Dot(g,m)<0&&(v=1),R=r.Dot(T,u),R=Math.min(1,Math.max(-1,R)),y=-Math.acos(R)*v,R<0&&d<2&&(y=Math.PI+y),s.x=c,s.y=y,s.z=f},r}();t.Vector3=e;var s=function(){function r(t,i,r,n){this.x=t,this.y=i,this.z=r,this.w=n}return r.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\"W:\"+this.w+\"}\"},r.prototype.getClassName=function(){return\"Vector4\"},r.prototype.getHashCode=function(){var t=this.x||0;return t=397*t^(this.y||0),t=397*t^(this.z||0),t=397*t^(this.w||0)},r.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},r.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,t[i+2]=this.z,t[i+3]=this.w,this},r.prototype.addInPlace=function(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this.w+=t.w,this},r.prototype.add=function(t){return new r(this.x+t.x,this.y+t.y,this.z+t.z,this.w+t.w)},r.prototype.addToRef=function(t,i){return i.x=this.x+t.x,i.y=this.y+t.y,i.z=this.z+t.z,i.w=this.w+t.w,this},r.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this.w-=t.w,this},r.prototype.subtract=function(t){return new r(this.x-t.x,this.y-t.y,this.z-t.z,this.w-t.w)},r.prototype.subtractToRef=function(t,i){return i.x=this.x-t.x,i.y=this.y-t.y,i.z=this.z-t.z,i.w=this.w-t.w,this},r.prototype.subtractFromFloats=function(t,i,n,o){return new r(this.x-t,this.y-i,this.z-n,this.w-o)},r.prototype.subtractFromFloatsToRef=function(t,i,r,n,o){return o.x=this.x-t,o.y=this.y-i,o.z=this.z-r,o.w=this.w-n,this},r.prototype.negate=function(){return new r((-this.x),(-this.y),(-this.z),(-this.w))},r.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this},r.prototype.scale=function(t){return new r(this.x*t,this.y*t,this.z*t,this.w*t)},r.prototype.scaleToRef=function(t,i){i.x=this.x*t,i.y=this.y*t,i.z=this.z*t,i.w=this.w*t},r.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z&&this.w===t.w},r.prototype.equalsWithEpsilon=function(r,n){return void 0===n&&(n=t.Epsilon),r&&i.WithinEpsilon(this.x,r.x,n)&&i.WithinEpsilon(this.y,r.y,n)&&i.WithinEpsilon(this.z,r.z,n)&&i.WithinEpsilon(this.w,r.w,n)},r.prototype.equalsToFloats=function(t,i,r,n){return this.x===t&&this.y===i&&this.z===r&&this.w===n},r.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this.w*=t.w,this},r.prototype.multiply=function(t){return new r(this.x*t.x,this.y*t.y,this.z*t.z,this.w*t.w)},r.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,i.z=this.z*t.z,i.w=this.w*t.w,this},r.prototype.multiplyByFloats=function(t,i,n,o){return new r(this.x*t,this.y*i,this.z*n,this.w*o)},r.prototype.divide=function(t){return new r(this.x/t.x,this.y/t.y,this.z/t.z,this.w/t.w)},r.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,i.z=this.z/t.z,i.w=this.w/t.w,this},r.prototype.MinimizeInPlace=function(t){return t.x<this.x&&(this.x=t.x),t.y<this.y&&(this.y=t.y),t.z<this.z&&(this.z=t.z),t.w<this.w&&(this.w=t.w),this},r.prototype.MaximizeInPlace=function(t){return t.x>this.x&&(this.x=t.x),t.y>this.y&&(this.y=t.y),t.z>this.z&&(this.z=t.z),t.w>this.w&&(this.w=t.w),this},r.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},r.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w},r.prototype.normalize=function(){var t=this.length();if(0===t)return this;var i=1/t;return this.x*=i,this.y*=i,this.z*=i,this.w*=i,this},r.prototype.toVector3=function(){return new e(this.x,this.y,this.z)},r.prototype.clone=function(){return new r(this.x,this.y,this.z,this.w)},r.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=t.w,this},r.prototype.copyFromFloats=function(t,i,r,n){return this.x=t,this.y=i,this.z=r,this.w=n,this},r.FromArray=function(t,i){return i||(i=0),new r(t[i],t[i+1],t[i+2],t[i+3])},r.FromArrayToRef=function(t,i,r){r.x=t[i],r.y=t[i+1],r.z=t[i+2],r.w=t[i+3]},r.FromFloatArrayToRef=function(t,i,r){r.x=t[i],r.y=t[i+1],r.z=t[i+2],r.w=t[i+3]},r.FromFloatsToRef=function(t,i,r,n,o){o.x=t,o.y=i,o.z=r,o.w=n},r.Zero=function(){return new r(0,0,0,0)},r.Normalize=function(t){var i=r.Zero();return r.NormalizeToRef(t,i),i},r.NormalizeToRef=function(t,i){i.copyFrom(t),i.normalize()},r.Minimize=function(t,i){var r=t.clone();return r.MinimizeInPlace(i),r},r.Maximize=function(t,i){var r=t.clone();return r.MaximizeInPlace(i),r},r.Distance=function(t,i){return Math.sqrt(r.DistanceSquared(t,i))},r.DistanceSquared=function(t,i){var r=t.x-i.x,n=t.y-i.y,o=t.z-i.z,e=t.w-i.w;return r*r+n*n+o*o+e*e},r.Center=function(t,i){var r=t.add(i);return r.scaleInPlace(.5),r},r}();t.Vector4=s;var h=function(){function t(t,i){this.width=t,this.height=i}return t.prototype.toString=function(){return\"{W: \"+this.width+\", H: \"+this.height+\"}\"},t.prototype.getClassName=function(){return\"Size\"},t.prototype.getHashCode=function(){var t=this.width||0;return t=397*t^(this.height||0)},t.prototype.copyFrom=function(t){this.width=t.width,this.height=t.height},t.prototype.copyFromFloats=function(t,i){this.width=t,this.height=i},t.prototype.multiplyByFloats=function(i,r){return new t(this.width*i,this.height*r)},t.prototype.clone=function(){return new t(this.width,this.height)},t.prototype.equals=function(t){return!!t&&(this.width===t.width&&this.height===t.height)},Object.defineProperty(t.prototype,\"surface\",{get:function(){return this.width*this.height},enumerable:!0,configurable:!0}),t.Zero=function(){return new t(0,0)},t.prototype.add=function(i){var r=new t(this.width+i.width,this.height+i.height);return r},t.prototype.substract=function(i){var r=new t(this.width-i.width,this.height-i.height);return r},t.Lerp=function(i,r,n){var o=i.width+(r.width-i.width)*n,e=i.height+(r.height-i.height)*n;return new t(o,e)},t}();t.Size=h;var a=function(){function t(t,i,r,n){void 0===t&&(t=0),void 0===i&&(i=0),void 0===r&&(r=0),void 0===n&&(n=1),this.x=t,this.y=i,this.z=r,this.w=n}return t.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\" W:\"+this.w+\"}\"},t.prototype.getClassName=function(){return\"Quaternion\"},t.prototype.getHashCode=function(){var t=this.x||0;return t=397*t^(this.y||0),t=397*t^(this.z||0),t=397*t^(this.w||0)},t.prototype.asArray=function(){return[this.x,this.y,this.z,this.w]},t.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z&&this.w===t.w},t.prototype.clone=function(){return new t(this.x,this.y,this.z,this.w)},t.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=t.w,this},t.prototype.copyFromFloats=function(t,i,r,n){return this.x=t,this.y=i,this.z=r,this.w=n,this},t.prototype.add=function(i){return new t(this.x+i.x,this.y+i.y,this.z+i.z,this.w+i.w)},t.prototype.subtract=function(i){return new t(this.x-i.x,this.y-i.y,this.z-i.z,this.w-i.w)},t.prototype.scale=function(i){return new t(this.x*i,this.y*i,this.z*i,this.w*i)},t.prototype.multiply=function(i){var r=new t(0,0,0,1);return this.multiplyToRef(i,r),r},t.prototype.multiplyToRef=function(t,i){var r=this.x*t.w+this.y*t.z-this.z*t.y+this.w*t.x,n=-this.x*t.z+this.y*t.w+this.z*t.x+this.w*t.y,o=this.x*t.y-this.y*t.x+this.z*t.w+this.w*t.z,e=-this.x*t.x-this.y*t.y-this.z*t.z+this.w*t.w;return i.copyFromFloats(r,n,o,e),this},t.prototype.multiplyInPlace=function(t){return this.multiplyToRef(t,this),this},t.prototype.conjugateToRef=function(t){return t.copyFromFloats(-this.x,-this.y,-this.z,this.w),this},t.prototype.conjugateInPlace=function(){return this.x*=-1,this.y*=-1,this.z*=-1,this},t.prototype.conjugate=function(){var i=new t((-this.x),(-this.y),(-this.z),this.w);return i},t.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},t.prototype.normalize=function(){var t=1/this.length();return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this},t.prototype.toEulerAngles=function(t){void 0===t&&(t=\"YZX\");var i=e.Zero();return this.toEulerAnglesToRef(i,t),i},t.prototype.toEulerAnglesToRef=function(t,i){void 0===i&&(i=\"YZX\");var r,n,o,e=this.x,s=this.y,h=this.z,a=this.w;switch(i){case\"YZX\":var u=e*s+h*a;if(u>.499&&(r=2*Math.atan2(e,a),n=Math.PI/2,o=0),u<-.499&&(r=-2*Math.atan2(e,a),n=-Math.PI/2,o=0),isNaN(r)){var m=e*e,y=s*s,c=h*h;r=Math.atan2(2*s*a-2*e*h,1-2*y-2*c),n=Math.asin(2*u),o=Math.atan2(2*e*a-2*s*h,1-2*m-2*c)}break;default:throw new Error(\"Euler order \"+i+\" not supported yet.\")}return t.y=r,t.z=n,t.x=o,this},t.prototype.toRotationMatrix=function(t){var i=this.x*this.x,r=this.y*this.y,n=this.z*this.z,o=this.x*this.y,e=this.z*this.w,s=this.z*this.x,h=this.y*this.w,a=this.y*this.z,u=this.x*this.w;return t.m[0]=1-2*(r+n),t.m[1]=2*(o+e),t.m[2]=2*(s-h),t.m[3]=0,t.m[4]=2*(o-e),t.m[5]=1-2*(n+i),t.m[6]=2*(a+u),t.m[7]=0,t.m[8]=2*(s+h),t.m[9]=2*(a-u),t.m[10]=1-2*(r+i),t.m[11]=0,t.m[12]=0,t.m[13]=0,t.m[14]=0,t.m[15]=1,this},t.prototype.fromRotationMatrix=function(i){return t.FromRotationMatrixToRef(i,this),this},t.FromRotationMatrix=function(i){var r=new t;return t.FromRotationMatrixToRef(i,r),r},t.FromRotationMatrixToRef=function(t,i){var r,n=t.m,o=n[0],e=n[4],s=n[8],h=n[1],a=n[5],u=n[9],m=n[2],y=n[6],c=n[10],p=o+a+c;p>0?(r=.5/Math.sqrt(p+1),i.w=.25/r,i.x=(y-u)*r,i.y=(s-m)*r,i.z=(h-e)*r):o>a&&o>c?(r=2*Math.sqrt(1+o-a-c),i.w=(y-u)/r,i.x=.25*r,i.y=(e+h)/r,i.z=(s+m)/r):a>c?(r=2*Math.sqrt(1+a-o-c),i.w=(s-m)/r,i.x=(e+h)/r,i.y=.25*r,i.z=(u+y)/r):(r=2*Math.sqrt(1+c-o-a),i.w=(h-e)/r,i.x=(s+m)/r,i.y=(u+y)/r,i.z=.25*r)},t.Inverse=function(i){return new t((-i.x),(-i.y),(-i.z),i.w)},t.Identity=function(){return new t(0,0,0,1)},t.RotationAxis=function(i,r){return t.RotationAxisToRef(i,r,new t)},t.RotationAxisToRef=function(t,i,r){var n=Math.sin(i/2);return t.normalize(),r.w=Math.cos(i/2),r.x=t.x*n,r.y=t.y*n,r.z=t.z*n,r},t.FromArray=function(i,r){return r||(r=0),new t(i[r],i[r+1],i[r+2],i[r+3])},t.RotationYawPitchRoll=function(i,r,n){var o=new t;return t.RotationYawPitchRollToRef(i,r,n,o),o},t.RotationYawPitchRollToRef=function(t,i,r,n){var o=.5*r,e=.5*i,s=.5*t,h=Math.sin(o),a=Math.cos(o),u=Math.sin(e),m=Math.cos(e),y=Math.sin(s),c=Math.cos(s);n.x=c*u*a+y*m*h,n.y=y*m*a-c*u*h,n.z=c*m*h-y*u*a,n.w=c*m*a+y*u*h},t.RotationAlphaBetaGamma=function(i,r,n){var o=new t;return t.RotationAlphaBetaGammaToRef(i,r,n,o),o},t.RotationAlphaBetaGammaToRef=function(t,i,r,n){var o=.5*(r+t),e=.5*(r-t),s=.5*i;n.x=Math.cos(e)*Math.sin(s),n.y=Math.sin(e)*Math.sin(s),n.z=Math.sin(o)*Math.cos(s),n.w=Math.cos(o)*Math.cos(s)},t.Slerp=function(i,r,n){var o,e,s=n,h=i.x*r.x+i.y*r.y+i.z*r.z+i.w*r.w,a=!1;if(h<0&&(a=!0,h=-h),h>.999999)e=1-s,o=a?-s:s;else{var u=Math.acos(h),m=1/Math.sin(u);e=Math.sin((1-s)*u)*m,o=a?-Math.sin(s*u)*m:Math.sin(s*u)*m}return new t(e*i.x+o*r.x,e*i.y+o*r.y,e*i.z+o*r.z,e*i.w+o*r.w)},t}();t.Quaternion=a;var u=function(){function t(){this.m=new Float32Array(16)}return t.prototype.isIdentity=function(){return 1===this.m[0]&&1===this.m[5]&&1===this.m[10]&&1===this.m[15]&&(0===this.m[1]&&0===this.m[2]&&0===this.m[3]&&0===this.m[4]&&0===this.m[6]&&0===this.m[7]&&0===this.m[8]&&0===this.m[9]&&0===this.m[11]&&0===this.m[12]&&0===this.m[13]&&0===this.m[14])},t.prototype.determinant=function(){var t=this.m[10]*this.m[15]-this.m[11]*this.m[14],i=this.m[9]*this.m[15]-this.m[11]*this.m[13],r=this.m[9]*this.m[14]-this.m[10]*this.m[13],n=this.m[8]*this.m[15]-this.m[11]*this.m[12],o=this.m[8]*this.m[14]-this.m[10]*this.m[12],e=this.m[8]*this.m[13]-this.m[9]*this.m[12];return this.m[0]*(this.m[5]*t-this.m[6]*i+this.m[7]*r)-this.m[1]*(this.m[4]*t-this.m[6]*n+this.m[7]*o)+this.m[2]*(this.m[4]*i-this.m[5]*n+this.m[7]*e)-this.m[3]*(this.m[4]*r-this.m[5]*o+this.m[6]*e)},t.prototype.toArray=function(){return this.m},t.prototype.asArray=function(){return this.toArray()},t.prototype.invert=function(){return this.invertToRef(this),this},t.prototype.reset=function(){for(var t=0;t<16;t++)this.m[t]=0;return this},t.prototype.add=function(i){var r=new t;return this.addToRef(i,r),r},t.prototype.addToRef=function(t,i){for(var r=0;r<16;r++)i.m[r]=this.m[r]+t.m[r];return this},t.prototype.addToSelf=function(t){for(var i=0;i<16;i++)this.m[i]+=t.m[i];return this},t.prototype.invertToRef=function(t){var i=this.m[0],r=this.m[1],n=this.m[2],o=this.m[3],e=this.m[4],s=this.m[5],h=this.m[6],a=this.m[7],u=this.m[8],m=this.m[9],y=this.m[10],c=this.m[11],p=this.m[12],f=this.m[13],x=this.m[14],l=this.m[15],z=y*l-c*x,w=m*l-c*f,v=m*x-y*f,d=u*l-c*p,g=u*x-y*p,R=u*f-m*p,T=s*z-h*w+a*v,_=-(e*z-h*d+a*g),M=e*w-s*d+a*R,A=-(e*v-s*g+h*R),b=1/(i*T+r*_+n*M+o*A),F=h*l-a*x,L=s*l-a*f,C=s*x-h*f,P=e*l-a*p,Z=e*x-h*p,S=e*f-s*p,I=h*c-a*y,H=s*c-a*m,D=s*y-h*m,q=e*c-a*u,V=e*y-h*u,N=e*m-s*u;return t.m[0]=T*b,t.m[4]=_*b,t.m[8]=M*b,t.m[12]=A*b,t.m[1]=-(r*z-n*w+o*v)*b,t.m[5]=(i*z-n*d+o*g)*b,t.m[9]=-(i*w-r*d+o*R)*b,t.m[13]=(i*v-r*g+n*R)*b,t.m[2]=(r*F-n*L+o*C)*b,t.m[6]=-(i*F-n*P+o*Z)*b,t.m[10]=(i*L-r*P+o*S)*b,t.m[14]=-(i*C-r*Z+n*S)*b,t.m[3]=-(r*I-n*H+o*D)*b,t.m[7]=(i*I-n*q+o*V)*b,t.m[11]=-(i*H-r*q+o*N)*b,t.m[15]=(i*D-r*V+n*N)*b,this},t.prototype.setTranslation=function(t){return this.m[12]=t.x,this.m[13]=t.y,this.m[14]=t.z,this},t.prototype.getTranslation=function(){return new e(this.m[12],this.m[13],this.m[14])},t.prototype.multiply=function(i){var r=new t;return this.multiplyToRef(i,r),r},t.prototype.copyFrom=function(t){for(var i=0;i<16;i++)this.m[i]=t.m[i];return this},t.prototype.copyToArray=function(t,i){void 0===i&&(i=0);for(var r=0;r<16;r++)t[i+r]=this.m[r];return this},t.prototype.multiplyToRef=function(t,i){\nreturn this.multiplyToArray(t,i.m,0),this},t.prototype.multiplyToArray=function(t,i,r){var n=this.m[0],o=this.m[1],e=this.m[2],s=this.m[3],h=this.m[4],a=this.m[5],u=this.m[6],m=this.m[7],y=this.m[8],c=this.m[9],p=this.m[10],f=this.m[11],x=this.m[12],l=this.m[13],z=this.m[14],w=this.m[15],v=t.m[0],d=t.m[1],g=t.m[2],R=t.m[3],T=t.m[4],_=t.m[5],M=t.m[6],A=t.m[7],b=t.m[8],F=t.m[9],L=t.m[10],C=t.m[11],P=t.m[12],Z=t.m[13],S=t.m[14],I=t.m[15];return i[r]=n*v+o*T+e*b+s*P,i[r+1]=n*d+o*_+e*F+s*Z,i[r+2]=n*g+o*M+e*L+s*S,i[r+3]=n*R+o*A+e*C+s*I,i[r+4]=h*v+a*T+u*b+m*P,i[r+5]=h*d+a*_+u*F+m*Z,i[r+6]=h*g+a*M+u*L+m*S,i[r+7]=h*R+a*A+u*C+m*I,i[r+8]=y*v+c*T+p*b+f*P,i[r+9]=y*d+c*_+p*F+f*Z,i[r+10]=y*g+c*M+p*L+f*S,i[r+11]=y*R+c*A+p*C+f*I,i[r+12]=x*v+l*T+z*b+w*P,i[r+13]=x*d+l*_+z*F+w*Z,i[r+14]=x*g+l*M+z*L+w*S,i[r+15]=x*R+l*A+z*C+w*I,this},t.prototype.equals=function(t){return t&&this.m[0]===t.m[0]&&this.m[1]===t.m[1]&&this.m[2]===t.m[2]&&this.m[3]===t.m[3]&&this.m[4]===t.m[4]&&this.m[5]===t.m[5]&&this.m[6]===t.m[6]&&this.m[7]===t.m[7]&&this.m[8]===t.m[8]&&this.m[9]===t.m[9]&&this.m[10]===t.m[10]&&this.m[11]===t.m[11]&&this.m[12]===t.m[12]&&this.m[13]===t.m[13]&&this.m[14]===t.m[14]&&this.m[15]===t.m[15]},t.prototype.clone=function(){return t.FromValues(this.m[0],this.m[1],this.m[2],this.m[3],this.m[4],this.m[5],this.m[6],this.m[7],this.m[8],this.m[9],this.m[10],this.m[11],this.m[12],this.m[13],this.m[14],this.m[15])},t.prototype.getClassName=function(){return\"Matrix\"},t.prototype.getHashCode=function(){for(var t=this.m[0]||0,i=1;i<16;i++)t=397*t^(this.m[i]||0);return t},t.prototype.decompose=function(r,n,o){o.x=this.m[12],o.y=this.m[13],o.z=this.m[14];var e=i.Sign(this.m[0]*this.m[1]*this.m[2]*this.m[3])<0?-1:1,s=i.Sign(this.m[4]*this.m[5]*this.m[6]*this.m[7])<0?-1:1,h=i.Sign(this.m[8]*this.m[9]*this.m[10]*this.m[11])<0?-1:1;if(r.x=e*Math.sqrt(this.m[0]*this.m[0]+this.m[1]*this.m[1]+this.m[2]*this.m[2]),r.y=s*Math.sqrt(this.m[4]*this.m[4]+this.m[5]*this.m[5]+this.m[6]*this.m[6]),r.z=h*Math.sqrt(this.m[8]*this.m[8]+this.m[9]*this.m[9]+this.m[10]*this.m[10]),0===r.x||0===r.y||0===r.z)return n.x=0,n.y=0,n.z=0,n.w=1,!1;var u=t.FromValues(this.m[0]/r.x,this.m[1]/r.x,this.m[2]/r.x,0,this.m[4]/r.y,this.m[5]/r.y,this.m[6]/r.y,0,this.m[8]/r.z,this.m[9]/r.z,this.m[10]/r.z,0,0,0,0,1);return a.FromRotationMatrixToRef(u,n),!0},t.FromArray=function(i,r){var n=new t;return r||(r=0),t.FromArrayToRef(i,r,n),n},t.FromArrayToRef=function(t,i,r){for(var n=0;n<16;n++)r.m[n]=t[n+i]},t.FromFloat32ArrayToRefScaled=function(t,i,r,n){for(var o=0;o<16;o++)n.m[o]=t[o+i]*r},t.FromValuesToRef=function(t,i,r,n,o,e,s,h,a,u,m,y,c,p,f,x,l){l.m[0]=t,l.m[1]=i,l.m[2]=r,l.m[3]=n,l.m[4]=o,l.m[5]=e,l.m[6]=s,l.m[7]=h,l.m[8]=a,l.m[9]=u,l.m[10]=m,l.m[11]=y,l.m[12]=c,l.m[13]=p,l.m[14]=f,l.m[15]=x},t.prototype.getRow=function(t){if(t<0||t>3)return null;var i=4*t;return new s(this.m[i+0],this.m[i+1],this.m[i+2],this.m[i+3])},t.prototype.setRow=function(t,i){if(t<0||t>3)return this;var r=4*t;return this.m[r+0]=i.x,this.m[r+1]=i.y,this.m[r+2]=i.z,this.m[r+3]=i.w,this},t.FromValues=function(i,r,n,o,e,s,h,a,u,m,y,c,p,f,x,l){var z=new t;return z.m[0]=i,z.m[1]=r,z.m[2]=n,z.m[3]=o,z.m[4]=e,z.m[5]=s,z.m[6]=h,z.m[7]=a,z.m[8]=u,z.m[9]=m,z.m[10]=y,z.m[11]=c,z.m[12]=p,z.m[13]=f,z.m[14]=x,z.m[15]=l,z},t.Compose=function(i,r,n){var o=t.FromValues(i.x,0,0,0,0,i.y,0,0,0,0,i.z,0,0,0,0,1),e=t.Identity();return r.toRotationMatrix(e),o=o.multiply(e),o.setTranslation(n),o},t.Identity=function(){return t.FromValues(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1)},t.IdentityToRef=function(i){t.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1,i)},t.Zero=function(){return t.FromValues(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)},t.RotationX=function(i){var r=new t;return t.RotationXToRef(i,r),r},t.Invert=function(i){var r=new t;return i.invertToRef(r),r},t.RotationXToRef=function(t,i){var r=Math.sin(t),n=Math.cos(t);i.m[0]=1,i.m[15]=1,i.m[5]=n,i.m[10]=n,i.m[9]=-r,i.m[6]=r,i.m[1]=0,i.m[2]=0,i.m[3]=0,i.m[4]=0,i.m[7]=0,i.m[8]=0,i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0},t.RotationY=function(i){var r=new t;return t.RotationYToRef(i,r),r},t.RotationYToRef=function(t,i){var r=Math.sin(t),n=Math.cos(t);i.m[5]=1,i.m[15]=1,i.m[0]=n,i.m[2]=-r,i.m[8]=r,i.m[10]=n,i.m[1]=0,i.m[3]=0,i.m[4]=0,i.m[6]=0,i.m[7]=0,i.m[9]=0,i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0},t.RotationZ=function(i){var r=new t;return t.RotationZToRef(i,r),r},t.RotationZToRef=function(t,i){var r=Math.sin(t),n=Math.cos(t);i.m[10]=1,i.m[15]=1,i.m[0]=n,i.m[1]=r,i.m[4]=-r,i.m[5]=n,i.m[2]=0,i.m[3]=0,i.m[6]=0,i.m[7]=0,i.m[8]=0,i.m[9]=0,i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0},t.RotationAxis=function(i,r){var n=t.Zero();return t.RotationAxisToRef(i,r,n),n},t.RotationAxisToRef=function(t,i,r){var n=Math.sin(-i),o=Math.cos(-i),e=1-o;t.normalize(),r.m[0]=t.x*t.x*e+o,r.m[1]=t.x*t.y*e-t.z*n,r.m[2]=t.x*t.z*e+t.y*n,r.m[3]=0,r.m[4]=t.y*t.x*e+t.z*n,r.m[5]=t.y*t.y*e+o,r.m[6]=t.y*t.z*e-t.x*n,r.m[7]=0,r.m[8]=t.z*t.x*e-t.y*n,r.m[9]=t.z*t.y*e+t.x*n,r.m[10]=t.z*t.z*e+o,r.m[11]=0,r.m[15]=1},t.RotationYawPitchRoll=function(i,r,n){var o=new t;return t.RotationYawPitchRollToRef(i,r,n,o),o},t.RotationYawPitchRollToRef=function(t,i,r,n){a.RotationYawPitchRollToRef(t,i,r,this._tempQuaternion),this._tempQuaternion.toRotationMatrix(n)},t.Scaling=function(i,r,n){var o=t.Zero();return t.ScalingToRef(i,r,n,o),o},t.ScalingToRef=function(t,i,r,n){n.m[0]=t,n.m[1]=0,n.m[2]=0,n.m[3]=0,n.m[4]=0,n.m[5]=i,n.m[6]=0,n.m[7]=0,n.m[8]=0,n.m[9]=0,n.m[10]=r,n.m[11]=0,n.m[12]=0,n.m[13]=0,n.m[14]=0,n.m[15]=1},t.Translation=function(i,r,n){var o=t.Identity();return t.TranslationToRef(i,r,n,o),o},t.TranslationToRef=function(i,r,n,o){t.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,i,r,n,1,o)},t.Lerp=function(i,r,n){for(var o=t.Zero(),e=0;e<16;e++)o.m[e]=i.m[e]*(1-n)+r.m[e]*n;return o},t.DecomposeLerp=function(i,r,n){var o=new e(0,0,0),s=new a,h=new e(0,0,0);i.decompose(o,s,h);var u=new e(0,0,0),m=new a,y=new e(0,0,0);r.decompose(u,m,y);var c=e.Lerp(o,u,n),p=a.Slerp(s,m,n),f=e.Lerp(h,y,n);return t.Compose(c,p,f)},t.LookAtLH=function(i,r,n){var o=t.Zero();return t.LookAtLHToRef(i,r,n,o),o},t.LookAtLHToRef=function(i,r,n,o){r.subtractToRef(i,this._zAxis),this._zAxis.normalize(),e.CrossToRef(n,this._zAxis,this._xAxis),0===this._xAxis.lengthSquared()?this._xAxis.x=1:this._xAxis.normalize(),e.CrossToRef(this._zAxis,this._xAxis,this._yAxis),this._yAxis.normalize();var s=-e.Dot(this._xAxis,i),h=-e.Dot(this._yAxis,i),a=-e.Dot(this._zAxis,i);return t.FromValuesToRef(this._xAxis.x,this._yAxis.x,this._zAxis.x,0,this._xAxis.y,this._yAxis.y,this._zAxis.y,0,this._xAxis.z,this._yAxis.z,this._zAxis.z,0,s,h,a,1,o)},t.LookAtRH=function(i,r,n){var o=t.Zero();return t.LookAtRHToRef(i,r,n,o),o},t.LookAtRHToRef=function(i,r,n,o){i.subtractToRef(r,this._zAxis),this._zAxis.normalize(),e.CrossToRef(n,this._zAxis,this._xAxis),0===this._xAxis.lengthSquared()?this._xAxis.x=1:this._xAxis.normalize(),e.CrossToRef(this._zAxis,this._xAxis,this._yAxis),this._yAxis.normalize();var s=-e.Dot(this._xAxis,i),h=-e.Dot(this._yAxis,i),a=-e.Dot(this._zAxis,i);return t.FromValuesToRef(this._xAxis.x,this._yAxis.x,this._zAxis.x,0,this._xAxis.y,this._yAxis.y,this._zAxis.y,0,this._xAxis.z,this._yAxis.z,this._zAxis.z,0,s,h,a,1,o)},t.OrthoLH=function(i,r,n,o){var e=t.Zero();return t.OrthoLHToRef(i,r,n,o,e),e},t.OrthoLHToRef=function(i,r,n,o,e){var s=2/i,h=2/r,a=1/(o-n),u=n/(n-o);t.FromValuesToRef(s,0,0,0,0,h,0,0,0,0,a,0,0,0,u,1,e)},t.OrthoOffCenterLH=function(i,r,n,o,e,s){var h=t.Zero();return t.OrthoOffCenterLHToRef(i,r,n,o,e,s,h),h},t.OrthoOffCenterLHToRef=function(t,i,r,n,o,e,s){s.m[0]=2/(i-t),s.m[1]=s.m[2]=s.m[3]=0,s.m[5]=2/(n-r),s.m[4]=s.m[6]=s.m[7]=0,s.m[10]=1/(e-o),s.m[8]=s.m[9]=s.m[11]=0,s.m[12]=(t+i)/(t-i),s.m[13]=(n+r)/(r-n),s.m[14]=-o/(e-o),s.m[15]=1},t.OrthoOffCenterRH=function(i,r,n,o,e,s){var h=t.Zero();return t.OrthoOffCenterRHToRef(i,r,n,o,e,s,h),h},t.OrthoOffCenterRHToRef=function(i,r,n,o,e,s,h){t.OrthoOffCenterLHToRef(i,r,n,o,e,s,h),h.m[10]*=-1},t.PerspectiveLH=function(i,r,n,o){var e=t.Zero();return e.m[0]=2*n/i,e.m[1]=e.m[2]=e.m[3]=0,e.m[5]=2*n/r,e.m[4]=e.m[6]=e.m[7]=0,e.m[10]=-o/(n-o),e.m[8]=e.m[9]=0,e.m[11]=1,e.m[12]=e.m[13]=e.m[15]=0,e.m[14]=n*o/(n-o),e},t.PerspectiveFovLH=function(i,r,n,o){var e=t.Zero();return t.PerspectiveFovLHToRef(i,r,n,o,e),e},t.PerspectiveFovLHToRef=function(t,i,r,n,o,e){void 0===e&&(e=!0);var s=1/Math.tan(.5*t);e?o.m[0]=s/i:o.m[0]=s,o.m[1]=o.m[2]=o.m[3]=0,e?o.m[5]=s:o.m[5]=s*i,o.m[4]=o.m[6]=o.m[7]=0,o.m[8]=o.m[9]=0,o.m[10]=n/(n-r),o.m[11]=1,o.m[12]=o.m[13]=o.m[15]=0,o.m[14]=-(r*n)/(n-r)},t.PerspectiveFovRH=function(i,r,n,o){var e=t.Zero();return t.PerspectiveFovRHToRef(i,r,n,o,e),e},t.PerspectiveFovRHToRef=function(t,i,r,n,o,e){void 0===e&&(e=!0);var s=1/Math.tan(.5*t);e?o.m[0]=s/i:o.m[0]=s,o.m[1]=o.m[2]=o.m[3]=0,e?o.m[5]=s:o.m[5]=s*i,o.m[4]=o.m[6]=o.m[7]=0,o.m[8]=o.m[9]=0,o.m[10]=n/(r-n),o.m[11]=-1,o.m[12]=o.m[13]=o.m[15]=0,o.m[14]=r*n/(r-n)},t.PerspectiveFovWebVRToRef=function(t,i,r,n,o){void 0===o&&(o=!0);var e=Math.tan(t.upDegrees*Math.PI/180),s=Math.tan(t.downDegrees*Math.PI/180),h=Math.tan(t.leftDegrees*Math.PI/180),a=Math.tan(t.rightDegrees*Math.PI/180),u=2/(h+a),m=2/(e+s);n.m[0]=u,n.m[1]=n.m[2]=n.m[3]=n.m[4]=0,n.m[5]=m,n.m[6]=n.m[7]=0,n.m[8]=(h-a)*u*.5,n.m[9]=-((e-s)*m*.5),n.m[10]=-r/(i-r),n.m[11]=1,n.m[12]=n.m[13]=n.m[15]=0,n.m[14]=i*r/(i-r)},t.GetFinalMatrix=function(i,r,n,o,e,s){var h=i.width,a=i.height,u=i.x,m=i.y,y=t.FromValues(h/2,0,0,0,0,-a/2,0,0,0,0,s-e,0,u+h/2,a/2+m,e,1);return r.multiply(n).multiply(o).multiply(y)},t.GetAsMatrix2x2=function(t){return new Float32Array([t.m[0],t.m[1],t.m[4],t.m[5]])},t.GetAsMatrix3x3=function(t){return new Float32Array([t.m[0],t.m[1],t.m[2],t.m[4],t.m[5],t.m[6],t.m[8],t.m[9],t.m[10]])},t.Transpose=function(i){var r=new t;return r.m[0]=i.m[0],r.m[1]=i.m[4],r.m[2]=i.m[8],r.m[3]=i.m[12],r.m[4]=i.m[1],r.m[5]=i.m[5],r.m[6]=i.m[9],r.m[7]=i.m[13],r.m[8]=i.m[2],r.m[9]=i.m[6],r.m[10]=i.m[10],r.m[11]=i.m[14],r.m[12]=i.m[3],r.m[13]=i.m[7],r.m[14]=i.m[11],r.m[15]=i.m[15],r},t.Reflection=function(i){var r=new t;return t.ReflectionToRef(i,r),r},t.ReflectionToRef=function(t,i){t.normalize();var r=t.normal.x,n=t.normal.y,o=t.normal.z,e=-2*r,s=-2*n,h=-2*o;i.m[0]=e*r+1,i.m[1]=s*r,i.m[2]=h*r,i.m[3]=0,i.m[4]=e*n,i.m[5]=s*n+1,i.m[6]=h*n,i.m[7]=0,i.m[8]=e*o,i.m[9]=s*o,i.m[10]=h*o+1,i.m[11]=0,i.m[12]=e*t.d,i.m[13]=s*t.d,i.m[14]=h*t.d,i.m[15]=1},t._tempQuaternion=new a,t._xAxis=e.Zero(),t._yAxis=e.Zero(),t._zAxis=e.Zero(),t}();t.Matrix=u;var m=function(){function t(t,i,r,n){this.normal=new e(t,i,r),this.d=n}return t.prototype.asArray=function(){return[this.normal.x,this.normal.y,this.normal.z,this.d]},t.prototype.clone=function(){return new t(this.normal.x,this.normal.y,this.normal.z,this.d)},t.prototype.getClassName=function(){return\"Plane\"},t.prototype.getHashCode=function(){var t=this.normal.getHashCode();return t=397*t^(this.d||0)},t.prototype.normalize=function(){var t=Math.sqrt(this.normal.x*this.normal.x+this.normal.y*this.normal.y+this.normal.z*this.normal.z),i=0;return 0!==t&&(i=1/t),this.normal.x*=i,this.normal.y*=i,this.normal.z*=i,this.d*=i,this},t.prototype.transform=function(i){var r=u.Transpose(i),n=this.normal.x,o=this.normal.y,e=this.normal.z,s=this.d,h=n*r.m[0]+o*r.m[1]+e*r.m[2]+s*r.m[3],a=n*r.m[4]+o*r.m[5]+e*r.m[6]+s*r.m[7],m=n*r.m[8]+o*r.m[9]+e*r.m[10]+s*r.m[11],y=n*r.m[12]+o*r.m[13]+e*r.m[14]+s*r.m[15];return new t(h,a,m,y)},t.prototype.dotCoordinate=function(t){return this.normal.x*t.x+this.normal.y*t.y+this.normal.z*t.z+this.d},t.prototype.copyFromPoints=function(t,i,r){var n,o=i.x-t.x,e=i.y-t.y,s=i.z-t.z,h=r.x-t.x,a=r.y-t.y,u=r.z-t.z,m=e*u-s*a,y=s*h-o*u,c=o*a-e*h,p=Math.sqrt(m*m+y*y+c*c);return n=0!==p?1/p:0,this.normal.x=m*n,this.normal.y=y*n,this.normal.z=c*n,this.d=-(this.normal.x*t.x+this.normal.y*t.y+this.normal.z*t.z),this},t.prototype.isFrontFacingTo=function(t,i){var r=e.Dot(this.normal,t);return r<=i},t.prototype.signedDistanceTo=function(t){return e.Dot(t,this.normal)+this.d},t.FromArray=function(i){return new t(i[0],i[1],i[2],i[3])},t.FromPoints=function(i,r,n){var o=new t(0,0,0,0);return o.copyFromPoints(i,r,n),o},t.FromPositionAndNormal=function(i,r){var n=new t(0,0,0,0);return r.normalize(),n.normal=r,n.d=-(r.x*i.x+r.y*i.y+r.z*i.z),n},t.SignedDistanceToPlaneFromPositionAndNormal=function(t,i,r){var n=-(i.x*t.x+i.y*t.y+i.z*t.z);return e.Dot(r,i)+n},t}();t.Plane=m;var y=function(){function t(t,i,r,n){this.x=t,this.y=i,this.width=r,this.height=n}return t.prototype.toGlobal=function(i,r){return new t(this.x*i,this.y*r,this.width*i,this.height*r)},t}();t.Viewport=y;var c=function(){function t(){}return t.GetPlanes=function(i){for(var r=[],n=0;n<6;n++)r.push(new m(0,0,0,0));return t.GetPlanesToRef(i,r),r},t.GetPlanesToRef=function(t,i){i[0].normal.x=t.m[3]+t.m[2],i[0].normal.y=t.m[7]+t.m[6],i[0].normal.z=t.m[11]+t.m[10],i[0].d=t.m[15]+t.m[14],i[0].normalize(),i[1].normal.x=t.m[3]-t.m[2],i[1].normal.y=t.m[7]-t.m[6],i[1].normal.z=t.m[11]-t.m[10],i[1].d=t.m[15]-t.m[14],i[1].normalize(),i[2].normal.x=t.m[3]+t.m[0],i[2].normal.y=t.m[7]+t.m[4],i[2].normal.z=t.m[11]+t.m[8],i[2].d=t.m[15]+t.m[12],i[2].normalize(),i[3].normal.x=t.m[3]-t.m[0],i[3].normal.y=t.m[7]-t.m[4],i[3].normal.z=t.m[11]-t.m[8],i[3].d=t.m[15]-t.m[12],i[3].normalize(),i[4].normal.x=t.m[3]-t.m[1],i[4].normal.y=t.m[7]-t.m[5],i[4].normal.z=t.m[11]-t.m[9],i[4].d=t.m[15]-t.m[13],i[4].normalize(),i[5].normal.x=t.m[3]+t.m[1],i[5].normal.y=t.m[7]+t.m[5],i[5].normal.z=t.m[11]+t.m[9],i[5].d=t.m[15]+t.m[13],i[5].normalize()},t}();t.Frustum=c,function(t){t[t.LOCAL=0]=\"LOCAL\",t[t.WORLD=1]=\"WORLD\"}(t.Space||(t.Space={}));var p=(t.Space,function(){function t(){}return t.X=new e(1,0,0),t.Y=new e(0,1,0),t.Z=new e(0,0,1),t}());t.Axis=p;var f=function(){function t(){}return t.interpolate=function(t,i,r,n,o){for(var e=1-3*n+3*i,s=3*n-6*i,h=3*i,a=t,u=0;u<5;u++){var m=a*a,y=m*a,c=e*y+s*m+h*a,p=1/(3*e*m+2*s*a+h);a-=(c-t)*p,a=Math.min(1,Math.max(0,a))}return 3*Math.pow(1-a,2)*a*r+3*(1-a)*Math.pow(a,2)*o+Math.pow(a,3)},t}();t.BezierCurve=f,function(t){t[t.CW=0]=\"CW\",t[t.CCW=1]=\"CCW\"}(t.Orientation||(t.Orientation={}));var x=t.Orientation,l=function(){function t(t){var i=this;this.degrees=function(){return 180*i._radians/Math.PI},this.radians=function(){return i._radians},this._radians=t,this._radians<0&&(this._radians+=2*Math.PI)}return t.BetweenTwoPoints=function(i,r){var n=r.subtract(i),o=Math.atan2(n.y,n.x);return new t(o)},t.FromRadians=function(i){return new t(i)},t.FromDegrees=function(i){return new t(i*Math.PI/180)},t}();t.Angle=l;var z=function(){function t(t,i,r){this.startPoint=t,this.midPoint=i,this.endPoint=r;var n=Math.pow(i.x,2)+Math.pow(i.y,2),e=(Math.pow(t.x,2)+Math.pow(t.y,2)-n)/2,s=(n-Math.pow(r.x,2)-Math.pow(r.y,2))/2,h=(t.x-i.x)*(i.y-r.y)-(i.x-r.x)*(t.y-i.y);this.centerPoint=new o((e*(i.y-r.y)-s*(t.y-i.y))/h,((t.x-i.x)*s-(i.x-r.x)*e)/h),this.radius=this.centerPoint.subtract(this.startPoint).length(),this.startAngle=l.BetweenTwoPoints(this.centerPoint,this.startPoint);var a=this.startAngle.degrees(),u=l.BetweenTwoPoints(this.centerPoint,this.midPoint).degrees(),m=l.BetweenTwoPoints(this.centerPoint,this.endPoint).degrees();u-a>180&&(u-=360),u-a<-180&&(u+=360),m-u>180&&(m-=360),m-u<-180&&(m+=360),this.orientation=u-a<0?x.CW:x.CCW,this.angle=l.FromDegrees(this.orientation===x.CW?a-m:m-a)}return t}();t.Arc2=z;var w=function(){function t(t,i){this._points=new Array,this._length=0,this.closed=!1,this._points.push(new o(t,i))}return t.prototype.addLineTo=function(t,i){if(closed)return this;var r=new o(t,i),n=this._points[this._points.length-1];return this._points.push(r),this._length+=r.subtract(n).length(),this},t.prototype.addArcTo=function(t,i,r,n,e){if(void 0===e&&(e=36),closed)return this;var s=this._points[this._points.length-1],h=new o(t,i),a=new o(r,n),u=new z(s,h,a),m=u.angle.radians()/e;u.orientation===x.CW&&(m*=-1);for(var y=u.startAngle.radians()+m,c=0;c<e;c++){var p=Math.cos(y)*u.radius+u.centerPoint.x,f=Math.sin(y)*u.radius+u.centerPoint.y;this.addLineTo(p,f),y+=m}return this},t.prototype.close=function(){return this.closed=!0,this},t.prototype.length=function(){var t=this._length;if(!this.closed){var i=this._points[this._points.length-1],r=this._points[0];t+=r.subtract(i).length()}return t},t.prototype.getPoints=function(){return this._points},t.prototype.getPointAtLengthPosition=function(t){if(t<0||t>1)return o.Zero();for(var i=t*this.length(),r=0,n=0;n<this._points.length;n++){var e=(n+1)%this._points.length,s=this._points[n],h=this._points[e],a=h.subtract(s),u=a.length()+r;if(i>=r&&i<=u){var m=a.normalize(),y=i-r;return new o(s.x+m.x*y,s.y+m.y*y)}r=u}return o.Zero()},t.StartingAt=function(i,r){return new t(i,r)},t}();t.Path2=w;var v=function(){function r(t,i,r){this.path=t,this._curve=new Array,this._distances=new Array,this._tangents=new Array,this._normals=new Array,this._binormals=new Array;for(var n=0;n<t.length;n++)this._curve[n]=t[n].clone();this._raw=r||!1,this._compute(i)}return r.prototype.getCurve=function(){return this._curve},r.prototype.getTangents=function(){return this._tangents},r.prototype.getNormals=function(){return this._normals},r.prototype.getBinormals=function(){return this._binormals},r.prototype.getDistances=function(){return this._distances},r.prototype.update=function(t,i){for(var r=0;r<t.length;r++)this._curve[r].x=t[r].x,this._curve[r].y=t[r].y,this._curve[r].z=t[r].z;return this._compute(i),this},r.prototype._compute=function(t){var i=this._curve.length;this._tangents[0]=this._getFirstNonNullVector(0),this._raw||this._tangents[0].normalize(),this._tangents[i-1]=this._curve[i-1].subtract(this._curve[i-2]),this._raw||this._tangents[i-1].normalize();var r=this._tangents[0],n=this._normalVector(this._curve[0],r,t);this._normals[0]=n,this._raw||this._normals[0].normalize(),this._binormals[0]=e.Cross(r,this._normals[0]),this._raw||this._binormals[0].normalize(),this._distances[0]=0;for(var o,s,h,a,u=1;u<i;u++)o=this._getLastNonNullVector(u),u<i-1&&(s=this._getFirstNonNullVector(u),this._tangents[u]=o.add(s),this._tangents[u].normalize()),this._distances[u]=this._distances[u-1]+o.length(),h=this._tangents[u],a=this._binormals[u-1],this._normals[u]=e.Cross(a,h),this._raw||this._normals[u].normalize(),this._binormals[u]=e.Cross(h,this._normals[u]),this._raw||this._binormals[u].normalize()},r.prototype._getFirstNonNullVector=function(t){for(var i=1,r=this._curve[t+i].subtract(this._curve[t]);0===r.length()&&t+i+1<this._curve.length;)i++,r=this._curve[t+i].subtract(this._curve[t]);return r},r.prototype._getLastNonNullVector=function(t){for(var i=1,r=this._curve[t].subtract(this._curve[t-i]);0===r.length()&&t>i+1;)i++,r=this._curve[t].subtract(this._curve[t-i]);return r},r.prototype._normalVector=function(r,n,o){var s,h=n.length();if(0===h&&(h=1),void 0===o||null===o){var a;i.WithinEpsilon(Math.abs(n.y)/h,1,t.Epsilon)?i.WithinEpsilon(Math.abs(n.x)/h,1,t.Epsilon)?i.WithinEpsilon(Math.abs(n.z)/h,1,t.Epsilon)||(a=new e(0,0,1)):a=new e(1,0,0):a=new e(0,(-1),0),s=e.Cross(n,a)}else s=e.Cross(n,o),e.CrossToRef(s,n,s);return s.normalize(),s},r}();t.Path3D=v;var d=function(){function t(t){this._length=0,this._points=t,this._length=this._computeLength(t)}return t.CreateQuadraticBezier=function(i,r,n,o){o=o>2?o:3;for(var s=new Array,h=function(t,i,r,n){var o=(1-t)*(1-t)*i+2*t*(1-t)*r+t*t*n;return o},a=0;a<=o;a++)s.push(new e(h(a/o,i.x,r.x,n.x),h(a/o,i.y,r.y,n.y),h(a/o,i.z,r.z,n.z)));return new t(s)},t.CreateCubicBezier=function(i,r,n,o,s){s=s>3?s:4;for(var h=new Array,a=function(t,i,r,n,o){var e=(1-t)*(1-t)*(1-t)*i+3*t*(1-t)*(1-t)*r+3*t*t*(1-t)*n+t*t*t*o;return e},u=0;u<=s;u++)h.push(new e(a(u/s,i.x,r.x,n.x,o.x),a(u/s,i.y,r.y,n.y,o.y),a(u/s,i.z,r.z,n.z,o.z)));return new t(h)},t.CreateHermiteSpline=function(i,r,n,o,s){for(var h=new Array,a=1/s,u=0;u<=s;u++)h.push(e.Hermite(i,r,n,o,u*a));return new t(h)},t.prototype.getPoints=function(){return this._points},t.prototype.length=function(){return this._length},t.prototype[\"continue\"]=function(i){for(var r=this._points[this._points.length-1],n=this._points.slice(),o=i.getPoints(),e=1;e<o.length;e++)n.push(o[e].subtract(o[0]).add(r));var s=new t(n);return s},t.prototype._computeLength=function(t){for(var i=0,r=1;r<t.length;r++)i+=t[r].subtract(t[r-1]).length();return i},t}();t.Curve3=d;var g=function(){function t(){this.L00=e.Zero(),this.L1_1=e.Zero(),this.L10=e.Zero(),this.L11=e.Zero(),this.L2_2=e.Zero(),this.L2_1=e.Zero(),this.L20=e.Zero(),this.L21=e.Zero(),this.L22=e.Zero()}return t.prototype.addLight=function(t,i,r){var n=new e(i.r,i.g,i.b),o=n.scale(r);this.L00=this.L00.add(o.scale(.282095)),this.L1_1=this.L1_1.add(o.scale(.488603*t.y)),this.L10=this.L10.add(o.scale(.488603*t.z)),this.L11=this.L11.add(o.scale(.488603*t.x)),this.L2_2=this.L2_2.add(o.scale(1.092548*t.x*t.y)),this.L2_1=this.L2_1.add(o.scale(1.092548*t.y*t.z)),this.L21=this.L21.add(o.scale(1.092548*t.x*t.z)),this.L20=this.L20.add(o.scale(.315392*(3*t.z*t.z-1))),this.L22=this.L22.add(o.scale(.546274*(t.x*t.x-t.y*t.y)))},t.prototype.scale=function(t){this.L00=this.L00.scale(t),this.L1_1=this.L1_1.scale(t),this.L10=this.L10.scale(t),this.L11=this.L11.scale(t),this.L2_2=this.L2_2.scale(t),this.L2_1=this.L2_1.scale(t),this.L20=this.L20.scale(t),this.L21=this.L21.scale(t),this.L22=this.L22.scale(t)},t}();t.SphericalHarmonics=g;var R=function(){function t(){this.x=e.Zero(),this.y=e.Zero(),this.z=e.Zero(),this.xx=e.Zero(),this.yy=e.Zero(),this.zz=e.Zero(),this.xy=e.Zero(),this.yz=e.Zero(),this.zx=e.Zero()}return t.prototype.addAmbient=function(t){var i=new e(t.r,t.g,t.b);this.xx=this.xx.add(i),this.yy=this.yy.add(i),this.zz=this.zz.add(i)},t.getSphericalPolynomialFromHarmonics=function(i){var r=new t;return r.x=i.L11.scale(1.02333),r.y=i.L1_1.scale(1.02333),r.z=i.L10.scale(1.02333),r.xx=i.L00.scale(.886277).subtract(i.L20.scale(.247708)).add(i.L22.scale(.429043)),r.yy=i.L00.scale(.886277).subtract(i.L20.scale(.247708)).subtract(i.L22.scale(.429043)),r.zz=i.L00.scale(.886277).add(i.L20.scale(.495417)),r.yz=i.L2_1.scale(.858086),r.zx=i.L21.scale(.858086),r.xy=i.L2_2.scale(.858086),r},t}();t.SphericalPolynomial=R;var T=function(){function t(t,i){void 0===t&&(t=e.Zero()),void 0===i&&(i=e.Up()),this.position=t,this.normal=i}return t.prototype.clone=function(){return new t(this.position.clone(),this.normal.clone())},t}();t.PositionNormalVertex=T;var _=function(){function t(t,i,r){void 0===t&&(t=e.Zero()),void 0===i&&(i=e.Up()),void 0===r&&(r=o.Zero()),this.position=t,this.normal=i,this.uv=r}return t.prototype.clone=function(){return new t(this.position.clone(),this.normal.clone(),this.uv.clone())},t}();t.PositionNormalTextureVertex=_;var M=function(){function t(){}return t.Color3=[r.Black(),r.Black(),r.Black()],t.Vector2=[o.Zero(),o.Zero(),o.Zero()],t.Vector3=[e.Zero(),e.Zero(),e.Zero(),e.Zero(),e.Zero(),e.Zero(),e.Zero(),e.Zero(),e.Zero()],t.Vector4=[s.Zero(),s.Zero(),s.Zero()],t.Quaternion=[new a(0,0,0,0)],t.Matrix=[u.Zero(),u.Zero(),u.Zero(),u.Zero(),u.Zero(),u.Zero(),u.Zero(),u.Zero()],t}();t.Tmp=M}(BABYLON||(BABYLON={}));";
  63509. if (((typeof window != "undefined" && window.module) || (typeof module != "undefined")) && typeof module.exports != "undefined") {
  63510. module.exports = BABYLON;
  63511. };